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