[C++/mingw] gdbserver: gdb/host signal mixup
[deliverable/binutils-gdb.git] / gdb / windows-nat.c
CommitLineData
dc05df57 1/* Target-vector operations for controlling windows child processes, for GDB.
0a65a603 2
32d0add0 3 Copyright (C) 1995-2015 Free Software Foundation, Inc.
0a65a603 4
e6433c28 5 Contributed by Cygnus Solutions, A Red Hat Company.
e88c49c3 6
24e60978
SC
7 This file is part of GDB.
8
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
a9762ec7 11 the Free Software Foundation; either version 3 of the License, or
24e60978
SC
12 (at your option) any later version.
13
14 This program is distributed in the hope that it will be useful,
a9762ec7 15 but WITHOUT ANY WARRANTY; without even the implied warranty of
24e60978
SC
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
a9762ec7 20 along with this program. If not, see <http://www.gnu.org/licenses/>. */
24e60978 21
dfe7f3ac 22/* Originally by Steve Chamberlain, sac@cygnus.com */
24e60978
SC
23
24#include "defs.h"
25#include "frame.h" /* required by inferior.h */
26#include "inferior.h"
45741a9c 27#include "infrun.h"
24e60978 28#include "target.h"
24e60978
SC
29#include "gdbcore.h"
30#include "command.h"
fa58ee11 31#include "completer.h"
4e052eda 32#include "regcache.h"
2a3d5645 33#include "top.h"
403d9909
CF
34#include <signal.h>
35#include <sys/types.h>
36#include <fcntl.h>
403d9909
CF
37#include <windows.h>
38#include <imagehlp.h>
2b008701 39#include <psapi.h>
10325bc5 40#ifdef __CYGWIN__
b7ff339d 41#include <wchar.h>
403d9909 42#include <sys/cygwin.h>
b7ff339d 43#include <cygwin/version.h>
10325bc5 44#endif
cad9cd60 45
24e60978 46#include "buildsym.h"
0ba1096a 47#include "filenames.h"
1ef980b9
SC
48#include "symfile.h"
49#include "objfiles.h"
92107356 50#include "gdb_bfd.h"
de1b3c3d 51#include "gdb_obstack.h"
fdfa3315 52#include "gdbthread.h"
24e60978 53#include "gdbcmd.h"
1e37c281 54#include <unistd.h>
4646aa9d 55#include "exec.h"
3ee6f623 56#include "solist.h"
3cb8e7f6 57#include "solib.h"
de1b3c3d 58#include "xml-support.h"
24e60978 59
6c7de422
MK
60#include "i386-tdep.h"
61#include "i387-tdep.h"
62
31b060a2
CF
63#include "windows-tdep.h"
64#include "windows-nat.h"
df7e5265 65#include "x86-nat.h"
ecc13e53 66#include "complaints.h"
51a9c8c5 67#include "inf-child.h"
de1b3c3d 68
418c6cb3 69#define AdjustTokenPrivileges dyn_AdjustTokenPrivileges
2b008701
CF
70#define DebugActiveProcessStop dyn_DebugActiveProcessStop
71#define DebugBreakProcess dyn_DebugBreakProcess
72#define DebugSetProcessKillOnExit dyn_DebugSetProcessKillOnExit
73#define EnumProcessModules dyn_EnumProcessModules
2b008701 74#define GetModuleInformation dyn_GetModuleInformation
418c6cb3
CF
75#define LookupPrivilegeValueA dyn_LookupPrivilegeValueA
76#define OpenProcessToken dyn_OpenProcessToken
cd44747c
PM
77#define GetConsoleFontSize dyn_GetConsoleFontSize
78#define GetCurrentConsoleFont dyn_GetCurrentConsoleFont
2b008701 79
43499ea3
PA
80typedef BOOL WINAPI (AdjustTokenPrivileges_ftype) (HANDLE, BOOL,
81 PTOKEN_PRIVILEGES,
82 DWORD, PTOKEN_PRIVILEGES,
83 PDWORD);
84static AdjustTokenPrivileges_ftype *AdjustTokenPrivileges;
85
86typedef BOOL WINAPI (DebugActiveProcessStop_ftype) (DWORD);
87static DebugActiveProcessStop_ftype *DebugActiveProcessStop;
88
89typedef BOOL WINAPI (DebugBreakProcess_ftype) (HANDLE);
90static DebugBreakProcess_ftype *DebugBreakProcess;
91
92typedef BOOL WINAPI (DebugSetProcessKillOnExit_ftype) (BOOL);
93static DebugSetProcessKillOnExit_ftype *DebugSetProcessKillOnExit;
94
95typedef BOOL WINAPI (EnumProcessModules_ftype) (HANDLE, HMODULE *, DWORD,
96 LPDWORD);
97static EnumProcessModules_ftype *EnumProcessModules;
98
99typedef BOOL WINAPI (GetModuleInformation_ftype) (HANDLE, HMODULE,
100 LPMODULEINFO, DWORD);
101static GetModuleInformation_ftype *GetModuleInformation;
102
103typedef BOOL WINAPI (LookupPrivilegeValueA_ftype) (LPCSTR, LPCSTR, PLUID);
104static LookupPrivilegeValueA_ftype *LookupPrivilegeValueA;
105
106typedef BOOL WINAPI (OpenProcessToken_ftype) (HANDLE, DWORD, PHANDLE);
107static OpenProcessToken_ftype *OpenProcessToken;
108
109typedef BOOL WINAPI (GetCurrentConsoleFont_ftype) (HANDLE, BOOL,
110 CONSOLE_FONT_INFO *);
111static GetCurrentConsoleFont_ftype *GetCurrentConsoleFont;
112
113typedef COORD WINAPI (GetConsoleFontSize_ftype) (HANDLE, DWORD);
114static GetConsoleFontSize_ftype *GetConsoleFontSize;
2b008701 115
b3c613f2
CF
116#undef STARTUPINFO
117#undef CreateProcess
118#undef GetModuleFileNameEx
119
120#ifndef __CYGWIN__
121# define __PMAX (MAX_PATH + 1)
43499ea3
PA
122 typedef DWORD WINAPI (GetModuleFileNameEx_ftype) (HANDLE, HMODULE, LPSTR, DWORD);
123 static GetModuleFileNameEx_ftype *GetModuleFileNameEx;
b3c613f2
CF
124# define STARTUPINFO STARTUPINFOA
125# define CreateProcess CreateProcessA
126# define GetModuleFileNameEx_name "GetModuleFileNameExA"
127# define bad_GetModuleFileNameEx bad_GetModuleFileNameExA
128#else
129# define __PMAX PATH_MAX
581e13c1 130/* The starting and ending address of the cygwin1.dll text segment. */
b3c613f2
CF
131 static CORE_ADDR cygwin_load_start;
132 static CORE_ADDR cygwin_load_end;
b3c613f2
CF
133# define __USEWIDE
134 typedef wchar_t cygwin_buf_t;
43499ea3
PA
135 typedef DWORD WINAPI (GetModuleFileNameEx_ftype) (HANDLE, HMODULE,
136 LPWSTR, DWORD);
137 static GetModuleFileNameEx_ftype *GetModuleFileNameEx;
b3c613f2
CF
138# define STARTUPINFO STARTUPINFOW
139# define CreateProcess CreateProcessW
140# define GetModuleFileNameEx_name "GetModuleFileNameExW"
141# define bad_GetModuleFileNameEx bad_GetModuleFileNameExW
10325bc5 142#endif
a244bdca 143
581e13c1
MS
144static int have_saved_context; /* True if we've saved context from a
145 cygwin signal. */
146static CONTEXT saved_context; /* Containes the saved context from a
147 cygwin signal. */
a244bdca 148
0714f9bf
SS
149/* If we're not using the old Cygwin header file set, define the
150 following which never should have been in the generic Win32 API
581e13c1 151 headers in the first place since they were our own invention... */
0714f9bf 152#ifndef _GNU_H_WINDOWS_H
9d3789f7 153enum
8e860359
CF
154 {
155 FLAG_TRACE_BIT = 0x100,
8e860359 156 };
0714f9bf
SS
157#endif
158
5851ab76
JB
159#ifndef CONTEXT_EXTENDED_REGISTERS
160/* This macro is only defined on ia32. It only makes sense on this target,
161 so define it as zero if not already defined. */
162#define CONTEXT_EXTENDED_REGISTERS 0
163#endif
164
f0666312
JT
165#define CONTEXT_DEBUGGER_DR CONTEXT_FULL | CONTEXT_FLOATING_POINT \
166 | CONTEXT_SEGMENTS | CONTEXT_DEBUG_REGISTERS \
167 | CONTEXT_EXTENDED_REGISTERS
97da3b20 168
41b4aadc 169static uintptr_t dr[8];
87a45c96
CF
170static int debug_registers_changed;
171static int debug_registers_used;
16d905e2
CF
172
173static int windows_initialization_done;
6537bb24 174#define DR6_CLEAR_VALUE 0xffff0ff0
97da3b20 175
3cee93ac 176/* The string sent by cygwin when it processes a signal.
581e13c1 177 FIXME: This should be in a cygwin include file. */
3929abe9
CF
178#ifndef _CYGWIN_SIGNAL_STRING
179#define _CYGWIN_SIGNAL_STRING "cYgSiGw00f"
180#endif
3cee93ac 181
29fe111d 182#define CHECK(x) check (x, __FILE__,__LINE__)
dfe7f3ac 183#define DEBUG_EXEC(x) if (debug_exec) printf_unfiltered x
4e52d31c
PM
184#define DEBUG_EVENTS(x) if (debug_events) printf_unfiltered x
185#define DEBUG_MEM(x) if (debug_memory) printf_unfiltered x
186#define DEBUG_EXCEPT(x) if (debug_exceptions) printf_unfiltered x
24e60978 187
bfedc46a 188static void windows_interrupt (struct target_ops *self, ptid_t);
02529b48 189static int windows_thread_alive (struct target_ops *, ptid_t);
7d85a9c0 190static void windows_kill_inferior (struct target_ops *);
3cee93ac 191
9bb9e8ad
PM
192static void cygwin_set_dr (int i, CORE_ADDR addr);
193static void cygwin_set_dr7 (unsigned long val);
a961bc18 194static CORE_ADDR cygwin_get_dr (int i);
9bb9e8ad 195static unsigned long cygwin_get_dr6 (void);
a961bc18 196static unsigned long cygwin_get_dr7 (void);
9bb9e8ad 197
a493e3e2 198static enum gdb_signal last_sig = GDB_SIGNAL_0;
581e13c1 199/* Set if a signal was received from the debugged process. */
7393af7c 200
3cee93ac 201/* Thread information structure used to track information that is
6537bb24 202 not available in gdb's thread structure. */
876d1cd7 203typedef struct windows_thread_info_struct
3a4b77d8 204 {
876d1cd7 205 struct windows_thread_info_struct *next;
3a4b77d8
JM
206 DWORD id;
207 HANDLE h;
711e434b 208 CORE_ADDR thread_local_base;
3a4b77d8 209 char *name;
6537bb24 210 int suspended;
3ade5333 211 int reload_context;
3a4b77d8 212 CONTEXT context;
1e37c281 213 STACKFRAME sf;
8e860359 214 }
876d1cd7 215windows_thread_info;
1e37c281 216
876d1cd7 217static windows_thread_info thread_head;
24e60978 218
581e13c1 219/* The process and thread handles for the above context. */
24e60978 220
3cee93ac
CF
221static DEBUG_EVENT current_event; /* The current debug event from
222 WaitForDebugEvent */
223static HANDLE current_process_handle; /* Currently executing process */
876d1cd7 224static windows_thread_info *current_thread; /* Info on currently selected thread */
349b409f 225static DWORD main_thread_id; /* Thread ID of the main thread */
24e60978 226
581e13c1 227/* Counts of things. */
24e60978
SC
228static int exception_count = 0;
229static int event_count = 0;
dfe7f3ac 230static int saw_create;
bf25528d 231static int open_process_used = 0;
24e60978 232
581e13c1 233/* User options. */
24e60978 234static int new_console = 0;
10325bc5 235#ifdef __CYGWIN__
09280ddf 236static int cygwin_exceptions = 0;
10325bc5 237#endif
1e37c281 238static int new_group = 1;
dfe7f3ac
CF
239static int debug_exec = 0; /* show execution */
240static int debug_events = 0; /* show events from kernel */
241static int debug_memory = 0; /* show target memory accesses */
1ef980b9 242static int debug_exceptions = 0; /* show target exceptions */
dfe7f3ac
CF
243static int useshell = 0; /* use shell for subprocesses */
244
7e63b4e4 245/* This vector maps GDB's idea of a register's number into an offset
dc05df57 246 in the windows exception context vector.
24e60978 247
3cee93ac 248 It also contains the bit mask needed to load the register in question.
24e60978 249
7e63b4e4
JB
250 The contents of this table can only be computed by the units
251 that provide CPU-specific support for Windows native debugging.
252 These units should set the table by calling
dc05df57 253 windows_set_context_register_offsets.
7e63b4e4 254
24e60978
SC
255 One day we could read a reg, we could inspect the context we
256 already have loaded, if it doesn't have the bit set that we need,
257 we read that set of registers in using GetThreadContext. If the
581e13c1 258 context already contains what we need, we just unpack it. Then to
24e60978
SC
259 write a register, first we have to ensure that the context contains
260 the other regs of the group, and then we copy the info in and set
581e13c1 261 out bit. */
24e60978 262
7e63b4e4 263static const int *mappings;
d3a09475 264
d40dc7a8
JB
265/* The function to use in order to determine whether a register is
266 a segment register or not. */
267static segment_register_p_ftype *segment_register_p;
268
24e60978 269/* This vector maps the target's idea of an exception (extracted
581e13c1 270 from the DEBUG_EVENT structure) to GDB's idea. */
24e60978
SC
271
272struct xlate_exception
273 {
274 int them;
2ea28649 275 enum gdb_signal us;
24e60978
SC
276 };
277
24e60978
SC
278static const struct xlate_exception
279 xlate[] =
280{
a493e3e2
PA
281 {EXCEPTION_ACCESS_VIOLATION, GDB_SIGNAL_SEGV},
282 {STATUS_STACK_OVERFLOW, GDB_SIGNAL_SEGV},
283 {EXCEPTION_BREAKPOINT, GDB_SIGNAL_TRAP},
284 {DBG_CONTROL_C, GDB_SIGNAL_INT},
285 {EXCEPTION_SINGLE_STEP, GDB_SIGNAL_TRAP},
286 {STATUS_FLOAT_DIVIDE_BY_ZERO, GDB_SIGNAL_FPE},
56db1d67 287 {-1, GDB_SIGNAL_UNKNOWN}};
24e60978 288
7e63b4e4
JB
289/* Set the MAPPINGS static global to OFFSETS.
290 See the description of MAPPINGS for more details. */
291
292void
dc05df57 293windows_set_context_register_offsets (const int *offsets)
7e63b4e4
JB
294{
295 mappings = offsets;
296}
297
d40dc7a8
JB
298/* See windows-nat.h. */
299
300void
301windows_set_segment_register_p (segment_register_p_ftype *fun)
302{
303 segment_register_p = fun;
304}
305
fa4ba8da
PM
306static void
307check (BOOL ok, const char *file, int line)
308{
309 if (!ok)
d50a0ce2
CV
310 printf_filtered ("error return %s:%d was %u\n", file, line,
311 (unsigned) GetLastError ());
fa4ba8da
PM
312}
313
6537bb24
PA
314/* Find a thread record given a thread id. If GET_CONTEXT is not 0,
315 then also retrieve the context for this thread. If GET_CONTEXT is
316 negative, then don't suspend the thread. */
876d1cd7 317static windows_thread_info *
3cee93ac 318thread_rec (DWORD id, int get_context)
24e60978 319{
876d1cd7 320 windows_thread_info *th;
3cee93ac 321
3a4b77d8 322 for (th = &thread_head; (th = th->next) != NULL;)
3cee93ac
CF
323 if (th->id == id)
324 {
6537bb24 325 if (!th->suspended && get_context)
3cee93ac 326 {
8a892701 327 if (get_context > 0 && id != current_event.dwThreadId)
6537bb24
PA
328 {
329 if (SuspendThread (th->h) == (DWORD) -1)
330 {
331 DWORD err = GetLastError ();
22128028 332
17617f2d
EZ
333 /* We get Access Denied (5) when trying to suspend
334 threads that Windows started on behalf of the
335 debuggee, usually when those threads are just
5d9c55d3
JT
336 about to exit.
337 We can get Invalid Handle (6) if the main thread
338 has exited. */
339 if (err != ERROR_INVALID_HANDLE
340 && err != ERROR_ACCESS_DENIED)
17617f2d
EZ
341 warning (_("SuspendThread (tid=0x%x) failed."
342 " (winerr %u)"),
343 (unsigned) id, (unsigned) err);
344 th->suspended = -1;
6537bb24 345 }
17617f2d
EZ
346 else
347 th->suspended = 1;
6537bb24 348 }
3cee93ac 349 else if (get_context < 0)
6537bb24 350 th->suspended = -1;
3ade5333 351 th->reload_context = 1;
3cee93ac
CF
352 }
353 return th;
354 }
355
356 return NULL;
357}
358
2dc38344 359/* Add a thread to the thread list. */
876d1cd7 360static windows_thread_info *
711e434b 361windows_add_thread (ptid_t ptid, HANDLE h, void *tlb)
3cee93ac 362{
876d1cd7 363 windows_thread_info *th;
2dc38344
PA
364 DWORD id;
365
366 gdb_assert (ptid_get_tid (ptid) != 0);
367
368 id = ptid_get_tid (ptid);
3cee93ac
CF
369
370 if ((th = thread_rec (id, FALSE)))
371 return th;
372
876d1cd7 373 th = XCNEW (windows_thread_info);
3cee93ac
CF
374 th->id = id;
375 th->h = h;
711e434b 376 th->thread_local_base = (CORE_ADDR) (uintptr_t) tlb;
3cee93ac
CF
377 th->next = thread_head.next;
378 thread_head.next = th;
2dc38344
PA
379 add_thread (ptid);
380 /* Set the debug registers for the new thread if they are used. */
fa4ba8da
PM
381 if (debug_registers_used)
382 {
383 /* Only change the value of the debug registers. */
384 th->context.ContextFlags = CONTEXT_DEBUG_REGISTERS;
385 CHECK (GetThreadContext (th->h, &th->context));
386 th->context.Dr0 = dr[0];
387 th->context.Dr1 = dr[1];
388 th->context.Dr2 = dr[2];
389 th->context.Dr3 = dr[3];
6537bb24 390 th->context.Dr6 = DR6_CLEAR_VALUE;
fa4ba8da
PM
391 th->context.Dr7 = dr[7];
392 CHECK (SetThreadContext (th->h, &th->context));
393 th->context.ContextFlags = 0;
394 }
3cee93ac 395 return th;
24e60978
SC
396}
397
3cee93ac 398/* Clear out any old thread list and reintialize it to a
581e13c1 399 pristine state. */
24e60978 400static void
dc05df57 401windows_init_thread_list (void)
24e60978 402{
876d1cd7 403 windows_thread_info *th = &thread_head;
3cee93ac 404
dc05df57 405 DEBUG_EVENTS (("gdb: windows_init_thread_list\n"));
3cee93ac
CF
406 init_thread_list ();
407 while (th->next != NULL)
24e60978 408 {
876d1cd7 409 windows_thread_info *here = th->next;
3cee93ac 410 th->next = here->next;
b8c9b27d 411 xfree (here);
24e60978 412 }
059198c1 413 thread_head.next = NULL;
3cee93ac
CF
414}
415
581e13c1 416/* Delete a thread from the list of threads. */
3cee93ac 417static void
e0ea48a0 418windows_delete_thread (ptid_t ptid, DWORD exit_code)
3cee93ac 419{
876d1cd7 420 windows_thread_info *th;
2dc38344
PA
421 DWORD id;
422
423 gdb_assert (ptid_get_tid (ptid) != 0);
424
425 id = ptid_get_tid (ptid);
3cee93ac
CF
426
427 if (info_verbose)
2dc38344 428 printf_unfiltered ("[Deleting %s]\n", target_pid_to_str (ptid));
e0ea48a0
EZ
429 else if (print_thread_events && id != main_thread_id)
430 printf_unfiltered (_("[%s exited with code %u]\n"),
564eac42 431 target_pid_to_str (ptid), (unsigned) exit_code);
2dc38344 432 delete_thread (ptid);
3cee93ac
CF
433
434 for (th = &thread_head;
435 th->next != NULL && th->next->id != id;
436 th = th->next)
437 continue;
438
439 if (th->next != NULL)
24e60978 440 {
876d1cd7 441 windows_thread_info *here = th->next;
3cee93ac 442 th->next = here->next;
b8c9b27d 443 xfree (here);
24e60978
SC
444 }
445}
446
3cee93ac 447static void
dc05df57 448do_windows_fetch_inferior_registers (struct regcache *regcache, int r)
24e60978 449{
1e37c281 450 char *context_offset = ((char *) &current_thread->context) + mappings[r];
20a6ec49
MD
451 struct gdbarch *gdbarch = get_regcache_arch (regcache);
452 struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
1e37c281 453 long l;
6c7de422 454
3ade5333 455 if (!current_thread)
d6dc8049 456 return; /* Windows sometimes uses a non-existent thread id in its
581e13c1 457 events. */
3ade5333
CF
458
459 if (current_thread->reload_context)
460 {
f20c58f5 461#ifdef __CYGWIN__
a244bdca
CF
462 if (have_saved_context)
463 {
581e13c1
MS
464 /* Lie about where the program actually is stopped since
465 cygwin has informed us that we should consider the signal
466 to have occurred at another location which is stored in
467 "saved_context. */
468 memcpy (&current_thread->context, &saved_context,
469 __COPY_CONTEXT_SIZE);
a244bdca
CF
470 have_saved_context = 0;
471 }
472 else
cb832706 473#endif
a244bdca 474 {
876d1cd7 475 windows_thread_info *th = current_thread;
a244bdca 476 th->context.ContextFlags = CONTEXT_DEBUGGER_DR;
17617f2d 477 CHECK (GetThreadContext (th->h, &th->context));
2b008701 478 /* Copy dr values from that thread.
581e13c1
MS
479 But only if there were not modified since last stop.
480 PR gdb/2388 */
88616312
PM
481 if (!debug_registers_changed)
482 {
483 dr[0] = th->context.Dr0;
484 dr[1] = th->context.Dr1;
485 dr[2] = th->context.Dr2;
486 dr[3] = th->context.Dr3;
487 dr[6] = th->context.Dr6;
488 dr[7] = th->context.Dr7;
489 }
a244bdca 490 }
3ade5333
CF
491 current_thread->reload_context = 0;
492 }
493
20a6ec49 494 if (r == I387_FISEG_REGNUM (tdep))
1e37c281 495 {
8e860359 496 l = *((long *) context_offset) & 0xffff;
56be3814 497 regcache_raw_supply (regcache, r, (char *) &l);
1e37c281 498 }
20a6ec49 499 else if (r == I387_FOP_REGNUM (tdep))
1e37c281 500 {
8e860359 501 l = (*((long *) context_offset) >> 16) & ((1 << 11) - 1);
56be3814 502 regcache_raw_supply (regcache, r, (char *) &l);
1e37c281 503 }
d40dc7a8
JB
504 else if (segment_register_p (r))
505 {
506 /* GDB treats segment registers as 32bit registers, but they are
507 in fact only 16 bits long. Make sure we do not read extra
508 bits from our source buffer. */
509 l = *((long *) context_offset) & 0xffff;
510 regcache_raw_supply (regcache, r, (char *) &l);
511 }
1e37c281 512 else if (r >= 0)
56be3814 513 regcache_raw_supply (regcache, r, context_offset);
3cee93ac 514 else
24e60978 515 {
20a6ec49 516 for (r = 0; r < gdbarch_num_regs (gdbarch); r++)
dc05df57 517 do_windows_fetch_inferior_registers (regcache, r);
24e60978 518 }
3cee93ac
CF
519}
520
521static void
28439f5e
PA
522windows_fetch_inferior_registers (struct target_ops *ops,
523 struct regcache *regcache, int r)
3cee93ac 524{
2dc38344 525 current_thread = thread_rec (ptid_get_tid (inferior_ptid), TRUE);
d6dc8049 526 /* Check if current_thread exists. Windows sometimes uses a non-existent
581e13c1 527 thread id in its events. */
3ade5333 528 if (current_thread)
dc05df57 529 do_windows_fetch_inferior_registers (regcache, r);
3cee93ac
CF
530}
531
532static void
dc05df57 533do_windows_store_inferior_registers (const struct regcache *regcache, int r)
3cee93ac 534{
3ade5333 535 if (!current_thread)
581e13c1 536 /* Windows sometimes uses a non-existent thread id in its events. */;
3ade5333 537 else if (r >= 0)
56be3814 538 regcache_raw_collect (regcache, r,
822c9732 539 ((char *) &current_thread->context) + mappings[r]);
24e60978
SC
540 else
541 {
40a6adc1 542 for (r = 0; r < gdbarch_num_regs (get_regcache_arch (regcache)); r++)
dc05df57 543 do_windows_store_inferior_registers (regcache, r);
24e60978
SC
544 }
545}
546
581e13c1 547/* Store a new register value into the current thread context. */
3cee93ac 548static void
28439f5e
PA
549windows_store_inferior_registers (struct target_ops *ops,
550 struct regcache *regcache, int r)
3cee93ac 551{
2dc38344 552 current_thread = thread_rec (ptid_get_tid (inferior_ptid), TRUE);
d6dc8049 553 /* Check if current_thread exists. Windows sometimes uses a non-existent
581e13c1 554 thread id in its events. */
3ade5333 555 if (current_thread)
dc05df57 556 do_windows_store_inferior_registers (regcache, r);
3cee93ac 557}
24e60978 558
450005e7 559/* Encapsulate the information required in a call to
581e13c1 560 symbol_file_add_args. */
8a892701
CF
561struct safe_symbol_file_add_args
562{
563 char *name;
564 int from_tty;
565 struct section_addr_info *addrs;
566 int mainline;
567 int flags;
7c5c87c0 568 struct ui_file *err, *out;
8a892701
CF
569 struct objfile *ret;
570};
571
581e13c1 572/* Maintain a linked list of "so" information. */
3ee6f623 573struct lm_info
02e423b9 574{
d3653bf6 575 LPVOID load_addr;
3ee6f623
CF
576};
577
578static struct so_list solib_start, *solib_end;
02e423b9 579
de1b3c3d 580static struct so_list *
dc05df57 581windows_make_so (const char *name, LPVOID load_addr)
8e860359 582{
3ee6f623 583 struct so_list *so;
d0d0ab16
CV
584 char *p;
585#ifndef __CYGWIN__
b3c613f2
CF
586 char buf[__PMAX];
587 char cwd[__PMAX];
3f8ad85b
CF
588 WIN32_FIND_DATA w32_fd;
589 HANDLE h = FindFirstFile(name, &w32_fd);
3f8ad85b 590
6badb179
CF
591 if (h == INVALID_HANDLE_VALUE)
592 strcpy (buf, name);
593 else
3f8ad85b 594 {
c914e0cc
CF
595 FindClose (h);
596 strcpy (buf, name);
597 if (GetCurrentDirectory (MAX_PATH + 1, cwd))
598 {
599 p = strrchr (buf, '\\');
600 if (p)
601 p[1] = '\0';
602 SetCurrentDirectory (buf);
603 GetFullPathName (w32_fd.cFileName, MAX_PATH, buf, &p);
604 SetCurrentDirectory (cwd);
605 }
3f8ad85b 606 }
3ee6f623
CF
607 if (strcasecmp (buf, "ntdll.dll") == 0)
608 {
609 GetSystemDirectory (buf, sizeof (buf));
610 strcat (buf, "\\ntdll.dll");
611 }
d0d0ab16 612#else
b3c613f2 613 cygwin_buf_t buf[__PMAX];
d0d0ab16 614
b3c613f2 615 buf[0] = 0;
d0d0ab16
CV
616 if (access (name, F_OK) != 0)
617 {
618 if (strcasecmp (name, "ntdll.dll") == 0)
b3c613f2 619#ifdef __USEWIDE
d0d0ab16
CV
620 {
621 GetSystemDirectoryW (buf, sizeof (buf) / sizeof (wchar_t));
622 wcscat (buf, L"\\ntdll.dll");
623 }
b3c613f2
CF
624#else
625 {
626 GetSystemDirectoryA (buf, sizeof (buf) / sizeof (wchar_t));
627 strcat (buf, "\\ntdll.dll");
628 }
629#endif
d0d0ab16
CV
630 }
631#endif
41bf6aca 632 so = XCNEW (struct so_list);
8d749320 633 so->lm_info = XNEW (struct lm_info);
3ee6f623 634 so->lm_info->load_addr = load_addr;
de1b3c3d 635 strcpy (so->so_original_name, name);
10325bc5
PA
636#ifndef __CYGWIN__
637 strcpy (so->so_name, buf);
638#else
d0d0ab16
CV
639 if (buf[0])
640 cygwin_conv_path (CCP_WIN_W_TO_POSIX, buf, so->so_name,
641 SO_NAME_MAX_PATH_SIZE);
642 else
643 {
60c5c021 644 char *rname = realpath (name, NULL);
d0d0ab16
CV
645 if (rname && strlen (rname) < SO_NAME_MAX_PATH_SIZE)
646 {
647 strcpy (so->so_name, rname);
648 free (rname);
649 }
650 else
651 error (_("dll path too long"));
652 }
de1b3c3d
PA
653 /* Record cygwin1.dll .text start/end. */
654 p = strchr (so->so_name, '\0') - (sizeof ("/cygwin1.dll") - 1);
655 if (p >= so->so_name && strcasecmp (p, "/cygwin1.dll") == 0)
656 {
657 bfd *abfd;
658 asection *text = NULL;
659 CORE_ADDR text_vma;
8e860359 660
1c00ec6b 661 abfd = gdb_bfd_open (so->so_name, "pei-i386", -1);
a244bdca 662
de1b3c3d
PA
663 if (!abfd)
664 return so;
665
666 if (bfd_check_format (abfd, bfd_object))
667 text = bfd_get_section_by_name (abfd, ".text");
668
669 if (!text)
670 {
cbb099e8 671 gdb_bfd_unref (abfd);
de1b3c3d
PA
672 return so;
673 }
674
7a9dd1b2 675 /* The symbols in a dll are offset by 0x1000, which is the
de1b3c3d 676 offset from 0 of the first byte in an image - because of the
581e13c1
MS
677 file header and the section alignment. */
678 cygwin_load_start = (CORE_ADDR) (uintptr_t) ((char *)
679 load_addr + 0x1000);
dc05df57 680 cygwin_load_end = cygwin_load_start + bfd_section_size (abfd, text);
de1b3c3d 681
cbb099e8 682 gdb_bfd_unref (abfd);
de1b3c3d 683 }
10325bc5 684#endif
de1b3c3d
PA
685
686 return so;
8e860359
CF
687}
688
3ee6f623 689static char *
dfe7f3ac
CF
690get_image_name (HANDLE h, void *address, int unicode)
691{
d0d0ab16 692#ifdef __CYGWIN__
b3c613f2 693 static char buf[__PMAX];
d0d0ab16 694#else
b3c613f2 695 static char buf[(2 * __PMAX) + 1];
d0d0ab16 696#endif
dfe7f3ac
CF
697 DWORD size = unicode ? sizeof (WCHAR) : sizeof (char);
698 char *address_ptr;
699 int len = 0;
700 char b[2];
5732a500 701 SIZE_T done;
dfe7f3ac
CF
702
703 /* Attempt to read the name of the dll that was detected.
704 This is documented to work only when actively debugging
581e13c1 705 a program. It will not work for attached processes. */
dfe7f3ac
CF
706 if (address == NULL)
707 return NULL;
708
dfe7f3ac 709 /* See if we could read the address of a string, and that the
581e13c1
MS
710 address isn't null. */
711 if (!ReadProcessMemory (h, address, &address_ptr,
712 sizeof (address_ptr), &done)
6f17862b 713 || done != sizeof (address_ptr) || !address_ptr)
dfe7f3ac
CF
714 return NULL;
715
581e13c1 716 /* Find the length of the string. */
6f17862b
CF
717 while (ReadProcessMemory (h, address_ptr + len++ * size, &b, size, &done)
718 && (b[0] != 0 || b[size - 1] != 0) && done == size)
719 continue;
dfe7f3ac
CF
720
721 if (!unicode)
722 ReadProcessMemory (h, address_ptr, buf, len, &done);
723 else
724 {
725 WCHAR *unicode_address = (WCHAR *) alloca (len * sizeof (WCHAR));
726 ReadProcessMemory (h, address_ptr, unicode_address, len * sizeof (WCHAR),
727 &done);
d0d0ab16 728#ifdef __CYGWIN__
b3c613f2 729 wcstombs (buf, unicode_address, __PMAX);
d0d0ab16
CV
730#else
731 WideCharToMultiByte (CP_ACP, 0, unicode_address, len, buf, sizeof buf,
732 0, 0);
733#endif
dfe7f3ac
CF
734 }
735
736 return buf;
737}
738
1cd9feab
JB
739/* Handle a DLL load event, and return 1.
740
741 This function assumes that this event did not occur during inferior
742 initialization, where their event info may be incomplete (see
743 do_initial_windows_stuff and windows_add_all_dlls for more info
744 on how we handle DLL loading during that phase). */
745
1750a5ef 746static int
0a65a603 747handle_load_dll (void *dummy)
24e60978 748{
3a4b77d8 749 LOAD_DLL_DEBUG_INFO *event = &current_event.u.LoadDll;
1cd9feab 750 char *dll_name;
24e60978 751
94481b8c
JB
752 /* Try getting the DLL name via the lpImageName field of the event.
753 Note that Microsoft documents this fields as strictly optional,
754 in the sense that it might be NULL. And the first DLL event in
755 particular is explicitly documented as "likely not pass[ed]"
756 (source: MSDN LOAD_DLL_DEBUG_INFO structure). */
1cd9feab
JB
757 dll_name = get_image_name (current_process_handle,
758 event->lpImageName, event->fUnicode);
3cee93ac
CF
759 if (!dll_name)
760 return 1;
761
dc05df57 762 solib_end->next = windows_make_so (dll_name, event->lpBaseOfDll);
de1b3c3d 763 solib_end = solib_end->next;
450005e7 764
a74ce742
PM
765 DEBUG_EVENTS (("gdb: Loading dll \"%s\" at %s.\n", solib_end->so_name,
766 host_address_to_string (solib_end->lm_info->load_addr)));
7488902c 767
450005e7
CF
768 return 1;
769}
770
3ee6f623 771static void
dc05df57 772windows_free_so (struct so_list *so)
3ee6f623 773{
3ee6f623
CF
774 if (so->lm_info)
775 xfree (so->lm_info);
de1b3c3d 776 xfree (so);
3cb8e7f6
CF
777}
778
3be75f87
JB
779/* Handle a DLL unload event.
780 Return 1 if successful, or zero otherwise.
781
782 This function assumes that this event did not occur during inferior
783 initialization, where their event info may be incomplete (see
784 do_initial_windows_stuff and windows_add_all_dlls for more info
785 on how we handle DLL loading during that phase). */
786
d3ff4a77 787static int
0a65a603 788handle_unload_dll (void *dummy)
d3ff4a77 789{
d3653bf6 790 LPVOID lpBaseOfDll = current_event.u.UnloadDll.lpBaseOfDll;
3ee6f623 791 struct so_list *so;
d3ff4a77
CF
792
793 for (so = &solib_start; so->next != NULL; so = so->next)
3ee6f623 794 if (so->next->lm_info->load_addr == lpBaseOfDll)
d3ff4a77 795 {
3ee6f623 796 struct so_list *sodel = so->next;
a25cd31f 797
d3ff4a77
CF
798 so->next = sodel->next;
799 if (!so->next)
800 solib_end = so;
7488902c
PM
801 DEBUG_EVENTS (("gdb: Unloading dll \"%s\".\n", sodel->so_name));
802
dc05df57 803 windows_free_so (sodel);
d3ff4a77
CF
804 return 1;
805 }
3929abe9 806
ecc13e53
JB
807 /* We did not find any DLL that was previously loaded at this address,
808 so register a complaint. We do not report an error, because we have
809 observed that this may be happening under some circumstances. For
810 instance, running 32bit applications on x64 Windows causes us to receive
811 4 mysterious UNLOAD_DLL_DEBUG_EVENTs during the startup phase (these
812 events are apparently caused by the WOW layer, the interface between
813 32bit and 64bit worlds). */
814 complaint (&symfile_complaints, _("dll starting at %s not found."),
815 host_address_to_string (lpBaseOfDll));
d3ff4a77
CF
816
817 return 0;
818}
819
581e13c1 820/* Clear list of loaded DLLs. */
3ee6f623 821static void
dc05df57 822windows_clear_solib (void)
450005e7 823{
450005e7
CF
824 solib_start.next = NULL;
825 solib_end = &solib_start;
450005e7 826}
295732ea 827
3cee93ac
CF
828/* Handle DEBUG_STRING output from child process.
829 Cygwin prepends its messages with a "cygwin:". Interpret this as
581e13c1 830 a Cygwin signal. Otherwise just print the string as a warning. */
3cee93ac
CF
831static int
832handle_output_debug_string (struct target_waitstatus *ourstatus)
833{
a244bdca
CF
834 char *s = NULL;
835 int retval = 0;
3cee93ac
CF
836
837 if (!target_read_string
2c647436
PM
838 ((CORE_ADDR) (uintptr_t) current_event.u.DebugString.lpDebugStringData,
839 &s, 1024, 0)
3cee93ac 840 || !s || !*s)
a244bdca 841 /* nothing to do */;
61012eef 842 else if (!startswith (s, _CYGWIN_SIGNAL_STRING))
3cee93ac 843 {
10325bc5 844#ifdef __CYGWIN__
61012eef 845 if (!startswith (s, "cYg"))
10325bc5 846#endif
040ea00b
JT
847 {
848 char *p = strchr (s, '\0');
849
850 if (p > s && *--p == '\n')
851 *p = '\0';
852 warning (("%s"), s);
853 }
3cee93ac 854 }
f20c58f5 855#ifdef __CYGWIN__
d3a09475 856 else
3cee93ac 857 {
581e13c1
MS
858 /* Got a cygwin signal marker. A cygwin signal is followed by
859 the signal number itself and then optionally followed by the
860 thread id and address to saved context within the DLL. If
861 these are supplied, then the given thread is assumed to have
862 issued the signal and the context from the thread is assumed
863 to be stored at the given address in the inferior. Tell gdb
864 to treat this like a real signal. */
3cee93ac 865 char *p;
3929abe9 866 int sig = strtol (s + sizeof (_CYGWIN_SIGNAL_STRING) - 1, &p, 0);
2ea28649 867 int gotasig = gdb_signal_from_host (sig);
c62fa0e2 868
0714f9bf
SS
869 ourstatus->value.sig = gotasig;
870 if (gotasig)
a244bdca
CF
871 {
872 LPCVOID x;
2c15ef43 873 SIZE_T n;
c62fa0e2 874
a244bdca
CF
875 ourstatus->kind = TARGET_WAITKIND_STOPPED;
876 retval = strtoul (p, &p, 0);
877 if (!retval)
878 retval = main_thread_id;
40653b35 879 else if ((x = (LPCVOID) (uintptr_t) strtoull (p, NULL, 0))
a244bdca 880 && ReadProcessMemory (current_process_handle, x,
581e13c1
MS
881 &saved_context,
882 __COPY_CONTEXT_SIZE, &n)
a244bdca
CF
883 && n == __COPY_CONTEXT_SIZE)
884 have_saved_context = 1;
a244bdca 885 }
3cee93ac 886 }
cb832706 887#endif
3cee93ac 888
a244bdca
CF
889 if (s)
890 xfree (s);
891 return retval;
3cee93ac 892}
24e60978 893
c1748f97
PM
894static int
895display_selector (HANDLE thread, DWORD sel)
896{
897 LDT_ENTRY info;
898 if (GetThreadSelectorEntry (thread, sel, &info))
899 {
900 int base, limit;
d50a0ce2 901 printf_filtered ("0x%03x: ", (unsigned) sel);
c1748f97 902 if (!info.HighWord.Bits.Pres)
baa93fa6
CF
903 {
904 puts_filtered ("Segment not present\n");
905 return 0;
906 }
c1748f97
PM
907 base = (info.HighWord.Bits.BaseHi << 24) +
908 (info.HighWord.Bits.BaseMid << 16)
909 + info.BaseLow;
910 limit = (info.HighWord.Bits.LimitHi << 16) + info.LimitLow;
911 if (info.HighWord.Bits.Granularity)
caad7706 912 limit = (limit << 12) | 0xfff;
c1748f97
PM
913 printf_filtered ("base=0x%08x limit=0x%08x", base, limit);
914 if (info.HighWord.Bits.Default_Big)
baa93fa6 915 puts_filtered(" 32-bit ");
c1748f97 916 else
baa93fa6 917 puts_filtered(" 16-bit ");
c1748f97
PM
918 switch ((info.HighWord.Bits.Type & 0xf) >> 1)
919 {
920 case 0:
baa93fa6
CF
921 puts_filtered ("Data (Read-Only, Exp-up");
922 break;
c1748f97 923 case 1:
baa93fa6
CF
924 puts_filtered ("Data (Read/Write, Exp-up");
925 break;
c1748f97 926 case 2:
baa93fa6
CF
927 puts_filtered ("Unused segment (");
928 break;
c1748f97 929 case 3:
baa93fa6
CF
930 puts_filtered ("Data (Read/Write, Exp-down");
931 break;
c1748f97 932 case 4:
baa93fa6
CF
933 puts_filtered ("Code (Exec-Only, N.Conf");
934 break;
c1748f97 935 case 5:
baa93fa6 936 puts_filtered ("Code (Exec/Read, N.Conf");
c1748f97
PM
937 break;
938 case 6:
baa93fa6 939 puts_filtered ("Code (Exec-Only, Conf");
c1748f97
PM
940 break;
941 case 7:
baa93fa6 942 puts_filtered ("Code (Exec/Read, Conf");
c1748f97
PM
943 break;
944 default:
945 printf_filtered ("Unknown type 0x%x",info.HighWord.Bits.Type);
946 }
947 if ((info.HighWord.Bits.Type & 0x1) == 0)
baa93fa6 948 puts_filtered(", N.Acc");
c1748f97
PM
949 puts_filtered (")\n");
950 if ((info.HighWord.Bits.Type & 0x10) == 0)
951 puts_filtered("System selector ");
952 printf_filtered ("Priviledge level = %d. ", info.HighWord.Bits.Dpl);
953 if (info.HighWord.Bits.Granularity)
baa93fa6 954 puts_filtered ("Page granular.\n");
c1748f97
PM
955 else
956 puts_filtered ("Byte granular.\n");
957 return 1;
958 }
959 else
960 {
5572ce1f
PM
961 DWORD err = GetLastError ();
962 if (err == ERROR_NOT_SUPPORTED)
963 printf_filtered ("Function not supported\n");
964 else
d50a0ce2 965 printf_filtered ("Invalid selector 0x%x.\n", (unsigned) sel);
c1748f97
PM
966 return 0;
967 }
968}
969
970static void
971display_selectors (char * args, int from_tty)
972{
973 if (!current_thread)
974 {
975 puts_filtered ("Impossible to display selectors now.\n");
976 return;
977 }
978 if (!args)
979 {
980
981 puts_filtered ("Selector $cs\n");
982 display_selector (current_thread->h,
baa93fa6 983 current_thread->context.SegCs);
c1748f97
PM
984 puts_filtered ("Selector $ds\n");
985 display_selector (current_thread->h,
baa93fa6 986 current_thread->context.SegDs);
c1748f97
PM
987 puts_filtered ("Selector $es\n");
988 display_selector (current_thread->h,
baa93fa6 989 current_thread->context.SegEs);
c1748f97
PM
990 puts_filtered ("Selector $ss\n");
991 display_selector (current_thread->h,
baa93fa6 992 current_thread->context.SegSs);
c1748f97
PM
993 puts_filtered ("Selector $fs\n");
994 display_selector (current_thread->h,
995 current_thread->context.SegFs);
996 puts_filtered ("Selector $gs\n");
997 display_selector (current_thread->h,
baa93fa6 998 current_thread->context.SegGs);
c1748f97
PM
999 }
1000 else
1001 {
1002 int sel;
1003 sel = parse_and_eval_long (args);
1004 printf_filtered ("Selector \"%s\"\n",args);
1005 display_selector (current_thread->h, sel);
1006 }
1007}
1008
7393af7c 1009#define DEBUG_EXCEPTION_SIMPLE(x) if (debug_exceptions) \
a74ce742
PM
1010 printf_unfiltered ("gdb: Target exception %s at %s\n", x, \
1011 host_address_to_string (\
1012 current_event.u.Exception.ExceptionRecord.ExceptionAddress))
7393af7c 1013
36339ecd 1014static int
450005e7 1015handle_exception (struct target_waitstatus *ourstatus)
24e60978 1016{
876d1cd7 1017 windows_thread_info *th;
29fe111d 1018 DWORD code = current_event.u.Exception.ExceptionRecord.ExceptionCode;
3cee93ac 1019
29fe111d 1020 ourstatus->kind = TARGET_WAITKIND_STOPPED;
8a892701 1021
581e13c1 1022 /* Record the context of the current thread. */
3cee93ac 1023 th = thread_rec (current_event.dwThreadId, -1);
24e60978 1024
29fe111d 1025 switch (code)
24e60978 1026 {
1ef980b9 1027 case EXCEPTION_ACCESS_VIOLATION:
7393af7c 1028 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ACCESS_VIOLATION");
a493e3e2 1029 ourstatus->value.sig = GDB_SIGNAL_SEGV;
10325bc5 1030#ifdef __CYGWIN__
8da8e0b3 1031 {
581e13c1
MS
1032 /* See if the access violation happened within the cygwin DLL
1033 itself. Cygwin uses a kind of exception handling to deal
1034 with passed-in invalid addresses. gdb should not treat
1035 these as real SEGVs since they will be silently handled by
1036 cygwin. A real SEGV will (theoretically) be caught by
1037 cygwin later in the process and will be sent as a
1038 cygwin-specific-signal. So, ignore SEGVs if they show up
1039 within the text segment of the DLL itself. */
2c02bd72 1040 const char *fn;
581e13c1
MS
1041 CORE_ADDR addr = (CORE_ADDR) (uintptr_t)
1042 current_event.u.Exception.ExceptionRecord.ExceptionAddress;
1043
1044 if ((!cygwin_exceptions && (addr >= cygwin_load_start
1045 && addr < cygwin_load_end))
a244bdca 1046 || (find_pc_partial_function (addr, &fn, NULL, NULL)
61012eef 1047 && startswith (fn, "KERNEL32!IsBad")))
8da8e0b3
CF
1048 return 0;
1049 }
10325bc5 1050#endif
7393af7c
PM
1051 break;
1052 case STATUS_STACK_OVERFLOW:
1053 DEBUG_EXCEPTION_SIMPLE ("STATUS_STACK_OVERFLOW");
a493e3e2 1054 ourstatus->value.sig = GDB_SIGNAL_SEGV;
7393af7c
PM
1055 break;
1056 case STATUS_FLOAT_DENORMAL_OPERAND:
1057 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DENORMAL_OPERAND");
a493e3e2 1058 ourstatus->value.sig = GDB_SIGNAL_FPE;
7393af7c
PM
1059 break;
1060 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
1061 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ARRAY_BOUNDS_EXCEEDED");
a493e3e2 1062 ourstatus->value.sig = GDB_SIGNAL_FPE;
7393af7c
PM
1063 break;
1064 case STATUS_FLOAT_INEXACT_RESULT:
1065 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INEXACT_RESULT");
a493e3e2 1066 ourstatus->value.sig = GDB_SIGNAL_FPE;
7393af7c
PM
1067 break;
1068 case STATUS_FLOAT_INVALID_OPERATION:
1069 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INVALID_OPERATION");
a493e3e2 1070 ourstatus->value.sig = GDB_SIGNAL_FPE;
7393af7c
PM
1071 break;
1072 case STATUS_FLOAT_OVERFLOW:
1073 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_OVERFLOW");
a493e3e2 1074 ourstatus->value.sig = GDB_SIGNAL_FPE;
7393af7c
PM
1075 break;
1076 case STATUS_FLOAT_STACK_CHECK:
1077 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_STACK_CHECK");
a493e3e2 1078 ourstatus->value.sig = GDB_SIGNAL_FPE;
1ef980b9 1079 break;
3b7c8b74 1080 case STATUS_FLOAT_UNDERFLOW:
7393af7c 1081 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_UNDERFLOW");
a493e3e2 1082 ourstatus->value.sig = GDB_SIGNAL_FPE;
7393af7c 1083 break;
3b7c8b74 1084 case STATUS_FLOAT_DIVIDE_BY_ZERO:
7393af7c 1085 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DIVIDE_BY_ZERO");
a493e3e2 1086 ourstatus->value.sig = GDB_SIGNAL_FPE;
7393af7c 1087 break;
3b7c8b74 1088 case STATUS_INTEGER_DIVIDE_BY_ZERO:
7393af7c 1089 DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_DIVIDE_BY_ZERO");
a493e3e2 1090 ourstatus->value.sig = GDB_SIGNAL_FPE;
3b7c8b74 1091 break;
7393af7c
PM
1092 case STATUS_INTEGER_OVERFLOW:
1093 DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_OVERFLOW");
a493e3e2 1094 ourstatus->value.sig = GDB_SIGNAL_FPE;
1ef980b9
SC
1095 break;
1096 case EXCEPTION_BREAKPOINT:
7393af7c 1097 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_BREAKPOINT");
a493e3e2 1098 ourstatus->value.sig = GDB_SIGNAL_TRAP;
1ef980b9
SC
1099 break;
1100 case DBG_CONTROL_C:
7393af7c 1101 DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_C");
a493e3e2 1102 ourstatus->value.sig = GDB_SIGNAL_INT;
5b421780
PM
1103 break;
1104 case DBG_CONTROL_BREAK:
7393af7c 1105 DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_BREAK");
a493e3e2 1106 ourstatus->value.sig = GDB_SIGNAL_INT;
1ef980b9
SC
1107 break;
1108 case EXCEPTION_SINGLE_STEP:
7393af7c 1109 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_SINGLE_STEP");
a493e3e2 1110 ourstatus->value.sig = GDB_SIGNAL_TRAP;
1ef980b9 1111 break;
8227c82d 1112 case EXCEPTION_ILLEGAL_INSTRUCTION:
7393af7c 1113 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ILLEGAL_INSTRUCTION");
a493e3e2 1114 ourstatus->value.sig = GDB_SIGNAL_ILL;
7393af7c
PM
1115 break;
1116 case EXCEPTION_PRIV_INSTRUCTION:
1117 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_PRIV_INSTRUCTION");
a493e3e2 1118 ourstatus->value.sig = GDB_SIGNAL_ILL;
7393af7c
PM
1119 break;
1120 case EXCEPTION_NONCONTINUABLE_EXCEPTION:
1121 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_NONCONTINUABLE_EXCEPTION");
a493e3e2 1122 ourstatus->value.sig = GDB_SIGNAL_ILL;
8227c82d 1123 break;
1ef980b9 1124 default:
581e13c1 1125 /* Treat unhandled first chance exceptions specially. */
02e423b9 1126 if (current_event.u.Exception.dwFirstChance)
a244bdca 1127 return -1;
d50a0ce2
CV
1128 printf_unfiltered ("gdb: unknown target exception 0x%08x at %s\n",
1129 (unsigned) current_event.u.Exception.ExceptionRecord.ExceptionCode,
a74ce742
PM
1130 host_address_to_string (
1131 current_event.u.Exception.ExceptionRecord.ExceptionAddress));
a493e3e2 1132 ourstatus->value.sig = GDB_SIGNAL_UNKNOWN;
1ef980b9 1133 break;
24e60978 1134 }
24e60978 1135 exception_count++;
7393af7c 1136 last_sig = ourstatus->value.sig;
36339ecd 1137 return 1;
24e60978
SC
1138}
1139
17617f2d
EZ
1140/* Resume thread specified by ID, or all artificially suspended
1141 threads, if we are continuing execution. KILLED non-zero means we
1142 have killed the inferior, so we should ignore weird errors due to
1143 threads shutting down. */
3cee93ac 1144static BOOL
17617f2d 1145windows_continue (DWORD continue_status, int id, int killed)
3cee93ac
CF
1146{
1147 int i;
876d1cd7 1148 windows_thread_info *th;
3cee93ac
CF
1149 BOOL res;
1150
0c3d84be 1151 DEBUG_EVENTS (("ContinueDebugEvent (cpid=%d, ctid=0x%x, %s);\n",
d50a0ce2
CV
1152 (unsigned) current_event.dwProcessId,
1153 (unsigned) current_event.dwThreadId,
dfe7f3ac 1154 continue_status == DBG_CONTINUE ?
7393af7c 1155 "DBG_CONTINUE" : "DBG_EXCEPTION_NOT_HANDLED"));
6537bb24
PA
1156
1157 for (th = &thread_head; (th = th->next) != NULL;)
1158 if ((id == -1 || id == (int) th->id)
1159 && th->suspended)
1160 {
1161 if (debug_registers_changed)
1162 {
1163 th->context.ContextFlags |= CONTEXT_DEBUG_REGISTERS;
1164 th->context.Dr0 = dr[0];
1165 th->context.Dr1 = dr[1];
1166 th->context.Dr2 = dr[2];
1167 th->context.Dr3 = dr[3];
1168 th->context.Dr6 = DR6_CLEAR_VALUE;
1169 th->context.Dr7 = dr[7];
1170 }
1171 if (th->context.ContextFlags)
1172 {
17617f2d
EZ
1173 DWORD ec = 0;
1174
1175 if (GetExitCodeThread (th->h, &ec)
1176 && ec == STILL_ACTIVE)
1177 {
1178 BOOL status = SetThreadContext (th->h, &th->context);
1179
1180 if (!killed)
1181 CHECK (status);
1182 }
6537bb24
PA
1183 th->context.ContextFlags = 0;
1184 }
1185 if (th->suspended > 0)
1186 (void) ResumeThread (th->h);
1187 th->suspended = 0;
1188 }
1189
0714f9bf
SS
1190 res = ContinueDebugEvent (current_event.dwProcessId,
1191 current_event.dwThreadId,
1192 continue_status);
3cee93ac 1193
68ffc902
JT
1194 if (!res)
1195 error (_("Failed to resume program execution"
1196 " (ContinueDebugEvent failed, error %u)"),
1197 (unsigned int) GetLastError ());
1198
fa4ba8da 1199 debug_registers_changed = 0;
3cee93ac
CF
1200 return res;
1201}
1202
d6dc8049
CF
1203/* Called in pathological case where Windows fails to send a
1204 CREATE_PROCESS_DEBUG_EVENT after an attach. */
3ee6f623 1205static DWORD
5439edaa 1206fake_create_process (void)
3ade5333
CF
1207{
1208 current_process_handle = OpenProcess (PROCESS_ALL_ACCESS, FALSE,
1209 current_event.dwProcessId);
bf25528d
CF
1210 if (current_process_handle != NULL)
1211 open_process_used = 1;
1212 else
1213 {
d50a0ce2
CV
1214 error (_("OpenProcess call failed, GetLastError = %u"),
1215 (unsigned) GetLastError ());
bf25528d
CF
1216 /* We can not debug anything in that case. */
1217 }
3ade5333 1218 main_thread_id = current_event.dwThreadId;
711e434b
PM
1219 current_thread = windows_add_thread (
1220 ptid_build (current_event.dwProcessId, 0,
1221 current_event.dwThreadId),
1222 current_event.u.CreateThread.hThread,
1223 current_event.u.CreateThread.lpThreadLocalBase);
3ade5333
CF
1224 return main_thread_id;
1225}
1226
a244bdca 1227static void
28439f5e 1228windows_resume (struct target_ops *ops,
2ea28649 1229 ptid_t ptid, int step, enum gdb_signal sig)
a244bdca 1230{
876d1cd7 1231 windows_thread_info *th;
a244bdca
CF
1232 DWORD continue_status = DBG_CONTINUE;
1233
2dc38344
PA
1234 /* A specific PTID means `step only this thread id'. */
1235 int resume_all = ptid_equal (ptid, minus_one_ptid);
1236
1237 /* If we're continuing all threads, it's the current inferior that
1238 should be handled specially. */
1239 if (resume_all)
1240 ptid = inferior_ptid;
a244bdca 1241
a493e3e2 1242 if (sig != GDB_SIGNAL_0)
a244bdca
CF
1243 {
1244 if (current_event.dwDebugEventCode != EXCEPTION_DEBUG_EVENT)
1245 {
1246 DEBUG_EXCEPT(("Cannot continue with signal %d here.\n",sig));
1247 }
1248 else if (sig == last_sig)
1249 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1250 else
1251#if 0
1252/* This code does not seem to work, because
1253 the kernel does probably not consider changes in the ExceptionRecord
1254 structure when passing the exception to the inferior.
1255 Note that this seems possible in the exception handler itself. */
1256 {
1257 int i;
1258 for (i = 0; xlate[i].them != -1; i++)
1259 if (xlate[i].us == sig)
1260 {
581e13c1
MS
1261 current_event.u.Exception.ExceptionRecord.ExceptionCode
1262 = xlate[i].them;
a244bdca
CF
1263 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1264 break;
1265 }
1266 if (continue_status == DBG_CONTINUE)
1267 {
1268 DEBUG_EXCEPT(("Cannot continue with signal %d.\n",sig));
1269 }
1270 }
1271#endif
23942819 1272 DEBUG_EXCEPT(("Can only continue with received signal %d.\n",
a244bdca
CF
1273 last_sig));
1274 }
1275
a493e3e2 1276 last_sig = GDB_SIGNAL_0;
a244bdca 1277
dc05df57 1278 DEBUG_EXEC (("gdb: windows_resume (pid=%d, tid=%ld, step=%d, sig=%d);\n",
2dc38344 1279 ptid_get_pid (ptid), ptid_get_tid (ptid), step, sig));
a244bdca 1280
581e13c1 1281 /* Get context for currently selected thread. */
2dc38344 1282 th = thread_rec (ptid_get_tid (inferior_ptid), FALSE);
a244bdca
CF
1283 if (th)
1284 {
1285 if (step)
1286 {
581e13c1 1287 /* Single step by setting t bit. */
a97b0ac8
UW
1288 struct regcache *regcache = get_current_regcache ();
1289 struct gdbarch *gdbarch = get_regcache_arch (regcache);
1290 windows_fetch_inferior_registers (ops, regcache,
1291 gdbarch_ps_regnum (gdbarch));
a244bdca
CF
1292 th->context.EFlags |= FLAG_TRACE_BIT;
1293 }
1294
1295 if (th->context.ContextFlags)
1296 {
1297 if (debug_registers_changed)
1298 {
1299 th->context.Dr0 = dr[0];
1300 th->context.Dr1 = dr[1];
1301 th->context.Dr2 = dr[2];
1302 th->context.Dr3 = dr[3];
6537bb24 1303 th->context.Dr6 = DR6_CLEAR_VALUE;
a244bdca
CF
1304 th->context.Dr7 = dr[7];
1305 }
1306 CHECK (SetThreadContext (th->h, &th->context));
1307 th->context.ContextFlags = 0;
1308 }
1309 }
1310
1311 /* Allow continuing with the same signal that interrupted us.
581e13c1 1312 Otherwise complain. */
a244bdca 1313
2dc38344 1314 if (resume_all)
17617f2d 1315 windows_continue (continue_status, -1, 0);
2dc38344 1316 else
17617f2d 1317 windows_continue (continue_status, ptid_get_tid (ptid), 0);
a244bdca
CF
1318}
1319
695de547
CF
1320/* Ctrl-C handler used when the inferior is not run in the same console. The
1321 handler is in charge of interrupting the inferior using DebugBreakProcess.
1322 Note that this function is not available prior to Windows XP. In this case
1323 we emit a warning. */
d603d4b3 1324static BOOL WINAPI
695de547
CF
1325ctrl_c_handler (DWORD event_type)
1326{
1327 const int attach_flag = current_inferior ()->attach_flag;
1328
bb0613a5
PM
1329 /* Only handle Ctrl-C and Ctrl-Break events. Ignore others. */
1330 if (event_type != CTRL_C_EVENT && event_type != CTRL_BREAK_EVENT)
695de547
CF
1331 return FALSE;
1332
1333 /* If the inferior and the debugger share the same console, do nothing as
1334 the inferior has also received the Ctrl-C event. */
1335 if (!new_console && !attach_flag)
1336 return TRUE;
1337
1338 if (!DebugBreakProcess (current_process_handle))
581e13c1
MS
1339 warning (_("Could not interrupt program. "
1340 "Press Ctrl-c in the program console."));
695de547
CF
1341
1342 /* Return true to tell that Ctrl-C has been handled. */
1343 return TRUE;
1344}
1345
e6ad66bd
JT
1346/* Get the next event from the child. Returns a non-zero thread id if the event
1347 requires handling by WFI (or whatever). */
1e37c281 1348static int
28439f5e
PA
1349get_windows_debug_event (struct target_ops *ops,
1350 int pid, struct target_waitstatus *ourstatus)
1e37c281
JM
1351{
1352 BOOL debug_event;
8a892701 1353 DWORD continue_status, event_code;
876d1cd7
YZ
1354 windows_thread_info *th;
1355 static windows_thread_info dummy_thread_info;
e6ad66bd 1356 DWORD thread_id = 0;
1e37c281 1357
a493e3e2 1358 last_sig = GDB_SIGNAL_0;
9d3789f7 1359
8a892701 1360 if (!(debug_event = WaitForDebugEvent (&current_event, 1000)))
29fe111d 1361 goto out;
1e37c281
JM
1362
1363 event_count++;
1364 continue_status = DBG_CONTINUE;
1e37c281 1365
8a892701 1366 event_code = current_event.dwDebugEventCode;
450005e7 1367 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
87a45c96 1368 th = NULL;
a244bdca 1369 have_saved_context = 0;
8a892701
CF
1370
1371 switch (event_code)
1e37c281
JM
1372 {
1373 case CREATE_THREAD_DEBUG_EVENT:
0c3d84be 1374 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
8a892701
CF
1375 (unsigned) current_event.dwProcessId,
1376 (unsigned) current_event.dwThreadId,
1377 "CREATE_THREAD_DEBUG_EVENT"));
dfe7f3ac 1378 if (saw_create != 1)
3ade5333 1379 {
181e7f93
PA
1380 struct inferior *inf;
1381 inf = find_inferior_pid (current_event.dwProcessId);
1382 if (!saw_create && inf->attach_flag)
3ade5333 1383 {
d6dc8049
CF
1384 /* Kludge around a Windows bug where first event is a create
1385 thread event. Caused when attached process does not have
581e13c1 1386 a main thread. */
e6ad66bd
JT
1387 thread_id = fake_create_process ();
1388 if (thread_id)
181e7f93 1389 saw_create++;
3ade5333
CF
1390 }
1391 break;
1392 }
581e13c1 1393 /* Record the existence of this thread. */
e6ad66bd 1394 thread_id = current_event.dwThreadId;
dc05df57 1395 th = windows_add_thread (ptid_build (current_event.dwProcessId, 0,
2dc38344 1396 current_event.dwThreadId),
711e434b
PM
1397 current_event.u.CreateThread.hThread,
1398 current_event.u.CreateThread.lpThreadLocalBase);
1399
1e37c281
JM
1400 break;
1401
1402 case EXIT_THREAD_DEBUG_EVENT:
0c3d84be 1403 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
8a892701
CF
1404 (unsigned) current_event.dwProcessId,
1405 (unsigned) current_event.dwThreadId,
1406 "EXIT_THREAD_DEBUG_EVENT"));
b3c613f2 1407
87a45c96
CF
1408 if (current_event.dwThreadId != main_thread_id)
1409 {
dc05df57 1410 windows_delete_thread (ptid_build (current_event.dwProcessId, 0,
e0ea48a0
EZ
1411 current_event.dwThreadId),
1412 current_event.u.ExitThread.dwExitCode);
87a45c96
CF
1413 th = &dummy_thread_info;
1414 }
1e37c281
JM
1415 break;
1416
1417 case CREATE_PROCESS_DEBUG_EVENT:
0c3d84be 1418 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
8a892701
CF
1419 (unsigned) current_event.dwProcessId,
1420 (unsigned) current_event.dwThreadId,
1421 "CREATE_PROCESS_DEBUG_EVENT"));
700b351b 1422 CloseHandle (current_event.u.CreateProcessInfo.hFile);
dfe7f3ac 1423 if (++saw_create != 1)
bf25528d 1424 break;
1e37c281 1425
dfe7f3ac 1426 current_process_handle = current_event.u.CreateProcessInfo.hProcess;
87a45c96 1427 if (main_thread_id)
695de547 1428 windows_delete_thread (ptid_build (current_event.dwProcessId, 0,
e0ea48a0
EZ
1429 main_thread_id),
1430 0);
9d3789f7 1431 main_thread_id = current_event.dwThreadId;
581e13c1 1432 /* Add the main thread. */
dc05df57 1433 th = windows_add_thread (ptid_build (current_event.dwProcessId, 0,
695de547 1434 current_event.dwThreadId),
711e434b
PM
1435 current_event.u.CreateProcessInfo.hThread,
1436 current_event.u.CreateProcessInfo.lpThreadLocalBase);
e6ad66bd 1437 thread_id = current_event.dwThreadId;
1e37c281
JM
1438 break;
1439
1440 case EXIT_PROCESS_DEBUG_EVENT:
0c3d84be 1441 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
8a892701
CF
1442 (unsigned) current_event.dwProcessId,
1443 (unsigned) current_event.dwThreadId,
1444 "EXIT_PROCESS_DEBUG_EVENT"));
16d905e2
CF
1445 if (!windows_initialization_done)
1446 {
1447 target_terminal_ours ();
1448 target_mourn_inferior ();
1449 error (_("During startup program exited with code 0x%x."),
1450 (unsigned int) current_event.u.ExitProcess.dwExitCode);
1451 }
1452 else if (saw_create == 1)
1453 {
1454 ourstatus->kind = TARGET_WAITKIND_EXITED;
1455 ourstatus->value.integer = current_event.u.ExitProcess.dwExitCode;
e6ad66bd 1456 thread_id = main_thread_id;
16d905e2 1457 }
8a892701 1458 break;
1e37c281
JM
1459
1460 case LOAD_DLL_DEBUG_EVENT:
0c3d84be 1461 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
8a892701
CF
1462 (unsigned) current_event.dwProcessId,
1463 (unsigned) current_event.dwThreadId,
1464 "LOAD_DLL_DEBUG_EVENT"));
700b351b 1465 CloseHandle (current_event.u.LoadDll.hFile);
ea39ad35 1466 if (saw_create != 1 || ! windows_initialization_done)
dfe7f3ac 1467 break;
8a892701 1468 catch_errors (handle_load_dll, NULL, (char *) "", RETURN_MASK_ALL);
450005e7
CF
1469 ourstatus->kind = TARGET_WAITKIND_LOADED;
1470 ourstatus->value.integer = 0;
e6ad66bd 1471 thread_id = main_thread_id;
1e37c281
JM
1472 break;
1473
1474 case UNLOAD_DLL_DEBUG_EVENT:
0c3d84be 1475 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
8a892701
CF
1476 (unsigned) current_event.dwProcessId,
1477 (unsigned) current_event.dwThreadId,
1478 "UNLOAD_DLL_DEBUG_EVENT"));
ea39ad35 1479 if (saw_create != 1 || ! windows_initialization_done)
dfe7f3ac 1480 break;
d3ff4a77 1481 catch_errors (handle_unload_dll, NULL, (char *) "", RETURN_MASK_ALL);
de1b3c3d
PA
1482 ourstatus->kind = TARGET_WAITKIND_LOADED;
1483 ourstatus->value.integer = 0;
e6ad66bd 1484 thread_id = main_thread_id;
d3ff4a77 1485 break;
1e37c281
JM
1486
1487 case EXCEPTION_DEBUG_EVENT:
0c3d84be 1488 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
8a892701
CF
1489 (unsigned) current_event.dwProcessId,
1490 (unsigned) current_event.dwThreadId,
1491 "EXCEPTION_DEBUG_EVENT"));
dfe7f3ac
CF
1492 if (saw_create != 1)
1493 break;
a244bdca
CF
1494 switch (handle_exception (ourstatus))
1495 {
1496 case 0:
1497 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1498 break;
1499 case 1:
e6ad66bd 1500 thread_id = current_event.dwThreadId;
a244bdca
CF
1501 break;
1502 case -1:
1503 last_sig = 1;
1504 continue_status = -1;
1505 break;
1506 }
1e37c281
JM
1507 break;
1508
581e13c1 1509 case OUTPUT_DEBUG_STRING_EVENT: /* Message from the kernel. */
0c3d84be 1510 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
8a892701
CF
1511 (unsigned) current_event.dwProcessId,
1512 (unsigned) current_event.dwThreadId,
1513 "OUTPUT_DEBUG_STRING_EVENT"));
dfe7f3ac
CF
1514 if (saw_create != 1)
1515 break;
e6ad66bd 1516 thread_id = handle_output_debug_string (ourstatus);
1e37c281 1517 break;
9d3789f7 1518
1e37c281 1519 default:
dfe7f3ac
CF
1520 if (saw_create != 1)
1521 break;
0c3d84be 1522 printf_unfiltered ("gdb: kernel event for pid=%u tid=0x%x\n",
d50a0ce2
CV
1523 (unsigned) current_event.dwProcessId,
1524 (unsigned) current_event.dwThreadId);
1525 printf_unfiltered (" unknown event code %u\n",
1526 (unsigned) current_event.dwDebugEventCode);
1e37c281
JM
1527 break;
1528 }
1529
e6ad66bd 1530 if (!thread_id || saw_create != 1)
a244bdca
CF
1531 {
1532 if (continue_status == -1)
02529b48 1533 windows_resume (ops, minus_one_ptid, 0, 1);
a244bdca 1534 else
17617f2d 1535 CHECK (windows_continue (continue_status, -1, 0));
a244bdca 1536 }
450005e7 1537 else
9d3789f7 1538 {
2dc38344 1539 inferior_ptid = ptid_build (current_event.dwProcessId, 0,
e6ad66bd 1540 thread_id);
776704b9
JT
1541 current_thread = th;
1542 if (!current_thread)
f16eab5f 1543 current_thread = thread_rec (thread_id, TRUE);
9d3789f7 1544 }
1e37c281
JM
1545
1546out:
e6ad66bd 1547 return thread_id;
1e37c281
JM
1548}
1549
2dc38344 1550/* Wait for interesting events to occur in the target process. */
39f77062 1551static ptid_t
117de6a9 1552windows_wait (struct target_ops *ops,
47608cb1 1553 ptid_t ptid, struct target_waitstatus *ourstatus, int options)
24e60978 1554{
2dc38344 1555 int pid = -1;
39f77062 1556
c44537cf
CV
1557 target_terminal_ours ();
1558
24e60978
SC
1559 /* We loop when we get a non-standard exception rather than return
1560 with a SPURIOUS because resume can try and step or modify things,
3cee93ac 1561 which needs a current_thread->h. But some of these exceptions mark
24e60978 1562 the birth or death of threads, which mean that the current thread
581e13c1 1563 isn't necessarily what you think it is. */
24e60978
SC
1564
1565 while (1)
450005e7 1566 {
c57918b2 1567 int retval;
2b008701 1568
695de547
CF
1569 /* If the user presses Ctrl-c while the debugger is waiting
1570 for an event, he expects the debugger to interrupt his program
1571 and to get the prompt back. There are two possible situations:
1572
1573 - The debugger and the program do not share the console, in
1574 which case the Ctrl-c event only reached the debugger.
1575 In that case, the ctrl_c handler will take care of interrupting
581e13c1
MS
1576 the inferior. Note that this case is working starting with
1577 Windows XP. For Windows 2000, Ctrl-C should be pressed in the
695de547
CF
1578 inferior console.
1579
1580 - The debugger and the program share the same console, in which
1581 case both debugger and inferior will receive the Ctrl-c event.
1582 In that case the ctrl_c handler will ignore the event, as the
1583 Ctrl-c event generated inside the inferior will trigger the
1584 expected debug event.
1585
1586 FIXME: brobecker/2008-05-20: If the inferior receives the
1587 signal first and the delay until GDB receives that signal
1588 is sufficiently long, GDB can sometimes receive the SIGINT
1589 after we have unblocked the CTRL+C handler. This would
1590 lead to the debugger stopping prematurely while handling
1591 the new-thread event that comes with the handling of the SIGINT
1592 inside the inferior, and then stop again immediately when
1593 the user tries to resume the execution in the inferior.
1594 This is a classic race that we should try to fix one day. */
1595 SetConsoleCtrlHandler (&ctrl_c_handler, TRUE);
28439f5e 1596 retval = get_windows_debug_event (ops, pid, ourstatus);
695de547 1597 SetConsoleCtrlHandler (&ctrl_c_handler, FALSE);
c57918b2 1598
450005e7 1599 if (retval)
2dc38344 1600 return ptid_build (current_event.dwProcessId, 0, retval);
450005e7
CF
1601 else
1602 {
1603 int detach = 0;
3cee93ac 1604
98bbd631
AC
1605 if (deprecated_ui_loop_hook != NULL)
1606 detach = deprecated_ui_loop_hook (0);
0714f9bf 1607
450005e7 1608 if (detach)
7d85a9c0 1609 windows_kill_inferior (ops);
450005e7
CF
1610 }
1611 }
24e60978
SC
1612}
1613
ea39ad35
JB
1614/* Iterate over all DLLs currently mapped by our inferior, and
1615 add them to our list of solibs. */
94481b8c
JB
1616
1617static void
ea39ad35 1618windows_add_all_dlls (void)
94481b8c
JB
1619{
1620 struct so_list *so;
1621 HMODULE dummy_hmodule;
1622 DWORD cb_needed;
1623 HMODULE *hmodules;
1624 int i;
1625
94481b8c
JB
1626 if (EnumProcessModules (current_process_handle, &dummy_hmodule,
1627 sizeof (HMODULE), &cb_needed) == 0)
1628 return;
1629
1630 if (cb_needed < 1)
1631 return;
1632
1633 hmodules = (HMODULE *) alloca (cb_needed);
1634 if (EnumProcessModules (current_process_handle, hmodules,
1635 cb_needed, &cb_needed) == 0)
1636 return;
1637
ea39ad35 1638 for (i = 1; i < (int) (cb_needed / sizeof (HMODULE)); i++)
94481b8c
JB
1639 {
1640 MODULEINFO mi;
774f74c2
PM
1641#ifdef __USEWIDE
1642 wchar_t dll_name[__PMAX];
1643 char name[__PMAX];
1644#else
94481b8c 1645 char dll_name[__PMAX];
774f74c2
PM
1646 char *name;
1647#endif
94481b8c
JB
1648 if (GetModuleInformation (current_process_handle, hmodules[i],
1649 &mi, sizeof (mi)) == 0)
1650 continue;
1651 if (GetModuleFileNameEx (current_process_handle, hmodules[i],
1652 dll_name, sizeof (dll_name)) == 0)
1653 continue;
774f74c2
PM
1654#ifdef __USEWIDE
1655 wcstombs (name, dll_name, __PMAX);
1656#else
1657 name = dll_name;
1658#endif
ea39ad35
JB
1659
1660 solib_end->next = windows_make_so (name, mi.lpBaseOfDll);
1661 solib_end = solib_end->next;
94481b8c
JB
1662 }
1663}
1664
9d3789f7 1665static void
dc05df57 1666do_initial_windows_stuff (struct target_ops *ops, DWORD pid, int attaching)
9d3789f7 1667{
fa4ba8da 1668 int i;
d6b48e9c 1669 struct inferior *inf;
2020b7ab 1670 struct thread_info *tp;
9d3789f7 1671
a493e3e2 1672 last_sig = GDB_SIGNAL_0;
9d3789f7
CF
1673 event_count = 0;
1674 exception_count = 0;
bf25528d 1675 open_process_used = 0;
fa4ba8da 1676 debug_registers_changed = 0;
dfe7f3ac 1677 debug_registers_used = 0;
fa4ba8da
PM
1678 for (i = 0; i < sizeof (dr) / sizeof (dr[0]); i++)
1679 dr[i] = 0;
10325bc5 1680#ifdef __CYGWIN__
de1b3c3d 1681 cygwin_load_start = cygwin_load_end = 0;
10325bc5 1682#endif
9d3789f7
CF
1683 current_event.dwProcessId = pid;
1684 memset (&current_event, 0, sizeof (current_event));
6a3cb8e8
PA
1685 if (!target_is_pushed (ops))
1686 push_target (ops);
cb851954 1687 disable_breakpoints_in_shlibs ();
dc05df57 1688 windows_clear_solib ();
88056fbb 1689 clear_proceed_status (0);
9d3789f7
CF
1690 init_wait_for_inferior ();
1691
6c95b8df
PA
1692 inf = current_inferior ();
1693 inferior_appeared (inf, pid);
181e7f93 1694 inf->attach_flag = attaching;
7f9f62ba 1695
9f9d052e
PM
1696 /* Make the new process the current inferior, so terminal handling
1697 can rely on it. When attaching, we don't know about any thread
1698 id here, but that's OK --- nothing should be referencing the
dc05df57 1699 current thread until we report an event out of windows_wait. */
9f9d052e
PM
1700 inferior_ptid = pid_to_ptid (pid);
1701
5842f62a 1702 target_terminal_init ();
9d3789f7
CF
1703 target_terminal_inferior ();
1704
16d905e2 1705 windows_initialization_done = 0;
c72f45d1 1706
9d3789f7
CF
1707 while (1)
1708 {
c72f45d1
PA
1709 struct target_waitstatus status;
1710
1711 windows_wait (ops, minus_one_ptid, &status, 0);
1712
1713 /* Note windows_wait returns TARGET_WAITKIND_SPURIOUS for thread
1714 events. */
1715 if (status.kind != TARGET_WAITKIND_LOADED
1716 && status.kind != TARGET_WAITKIND_SPURIOUS)
9d3789f7 1717 break;
c72f45d1
PA
1718
1719 windows_resume (ops, minus_one_ptid, 0, GDB_SIGNAL_0);
9d3789f7 1720 }
eff8332b 1721
ea39ad35 1722 /* Now that the inferior has been started and all DLLs have been mapped,
3be75f87
JB
1723 we can iterate over all DLLs and load them in.
1724
1725 We avoid doing it any earlier because, on certain versions of Windows,
1726 LOAD_DLL_DEBUG_EVENTs are sometimes not complete. In particular,
1727 we have seen on Windows 8.1 that the ntdll.dll load event does not
1728 include the DLL name, preventing us from creating an associated SO.
1729 A possible explanation is that ntdll.dll might be mapped before
1730 the SO info gets created by the Windows system -- ntdll.dll is
1731 the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs
1732 do not seem to suffer from that problem.
1733
1734 Rather than try to work around this sort of issue, it is much
1735 simpler to just ignore DLL load/unload events during the startup
1736 phase, and then process them all in one batch now. */
ea39ad35 1737 windows_add_all_dlls ();
94481b8c 1738
16d905e2 1739 windows_initialization_done = 1;
9d3789f7
CF
1740 return;
1741}
1742
616a9dc4
CV
1743/* Try to set or remove a user privilege to the current process. Return -1
1744 if that fails, the previous setting of that privilege otherwise.
1745
1746 This code is copied from the Cygwin source code and rearranged to allow
1747 dynamically loading of the needed symbols from advapi32 which is only
581e13c1 1748 available on NT/2K/XP. */
616a9dc4
CV
1749static int
1750set_process_privilege (const char *privilege, BOOL enable)
1751{
616a9dc4
CV
1752 HANDLE token_hdl = NULL;
1753 LUID restore_priv;
1754 TOKEN_PRIVILEGES new_priv, orig_priv;
1755 int ret = -1;
1756 DWORD size;
1757
616a9dc4
CV
1758 if (!OpenProcessToken (GetCurrentProcess (),
1759 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
1760 &token_hdl))
1761 goto out;
1762
418c6cb3 1763 if (!LookupPrivilegeValueA (NULL, privilege, &restore_priv))
616a9dc4
CV
1764 goto out;
1765
1766 new_priv.PrivilegeCount = 1;
1767 new_priv.Privileges[0].Luid = restore_priv;
1768 new_priv.Privileges[0].Attributes = enable ? SE_PRIVILEGE_ENABLED : 0;
1769
1770 if (!AdjustTokenPrivileges (token_hdl, FALSE, &new_priv,
295732ea 1771 sizeof orig_priv, &orig_priv, &size))
616a9dc4
CV
1772 goto out;
1773#if 0
1774 /* Disabled, otherwise every `attach' in an unprivileged user session
1775 would raise the "Failed to get SE_DEBUG_NAME privilege" warning in
581e13c1 1776 windows_attach(). */
616a9dc4 1777 /* AdjustTokenPrivileges returns TRUE even if the privilege could not
581e13c1 1778 be enabled. GetLastError () returns an correct error code, though. */
616a9dc4
CV
1779 if (enable && GetLastError () == ERROR_NOT_ALL_ASSIGNED)
1780 goto out;
1781#endif
1782
1783 ret = orig_priv.Privileges[0].Attributes == SE_PRIVILEGE_ENABLED ? 1 : 0;
1784
1785out:
1786 if (token_hdl)
1787 CloseHandle (token_hdl);
1788
1789 return ret;
1790}
1791
02cc9f49 1792/* Attach to process PID, then initialize for debugging it. */
24e60978 1793static void
c0939df1 1794windows_attach (struct target_ops *ops, const char *args, int from_tty)
24e60978
SC
1795{
1796 BOOL ok;
559e75c0 1797 DWORD pid;
24e60978 1798
74164c56 1799 pid = parse_pid_to_attach (args);
24e60978 1800
616a9dc4
CV
1801 if (set_process_privilege (SE_DEBUG_NAME, TRUE) < 0)
1802 {
1803 printf_unfiltered ("Warning: Failed to get SE_DEBUG_NAME privilege\n");
581e13c1
MS
1804 printf_unfiltered ("This can cause attach to "
1805 "fail on Windows NT/2K/XP\n");
616a9dc4
CV
1806 }
1807
dc05df57 1808 windows_init_thread_list ();
9d3789f7 1809 ok = DebugActiveProcess (pid);
91a175b3 1810 saw_create = 0;
24e60978 1811
10325bc5 1812#ifdef __CYGWIN__
24e60978 1813 if (!ok)
baa93fa6 1814 {
581e13c1 1815 /* Try fall back to Cygwin pid. */
baa93fa6
CF
1816 pid = cygwin_internal (CW_CYGWIN_PID_TO_WINPID, pid);
1817
1818 if (pid > 0)
1819 ok = DebugActiveProcess (pid);
10325bc5
PA
1820 }
1821#endif
baa93fa6 1822
10325bc5
PA
1823 if (!ok)
1824 error (_("Can't attach to process."));
24e60978 1825
2b008701 1826 DebugSetProcessKillOnExit (FALSE);
3ade5333 1827
24e60978
SC
1828 if (from_tty)
1829 {
1830 char *exec_file = (char *) get_exec_file (0);
1831
1832 if (exec_file)
1833 printf_unfiltered ("Attaching to program `%s', %s\n", exec_file,
39f77062 1834 target_pid_to_str (pid_to_ptid (pid)));
24e60978
SC
1835 else
1836 printf_unfiltered ("Attaching to %s\n",
39f77062 1837 target_pid_to_str (pid_to_ptid (pid)));
24e60978
SC
1838
1839 gdb_flush (gdb_stdout);
1840 }
1841
dc05df57 1842 do_initial_windows_stuff (ops, pid, 1);
9d3789f7 1843 target_terminal_ours ();
24e60978
SC
1844}
1845
24e60978 1846static void
52554a0e 1847windows_detach (struct target_ops *ops, const char *args, int from_tty)
24e60978 1848{
02cc9f49
CV
1849 int detached = 1;
1850
2b008701 1851 ptid_t ptid = {-1};
a493e3e2 1852 windows_resume (ops, ptid, 0, GDB_SIGNAL_0);
96998ce7 1853
2b008701
CF
1854 if (!DebugActiveProcessStop (current_event.dwProcessId))
1855 {
d50a0ce2
CV
1856 error (_("Can't detach process %u (error %u)"),
1857 (unsigned) current_event.dwProcessId, (unsigned) GetLastError ());
2b008701 1858 detached = 0;
02cc9f49 1859 }
2b008701
CF
1860 DebugSetProcessKillOnExit (FALSE);
1861
02cc9f49 1862 if (detached && from_tty)
24e60978
SC
1863 {
1864 char *exec_file = get_exec_file (0);
1865 if (exec_file == 0)
1866 exec_file = "";
d50a0ce2
CV
1867 printf_unfiltered ("Detaching from program: %s, Pid %u\n", exec_file,
1868 (unsigned) current_event.dwProcessId);
24e60978
SC
1869 gdb_flush (gdb_stdout);
1870 }
7f9f62ba 1871
df7e5265 1872 x86_cleanup_dregs ();
39f77062 1873 inferior_ptid = null_ptid;
7f9f62ba
PA
1874 detach_inferior (current_event.dwProcessId);
1875
6a3cb8e8 1876 inf_child_maybe_unpush_target (ops);
24e60978
SC
1877}
1878
47f7ffdb
JB
1879/* Try to determine the executable filename.
1880
1881 EXE_NAME_RET is a pointer to a buffer whose size is EXE_NAME_MAX_LEN.
1882
1883 Upon success, the filename is stored inside EXE_NAME_RET, and
1884 this function returns nonzero.
1885
1886 Otherwise, this function returns zero and the contents of
1887 EXE_NAME_RET is undefined. */
1888
1889static int
1890windows_get_exec_module_filename (char *exe_name_ret, size_t exe_name_max_len)
1891{
1892 DWORD len;
1893 HMODULE dh_buf;
1894 DWORD cbNeeded;
1895
1896 cbNeeded = 0;
1897 if (!EnumProcessModules (current_process_handle, &dh_buf,
1898 sizeof (HMODULE), &cbNeeded) || !cbNeeded)
1899 return 0;
1900
1901 /* We know the executable is always first in the list of modules,
1902 which we just fetched. So no need to fetch more. */
1903
1904#ifdef __CYGWIN__
1905 {
1906 /* Cygwin prefers that the path be in /x/y/z format, so extract
1907 the filename into a temporary buffer first, and then convert it
1908 to POSIX format into the destination buffer. */
1909 cygwin_buf_t *pathbuf = alloca (exe_name_max_len * sizeof (cygwin_buf_t));
1910
1911 len = GetModuleFileNameEx (current_process_handle,
1912 dh_buf, pathbuf, exe_name_max_len);
1913 if (len == 0)
1914 error (_("Error getting executable filename: %u."),
1915 (unsigned) GetLastError ());
1916 if (cygwin_conv_path (CCP_WIN_W_TO_POSIX, pathbuf, exe_name_ret,
1917 exe_name_max_len) < 0)
1918 error (_("Error converting executable filename to POSIX: %d."), errno);
1919 }
1920#else
1921 len = GetModuleFileNameEx (current_process_handle,
1922 dh_buf, exe_name_ret, exe_name_max_len);
1923 if (len == 0)
1924 error (_("Error getting executable filename: %u."),
1925 (unsigned) GetLastError ());
1926#endif
1927
1928 return 1; /* success */
1929}
1930
1931/* The pid_to_exec_file target_ops method for this platform. */
1932
3ee6f623 1933static char *
8dd27370 1934windows_pid_to_exec_file (struct target_ops *self, int pid)
47216e51 1935{
b3c613f2 1936 static char path[__PMAX];
10325bc5 1937#ifdef __CYGWIN__
581e13c1 1938 /* Try to find exe name as symlink target of /proc/<pid>/exe. */
33605d39
CF
1939 int nchars;
1940 char procexe[sizeof ("/proc/4294967295/exe")];
08850b56
PM
1941
1942 xsnprintf (procexe, sizeof (procexe), "/proc/%u/exe", pid);
33605d39
CF
1943 nchars = readlink (procexe, path, sizeof(path));
1944 if (nchars > 0 && nchars < sizeof (path))
47216e51 1945 {
33605d39
CF
1946 path[nchars] = '\0'; /* Got it */
1947 return path;
47216e51 1948 }
10325bc5
PA
1949#endif
1950
33605d39 1951 /* If we get here then either Cygwin is hosed, this isn't a Cygwin version
581e13c1 1952 of gdb, or we're trying to debug a non-Cygwin windows executable. */
47f7ffdb 1953 if (!windows_get_exec_module_filename (path, sizeof (path)))
33605d39
CF
1954 path[0] = '\0';
1955
1956 return path;
47216e51
CV
1957}
1958
24e60978
SC
1959/* Print status information about what we're accessing. */
1960
1961static void
dc05df57 1962windows_files_info (struct target_ops *ignore)
24e60978 1963{
181e7f93
PA
1964 struct inferior *inf = current_inferior ();
1965
24e60978 1966 printf_unfiltered ("\tUsing the running image of %s %s.\n",
181e7f93
PA
1967 inf->attach_flag ? "attached" : "child",
1968 target_pid_to_str (inferior_ptid));
24e60978
SC
1969}
1970
cd44747c
PM
1971/* Modify CreateProcess parameters for use of a new separate console.
1972 Parameters are:
1973 *FLAGS: DWORD parameter for general process creation flags.
1974 *SI: STARTUPINFO structure, for which the console window size and
1975 console buffer size is filled in if GDB is running in a console.
1976 to create the new console.
1977 The size of the used font is not available on all versions of
1978 Windows OS. Furthermore, the current font might not be the default
1979 font, but this is still better than before.
1980 If the windows and buffer sizes are computed,
1981 SI->DWFLAGS is changed so that this information is used
1982 by CreateProcess function. */
1983
1984static void
1985windows_set_console_info (STARTUPINFO *si, DWORD *flags)
1986{
1987 HANDLE hconsole = CreateFile ("CONOUT$", GENERIC_READ | GENERIC_WRITE,
1988 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
1989
1990 if (hconsole != INVALID_HANDLE_VALUE)
1991 {
1992 CONSOLE_SCREEN_BUFFER_INFO sbinfo;
1993 COORD font_size;
1994 CONSOLE_FONT_INFO cfi;
1995
1996 GetCurrentConsoleFont (hconsole, FALSE, &cfi);
1997 font_size = GetConsoleFontSize (hconsole, cfi.nFont);
1998 GetConsoleScreenBufferInfo(hconsole, &sbinfo);
1999 si->dwXSize = sbinfo.srWindow.Right - sbinfo.srWindow.Left + 1;
2000 si->dwYSize = sbinfo.srWindow.Bottom - sbinfo.srWindow.Top + 1;
2001 if (font_size.X)
2002 si->dwXSize *= font_size.X;
2003 else
2004 si->dwXSize *= 8;
2005 if (font_size.Y)
2006 si->dwYSize *= font_size.Y;
2007 else
2008 si->dwYSize *= 12;
2009 si->dwXCountChars = sbinfo.dwSize.X;
2010 si->dwYCountChars = sbinfo.dwSize.Y;
2011 si->dwFlags |= STARTF_USESIZE | STARTF_USECOUNTCHARS;
2012 }
2013 *flags |= CREATE_NEW_CONSOLE;
2014}
2015
c93dbcba
EZ
2016#ifndef __CYGWIN__
2017/* Function called by qsort to sort environment strings. */
2018
2019static int
2020envvar_cmp (const void *a, const void *b)
2021{
2022 const char **p = (const char **) a;
2023 const char **q = (const char **) b;
2024 return strcasecmp (*p, *q);
2025}
2026#endif
2027
b7ff339d
CV
2028#ifdef __CYGWIN__
2029static void
2030clear_win32_environment (char **env)
2031{
2032 int i;
2033 size_t len;
2034 wchar_t *copy = NULL, *equalpos;
2035
2036 for (i = 0; env[i] && *env[i]; i++)
2037 {
2038 len = mbstowcs (NULL, env[i], 0) + 1;
2039 copy = (wchar_t *) xrealloc (copy, len * sizeof (wchar_t));
2040 mbstowcs (copy, env[i], len);
2041 equalpos = wcschr (copy, L'=');
2042 if (equalpos)
2043 *equalpos = L'\0';
2044 SetEnvironmentVariableW (copy, NULL);
2045 }
2046 xfree (copy);
2047}
2048#endif
2049
dc05df57 2050/* Start an inferior windows child process and sets inferior_ptid to its pid.
24e60978
SC
2051 EXEC_FILE is the file to run.
2052 ALLARGS is a string containing the arguments to the program.
2053 ENV is the environment vector to pass. Errors reported with error(). */
2054
24e60978 2055static void
dc05df57 2056windows_create_inferior (struct target_ops *ops, char *exec_file,
136d6dae 2057 char *allargs, char **in_env, int from_tty)
24e60978 2058{
b3c613f2 2059 STARTUPINFO si;
41b4aadc 2060#ifdef __CYGWIN__
b3c613f2
CF
2061 cygwin_buf_t real_path[__PMAX];
2062 cygwin_buf_t shell[__PMAX]; /* Path to shell */
d0d0ab16 2063 const char *sh;
b3c613f2
CF
2064 cygwin_buf_t *toexec;
2065 cygwin_buf_t *cygallargs;
2066 cygwin_buf_t *args;
b7ff339d
CV
2067 char **old_env = NULL;
2068 PWCHAR w32_env;
d0d0ab16 2069 size_t len;
2becadee
CF
2070 int tty;
2071 int ostdin, ostdout, ostderr;
41b4aadc 2072#else
b3c613f2
CF
2073 char real_path[__PMAX];
2074 char shell[__PMAX]; /* Path to shell */
d0d0ab16
CV
2075 char *toexec;
2076 char *args;
8f205f9c 2077 size_t args_len;
41b4aadc 2078 HANDLE tty;
c93dbcba
EZ
2079 char *w32env;
2080 char *temp;
2081 size_t envlen;
2082 int i;
2083 size_t envsize;
2084 char **env;
41b4aadc 2085#endif
d0d0ab16
CV
2086 PROCESS_INFORMATION pi;
2087 BOOL ret;
2088 DWORD flags = 0;
3cb3b8df 2089 const char *inferior_io_terminal = get_inferior_io_terminal ();
24e60978
SC
2090
2091 if (!exec_file)
8a3fe4f8 2092 error (_("No executable specified, use `target exec'."));
24e60978
SC
2093
2094 memset (&si, 0, sizeof (si));
2095 si.cb = sizeof (si);
2096
d0d0ab16
CV
2097 if (new_group)
2098 flags |= CREATE_NEW_PROCESS_GROUP;
2099
2100 if (new_console)
cd44747c 2101 windows_set_console_info (&si, &flags);
d0d0ab16 2102
10325bc5 2103#ifdef __CYGWIN__
349b409f 2104 if (!useshell)
dfe7f3ac 2105 {
d0d0ab16
CV
2106 flags |= DEBUG_ONLY_THIS_PROCESS;
2107 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, exec_file, real_path,
b3c613f2 2108 __PMAX * sizeof (cygwin_buf_t)) < 0)
d0d0ab16 2109 error (_("Error starting executable: %d"), errno);
dfe7f3ac 2110 toexec = real_path;
b3c613f2 2111#ifdef __USEWIDE
d0d0ab16
CV
2112 len = mbstowcs (NULL, allargs, 0) + 1;
2113 if (len == (size_t) -1)
2114 error (_("Error starting executable: %d"), errno);
2115 cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
2116 mbstowcs (cygallargs, allargs, len);
60c5c021
CF
2117#else
2118 cygallargs = allargs;
b3c613f2 2119#endif
dfe7f3ac
CF
2120 }
2121 else
2122 {
349b409f
CF
2123 sh = getenv ("SHELL");
2124 if (!sh)
2125 sh = "/bin/sh";
b3c613f2 2126 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, sh, shell, __PMAX) < 0)
d0d0ab16 2127 error (_("Error starting executable via shell: %d"), errno);
b3c613f2 2128#ifdef __USEWIDE
d0d0ab16
CV
2129 len = sizeof (L" -c 'exec '") + mbstowcs (NULL, exec_file, 0)
2130 + mbstowcs (NULL, allargs, 0) + 2;
2131 cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
2132 swprintf (cygallargs, len, L" -c 'exec %s %s'", exec_file, allargs);
b3c613f2 2133#else
08850b56
PM
2134 len = (sizeof (" -c 'exec '") + strlen (exec_file)
2135 + strlen (allargs) + 2);
2136 cygallargs = (char *) alloca (len);
2137 xsnprintf (cygallargs, len, " -c 'exec %s %s'", exec_file, allargs);
b3c613f2 2138#endif
dfe7f3ac 2139 toexec = shell;
d0d0ab16 2140 flags |= DEBUG_PROCESS;
dfe7f3ac 2141 }
b3c613f2
CF
2142
2143#ifdef __USEWIDE
2144 args = (cygwin_buf_t *) alloca ((wcslen (toexec) + wcslen (cygallargs) + 2)
2145 * sizeof (wchar_t));
d0d0ab16
CV
2146 wcscpy (args, toexec);
2147 wcscat (args, L" ");
2148 wcscat (args, cygallargs);
b3c613f2
CF
2149#else
2150 args = (cygwin_buf_t *) alloca (strlen (toexec) + strlen (cygallargs) + 2);
2151 strcpy (args, toexec);
2152 strcat (args, " ");
2153 strcat (args, cygallargs);
2154#endif
2155
b7ff339d
CV
2156#ifdef CW_CVT_ENV_TO_WINENV
2157 /* First try to create a direct Win32 copy of the POSIX environment. */
2158 w32_env = (PWCHAR) cygwin_internal (CW_CVT_ENV_TO_WINENV, in_env);
2159 if (w32_env != (PWCHAR) -1)
2160 flags |= CREATE_UNICODE_ENVIRONMENT;
2161 else
2162 /* If that fails, fall back to old method tweaking GDB's environment. */
2163#endif
2164 {
2165 /* Reset all Win32 environment variables to avoid leftover on next run. */
2166 clear_win32_environment (environ);
2167 /* Prepare the environment vars for CreateProcess. */
2168 old_env = environ;
2169 environ = in_env;
2170 cygwin_internal (CW_SYNC_WINENV);
2171 w32_env = NULL;
2172 }
1750a5ef 2173
2becadee
CF
2174 if (!inferior_io_terminal)
2175 tty = ostdin = ostdout = ostderr = -1;
2176 else
2177 {
2178 tty = open (inferior_io_terminal, O_RDWR | O_NOCTTY);
2179 if (tty < 0)
2180 {
2181 print_sys_errmsg (inferior_io_terminal, errno);
2182 ostdin = ostdout = ostderr = -1;
2183 }
2184 else
2185 {
2186 ostdin = dup (0);
2187 ostdout = dup (1);
2188 ostderr = dup (2);
2189 dup2 (tty, 0);
2190 dup2 (tty, 1);
2191 dup2 (tty, 2);
2192 }
2193 }
d0d0ab16
CV
2194
2195 windows_init_thread_list ();
b3c613f2
CF
2196 ret = CreateProcess (0,
2197 args, /* command line */
2198 NULL, /* Security */
2199 NULL, /* thread */
2200 TRUE, /* inherit handles */
2201 flags, /* start flags */
b7ff339d 2202 w32_env, /* environment */
b3c613f2
CF
2203 NULL, /* current directory */
2204 &si,
2205 &pi);
b7ff339d
CV
2206 if (w32_env)
2207 /* Just free the Win32 environment, if it could be created. */
2208 free (w32_env);
2209 else
2210 {
2211 /* Reset all environment variables to avoid leftover on next run. */
2212 clear_win32_environment (in_env);
2213 /* Restore normal GDB environment variables. */
2214 environ = old_env;
2215 cygwin_internal (CW_SYNC_WINENV);
2216 }
2217
d0d0ab16
CV
2218 if (tty >= 0)
2219 {
2220 close (tty);
2221 dup2 (ostdin, 0);
2222 dup2 (ostdout, 1);
2223 dup2 (ostderr, 2);
2224 close (ostdin);
2225 close (ostdout);
2226 close (ostderr);
2227 }
41b4aadc 2228#else
b3c613f2 2229 toexec = exec_file;
8f205f9c
JB
2230 /* Build the command line, a space-separated list of tokens where
2231 the first token is the name of the module to be executed.
2232 To avoid ambiguities introduced by spaces in the module name,
2233 we quote it. */
2234 args_len = strlen (toexec) + 2 /* quotes */ + strlen (allargs) + 2;
0ae1c716 2235 args = (char *) alloca (args_len);
8f205f9c 2236 xsnprintf (args, args_len, "\"%s\" %s", toexec, allargs);
d0d0ab16 2237
d0d0ab16
CV
2238 flags |= DEBUG_ONLY_THIS_PROCESS;
2239
41b4aadc
CF
2240 if (!inferior_io_terminal)
2241 tty = INVALID_HANDLE_VALUE;
2242 else
2243 {
2244 SECURITY_ATTRIBUTES sa;
2245 sa.nLength = sizeof(sa);
2246 sa.lpSecurityDescriptor = 0;
2247 sa.bInheritHandle = TRUE;
2248 tty = CreateFileA (inferior_io_terminal, GENERIC_READ | GENERIC_WRITE,
2249 0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
2250 if (tty == INVALID_HANDLE_VALUE)
2251 warning (_("Warning: Failed to open TTY %s, error %#x."),
2252 inferior_io_terminal, (unsigned) GetLastError ());
2253 else
2254 {
2255 si.hStdInput = tty;
2256 si.hStdOutput = tty;
2257 si.hStdError = tty;
2258 si.dwFlags |= STARTF_USESTDHANDLES;
2259 }
2260 }
2becadee 2261
c93dbcba
EZ
2262 /* CreateProcess takes the environment list as a null terminated set of
2263 strings (i.e. two nulls terminate the list). */
2264
2265 /* Get total size for env strings. */
2266 for (envlen = 0, i = 0; in_env[i] && *in_env[i]; i++)
2267 envlen += strlen (in_env[i]) + 1;
2268
2269 envsize = sizeof (in_env[0]) * (i + 1);
2270 env = (char **) alloca (envsize);
2271 memcpy (env, in_env, envsize);
2272 /* Windows programs expect the environment block to be sorted. */
2273 qsort (env, i, sizeof (char *), envvar_cmp);
2274
0ae1c716 2275 w32env = (char *) alloca (envlen + 1);
c93dbcba
EZ
2276
2277 /* Copy env strings into new buffer. */
2278 for (temp = w32env, i = 0; env[i] && *env[i]; i++)
2279 {
2280 strcpy (temp, env[i]);
2281 temp += strlen (temp) + 1;
2282 }
2283
2284 /* Final nil string to terminate new env. */
2285 *temp = 0;
2286
dc05df57 2287 windows_init_thread_list ();
d0d0ab16
CV
2288 ret = CreateProcessA (0,
2289 args, /* command line */
2290 NULL, /* Security */
2291 NULL, /* thread */
2292 TRUE, /* inherit handles */
2293 flags, /* start flags */
c93dbcba 2294 w32env, /* environment */
d0d0ab16
CV
2295 NULL, /* current directory */
2296 &si,
2297 &pi);
41b4aadc
CF
2298 if (tty != INVALID_HANDLE_VALUE)
2299 CloseHandle (tty);
10325bc5 2300#endif
2becadee 2301
24e60978 2302 if (!ret)
d50a0ce2 2303 error (_("Error creating process %s, (error %u)."),
8a3fe4f8 2304 exec_file, (unsigned) GetLastError ());
24e60978 2305
c1766e7d
PM
2306 CloseHandle (pi.hThread);
2307 CloseHandle (pi.hProcess);
2308
dfe7f3ac
CF
2309 if (useshell && shell[0] != '\0')
2310 saw_create = -1;
2311 else
2312 saw_create = 0;
2313
dc05df57 2314 do_initial_windows_stuff (ops, pi.dwProcessId, 0);
d3a09475 2315
17617f2d 2316 /* windows_continue (DBG_CONTINUE, -1, 0); */
24e60978
SC
2317}
2318
2319static void
dc05df57 2320windows_mourn_inferior (struct target_ops *ops)
24e60978 2321{
17617f2d 2322 (void) windows_continue (DBG_CONTINUE, -1, 0);
df7e5265 2323 x86_cleanup_dregs();
bf25528d
CF
2324 if (open_process_used)
2325 {
2326 CHECK (CloseHandle (current_process_handle));
2327 open_process_used = 0;
2328 }
c1ee2fb3 2329 inf_child_mourn_inferior (ops);
24e60978
SC
2330}
2331
24e60978 2332/* Send a SIGINT to the process group. This acts just like the user typed a
581e13c1 2333 ^C on the controlling terminal. */
24e60978 2334
b607efe7 2335static void
bfedc46a 2336windows_interrupt (struct target_ops *self, ptid_t ptid)
24e60978 2337{
1ef980b9 2338 DEBUG_EVENTS (("gdb: GenerateConsoleCtrlEvent (CTRLC_EVENT, 0)\n"));
1e37c281 2339 CHECK (GenerateConsoleCtrlEvent (CTRL_C_EVENT, current_event.dwProcessId));
3a4b77d8 2340 registers_changed (); /* refresh register state */
24e60978
SC
2341}
2342
44f38867
PA
2343/* Helper for windows_xfer_partial that handles memory transfers.
2344 Arguments are like target_xfer_partial. */
2345
9b409511 2346static enum target_xfer_status
44f38867 2347windows_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
9b409511 2348 ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
24e60978 2349{
5732a500 2350 SIZE_T done = 0;
44f38867 2351 BOOL success;
9e52adf9 2352 DWORD lasterror = 0;
44f38867
PA
2353
2354 if (writebuf != NULL)
24e60978 2355 {
a2388568 2356 DEBUG_MEM (("gdb: write target memory, %s bytes at %s\n",
b55e14c7 2357 pulongest (len), core_addr_to_string (memaddr)));
44f38867
PA
2358 success = WriteProcessMemory (current_process_handle,
2359 (LPVOID) (uintptr_t) memaddr, writebuf,
2360 len, &done);
9e52adf9 2361 if (!success)
7126d5c8 2362 lasterror = GetLastError ();
2b008701 2363 FlushInstructionCache (current_process_handle,
2c647436 2364 (LPCVOID) (uintptr_t) memaddr, len);
24e60978
SC
2365 }
2366 else
2367 {
a2388568 2368 DEBUG_MEM (("gdb: read target memory, %s bytes at %s\n",
b55e14c7 2369 pulongest (len), core_addr_to_string (memaddr)));
44f38867
PA
2370 success = ReadProcessMemory (current_process_handle,
2371 (LPCVOID) (uintptr_t) memaddr, readbuf,
2372 len, &done);
9e52adf9 2373 if (!success)
7126d5c8 2374 lasterror = GetLastError ();
24e60978 2375 }
9b409511 2376 *xfered_len = (ULONGEST) done;
9e52adf9 2377 if (!success && lasterror == ERROR_PARTIAL_COPY && done > 0)
9b409511 2378 return TARGET_XFER_OK;
9e52adf9 2379 else
9b409511 2380 return success ? TARGET_XFER_OK : TARGET_XFER_E_IO;
24e60978
SC
2381}
2382
3ee6f623 2383static void
7d85a9c0 2384windows_kill_inferior (struct target_ops *ops)
24e60978 2385{
3cee93ac
CF
2386 CHECK (TerminateProcess (current_process_handle, 0));
2387
b5edcb45
ILT
2388 for (;;)
2389 {
17617f2d 2390 if (!windows_continue (DBG_CONTINUE, -1, 1))
b5edcb45 2391 break;
3cee93ac 2392 if (!WaitForDebugEvent (&current_event, INFINITE))
b5edcb45 2393 break;
3cee93ac 2394 if (current_event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
b5edcb45
ILT
2395 break;
2396 }
2397
581e13c1 2398 target_mourn_inferior (); /* Or just windows_mourn_inferior? */
24e60978
SC
2399}
2400
24e60978 2401static void
de90e03d 2402windows_close (struct target_ops *self)
24e60978 2403{
dc05df57 2404 DEBUG_EVENTS (("gdb: windows_close, inferior_ptid=%d\n",
dfd4cc63 2405 ptid_get_pid (inferior_ptid)));
24e60978 2406}
1ef980b9 2407
581e13c1 2408/* Convert pid to printable format. */
3ee6f623 2409static char *
117de6a9 2410windows_pid_to_str (struct target_ops *ops, ptid_t ptid)
24e60978 2411{
3ee6f623 2412 static char buf[80];
3ee6f623 2413
2dc38344
PA
2414 if (ptid_get_tid (ptid) != 0)
2415 {
2416 snprintf (buf, sizeof (buf), "Thread %d.0x%lx",
2417 ptid_get_pid (ptid), ptid_get_tid (ptid));
2418 return buf;
2419 }
2420
2421 return normal_pid_to_str (ptid);
3ee6f623
CF
2422}
2423
9b409511 2424static enum target_xfer_status
dc05df57 2425windows_xfer_shared_libraries (struct target_ops *ops,
9b409511
YQ
2426 enum target_object object, const char *annex,
2427 gdb_byte *readbuf, const gdb_byte *writebuf,
2428 ULONGEST offset, ULONGEST len,
2429 ULONGEST *xfered_len)
3cb8e7f6 2430{
de1b3c3d
PA
2431 struct obstack obstack;
2432 const char *buf;
2433 LONGEST len_avail;
3cb8e7f6 2434 struct so_list *so;
3cb8e7f6 2435
de1b3c3d 2436 if (writebuf)
2ed4b548 2437 return TARGET_XFER_E_IO;
3cb8e7f6 2438
de1b3c3d
PA
2439 obstack_init (&obstack);
2440 obstack_grow_str (&obstack, "<library-list>\n");
2441 for (so = solib_start.next; so; so = so->next)
581e13c1
MS
2442 windows_xfer_shared_library (so->so_name, (CORE_ADDR)
2443 (uintptr_t) so->lm_info->load_addr,
f5656ead 2444 target_gdbarch (), &obstack);
de1b3c3d 2445 obstack_grow_str0 (&obstack, "</library-list>\n");
3cb8e7f6 2446
0ae1c716 2447 buf = (const char *) obstack_finish (&obstack);
de1b3c3d
PA
2448 len_avail = strlen (buf);
2449 if (offset >= len_avail)
49dc7f4b
PM
2450 len= 0;
2451 else
2452 {
2453 if (len > len_avail - offset)
2454 len = len_avail - offset;
2455 memcpy (readbuf, buf + offset, len);
2456 }
3cb8e7f6 2457
de1b3c3d 2458 obstack_free (&obstack, NULL);
9b409511 2459 *xfered_len = (ULONGEST) len;
0837c976 2460 return len != 0 ? TARGET_XFER_OK : TARGET_XFER_EOF;
3cb8e7f6
CF
2461}
2462
9b409511 2463static enum target_xfer_status
dc05df57 2464windows_xfer_partial (struct target_ops *ops, enum target_object object,
9b409511
YQ
2465 const char *annex, gdb_byte *readbuf,
2466 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
2467 ULONGEST *xfered_len)
3cb8e7f6 2468{
de1b3c3d 2469 switch (object)
3cb8e7f6 2470 {
de1b3c3d 2471 case TARGET_OBJECT_MEMORY:
9b409511 2472 return windows_xfer_memory (readbuf, writebuf, offset, len, xfered_len);
de1b3c3d
PA
2473
2474 case TARGET_OBJECT_LIBRARIES:
dc05df57 2475 return windows_xfer_shared_libraries (ops, object, annex, readbuf,
9b409511 2476 writebuf, offset, len, xfered_len);
3929abe9 2477
de1b3c3d 2478 default:
e75fdfca
TT
2479 return ops->beneath->to_xfer_partial (ops->beneath, object, annex,
2480 readbuf, writebuf, offset, len,
2481 xfered_len);
3929abe9 2482 }
02c5aecd
CF
2483}
2484
711e434b
PM
2485/* Provide thread local base, i.e. Thread Information Block address.
2486 Returns 1 if ptid is found and sets *ADDR to thread_local_base. */
2487
2488static int
bd7ae0f5
TT
2489windows_get_tib_address (struct target_ops *self,
2490 ptid_t ptid, CORE_ADDR *addr)
711e434b 2491{
876d1cd7 2492 windows_thread_info *th;
711e434b
PM
2493
2494 th = thread_rec (ptid_get_tid (ptid), 0);
2495 if (th == NULL)
2496 return 0;
2497
2498 if (addr != NULL)
2499 *addr = th->thread_local_base;
2500
2501 return 1;
2502}
2503
1e2f1c5c 2504static ptid_t
1e6b91a4 2505windows_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
1e2f1c5c
JB
2506{
2507 return ptid_build (ptid_get_pid (inferior_ptid), 0, lwp);
2508}
2509
51a9c8c5
PA
2510static struct target_ops *
2511windows_target (void)
3ee6f623 2512{
51a9c8c5
PA
2513 struct target_ops *t = inf_child_target ();
2514
51a9c8c5
PA
2515 t->to_close = windows_close;
2516 t->to_attach = windows_attach;
2517 t->to_attach_no_wait = 1;
2518 t->to_detach = windows_detach;
2519 t->to_resume = windows_resume;
2520 t->to_wait = windows_wait;
2521 t->to_fetch_registers = windows_fetch_inferior_registers;
2522 t->to_store_registers = windows_store_inferior_registers;
2523 t->to_xfer_partial = windows_xfer_partial;
2524 t->to_files_info = windows_files_info;
2525 t->to_kill = windows_kill_inferior;
2526 t->to_create_inferior = windows_create_inferior;
2527 t->to_mourn_inferior = windows_mourn_inferior;
2528 t->to_thread_alive = windows_thread_alive;
2529 t->to_pid_to_str = windows_pid_to_str;
bfedc46a 2530 t->to_interrupt = windows_interrupt;
51a9c8c5
PA
2531 t->to_pid_to_exec_file = windows_pid_to_exec_file;
2532 t->to_get_ada_task_ptid = windows_get_ada_task_ptid;
2533 t->to_get_tib_address = windows_get_tib_address;
2534
2535 return t;
c719b714 2536}
24e60978 2537
d603d4b3
JK
2538/* -Wmissing-prototypes */
2539extern initialize_file_ftype _initialize_windows_nat;
2540
24e60978 2541void
dc05df57 2542_initialize_windows_nat (void)
24e60978 2543{
51a9c8c5
PA
2544 struct target_ops *t;
2545
2546 t = windows_target ();
2547
df7e5265 2548 x86_use_watchpoints (t);
51a9c8c5 2549
df7e5265
GB
2550 x86_dr_low.set_control = cygwin_set_dr7;
2551 x86_dr_low.set_addr = cygwin_set_dr;
2552 x86_dr_low.get_addr = cygwin_get_dr;
2553 x86_dr_low.get_status = cygwin_get_dr6;
2554 x86_dr_low.get_control = cygwin_get_dr7;
51a9c8c5 2555
df7e5265
GB
2556 /* x86_dr_low.debug_register_length field is set by
2557 calling x86_set_debug_register_length function
51a9c8c5 2558 in processor windows specific native file. */
fa58ee11 2559
51a9c8c5 2560 add_target (t);
1ef980b9 2561
d0d0ab16
CV
2562#ifdef __CYGWIN__
2563 cygwin_internal (CW_SET_DOS_FILE_WARNING, 0);
2564#endif
2565
10325bc5 2566#ifdef __CYGWIN__
5bf193a2
AC
2567 add_setshow_boolean_cmd ("shell", class_support, &useshell, _("\
2568Set use of shell to start subprocess."), _("\
2569Show use of shell to start subprocess."), NULL,
2570 NULL,
2571 NULL, /* FIXME: i18n: */
2572 &setlist, &showlist);
2573
581e13c1
MS
2574 add_setshow_boolean_cmd ("cygwin-exceptions", class_support,
2575 &cygwin_exceptions, _("\
09280ddf
CF
2576Break when an exception is detected in the Cygwin DLL itself."), _("\
2577Show whether gdb breaks on exceptions in the Cygwin DLL itself."), NULL,
2578 NULL,
2579 NULL, /* FIXME: i18n: */
2580 &setlist, &showlist);
10325bc5 2581#endif
09280ddf 2582
5bf193a2
AC
2583 add_setshow_boolean_cmd ("new-console", class_support, &new_console, _("\
2584Set creation of new console when creating child process."), _("\
2585Show creation of new console when creating child process."), NULL,
2586 NULL,
2587 NULL, /* FIXME: i18n: */
2588 &setlist, &showlist);
2589
2590 add_setshow_boolean_cmd ("new-group", class_support, &new_group, _("\
2591Set creation of new group when creating child process."), _("\
2592Show creation of new group when creating child process."), NULL,
2593 NULL,
2594 NULL, /* FIXME: i18n: */
2595 &setlist, &showlist);
2596
2597 add_setshow_boolean_cmd ("debugexec", class_support, &debug_exec, _("\
2598Set whether to display execution in child process."), _("\
2599Show whether to display execution in child process."), NULL,
2600 NULL,
2601 NULL, /* FIXME: i18n: */
2602 &setlist, &showlist);
2603
2604 add_setshow_boolean_cmd ("debugevents", class_support, &debug_events, _("\
2605Set whether to display kernel events in child process."), _("\
2606Show whether to display kernel events in child process."), NULL,
2607 NULL,
2608 NULL, /* FIXME: i18n: */
2609 &setlist, &showlist);
2610
2611 add_setshow_boolean_cmd ("debugmemory", class_support, &debug_memory, _("\
2612Set whether to display memory accesses in child process."), _("\
2613Show whether to display memory accesses in child process."), NULL,
2614 NULL,
2615 NULL, /* FIXME: i18n: */
2616 &setlist, &showlist);
2617
2618 add_setshow_boolean_cmd ("debugexceptions", class_support,
2619 &debug_exceptions, _("\
2620Set whether to display kernel exceptions in child process."), _("\
2621Show whether to display kernel exceptions in child process."), NULL,
2622 NULL,
2623 NULL, /* FIXME: i18n: */
2624 &setlist, &showlist);
1ef980b9 2625
711e434b 2626 init_w32_command_list ();
c1748f97
PM
2627
2628 add_cmd ("selector", class_info, display_selectors,
1a966eab 2629 _("Display selectors infos."),
c1748f97 2630 &info_w32_cmdlist);
24e60978 2631}
3cee93ac 2632
fa4ba8da
PM
2633/* Hardware watchpoint support, adapted from go32-nat.c code. */
2634
2635/* Pass the address ADDR to the inferior in the I'th debug register.
2636 Here we just store the address in dr array, the registers will be
dc05df57 2637 actually set up when windows_continue is called. */
9bb9e8ad 2638static void
fa4ba8da
PM
2639cygwin_set_dr (int i, CORE_ADDR addr)
2640{
2641 if (i < 0 || i > 3)
2642 internal_error (__FILE__, __LINE__,
e2e0b3e5 2643 _("Invalid register %d in cygwin_set_dr.\n"), i);
41b4aadc 2644 dr[i] = addr;
fa4ba8da
PM
2645 debug_registers_changed = 1;
2646 debug_registers_used = 1;
2647}
2648
2649/* Pass the value VAL to the inferior in the DR7 debug control
2650 register. Here we just store the address in D_REGS, the watchpoint
dc05df57 2651 will be actually set up in windows_wait. */
9bb9e8ad
PM
2652static void
2653cygwin_set_dr7 (unsigned long val)
fa4ba8da 2654{
9bb9e8ad 2655 dr[7] = (CORE_ADDR) val;
fa4ba8da
PM
2656 debug_registers_changed = 1;
2657 debug_registers_used = 1;
2658}
2659
7b50312a
PA
2660/* Get the value of debug register I from the inferior. */
2661
2662static CORE_ADDR
2663cygwin_get_dr (int i)
2664{
2665 return dr[i];
2666}
2667
fa4ba8da
PM
2668/* Get the value of the DR6 debug status register from the inferior.
2669 Here we just return the value stored in dr[6]
2670 by the last call to thread_rec for current_event.dwThreadId id. */
9bb9e8ad 2671static unsigned long
fa4ba8da
PM
2672cygwin_get_dr6 (void)
2673{
9bb9e8ad 2674 return (unsigned long) dr[6];
fa4ba8da
PM
2675}
2676
7b50312a
PA
2677/* Get the value of the DR7 debug status register from the inferior.
2678 Here we just return the value stored in dr[7] by the last call to
2679 thread_rec for current_event.dwThreadId id. */
2680
2681static unsigned long
2682cygwin_get_dr7 (void)
2683{
2684 return (unsigned long) dr[7];
2685}
2686
2dc38344 2687/* Determine if the thread referenced by "ptid" is alive
3cee93ac 2688 by "polling" it. If WaitForSingleObject returns WAIT_OBJECT_0
581e13c1 2689 it means that the thread has died. Otherwise it is assumed to be alive. */
3cee93ac 2690static int
28439f5e 2691windows_thread_alive (struct target_ops *ops, ptid_t ptid)
3cee93ac 2692{
2dc38344
PA
2693 int tid;
2694
2695 gdb_assert (ptid_get_tid (ptid) != 0);
2696 tid = ptid_get_tid (ptid);
39f77062 2697
581e13c1
MS
2698 return WaitForSingleObject (thread_rec (tid, FALSE)->h, 0) == WAIT_OBJECT_0
2699 ? FALSE : TRUE;
3cee93ac
CF
2700}
2701
d603d4b3
JK
2702/* -Wmissing-prototypes */
2703extern initialize_file_ftype _initialize_check_for_gdb_ini;
2704
2a3d5645
CF
2705void
2706_initialize_check_for_gdb_ini (void)
2707{
2708 char *homedir;
2709 if (inhibit_gdbinit)
2710 return;
2711
2712 homedir = getenv ("HOME");
2713 if (homedir)
2714 {
2715 char *p;
2716 char *oldini = (char *) alloca (strlen (homedir) +
2717 sizeof ("/gdb.ini"));
2718 strcpy (oldini, homedir);
2719 p = strchr (oldini, '\0');
0ba1096a 2720 if (p > oldini && !IS_DIR_SEPARATOR (p[-1]))
2a3d5645
CF
2721 *p++ = '/';
2722 strcpy (p, "gdb.ini");
2723 if (access (oldini, 0) == 0)
2724 {
2725 int len = strlen (oldini);
0ae1c716 2726 char *newini = (char *) alloca (len + 1);
08850b56
PM
2727
2728 xsnprintf (newini, len + 1, "%.*s.gdbinit",
2729 (int) (len - (sizeof ("gdb.ini") - 1)), oldini);
8a3fe4f8 2730 warning (_("obsolete '%s' found. Rename to '%s'."), oldini, newini);
2a3d5645
CF
2731 }
2732 }
2733}
33605d39 2734
2b008701 2735/* Define dummy functions which always return error for the rare cases where
581e13c1 2736 these functions could not be found. */
2b008701
CF
2737static BOOL WINAPI
2738bad_DebugActiveProcessStop (DWORD w)
2739{
2740 return FALSE;
2741}
2742static BOOL WINAPI
2743bad_DebugBreakProcess (HANDLE w)
2744{
2745 return FALSE;
2746}
2747static BOOL WINAPI
2748bad_DebugSetProcessKillOnExit (BOOL w)
2749{
2750 return FALSE;
2751}
2752static BOOL WINAPI
2753bad_EnumProcessModules (HANDLE w, HMODULE *x, DWORD y, LPDWORD z)
2754{
2755 return FALSE;
2756}
b3c613f2
CF
2757
2758#ifdef __USEWIDE
2b008701 2759static DWORD WINAPI
b3c613f2 2760bad_GetModuleFileNameExW (HANDLE w, HMODULE x, LPWSTR y, DWORD z)
2b008701
CF
2761{
2762 return 0;
2763}
d0d0ab16
CV
2764#else
2765static DWORD WINAPI
b3c613f2 2766bad_GetModuleFileNameExA (HANDLE w, HMODULE x, LPSTR y, DWORD z)
d0d0ab16
CV
2767{
2768 return 0;
2769}
2770#endif
b3c613f2 2771
2b008701
CF
2772static BOOL WINAPI
2773bad_GetModuleInformation (HANDLE w, HMODULE x, LPMODULEINFO y, DWORD z)
2774{
2775 return FALSE;
2776}
2777
418c6cb3
CF
2778static BOOL WINAPI
2779bad_OpenProcessToken (HANDLE w, DWORD x, PHANDLE y)
2780{
2781 return FALSE;
2782}
2783
cd44747c
PM
2784static BOOL WINAPI
2785bad_GetCurrentConsoleFont (HANDLE w, BOOL bMaxWindow, CONSOLE_FONT_INFO *f)
2786{
2787 f->nFont = 0;
2788 return 1;
2789}
2790static COORD WINAPI
2791bad_GetConsoleFontSize (HANDLE w, DWORD nFont)
2792{
2793 COORD size;
2794 size.X = 8;
2795 size.Y = 12;
2796 return size;
2797}
2798
d603d4b3
JK
2799/* -Wmissing-prototypes */
2800extern initialize_file_ftype _initialize_loadable;
2801
2b008701 2802/* Load any functions which may not be available in ancient versions
581e13c1 2803 of Windows. */
d603d4b3 2804
33605d39 2805void
2b008701 2806_initialize_loadable (void)
33605d39 2807{
2b008701
CF
2808 HMODULE hm = NULL;
2809
43499ea3
PA
2810#define GPA(m, func) \
2811 func = (func ## _ftype *) GetProcAddress (m, #func)
2812
2b008701
CF
2813 hm = LoadLibrary ("kernel32.dll");
2814 if (hm)
33605d39 2815 {
43499ea3
PA
2816 GPA (hm, DebugActiveProcessStop);
2817 GPA (hm, DebugBreakProcess);
2818 GPA (hm, DebugSetProcessKillOnExit);
2819 GPA (hm, GetConsoleFontSize);
2820 GPA (hm, DebugActiveProcessStop);
2821 GPA (hm, GetCurrentConsoleFont);
2b008701 2822 }
33605d39 2823
2b008701 2824 /* Set variables to dummy versions of these processes if the function
581e13c1 2825 wasn't found in kernel32.dll. */
b3c613f2
CF
2826 if (!DebugBreakProcess)
2827 DebugBreakProcess = bad_DebugBreakProcess;
2828 if (!DebugActiveProcessStop || !DebugSetProcessKillOnExit)
2b008701 2829 {
b3c613f2
CF
2830 DebugActiveProcessStop = bad_DebugActiveProcessStop;
2831 DebugSetProcessKillOnExit = bad_DebugSetProcessKillOnExit;
2b008701 2832 }
cd44747c
PM
2833 if (!GetConsoleFontSize)
2834 GetConsoleFontSize = bad_GetConsoleFontSize;
2835 if (!GetCurrentConsoleFont)
2836 GetCurrentConsoleFont = bad_GetCurrentConsoleFont;
33605d39 2837
2b008701 2838 /* Load optional functions used for retrieving filename information
581e13c1 2839 associated with the currently debugged process or its dlls. */
2b008701
CF
2840 hm = LoadLibrary ("psapi.dll");
2841 if (hm)
2842 {
43499ea3
PA
2843 GPA (hm, EnumProcessModules);
2844 GPA (hm, GetModuleInformation);
2845 GPA (hm, GetModuleFileNameEx);
33605d39
CF
2846 }
2847
b3c613f2 2848 if (!EnumProcessModules || !GetModuleInformation || !GetModuleFileNameEx)
2b008701
CF
2849 {
2850 /* Set variables to dummy versions of these processes if the function
581e13c1 2851 wasn't found in psapi.dll. */
b3c613f2
CF
2852 EnumProcessModules = bad_EnumProcessModules;
2853 GetModuleInformation = bad_GetModuleInformation;
2854 GetModuleFileNameEx = bad_GetModuleFileNameEx;
581e13c1
MS
2855 /* This will probably fail on Windows 9x/Me. Let the user know
2856 that we're missing some functionality. */
2857 warning(_("\
2858cannot automatically find executable file or library to read symbols.\n\
2859Use \"file\" or \"dll\" command to load executable/libraries directly."));
418c6cb3
CF
2860 }
2861
2862 hm = LoadLibrary ("advapi32.dll");
2863 if (hm)
2864 {
43499ea3
PA
2865 GPA (hm, OpenProcessToken);
2866 GPA (hm, LookupPrivilegeValueA);
2867 GPA (hm, AdjustTokenPrivileges);
418c6cb3 2868 /* Only need to set one of these since if OpenProcessToken fails nothing
581e13c1
MS
2869 else is needed. */
2870 if (!OpenProcessToken || !LookupPrivilegeValueA
2871 || !AdjustTokenPrivileges)
b3c613f2 2872 OpenProcessToken = bad_OpenProcessToken;
2b008701 2873 }
43499ea3
PA
2874
2875#undef GPA
33605d39 2876}
This page took 2.19027 seconds and 4 git commands to generate.