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