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