* target.c (update_current_target): Call setup_target_debug.
[deliverable/binutils-gdb.git] / gdb / win32-nat.c
CommitLineData
c906108c 1/* Target-vector operations for controlling win32 child processes, for GDB.
0a65a603 2
281b533b 3 Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
6aba47ca 4 2005, 2006, 2007 Free Software Foundation, Inc.
0a65a603 5
e6433c28 6 Contributed by Cygnus Solutions, A Red Hat Company.
c906108c
SS
7
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
c906108c
SS
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
c906108c
SS
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/>. */
c906108c 22
dfe7f3ac 23/* Originally by Steve Chamberlain, sac@cygnus.com */
c906108c
SS
24
25/* We assume we're being built with and will be used for cygwin. */
26
27#include "defs.h"
28#include "frame.h" /* required by inferior.h */
29#include "inferior.h"
30#include "target.h"
60250e8b 31#include "exceptions.h"
c906108c
SS
32#include "gdbcore.h"
33#include "command.h"
fa58ee11 34#include "completer.h"
4e052eda 35#include "regcache.h"
2a3d5645 36#include "top.h"
403d9909
CF
37#include <signal.h>
38#include <sys/types.h>
39#include <fcntl.h>
40#include <stdlib.h>
41#include <windows.h>
42#include <imagehlp.h>
43#include <sys/cygwin.h>
a244bdca 44#include <signal.h>
c906108c
SS
45
46#include "buildsym.h"
47#include "symfile.h"
48#include "objfiles.h"
de1b3c3d 49#include "gdb_obstack.h"
c906108c
SS
50#include "gdb_string.h"
51#include "gdbthread.h"
52#include "gdbcmd.h"
53#include <sys/param.h>
c2d11a7d 54#include <unistd.h>
4646aa9d 55#include "exec.h"
3ee6f623 56#include "solist.h"
3cb8e7f6 57#include "solib.h"
de1b3c3d 58#include "xml-support.h"
c906108c 59
6c7de422
MK
60#include "i386-tdep.h"
61#include "i387-tdep.h"
62
de1b3c3d
PA
63#include "i386-cygwin-tdep.h"
64
3ee6f623 65static struct target_ops win32_ops;
3ee6f623 66
a244bdca
CF
67/* The starting and ending address of the cygwin1.dll text segment. */
68static bfd_vma cygwin_load_start;
69static bfd_vma cygwin_load_end;
70
71static int have_saved_context; /* True if we've saved context from a cygwin signal. */
72static CONTEXT saved_context; /* Containes the saved context from a cygwin signal. */
73
7a292a7a
SS
74/* If we're not using the old Cygwin header file set, define the
75 following which never should have been in the generic Win32 API
76 headers in the first place since they were our own invention... */
77#ifndef _GNU_H_WINDOWS_H
9d3789f7 78enum
8e860359
CF
79 {
80 FLAG_TRACE_BIT = 0x100,
81 CONTEXT_DEBUGGER = (CONTEXT_FULL | CONTEXT_FLOATING_POINT)
82 };
7a292a7a 83#endif
8e860359
CF
84#include <sys/procfs.h>
85#include <psapi.h>
7a292a7a 86
fa4ba8da
PM
87#define CONTEXT_DEBUGGER_DR CONTEXT_DEBUGGER | CONTEXT_DEBUG_REGISTERS \
88 | CONTEXT_EXTENDED_REGISTERS
97da3b20 89
fa4ba8da 90static unsigned dr[8];
87a45c96
CF
91static int debug_registers_changed;
92static int debug_registers_used;
97da3b20 93
c906108c
SS
94/* The string sent by cygwin when it processes a signal.
95 FIXME: This should be in a cygwin include file. */
3929abe9
CF
96#ifndef _CYGWIN_SIGNAL_STRING
97#define _CYGWIN_SIGNAL_STRING "cYgSiGw00f"
98#endif
c906108c 99
29fe111d 100#define CHECK(x) check (x, __FILE__,__LINE__)
dfe7f3ac 101#define DEBUG_EXEC(x) if (debug_exec) printf_unfiltered x
4e52d31c
PM
102#define DEBUG_EVENTS(x) if (debug_events) printf_unfiltered x
103#define DEBUG_MEM(x) if (debug_memory) printf_unfiltered x
104#define DEBUG_EXCEPT(x) if (debug_exceptions) printf_unfiltered x
c906108c 105
3ee6f623
CF
106static void win32_stop (void);
107static int win32_win32_thread_alive (ptid_t);
108static void win32_kill_inferior (void);
c906108c 109
7393af7c
PM
110static enum target_signal last_sig = TARGET_SIGNAL_0;
111/* Set if a signal was received from the debugged process */
112
c906108c
SS
113/* Thread information structure used to track information that is
114 not available in gdb's thread structure. */
115typedef struct thread_info_struct
c5aa993b
JM
116 {
117 struct thread_info_struct *next;
118 DWORD id;
119 HANDLE h;
120 char *name;
121 int suspend_count;
3ade5333 122 int reload_context;
c5aa993b 123 CONTEXT context;
c2d11a7d 124 STACKFRAME sf;
8e860359
CF
125 }
126thread_info;
c2d11a7d 127
29fe111d 128static thread_info thread_head;
c906108c 129
c906108c
SS
130/* The process and thread handles for the above context. */
131
132static DEBUG_EVENT current_event; /* The current debug event from
133 WaitForDebugEvent */
134static HANDLE current_process_handle; /* Currently executing process */
135static thread_info *current_thread; /* Info on currently selected thread */
349b409f 136static DWORD main_thread_id; /* Thread ID of the main thread */
c906108c
SS
137
138/* Counts of things. */
139static int exception_count = 0;
140static int event_count = 0;
dfe7f3ac 141static int saw_create;
c906108c
SS
142
143/* User options. */
144static int new_console = 0;
09280ddf 145static int cygwin_exceptions = 0;
c2d11a7d 146static int new_group = 1;
dfe7f3ac
CF
147static int debug_exec = 0; /* show execution */
148static int debug_events = 0; /* show events from kernel */
149static int debug_memory = 0; /* show target memory accesses */
c906108c 150static int debug_exceptions = 0; /* show target exceptions */
dfe7f3ac
CF
151static int useshell = 0; /* use shell for subprocesses */
152
c906108c
SS
153/* This vector maps GDB's idea of a register's number into an address
154 in the win32 exception context vector.
155
156 It also contains the bit mask needed to load the register in question.
157
158 One day we could read a reg, we could inspect the context we
159 already have loaded, if it doesn't have the bit set that we need,
160 we read that set of registers in using GetThreadContext. If the
161 context already contains what we need, we just unpack it. Then to
162 write a register, first we have to ensure that the context contains
163 the other regs of the group, and then we copy the info in and set
164 out bit. */
165
166#define context_offset(x) ((int)&(((CONTEXT *)NULL)->x))
167static const int mappings[] =
168{
c5aa993b
JM
169 context_offset (Eax),
170 context_offset (Ecx),
171 context_offset (Edx),
172 context_offset (Ebx),
173 context_offset (Esp),
174 context_offset (Ebp),
175 context_offset (Esi),
176 context_offset (Edi),
177 context_offset (Eip),
178 context_offset (EFlags),
179 context_offset (SegCs),
180 context_offset (SegSs),
181 context_offset (SegDs),
182 context_offset (SegEs),
183 context_offset (SegFs),
184 context_offset (SegGs),
185 context_offset (FloatSave.RegisterArea[0 * 10]),
186 context_offset (FloatSave.RegisterArea[1 * 10]),
187 context_offset (FloatSave.RegisterArea[2 * 10]),
188 context_offset (FloatSave.RegisterArea[3 * 10]),
189 context_offset (FloatSave.RegisterArea[4 * 10]),
190 context_offset (FloatSave.RegisterArea[5 * 10]),
191 context_offset (FloatSave.RegisterArea[6 * 10]),
192 context_offset (FloatSave.RegisterArea[7 * 10]),
c2d11a7d
JM
193 context_offset (FloatSave.ControlWord),
194 context_offset (FloatSave.StatusWord),
195 context_offset (FloatSave.TagWord),
196 context_offset (FloatSave.ErrorSelector),
197 context_offset (FloatSave.ErrorOffset),
198 context_offset (FloatSave.DataSelector),
199 context_offset (FloatSave.DataOffset),
ed9a39eb 200 context_offset (FloatSave.ErrorSelector)
97da3b20 201 /* XMM0-7 */ ,
441532d7
PM
202 context_offset (ExtendedRegisters[10*16]),
203 context_offset (ExtendedRegisters[11*16]),
204 context_offset (ExtendedRegisters[12*16]),
205 context_offset (ExtendedRegisters[13*16]),
206 context_offset (ExtendedRegisters[14*16]),
207 context_offset (ExtendedRegisters[15*16]),
208 context_offset (ExtendedRegisters[16*16]),
209 context_offset (ExtendedRegisters[17*16]),
210 /* MXCSR */
211 context_offset (ExtendedRegisters[24])
c906108c
SS
212};
213
ed9a39eb
JM
214#undef context_offset
215
c906108c
SS
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
225static const struct xlate_exception
226 xlate[] =
227{
228 {EXCEPTION_ACCESS_VIOLATION, TARGET_SIGNAL_SEGV},
229 {STATUS_STACK_OVERFLOW, TARGET_SIGNAL_SEGV},
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},
c906108c
SS
234 {-1, -1}};
235
fa4ba8da
PM
236static void
237check (BOOL ok, const char *file, int line)
238{
239 if (!ok)
dfe7f3ac 240 printf_filtered ("error return %s:%d was %lu\n", file, line,
fa4ba8da
PM
241 GetLastError ());
242}
243
c906108c
SS
244/* Find a thread record given a thread id.
245 If get_context then also retrieve the context for this
246 thread. */
247static thread_info *
248thread_rec (DWORD id, int get_context)
249{
250 thread_info *th;
251
c5aa993b 252 for (th = &thread_head; (th = th->next) != NULL;)
c906108c
SS
253 if (th->id == id)
254 {
255 if (!th->suspend_count && get_context)
256 {
8a892701 257 if (get_context > 0 && id != current_event.dwThreadId)
c906108c
SS
258 th->suspend_count = SuspendThread (th->h) + 1;
259 else if (get_context < 0)
260 th->suspend_count = -1;
3ade5333 261 th->reload_context = 1;
c906108c
SS
262 }
263 return th;
264 }
265
266 return NULL;
267}
268
269/* Add a thread to the thread list */
270static thread_info *
3ee6f623 271win32_add_thread (DWORD id, HANDLE h)
c906108c
SS
272{
273 thread_info *th;
274
275 if ((th = thread_rec (id, FALSE)))
276 return th;
277
3929abe9 278 th = XZALLOC (thread_info);
c906108c
SS
279 th->id = id;
280 th->h = h;
281 th->next = thread_head.next;
282 thread_head.next = th;
39f77062 283 add_thread (pid_to_ptid (id));
dfe7f3ac 284 /* Set the debug registers for the new thread in they are used. */
fa4ba8da
PM
285 if (debug_registers_used)
286 {
287 /* Only change the value of the debug registers. */
288 th->context.ContextFlags = CONTEXT_DEBUG_REGISTERS;
289 CHECK (GetThreadContext (th->h, &th->context));
290 th->context.Dr0 = dr[0];
291 th->context.Dr1 = dr[1];
292 th->context.Dr2 = dr[2];
293 th->context.Dr3 = dr[3];
294 /* th->context.Dr6 = dr[6];
295 FIXME: should we set dr6 also ?? */
296 th->context.Dr7 = dr[7];
297 CHECK (SetThreadContext (th->h, &th->context));
298 th->context.ContextFlags = 0;
299 }
c906108c
SS
300 return th;
301}
302
303/* Clear out any old thread list and reintialize it to a
304 pristine state. */
305static void
3ee6f623 306win32_init_thread_list (void)
c906108c
SS
307{
308 thread_info *th = &thread_head;
309
3ee6f623 310 DEBUG_EVENTS (("gdb: win32_init_thread_list\n"));
c906108c
SS
311 init_thread_list ();
312 while (th->next != NULL)
313 {
314 thread_info *here = th->next;
315 th->next = here->next;
316 (void) CloseHandle (here->h);
b8c9b27d 317 xfree (here);
c906108c 318 }
059198c1 319 thread_head.next = NULL;
c906108c
SS
320}
321
322/* Delete a thread from the list of threads */
323static void
3ee6f623 324win32_delete_thread (DWORD id)
c906108c
SS
325{
326 thread_info *th;
327
328 if (info_verbose)
39f77062
KB
329 printf_unfiltered ("[Deleting %s]\n", target_pid_to_str (pid_to_ptid (id)));
330 delete_thread (pid_to_ptid (id));
c906108c
SS
331
332 for (th = &thread_head;
333 th->next != NULL && th->next->id != id;
334 th = th->next)
335 continue;
336
337 if (th->next != NULL)
338 {
339 thread_info *here = th->next;
340 th->next = here->next;
341 CloseHandle (here->h);
b8c9b27d 342 xfree (here);
c906108c
SS
343 }
344}
345
c906108c 346static void
56be3814 347do_win32_fetch_inferior_registers (struct regcache *regcache, int r)
c906108c 348{
c2d11a7d
JM
349 char *context_offset = ((char *) &current_thread->context) + mappings[r];
350 long l;
6c7de422 351
3ade5333 352 if (!current_thread)
d6dc8049
CF
353 return; /* Windows sometimes uses a non-existent thread id in its
354 events */
3ade5333
CF
355
356 if (current_thread->reload_context)
357 {
cb832706 358#ifdef __COPY_CONTEXT_SIZE
a244bdca
CF
359 if (have_saved_context)
360 {
361 /* Lie about where the program actually is stopped since cygwin has informed us that
362 we should consider the signal to have occurred at another location which is stored
363 in "saved_context. */
364 memcpy (&current_thread->context, &saved_context, __COPY_CONTEXT_SIZE);
365 have_saved_context = 0;
366 }
367 else
cb832706 368#endif
a244bdca
CF
369 {
370 thread_info *th = current_thread;
371 th->context.ContextFlags = CONTEXT_DEBUGGER_DR;
372 GetThreadContext (th->h, &th->context);
373 /* Copy dr values from that thread. */
374 dr[0] = th->context.Dr0;
375 dr[1] = th->context.Dr1;
376 dr[2] = th->context.Dr2;
377 dr[3] = th->context.Dr3;
378 dr[6] = th->context.Dr6;
379 dr[7] = th->context.Dr7;
380 }
3ade5333
CF
381 current_thread->reload_context = 0;
382 }
383
6c7de422
MK
384#define I387_ST0_REGNUM I386_ST0_REGNUM
385
386 if (r == I387_FISEG_REGNUM)
c2d11a7d 387 {
8e860359 388 l = *((long *) context_offset) & 0xffff;
56be3814 389 regcache_raw_supply (regcache, r, (char *) &l);
c2d11a7d 390 }
6c7de422 391 else if (r == I387_FOP_REGNUM)
c2d11a7d 392 {
8e860359 393 l = (*((long *) context_offset) >> 16) & ((1 << 11) - 1);
56be3814 394 regcache_raw_supply (regcache, r, (char *) &l);
c2d11a7d
JM
395 }
396 else if (r >= 0)
56be3814 397 regcache_raw_supply (regcache, r, context_offset);
c906108c
SS
398 else
399 {
f57d151a 400 for (r = 0; r < gdbarch_num_regs (current_gdbarch); r++)
56be3814 401 do_win32_fetch_inferior_registers (regcache, r);
c906108c 402 }
6c7de422
MK
403
404#undef I387_ST0_REGNUM
c906108c
SS
405}
406
407static void
56be3814 408win32_fetch_inferior_registers (struct regcache *regcache, int r)
c906108c 409{
39f77062 410 current_thread = thread_rec (PIDGET (inferior_ptid), TRUE);
d6dc8049
CF
411 /* Check if current_thread exists. Windows sometimes uses a non-existent
412 thread id in its events */
3ade5333 413 if (current_thread)
56be3814 414 do_win32_fetch_inferior_registers (regcache, r);
c906108c
SS
415}
416
417static void
56be3814 418do_win32_store_inferior_registers (const struct regcache *regcache, int r)
c906108c 419{
3ade5333 420 if (!current_thread)
d6dc8049 421 /* Windows sometimes uses a non-existent thread id in its events */;
3ade5333 422 else if (r >= 0)
56be3814 423 regcache_raw_collect (regcache, r,
822c9732 424 ((char *) &current_thread->context) + mappings[r]);
c906108c
SS
425 else
426 {
f57d151a 427 for (r = 0; r < gdbarch_num_regs (current_gdbarch); r++)
56be3814 428 do_win32_store_inferior_registers (regcache, r);
c906108c
SS
429 }
430}
431
432/* Store a new register value into the current thread context */
433static void
56be3814 434win32_store_inferior_registers (struct regcache *regcache, int r)
c906108c 435{
39f77062 436 current_thread = thread_rec (PIDGET (inferior_ptid), TRUE);
d6dc8049
CF
437 /* Check if current_thread exists. Windows sometimes uses a non-existent
438 thread id in its events */
3ade5333 439 if (current_thread)
56be3814 440 do_win32_store_inferior_registers (regcache, r);
c906108c
SS
441}
442
c2d11a7d
JM
443static int psapi_loaded = 0;
444static HMODULE psapi_module_handle = NULL;
8e860359
CF
445static BOOL WINAPI (*psapi_EnumProcessModules) (HANDLE, HMODULE *, DWORD, LPDWORD) = NULL;
446static BOOL WINAPI (*psapi_GetModuleInformation) (HANDLE, HMODULE, LPMODULEINFO, DWORD) = NULL;
447static DWORD WINAPI (*psapi_GetModuleFileNameExA) (HANDLE, HMODULE, LPSTR, DWORD) = NULL;
c2d11a7d 448
3ee6f623 449static int
8e860359 450psapi_get_dll_name (DWORD BaseAddress, char *dll_name_ret)
c2d11a7d
JM
451{
452 DWORD len;
453 MODULEINFO mi;
454 int i;
8e860359
CF
455 HMODULE dh_buf[1];
456 HMODULE *DllHandle = dh_buf;
c2d11a7d
JM
457 DWORD cbNeeded;
458 BOOL ok;
459
460 if (!psapi_loaded ||
8e860359
CF
461 psapi_EnumProcessModules == NULL ||
462 psapi_GetModuleInformation == NULL ||
463 psapi_GetModuleFileNameExA == NULL)
c2d11a7d 464 {
8e860359
CF
465 if (psapi_loaded)
466 goto failed;
c2d11a7d
JM
467 psapi_loaded = 1;
468 psapi_module_handle = LoadLibrary ("psapi.dll");
469 if (!psapi_module_handle)
8e860359
CF
470 {
471 /* printf_unfiltered ("error loading psapi.dll: %u", GetLastError ()); */
472 goto failed;
473 }
474 psapi_EnumProcessModules = GetProcAddress (psapi_module_handle, "EnumProcessModules");
c2d11a7d
JM
475 psapi_GetModuleInformation = GetProcAddress (psapi_module_handle, "GetModuleInformation");
476 psapi_GetModuleFileNameExA = (void *) GetProcAddress (psapi_module_handle,
8e860359
CF
477 "GetModuleFileNameExA");
478 if (psapi_EnumProcessModules == NULL ||
479 psapi_GetModuleInformation == NULL ||
480 psapi_GetModuleFileNameExA == NULL)
c2d11a7d
JM
481 goto failed;
482 }
483
484 cbNeeded = 0;
485 ok = (*psapi_EnumProcessModules) (current_process_handle,
8e860359
CF
486 DllHandle,
487 sizeof (HMODULE),
488 &cbNeeded);
c2d11a7d
JM
489
490 if (!ok || !cbNeeded)
491 goto failed;
492
8e860359 493 DllHandle = (HMODULE *) alloca (cbNeeded);
c2d11a7d
JM
494 if (!DllHandle)
495 goto failed;
496
497 ok = (*psapi_EnumProcessModules) (current_process_handle,
8e860359
CF
498 DllHandle,
499 cbNeeded,
500 &cbNeeded);
c2d11a7d
JM
501 if (!ok)
502 goto failed;
503
29fe111d 504 for (i = 0; i < (int) (cbNeeded / sizeof (HMODULE)); i++)
c2d11a7d
JM
505 {
506 if (!(*psapi_GetModuleInformation) (current_process_handle,
8e860359
CF
507 DllHandle[i],
508 &mi,
509 sizeof (mi)))
8a3fe4f8 510 error (_("Can't get module info"));
c2d11a7d
JM
511
512 len = (*psapi_GetModuleFileNameExA) (current_process_handle,
8e860359
CF
513 DllHandle[i],
514 dll_name_ret,
515 MAX_PATH);
c2d11a7d 516 if (len == 0)
8a3fe4f8 517 error (_("Error getting dll name: %u."), (unsigned) GetLastError ());
c2d11a7d
JM
518
519 if ((DWORD) (mi.lpBaseOfDll) == BaseAddress)
520 return 1;
521 }
522
523failed:
524 dll_name_ret[0] = '\0';
525 return 0;
526}
527
450005e7
CF
528/* Encapsulate the information required in a call to
529 symbol_file_add_args */
8a892701
CF
530struct safe_symbol_file_add_args
531{
532 char *name;
533 int from_tty;
534 struct section_addr_info *addrs;
535 int mainline;
536 int flags;
7c5c87c0 537 struct ui_file *err, *out;
8a892701
CF
538 struct objfile *ret;
539};
540
02e423b9 541/* Maintain a linked list of "so" information. */
3ee6f623 542struct lm_info
02e423b9 543{
02e423b9 544 DWORD load_addr;
3ee6f623
CF
545};
546
547static struct so_list solib_start, *solib_end;
02e423b9 548
450005e7
CF
549/* Call symbol_file_add with stderr redirected. We don't care if there
550 are errors. */
8a892701
CF
551static int
552safe_symbol_file_add_stub (void *argv)
553{
3ee6f623
CF
554#define p ((struct safe_symbol_file_add_args *) argv)
555 struct so_list *so = &solib_start;
02e423b9 556
8a892701
CF
557 p->ret = symbol_file_add (p->name, p->from_tty, p->addrs, p->mainline, p->flags);
558 return !!p->ret;
559#undef p
560}
561
450005e7 562/* Restore gdb's stderr after calling symbol_file_add */
8a892701 563static void
7c5c87c0 564safe_symbol_file_add_cleanup (void *p)
8a892701 565{
8e860359 566#define sp ((struct safe_symbol_file_add_args *)p)
450005e7 567 gdb_flush (gdb_stderr);
7c5c87c0 568 gdb_flush (gdb_stdout);
d3ff4a77 569 ui_file_delete (gdb_stderr);
7c5c87c0 570 ui_file_delete (gdb_stdout);
d3ff4a77 571 gdb_stderr = sp->err;
9d3789f7 572 gdb_stdout = sp->out;
8e860359 573#undef sp
8a892701
CF
574}
575
450005e7 576/* symbol_file_add wrapper that prevents errors from being displayed. */
8a892701
CF
577static struct objfile *
578safe_symbol_file_add (char *name, int from_tty,
579 struct section_addr_info *addrs,
580 int mainline, int flags)
8a892701
CF
581{
582 struct safe_symbol_file_add_args p;
583 struct cleanup *cleanup;
584
7c5c87c0 585 cleanup = make_cleanup (safe_symbol_file_add_cleanup, &p);
8a892701 586
7c5c87c0
CF
587 p.err = gdb_stderr;
588 p.out = gdb_stdout;
450005e7 589 gdb_flush (gdb_stderr);
7c5c87c0 590 gdb_flush (gdb_stdout);
d3ff4a77 591 gdb_stderr = ui_file_new ();
7c5c87c0 592 gdb_stdout = ui_file_new ();
8a892701
CF
593 p.name = name;
594 p.from_tty = from_tty;
595 p.addrs = addrs;
596 p.mainline = mainline;
597 p.flags = flags;
598 catch_errors (safe_symbol_file_add_stub, &p, "", RETURN_MASK_ERROR);
599
600 do_cleanups (cleanup);
601 return p.ret;
602}
603
de1b3c3d
PA
604static struct so_list *
605win32_make_so (const char *name, DWORD load_addr)
8e860359 606{
3ee6f623 607 struct so_list *so;
3f8ad85b
CF
608 char buf[MAX_PATH + 1];
609 char cwd[MAX_PATH + 1];
610 char *p;
611 WIN32_FIND_DATA w32_fd;
612 HANDLE h = FindFirstFile(name, &w32_fd);
5633f842 613 MEMORY_BASIC_INFORMATION m;
3f8ad85b 614
6badb179
CF
615 if (h == INVALID_HANDLE_VALUE)
616 strcpy (buf, name);
617 else
3f8ad85b 618 {
c914e0cc
CF
619 FindClose (h);
620 strcpy (buf, name);
621 if (GetCurrentDirectory (MAX_PATH + 1, cwd))
622 {
623 p = strrchr (buf, '\\');
624 if (p)
625 p[1] = '\0';
626 SetCurrentDirectory (buf);
627 GetFullPathName (w32_fd.cFileName, MAX_PATH, buf, &p);
628 SetCurrentDirectory (cwd);
629 }
3f8ad85b
CF
630 }
631
3ee6f623
CF
632 if (strcasecmp (buf, "ntdll.dll") == 0)
633 {
634 GetSystemDirectory (buf, sizeof (buf));
635 strcat (buf, "\\ntdll.dll");
636 }
3929abe9 637 so = XZALLOC (struct so_list);
3ee6f623
CF
638 so->lm_info = (struct lm_info *) xmalloc (sizeof (struct lm_info));
639 so->lm_info->load_addr = load_addr;
3cb8e7f6 640 cygwin_conv_to_posix_path (buf, so->so_name);
de1b3c3d
PA
641 strcpy (so->so_original_name, name);
642
643 /* Record cygwin1.dll .text start/end. */
644 p = strchr (so->so_name, '\0') - (sizeof ("/cygwin1.dll") - 1);
645 if (p >= so->so_name && strcasecmp (p, "/cygwin1.dll") == 0)
646 {
647 bfd *abfd;
648 asection *text = NULL;
649 CORE_ADDR text_vma;
8e860359 650
de1b3c3d 651 abfd = bfd_openr (name, "pei-i386");
a244bdca 652
de1b3c3d
PA
653 if (!abfd)
654 return so;
655
656 if (bfd_check_format (abfd, bfd_object))
657 text = bfd_get_section_by_name (abfd, ".text");
658
659 if (!text)
660 {
661 bfd_close (abfd);
662 return so;
663 }
664
665 /* The symbols in a dll are offset by 0x1000, which is the the
666 offset from 0 of the first byte in an image - because of the
667 file header and the section alignment. */
668 cygwin_load_start = load_addr + 0x1000;
669 cygwin_load_end = cygwin_load_start + bfd_section_size (abfd, text);
670
671 bfd_close (abfd);
672 }
673
674 return so;
8e860359
CF
675}
676
3ee6f623 677static char *
dfe7f3ac
CF
678get_image_name (HANDLE h, void *address, int unicode)
679{
680 static char buf[(2 * MAX_PATH) + 1];
681 DWORD size = unicode ? sizeof (WCHAR) : sizeof (char);
682 char *address_ptr;
683 int len = 0;
684 char b[2];
685 DWORD done;
686
687 /* Attempt to read the name of the dll that was detected.
688 This is documented to work only when actively debugging
689 a program. It will not work for attached processes. */
690 if (address == NULL)
691 return NULL;
692
dfe7f3ac
CF
693 /* See if we could read the address of a string, and that the
694 address isn't null. */
9f476a01 695 if (!ReadProcessMemory (h, address, &address_ptr, sizeof (address_ptr), &done)
6f17862b 696 || done != sizeof (address_ptr) || !address_ptr)
dfe7f3ac
CF
697 return NULL;
698
699 /* Find the length of the string */
6f17862b
CF
700 while (ReadProcessMemory (h, address_ptr + len++ * size, &b, size, &done)
701 && (b[0] != 0 || b[size - 1] != 0) && done == size)
702 continue;
dfe7f3ac
CF
703
704 if (!unicode)
705 ReadProcessMemory (h, address_ptr, buf, len, &done);
706 else
707 {
708 WCHAR *unicode_address = (WCHAR *) alloca (len * sizeof (WCHAR));
709 ReadProcessMemory (h, address_ptr, unicode_address, len * sizeof (WCHAR),
710 &done);
711
712 WideCharToMultiByte (CP_ACP, 0, unicode_address, len, buf, len, 0, 0);
713 }
714
715 return buf;
716}
717
c906108c
SS
718/* Wait for child to do something. Return pid of child, or -1 in case
719 of error; store status through argument pointer OURSTATUS. */
c906108c 720static int
0a65a603 721handle_load_dll (void *dummy)
c906108c 722{
c5aa993b 723 LOAD_DLL_DEBUG_INFO *event = &current_event.u.LoadDll;
c906108c 724 char dll_buf[MAX_PATH + 1];
450005e7 725 char *dll_name = NULL;
c906108c 726
c5aa993b 727 dll_buf[0] = dll_buf[sizeof (dll_buf) - 1] = '\0';
c906108c 728
c2d11a7d 729 if (!psapi_get_dll_name ((DWORD) (event->lpBaseOfDll), dll_buf))
8e860359 730 dll_buf[0] = dll_buf[sizeof (dll_buf) - 1] = '\0';
c906108c 731
c2d11a7d 732 dll_name = dll_buf;
c906108c 733
dfe7f3ac 734 if (*dll_name == '\0')
de1b3c3d
PA
735 dll_name = get_image_name (current_process_handle,
736 event->lpImageName, event->fUnicode);
c906108c
SS
737 if (!dll_name)
738 return 1;
739
de1b3c3d
PA
740 solib_end->next = win32_make_so (dll_name, (DWORD) event->lpBaseOfDll);
741 solib_end = solib_end->next;
450005e7
CF
742
743 return 1;
744}
745
3ee6f623
CF
746static void
747win32_free_so (struct so_list *so)
748{
3ee6f623
CF
749 if (so->lm_info)
750 xfree (so->lm_info);
de1b3c3d 751 xfree (so);
3cb8e7f6
CF
752}
753
d3ff4a77 754static int
0a65a603 755handle_unload_dll (void *dummy)
d3ff4a77 756{
de1b3c3d 757 DWORD lpBaseOfDll = (DWORD) current_event.u.UnloadDll.lpBaseOfDll;
3ee6f623 758 struct so_list *so;
d3ff4a77
CF
759
760 for (so = &solib_start; so->next != NULL; so = so->next)
3ee6f623 761 if (so->next->lm_info->load_addr == lpBaseOfDll)
d3ff4a77 762 {
3ee6f623 763 struct so_list *sodel = so->next;
d3ff4a77
CF
764 so->next = sodel->next;
765 if (!so->next)
766 solib_end = so;
de1b3c3d 767 win32_free_so (sodel);
3929abe9 768 solib_add (NULL, 0, NULL, auto_solib_add);
d3ff4a77
CF
769 return 1;
770 }
3929abe9 771
8a3fe4f8 772 error (_("Error: dll starting at 0x%lx not found."), (DWORD) lpBaseOfDll);
d3ff4a77
CF
773
774 return 0;
775}
776
450005e7 777/* Clear list of loaded DLLs. */
3ee6f623
CF
778static void
779win32_clear_solib (void)
450005e7 780{
450005e7
CF
781 solib_start.next = NULL;
782 solib_end = &solib_start;
450005e7 783}
295732ea 784
450005e7
CF
785/* Load DLL symbol info. */
786void
7470a420 787dll_symbol_command (char *args, int from_tty)
450005e7 788{
8e860359 789 int n;
450005e7 790 dont_repeat ();
8e860359 791
450005e7 792 if (args == NULL)
8a3fe4f8 793 error (_("dll-symbols requires a file name"));
450005e7 794
8e860359
CF
795 n = strlen (args);
796 if (n > 4 && strcasecmp (args + n - 4, ".dll") != 0)
797 {
798 char *newargs = (char *) alloca (n + 4 + 1);
799 strcpy (newargs, args);
800 strcat (newargs, ".dll");
801 args = newargs;
802 }
803
7470a420 804 safe_symbol_file_add (args, from_tty, NULL, 0, OBJF_SHARED | OBJF_USERLOADED);
8e860359 805}
450005e7 806
c906108c
SS
807/* Handle DEBUG_STRING output from child process.
808 Cygwin prepends its messages with a "cygwin:". Interpret this as
809 a Cygwin signal. Otherwise just print the string as a warning. */
810static int
811handle_output_debug_string (struct target_waitstatus *ourstatus)
812{
a244bdca
CF
813 char *s = NULL;
814 int retval = 0;
c906108c
SS
815
816 if (!target_read_string
c5aa993b 817 ((CORE_ADDR) current_event.u.DebugString.lpDebugStringData, &s, 1024, 0)
c906108c 818 || !s || !*s)
a244bdca
CF
819 /* nothing to do */;
820 else if (strncmp (s, _CYGWIN_SIGNAL_STRING, sizeof (_CYGWIN_SIGNAL_STRING) - 1) != 0)
c906108c 821 {
ed9a39eb 822 if (strncmp (s, "cYg", 3) != 0)
8a3fe4f8 823 warning (("%s"), s);
c906108c 824 }
cb832706 825#ifdef __COPY_CONTEXT_SIZE
ed9a39eb 826 else
c906108c 827 {
a244bdca
CF
828 /* Got a cygwin signal marker. A cygwin signal is followed by the signal number
829 itself and then optionally followed by the thread id and address to saved context
830 within the DLL. If these are supplied, then the given thread is assumed to have
831 issued the signal and the context from the thread is assumed to be stored at the
832 given address in the inferior. Tell gdb to treat this like a real signal. */
c906108c 833 char *p;
3929abe9 834 int sig = strtol (s + sizeof (_CYGWIN_SIGNAL_STRING) - 1, &p, 0);
a244bdca 835 int gotasig = target_signal_from_host (sig);
7a292a7a
SS
836 ourstatus->value.sig = gotasig;
837 if (gotasig)
a244bdca
CF
838 {
839 LPCVOID x;
840 DWORD n;
841 ourstatus->kind = TARGET_WAITKIND_STOPPED;
842 retval = strtoul (p, &p, 0);
843 if (!retval)
844 retval = main_thread_id;
845 else if ((x = (LPCVOID) strtoul (p, &p, 0))
846 && ReadProcessMemory (current_process_handle, x,
847 &saved_context, __COPY_CONTEXT_SIZE, &n)
848 && n == __COPY_CONTEXT_SIZE)
849 have_saved_context = 1;
850 current_event.dwThreadId = retval;
851 }
c906108c 852 }
cb832706 853#endif
c906108c 854
a244bdca
CF
855 if (s)
856 xfree (s);
857 return retval;
c906108c
SS
858}
859
c1748f97
PM
860static int
861display_selector (HANDLE thread, DWORD sel)
862{
863 LDT_ENTRY info;
864 if (GetThreadSelectorEntry (thread, sel, &info))
865 {
866 int base, limit;
867 printf_filtered ("0x%03lx: ", sel);
868 if (!info.HighWord.Bits.Pres)
baa93fa6
CF
869 {
870 puts_filtered ("Segment not present\n");
871 return 0;
872 }
c1748f97
PM
873 base = (info.HighWord.Bits.BaseHi << 24) +
874 (info.HighWord.Bits.BaseMid << 16)
875 + info.BaseLow;
876 limit = (info.HighWord.Bits.LimitHi << 16) + info.LimitLow;
877 if (info.HighWord.Bits.Granularity)
caad7706 878 limit = (limit << 12) | 0xfff;
c1748f97
PM
879 printf_filtered ("base=0x%08x limit=0x%08x", base, limit);
880 if (info.HighWord.Bits.Default_Big)
baa93fa6 881 puts_filtered(" 32-bit ");
c1748f97 882 else
baa93fa6 883 puts_filtered(" 16-bit ");
c1748f97
PM
884 switch ((info.HighWord.Bits.Type & 0xf) >> 1)
885 {
886 case 0:
baa93fa6
CF
887 puts_filtered ("Data (Read-Only, Exp-up");
888 break;
c1748f97 889 case 1:
baa93fa6
CF
890 puts_filtered ("Data (Read/Write, Exp-up");
891 break;
c1748f97 892 case 2:
baa93fa6
CF
893 puts_filtered ("Unused segment (");
894 break;
c1748f97 895 case 3:
baa93fa6
CF
896 puts_filtered ("Data (Read/Write, Exp-down");
897 break;
c1748f97 898 case 4:
baa93fa6
CF
899 puts_filtered ("Code (Exec-Only, N.Conf");
900 break;
c1748f97 901 case 5:
baa93fa6 902 puts_filtered ("Code (Exec/Read, N.Conf");
c1748f97
PM
903 break;
904 case 6:
baa93fa6 905 puts_filtered ("Code (Exec-Only, Conf");
c1748f97
PM
906 break;
907 case 7:
baa93fa6 908 puts_filtered ("Code (Exec/Read, Conf");
c1748f97
PM
909 break;
910 default:
911 printf_filtered ("Unknown type 0x%x",info.HighWord.Bits.Type);
912 }
913 if ((info.HighWord.Bits.Type & 0x1) == 0)
baa93fa6 914 puts_filtered(", N.Acc");
c1748f97
PM
915 puts_filtered (")\n");
916 if ((info.HighWord.Bits.Type & 0x10) == 0)
917 puts_filtered("System selector ");
918 printf_filtered ("Priviledge level = %d. ", info.HighWord.Bits.Dpl);
919 if (info.HighWord.Bits.Granularity)
baa93fa6 920 puts_filtered ("Page granular.\n");
c1748f97
PM
921 else
922 puts_filtered ("Byte granular.\n");
923 return 1;
924 }
925 else
926 {
927 printf_filtered ("Invalid selector 0x%lx.\n",sel);
928 return 0;
929 }
930}
931
932static void
933display_selectors (char * args, int from_tty)
934{
935 if (!current_thread)
936 {
937 puts_filtered ("Impossible to display selectors now.\n");
938 return;
939 }
940 if (!args)
941 {
942
943 puts_filtered ("Selector $cs\n");
944 display_selector (current_thread->h,
baa93fa6 945 current_thread->context.SegCs);
c1748f97
PM
946 puts_filtered ("Selector $ds\n");
947 display_selector (current_thread->h,
baa93fa6 948 current_thread->context.SegDs);
c1748f97
PM
949 puts_filtered ("Selector $es\n");
950 display_selector (current_thread->h,
baa93fa6 951 current_thread->context.SegEs);
c1748f97
PM
952 puts_filtered ("Selector $ss\n");
953 display_selector (current_thread->h,
baa93fa6 954 current_thread->context.SegSs);
c1748f97
PM
955 puts_filtered ("Selector $fs\n");
956 display_selector (current_thread->h,
957 current_thread->context.SegFs);
958 puts_filtered ("Selector $gs\n");
959 display_selector (current_thread->h,
baa93fa6 960 current_thread->context.SegGs);
c1748f97
PM
961 }
962 else
963 {
964 int sel;
965 sel = parse_and_eval_long (args);
966 printf_filtered ("Selector \"%s\"\n",args);
967 display_selector (current_thread->h, sel);
968 }
969}
970
971static struct cmd_list_element *info_w32_cmdlist = NULL;
972
973static void
974info_w32_command (char *args, int from_tty)
975{
976 help_list (info_w32_cmdlist, "info w32 ", class_info, gdb_stdout);
977}
978
979
7393af7c 980#define DEBUG_EXCEPTION_SIMPLE(x) if (debug_exceptions) \
4e52d31c 981 printf_unfiltered ("gdb: Target exception %s at 0x%08lx\n", x, \
7393af7c
PM
982 (DWORD) current_event.u.Exception.ExceptionRecord.ExceptionAddress)
983
c906108c 984static int
450005e7 985handle_exception (struct target_waitstatus *ourstatus)
c906108c 986{
c906108c 987 thread_info *th;
29fe111d 988 DWORD code = current_event.u.Exception.ExceptionRecord.ExceptionCode;
c906108c 989
29fe111d 990 ourstatus->kind = TARGET_WAITKIND_STOPPED;
8a892701 991
c906108c
SS
992 /* Record the context of the current thread */
993 th = thread_rec (current_event.dwThreadId, -1);
994
29fe111d 995 switch (code)
c906108c
SS
996 {
997 case EXCEPTION_ACCESS_VIOLATION:
7393af7c
PM
998 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ACCESS_VIOLATION");
999 ourstatus->value.sig = TARGET_SIGNAL_SEGV;
8da8e0b3 1000 {
a244bdca
CF
1001 /* See if the access violation happened within the cygwin DLL itself. Cygwin uses
1002 a kind of exception handling to deal with passed-in invalid addresses. gdb
1003 should not treat these as real SEGVs since they will be silently handled by
1004 cygwin. A real SEGV will (theoretically) be caught by cygwin later in the process
1005 and will be sent as a cygwin-specific-signal. So, ignore SEGVs if they show up
1006 within the text segment of the DLL itself. */
8da8e0b3 1007 char *fn;
a244bdca 1008 bfd_vma addr = (bfd_vma) current_event.u.Exception.ExceptionRecord.ExceptionAddress;
09280ddf 1009 if ((!cygwin_exceptions && (addr >= cygwin_load_start && addr < cygwin_load_end))
a244bdca
CF
1010 || (find_pc_partial_function (addr, &fn, NULL, NULL)
1011 && strncmp (fn, "KERNEL32!IsBad", strlen ("KERNEL32!IsBad")) == 0))
8da8e0b3
CF
1012 return 0;
1013 }
7393af7c
PM
1014 break;
1015 case STATUS_STACK_OVERFLOW:
1016 DEBUG_EXCEPTION_SIMPLE ("STATUS_STACK_OVERFLOW");
c906108c 1017 ourstatus->value.sig = TARGET_SIGNAL_SEGV;
7393af7c
PM
1018 break;
1019 case STATUS_FLOAT_DENORMAL_OPERAND:
1020 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DENORMAL_OPERAND");
1021 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1022 break;
1023 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
1024 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ARRAY_BOUNDS_EXCEEDED");
1025 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1026 break;
1027 case STATUS_FLOAT_INEXACT_RESULT:
1028 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INEXACT_RESULT");
1029 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1030 break;
1031 case STATUS_FLOAT_INVALID_OPERATION:
1032 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INVALID_OPERATION");
1033 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1034 break;
1035 case STATUS_FLOAT_OVERFLOW:
1036 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_OVERFLOW");
1037 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1038 break;
1039 case STATUS_FLOAT_STACK_CHECK:
1040 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_STACK_CHECK");
1041 ourstatus->value.sig = TARGET_SIGNAL_FPE;
c906108c 1042 break;
0d06e24b 1043 case STATUS_FLOAT_UNDERFLOW:
7393af7c
PM
1044 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_UNDERFLOW");
1045 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1046 break;
0d06e24b 1047 case STATUS_FLOAT_DIVIDE_BY_ZERO:
7393af7c
PM
1048 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DIVIDE_BY_ZERO");
1049 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1050 break;
0d06e24b 1051 case STATUS_INTEGER_DIVIDE_BY_ZERO:
7393af7c 1052 DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_DIVIDE_BY_ZERO");
0d06e24b 1053 ourstatus->value.sig = TARGET_SIGNAL_FPE;
0d06e24b 1054 break;
7393af7c
PM
1055 case STATUS_INTEGER_OVERFLOW:
1056 DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_OVERFLOW");
1057 ourstatus->value.sig = TARGET_SIGNAL_FPE;
c906108c
SS
1058 break;
1059 case EXCEPTION_BREAKPOINT:
7393af7c 1060 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_BREAKPOINT");
c906108c
SS
1061 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
1062 break;
1063 case DBG_CONTROL_C:
7393af7c 1064 DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_C");
c906108c 1065 ourstatus->value.sig = TARGET_SIGNAL_INT;
5b421780
PM
1066 break;
1067 case DBG_CONTROL_BREAK:
7393af7c 1068 DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_BREAK");
5b421780 1069 ourstatus->value.sig = TARGET_SIGNAL_INT;
c906108c
SS
1070 break;
1071 case EXCEPTION_SINGLE_STEP:
7393af7c 1072 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_SINGLE_STEP");
c906108c
SS
1073 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
1074 break;
8227c82d 1075 case EXCEPTION_ILLEGAL_INSTRUCTION:
7393af7c
PM
1076 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ILLEGAL_INSTRUCTION");
1077 ourstatus->value.sig = TARGET_SIGNAL_ILL;
1078 break;
1079 case EXCEPTION_PRIV_INSTRUCTION:
1080 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_PRIV_INSTRUCTION");
1081 ourstatus->value.sig = TARGET_SIGNAL_ILL;
1082 break;
1083 case EXCEPTION_NONCONTINUABLE_EXCEPTION:
1084 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_NONCONTINUABLE_EXCEPTION");
8227c82d
CF
1085 ourstatus->value.sig = TARGET_SIGNAL_ILL;
1086 break;
c906108c 1087 default:
a244bdca 1088 /* Treat unhandled first chance exceptions specially. */
02e423b9 1089 if (current_event.u.Exception.dwFirstChance)
a244bdca 1090 return -1;
29fe111d 1091 printf_unfiltered ("gdb: unknown target exception 0x%08lx at 0x%08lx\n",
c5aa993b 1092 current_event.u.Exception.ExceptionRecord.ExceptionCode,
8e860359 1093 (DWORD) current_event.u.Exception.ExceptionRecord.ExceptionAddress);
c906108c
SS
1094 ourstatus->value.sig = TARGET_SIGNAL_UNKNOWN;
1095 break;
1096 }
1097 exception_count++;
7393af7c 1098 last_sig = ourstatus->value.sig;
c906108c
SS
1099 return 1;
1100}
1101
1102/* Resume all artificially suspended threads if we are continuing
1103 execution */
1104static BOOL
3ee6f623 1105win32_continue (DWORD continue_status, int id)
c906108c
SS
1106{
1107 int i;
1108 thread_info *th;
1109 BOOL res;
1110
7393af7c
PM
1111 DEBUG_EVENTS (("ContinueDebugEvent (cpid=%ld, ctid=%ld, %s);\n",
1112 current_event.dwProcessId, current_event.dwThreadId,
dfe7f3ac 1113 continue_status == DBG_CONTINUE ?
7393af7c 1114 "DBG_CONTINUE" : "DBG_EXCEPTION_NOT_HANDLED"));
7a292a7a
SS
1115 res = ContinueDebugEvent (current_event.dwProcessId,
1116 current_event.dwThreadId,
1117 continue_status);
1118 if (res)
c5aa993b 1119 for (th = &thread_head; (th = th->next) != NULL;)
29fe111d 1120 if (((id == -1) || (id == (int) th->id)) && th->suspend_count)
c906108c 1121 {
fa4ba8da 1122
c906108c
SS
1123 for (i = 0; i < th->suspend_count; i++)
1124 (void) ResumeThread (th->h);
1125 th->suspend_count = 0;
fa4ba8da
PM
1126 if (debug_registers_changed)
1127 {
3ade5333 1128 /* Only change the value of the debug registers */
fa4ba8da
PM
1129 th->context.ContextFlags = CONTEXT_DEBUG_REGISTERS;
1130 th->context.Dr0 = dr[0];
1131 th->context.Dr1 = dr[1];
1132 th->context.Dr2 = dr[2];
1133 th->context.Dr3 = dr[3];
1134 /* th->context.Dr6 = dr[6];
dfe7f3ac 1135 FIXME: should we set dr6 also ?? */
fa4ba8da
PM
1136 th->context.Dr7 = dr[7];
1137 CHECK (SetThreadContext (th->h, &th->context));
1138 th->context.ContextFlags = 0;
1139 }
c906108c
SS
1140 }
1141
fa4ba8da 1142 debug_registers_changed = 0;
c906108c
SS
1143 return res;
1144}
1145
d6dc8049
CF
1146/* Called in pathological case where Windows fails to send a
1147 CREATE_PROCESS_DEBUG_EVENT after an attach. */
3ee6f623 1148static DWORD
5439edaa 1149fake_create_process (void)
3ade5333
CF
1150{
1151 current_process_handle = OpenProcess (PROCESS_ALL_ACCESS, FALSE,
1152 current_event.dwProcessId);
1153 main_thread_id = current_event.dwThreadId;
3ee6f623 1154 current_thread = win32_add_thread (main_thread_id,
3ade5333
CF
1155 current_event.u.CreateThread.hThread);
1156 return main_thread_id;
1157}
1158
a244bdca
CF
1159static void
1160win32_resume (ptid_t ptid, int step, enum target_signal sig)
1161{
1162 thread_info *th;
1163 DWORD continue_status = DBG_CONTINUE;
1164
1165 int pid = PIDGET (ptid);
1166
1167 if (sig != TARGET_SIGNAL_0)
1168 {
1169 if (current_event.dwDebugEventCode != EXCEPTION_DEBUG_EVENT)
1170 {
1171 DEBUG_EXCEPT(("Cannot continue with signal %d here.\n",sig));
1172 }
1173 else if (sig == last_sig)
1174 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1175 else
1176#if 0
1177/* This code does not seem to work, because
1178 the kernel does probably not consider changes in the ExceptionRecord
1179 structure when passing the exception to the inferior.
1180 Note that this seems possible in the exception handler itself. */
1181 {
1182 int i;
1183 for (i = 0; xlate[i].them != -1; i++)
1184 if (xlate[i].us == sig)
1185 {
1186 current_event.u.Exception.ExceptionRecord.ExceptionCode =
1187 xlate[i].them;
1188 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1189 break;
1190 }
1191 if (continue_status == DBG_CONTINUE)
1192 {
1193 DEBUG_EXCEPT(("Cannot continue with signal %d.\n",sig));
1194 }
1195 }
1196#endif
1197 DEBUG_EXCEPT(("Can only continue with recieved signal %d.\n",
1198 last_sig));
1199 }
1200
1201 last_sig = TARGET_SIGNAL_0;
1202
1203 DEBUG_EXEC (("gdb: win32_resume (pid=%d, step=%d, sig=%d);\n",
1204 pid, step, sig));
1205
1206 /* Get context for currently selected thread */
1207 th = thread_rec (current_event.dwThreadId, FALSE);
1208 if (th)
1209 {
1210 if (step)
1211 {
1212 /* Single step by setting t bit */
3e8c568d
UW
1213 win32_fetch_inferior_registers (get_current_regcache (),
1214 gdbarch_ps_regnum (current_gdbarch));
a244bdca
CF
1215 th->context.EFlags |= FLAG_TRACE_BIT;
1216 }
1217
1218 if (th->context.ContextFlags)
1219 {
1220 if (debug_registers_changed)
1221 {
1222 th->context.Dr0 = dr[0];
1223 th->context.Dr1 = dr[1];
1224 th->context.Dr2 = dr[2];
1225 th->context.Dr3 = dr[3];
1226 /* th->context.Dr6 = dr[6];
1227 FIXME: should we set dr6 also ?? */
1228 th->context.Dr7 = dr[7];
1229 }
1230 CHECK (SetThreadContext (th->h, &th->context));
1231 th->context.ContextFlags = 0;
1232 }
1233 }
1234
1235 /* Allow continuing with the same signal that interrupted us.
1236 Otherwise complain. */
1237
1238 win32_continue (continue_status, pid);
1239}
1240
8a892701
CF
1241/* Get the next event from the child. Return 1 if the event requires
1242 handling by WFI (or whatever).
1243 */
c2d11a7d 1244static int
3ee6f623 1245get_win32_debug_event (int pid, struct target_waitstatus *ourstatus)
c2d11a7d
JM
1246{
1247 BOOL debug_event;
8a892701 1248 DWORD continue_status, event_code;
87a45c96 1249 thread_info *th;
8a892701 1250 static thread_info dummy_thread_info;
450005e7 1251 int retval = 0;
a244bdca 1252 ptid_t ptid = {-1};
c2d11a7d 1253
7393af7c 1254 last_sig = TARGET_SIGNAL_0;
9d3789f7 1255
8a892701 1256 if (!(debug_event = WaitForDebugEvent (&current_event, 1000)))
29fe111d 1257 goto out;
c2d11a7d
JM
1258
1259 event_count++;
1260 continue_status = DBG_CONTINUE;
c2d11a7d 1261
8a892701 1262 event_code = current_event.dwDebugEventCode;
450005e7 1263 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
87a45c96 1264 th = NULL;
a244bdca 1265 have_saved_context = 0;
8a892701
CF
1266
1267 switch (event_code)
c2d11a7d
JM
1268 {
1269 case CREATE_THREAD_DEBUG_EVENT:
1270 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%x code=%s)\n",
8a892701
CF
1271 (unsigned) current_event.dwProcessId,
1272 (unsigned) current_event.dwThreadId,
1273 "CREATE_THREAD_DEBUG_EVENT"));
dfe7f3ac 1274 if (saw_create != 1)
3ade5333
CF
1275 {
1276 if (!saw_create && attach_flag)
1277 {
d6dc8049
CF
1278 /* Kludge around a Windows bug where first event is a create
1279 thread event. Caused when attached process does not have
1280 a main thread. */
3ade5333
CF
1281 retval = ourstatus->value.related_pid = fake_create_process ();
1282 saw_create++;
1283 }
1284 break;
1285 }
c2d11a7d 1286 /* Record the existence of this thread */
3ee6f623 1287 th = win32_add_thread (current_event.dwThreadId,
8a892701 1288 current_event.u.CreateThread.hThread);
c2d11a7d
JM
1289 if (info_verbose)
1290 printf_unfiltered ("[New %s]\n",
39f77062
KB
1291 target_pid_to_str (
1292 pid_to_ptid (current_event.dwThreadId)));
450005e7 1293 retval = current_event.dwThreadId;
c2d11a7d
JM
1294 break;
1295
1296 case EXIT_THREAD_DEBUG_EVENT:
1297 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
8a892701
CF
1298 (unsigned) current_event.dwProcessId,
1299 (unsigned) current_event.dwThreadId,
1300 "EXIT_THREAD_DEBUG_EVENT"));
87a45c96
CF
1301 if (current_event.dwThreadId != main_thread_id)
1302 {
3ee6f623 1303 win32_delete_thread (current_event.dwThreadId);
87a45c96
CF
1304 th = &dummy_thread_info;
1305 }
c2d11a7d
JM
1306 break;
1307
1308 case CREATE_PROCESS_DEBUG_EVENT:
1309 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
8a892701
CF
1310 (unsigned) current_event.dwProcessId,
1311 (unsigned) current_event.dwThreadId,
1312 "CREATE_PROCESS_DEBUG_EVENT"));
700b351b 1313 CloseHandle (current_event.u.CreateProcessInfo.hFile);
dfe7f3ac
CF
1314 if (++saw_create != 1)
1315 {
1316 CloseHandle (current_event.u.CreateProcessInfo.hProcess);
1317 break;
1318 }
c2d11a7d 1319
dfe7f3ac 1320 current_process_handle = current_event.u.CreateProcessInfo.hProcess;
87a45c96 1321 if (main_thread_id)
3ee6f623 1322 win32_delete_thread (main_thread_id);
9d3789f7 1323 main_thread_id = current_event.dwThreadId;
c2d11a7d 1324 /* Add the main thread */
3ee6f623 1325 th = win32_add_thread (main_thread_id,
8a892701 1326 current_event.u.CreateProcessInfo.hThread);
9d3789f7 1327 retval = ourstatus->value.related_pid = current_event.dwThreadId;
c2d11a7d
JM
1328 break;
1329
1330 case EXIT_PROCESS_DEBUG_EVENT:
1331 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
8a892701
CF
1332 (unsigned) current_event.dwProcessId,
1333 (unsigned) current_event.dwThreadId,
1334 "EXIT_PROCESS_DEBUG_EVENT"));
dfe7f3ac
CF
1335 if (saw_create != 1)
1336 break;
c2d11a7d
JM
1337 ourstatus->kind = TARGET_WAITKIND_EXITED;
1338 ourstatus->value.integer = current_event.u.ExitProcess.dwExitCode;
1339 CloseHandle (current_process_handle);
9d3789f7 1340 retval = main_thread_id;
8a892701 1341 break;
c2d11a7d
JM
1342
1343 case LOAD_DLL_DEBUG_EVENT:
1344 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
8a892701
CF
1345 (unsigned) current_event.dwProcessId,
1346 (unsigned) current_event.dwThreadId,
1347 "LOAD_DLL_DEBUG_EVENT"));
700b351b 1348 CloseHandle (current_event.u.LoadDll.hFile);
dfe7f3ac
CF
1349 if (saw_create != 1)
1350 break;
8a892701 1351 catch_errors (handle_load_dll, NULL, (char *) "", RETURN_MASK_ALL);
450005e7
CF
1352 ourstatus->kind = TARGET_WAITKIND_LOADED;
1353 ourstatus->value.integer = 0;
9d3789f7 1354 retval = main_thread_id;
c2d11a7d
JM
1355 break;
1356
1357 case UNLOAD_DLL_DEBUG_EVENT:
1358 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
8a892701
CF
1359 (unsigned) current_event.dwProcessId,
1360 (unsigned) current_event.dwThreadId,
1361 "UNLOAD_DLL_DEBUG_EVENT"));
dfe7f3ac
CF
1362 if (saw_create != 1)
1363 break;
d3ff4a77 1364 catch_errors (handle_unload_dll, NULL, (char *) "", RETURN_MASK_ALL);
de1b3c3d
PA
1365 ourstatus->kind = TARGET_WAITKIND_LOADED;
1366 ourstatus->value.integer = 0;
1367 retval = main_thread_id;
d3ff4a77 1368 break;
c2d11a7d
JM
1369
1370 case EXCEPTION_DEBUG_EVENT:
1371 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
8a892701
CF
1372 (unsigned) current_event.dwProcessId,
1373 (unsigned) current_event.dwThreadId,
1374 "EXCEPTION_DEBUG_EVENT"));
dfe7f3ac
CF
1375 if (saw_create != 1)
1376 break;
a244bdca
CF
1377 switch (handle_exception (ourstatus))
1378 {
1379 case 0:
1380 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1381 break;
1382 case 1:
1383 retval = current_event.dwThreadId;
1384 break;
1385 case -1:
1386 last_sig = 1;
1387 continue_status = -1;
1388 break;
1389 }
c2d11a7d
JM
1390 break;
1391
8a892701 1392 case OUTPUT_DEBUG_STRING_EVENT: /* message from the kernel */
c2d11a7d 1393 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
8a892701
CF
1394 (unsigned) current_event.dwProcessId,
1395 (unsigned) current_event.dwThreadId,
1396 "OUTPUT_DEBUG_STRING_EVENT"));
dfe7f3ac
CF
1397 if (saw_create != 1)
1398 break;
a244bdca 1399 retval = handle_output_debug_string (ourstatus);
c2d11a7d 1400 break;
9d3789f7 1401
c2d11a7d 1402 default:
dfe7f3ac
CF
1403 if (saw_create != 1)
1404 break;
29fe111d
CF
1405 printf_unfiltered ("gdb: kernel event for pid=%ld tid=%ld\n",
1406 (DWORD) current_event.dwProcessId,
1407 (DWORD) current_event.dwThreadId);
1408 printf_unfiltered (" unknown event code %ld\n",
c2d11a7d
JM
1409 current_event.dwDebugEventCode);
1410 break;
1411 }
1412
dfe7f3ac 1413 if (!retval || saw_create != 1)
a244bdca
CF
1414 {
1415 if (continue_status == -1)
1416 win32_resume (ptid, 0, 1);
1417 else
1418 CHECK (win32_continue (continue_status, -1));
1419 }
450005e7 1420 else
9d3789f7 1421 {
39f77062 1422 inferior_ptid = pid_to_ptid (retval);
3ade5333 1423 current_thread = th ?: thread_rec (current_event.dwThreadId, TRUE);
9d3789f7 1424 }
c2d11a7d
JM
1425
1426out:
450005e7 1427 return retval;
c2d11a7d
JM
1428}
1429
c2d11a7d 1430/* Wait for interesting events to occur in the target process. */
39f77062 1431static ptid_t
3ee6f623 1432win32_wait (ptid_t ptid, struct target_waitstatus *ourstatus)
c906108c 1433{
39f77062
KB
1434 int pid = PIDGET (ptid);
1435
c44537cf
CV
1436 target_terminal_ours ();
1437
c906108c
SS
1438 /* We loop when we get a non-standard exception rather than return
1439 with a SPURIOUS because resume can try and step or modify things,
1440 which needs a current_thread->h. But some of these exceptions mark
1441 the birth or death of threads, which mean that the current thread
1442 isn't necessarily what you think it is. */
1443
1444 while (1)
450005e7 1445 {
3ee6f623 1446 int retval = get_win32_debug_event (pid, ourstatus);
450005e7 1447 if (retval)
39f77062 1448 return pid_to_ptid (retval);
450005e7
CF
1449 else
1450 {
1451 int detach = 0;
c906108c 1452
98bbd631
AC
1453 if (deprecated_ui_loop_hook != NULL)
1454 detach = deprecated_ui_loop_hook (0);
7a292a7a 1455
450005e7 1456 if (detach)
3ee6f623 1457 win32_kill_inferior ();
450005e7
CF
1458 }
1459 }
c906108c
SS
1460}
1461
9d3789f7 1462static void
3ee6f623 1463do_initial_win32_stuff (DWORD pid)
9d3789f7
CF
1464{
1465 extern int stop_after_trap;
fa4ba8da 1466 int i;
9d3789f7 1467
7393af7c 1468 last_sig = TARGET_SIGNAL_0;
9d3789f7
CF
1469 event_count = 0;
1470 exception_count = 0;
fa4ba8da 1471 debug_registers_changed = 0;
dfe7f3ac 1472 debug_registers_used = 0;
fa4ba8da
PM
1473 for (i = 0; i < sizeof (dr) / sizeof (dr[0]); i++)
1474 dr[i] = 0;
de1b3c3d 1475 cygwin_load_start = cygwin_load_end = 0;
9d3789f7
CF
1476 current_event.dwProcessId = pid;
1477 memset (&current_event, 0, sizeof (current_event));
3ee6f623 1478 push_target (&win32_ops);
cb851954 1479 disable_breakpoints_in_shlibs ();
3ee6f623 1480 win32_clear_solib ();
9d3789f7
CF
1481 clear_proceed_status ();
1482 init_wait_for_inferior ();
1483
c44537cf 1484 terminal_init_inferior_with_pgrp (pid);
9d3789f7
CF
1485 target_terminal_inferior ();
1486
1487 while (1)
1488 {
1489 stop_after_trap = 1;
1490 wait_for_inferior ();
1491 if (stop_signal != TARGET_SIGNAL_TRAP)
1492 resume (0, stop_signal);
1493 else
1494 break;
1495 }
1496 stop_after_trap = 0;
1497 return;
1498}
1499
02cc9f49
CV
1500/* Since Windows XP, detaching from a process is supported by Windows.
1501 The following code tries loading the appropriate functions dynamically.
1502 If loading these functions succeeds use them to actually detach from
1503 the inferior process, otherwise behave as usual, pretending that
1504 detach has worked. */
1505static BOOL WINAPI (*DebugSetProcessKillOnExit)(BOOL);
1506static BOOL WINAPI (*DebugActiveProcessStop)(DWORD);
1507
1508static int
5ae5f592 1509has_detach_ability (void)
02cc9f49
CV
1510{
1511 static HMODULE kernel32 = NULL;
1512
1513 if (!kernel32)
1514 kernel32 = LoadLibrary ("kernel32.dll");
1515 if (kernel32)
1516 {
1517 if (!DebugSetProcessKillOnExit)
1518 DebugSetProcessKillOnExit = GetProcAddress (kernel32,
1519 "DebugSetProcessKillOnExit");
1520 if (!DebugActiveProcessStop)
1521 DebugActiveProcessStop = GetProcAddress (kernel32,
1522 "DebugActiveProcessStop");
1523 if (DebugSetProcessKillOnExit && DebugActiveProcessStop)
1524 return 1;
1525 }
1526 return 0;
1527}
c906108c 1528
616a9dc4
CV
1529/* Try to set or remove a user privilege to the current process. Return -1
1530 if that fails, the previous setting of that privilege otherwise.
1531
1532 This code is copied from the Cygwin source code and rearranged to allow
1533 dynamically loading of the needed symbols from advapi32 which is only
1534 available on NT/2K/XP. */
1535static int
1536set_process_privilege (const char *privilege, BOOL enable)
1537{
1538 static HMODULE advapi32 = NULL;
1539 static BOOL WINAPI (*OpenProcessToken)(HANDLE, DWORD, PHANDLE);
1540 static BOOL WINAPI (*LookupPrivilegeValue)(LPCSTR, LPCSTR, PLUID);
1541 static BOOL WINAPI (*AdjustTokenPrivileges)(HANDLE, BOOL, PTOKEN_PRIVILEGES,
1542 DWORD, PTOKEN_PRIVILEGES, PDWORD);
1543
1544 HANDLE token_hdl = NULL;
1545 LUID restore_priv;
1546 TOKEN_PRIVILEGES new_priv, orig_priv;
1547 int ret = -1;
1548 DWORD size;
1549
1550 if (GetVersion () >= 0x80000000) /* No security availbale on 9x/Me */
1551 return 0;
1552
1553 if (!advapi32)
1554 {
1555 if (!(advapi32 = LoadLibrary ("advapi32.dll")))
1556 goto out;
1557 if (!OpenProcessToken)
1558 OpenProcessToken = GetProcAddress (advapi32, "OpenProcessToken");
1559 if (!LookupPrivilegeValue)
1560 LookupPrivilegeValue = GetProcAddress (advapi32,
1561 "LookupPrivilegeValueA");
1562 if (!AdjustTokenPrivileges)
1563 AdjustTokenPrivileges = GetProcAddress (advapi32,
1564 "AdjustTokenPrivileges");
1565 if (!OpenProcessToken || !LookupPrivilegeValue || !AdjustTokenPrivileges)
295732ea 1566 {
616a9dc4
CV
1567 advapi32 = NULL;
1568 goto out;
1569 }
1570 }
295732ea 1571
616a9dc4
CV
1572 if (!OpenProcessToken (GetCurrentProcess (),
1573 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
1574 &token_hdl))
1575 goto out;
1576
1577 if (!LookupPrivilegeValue (NULL, privilege, &restore_priv))
1578 goto out;
1579
1580 new_priv.PrivilegeCount = 1;
1581 new_priv.Privileges[0].Luid = restore_priv;
1582 new_priv.Privileges[0].Attributes = enable ? SE_PRIVILEGE_ENABLED : 0;
1583
1584 if (!AdjustTokenPrivileges (token_hdl, FALSE, &new_priv,
295732ea 1585 sizeof orig_priv, &orig_priv, &size))
616a9dc4
CV
1586 goto out;
1587#if 0
1588 /* Disabled, otherwise every `attach' in an unprivileged user session
1589 would raise the "Failed to get SE_DEBUG_NAME privilege" warning in
3ee6f623 1590 win32_attach(). */
616a9dc4
CV
1591 /* AdjustTokenPrivileges returns TRUE even if the privilege could not
1592 be enabled. GetLastError () returns an correct error code, though. */
1593 if (enable && GetLastError () == ERROR_NOT_ALL_ASSIGNED)
1594 goto out;
1595#endif
1596
1597 ret = orig_priv.Privileges[0].Attributes == SE_PRIVILEGE_ENABLED ? 1 : 0;
1598
1599out:
1600 if (token_hdl)
1601 CloseHandle (token_hdl);
1602
1603 return ret;
1604}
1605
02cc9f49 1606/* Attach to process PID, then initialize for debugging it. */
c906108c 1607static void
3ee6f623 1608win32_attach (char *args, int from_tty)
c906108c
SS
1609{
1610 BOOL ok;
559e75c0 1611 DWORD pid;
c906108c
SS
1612
1613 if (!args)
e2e0b3e5 1614 error_no_arg (_("process-id to attach"));
c906108c 1615
616a9dc4
CV
1616 if (set_process_privilege (SE_DEBUG_NAME, TRUE) < 0)
1617 {
1618 printf_unfiltered ("Warning: Failed to get SE_DEBUG_NAME privilege\n");
1619 printf_unfiltered ("This can cause attach to fail on Windows NT/2K/XP\n");
1620 }
1621
baa93fa6
CF
1622 pid = strtoul (args, 0, 0); /* Windows pid */
1623
3ee6f623 1624 win32_init_thread_list ();
9d3789f7 1625 ok = DebugActiveProcess (pid);
91a175b3 1626 saw_create = 0;
c906108c
SS
1627
1628 if (!ok)
baa93fa6
CF
1629 {
1630 /* Try fall back to Cygwin pid */
1631 pid = cygwin_internal (CW_CYGWIN_PID_TO_WINPID, pid);
1632
1633 if (pid > 0)
1634 ok = DebugActiveProcess (pid);
1635
1636 if (!ok)
8a3fe4f8 1637 error (_("Can't attach to process."));
baa93fa6 1638 }
c906108c 1639
02cc9f49 1640 if (has_detach_ability ())
3ade5333
CF
1641 DebugSetProcessKillOnExit (FALSE);
1642
1643 attach_flag = 1;
02cc9f49 1644
c906108c
SS
1645 if (from_tty)
1646 {
1647 char *exec_file = (char *) get_exec_file (0);
1648
1649 if (exec_file)
1650 printf_unfiltered ("Attaching to program `%s', %s\n", exec_file,
39f77062 1651 target_pid_to_str (pid_to_ptid (pid)));
c906108c
SS
1652 else
1653 printf_unfiltered ("Attaching to %s\n",
39f77062 1654 target_pid_to_str (pid_to_ptid (pid)));
c906108c
SS
1655
1656 gdb_flush (gdb_stdout);
1657 }
1658
3ee6f623 1659 do_initial_win32_stuff (pid);
9d3789f7 1660 target_terminal_ours ();
c906108c
SS
1661}
1662
1663static void
3ee6f623 1664win32_detach (char *args, int from_tty)
c906108c 1665{
02cc9f49
CV
1666 int detached = 1;
1667
1668 if (has_detach_ability ())
1669 {
96998ce7
PA
1670 ptid_t ptid = {-1};
1671 win32_resume (ptid, 0, TARGET_SIGNAL_0);
1672
02cc9f49 1673 if (!DebugActiveProcessStop (current_event.dwProcessId))
3bccec63 1674 {
8a3fe4f8 1675 error (_("Can't detach process %lu (error %lu)"),
02cc9f49
CV
1676 current_event.dwProcessId, GetLastError ());
1677 detached = 0;
3bccec63 1678 }
02cc9f49
CV
1679 DebugSetProcessKillOnExit (FALSE);
1680 }
1681 if (detached && from_tty)
c906108c
SS
1682 {
1683 char *exec_file = get_exec_file (0);
1684 if (exec_file == 0)
1685 exec_file = "";
02cc9f49
CV
1686 printf_unfiltered ("Detaching from program: %s, Pid %lu\n", exec_file,
1687 current_event.dwProcessId);
c906108c
SS
1688 gdb_flush (gdb_stdout);
1689 }
39f77062 1690 inferior_ptid = null_ptid;
3ee6f623 1691 unpush_target (&win32_ops);
c906108c
SS
1692}
1693
3ee6f623
CF
1694static char *
1695win32_pid_to_exec_file (int pid)
47216e51
CV
1696{
1697 /* Try to find the process path using the Cygwin internal process list
1698 pid isn't a valid pid, unfortunately. Use current_event.dwProcessId
1699 instead. */
1700 /* TODO: Also find native Windows processes using CW_GETPINFO_FULL. */
1701
1702 static char path[MAX_PATH + 1];
1703 char *path_ptr = NULL;
1704 int cpid;
1705 struct external_pinfo *pinfo;
1706
1707 cygwin_internal (CW_LOCK_PINFO, 1000);
1708 for (cpid = 0;
1709 (pinfo = (struct external_pinfo *)
3cb8e7f6 1710 cygwin_internal (CW_GETPINFO, cpid | CW_NEXTPID));
47216e51
CV
1711 cpid = pinfo->pid)
1712 {
1713 if (pinfo->dwProcessId == current_event.dwProcessId) /* Got it */
1714 {
3cb8e7f6
CF
1715 cygwin_conv_to_full_posix_path (pinfo->progname, path);
1716 path_ptr = path;
1717 break;
47216e51
CV
1718 }
1719 }
1720 cygwin_internal (CW_UNLOCK_PINFO);
3cb8e7f6 1721 return path_ptr;
47216e51
CV
1722}
1723
c906108c
SS
1724/* Print status information about what we're accessing. */
1725
1726static void
3ee6f623 1727win32_files_info (struct target_ops *ignore)
c906108c
SS
1728{
1729 printf_unfiltered ("\tUsing the running image of %s %s.\n",
39f77062 1730 attach_flag ? "attached" : "child", target_pid_to_str (inferior_ptid));
c906108c
SS
1731}
1732
c906108c 1733static void
3ee6f623 1734win32_open (char *arg, int from_tty)
c906108c 1735{
8a3fe4f8 1736 error (_("Use the \"run\" command to start a Unix child process."));
c906108c
SS
1737}
1738
39f77062 1739/* Start an inferior win32 child process and sets inferior_ptid to its pid.
c906108c
SS
1740 EXEC_FILE is the file to run.
1741 ALLARGS is a string containing the arguments to the program.
1742 ENV is the environment vector to pass. Errors reported with error(). */
1743
1744static void
8efc5725 1745win32_create_inferior (char *exec_file, char *allargs, char **in_env,
c27cda74 1746 int from_tty)
c906108c 1747{
c906108c
SS
1748 STARTUPINFO si;
1749 PROCESS_INFORMATION pi;
c906108c
SS
1750 BOOL ret;
1751 DWORD flags;
1752 char *args;
dfe7f3ac
CF
1753 char real_path[MAXPATHLEN];
1754 char *toexec;
349b409f
CF
1755 char shell[MAX_PATH + 1]; /* Path to shell */
1756 const char *sh;
2becadee
CF
1757 int tty;
1758 int ostdin, ostdout, ostderr;
3cb3b8df 1759 const char *inferior_io_terminal = get_inferior_io_terminal ();
c906108c
SS
1760
1761 if (!exec_file)
8a3fe4f8 1762 error (_("No executable specified, use `target exec'."));
c906108c
SS
1763
1764 memset (&si, 0, sizeof (si));
1765 si.cb = sizeof (si);
1766
349b409f 1767 if (!useshell)
dfe7f3ac
CF
1768 {
1769 flags = DEBUG_ONLY_THIS_PROCESS;
1770 cygwin_conv_to_win32_path (exec_file, real_path);
1771 toexec = real_path;
1772 }
1773 else
1774 {
349b409f
CF
1775 char *newallargs;
1776 sh = getenv ("SHELL");
1777 if (!sh)
1778 sh = "/bin/sh";
1779 cygwin_conv_to_win32_path (sh, shell);
1780 newallargs = alloca (sizeof (" -c 'exec '") + strlen (exec_file)
1781 + strlen (allargs) + 2);
dfe7f3ac
CF
1782 sprintf (newallargs, " -c 'exec %s %s'", exec_file, allargs);
1783 allargs = newallargs;
1784 toexec = shell;
1785 flags = DEBUG_PROCESS;
1786 }
c906108c 1787
eeb25b8a
PM
1788 if (new_group)
1789 flags |= CREATE_NEW_PROCESS_GROUP;
1790
1791 if (new_console)
1792 flags |= CREATE_NEW_CONSOLE;
1793
3ade5333
CF
1794 attach_flag = 0;
1795
dfe7f3ac
CF
1796 args = alloca (strlen (toexec) + strlen (allargs) + 2);
1797 strcpy (args, toexec);
c906108c
SS
1798 strcat (args, " ");
1799 strcat (args, allargs);
1800
1801 /* Prepare the environment vars for CreateProcess. */
002c07a9 1802 cygwin_internal (CW_SYNC_WINENV);
c906108c 1803
2becadee
CF
1804 if (!inferior_io_terminal)
1805 tty = ostdin = ostdout = ostderr = -1;
1806 else
1807 {
1808 tty = open (inferior_io_terminal, O_RDWR | O_NOCTTY);
1809 if (tty < 0)
1810 {
1811 print_sys_errmsg (inferior_io_terminal, errno);
1812 ostdin = ostdout = ostderr = -1;
1813 }
1814 else
1815 {
1816 ostdin = dup (0);
1817 ostdout = dup (1);
1818 ostderr = dup (2);
1819 dup2 (tty, 0);
1820 dup2 (tty, 1);
1821 dup2 (tty, 2);
1822 }
1823 }
1824
3ee6f623 1825 win32_init_thread_list ();
c906108c 1826 ret = CreateProcess (0,
c5aa993b 1827 args, /* command line */
c906108c
SS
1828 NULL, /* Security */
1829 NULL, /* thread */
1830 TRUE, /* inherit handles */
1831 flags, /* start flags */
002c07a9 1832 NULL, /* environment */
c906108c
SS
1833 NULL, /* current directory */
1834 &si,
1835 &pi);
2becadee
CF
1836 if (tty >= 0)
1837 {
1838 close (tty);
1839 dup2 (ostdin, 0);
1840 dup2 (ostdout, 1);
1841 dup2 (ostderr, 2);
1842 close (ostdin);
1843 close (ostdout);
1844 close (ostderr);
1845 }
1846
c906108c 1847 if (!ret)
8a3fe4f8
AC
1848 error (_("Error creating process %s, (error %d)."),
1849 exec_file, (unsigned) GetLastError ());
c906108c 1850
700b351b
CF
1851 CloseHandle (pi.hThread);
1852 CloseHandle (pi.hProcess);
dfe7f3ac
CF
1853
1854 if (useshell && shell[0] != '\0')
1855 saw_create = -1;
1856 else
1857 saw_create = 0;
1858
3ee6f623 1859 do_initial_win32_stuff (pi.dwProcessId);
ed9a39eb 1860
3ee6f623 1861 /* win32_continue (DBG_CONTINUE, -1); */
c906108c
SS
1862}
1863
1864static void
3ee6f623 1865win32_mourn_inferior (void)
c906108c 1866{
3ee6f623 1867 (void) win32_continue (DBG_CONTINUE, -1);
fa4ba8da 1868 i386_cleanup_dregs();
3ee6f623 1869 unpush_target (&win32_ops);
c906108c
SS
1870 generic_mourn_inferior ();
1871}
1872
1873/* Send a SIGINT to the process group. This acts just like the user typed a
1874 ^C on the controlling terminal. */
1875
1876static void
3ee6f623 1877win32_stop (void)
c906108c
SS
1878{
1879 DEBUG_EVENTS (("gdb: GenerateConsoleCtrlEvent (CTRLC_EVENT, 0)\n"));
c2d11a7d 1880 CHECK (GenerateConsoleCtrlEvent (CTRL_C_EVENT, current_event.dwProcessId));
c5aa993b 1881 registers_changed (); /* refresh register state */
c906108c
SS
1882}
1883
3ee6f623
CF
1884static int
1885win32_xfer_memory (CORE_ADDR memaddr, gdb_byte *our, int len,
0a65a603
AC
1886 int write, struct mem_attrib *mem,
1887 struct target_ops *target)
c906108c 1888{
6f17862b 1889 DWORD done = 0;
c906108c
SS
1890 if (write)
1891 {
29fe111d
CF
1892 DEBUG_MEM (("gdb: write target memory, %d bytes at 0x%08lx\n",
1893 len, (DWORD) memaddr));
6f17862b
CF
1894 if (!WriteProcessMemory (current_process_handle, (LPVOID) memaddr, our,
1895 len, &done))
1896 done = 0;
c906108c
SS
1897 FlushInstructionCache (current_process_handle, (LPCVOID) memaddr, len);
1898 }
1899 else
1900 {
29fe111d
CF
1901 DEBUG_MEM (("gdb: read target memory, %d bytes at 0x%08lx\n",
1902 len, (DWORD) memaddr));
6f17862b
CF
1903 if (!ReadProcessMemory (current_process_handle, (LPCVOID) memaddr, our,
1904 len, &done))
1905 done = 0;
c906108c
SS
1906 }
1907 return done;
1908}
1909
3ee6f623
CF
1910static void
1911win32_kill_inferior (void)
c906108c
SS
1912{
1913 CHECK (TerminateProcess (current_process_handle, 0));
1914
1915 for (;;)
1916 {
3ee6f623 1917 if (!win32_continue (DBG_CONTINUE, -1))
c906108c
SS
1918 break;
1919 if (!WaitForDebugEvent (&current_event, INFINITE))
1920 break;
1921 if (current_event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
1922 break;
1923 }
1924
1925 CHECK (CloseHandle (current_process_handle));
1926
1927 /* this may fail in an attached process so don't check. */
3ade5333
CF
1928 if (current_thread && current_thread->h)
1929 (void) CloseHandle (current_thread->h);
3ee6f623 1930 target_mourn_inferior (); /* or just win32_mourn_inferior? */
c906108c
SS
1931}
1932
c906108c 1933static void
316f2060 1934win32_prepare_to_store (struct regcache *regcache)
c906108c
SS
1935{
1936 /* Do nothing, since we can store individual regs */
1937}
1938
1939static int
3ee6f623 1940win32_can_run (void)
c906108c
SS
1941{
1942 return 1;
1943}
1944
1945static void
3ee6f623 1946win32_close (int x)
c906108c 1947{
3ee6f623 1948 DEBUG_EVENTS (("gdb: win32_close, inferior_ptid=%d\n",
3bccec63 1949 PIDGET (inferior_ptid)));
c906108c
SS
1950}
1951
3ee6f623
CF
1952/* Convert pid to printable format. */
1953static char *
1954cygwin_pid_to_str (ptid_t ptid)
c906108c 1955{
3ee6f623
CF
1956 static char buf[80];
1957 int pid = PIDGET (ptid);
1958
1959 if ((DWORD) pid == current_event.dwProcessId)
1960 sprintf (buf, "process %d", pid);
1961 else
1962 sprintf (buf, "thread %ld.0x%x", current_event.dwProcessId, pid);
1963 return buf;
1964}
1965
de1b3c3d
PA
1966static LONGEST
1967win32_xfer_shared_libraries (struct target_ops *ops,
1968 enum target_object object, const char *annex,
1969 gdb_byte *readbuf, const gdb_byte *writebuf,
1970 ULONGEST offset, LONGEST len)
3cb8e7f6 1971{
de1b3c3d
PA
1972 struct obstack obstack;
1973 const char *buf;
1974 LONGEST len_avail;
3cb8e7f6 1975 struct so_list *so;
3cb8e7f6 1976
de1b3c3d
PA
1977 if (writebuf)
1978 return -1;
3cb8e7f6 1979
de1b3c3d
PA
1980 obstack_init (&obstack);
1981 obstack_grow_str (&obstack, "<library-list>\n");
1982 for (so = solib_start.next; so; so = so->next)
1983 win32_xfer_shared_library (so->so_name, so->lm_info->load_addr, &obstack);
1984 obstack_grow_str0 (&obstack, "</library-list>\n");
3cb8e7f6 1985
de1b3c3d
PA
1986 buf = obstack_finish (&obstack);
1987 len_avail = strlen (buf);
1988 if (offset >= len_avail)
1989 return 0;
3cb8e7f6 1990
de1b3c3d
PA
1991 if (len > len_avail - offset)
1992 len = len_avail - offset;
1993 memcpy (readbuf, buf + offset, len);
3cb8e7f6 1994
de1b3c3d
PA
1995 obstack_free (&obstack, NULL);
1996 return len;
3cb8e7f6
CF
1997}
1998
de1b3c3d
PA
1999static LONGEST
2000win32_xfer_partial (struct target_ops *ops, enum target_object object,
2001 const char *annex, gdb_byte *readbuf,
2002 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
3cb8e7f6 2003{
de1b3c3d 2004 switch (object)
3cb8e7f6 2005 {
de1b3c3d
PA
2006 case TARGET_OBJECT_MEMORY:
2007 if (readbuf)
2008 return (*ops->deprecated_xfer_memory) (offset, readbuf,
2009 len, 0/*write*/, NULL, ops);
2010 if (writebuf)
2011 return (*ops->deprecated_xfer_memory) (offset, (gdb_byte *) writebuf,
2012 len, 1/*write*/, NULL, ops);
2013 return -1;
2014
2015 case TARGET_OBJECT_LIBRARIES:
2016 return win32_xfer_shared_libraries (ops, object, annex, readbuf,
2017 writebuf, offset, len);
3929abe9 2018
de1b3c3d
PA
2019 default:
2020 if (ops->beneath != NULL)
2021 return ops->beneath->to_xfer_partial (ops->beneath, object, annex,
2022 readbuf, writebuf, offset, len);
2023 return -1;
3929abe9 2024 }
02c5aecd
CF
2025}
2026
3ee6f623
CF
2027static void
2028init_win32_ops (void)
2029{
2030 win32_ops.to_shortname = "child";
2031 win32_ops.to_longname = "Win32 child process";
2032 win32_ops.to_doc = "Win32 child process (started by the \"run\" command).";
2033 win32_ops.to_open = win32_open;
2034 win32_ops.to_close = win32_close;
2035 win32_ops.to_attach = win32_attach;
2036 win32_ops.to_detach = win32_detach;
2037 win32_ops.to_resume = win32_resume;
2038 win32_ops.to_wait = win32_wait;
2039 win32_ops.to_fetch_registers = win32_fetch_inferior_registers;
2040 win32_ops.to_store_registers = win32_store_inferior_registers;
2041 win32_ops.to_prepare_to_store = win32_prepare_to_store;
2042 win32_ops.deprecated_xfer_memory = win32_xfer_memory;
de1b3c3d 2043 win32_ops.to_xfer_partial = win32_xfer_partial;
3ee6f623
CF
2044 win32_ops.to_files_info = win32_files_info;
2045 win32_ops.to_insert_breakpoint = memory_insert_breakpoint;
2046 win32_ops.to_remove_breakpoint = memory_remove_breakpoint;
2047 win32_ops.to_terminal_init = terminal_init_inferior;
2048 win32_ops.to_terminal_inferior = terminal_inferior;
2049 win32_ops.to_terminal_ours_for_output = terminal_ours_for_output;
2050 win32_ops.to_terminal_ours = terminal_ours;
2051 win32_ops.to_terminal_save_ours = terminal_save_ours;
2052 win32_ops.to_terminal_info = child_terminal_info;
2053 win32_ops.to_kill = win32_kill_inferior;
2054 win32_ops.to_create_inferior = win32_create_inferior;
2055 win32_ops.to_mourn_inferior = win32_mourn_inferior;
2056 win32_ops.to_can_run = win32_can_run;
2057 win32_ops.to_thread_alive = win32_win32_thread_alive;
2058 win32_ops.to_pid_to_str = cygwin_pid_to_str;
2059 win32_ops.to_stop = win32_stop;
2060 win32_ops.to_stratum = process_stratum;
2061 win32_ops.to_has_all_memory = 1;
2062 win32_ops.to_has_memory = 1;
2063 win32_ops.to_has_stack = 1;
2064 win32_ops.to_has_registers = 1;
2065 win32_ops.to_has_execution = 1;
2066 win32_ops.to_magic = OPS_MAGIC;
2067 win32_ops.to_pid_to_exec_file = win32_pid_to_exec_file;
c906108c
SS
2068}
2069
3929abe9
CF
2070static void
2071set_win32_aliases (char *argv0)
2072{
2073 add_info_alias ("dll", "sharedlibrary", 1);
2074}
2075
c906108c 2076void
a6b6b089 2077_initialize_win32_nat (void)
c906108c 2078{
fa58ee11
EZ
2079 struct cmd_list_element *c;
2080
3ee6f623 2081 init_win32_ops ();
c906108c 2082
fa58ee11 2083 c = add_com ("dll-symbols", class_files, dll_symbol_command,
1bedd215 2084 _("Load dll library symbols from FILE."));
5ba2abeb 2085 set_cmd_completer (c, filename_completer);
450005e7
CF
2086
2087 add_com_alias ("sharedlibrary", "dll-symbols", class_alias, 1);
2088
5bf193a2
AC
2089 add_setshow_boolean_cmd ("shell", class_support, &useshell, _("\
2090Set use of shell to start subprocess."), _("\
2091Show use of shell to start subprocess."), NULL,
2092 NULL,
2093 NULL, /* FIXME: i18n: */
2094 &setlist, &showlist);
2095
09280ddf
CF
2096 add_setshow_boolean_cmd ("cygwin-exceptions", class_support, &cygwin_exceptions, _("\
2097Break when an exception is detected in the Cygwin DLL itself."), _("\
2098Show whether gdb breaks on exceptions in the Cygwin DLL itself."), NULL,
2099 NULL,
2100 NULL, /* FIXME: i18n: */
2101 &setlist, &showlist);
2102
5bf193a2
AC
2103 add_setshow_boolean_cmd ("new-console", class_support, &new_console, _("\
2104Set creation of new console when creating child process."), _("\
2105Show creation of new console when creating child process."), NULL,
2106 NULL,
2107 NULL, /* FIXME: i18n: */
2108 &setlist, &showlist);
2109
2110 add_setshow_boolean_cmd ("new-group", class_support, &new_group, _("\
2111Set creation of new group when creating child process."), _("\
2112Show creation of new group when creating child process."), NULL,
2113 NULL,
2114 NULL, /* FIXME: i18n: */
2115 &setlist, &showlist);
2116
2117 add_setshow_boolean_cmd ("debugexec", class_support, &debug_exec, _("\
2118Set whether to display execution in child process."), _("\
2119Show whether to display execution in child process."), NULL,
2120 NULL,
2121 NULL, /* FIXME: i18n: */
2122 &setlist, &showlist);
2123
2124 add_setshow_boolean_cmd ("debugevents", class_support, &debug_events, _("\
2125Set whether to display kernel events in child process."), _("\
2126Show whether to display kernel events in child process."), NULL,
2127 NULL,
2128 NULL, /* FIXME: i18n: */
2129 &setlist, &showlist);
2130
2131 add_setshow_boolean_cmd ("debugmemory", class_support, &debug_memory, _("\
2132Set whether to display memory accesses in child process."), _("\
2133Show whether to display memory accesses in child process."), NULL,
2134 NULL,
2135 NULL, /* FIXME: i18n: */
2136 &setlist, &showlist);
2137
2138 add_setshow_boolean_cmd ("debugexceptions", class_support,
2139 &debug_exceptions, _("\
2140Set whether to display kernel exceptions in child process."), _("\
2141Show whether to display kernel exceptions in child process."), NULL,
2142 NULL,
2143 NULL, /* FIXME: i18n: */
2144 &setlist, &showlist);
c906108c 2145
c1748f97 2146 add_prefix_cmd ("w32", class_info, info_w32_command,
1bedd215 2147 _("Print information specific to Win32 debugging."),
baa93fa6 2148 &info_w32_cmdlist, "info w32 ", 0, &infolist);
c1748f97
PM
2149
2150 add_cmd ("selector", class_info, display_selectors,
1a966eab 2151 _("Display selectors infos."),
c1748f97 2152 &info_w32_cmdlist);
3ee6f623 2153 add_target (&win32_ops);
3929abe9 2154 deprecated_init_ui_hook = set_win32_aliases;
c906108c
SS
2155}
2156
fa4ba8da
PM
2157/* Hardware watchpoint support, adapted from go32-nat.c code. */
2158
2159/* Pass the address ADDR to the inferior in the I'th debug register.
2160 Here we just store the address in dr array, the registers will be
3ee6f623 2161 actually set up when win32_continue is called. */
fa4ba8da
PM
2162void
2163cygwin_set_dr (int i, CORE_ADDR addr)
2164{
2165 if (i < 0 || i > 3)
2166 internal_error (__FILE__, __LINE__,
e2e0b3e5 2167 _("Invalid register %d in cygwin_set_dr.\n"), i);
fa4ba8da
PM
2168 dr[i] = (unsigned) addr;
2169 debug_registers_changed = 1;
2170 debug_registers_used = 1;
2171}
2172
2173/* Pass the value VAL to the inferior in the DR7 debug control
2174 register. Here we just store the address in D_REGS, the watchpoint
3ee6f623 2175 will be actually set up in win32_wait. */
fa4ba8da
PM
2176void
2177cygwin_set_dr7 (unsigned val)
2178{
2179 dr[7] = val;
2180 debug_registers_changed = 1;
2181 debug_registers_used = 1;
2182}
2183
2184/* Get the value of the DR6 debug status register from the inferior.
2185 Here we just return the value stored in dr[6]
2186 by the last call to thread_rec for current_event.dwThreadId id. */
2187unsigned
2188cygwin_get_dr6 (void)
2189{
2190 return dr[6];
2191}
2192
c906108c
SS
2193/* Determine if the thread referenced by "pid" is alive
2194 by "polling" it. If WaitForSingleObject returns WAIT_OBJECT_0
2195 it means that the pid has died. Otherwise it is assumed to be alive. */
2196static int
3ee6f623 2197win32_win32_thread_alive (ptid_t ptid)
c906108c 2198{
39f77062
KB
2199 int pid = PIDGET (ptid);
2200
c5aa993b
JM
2201 return WaitForSingleObject (thread_rec (pid, FALSE)->h, 0) == WAIT_OBJECT_0 ?
2202 FALSE : TRUE;
c906108c
SS
2203}
2204
2a3d5645
CF
2205void
2206_initialize_check_for_gdb_ini (void)
2207{
2208 char *homedir;
2209 if (inhibit_gdbinit)
2210 return;
2211
2212 homedir = getenv ("HOME");
2213 if (homedir)
2214 {
2215 char *p;
2216 char *oldini = (char *) alloca (strlen (homedir) +
2217 sizeof ("/gdb.ini"));
2218 strcpy (oldini, homedir);
2219 p = strchr (oldini, '\0');
2220 if (p > oldini && p[-1] != '/')
2221 *p++ = '/';
2222 strcpy (p, "gdb.ini");
2223 if (access (oldini, 0) == 0)
2224 {
2225 int len = strlen (oldini);
2226 char *newini = alloca (len + 1);
dfe7f3ac 2227 sprintf (newini, "%.*s.gdbinit",
58fa08f0 2228 (int) (len - (sizeof ("gdb.ini") - 1)), oldini);
8a3fe4f8 2229 warning (_("obsolete '%s' found. Rename to '%s'."), oldini, newini);
2a3d5645
CF
2230 }
2231 }
2232}
This page took 0.893708 seconds and 4 git commands to generate.