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