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