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