Document i386 XML target features.
[deliverable/binutils-gdb.git] / gdb / windows-nat.c
CommitLineData
dc05df57 1/* Target-vector operations for controlling windows child processes, for GDB.
0a65a603 2
281b533b 3 Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4c38e0a4 4 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
0a65a603 5
e6433c28 6 Contributed by Cygnus Solutions, A Red Hat Company.
e88c49c3 7
24e60978
SC
8 This file is part of GDB.
9
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
a9762ec7 12 the Free Software Foundation; either version 3 of the License, or
24e60978
SC
13 (at your option) any later version.
14
15 This program is distributed in the hope that it will be useful,
a9762ec7 16 but WITHOUT ANY WARRANTY; without even the implied warranty of
24e60978
SC
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
a9762ec7 21 along with this program. If not, see <http://www.gnu.org/licenses/>. */
24e60978 22
dfe7f3ac 23/* Originally by Steve Chamberlain, sac@cygnus.com */
24e60978
SC
24
25#include "defs.h"
26#include "frame.h" /* required by inferior.h */
27#include "inferior.h"
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>
38#include <stdlib.h>
39#include <windows.h>
40#include <imagehlp.h>
2b008701 41#include <psapi.h>
10325bc5 42#ifdef __CYGWIN__
403d9909 43#include <sys/cygwin.h>
10325bc5 44#endif
a244bdca 45#include <signal.h>
cad9cd60 46
24e60978 47#include "buildsym.h"
1ef980b9
SC
48#include "symfile.h"
49#include "objfiles.h"
de1b3c3d 50#include "gdb_obstack.h"
24e60978 51#include "gdb_string.h"
fdfa3315 52#include "gdbthread.h"
24e60978 53#include "gdbcmd.h"
1750a5ef 54#include <sys/param.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"
9bb9e8ad 66#include "i386-nat.h"
de1b3c3d 67
418c6cb3 68#define AdjustTokenPrivileges dyn_AdjustTokenPrivileges
2b008701
CF
69#define DebugActiveProcessStop dyn_DebugActiveProcessStop
70#define DebugBreakProcess dyn_DebugBreakProcess
71#define DebugSetProcessKillOnExit dyn_DebugSetProcessKillOnExit
72#define EnumProcessModules dyn_EnumProcessModules
73#define GetModuleFileNameExA dyn_GetModuleFileNameExA
74#define GetModuleInformation dyn_GetModuleInformation
418c6cb3
CF
75#define LookupPrivilegeValueA dyn_LookupPrivilegeValueA
76#define OpenProcessToken dyn_OpenProcessToken
2b008701 77
418c6cb3
CF
78static BOOL WINAPI (*AdjustTokenPrivileges)(HANDLE, BOOL, PTOKEN_PRIVILEGES,
79 DWORD, PTOKEN_PRIVILEGES, PDWORD);
2b008701
CF
80static BOOL WINAPI (*DebugActiveProcessStop) (DWORD);
81static BOOL WINAPI (*DebugBreakProcess) (HANDLE);
82static BOOL WINAPI (*DebugSetProcessKillOnExit) (BOOL);
83static BOOL WINAPI (*EnumProcessModules) (HANDLE, HMODULE *, DWORD,
84 LPDWORD);
85static DWORD WINAPI (*GetModuleFileNameExA) (HANDLE, HMODULE, LPSTR,
86 DWORD);
87static BOOL WINAPI (*GetModuleInformation) (HANDLE, HMODULE, LPMODULEINFO,
88 DWORD);
418c6cb3
CF
89static BOOL WINAPI (*LookupPrivilegeValueA)(LPCSTR, LPCSTR, PLUID);
90static BOOL WINAPI (*OpenProcessToken)(HANDLE, DWORD, PHANDLE);
2b008701 91
dc05df57 92static struct target_ops windows_ops;
3ee6f623 93
10325bc5 94#ifdef __CYGWIN__
a244bdca 95/* The starting and ending address of the cygwin1.dll text segment. */
dc05df57
CF
96static CORE_ADDR cygwin_load_start;
97static CORE_ADDR cygwin_load_end;
10325bc5 98#endif
a244bdca
CF
99
100static int have_saved_context; /* True if we've saved context from a cygwin signal. */
101static CONTEXT saved_context; /* Containes the saved context from a cygwin signal. */
102
0714f9bf
SS
103/* If we're not using the old Cygwin header file set, define the
104 following which never should have been in the generic Win32 API
105 headers in the first place since they were our own invention... */
106#ifndef _GNU_H_WINDOWS_H
9d3789f7 107enum
8e860359
CF
108 {
109 FLAG_TRACE_BIT = 0x100,
110 CONTEXT_DEBUGGER = (CONTEXT_FULL | CONTEXT_FLOATING_POINT)
111 };
0714f9bf
SS
112#endif
113
5851ab76
JB
114#ifndef CONTEXT_EXTENDED_REGISTERS
115/* This macro is only defined on ia32. It only makes sense on this target,
116 so define it as zero if not already defined. */
117#define CONTEXT_EXTENDED_REGISTERS 0
118#endif
119
fa4ba8da
PM
120#define CONTEXT_DEBUGGER_DR CONTEXT_DEBUGGER | CONTEXT_DEBUG_REGISTERS \
121 | CONTEXT_EXTENDED_REGISTERS
97da3b20 122
41b4aadc 123static uintptr_t dr[8];
87a45c96
CF
124static int debug_registers_changed;
125static int debug_registers_used;
16d905e2
CF
126
127static int windows_initialization_done;
6537bb24 128#define DR6_CLEAR_VALUE 0xffff0ff0
97da3b20 129
3cee93ac
CF
130/* The string sent by cygwin when it processes a signal.
131 FIXME: This should be in a cygwin include file. */
3929abe9
CF
132#ifndef _CYGWIN_SIGNAL_STRING
133#define _CYGWIN_SIGNAL_STRING "cYgSiGw00f"
134#endif
3cee93ac 135
29fe111d 136#define CHECK(x) check (x, __FILE__,__LINE__)
dfe7f3ac 137#define DEBUG_EXEC(x) if (debug_exec) printf_unfiltered x
4e52d31c
PM
138#define DEBUG_EVENTS(x) if (debug_events) printf_unfiltered x
139#define DEBUG_MEM(x) if (debug_memory) printf_unfiltered x
140#define DEBUG_EXCEPT(x) if (debug_exceptions) printf_unfiltered x
24e60978 141
dc05df57 142static void windows_stop (ptid_t);
02529b48 143static int windows_thread_alive (struct target_ops *, ptid_t);
7d85a9c0 144static void windows_kill_inferior (struct target_ops *);
3cee93ac 145
9bb9e8ad
PM
146static void cygwin_set_dr (int i, CORE_ADDR addr);
147static void cygwin_set_dr7 (unsigned long val);
148static unsigned long cygwin_get_dr6 (void);
149
7393af7c
PM
150static enum target_signal last_sig = TARGET_SIGNAL_0;
151/* Set if a signal was received from the debugged process */
152
3cee93ac 153/* Thread information structure used to track information that is
6537bb24 154 not available in gdb's thread structure. */
3cee93ac 155typedef struct thread_info_struct
3a4b77d8
JM
156 {
157 struct thread_info_struct *next;
158 DWORD id;
159 HANDLE h;
160 char *name;
6537bb24 161 int suspended;
3ade5333 162 int reload_context;
3a4b77d8 163 CONTEXT context;
1e37c281 164 STACKFRAME sf;
8e860359
CF
165 }
166thread_info;
1e37c281 167
29fe111d 168static thread_info thread_head;
24e60978 169
24e60978
SC
170/* The process and thread handles for the above context. */
171
3cee93ac
CF
172static DEBUG_EVENT current_event; /* The current debug event from
173 WaitForDebugEvent */
174static HANDLE current_process_handle; /* Currently executing process */
175static thread_info *current_thread; /* Info on currently selected thread */
349b409f 176static DWORD main_thread_id; /* Thread ID of the main thread */
24e60978
SC
177
178/* Counts of things. */
179static int exception_count = 0;
180static int event_count = 0;
dfe7f3ac 181static int saw_create;
bf25528d 182static int open_process_used = 0;
24e60978
SC
183
184/* User options. */
185static int new_console = 0;
10325bc5 186#ifdef __CYGWIN__
09280ddf 187static int cygwin_exceptions = 0;
10325bc5 188#endif
1e37c281 189static int new_group = 1;
dfe7f3ac
CF
190static int debug_exec = 0; /* show execution */
191static int debug_events = 0; /* show events from kernel */
192static int debug_memory = 0; /* show target memory accesses */
1ef980b9 193static int debug_exceptions = 0; /* show target exceptions */
dfe7f3ac
CF
194static int useshell = 0; /* use shell for subprocesses */
195
7e63b4e4 196/* This vector maps GDB's idea of a register's number into an offset
dc05df57 197 in the windows exception context vector.
24e60978 198
3cee93ac 199 It also contains the bit mask needed to load the register in question.
24e60978 200
7e63b4e4
JB
201 The contents of this table can only be computed by the units
202 that provide CPU-specific support for Windows native debugging.
203 These units should set the table by calling
dc05df57 204 windows_set_context_register_offsets.
7e63b4e4 205
24e60978
SC
206 One day we could read a reg, we could inspect the context we
207 already have loaded, if it doesn't have the bit set that we need,
208 we read that set of registers in using GetThreadContext. If the
209 context already contains what we need, we just unpack it. Then to
210 write a register, first we have to ensure that the context contains
211 the other regs of the group, and then we copy the info in and set
212 out bit. */
213
7e63b4e4 214static const int *mappings;
d3a09475 215
24e60978
SC
216/* This vector maps the target's idea of an exception (extracted
217 from the DEBUG_EVENT structure) to GDB's idea. */
218
219struct xlate_exception
220 {
221 int them;
222 enum target_signal us;
223 };
224
24e60978
SC
225static const struct xlate_exception
226 xlate[] =
227{
228 {EXCEPTION_ACCESS_VIOLATION, TARGET_SIGNAL_SEGV},
9cbf6c0e 229 {STATUS_STACK_OVERFLOW, TARGET_SIGNAL_SEGV},
24e60978
SC
230 {EXCEPTION_BREAKPOINT, TARGET_SIGNAL_TRAP},
231 {DBG_CONTROL_C, TARGET_SIGNAL_INT},
232 {EXCEPTION_SINGLE_STEP, TARGET_SIGNAL_TRAP},
7393af7c 233 {STATUS_FLOAT_DIVIDE_BY_ZERO, TARGET_SIGNAL_FPE},
24e60978
SC
234 {-1, -1}};
235
7e63b4e4
JB
236/* Set the MAPPINGS static global to OFFSETS.
237 See the description of MAPPINGS for more details. */
238
239void
dc05df57 240windows_set_context_register_offsets (const int *offsets)
7e63b4e4
JB
241{
242 mappings = offsets;
243}
244
fa4ba8da
PM
245static void
246check (BOOL ok, const char *file, int line)
247{
248 if (!ok)
dfe7f3ac 249 printf_filtered ("error return %s:%d was %lu\n", file, line,
fa4ba8da
PM
250 GetLastError ());
251}
252
6537bb24
PA
253/* Find a thread record given a thread id. If GET_CONTEXT is not 0,
254 then also retrieve the context for this thread. If GET_CONTEXT is
255 negative, then don't suspend the thread. */
3cee93ac
CF
256static thread_info *
257thread_rec (DWORD id, int get_context)
24e60978 258{
3cee93ac
CF
259 thread_info *th;
260
3a4b77d8 261 for (th = &thread_head; (th = th->next) != NULL;)
3cee93ac
CF
262 if (th->id == id)
263 {
6537bb24 264 if (!th->suspended && get_context)
3cee93ac 265 {
8a892701 266 if (get_context > 0 && id != current_event.dwThreadId)
6537bb24
PA
267 {
268 if (SuspendThread (th->h) == (DWORD) -1)
269 {
270 DWORD err = GetLastError ();
271 warning (_("SuspendThread failed. (winerr %d)"),
272 (int) err);
273 return NULL;
274 }
275 th->suspended = 1;
276 }
3cee93ac 277 else if (get_context < 0)
6537bb24 278 th->suspended = -1;
3ade5333 279 th->reload_context = 1;
3cee93ac
CF
280 }
281 return th;
282 }
283
284 return NULL;
285}
286
2dc38344 287/* Add a thread to the thread list. */
3cee93ac 288static thread_info *
dc05df57 289windows_add_thread (ptid_t ptid, HANDLE h)
3cee93ac
CF
290{
291 thread_info *th;
2dc38344
PA
292 DWORD id;
293
294 gdb_assert (ptid_get_tid (ptid) != 0);
295
296 id = ptid_get_tid (ptid);
3cee93ac
CF
297
298 if ((th = thread_rec (id, FALSE)))
299 return th;
300
3929abe9 301 th = XZALLOC (thread_info);
3cee93ac
CF
302 th->id = id;
303 th->h = h;
304 th->next = thread_head.next;
305 thread_head.next = th;
2dc38344
PA
306 add_thread (ptid);
307 /* Set the debug registers for the new thread if they are used. */
fa4ba8da
PM
308 if (debug_registers_used)
309 {
310 /* Only change the value of the debug registers. */
311 th->context.ContextFlags = CONTEXT_DEBUG_REGISTERS;
312 CHECK (GetThreadContext (th->h, &th->context));
313 th->context.Dr0 = dr[0];
314 th->context.Dr1 = dr[1];
315 th->context.Dr2 = dr[2];
316 th->context.Dr3 = dr[3];
6537bb24 317 th->context.Dr6 = DR6_CLEAR_VALUE;
fa4ba8da
PM
318 th->context.Dr7 = dr[7];
319 CHECK (SetThreadContext (th->h, &th->context));
320 th->context.ContextFlags = 0;
321 }
3cee93ac 322 return th;
24e60978
SC
323}
324
3cee93ac
CF
325/* Clear out any old thread list and reintialize it to a
326 pristine state. */
24e60978 327static void
dc05df57 328windows_init_thread_list (void)
24e60978 329{
3cee93ac
CF
330 thread_info *th = &thread_head;
331
dc05df57 332 DEBUG_EVENTS (("gdb: windows_init_thread_list\n"));
3cee93ac
CF
333 init_thread_list ();
334 while (th->next != NULL)
24e60978 335 {
3cee93ac
CF
336 thread_info *here = th->next;
337 th->next = here->next;
b8c9b27d 338 xfree (here);
24e60978 339 }
059198c1 340 thread_head.next = NULL;
3cee93ac
CF
341}
342
343/* Delete a thread from the list of threads */
344static void
dc05df57 345windows_delete_thread (ptid_t ptid)
3cee93ac
CF
346{
347 thread_info *th;
2dc38344
PA
348 DWORD id;
349
350 gdb_assert (ptid_get_tid (ptid) != 0);
351
352 id = ptid_get_tid (ptid);
3cee93ac
CF
353
354 if (info_verbose)
2dc38344
PA
355 printf_unfiltered ("[Deleting %s]\n", target_pid_to_str (ptid));
356 delete_thread (ptid);
3cee93ac
CF
357
358 for (th = &thread_head;
359 th->next != NULL && th->next->id != id;
360 th = th->next)
361 continue;
362
363 if (th->next != NULL)
24e60978 364 {
3cee93ac
CF
365 thread_info *here = th->next;
366 th->next = here->next;
b8c9b27d 367 xfree (here);
24e60978
SC
368 }
369}
370
3cee93ac 371static void
dc05df57 372do_windows_fetch_inferior_registers (struct regcache *regcache, int r)
24e60978 373{
1e37c281 374 char *context_offset = ((char *) &current_thread->context) + mappings[r];
20a6ec49
MD
375 struct gdbarch *gdbarch = get_regcache_arch (regcache);
376 struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
1e37c281 377 long l;
6c7de422 378
3ade5333 379 if (!current_thread)
d6dc8049
CF
380 return; /* Windows sometimes uses a non-existent thread id in its
381 events */
3ade5333
CF
382
383 if (current_thread->reload_context)
384 {
cb832706 385#ifdef __COPY_CONTEXT_SIZE
a244bdca
CF
386 if (have_saved_context)
387 {
388 /* Lie about where the program actually is stopped since cygwin has informed us that
389 we should consider the signal to have occurred at another location which is stored
390 in "saved_context. */
391 memcpy (&current_thread->context, &saved_context, __COPY_CONTEXT_SIZE);
392 have_saved_context = 0;
393 }
394 else
cb832706 395#endif
a244bdca
CF
396 {
397 thread_info *th = current_thread;
398 th->context.ContextFlags = CONTEXT_DEBUGGER_DR;
399 GetThreadContext (th->h, &th->context);
2b008701 400 /* Copy dr values from that thread.
88616312
PM
401 But only if there were not modified since last stop. PR gdb/2388 */
402 if (!debug_registers_changed)
403 {
404 dr[0] = th->context.Dr0;
405 dr[1] = th->context.Dr1;
406 dr[2] = th->context.Dr2;
407 dr[3] = th->context.Dr3;
408 dr[6] = th->context.Dr6;
409 dr[7] = th->context.Dr7;
410 }
a244bdca 411 }
3ade5333
CF
412 current_thread->reload_context = 0;
413 }
414
20a6ec49 415 if (r == I387_FISEG_REGNUM (tdep))
1e37c281 416 {
8e860359 417 l = *((long *) context_offset) & 0xffff;
56be3814 418 regcache_raw_supply (regcache, r, (char *) &l);
1e37c281 419 }
20a6ec49 420 else if (r == I387_FOP_REGNUM (tdep))
1e37c281 421 {
8e860359 422 l = (*((long *) context_offset) >> 16) & ((1 << 11) - 1);
56be3814 423 regcache_raw_supply (regcache, r, (char *) &l);
1e37c281
JM
424 }
425 else if (r >= 0)
56be3814 426 regcache_raw_supply (regcache, r, context_offset);
3cee93ac 427 else
24e60978 428 {
20a6ec49 429 for (r = 0; r < gdbarch_num_regs (gdbarch); r++)
dc05df57 430 do_windows_fetch_inferior_registers (regcache, r);
24e60978 431 }
3cee93ac
CF
432}
433
434static void
28439f5e
PA
435windows_fetch_inferior_registers (struct target_ops *ops,
436 struct regcache *regcache, int r)
3cee93ac 437{
2dc38344 438 current_thread = thread_rec (ptid_get_tid (inferior_ptid), TRUE);
d6dc8049
CF
439 /* Check if current_thread exists. Windows sometimes uses a non-existent
440 thread id in its events */
3ade5333 441 if (current_thread)
dc05df57 442 do_windows_fetch_inferior_registers (regcache, r);
3cee93ac
CF
443}
444
445static void
dc05df57 446do_windows_store_inferior_registers (const struct regcache *regcache, int r)
3cee93ac 447{
3ade5333 448 if (!current_thread)
d6dc8049 449 /* Windows sometimes uses a non-existent thread id in its events */;
3ade5333 450 else if (r >= 0)
56be3814 451 regcache_raw_collect (regcache, r,
822c9732 452 ((char *) &current_thread->context) + mappings[r]);
24e60978
SC
453 else
454 {
40a6adc1 455 for (r = 0; r < gdbarch_num_regs (get_regcache_arch (regcache)); r++)
dc05df57 456 do_windows_store_inferior_registers (regcache, r);
24e60978
SC
457 }
458}
459
3cee93ac
CF
460/* Store a new register value into the current thread context */
461static void
28439f5e
PA
462windows_store_inferior_registers (struct target_ops *ops,
463 struct regcache *regcache, int r)
3cee93ac 464{
2dc38344 465 current_thread = thread_rec (ptid_get_tid (inferior_ptid), TRUE);
d6dc8049
CF
466 /* Check if current_thread exists. Windows sometimes uses a non-existent
467 thread id in its events */
3ade5333 468 if (current_thread)
dc05df57 469 do_windows_store_inferior_registers (regcache, r);
3cee93ac 470}
24e60978 471
33605d39
CF
472/* Get the name of a given module at at given base address. If base_address
473 is zero return the first loaded module (which is always the name of the
474 executable). */
3ee6f623 475static int
d3653bf6 476get_module_name (LPVOID base_address, char *dll_name_ret)
1e37c281
JM
477{
478 DWORD len;
479 MODULEINFO mi;
480 int i;
8e860359 481 HMODULE dh_buf[1];
33605d39 482 HMODULE *DllHandle = dh_buf; /* Set to temporary storage for initial query */
1e37c281 483 DWORD cbNeeded;
33605d39
CF
484#ifdef __CYGWIN__
485 char pathbuf[PATH_MAX + 1]; /* Temporary storage prior to converting to
486 posix form */
487#else
488 char *pathbuf = dll_name_ret; /* Just copy directly to passed-in arg */
489#endif
1e37c281 490
1e37c281 491 cbNeeded = 0;
33605d39 492 /* Find size of buffer needed to handle list of modules loaded in inferior */
2b008701
CF
493 if (!EnumProcessModules (current_process_handle, DllHandle,
494 sizeof (HMODULE), &cbNeeded) || !cbNeeded)
1e37c281
JM
495 goto failed;
496
33605d39 497 /* Allocate correct amount of space for module list */
8e860359 498 DllHandle = (HMODULE *) alloca (cbNeeded);
1e37c281
JM
499 if (!DllHandle)
500 goto failed;
501
33605d39 502 /* Get the list of modules */
2b008701 503 if (!EnumProcessModules (current_process_handle, DllHandle, cbNeeded,
33605d39 504 &cbNeeded))
1e37c281
JM
505 goto failed;
506
29fe111d 507 for (i = 0; i < (int) (cbNeeded / sizeof (HMODULE)); i++)
1e37c281 508 {
33605d39 509 /* Get information on this module */
2b008701
CF
510 if (!GetModuleInformation (current_process_handle, DllHandle[i],
511 &mi, sizeof (mi)))
8a3fe4f8 512 error (_("Can't get module info"));
1e37c281 513
d3653bf6 514 if (!base_address || mi.lpBaseOfDll == base_address)
33605d39
CF
515 {
516 /* Try to find the name of the given module */
2b008701
CF
517 len = GetModuleFileNameExA (current_process_handle,
518 DllHandle[i], pathbuf, MAX_PATH);
33605d39
CF
519 if (len == 0)
520 error (_("Error getting dll name: %u."), (unsigned) GetLastError ());
521#ifdef __CYGWIN__
522 /* Cygwin prefers that the path be in /x/y/z format */
523 cygwin_conv_to_full_posix_path (pathbuf, dll_name_ret);
524#endif
525 return 1; /* success */
526 }
1e37c281
JM
527 }
528
529failed:
530 dll_name_ret[0] = '\0';
33605d39 531 return 0; /* failure */
1e37c281
JM
532}
533
450005e7
CF
534/* Encapsulate the information required in a call to
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
02e423b9 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
CF
555/* Call symbol_file_add with stderr redirected. We don't care if there
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
450005e7 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
450005e7 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;
3f8ad85b
CF
614 char buf[MAX_PATH + 1];
615 char cwd[MAX_PATH + 1];
616 char *p;
617 WIN32_FIND_DATA w32_fd;
618 HANDLE h = FindFirstFile(name, &w32_fd);
5633f842 619 MEMORY_BASIC_INFORMATION m;
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
CF
636 }
637
3ee6f623
CF
638 if (strcasecmp (buf, "ntdll.dll") == 0)
639 {
640 GetSystemDirectory (buf, sizeof (buf));
641 strcat (buf, "\\ntdll.dll");
642 }
3929abe9 643 so = XZALLOC (struct so_list);
3ee6f623
CF
644 so->lm_info = (struct lm_info *) xmalloc (sizeof (struct lm_info));
645 so->lm_info->load_addr = load_addr;
de1b3c3d 646 strcpy (so->so_original_name, name);
10325bc5
PA
647#ifndef __CYGWIN__
648 strcpy (so->so_name, buf);
649#else
650 cygwin_conv_to_posix_path (buf, so->so_name);
de1b3c3d
PA
651 /* Record cygwin1.dll .text start/end. */
652 p = strchr (so->so_name, '\0') - (sizeof ("/cygwin1.dll") - 1);
653 if (p >= so->so_name && strcasecmp (p, "/cygwin1.dll") == 0)
654 {
655 bfd *abfd;
656 asection *text = NULL;
657 CORE_ADDR text_vma;
8e860359 658
610dd7f9 659 abfd = bfd_openr (so->so_name, "pei-i386");
a244bdca 660
de1b3c3d
PA
661 if (!abfd)
662 return so;
663
664 if (bfd_check_format (abfd, bfd_object))
665 text = bfd_get_section_by_name (abfd, ".text");
666
667 if (!text)
668 {
669 bfd_close (abfd);
670 return so;
671 }
672
673 /* The symbols in a dll are offset by 0x1000, which is the the
674 offset from 0 of the first byte in an image - because of the
675 file header and the section alignment. */
dc05df57
CF
676 cygwin_load_start = (CORE_ADDR) (uintptr_t) ((char *) load_addr + 0x1000);
677 cygwin_load_end = cygwin_load_start + bfd_section_size (abfd, text);
de1b3c3d
PA
678
679 bfd_close (abfd);
680 }
10325bc5 681#endif
de1b3c3d
PA
682
683 return so;
8e860359
CF
684}
685
3ee6f623 686static char *
dfe7f3ac
CF
687get_image_name (HANDLE h, void *address, int unicode)
688{
689 static char buf[(2 * MAX_PATH) + 1];
690 DWORD size = unicode ? sizeof (WCHAR) : sizeof (char);
691 char *address_ptr;
692 int len = 0;
693 char b[2];
5732a500 694 SIZE_T done;
dfe7f3ac
CF
695
696 /* Attempt to read the name of the dll that was detected.
697 This is documented to work only when actively debugging
698 a program. It will not work for attached processes. */
699 if (address == NULL)
700 return NULL;
701
dfe7f3ac
CF
702 /* See if we could read the address of a string, and that the
703 address isn't null. */
9f476a01 704 if (!ReadProcessMemory (h, address, &address_ptr, sizeof (address_ptr), &done)
6f17862b 705 || done != sizeof (address_ptr) || !address_ptr)
dfe7f3ac
CF
706 return NULL;
707
708 /* Find the length of the string */
6f17862b
CF
709 while (ReadProcessMemory (h, address_ptr + len++ * size, &b, size, &done)
710 && (b[0] != 0 || b[size - 1] != 0) && done == size)
711 continue;
dfe7f3ac
CF
712
713 if (!unicode)
714 ReadProcessMemory (h, address_ptr, buf, len, &done);
715 else
716 {
717 WCHAR *unicode_address = (WCHAR *) alloca (len * sizeof (WCHAR));
718 ReadProcessMemory (h, address_ptr, unicode_address, len * sizeof (WCHAR),
719 &done);
720
721 WideCharToMultiByte (CP_ACP, 0, unicode_address, len, buf, len, 0, 0);
722 }
723
724 return buf;
725}
726
24e60978
SC
727/* Wait for child to do something. Return pid of child, or -1 in case
728 of error; store status through argument pointer OURSTATUS. */
1750a5ef 729static int
0a65a603 730handle_load_dll (void *dummy)
24e60978 731{
3a4b77d8 732 LOAD_DLL_DEBUG_INFO *event = &current_event.u.LoadDll;
3cee93ac 733 char dll_buf[MAX_PATH + 1];
450005e7 734 char *dll_name = NULL;
3cee93ac 735
3a4b77d8 736 dll_buf[0] = dll_buf[sizeof (dll_buf) - 1] = '\0';
3cee93ac 737
d3653bf6 738 if (!get_module_name (event->lpBaseOfDll, dll_buf))
8e860359 739 dll_buf[0] = dll_buf[sizeof (dll_buf) - 1] = '\0';
3cee93ac 740
1e37c281 741 dll_name = dll_buf;
24e60978 742
dfe7f3ac 743 if (*dll_name == '\0')
de1b3c3d
PA
744 dll_name = get_image_name (current_process_handle,
745 event->lpImageName, event->fUnicode);
3cee93ac
CF
746 if (!dll_name)
747 return 1;
748
dc05df57 749 solib_end->next = windows_make_so (dll_name, event->lpBaseOfDll);
de1b3c3d 750 solib_end = solib_end->next;
450005e7 751
a74ce742
PM
752 DEBUG_EVENTS (("gdb: Loading dll \"%s\" at %s.\n", solib_end->so_name,
753 host_address_to_string (solib_end->lm_info->load_addr)));
7488902c 754
450005e7
CF
755 return 1;
756}
757
3ee6f623 758static void
dc05df57 759windows_free_so (struct so_list *so)
3ee6f623 760{
3ee6f623
CF
761 if (so->lm_info)
762 xfree (so->lm_info);
de1b3c3d 763 xfree (so);
3cb8e7f6
CF
764}
765
d3ff4a77 766static int
0a65a603 767handle_unload_dll (void *dummy)
d3ff4a77 768{
d3653bf6 769 LPVOID lpBaseOfDll = current_event.u.UnloadDll.lpBaseOfDll;
3ee6f623 770 struct so_list *so;
d3ff4a77
CF
771
772 for (so = &solib_start; so->next != NULL; so = so->next)
3ee6f623 773 if (so->next->lm_info->load_addr == lpBaseOfDll)
d3ff4a77 774 {
3ee6f623 775 struct so_list *sodel = so->next;
d3ff4a77
CF
776 so->next = sodel->next;
777 if (!so->next)
778 solib_end = so;
7488902c
PM
779 DEBUG_EVENTS (("gdb: Unloading dll \"%s\".\n", sodel->so_name));
780
dc05df57 781 windows_free_so (sodel);
3929abe9 782 solib_add (NULL, 0, NULL, auto_solib_add);
d3ff4a77
CF
783 return 1;
784 }
3929abe9 785
a74ce742
PM
786 error (_("Error: dll starting at %s not found."),
787 host_address_to_string (lpBaseOfDll));
d3ff4a77
CF
788
789 return 0;
790}
791
450005e7 792/* Clear list of loaded DLLs. */
3ee6f623 793static void
dc05df57 794windows_clear_solib (void)
450005e7 795{
450005e7
CF
796 solib_start.next = NULL;
797 solib_end = &solib_start;
450005e7 798}
295732ea 799
450005e7
CF
800/* Load DLL symbol info. */
801void
7470a420 802dll_symbol_command (char *args, int from_tty)
450005e7 803{
8e860359 804 int n;
450005e7 805 dont_repeat ();
8e860359 806
450005e7 807 if (args == NULL)
8a3fe4f8 808 error (_("dll-symbols requires a file name"));
450005e7 809
8e860359
CF
810 n = strlen (args);
811 if (n > 4 && strcasecmp (args + n - 4, ".dll") != 0)
812 {
813 char *newargs = (char *) alloca (n + 4 + 1);
814 strcpy (newargs, args);
815 strcat (newargs, ".dll");
816 args = newargs;
817 }
818
7470a420 819 safe_symbol_file_add (args, from_tty, NULL, 0, OBJF_SHARED | OBJF_USERLOADED);
8e860359 820}
450005e7 821
3cee93ac
CF
822/* Handle DEBUG_STRING output from child process.
823 Cygwin prepends its messages with a "cygwin:". Interpret this as
824 a Cygwin signal. Otherwise just print the string as a warning. */
825static int
826handle_output_debug_string (struct target_waitstatus *ourstatus)
827{
a244bdca
CF
828 char *s = NULL;
829 int retval = 0;
3cee93ac
CF
830
831 if (!target_read_string
2c647436
PM
832 ((CORE_ADDR) (uintptr_t) current_event.u.DebugString.lpDebugStringData,
833 &s, 1024, 0)
3cee93ac 834 || !s || !*s)
a244bdca
CF
835 /* nothing to do */;
836 else if (strncmp (s, _CYGWIN_SIGNAL_STRING, sizeof (_CYGWIN_SIGNAL_STRING) - 1) != 0)
3cee93ac 837 {
10325bc5 838#ifdef __CYGWIN__
d3a09475 839 if (strncmp (s, "cYg", 3) != 0)
10325bc5 840#endif
8a3fe4f8 841 warning (("%s"), s);
3cee93ac 842 }
cb832706 843#ifdef __COPY_CONTEXT_SIZE
d3a09475 844 else
3cee93ac 845 {
a244bdca
CF
846 /* Got a cygwin signal marker. A cygwin signal is followed by the signal number
847 itself and then optionally followed by the thread id and address to saved context
848 within the DLL. If these are supplied, then the given thread is assumed to have
849 issued the signal and the context from the thread is assumed to be stored at the
850 given address in the inferior. Tell gdb to treat this like a real signal. */
3cee93ac 851 char *p;
3929abe9 852 int sig = strtol (s + sizeof (_CYGWIN_SIGNAL_STRING) - 1, &p, 0);
a244bdca 853 int gotasig = target_signal_from_host (sig);
0714f9bf
SS
854 ourstatus->value.sig = gotasig;
855 if (gotasig)
a244bdca
CF
856 {
857 LPCVOID x;
858 DWORD n;
859 ourstatus->kind = TARGET_WAITKIND_STOPPED;
860 retval = strtoul (p, &p, 0);
861 if (!retval)
862 retval = main_thread_id;
863 else if ((x = (LPCVOID) strtoul (p, &p, 0))
864 && ReadProcessMemory (current_process_handle, x,
865 &saved_context, __COPY_CONTEXT_SIZE, &n)
866 && n == __COPY_CONTEXT_SIZE)
867 have_saved_context = 1;
868 current_event.dwThreadId = retval;
869 }
3cee93ac 870 }
cb832706 871#endif
3cee93ac 872
a244bdca
CF
873 if (s)
874 xfree (s);
875 return retval;
3cee93ac 876}
24e60978 877
c1748f97
PM
878static int
879display_selector (HANDLE thread, DWORD sel)
880{
881 LDT_ENTRY info;
882 if (GetThreadSelectorEntry (thread, sel, &info))
883 {
884 int base, limit;
885 printf_filtered ("0x%03lx: ", sel);
886 if (!info.HighWord.Bits.Pres)
baa93fa6
CF
887 {
888 puts_filtered ("Segment not present\n");
889 return 0;
890 }
c1748f97
PM
891 base = (info.HighWord.Bits.BaseHi << 24) +
892 (info.HighWord.Bits.BaseMid << 16)
893 + info.BaseLow;
894 limit = (info.HighWord.Bits.LimitHi << 16) + info.LimitLow;
895 if (info.HighWord.Bits.Granularity)
caad7706 896 limit = (limit << 12) | 0xfff;
c1748f97
PM
897 printf_filtered ("base=0x%08x limit=0x%08x", base, limit);
898 if (info.HighWord.Bits.Default_Big)
baa93fa6 899 puts_filtered(" 32-bit ");
c1748f97 900 else
baa93fa6 901 puts_filtered(" 16-bit ");
c1748f97
PM
902 switch ((info.HighWord.Bits.Type & 0xf) >> 1)
903 {
904 case 0:
baa93fa6
CF
905 puts_filtered ("Data (Read-Only, Exp-up");
906 break;
c1748f97 907 case 1:
baa93fa6
CF
908 puts_filtered ("Data (Read/Write, Exp-up");
909 break;
c1748f97 910 case 2:
baa93fa6
CF
911 puts_filtered ("Unused segment (");
912 break;
c1748f97 913 case 3:
baa93fa6
CF
914 puts_filtered ("Data (Read/Write, Exp-down");
915 break;
c1748f97 916 case 4:
baa93fa6
CF
917 puts_filtered ("Code (Exec-Only, N.Conf");
918 break;
c1748f97 919 case 5:
baa93fa6 920 puts_filtered ("Code (Exec/Read, N.Conf");
c1748f97
PM
921 break;
922 case 6:
baa93fa6 923 puts_filtered ("Code (Exec-Only, Conf");
c1748f97
PM
924 break;
925 case 7:
baa93fa6 926 puts_filtered ("Code (Exec/Read, Conf");
c1748f97
PM
927 break;
928 default:
929 printf_filtered ("Unknown type 0x%x",info.HighWord.Bits.Type);
930 }
931 if ((info.HighWord.Bits.Type & 0x1) == 0)
baa93fa6 932 puts_filtered(", N.Acc");
c1748f97
PM
933 puts_filtered (")\n");
934 if ((info.HighWord.Bits.Type & 0x10) == 0)
935 puts_filtered("System selector ");
936 printf_filtered ("Priviledge level = %d. ", info.HighWord.Bits.Dpl);
937 if (info.HighWord.Bits.Granularity)
baa93fa6 938 puts_filtered ("Page granular.\n");
c1748f97
PM
939 else
940 puts_filtered ("Byte granular.\n");
941 return 1;
942 }
943 else
944 {
945 printf_filtered ("Invalid selector 0x%lx.\n",sel);
946 return 0;
947 }
948}
949
950static void
951display_selectors (char * args, int from_tty)
952{
953 if (!current_thread)
954 {
955 puts_filtered ("Impossible to display selectors now.\n");
956 return;
957 }
958 if (!args)
959 {
960
961 puts_filtered ("Selector $cs\n");
962 display_selector (current_thread->h,
baa93fa6 963 current_thread->context.SegCs);
c1748f97
PM
964 puts_filtered ("Selector $ds\n");
965 display_selector (current_thread->h,
baa93fa6 966 current_thread->context.SegDs);
c1748f97
PM
967 puts_filtered ("Selector $es\n");
968 display_selector (current_thread->h,
baa93fa6 969 current_thread->context.SegEs);
c1748f97
PM
970 puts_filtered ("Selector $ss\n");
971 display_selector (current_thread->h,
baa93fa6 972 current_thread->context.SegSs);
c1748f97
PM
973 puts_filtered ("Selector $fs\n");
974 display_selector (current_thread->h,
975 current_thread->context.SegFs);
976 puts_filtered ("Selector $gs\n");
977 display_selector (current_thread->h,
baa93fa6 978 current_thread->context.SegGs);
c1748f97
PM
979 }
980 else
981 {
982 int sel;
983 sel = parse_and_eval_long (args);
984 printf_filtered ("Selector \"%s\"\n",args);
985 display_selector (current_thread->h, sel);
986 }
987}
988
989static struct cmd_list_element *info_w32_cmdlist = NULL;
990
991static void
992info_w32_command (char *args, int from_tty)
993{
994 help_list (info_w32_cmdlist, "info w32 ", class_info, gdb_stdout);
995}
996
997
7393af7c 998#define DEBUG_EXCEPTION_SIMPLE(x) if (debug_exceptions) \
a74ce742
PM
999 printf_unfiltered ("gdb: Target exception %s at %s\n", x, \
1000 host_address_to_string (\
1001 current_event.u.Exception.ExceptionRecord.ExceptionAddress))
7393af7c 1002
36339ecd 1003static int
450005e7 1004handle_exception (struct target_waitstatus *ourstatus)
24e60978 1005{
3cee93ac 1006 thread_info *th;
29fe111d 1007 DWORD code = current_event.u.Exception.ExceptionRecord.ExceptionCode;
3cee93ac 1008
29fe111d 1009 ourstatus->kind = TARGET_WAITKIND_STOPPED;
8a892701 1010
3cee93ac
CF
1011 /* Record the context of the current thread */
1012 th = thread_rec (current_event.dwThreadId, -1);
24e60978 1013
29fe111d 1014 switch (code)
24e60978 1015 {
1ef980b9 1016 case EXCEPTION_ACCESS_VIOLATION:
7393af7c
PM
1017 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ACCESS_VIOLATION");
1018 ourstatus->value.sig = TARGET_SIGNAL_SEGV;
10325bc5 1019#ifdef __CYGWIN__
8da8e0b3 1020 {
a244bdca
CF
1021 /* See if the access violation happened within the cygwin DLL itself. Cygwin uses
1022 a kind of exception handling to deal with passed-in invalid addresses. gdb
1023 should not treat these as real SEGVs since they will be silently handled by
1024 cygwin. A real SEGV will (theoretically) be caught by cygwin later in the process
1025 and will be sent as a cygwin-specific-signal. So, ignore SEGVs if they show up
1026 within the text segment of the DLL itself. */
8da8e0b3 1027 char *fn;
dc05df57 1028 CORE_ADDR addr = (CORE_ADDR) (uintptr_t) current_event.u.Exception.ExceptionRecord.ExceptionAddress;
09280ddf 1029 if ((!cygwin_exceptions && (addr >= cygwin_load_start && addr < cygwin_load_end))
a244bdca
CF
1030 || (find_pc_partial_function (addr, &fn, NULL, NULL)
1031 && strncmp (fn, "KERNEL32!IsBad", strlen ("KERNEL32!IsBad")) == 0))
8da8e0b3
CF
1032 return 0;
1033 }
10325bc5 1034#endif
7393af7c
PM
1035 break;
1036 case STATUS_STACK_OVERFLOW:
1037 DEBUG_EXCEPTION_SIMPLE ("STATUS_STACK_OVERFLOW");
1ef980b9 1038 ourstatus->value.sig = TARGET_SIGNAL_SEGV;
7393af7c
PM
1039 break;
1040 case STATUS_FLOAT_DENORMAL_OPERAND:
1041 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DENORMAL_OPERAND");
1042 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1043 break;
1044 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
1045 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ARRAY_BOUNDS_EXCEEDED");
1046 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1047 break;
1048 case STATUS_FLOAT_INEXACT_RESULT:
1049 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INEXACT_RESULT");
1050 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1051 break;
1052 case STATUS_FLOAT_INVALID_OPERATION:
1053 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INVALID_OPERATION");
1054 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1055 break;
1056 case STATUS_FLOAT_OVERFLOW:
1057 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_OVERFLOW");
1058 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1059 break;
1060 case STATUS_FLOAT_STACK_CHECK:
1061 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_STACK_CHECK");
1062 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1ef980b9 1063 break;
3b7c8b74 1064 case STATUS_FLOAT_UNDERFLOW:
7393af7c
PM
1065 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_UNDERFLOW");
1066 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1067 break;
3b7c8b74 1068 case STATUS_FLOAT_DIVIDE_BY_ZERO:
7393af7c
PM
1069 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DIVIDE_BY_ZERO");
1070 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1071 break;
3b7c8b74 1072 case STATUS_INTEGER_DIVIDE_BY_ZERO:
7393af7c 1073 DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_DIVIDE_BY_ZERO");
3b7c8b74 1074 ourstatus->value.sig = TARGET_SIGNAL_FPE;
3b7c8b74 1075 break;
7393af7c
PM
1076 case STATUS_INTEGER_OVERFLOW:
1077 DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_OVERFLOW");
1078 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1ef980b9
SC
1079 break;
1080 case EXCEPTION_BREAKPOINT:
7393af7c 1081 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_BREAKPOINT");
1ef980b9
SC
1082 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
1083 break;
1084 case DBG_CONTROL_C:
7393af7c 1085 DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_C");
1ef980b9 1086 ourstatus->value.sig = TARGET_SIGNAL_INT;
5b421780
PM
1087 break;
1088 case DBG_CONTROL_BREAK:
7393af7c 1089 DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_BREAK");
5b421780 1090 ourstatus->value.sig = TARGET_SIGNAL_INT;
1ef980b9
SC
1091 break;
1092 case EXCEPTION_SINGLE_STEP:
7393af7c 1093 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_SINGLE_STEP");
1ef980b9
SC
1094 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
1095 break;
8227c82d 1096 case EXCEPTION_ILLEGAL_INSTRUCTION:
7393af7c
PM
1097 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ILLEGAL_INSTRUCTION");
1098 ourstatus->value.sig = TARGET_SIGNAL_ILL;
1099 break;
1100 case EXCEPTION_PRIV_INSTRUCTION:
1101 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_PRIV_INSTRUCTION");
1102 ourstatus->value.sig = TARGET_SIGNAL_ILL;
1103 break;
1104 case EXCEPTION_NONCONTINUABLE_EXCEPTION:
1105 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_NONCONTINUABLE_EXCEPTION");
8227c82d
CF
1106 ourstatus->value.sig = TARGET_SIGNAL_ILL;
1107 break;
1ef980b9 1108 default:
a244bdca 1109 /* Treat unhandled first chance exceptions specially. */
02e423b9 1110 if (current_event.u.Exception.dwFirstChance)
a244bdca 1111 return -1;
a74ce742
PM
1112 printf_unfiltered ("gdb: unknown target exception 0x%08lx at %s\n",
1113 current_event.u.Exception.ExceptionRecord.ExceptionCode,
1114 host_address_to_string (
1115 current_event.u.Exception.ExceptionRecord.ExceptionAddress));
24e60978 1116 ourstatus->value.sig = TARGET_SIGNAL_UNKNOWN;
1ef980b9 1117 break;
24e60978 1118 }
24e60978 1119 exception_count++;
7393af7c 1120 last_sig = ourstatus->value.sig;
36339ecd 1121 return 1;
24e60978
SC
1122}
1123
3cee93ac
CF
1124/* Resume all artificially suspended threads if we are continuing
1125 execution */
1126static BOOL
dc05df57 1127windows_continue (DWORD continue_status, int id)
3cee93ac
CF
1128{
1129 int i;
1130 thread_info *th;
1131 BOOL res;
1132
1c1238a5 1133 DEBUG_EVENTS (("ContinueDebugEvent (cpid=%ld, ctid=%lx, %s);\n",
7393af7c 1134 current_event.dwProcessId, current_event.dwThreadId,
dfe7f3ac 1135 continue_status == DBG_CONTINUE ?
7393af7c 1136 "DBG_CONTINUE" : "DBG_EXCEPTION_NOT_HANDLED"));
6537bb24
PA
1137
1138 for (th = &thread_head; (th = th->next) != NULL;)
1139 if ((id == -1 || id == (int) th->id)
1140 && th->suspended)
1141 {
1142 if (debug_registers_changed)
1143 {
1144 th->context.ContextFlags |= CONTEXT_DEBUG_REGISTERS;
1145 th->context.Dr0 = dr[0];
1146 th->context.Dr1 = dr[1];
1147 th->context.Dr2 = dr[2];
1148 th->context.Dr3 = dr[3];
1149 th->context.Dr6 = DR6_CLEAR_VALUE;
1150 th->context.Dr7 = dr[7];
1151 }
1152 if (th->context.ContextFlags)
1153 {
1154 CHECK (SetThreadContext (th->h, &th->context));
1155 th->context.ContextFlags = 0;
1156 }
1157 if (th->suspended > 0)
1158 (void) ResumeThread (th->h);
1159 th->suspended = 0;
1160 }
1161
0714f9bf
SS
1162 res = ContinueDebugEvent (current_event.dwProcessId,
1163 current_event.dwThreadId,
1164 continue_status);
3cee93ac 1165
fa4ba8da 1166 debug_registers_changed = 0;
3cee93ac
CF
1167 return res;
1168}
1169
d6dc8049
CF
1170/* Called in pathological case where Windows fails to send a
1171 CREATE_PROCESS_DEBUG_EVENT after an attach. */
3ee6f623 1172static DWORD
5439edaa 1173fake_create_process (void)
3ade5333
CF
1174{
1175 current_process_handle = OpenProcess (PROCESS_ALL_ACCESS, FALSE,
1176 current_event.dwProcessId);
bf25528d
CF
1177 if (current_process_handle != NULL)
1178 open_process_used = 1;
1179 else
1180 {
1181 error (_("OpenProcess call failed, GetLastError = %lud\n"),
1182 GetLastError ());
1183 /* We can not debug anything in that case. */
1184 }
3ade5333 1185 main_thread_id = current_event.dwThreadId;
dc05df57
CF
1186 current_thread = windows_add_thread (ptid_build (current_event.dwProcessId, 0,
1187 current_event.dwThreadId),
1188 current_event.u.CreateThread.hThread);
3ade5333
CF
1189 return main_thread_id;
1190}
1191
a244bdca 1192static void
28439f5e
PA
1193windows_resume (struct target_ops *ops,
1194 ptid_t ptid, int step, enum target_signal sig)
a244bdca
CF
1195{
1196 thread_info *th;
1197 DWORD continue_status = DBG_CONTINUE;
1198
2dc38344
PA
1199 /* A specific PTID means `step only this thread id'. */
1200 int resume_all = ptid_equal (ptid, minus_one_ptid);
1201
1202 /* If we're continuing all threads, it's the current inferior that
1203 should be handled specially. */
1204 if (resume_all)
1205 ptid = inferior_ptid;
a244bdca
CF
1206
1207 if (sig != TARGET_SIGNAL_0)
1208 {
1209 if (current_event.dwDebugEventCode != EXCEPTION_DEBUG_EVENT)
1210 {
1211 DEBUG_EXCEPT(("Cannot continue with signal %d here.\n",sig));
1212 }
1213 else if (sig == last_sig)
1214 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1215 else
1216#if 0
1217/* This code does not seem to work, because
1218 the kernel does probably not consider changes in the ExceptionRecord
1219 structure when passing the exception to the inferior.
1220 Note that this seems possible in the exception handler itself. */
1221 {
1222 int i;
1223 for (i = 0; xlate[i].them != -1; i++)
1224 if (xlate[i].us == sig)
1225 {
1226 current_event.u.Exception.ExceptionRecord.ExceptionCode =
1227 xlate[i].them;
1228 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1229 break;
1230 }
1231 if (continue_status == DBG_CONTINUE)
1232 {
1233 DEBUG_EXCEPT(("Cannot continue with signal %d.\n",sig));
1234 }
1235 }
1236#endif
1237 DEBUG_EXCEPT(("Can only continue with recieved signal %d.\n",
1238 last_sig));
1239 }
1240
1241 last_sig = TARGET_SIGNAL_0;
1242
dc05df57 1243 DEBUG_EXEC (("gdb: windows_resume (pid=%d, tid=%ld, step=%d, sig=%d);\n",
2dc38344 1244 ptid_get_pid (ptid), ptid_get_tid (ptid), step, sig));
a244bdca
CF
1245
1246 /* Get context for currently selected thread */
2dc38344 1247 th = thread_rec (ptid_get_tid (inferior_ptid), FALSE);
a244bdca
CF
1248 if (th)
1249 {
1250 if (step)
1251 {
1252 /* Single step by setting t bit */
a97b0ac8
UW
1253 struct regcache *regcache = get_current_regcache ();
1254 struct gdbarch *gdbarch = get_regcache_arch (regcache);
1255 windows_fetch_inferior_registers (ops, regcache,
1256 gdbarch_ps_regnum (gdbarch));
a244bdca
CF
1257 th->context.EFlags |= FLAG_TRACE_BIT;
1258 }
1259
1260 if (th->context.ContextFlags)
1261 {
1262 if (debug_registers_changed)
1263 {
1264 th->context.Dr0 = dr[0];
1265 th->context.Dr1 = dr[1];
1266 th->context.Dr2 = dr[2];
1267 th->context.Dr3 = dr[3];
6537bb24 1268 th->context.Dr6 = DR6_CLEAR_VALUE;
a244bdca
CF
1269 th->context.Dr7 = dr[7];
1270 }
1271 CHECK (SetThreadContext (th->h, &th->context));
1272 th->context.ContextFlags = 0;
1273 }
1274 }
1275
1276 /* Allow continuing with the same signal that interrupted us.
1277 Otherwise complain. */
1278
2dc38344 1279 if (resume_all)
dc05df57 1280 windows_continue (continue_status, -1);
2dc38344 1281 else
dc05df57 1282 windows_continue (continue_status, ptid_get_tid (ptid));
a244bdca
CF
1283}
1284
695de547
CF
1285/* Ctrl-C handler used when the inferior is not run in the same console. The
1286 handler is in charge of interrupting the inferior using DebugBreakProcess.
1287 Note that this function is not available prior to Windows XP. In this case
1288 we emit a warning. */
1289BOOL WINAPI
1290ctrl_c_handler (DWORD event_type)
1291{
1292 const int attach_flag = current_inferior ()->attach_flag;
1293
bb0613a5
PM
1294 /* Only handle Ctrl-C and Ctrl-Break events. Ignore others. */
1295 if (event_type != CTRL_C_EVENT && event_type != CTRL_BREAK_EVENT)
695de547
CF
1296 return FALSE;
1297
1298 /* If the inferior and the debugger share the same console, do nothing as
1299 the inferior has also received the Ctrl-C event. */
1300 if (!new_console && !attach_flag)
1301 return TRUE;
1302
1303 if (!DebugBreakProcess (current_process_handle))
1304 warning (_("\
1305Could not interrupt program. Press Ctrl-c in the program console."));
1306
1307 /* Return true to tell that Ctrl-C has been handled. */
1308 return TRUE;
1309}
1310
8a892701 1311/* Get the next event from the child. Return 1 if the event requires
695de547 1312 handling by WFI (or whatever). */
1e37c281 1313static int
28439f5e
PA
1314get_windows_debug_event (struct target_ops *ops,
1315 int pid, struct target_waitstatus *ourstatus)
1e37c281
JM
1316{
1317 BOOL debug_event;
8a892701 1318 DWORD continue_status, event_code;
87a45c96 1319 thread_info *th;
8a892701 1320 static thread_info dummy_thread_info;
450005e7 1321 int retval = 0;
1e37c281 1322
7393af7c 1323 last_sig = TARGET_SIGNAL_0;
9d3789f7 1324
8a892701 1325 if (!(debug_event = WaitForDebugEvent (&current_event, 1000)))
29fe111d 1326 goto out;
1e37c281
JM
1327
1328 event_count++;
1329 continue_status = DBG_CONTINUE;
1e37c281 1330
8a892701 1331 event_code = current_event.dwDebugEventCode;
450005e7 1332 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
87a45c96 1333 th = NULL;
a244bdca 1334 have_saved_context = 0;
8a892701
CF
1335
1336 switch (event_code)
1e37c281
JM
1337 {
1338 case CREATE_THREAD_DEBUG_EVENT:
1339 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%x code=%s)\n",
8a892701
CF
1340 (unsigned) current_event.dwProcessId,
1341 (unsigned) current_event.dwThreadId,
1342 "CREATE_THREAD_DEBUG_EVENT"));
dfe7f3ac 1343 if (saw_create != 1)
3ade5333 1344 {
181e7f93
PA
1345 struct inferior *inf;
1346 inf = find_inferior_pid (current_event.dwProcessId);
1347 if (!saw_create && inf->attach_flag)
3ade5333 1348 {
d6dc8049
CF
1349 /* Kludge around a Windows bug where first event is a create
1350 thread event. Caused when attached process does not have
1351 a main thread. */
3a3e9ee3 1352 retval = fake_create_process ();
181e7f93
PA
1353 if (retval)
1354 saw_create++;
3ade5333
CF
1355 }
1356 break;
1357 }
1e37c281 1358 /* Record the existence of this thread */
450005e7 1359 retval = current_event.dwThreadId;
dc05df57 1360 th = windows_add_thread (ptid_build (current_event.dwProcessId, 0,
2dc38344
PA
1361 current_event.dwThreadId),
1362 current_event.u.CreateThread.hThread);
1e37c281
JM
1363 break;
1364
1365 case EXIT_THREAD_DEBUG_EVENT:
1c1238a5 1366 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%x code=%s)\n",
8a892701
CF
1367 (unsigned) current_event.dwProcessId,
1368 (unsigned) current_event.dwThreadId,
1369 "EXIT_THREAD_DEBUG_EVENT"));
87a45c96
CF
1370 if (current_event.dwThreadId != main_thread_id)
1371 {
dc05df57 1372 windows_delete_thread (ptid_build (current_event.dwProcessId, 0,
2dc38344 1373 current_event.dwThreadId));
87a45c96
CF
1374 th = &dummy_thread_info;
1375 }
1e37c281
JM
1376 break;
1377
1378 case CREATE_PROCESS_DEBUG_EVENT:
1c1238a5 1379 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%x code=%s)\n",
8a892701
CF
1380 (unsigned) current_event.dwProcessId,
1381 (unsigned) current_event.dwThreadId,
1382 "CREATE_PROCESS_DEBUG_EVENT"));
700b351b 1383 CloseHandle (current_event.u.CreateProcessInfo.hFile);
dfe7f3ac 1384 if (++saw_create != 1)
bf25528d 1385 break;
1e37c281 1386
dfe7f3ac 1387 current_process_handle = current_event.u.CreateProcessInfo.hProcess;
87a45c96 1388 if (main_thread_id)
695de547
CF
1389 windows_delete_thread (ptid_build (current_event.dwProcessId, 0,
1390 main_thread_id));
9d3789f7 1391 main_thread_id = current_event.dwThreadId;
1e37c281 1392 /* Add the main thread */
dc05df57 1393 th = windows_add_thread (ptid_build (current_event.dwProcessId, 0,
695de547
CF
1394 current_event.dwThreadId),
1395 current_event.u.CreateProcessInfo.hThread);
3a3e9ee3 1396 retval = current_event.dwThreadId;
1e37c281
JM
1397 break;
1398
1399 case EXIT_PROCESS_DEBUG_EVENT:
1c1238a5 1400 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%x code=%s)\n",
8a892701
CF
1401 (unsigned) current_event.dwProcessId,
1402 (unsigned) current_event.dwThreadId,
1403 "EXIT_PROCESS_DEBUG_EVENT"));
16d905e2
CF
1404 if (!windows_initialization_done)
1405 {
1406 target_terminal_ours ();
1407 target_mourn_inferior ();
1408 error (_("During startup program exited with code 0x%x."),
1409 (unsigned int) current_event.u.ExitProcess.dwExitCode);
1410 }
1411 else if (saw_create == 1)
1412 {
1413 ourstatus->kind = TARGET_WAITKIND_EXITED;
1414 ourstatus->value.integer = current_event.u.ExitProcess.dwExitCode;
1415 retval = main_thread_id;
1416 }
8a892701 1417 break;
1e37c281
JM
1418
1419 case LOAD_DLL_DEBUG_EVENT:
1c1238a5 1420 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%x code=%s)\n",
8a892701
CF
1421 (unsigned) current_event.dwProcessId,
1422 (unsigned) current_event.dwThreadId,
1423 "LOAD_DLL_DEBUG_EVENT"));
700b351b 1424 CloseHandle (current_event.u.LoadDll.hFile);
dfe7f3ac
CF
1425 if (saw_create != 1)
1426 break;
8a892701 1427 catch_errors (handle_load_dll, NULL, (char *) "", RETURN_MASK_ALL);
450005e7
CF
1428 ourstatus->kind = TARGET_WAITKIND_LOADED;
1429 ourstatus->value.integer = 0;
9d3789f7 1430 retval = main_thread_id;
1e37c281
JM
1431 break;
1432
1433 case UNLOAD_DLL_DEBUG_EVENT:
1c1238a5 1434 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%x code=%s)\n",
8a892701
CF
1435 (unsigned) current_event.dwProcessId,
1436 (unsigned) current_event.dwThreadId,
1437 "UNLOAD_DLL_DEBUG_EVENT"));
dfe7f3ac
CF
1438 if (saw_create != 1)
1439 break;
d3ff4a77 1440 catch_errors (handle_unload_dll, NULL, (char *) "", RETURN_MASK_ALL);
de1b3c3d
PA
1441 ourstatus->kind = TARGET_WAITKIND_LOADED;
1442 ourstatus->value.integer = 0;
1443 retval = main_thread_id;
d3ff4a77 1444 break;
1e37c281
JM
1445
1446 case EXCEPTION_DEBUG_EVENT:
1c1238a5 1447 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%x code=%s)\n",
8a892701
CF
1448 (unsigned) current_event.dwProcessId,
1449 (unsigned) current_event.dwThreadId,
1450 "EXCEPTION_DEBUG_EVENT"));
dfe7f3ac
CF
1451 if (saw_create != 1)
1452 break;
a244bdca
CF
1453 switch (handle_exception (ourstatus))
1454 {
1455 case 0:
1456 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1457 break;
1458 case 1:
1459 retval = current_event.dwThreadId;
1460 break;
1461 case -1:
1462 last_sig = 1;
1463 continue_status = -1;
1464 break;
1465 }
1e37c281
JM
1466 break;
1467
8a892701 1468 case OUTPUT_DEBUG_STRING_EVENT: /* message from the kernel */
1c1238a5 1469 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%x code=%s)\n",
8a892701
CF
1470 (unsigned) current_event.dwProcessId,
1471 (unsigned) current_event.dwThreadId,
1472 "OUTPUT_DEBUG_STRING_EVENT"));
dfe7f3ac
CF
1473 if (saw_create != 1)
1474 break;
a244bdca 1475 retval = handle_output_debug_string (ourstatus);
1e37c281 1476 break;
9d3789f7 1477
1e37c281 1478 default:
dfe7f3ac
CF
1479 if (saw_create != 1)
1480 break;
29fe111d
CF
1481 printf_unfiltered ("gdb: kernel event for pid=%ld tid=%ld\n",
1482 (DWORD) current_event.dwProcessId,
1483 (DWORD) current_event.dwThreadId);
1484 printf_unfiltered (" unknown event code %ld\n",
1e37c281
JM
1485 current_event.dwDebugEventCode);
1486 break;
1487 }
1488
dfe7f3ac 1489 if (!retval || saw_create != 1)
a244bdca
CF
1490 {
1491 if (continue_status == -1)
02529b48 1492 windows_resume (ops, minus_one_ptid, 0, 1);
a244bdca 1493 else
dc05df57 1494 CHECK (windows_continue (continue_status, -1));
a244bdca 1495 }
450005e7 1496 else
9d3789f7 1497 {
2dc38344
PA
1498 inferior_ptid = ptid_build (current_event.dwProcessId, 0,
1499 retval);
3ade5333 1500 current_thread = th ?: thread_rec (current_event.dwThreadId, TRUE);
9d3789f7 1501 }
1e37c281
JM
1502
1503out:
450005e7 1504 return retval;
1e37c281
JM
1505}
1506
2dc38344 1507/* Wait for interesting events to occur in the target process. */
39f77062 1508static ptid_t
117de6a9 1509windows_wait (struct target_ops *ops,
47608cb1 1510 ptid_t ptid, struct target_waitstatus *ourstatus, int options)
24e60978 1511{
2dc38344 1512 int pid = -1;
39f77062 1513
c44537cf
CV
1514 target_terminal_ours ();
1515
24e60978
SC
1516 /* We loop when we get a non-standard exception rather than return
1517 with a SPURIOUS because resume can try and step or modify things,
3cee93ac 1518 which needs a current_thread->h. But some of these exceptions mark
24e60978
SC
1519 the birth or death of threads, which mean that the current thread
1520 isn't necessarily what you think it is. */
1521
1522 while (1)
450005e7 1523 {
c57918b2 1524 int retval;
2b008701 1525
695de547
CF
1526 /* If the user presses Ctrl-c while the debugger is waiting
1527 for an event, he expects the debugger to interrupt his program
1528 and to get the prompt back. There are two possible situations:
1529
1530 - The debugger and the program do not share the console, in
1531 which case the Ctrl-c event only reached the debugger.
1532 In that case, the ctrl_c handler will take care of interrupting
1533 the inferior. Note that this case is working starting with
1534 Windows XP. For Windows 2000, Ctrl-C should be pressed in the
1535 inferior console.
1536
1537 - The debugger and the program share the same console, in which
1538 case both debugger and inferior will receive the Ctrl-c event.
1539 In that case the ctrl_c handler will ignore the event, as the
1540 Ctrl-c event generated inside the inferior will trigger the
1541 expected debug event.
1542
1543 FIXME: brobecker/2008-05-20: If the inferior receives the
1544 signal first and the delay until GDB receives that signal
1545 is sufficiently long, GDB can sometimes receive the SIGINT
1546 after we have unblocked the CTRL+C handler. This would
1547 lead to the debugger stopping prematurely while handling
1548 the new-thread event that comes with the handling of the SIGINT
1549 inside the inferior, and then stop again immediately when
1550 the user tries to resume the execution in the inferior.
1551 This is a classic race that we should try to fix one day. */
1552 SetConsoleCtrlHandler (&ctrl_c_handler, TRUE);
28439f5e 1553 retval = get_windows_debug_event (ops, pid, ourstatus);
695de547 1554 SetConsoleCtrlHandler (&ctrl_c_handler, FALSE);
c57918b2 1555
450005e7 1556 if (retval)
2dc38344 1557 return ptid_build (current_event.dwProcessId, 0, retval);
450005e7
CF
1558 else
1559 {
1560 int detach = 0;
3cee93ac 1561
98bbd631
AC
1562 if (deprecated_ui_loop_hook != NULL)
1563 detach = deprecated_ui_loop_hook (0);
0714f9bf 1564
450005e7 1565 if (detach)
7d85a9c0 1566 windows_kill_inferior (ops);
450005e7
CF
1567 }
1568 }
24e60978
SC
1569}
1570
9d3789f7 1571static void
dc05df57 1572do_initial_windows_stuff (struct target_ops *ops, DWORD pid, int attaching)
9d3789f7
CF
1573{
1574 extern int stop_after_trap;
fa4ba8da 1575 int i;
d6b48e9c 1576 struct inferior *inf;
2020b7ab 1577 struct thread_info *tp;
9d3789f7 1578
7393af7c 1579 last_sig = TARGET_SIGNAL_0;
9d3789f7
CF
1580 event_count = 0;
1581 exception_count = 0;
bf25528d 1582 open_process_used = 0;
fa4ba8da 1583 debug_registers_changed = 0;
dfe7f3ac 1584 debug_registers_used = 0;
fa4ba8da
PM
1585 for (i = 0; i < sizeof (dr) / sizeof (dr[0]); i++)
1586 dr[i] = 0;
10325bc5 1587#ifdef __CYGWIN__
de1b3c3d 1588 cygwin_load_start = cygwin_load_end = 0;
10325bc5 1589#endif
9d3789f7
CF
1590 current_event.dwProcessId = pid;
1591 memset (&current_event, 0, sizeof (current_event));
0795be10 1592 push_target (ops);
cb851954 1593 disable_breakpoints_in_shlibs ();
dc05df57 1594 windows_clear_solib ();
9d3789f7
CF
1595 clear_proceed_status ();
1596 init_wait_for_inferior ();
1597
6c95b8df
PA
1598 inf = current_inferior ();
1599 inferior_appeared (inf, pid);
181e7f93 1600 inf->attach_flag = attaching;
7f9f62ba 1601
9f9d052e
PM
1602 /* Make the new process the current inferior, so terminal handling
1603 can rely on it. When attaching, we don't know about any thread
1604 id here, but that's OK --- nothing should be referencing the
dc05df57 1605 current thread until we report an event out of windows_wait. */
9f9d052e
PM
1606 inferior_ptid = pid_to_ptid (pid);
1607
c44537cf 1608 terminal_init_inferior_with_pgrp (pid);
9d3789f7
CF
1609 target_terminal_inferior ();
1610
16d905e2 1611 windows_initialization_done = 0;
d6b48e9c 1612 inf->stop_soon = STOP_QUIETLY;
9d3789f7
CF
1613 while (1)
1614 {
1615 stop_after_trap = 1;
ae123ec6 1616 wait_for_inferior (0);
2020b7ab
PA
1617 tp = inferior_thread ();
1618 if (tp->stop_signal != TARGET_SIGNAL_TRAP)
1619 resume (0, tp->stop_signal);
9d3789f7
CF
1620 else
1621 break;
1622 }
eff8332b 1623
16d905e2 1624 windows_initialization_done = 1;
d6b48e9c 1625 inf->stop_soon = NO_STOP_QUIETLY;
9d3789f7
CF
1626 stop_after_trap = 0;
1627 return;
1628}
1629
616a9dc4
CV
1630/* Try to set or remove a user privilege to the current process. Return -1
1631 if that fails, the previous setting of that privilege otherwise.
1632
1633 This code is copied from the Cygwin source code and rearranged to allow
1634 dynamically loading of the needed symbols from advapi32 which is only
1635 available on NT/2K/XP. */
1636static int
1637set_process_privilege (const char *privilege, BOOL enable)
1638{
616a9dc4
CV
1639 HANDLE token_hdl = NULL;
1640 LUID restore_priv;
1641 TOKEN_PRIVILEGES new_priv, orig_priv;
1642 int ret = -1;
1643 DWORD size;
1644
616a9dc4
CV
1645 if (!OpenProcessToken (GetCurrentProcess (),
1646 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
1647 &token_hdl))
1648 goto out;
1649
418c6cb3 1650 if (!LookupPrivilegeValueA (NULL, privilege, &restore_priv))
616a9dc4
CV
1651 goto out;
1652
1653 new_priv.PrivilegeCount = 1;
1654 new_priv.Privileges[0].Luid = restore_priv;
1655 new_priv.Privileges[0].Attributes = enable ? SE_PRIVILEGE_ENABLED : 0;
1656
1657 if (!AdjustTokenPrivileges (token_hdl, FALSE, &new_priv,
295732ea 1658 sizeof orig_priv, &orig_priv, &size))
616a9dc4
CV
1659 goto out;
1660#if 0
1661 /* Disabled, otherwise every `attach' in an unprivileged user session
1662 would raise the "Failed to get SE_DEBUG_NAME privilege" warning in
dc05df57 1663 windows_attach(). */
616a9dc4
CV
1664 /* AdjustTokenPrivileges returns TRUE even if the privilege could not
1665 be enabled. GetLastError () returns an correct error code, though. */
1666 if (enable && GetLastError () == ERROR_NOT_ALL_ASSIGNED)
1667 goto out;
1668#endif
1669
1670 ret = orig_priv.Privileges[0].Attributes == SE_PRIVILEGE_ENABLED ? 1 : 0;
1671
1672out:
1673 if (token_hdl)
1674 CloseHandle (token_hdl);
1675
1676 return ret;
1677}
1678
02cc9f49 1679/* Attach to process PID, then initialize for debugging it. */
24e60978 1680static void
dc05df57 1681windows_attach (struct target_ops *ops, char *args, int from_tty)
24e60978
SC
1682{
1683 BOOL ok;
559e75c0 1684 DWORD pid;
24e60978
SC
1685
1686 if (!args)
e2e0b3e5 1687 error_no_arg (_("process-id to attach"));
24e60978 1688
616a9dc4
CV
1689 if (set_process_privilege (SE_DEBUG_NAME, TRUE) < 0)
1690 {
1691 printf_unfiltered ("Warning: Failed to get SE_DEBUG_NAME privilege\n");
1692 printf_unfiltered ("This can cause attach to fail on Windows NT/2K/XP\n");
1693 }
1694
baa93fa6
CF
1695 pid = strtoul (args, 0, 0); /* Windows pid */
1696
dc05df57 1697 windows_init_thread_list ();
9d3789f7 1698 ok = DebugActiveProcess (pid);
91a175b3 1699 saw_create = 0;
24e60978 1700
10325bc5 1701#ifdef __CYGWIN__
24e60978 1702 if (!ok)
baa93fa6
CF
1703 {
1704 /* Try fall back to Cygwin pid */
1705 pid = cygwin_internal (CW_CYGWIN_PID_TO_WINPID, pid);
1706
1707 if (pid > 0)
1708 ok = DebugActiveProcess (pid);
10325bc5
PA
1709 }
1710#endif
baa93fa6 1711
10325bc5
PA
1712 if (!ok)
1713 error (_("Can't attach to process."));
24e60978 1714
2b008701 1715 DebugSetProcessKillOnExit (FALSE);
3ade5333 1716
24e60978
SC
1717 if (from_tty)
1718 {
1719 char *exec_file = (char *) get_exec_file (0);
1720
1721 if (exec_file)
1722 printf_unfiltered ("Attaching to program `%s', %s\n", exec_file,
39f77062 1723 target_pid_to_str (pid_to_ptid (pid)));
24e60978
SC
1724 else
1725 printf_unfiltered ("Attaching to %s\n",
39f77062 1726 target_pid_to_str (pid_to_ptid (pid)));
24e60978
SC
1727
1728 gdb_flush (gdb_stdout);
1729 }
1730
dc05df57 1731 do_initial_windows_stuff (ops, pid, 1);
9d3789f7 1732 target_terminal_ours ();
24e60978
SC
1733}
1734
24e60978 1735static void
dc05df57 1736windows_detach (struct target_ops *ops, char *args, int from_tty)
24e60978 1737{
02cc9f49
CV
1738 int detached = 1;
1739
2b008701
CF
1740 ptid_t ptid = {-1};
1741 windows_resume (ops, ptid, 0, TARGET_SIGNAL_0);
96998ce7 1742
2b008701
CF
1743 if (!DebugActiveProcessStop (current_event.dwProcessId))
1744 {
1745 error (_("Can't detach process %lu (error %lu)"),
1746 current_event.dwProcessId, GetLastError ());
1747 detached = 0;
02cc9f49 1748 }
2b008701
CF
1749 DebugSetProcessKillOnExit (FALSE);
1750
02cc9f49 1751 if (detached && from_tty)
24e60978
SC
1752 {
1753 char *exec_file = get_exec_file (0);
1754 if (exec_file == 0)
1755 exec_file = "";
02cc9f49
CV
1756 printf_unfiltered ("Detaching from program: %s, Pid %lu\n", exec_file,
1757 current_event.dwProcessId);
24e60978
SC
1758 gdb_flush (gdb_stdout);
1759 }
7f9f62ba 1760
39f77062 1761 inferior_ptid = null_ptid;
7f9f62ba
PA
1762 detach_inferior (current_event.dwProcessId);
1763
0795be10 1764 unpush_target (ops);
24e60978
SC
1765}
1766
3ee6f623 1767static char *
dc05df57 1768windows_pid_to_exec_file (int pid)
47216e51 1769{
47216e51 1770 static char path[MAX_PATH + 1];
10325bc5
PA
1771
1772#ifdef __CYGWIN__
33605d39
CF
1773 /* Try to find exe name as symlink target of /proc/<pid>/exe */
1774 int nchars;
1775 char procexe[sizeof ("/proc/4294967295/exe")];
2dc38344 1776 sprintf (procexe, "/proc/%u/exe", pid);
33605d39
CF
1777 nchars = readlink (procexe, path, sizeof(path));
1778 if (nchars > 0 && nchars < sizeof (path))
47216e51 1779 {
33605d39
CF
1780 path[nchars] = '\0'; /* Got it */
1781 return path;
47216e51 1782 }
10325bc5
PA
1783#endif
1784
33605d39
CF
1785 /* If we get here then either Cygwin is hosed, this isn't a Cygwin version
1786 of gdb, or we're trying to debug a non-Cygwin windows executable. */
1787 if (!get_module_name (0, path))
1788 path[0] = '\0';
1789
1790 return path;
47216e51
CV
1791}
1792
24e60978
SC
1793/* Print status information about what we're accessing. */
1794
1795static void
dc05df57 1796windows_files_info (struct target_ops *ignore)
24e60978 1797{
181e7f93
PA
1798 struct inferior *inf = current_inferior ();
1799
24e60978 1800 printf_unfiltered ("\tUsing the running image of %s %s.\n",
181e7f93
PA
1801 inf->attach_flag ? "attached" : "child",
1802 target_pid_to_str (inferior_ptid));
24e60978
SC
1803}
1804
24e60978 1805static void
dc05df57 1806windows_open (char *arg, int from_tty)
24e60978 1807{
8a3fe4f8 1808 error (_("Use the \"run\" command to start a Unix child process."));
24e60978
SC
1809}
1810
dc05df57 1811/* Start an inferior windows child process and sets inferior_ptid to its pid.
24e60978
SC
1812 EXEC_FILE is the file to run.
1813 ALLARGS is a string containing the arguments to the program.
1814 ENV is the environment vector to pass. Errors reported with error(). */
1815
24e60978 1816static void
dc05df57 1817windows_create_inferior (struct target_ops *ops, char *exec_file,
136d6dae 1818 char *allargs, char **in_env, int from_tty)
24e60978 1819{
24e60978
SC
1820 STARTUPINFO si;
1821 PROCESS_INFORMATION pi;
24e60978
SC
1822 BOOL ret;
1823 DWORD flags;
eb708f2e 1824 char *args;
dfe7f3ac
CF
1825 char real_path[MAXPATHLEN];
1826 char *toexec;
349b409f
CF
1827 char shell[MAX_PATH + 1]; /* Path to shell */
1828 const char *sh;
41b4aadc 1829#ifdef __CYGWIN__
2becadee
CF
1830 int tty;
1831 int ostdin, ostdout, ostderr;
41b4aadc
CF
1832#else
1833 HANDLE tty;
1834#endif
3cb3b8df 1835 const char *inferior_io_terminal = get_inferior_io_terminal ();
24e60978
SC
1836
1837 if (!exec_file)
8a3fe4f8 1838 error (_("No executable specified, use `target exec'."));
24e60978
SC
1839
1840 memset (&si, 0, sizeof (si));
1841 si.cb = sizeof (si);
1842
10325bc5 1843#ifdef __CYGWIN__
349b409f 1844 if (!useshell)
dfe7f3ac
CF
1845 {
1846 flags = DEBUG_ONLY_THIS_PROCESS;
1847 cygwin_conv_to_win32_path (exec_file, real_path);
1848 toexec = real_path;
1849 }
1850 else
1851 {
349b409f
CF
1852 char *newallargs;
1853 sh = getenv ("SHELL");
1854 if (!sh)
1855 sh = "/bin/sh";
1856 cygwin_conv_to_win32_path (sh, shell);
1857 newallargs = alloca (sizeof (" -c 'exec '") + strlen (exec_file)
1858 + strlen (allargs) + 2);
dfe7f3ac
CF
1859 sprintf (newallargs, " -c 'exec %s %s'", exec_file, allargs);
1860 allargs = newallargs;
1861 toexec = shell;
1862 flags = DEBUG_PROCESS;
1863 }
10325bc5
PA
1864#else
1865 toexec = exec_file;
1866 flags = DEBUG_ONLY_THIS_PROCESS;
1867#endif
eb708f2e 1868
eeb25b8a
PM
1869 if (new_group)
1870 flags |= CREATE_NEW_PROCESS_GROUP;
1871
1872 if (new_console)
1873 flags |= CREATE_NEW_CONSOLE;
1874
dfe7f3ac
CF
1875 args = alloca (strlen (toexec) + strlen (allargs) + 2);
1876 strcpy (args, toexec);
eb708f2e
SC
1877 strcat (args, " ");
1878 strcat (args, allargs);
1879
10325bc5 1880#ifdef __CYGWIN__
e88c49c3 1881 /* Prepare the environment vars for CreateProcess. */
002c07a9 1882 cygwin_internal (CW_SYNC_WINENV);
1750a5ef 1883
2becadee
CF
1884 if (!inferior_io_terminal)
1885 tty = ostdin = ostdout = ostderr = -1;
1886 else
1887 {
1888 tty = open (inferior_io_terminal, O_RDWR | O_NOCTTY);
1889 if (tty < 0)
1890 {
1891 print_sys_errmsg (inferior_io_terminal, errno);
1892 ostdin = ostdout = ostderr = -1;
1893 }
1894 else
1895 {
1896 ostdin = dup (0);
1897 ostdout = dup (1);
1898 ostderr = dup (2);
1899 dup2 (tty, 0);
1900 dup2 (tty, 1);
1901 dup2 (tty, 2);
1902 }
1903 }
41b4aadc
CF
1904#else
1905 if (!inferior_io_terminal)
1906 tty = INVALID_HANDLE_VALUE;
1907 else
1908 {
1909 SECURITY_ATTRIBUTES sa;
1910 sa.nLength = sizeof(sa);
1911 sa.lpSecurityDescriptor = 0;
1912 sa.bInheritHandle = TRUE;
1913 tty = CreateFileA (inferior_io_terminal, GENERIC_READ | GENERIC_WRITE,
1914 0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
1915 if (tty == INVALID_HANDLE_VALUE)
1916 warning (_("Warning: Failed to open TTY %s, error %#x."),
1917 inferior_io_terminal, (unsigned) GetLastError ());
1918 else
1919 {
1920 si.hStdInput = tty;
1921 si.hStdOutput = tty;
1922 si.hStdError = tty;
1923 si.dwFlags |= STARTF_USESTDHANDLES;
1924 }
1925 }
10325bc5 1926#endif
2becadee 1927
dc05df57 1928 windows_init_thread_list ();
1750a5ef 1929 ret = CreateProcess (0,
3a4b77d8 1930 args, /* command line */
24e60978
SC
1931 NULL, /* Security */
1932 NULL, /* thread */
1933 TRUE, /* inherit handles */
1934 flags, /* start flags */
002c07a9 1935 NULL, /* environment */
24e60978
SC
1936 NULL, /* current directory */
1937 &si,
1938 &pi);
10325bc5
PA
1939
1940#ifdef __CYGWIN__
2becadee
CF
1941 if (tty >= 0)
1942 {
1943 close (tty);
1944 dup2 (ostdin, 0);
1945 dup2 (ostdout, 1);
1946 dup2 (ostderr, 2);
1947 close (ostdin);
1948 close (ostdout);
1949 close (ostderr);
1950 }
41b4aadc
CF
1951#else
1952 if (tty != INVALID_HANDLE_VALUE)
1953 CloseHandle (tty);
10325bc5 1954#endif
2becadee 1955
24e60978 1956 if (!ret)
8a3fe4f8
AC
1957 error (_("Error creating process %s, (error %d)."),
1958 exec_file, (unsigned) GetLastError ());
24e60978 1959
c1766e7d
PM
1960 CloseHandle (pi.hThread);
1961 CloseHandle (pi.hProcess);
1962
dfe7f3ac
CF
1963 if (useshell && shell[0] != '\0')
1964 saw_create = -1;
1965 else
1966 saw_create = 0;
1967
dc05df57 1968 do_initial_windows_stuff (ops, pi.dwProcessId, 0);
d3a09475 1969
dc05df57 1970 /* windows_continue (DBG_CONTINUE, -1); */
24e60978
SC
1971}
1972
1973static void
dc05df57 1974windows_mourn_inferior (struct target_ops *ops)
24e60978 1975{
dc05df57 1976 (void) windows_continue (DBG_CONTINUE, -1);
fa4ba8da 1977 i386_cleanup_dregs();
bf25528d
CF
1978 if (open_process_used)
1979 {
1980 CHECK (CloseHandle (current_process_handle));
1981 open_process_used = 0;
1982 }
0795be10 1983 unpush_target (ops);
24e60978
SC
1984 generic_mourn_inferior ();
1985}
1986
24e60978
SC
1987/* Send a SIGINT to the process group. This acts just like the user typed a
1988 ^C on the controlling terminal. */
1989
b607efe7 1990static void
dc05df57 1991windows_stop (ptid_t ptid)
24e60978 1992{
1ef980b9 1993 DEBUG_EVENTS (("gdb: GenerateConsoleCtrlEvent (CTRLC_EVENT, 0)\n"));
1e37c281 1994 CHECK (GenerateConsoleCtrlEvent (CTRL_C_EVENT, current_event.dwProcessId));
3a4b77d8 1995 registers_changed (); /* refresh register state */
24e60978
SC
1996}
1997
3ee6f623 1998static int
dc05df57 1999windows_xfer_memory (CORE_ADDR memaddr, gdb_byte *our, int len,
0a65a603
AC
2000 int write, struct mem_attrib *mem,
2001 struct target_ops *target)
24e60978 2002{
5732a500 2003 SIZE_T done = 0;
24e60978
SC
2004 if (write)
2005 {
29fe111d 2006 DEBUG_MEM (("gdb: write target memory, %d bytes at 0x%08lx\n",
2c647436 2007 len, (DWORD) (uintptr_t) memaddr));
2b008701 2008 if (!WriteProcessMemory (current_process_handle,
2c647436 2009 (LPVOID) (uintptr_t) memaddr, our,
6f17862b
CF
2010 len, &done))
2011 done = 0;
2b008701 2012 FlushInstructionCache (current_process_handle,
2c647436 2013 (LPCVOID) (uintptr_t) memaddr, len);
24e60978
SC
2014 }
2015 else
2016 {
29fe111d 2017 DEBUG_MEM (("gdb: read target memory, %d bytes at 0x%08lx\n",
2c647436 2018 len, (DWORD) (uintptr_t) memaddr));
2b008701 2019 if (!ReadProcessMemory (current_process_handle,
2c647436 2020 (LPCVOID) (uintptr_t) memaddr, our,
6f17862b
CF
2021 len, &done))
2022 done = 0;
24e60978
SC
2023 }
2024 return done;
2025}
2026
3ee6f623 2027static void
7d85a9c0 2028windows_kill_inferior (struct target_ops *ops)
24e60978 2029{
3cee93ac
CF
2030 CHECK (TerminateProcess (current_process_handle, 0));
2031
b5edcb45
ILT
2032 for (;;)
2033 {
dc05df57 2034 if (!windows_continue (DBG_CONTINUE, -1))
b5edcb45 2035 break;
3cee93ac 2036 if (!WaitForDebugEvent (&current_event, INFINITE))
b5edcb45 2037 break;
3cee93ac 2038 if (current_event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
b5edcb45
ILT
2039 break;
2040 }
2041
dc05df57 2042 target_mourn_inferior (); /* or just windows_mourn_inferior? */
24e60978
SC
2043}
2044
24e60978 2045static void
dc05df57 2046windows_prepare_to_store (struct regcache *regcache)
24e60978
SC
2047{
2048 /* Do nothing, since we can store individual regs */
2049}
2050
2051static int
dc05df57 2052windows_can_run (void)
24e60978
SC
2053{
2054 return 1;
2055}
2056
2057static void
dc05df57 2058windows_close (int x)
24e60978 2059{
dc05df57 2060 DEBUG_EVENTS (("gdb: windows_close, inferior_ptid=%d\n",
3bccec63 2061 PIDGET (inferior_ptid)));
24e60978 2062}
1ef980b9 2063
3ee6f623
CF
2064/* Convert pid to printable format. */
2065static char *
117de6a9 2066windows_pid_to_str (struct target_ops *ops, ptid_t ptid)
24e60978 2067{
3ee6f623 2068 static char buf[80];
3ee6f623 2069
2dc38344
PA
2070 if (ptid_get_tid (ptid) != 0)
2071 {
2072 snprintf (buf, sizeof (buf), "Thread %d.0x%lx",
2073 ptid_get_pid (ptid), ptid_get_tid (ptid));
2074 return buf;
2075 }
2076
2077 return normal_pid_to_str (ptid);
3ee6f623
CF
2078}
2079
de1b3c3d 2080static LONGEST
dc05df57 2081windows_xfer_shared_libraries (struct target_ops *ops,
de1b3c3d
PA
2082 enum target_object object, const char *annex,
2083 gdb_byte *readbuf, const gdb_byte *writebuf,
2084 ULONGEST offset, LONGEST len)
3cb8e7f6 2085{
de1b3c3d
PA
2086 struct obstack obstack;
2087 const char *buf;
2088 LONGEST len_avail;
3cb8e7f6 2089 struct so_list *so;
3cb8e7f6 2090
de1b3c3d
PA
2091 if (writebuf)
2092 return -1;
3cb8e7f6 2093
de1b3c3d
PA
2094 obstack_init (&obstack);
2095 obstack_grow_str (&obstack, "<library-list>\n");
2096 for (so = solib_start.next; so; so = so->next)
dc05df57 2097 windows_xfer_shared_library (so->so_name, (CORE_ADDR) (uintptr_t) so->lm_info->load_addr,
5af949e3 2098 target_gdbarch, &obstack);
de1b3c3d 2099 obstack_grow_str0 (&obstack, "</library-list>\n");
3cb8e7f6 2100
de1b3c3d
PA
2101 buf = obstack_finish (&obstack);
2102 len_avail = strlen (buf);
2103 if (offset >= len_avail)
2104 return 0;
3cb8e7f6 2105
de1b3c3d
PA
2106 if (len > len_avail - offset)
2107 len = len_avail - offset;
2108 memcpy (readbuf, buf + offset, len);
3cb8e7f6 2109
de1b3c3d
PA
2110 obstack_free (&obstack, NULL);
2111 return len;
3cb8e7f6
CF
2112}
2113
de1b3c3d 2114static LONGEST
dc05df57 2115windows_xfer_partial (struct target_ops *ops, enum target_object object,
de1b3c3d
PA
2116 const char *annex, gdb_byte *readbuf,
2117 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
3cb8e7f6 2118{
de1b3c3d 2119 switch (object)
3cb8e7f6 2120 {
de1b3c3d
PA
2121 case TARGET_OBJECT_MEMORY:
2122 if (readbuf)
2123 return (*ops->deprecated_xfer_memory) (offset, readbuf,
244e85c8 2124 len, 0/*read*/, NULL, ops);
de1b3c3d
PA
2125 if (writebuf)
2126 return (*ops->deprecated_xfer_memory) (offset, (gdb_byte *) writebuf,
2127 len, 1/*write*/, NULL, ops);
2128 return -1;
2129
2130 case TARGET_OBJECT_LIBRARIES:
dc05df57 2131 return windows_xfer_shared_libraries (ops, object, annex, readbuf,
de1b3c3d 2132 writebuf, offset, len);
3929abe9 2133
de1b3c3d
PA
2134 default:
2135 if (ops->beneath != NULL)
2136 return ops->beneath->to_xfer_partial (ops->beneath, object, annex,
2137 readbuf, writebuf, offset, len);
2138 return -1;
3929abe9 2139 }
02c5aecd
CF
2140}
2141
1e2f1c5c
JB
2142static ptid_t
2143windows_get_ada_task_ptid (long lwp, long thread)
2144{
2145 return ptid_build (ptid_get_pid (inferior_ptid), 0, lwp);
2146}
2147
3ee6f623 2148static void
dc05df57 2149init_windows_ops (void)
3ee6f623 2150{
dc05df57
CF
2151 windows_ops.to_shortname = "child";
2152 windows_ops.to_longname = "Win32 child process";
2153 windows_ops.to_doc = "Win32 child process (started by the \"run\" command).";
2154 windows_ops.to_open = windows_open;
2155 windows_ops.to_close = windows_close;
2156 windows_ops.to_attach = windows_attach;
2157 windows_ops.to_attach_no_wait = 1;
2158 windows_ops.to_detach = windows_detach;
2159 windows_ops.to_resume = windows_resume;
2160 windows_ops.to_wait = windows_wait;
2161 windows_ops.to_fetch_registers = windows_fetch_inferior_registers;
2162 windows_ops.to_store_registers = windows_store_inferior_registers;
2163 windows_ops.to_prepare_to_store = windows_prepare_to_store;
2164 windows_ops.deprecated_xfer_memory = windows_xfer_memory;
2165 windows_ops.to_xfer_partial = windows_xfer_partial;
2166 windows_ops.to_files_info = windows_files_info;
2167 windows_ops.to_insert_breakpoint = memory_insert_breakpoint;
2168 windows_ops.to_remove_breakpoint = memory_remove_breakpoint;
2169 windows_ops.to_terminal_init = terminal_init_inferior;
2170 windows_ops.to_terminal_inferior = terminal_inferior;
2171 windows_ops.to_terminal_ours_for_output = terminal_ours_for_output;
2172 windows_ops.to_terminal_ours = terminal_ours;
2173 windows_ops.to_terminal_save_ours = terminal_save_ours;
2174 windows_ops.to_terminal_info = child_terminal_info;
2175 windows_ops.to_kill = windows_kill_inferior;
2176 windows_ops.to_create_inferior = windows_create_inferior;
2177 windows_ops.to_mourn_inferior = windows_mourn_inferior;
2178 windows_ops.to_can_run = windows_can_run;
2179 windows_ops.to_thread_alive = windows_thread_alive;
2180 windows_ops.to_pid_to_str = windows_pid_to_str;
2181 windows_ops.to_stop = windows_stop;
2182 windows_ops.to_stratum = process_stratum;
c35b1492
PA
2183 windows_ops.to_has_all_memory = default_child_has_all_memory;
2184 windows_ops.to_has_memory = default_child_has_memory;
2185 windows_ops.to_has_stack = default_child_has_stack;
2186 windows_ops.to_has_registers = default_child_has_registers;
2187 windows_ops.to_has_execution = default_child_has_execution;
dc05df57 2188 windows_ops.to_pid_to_exec_file = windows_pid_to_exec_file;
1e2f1c5c 2189 windows_ops.to_get_ada_task_ptid = windows_get_ada_task_ptid;
9bb9e8ad 2190
5aca5a82
PM
2191 i386_use_watchpoints (&windows_ops);
2192
9bb9e8ad
PM
2193 i386_dr_low.set_control = cygwin_set_dr7;
2194 i386_dr_low.set_addr = cygwin_set_dr;
2195 i386_dr_low.reset_addr = NULL;
2196 i386_dr_low.get_status = cygwin_get_dr6;
2197
2198 /* i386_dr_low.debug_register_length field is set by
2199 calling i386_set_debug_register_length function
2200 in processor windows specific native file. */
2201
dc05df57 2202 windows_ops.to_magic = OPS_MAGIC;
c719b714 2203}
24e60978 2204
3929abe9 2205static void
dc05df57 2206set_windows_aliases (char *argv0)
3929abe9
CF
2207{
2208 add_info_alias ("dll", "sharedlibrary", 1);
2209}
2210
24e60978 2211void
dc05df57 2212_initialize_windows_nat (void)
24e60978 2213{
fa58ee11
EZ
2214 struct cmd_list_element *c;
2215
dc05df57 2216 init_windows_ops ();
1ef980b9 2217
fa58ee11 2218 c = add_com ("dll-symbols", class_files, dll_symbol_command,
1bedd215 2219 _("Load dll library symbols from FILE."));
5ba2abeb 2220 set_cmd_completer (c, filename_completer);
450005e7
CF
2221
2222 add_com_alias ("sharedlibrary", "dll-symbols", class_alias, 1);
2223
70992597
PM
2224 add_com_alias ("add-shared-symbol-files", "dll-symbols", class_alias, 1);
2225
2226 add_com_alias ("assf", "dll-symbols", class_alias, 1);
2227
10325bc5 2228#ifdef __CYGWIN__
5bf193a2
AC
2229 add_setshow_boolean_cmd ("shell", class_support, &useshell, _("\
2230Set use of shell to start subprocess."), _("\
2231Show use of shell to start subprocess."), NULL,
2232 NULL,
2233 NULL, /* FIXME: i18n: */
2234 &setlist, &showlist);
2235
09280ddf
CF
2236 add_setshow_boolean_cmd ("cygwin-exceptions", class_support, &cygwin_exceptions, _("\
2237Break when an exception is detected in the Cygwin DLL itself."), _("\
2238Show whether gdb breaks on exceptions in the Cygwin DLL itself."), NULL,
2239 NULL,
2240 NULL, /* FIXME: i18n: */
2241 &setlist, &showlist);
10325bc5 2242#endif
09280ddf 2243
5bf193a2
AC
2244 add_setshow_boolean_cmd ("new-console", class_support, &new_console, _("\
2245Set creation of new console when creating child process."), _("\
2246Show creation of new console when creating child process."), NULL,
2247 NULL,
2248 NULL, /* FIXME: i18n: */
2249 &setlist, &showlist);
2250
2251 add_setshow_boolean_cmd ("new-group", class_support, &new_group, _("\
2252Set creation of new group when creating child process."), _("\
2253Show creation of new group when creating child process."), NULL,
2254 NULL,
2255 NULL, /* FIXME: i18n: */
2256 &setlist, &showlist);
2257
2258 add_setshow_boolean_cmd ("debugexec", class_support, &debug_exec, _("\
2259Set whether to display execution in child process."), _("\
2260Show whether to display execution in child process."), NULL,
2261 NULL,
2262 NULL, /* FIXME: i18n: */
2263 &setlist, &showlist);
2264
2265 add_setshow_boolean_cmd ("debugevents", class_support, &debug_events, _("\
2266Set whether to display kernel events in child process."), _("\
2267Show whether to display kernel events in child process."), NULL,
2268 NULL,
2269 NULL, /* FIXME: i18n: */
2270 &setlist, &showlist);
2271
2272 add_setshow_boolean_cmd ("debugmemory", class_support, &debug_memory, _("\
2273Set whether to display memory accesses in child process."), _("\
2274Show whether to display memory accesses in child process."), NULL,
2275 NULL,
2276 NULL, /* FIXME: i18n: */
2277 &setlist, &showlist);
2278
2279 add_setshow_boolean_cmd ("debugexceptions", class_support,
2280 &debug_exceptions, _("\
2281Set whether to display kernel exceptions in child process."), _("\
2282Show whether to display kernel exceptions in child process."), NULL,
2283 NULL,
2284 NULL, /* FIXME: i18n: */
2285 &setlist, &showlist);
1ef980b9 2286
c1748f97 2287 add_prefix_cmd ("w32", class_info, info_w32_command,
1bedd215 2288 _("Print information specific to Win32 debugging."),
baa93fa6 2289 &info_w32_cmdlist, "info w32 ", 0, &infolist);
c1748f97
PM
2290
2291 add_cmd ("selector", class_info, display_selectors,
1a966eab 2292 _("Display selectors infos."),
c1748f97 2293 &info_w32_cmdlist);
dc05df57
CF
2294 add_target (&windows_ops);
2295 deprecated_init_ui_hook = set_windows_aliases;
24e60978 2296}
3cee93ac 2297
fa4ba8da
PM
2298/* Hardware watchpoint support, adapted from go32-nat.c code. */
2299
2300/* Pass the address ADDR to the inferior in the I'th debug register.
2301 Here we just store the address in dr array, the registers will be
dc05df57 2302 actually set up when windows_continue is called. */
9bb9e8ad 2303static void
fa4ba8da
PM
2304cygwin_set_dr (int i, CORE_ADDR addr)
2305{
2306 if (i < 0 || i > 3)
2307 internal_error (__FILE__, __LINE__,
e2e0b3e5 2308 _("Invalid register %d in cygwin_set_dr.\n"), i);
41b4aadc 2309 dr[i] = addr;
fa4ba8da
PM
2310 debug_registers_changed = 1;
2311 debug_registers_used = 1;
2312}
2313
2314/* Pass the value VAL to the inferior in the DR7 debug control
2315 register. Here we just store the address in D_REGS, the watchpoint
dc05df57 2316 will be actually set up in windows_wait. */
9bb9e8ad
PM
2317static void
2318cygwin_set_dr7 (unsigned long val)
fa4ba8da 2319{
9bb9e8ad 2320 dr[7] = (CORE_ADDR) val;
fa4ba8da
PM
2321 debug_registers_changed = 1;
2322 debug_registers_used = 1;
2323}
2324
2325/* Get the value of the DR6 debug status register from the inferior.
2326 Here we just return the value stored in dr[6]
2327 by the last call to thread_rec for current_event.dwThreadId id. */
9bb9e8ad 2328static unsigned long
fa4ba8da
PM
2329cygwin_get_dr6 (void)
2330{
9bb9e8ad 2331 return (unsigned long) dr[6];
fa4ba8da
PM
2332}
2333
2dc38344 2334/* Determine if the thread referenced by "ptid" is alive
3cee93ac 2335 by "polling" it. If WaitForSingleObject returns WAIT_OBJECT_0
2dc38344 2336 it means that the thread has died. Otherwise it is assumed to be alive. */
3cee93ac 2337static int
28439f5e 2338windows_thread_alive (struct target_ops *ops, ptid_t ptid)
3cee93ac 2339{
2dc38344
PA
2340 int tid;
2341
2342 gdb_assert (ptid_get_tid (ptid) != 0);
2343 tid = ptid_get_tid (ptid);
39f77062 2344
2dc38344 2345 return WaitForSingleObject (thread_rec (tid, FALSE)->h, 0) == WAIT_OBJECT_0 ?
3a4b77d8 2346 FALSE : TRUE;
3cee93ac
CF
2347}
2348
2a3d5645
CF
2349void
2350_initialize_check_for_gdb_ini (void)
2351{
2352 char *homedir;
2353 if (inhibit_gdbinit)
2354 return;
2355
2356 homedir = getenv ("HOME");
2357 if (homedir)
2358 {
2359 char *p;
2360 char *oldini = (char *) alloca (strlen (homedir) +
2361 sizeof ("/gdb.ini"));
2362 strcpy (oldini, homedir);
2363 p = strchr (oldini, '\0');
2364 if (p > oldini && p[-1] != '/')
2365 *p++ = '/';
2366 strcpy (p, "gdb.ini");
2367 if (access (oldini, 0) == 0)
2368 {
2369 int len = strlen (oldini);
2370 char *newini = alloca (len + 1);
dfe7f3ac 2371 sprintf (newini, "%.*s.gdbinit",
58fa08f0 2372 (int) (len - (sizeof ("gdb.ini") - 1)), oldini);
8a3fe4f8 2373 warning (_("obsolete '%s' found. Rename to '%s'."), oldini, newini);
2a3d5645
CF
2374 }
2375 }
2376}
33605d39 2377
2b008701
CF
2378/* Define dummy functions which always return error for the rare cases where
2379 these functions could not be found. */
2380static BOOL WINAPI
2381bad_DebugActiveProcessStop (DWORD w)
2382{
2383 return FALSE;
2384}
2385static BOOL WINAPI
2386bad_DebugBreakProcess (HANDLE w)
2387{
2388 return FALSE;
2389}
2390static BOOL WINAPI
2391bad_DebugSetProcessKillOnExit (BOOL w)
2392{
2393 return FALSE;
2394}
2395static BOOL WINAPI
2396bad_EnumProcessModules (HANDLE w, HMODULE *x, DWORD y, LPDWORD z)
2397{
2398 return FALSE;
2399}
2400static DWORD WINAPI
2401bad_GetModuleFileNameExA (HANDLE w, HMODULE x, LPSTR y, DWORD z)
2402{
2403 return 0;
2404}
2405static BOOL WINAPI
2406bad_GetModuleInformation (HANDLE w, HMODULE x, LPMODULEINFO y, DWORD z)
2407{
2408 return FALSE;
2409}
2410
418c6cb3
CF
2411static BOOL WINAPI
2412bad_OpenProcessToken (HANDLE w, DWORD x, PHANDLE y)
2413{
2414 return FALSE;
2415}
2416
2b008701
CF
2417/* Load any functions which may not be available in ancient versions
2418 of Windows. */
33605d39 2419void
2b008701 2420_initialize_loadable (void)
33605d39 2421{
2b008701
CF
2422 HMODULE hm = NULL;
2423
2424 hm = LoadLibrary ("kernel32.dll");
2425 if (hm)
33605d39 2426 {
2b008701
CF
2427 dyn_DebugActiveProcessStop = (void *)
2428 GetProcAddress (hm, "DebugActiveProcessStop");
2429 dyn_DebugBreakProcess = (void *)
2430 GetProcAddress (hm, "DebugBreakProcess");
2431 dyn_DebugSetProcessKillOnExit = (void *)
2432 GetProcAddress (hm, "DebugSetProcessKillOnExit");
2433 }
33605d39 2434
2b008701
CF
2435 /* Set variables to dummy versions of these processes if the function
2436 wasn't found in kernel32.dll. */
2437 if (!dyn_DebugBreakProcess)
2438 dyn_DebugBreakProcess = bad_DebugBreakProcess;
2439 if (!dyn_DebugActiveProcessStop || !dyn_DebugSetProcessKillOnExit)
2440 {
2441 dyn_DebugActiveProcessStop = bad_DebugActiveProcessStop;
2442 dyn_DebugSetProcessKillOnExit = bad_DebugSetProcessKillOnExit;
2443 }
33605d39 2444
2b008701
CF
2445 /* Load optional functions used for retrieving filename information
2446 associated with the currently debugged process or its dlls. */
2447 hm = LoadLibrary ("psapi.dll");
2448 if (hm)
2449 {
2450 dyn_EnumProcessModules = (void *)
2451 GetProcAddress (hm, "EnumProcessModules");
2452 dyn_GetModuleInformation = (void *)
2453 GetProcAddress (hm, "GetModuleInformation");
2454 dyn_GetModuleFileNameExA = (void *)
2455 GetProcAddress (hm, "GetModuleFileNameExA");
33605d39
CF
2456 }
2457
2b008701
CF
2458 if (!dyn_EnumProcessModules || !dyn_GetModuleInformation || !dyn_GetModuleFileNameExA)
2459 {
2460 /* Set variables to dummy versions of these processes if the function
2461 wasn't found in psapi.dll. */
2462 dyn_EnumProcessModules = bad_EnumProcessModules;
2463 dyn_GetModuleInformation = bad_GetModuleInformation;
2464 dyn_GetModuleFileNameExA = bad_GetModuleFileNameExA;
2465 /* This will probably fail on Windows 9x/Me. Let the user know that we're
2466 missing some functionality. */
418c6cb3
CF
2467 warning(_("cannot automatically find executable file or library to read symbols.\nUse \"file\" or \"dll\" command to load executable/libraries directly."));
2468 }
2469
2470 hm = LoadLibrary ("advapi32.dll");
2471 if (hm)
2472 {
2473 dyn_OpenProcessToken = (void *)
2474 GetProcAddress (hm, "OpenProcessToken");
2475 dyn_LookupPrivilegeValueA = (void *)
2476 GetProcAddress (hm, "LookupPrivilegeValueA");
2477 dyn_AdjustTokenPrivileges = (void *)
2478 GetProcAddress (hm, "AdjustTokenPrivileges");
2479 /* Only need to set one of these since if OpenProcessToken fails nothing
2480 else is needed. */
2481 if (!dyn_OpenProcessToken || !dyn_LookupPrivilegeValueA || !dyn_AdjustTokenPrivileges)
2482 dyn_OpenProcessToken = bad_OpenProcessToken;
2b008701 2483 }
33605d39 2484}
This page took 1.36773 seconds and 4 git commands to generate.