gdb.base/watchpoint.{c,exp}
[deliverable/binutils-gdb.git] / gdb / windows-nat.c
CommitLineData
dc05df57 1/* Target-vector operations for controlling windows child processes, for GDB.
0a65a603 2
b811d2c2 3 Copyright (C) 1995-2020 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
a1b85d28 45#include <algorithm>
93366324 46#include <vector>
cad9cd60 47
0ba1096a 48#include "filenames.h"
1ef980b9
SC
49#include "symfile.h"
50#include "objfiles.h"
92107356 51#include "gdb_bfd.h"
de1b3c3d 52#include "gdb_obstack.h"
fdfa3315 53#include "gdbthread.h"
24e60978 54#include "gdbcmd.h"
1e37c281 55#include <unistd.h>
4646aa9d 56#include "exec.h"
3ee6f623 57#include "solist.h"
3cb8e7f6 58#include "solib.h"
de1b3c3d 59#include "xml-support.h"
463888ab 60#include "inttypes.h"
24e60978 61
6c7de422
MK
62#include "i386-tdep.h"
63#include "i387-tdep.h"
64
31b060a2
CF
65#include "windows-tdep.h"
66#include "windows-nat.h"
df7e5265 67#include "x86-nat.h"
ecc13e53 68#include "complaints.h"
51a9c8c5 69#include "inf-child.h"
268a13a5
TT
70#include "gdbsupport/gdb_tilde_expand.h"
71#include "gdbsupport/pathstuff.h"
559e7e50 72#include "gdbsupport/gdb_wait.h"
ae1f8880 73#include "nat/windows-nat.h"
0363df3d 74#include "gdbsupport/symbol.h"
de1b3c3d 75
4834dad0
TT
76using namespace windows_nat;
77
418c6cb3 78#define AdjustTokenPrivileges dyn_AdjustTokenPrivileges
2b008701
CF
79#define DebugActiveProcessStop dyn_DebugActiveProcessStop
80#define DebugBreakProcess dyn_DebugBreakProcess
81#define DebugSetProcessKillOnExit dyn_DebugSetProcessKillOnExit
82#define EnumProcessModules dyn_EnumProcessModules
46f9f931 83#define EnumProcessModulesEx dyn_EnumProcessModulesEx
2b008701 84#define GetModuleInformation dyn_GetModuleInformation
418c6cb3
CF
85#define LookupPrivilegeValueA dyn_LookupPrivilegeValueA
86#define OpenProcessToken dyn_OpenProcessToken
cd44747c
PM
87#define GetConsoleFontSize dyn_GetConsoleFontSize
88#define GetCurrentConsoleFont dyn_GetCurrentConsoleFont
46f9f931
HD
89#define Wow64SuspendThread dyn_Wow64SuspendThread
90#define Wow64GetThreadContext dyn_Wow64GetThreadContext
91#define Wow64SetThreadContext dyn_Wow64SetThreadContext
92#define Wow64GetThreadSelectorEntry dyn_Wow64GetThreadSelectorEntry
2b008701 93
43499ea3
PA
94typedef BOOL WINAPI (AdjustTokenPrivileges_ftype) (HANDLE, BOOL,
95 PTOKEN_PRIVILEGES,
96 DWORD, PTOKEN_PRIVILEGES,
97 PDWORD);
98static AdjustTokenPrivileges_ftype *AdjustTokenPrivileges;
99
100typedef BOOL WINAPI (DebugActiveProcessStop_ftype) (DWORD);
101static DebugActiveProcessStop_ftype *DebugActiveProcessStop;
102
103typedef BOOL WINAPI (DebugBreakProcess_ftype) (HANDLE);
104static DebugBreakProcess_ftype *DebugBreakProcess;
105
106typedef BOOL WINAPI (DebugSetProcessKillOnExit_ftype) (BOOL);
107static DebugSetProcessKillOnExit_ftype *DebugSetProcessKillOnExit;
108
109typedef BOOL WINAPI (EnumProcessModules_ftype) (HANDLE, HMODULE *, DWORD,
110 LPDWORD);
111static EnumProcessModules_ftype *EnumProcessModules;
112
46f9f931
HD
113#ifdef __x86_64__
114typedef BOOL WINAPI (EnumProcessModulesEx_ftype) (HANDLE, HMODULE *, DWORD,
115 LPDWORD, DWORD);
116static EnumProcessModulesEx_ftype *EnumProcessModulesEx;
117#endif
118
43499ea3
PA
119typedef BOOL WINAPI (GetModuleInformation_ftype) (HANDLE, HMODULE,
120 LPMODULEINFO, DWORD);
121static GetModuleInformation_ftype *GetModuleInformation;
122
123typedef BOOL WINAPI (LookupPrivilegeValueA_ftype) (LPCSTR, LPCSTR, PLUID);
124static LookupPrivilegeValueA_ftype *LookupPrivilegeValueA;
125
126typedef BOOL WINAPI (OpenProcessToken_ftype) (HANDLE, DWORD, PHANDLE);
127static OpenProcessToken_ftype *OpenProcessToken;
128
129typedef BOOL WINAPI (GetCurrentConsoleFont_ftype) (HANDLE, BOOL,
130 CONSOLE_FONT_INFO *);
131static GetCurrentConsoleFont_ftype *GetCurrentConsoleFont;
132
133typedef COORD WINAPI (GetConsoleFontSize_ftype) (HANDLE, DWORD);
134static GetConsoleFontSize_ftype *GetConsoleFontSize;
2b008701 135
46f9f931
HD
136#ifdef __x86_64__
137typedef DWORD WINAPI (Wow64SuspendThread_ftype) (HANDLE);
138static Wow64SuspendThread_ftype *Wow64SuspendThread;
139
140typedef BOOL WINAPI (Wow64GetThreadContext_ftype) (HANDLE, PWOW64_CONTEXT);
141static Wow64GetThreadContext_ftype *Wow64GetThreadContext;
142
143typedef BOOL WINAPI (Wow64SetThreadContext_ftype) (HANDLE,
144 const WOW64_CONTEXT *);
145static Wow64SetThreadContext_ftype *Wow64SetThreadContext;
146
147typedef BOOL WINAPI (Wow64GetThreadSelectorEntry_ftype) (HANDLE, DWORD,
148 PLDT_ENTRY);
149static Wow64GetThreadSelectorEntry_ftype *Wow64GetThreadSelectorEntry;
150#endif
151
b3c613f2
CF
152#undef STARTUPINFO
153#undef CreateProcess
154#undef GetModuleFileNameEx
155
156#ifndef __CYGWIN__
157# define __PMAX (MAX_PATH + 1)
43499ea3
PA
158 typedef DWORD WINAPI (GetModuleFileNameEx_ftype) (HANDLE, HMODULE, LPSTR, DWORD);
159 static GetModuleFileNameEx_ftype *GetModuleFileNameEx;
b3c613f2
CF
160# define STARTUPINFO STARTUPINFOA
161# define CreateProcess CreateProcessA
162# define GetModuleFileNameEx_name "GetModuleFileNameExA"
163# define bad_GetModuleFileNameEx bad_GetModuleFileNameExA
164#else
165# define __PMAX PATH_MAX
581e13c1 166/* The starting and ending address of the cygwin1.dll text segment. */
b3c613f2
CF
167 static CORE_ADDR cygwin_load_start;
168 static CORE_ADDR cygwin_load_end;
b3c613f2
CF
169# define __USEWIDE
170 typedef wchar_t cygwin_buf_t;
43499ea3
PA
171 typedef DWORD WINAPI (GetModuleFileNameEx_ftype) (HANDLE, HMODULE,
172 LPWSTR, DWORD);
173 static GetModuleFileNameEx_ftype *GetModuleFileNameEx;
b3c613f2
CF
174# define STARTUPINFO STARTUPINFOW
175# define CreateProcess CreateProcessW
176# define GetModuleFileNameEx_name "GetModuleFileNameExW"
177# define bad_GetModuleFileNameEx bad_GetModuleFileNameExW
10325bc5 178#endif
a244bdca 179
581e13c1
MS
180static int have_saved_context; /* True if we've saved context from a
181 cygwin signal. */
15766370 182#ifdef __CYGWIN__
85102364 183static CONTEXT saved_context; /* Contains the saved context from a
581e13c1 184 cygwin signal. */
15766370 185#endif
a244bdca 186
0714f9bf
SS
187/* If we're not using the old Cygwin header file set, define the
188 following which never should have been in the generic Win32 API
581e13c1 189 headers in the first place since they were our own invention... */
0714f9bf 190#ifndef _GNU_H_WINDOWS_H
9d3789f7 191enum
8e860359
CF
192 {
193 FLAG_TRACE_BIT = 0x100,
8e860359 194 };
0714f9bf
SS
195#endif
196
5851ab76
JB
197#ifndef CONTEXT_EXTENDED_REGISTERS
198/* This macro is only defined on ia32. It only makes sense on this target,
199 so define it as zero if not already defined. */
200#define CONTEXT_EXTENDED_REGISTERS 0
201#endif
202
f0666312
JT
203#define CONTEXT_DEBUGGER_DR CONTEXT_FULL | CONTEXT_FLOATING_POINT \
204 | CONTEXT_SEGMENTS | CONTEXT_DEBUG_REGISTERS \
205 | CONTEXT_EXTENDED_REGISTERS
97da3b20 206
41b4aadc 207static uintptr_t dr[8];
87a45c96
CF
208static int debug_registers_changed;
209static int debug_registers_used;
16d905e2
CF
210
211static int windows_initialization_done;
6537bb24 212#define DR6_CLEAR_VALUE 0xffff0ff0
97da3b20 213
3cee93ac 214/* The string sent by cygwin when it processes a signal.
581e13c1 215 FIXME: This should be in a cygwin include file. */
3929abe9
CF
216#ifndef _CYGWIN_SIGNAL_STRING
217#define _CYGWIN_SIGNAL_STRING "cYgSiGw00f"
218#endif
3cee93ac 219
29fe111d 220#define CHECK(x) check (x, __FILE__,__LINE__)
ce127a96
TT
221#define DEBUG_EXEC(x) if (debug_exec) debug_printf x
222#define DEBUG_EVENTS(x) if (debug_events) debug_printf x
223#define DEBUG_MEM(x) if (debug_memory) debug_printf x
224#define DEBUG_EXCEPT(x) if (debug_exceptions) debug_printf x
24e60978 225
9bb9e8ad
PM
226static void cygwin_set_dr (int i, CORE_ADDR addr);
227static void cygwin_set_dr7 (unsigned long val);
a961bc18 228static CORE_ADDR cygwin_get_dr (int i);
9bb9e8ad 229static unsigned long cygwin_get_dr6 (void);
a961bc18 230static unsigned long cygwin_get_dr7 (void);
9bb9e8ad 231
93366324 232static std::vector<windows_thread_info *> thread_list;
24e60978 233
581e13c1 234/* Counts of things. */
dfe7f3ac 235static int saw_create;
bf25528d 236static int open_process_used = 0;
46f9f931
HD
237#ifdef __x86_64__
238static bool wow64_process = false;
0363df3d 239static void *wow64_dbgbreak;
46f9f931 240#endif
24e60978 241
581e13c1 242/* User options. */
491144b5 243static bool new_console = false;
10325bc5 244#ifdef __CYGWIN__
491144b5 245static bool cygwin_exceptions = false;
10325bc5 246#endif
491144b5
CB
247static bool new_group = true;
248static bool debug_exec = false; /* show execution */
249static bool debug_events = false; /* show events from kernel */
250static bool debug_memory = false; /* show target memory accesses */
251static bool debug_exceptions = false; /* show target exceptions */
252static bool useshell = false; /* use shell for subprocesses */
dfe7f3ac 253
7e63b4e4 254/* This vector maps GDB's idea of a register's number into an offset
dc05df57 255 in the windows exception context vector.
24e60978 256
3cee93ac 257 It also contains the bit mask needed to load the register in question.
24e60978 258
7e63b4e4
JB
259 The contents of this table can only be computed by the units
260 that provide CPU-specific support for Windows native debugging.
261 These units should set the table by calling
dc05df57 262 windows_set_context_register_offsets.
7e63b4e4 263
24e60978
SC
264 One day we could read a reg, we could inspect the context we
265 already have loaded, if it doesn't have the bit set that we need,
266 we read that set of registers in using GetThreadContext. If the
581e13c1 267 context already contains what we need, we just unpack it. Then to
24e60978
SC
268 write a register, first we have to ensure that the context contains
269 the other regs of the group, and then we copy the info in and set
581e13c1 270 out bit. */
24e60978 271
7e63b4e4 272static const int *mappings;
d3a09475 273
d40dc7a8
JB
274/* The function to use in order to determine whether a register is
275 a segment register or not. */
276static segment_register_p_ftype *segment_register_p;
277
73c13fe6
TT
278/* See windows_nat_target::resume to understand why this is commented
279 out. */
280#if 0
24e60978 281/* This vector maps the target's idea of an exception (extracted
581e13c1 282 from the DEBUG_EVENT structure) to GDB's idea. */
24e60978
SC
283
284struct xlate_exception
285 {
73c13fe6 286 DWORD them;
2ea28649 287 enum gdb_signal us;
24e60978
SC
288 };
289
73c13fe6 290static const struct xlate_exception xlate[] =
24e60978 291{
a493e3e2
PA
292 {EXCEPTION_ACCESS_VIOLATION, GDB_SIGNAL_SEGV},
293 {STATUS_STACK_OVERFLOW, GDB_SIGNAL_SEGV},
294 {EXCEPTION_BREAKPOINT, GDB_SIGNAL_TRAP},
295 {DBG_CONTROL_C, GDB_SIGNAL_INT},
296 {EXCEPTION_SINGLE_STEP, GDB_SIGNAL_TRAP},
73c13fe6
TT
297 {STATUS_FLOAT_DIVIDE_BY_ZERO, GDB_SIGNAL_FPE}
298};
24e60978 299
73c13fe6 300#endif /* 0 */
f6ac5f3d
PA
301
302struct windows_nat_target final : public x86_nat_target<inf_child_target>
303{
304 void close () override;
305
306 void attach (const char *, int) override;
307
308 bool attach_no_wait () override
309 { return true; }
310
311 void detach (inferior *, int) override;
312
313 void resume (ptid_t, int , enum gdb_signal) override;
314
315 ptid_t wait (ptid_t, struct target_waitstatus *, int) override;
316
317 void fetch_registers (struct regcache *, int) override;
318 void store_registers (struct regcache *, int) override;
319
0a4afda3
TT
320 bool stopped_by_sw_breakpoint () override
321 {
50838d1b
PA
322 windows_thread_info *th
323 = thread_rec (inferior_ptid, DONT_INVALIDATE_CONTEXT);
324 return th->stopped_at_software_breakpoint;
0a4afda3
TT
325 }
326
327 bool supports_stopped_by_sw_breakpoint () override
328 {
329 return true;
330 }
331
f6ac5f3d
PA
332 enum target_xfer_status xfer_partial (enum target_object object,
333 const char *annex,
334 gdb_byte *readbuf,
335 const gdb_byte *writebuf,
336 ULONGEST offset, ULONGEST len,
337 ULONGEST *xfered_len) override;
338
339 void files_info () override;
340
341 void kill () override;
342
343 void create_inferior (const char *, const std::string &,
344 char **, int) override;
345
346 void mourn_inferior () override;
347
57810aa7 348 bool thread_alive (ptid_t ptid) override;
f6ac5f3d 349
a068643d 350 std::string pid_to_str (ptid_t) override;
f6ac5f3d
PA
351
352 void interrupt () override;
353
354 char *pid_to_exec_file (int pid) override;
355
356 ptid_t get_ada_task_ptid (long lwp, long thread) override;
357
57810aa7 358 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
f6ac5f3d
PA
359
360 const char *thread_name (struct thread_info *) override;
5b6d1e4f
PA
361
362 int get_windows_debug_event (int pid, struct target_waitstatus *ourstatus);
50838d1b
PA
363
364 void do_initial_windows_stuff (DWORD pid, bool attaching);
f6ac5f3d
PA
365};
366
367static windows_nat_target the_windows_nat_target;
368
7e63b4e4
JB
369/* Set the MAPPINGS static global to OFFSETS.
370 See the description of MAPPINGS for more details. */
371
46f9f931 372static void
dc05df57 373windows_set_context_register_offsets (const int *offsets)
7e63b4e4
JB
374{
375 mappings = offsets;
376}
377
46f9f931
HD
378/* Set the function that should be used by this module to determine
379 whether a given register is a segment register or not. */
d40dc7a8 380
46f9f931 381static void
d40dc7a8
JB
382windows_set_segment_register_p (segment_register_p_ftype *fun)
383{
384 segment_register_p = fun;
385}
386
fa4ba8da
PM
387static void
388check (BOOL ok, const char *file, int line)
389{
390 if (!ok)
d50a0ce2
CV
391 printf_filtered ("error return %s:%d was %u\n", file, line,
392 (unsigned) GetLastError ());
fa4ba8da
PM
393}
394
28688adf 395/* See nat/windows-nat.h. */
8e61ebec 396
28688adf
TT
397windows_thread_info *
398windows_nat::thread_rec (ptid_t ptid, thread_disposition_type disposition)
24e60978 399{
93366324 400 for (windows_thread_info *th : thread_list)
28688adf 401 if (th->tid == ptid.lwp ())
3cee93ac 402 {
8e61ebec 403 if (!th->suspended)
3cee93ac 404 {
8e61ebec
TT
405 switch (disposition)
406 {
407 case DONT_INVALIDATE_CONTEXT:
408 /* Nothing. */
409 break;
410 case INVALIDATE_CONTEXT:
28688adf 411 if (ptid.lwp () != current_event.dwThreadId)
8e61ebec
TT
412 th->suspend ();
413 th->reload_context = true;
414 break;
415 case DONT_SUSPEND:
416 th->reload_context = true;
417 th->suspended = -1;
418 break;
419 }
3cee93ac
CF
420 }
421 return th;
422 }
423
424 return NULL;
425}
426
c559d709
JB
427/* Add a thread to the thread list.
428
429 PTID is the ptid of the thread to be added.
430 H is its Windows handle.
431 TLB is its thread local base.
432 MAIN_THREAD_P should be true if the thread to be added is
433 the main thread, false otherwise. */
434
876d1cd7 435static windows_thread_info *
c559d709 436windows_add_thread (ptid_t ptid, HANDLE h, void *tlb, bool main_thread_p)
3cee93ac 437{
876d1cd7 438 windows_thread_info *th;
2dc38344 439
7c7411bc 440 gdb_assert (ptid.lwp () != 0);
2dc38344 441
28688adf 442 if ((th = thread_rec (ptid, DONT_INVALIDATE_CONTEXT)))
3cee93ac
CF
443 return th;
444
e9534bd2 445 CORE_ADDR base = (CORE_ADDR) (uintptr_t) tlb;
46f9f931
HD
446#ifdef __x86_64__
447 /* For WOW64 processes, this is actually the pointer to the 64bit TIB,
448 and the 32bit TIB is exactly 2 pages after it. */
449 if (wow64_process)
e9534bd2 450 base += 0x2000;
46f9f931 451#endif
28688adf 452 th = new windows_thread_info (ptid.lwp (), h, base);
93366324 453 thread_list.push_back (th);
c559d709
JB
454
455 /* Add this new thread to the list of threads.
456
457 To be consistent with what's done on other platforms, we add
458 the main thread silently (in reality, this thread is really
459 more of a process to the user than a thread). */
460 if (main_thread_p)
5b6d1e4f 461 add_thread_silent (&the_windows_nat_target, ptid);
c559d709 462 else
5b6d1e4f 463 add_thread (&the_windows_nat_target, ptid);
c559d709 464
2dc38344 465 /* Set the debug registers for the new thread if they are used. */
fa4ba8da
PM
466 if (debug_registers_used)
467 {
46f9f931
HD
468#ifdef __x86_64__
469 if (wow64_process)
470 {
471 /* Only change the value of the debug registers. */
472 th->wow64_context.ContextFlags = CONTEXT_DEBUG_REGISTERS;
473 CHECK (Wow64GetThreadContext (th->h, &th->wow64_context));
474 th->wow64_context.Dr0 = dr[0];
475 th->wow64_context.Dr1 = dr[1];
476 th->wow64_context.Dr2 = dr[2];
477 th->wow64_context.Dr3 = dr[3];
478 th->wow64_context.Dr6 = DR6_CLEAR_VALUE;
479 th->wow64_context.Dr7 = dr[7];
480 CHECK (Wow64SetThreadContext (th->h, &th->wow64_context));
481 th->wow64_context.ContextFlags = 0;
482 }
483 else
484#endif
485 {
486 /* Only change the value of the debug registers. */
487 th->context.ContextFlags = CONTEXT_DEBUG_REGISTERS;
488 CHECK (GetThreadContext (th->h, &th->context));
489 th->context.Dr0 = dr[0];
490 th->context.Dr1 = dr[1];
491 th->context.Dr2 = dr[2];
492 th->context.Dr3 = dr[3];
493 th->context.Dr6 = DR6_CLEAR_VALUE;
494 th->context.Dr7 = dr[7];
495 CHECK (SetThreadContext (th->h, &th->context));
496 th->context.ContextFlags = 0;
497 }
fa4ba8da 498 }
3cee93ac 499 return th;
24e60978
SC
500}
501
26c4b26f 502/* Clear out any old thread list and reinitialize it to a
581e13c1 503 pristine state. */
24e60978 504static void
dc05df57 505windows_init_thread_list (void)
24e60978 506{
dc05df57 507 DEBUG_EVENTS (("gdb: windows_init_thread_list\n"));
3cee93ac 508 init_thread_list ();
93366324
TT
509
510 for (windows_thread_info *here : thread_list)
e9534bd2 511 delete here;
93366324
TT
512
513 thread_list.clear ();
3cee93ac
CF
514}
515
c559d709
JB
516/* Delete a thread from the list of threads.
517
518 PTID is the ptid of the thread to be deleted.
519 EXIT_CODE is the thread's exit code.
520 MAIN_THREAD_P should be true if the thread to be deleted is
521 the main thread, false otherwise. */
522
3cee93ac 523static void
c559d709 524windows_delete_thread (ptid_t ptid, DWORD exit_code, bool main_thread_p)
3cee93ac 525{
2dc38344
PA
526 DWORD id;
527
7c7411bc 528 gdb_assert (ptid.lwp () != 0);
2dc38344 529
7c7411bc 530 id = ptid.lwp ();
3cee93ac 531
c559d709
JB
532 /* Emit a notification about the thread being deleted.
533
534 Note that no notification was printed when the main thread
535 was created, and thus, unless in verbose mode, we should be
85102364 536 symmetrical, and avoid that notification for the main thread
c559d709
JB
537 here as well. */
538
3cee93ac 539 if (info_verbose)
a068643d 540 printf_unfiltered ("[Deleting %s]\n", target_pid_to_str (ptid).c_str ());
c559d709 541 else if (print_thread_events && !main_thread_p)
e0ea48a0 542 printf_unfiltered (_("[%s exited with code %u]\n"),
a068643d
TT
543 target_pid_to_str (ptid).c_str (),
544 (unsigned) exit_code);
c559d709 545
5b6d1e4f 546 delete_thread (find_thread_ptid (&the_windows_nat_target, ptid));
3cee93ac 547
93366324
TT
548 auto iter = std::find_if (thread_list.begin (), thread_list.end (),
549 [=] (windows_thread_info *th)
550 {
55a1e039 551 return th->tid == id;
93366324 552 });
3cee93ac 553
93366324 554 if (iter != thread_list.end ())
24e60978 555 {
e9534bd2 556 delete *iter;
93366324 557 thread_list.erase (iter);
24e60978
SC
558 }
559}
560
9a325b7b
JB
561/* Fetches register number R from the given windows_thread_info,
562 and supplies its value to the given regcache.
563
564 This function assumes that R is non-negative. A failed assertion
565 is raised if that is not true.
566
567 This function assumes that TH->RELOAD_CONTEXT is not set, meaning
568 that the windows_thread_info has an up-to-date context. A failed
569 assertion is raised if that assumption is violated. */
570
3cee93ac 571static void
9a325b7b
JB
572windows_fetch_one_register (struct regcache *regcache,
573 windows_thread_info *th, int r)
24e60978 574{
9a325b7b
JB
575 gdb_assert (r >= 0);
576 gdb_assert (!th->reload_context);
577
46f9f931
HD
578 char *context_ptr = (char *) &th->context;
579#ifdef __x86_64__
580 if (wow64_process)
581 context_ptr = (char *) &th->wow64_context;
582#endif
583
584 char *context_offset = context_ptr + mappings[r];
ac7936df 585 struct gdbarch *gdbarch = regcache->arch ();
20a6ec49 586 struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
9a325b7b 587
0a4afda3
TT
588 gdb_assert (!gdbarch_read_pc_p (gdbarch));
589 gdb_assert (gdbarch_pc_regnum (gdbarch) >= 0);
590 gdb_assert (!gdbarch_write_pc_p (gdbarch));
591
9a325b7b
JB
592 if (r == I387_FISEG_REGNUM (tdep))
593 {
594 long l = *((long *) context_offset) & 0xffff;
595 regcache->raw_supply (r, (char *) &l);
596 }
597 else if (r == I387_FOP_REGNUM (tdep))
598 {
599 long l = (*((long *) context_offset) >> 16) & ((1 << 11) - 1);
600 regcache->raw_supply (r, (char *) &l);
601 }
602 else if (segment_register_p (r))
603 {
604 /* GDB treats segment registers as 32bit registers, but they are
605 in fact only 16 bits long. Make sure we do not read extra
606 bits from our source buffer. */
607 long l = *((long *) context_offset) & 0xffff;
608 regcache->raw_supply (r, (char *) &l);
609 }
610 else
0a4afda3
TT
611 {
612 if (th->stopped_at_software_breakpoint
7be2bb4f 613 && !th->pc_adjusted
0a4afda3
TT
614 && r == gdbarch_pc_regnum (gdbarch))
615 {
616 int size = register_size (gdbarch, r);
617 if (size == 4)
618 {
619 uint32_t value;
620 memcpy (&value, context_offset, size);
621 value -= gdbarch_decr_pc_after_break (gdbarch);
622 memcpy (context_offset, &value, size);
623 }
624 else
625 {
626 gdb_assert (size == 8);
627 uint64_t value;
628 memcpy (&value, context_offset, size);
629 value -= gdbarch_decr_pc_after_break (gdbarch);
630 memcpy (context_offset, &value, size);
631 }
7be2bb4f
TT
632 /* Make sure we only rewrite the PC a single time. */
633 th->pc_adjusted = true;
0a4afda3
TT
634 }
635 regcache->raw_supply (r, context_offset);
636 }
9a325b7b
JB
637}
638
639void
640windows_nat_target::fetch_registers (struct regcache *regcache, int r)
641{
28688adf 642 windows_thread_info *th = thread_rec (regcache->ptid (), INVALIDATE_CONTEXT);
9a325b7b
JB
643
644 /* Check if TH exists. Windows sometimes uses a non-existent
645 thread id in its events. */
646 if (th == NULL)
647 return;
6c7de422 648
3de88e9a 649 if (th->reload_context)
3ade5333 650 {
f20c58f5 651#ifdef __CYGWIN__
a244bdca
CF
652 if (have_saved_context)
653 {
581e13c1
MS
654 /* Lie about where the program actually is stopped since
655 cygwin has informed us that we should consider the signal
656 to have occurred at another location which is stored in
657 "saved_context. */
3de88e9a 658 memcpy (&th->context, &saved_context,
581e13c1 659 __COPY_CONTEXT_SIZE);
a244bdca
CF
660 have_saved_context = 0;
661 }
662 else
46f9f931
HD
663#endif
664#ifdef __x86_64__
665 if (wow64_process)
666 {
667 th->wow64_context.ContextFlags = CONTEXT_DEBUGGER_DR;
668 CHECK (Wow64GetThreadContext (th->h, &th->wow64_context));
669 /* Copy dr values from that thread.
670 But only if there were not modified since last stop.
671 PR gdb/2388 */
672 if (!debug_registers_changed)
673 {
674 dr[0] = th->wow64_context.Dr0;
675 dr[1] = th->wow64_context.Dr1;
676 dr[2] = th->wow64_context.Dr2;
677 dr[3] = th->wow64_context.Dr3;
678 dr[6] = th->wow64_context.Dr6;
679 dr[7] = th->wow64_context.Dr7;
680 }
681 }
682 else
cb832706 683#endif
a244bdca 684 {
a244bdca 685 th->context.ContextFlags = CONTEXT_DEBUGGER_DR;
17617f2d 686 CHECK (GetThreadContext (th->h, &th->context));
2b008701 687 /* Copy dr values from that thread.
581e13c1
MS
688 But only if there were not modified since last stop.
689 PR gdb/2388 */
88616312
PM
690 if (!debug_registers_changed)
691 {
692 dr[0] = th->context.Dr0;
693 dr[1] = th->context.Dr1;
694 dr[2] = th->context.Dr2;
695 dr[3] = th->context.Dr3;
696 dr[6] = th->context.Dr6;
697 dr[7] = th->context.Dr7;
698 }
a244bdca 699 }
62fe396b 700 th->reload_context = false;
3ade5333
CF
701 }
702
9a325b7b
JB
703 if (r < 0)
704 for (r = 0; r < gdbarch_num_regs (regcache->arch()); r++)
705 windows_fetch_one_register (regcache, th, r);
3cee93ac 706 else
9a325b7b 707 windows_fetch_one_register (regcache, th, r);
3cee93ac
CF
708}
709
9a325b7b
JB
710/* Collect the register number R from the given regcache, and store
711 its value into the corresponding area of the given thread's context.
3de88e9a 712
9a325b7b
JB
713 This function assumes that R is non-negative. A failed assertion
714 assertion is raised if that is not true. */
3cee93ac
CF
715
716static void
9a325b7b
JB
717windows_store_one_register (const struct regcache *regcache,
718 windows_thread_info *th, int r)
3cee93ac 719{
9a325b7b
JB
720 gdb_assert (r >= 0);
721
46f9f931
HD
722 char *context_ptr = (char *) &th->context;
723#ifdef __x86_64__
724 if (wow64_process)
725 context_ptr = (char *) &th->wow64_context;
726#endif
727
728 regcache->raw_collect (r, context_ptr + mappings[r]);
24e60978
SC
729}
730
3de88e9a
SM
731/* Store a new register value into the context of the thread tied to
732 REGCACHE. */
f6ac5f3d
PA
733
734void
735windows_nat_target::store_registers (struct regcache *regcache, int r)
3cee93ac 736{
28688adf 737 windows_thread_info *th = thread_rec (regcache->ptid (), INVALIDATE_CONTEXT);
3de88e9a
SM
738
739 /* Check if TH exists. Windows sometimes uses a non-existent
581e13c1 740 thread id in its events. */
9a325b7b
JB
741 if (th == NULL)
742 return;
743
744 if (r < 0)
745 for (r = 0; r < gdbarch_num_regs (regcache->arch ()); r++)
746 windows_store_one_register (regcache, th, r);
747 else
748 windows_store_one_register (regcache, th, r);
3cee93ac 749}
24e60978 750
581e13c1 751/* Maintain a linked list of "so" information. */
d0e449a1 752struct lm_info_windows : public lm_info_base
02e423b9 753{
f8fdb78e 754 LPVOID load_addr = 0;
c162ed3e 755 CORE_ADDR text_offset = 0;
3ee6f623
CF
756};
757
758static struct so_list solib_start, *solib_end;
02e423b9 759
de1b3c3d 760static struct so_list *
dc05df57 761windows_make_so (const char *name, LPVOID load_addr)
8e860359 762{
3ee6f623 763 struct so_list *so;
d0d0ab16
CV
764 char *p;
765#ifndef __CYGWIN__
b3c613f2
CF
766 char buf[__PMAX];
767 char cwd[__PMAX];
3f8ad85b
CF
768 WIN32_FIND_DATA w32_fd;
769 HANDLE h = FindFirstFile(name, &w32_fd);
3f8ad85b 770
6badb179
CF
771 if (h == INVALID_HANDLE_VALUE)
772 strcpy (buf, name);
773 else
3f8ad85b 774 {
c914e0cc
CF
775 FindClose (h);
776 strcpy (buf, name);
777 if (GetCurrentDirectory (MAX_PATH + 1, cwd))
778 {
779 p = strrchr (buf, '\\');
780 if (p)
781 p[1] = '\0';
782 SetCurrentDirectory (buf);
783 GetFullPathName (w32_fd.cFileName, MAX_PATH, buf, &p);
784 SetCurrentDirectory (cwd);
785 }
3f8ad85b 786 }
3ee6f623
CF
787 if (strcasecmp (buf, "ntdll.dll") == 0)
788 {
789 GetSystemDirectory (buf, sizeof (buf));
790 strcat (buf, "\\ntdll.dll");
791 }
d0d0ab16 792#else
b3c613f2 793 cygwin_buf_t buf[__PMAX];
d0d0ab16 794
b3c613f2 795 buf[0] = 0;
d0d0ab16
CV
796 if (access (name, F_OK) != 0)
797 {
798 if (strcasecmp (name, "ntdll.dll") == 0)
b3c613f2 799#ifdef __USEWIDE
d0d0ab16
CV
800 {
801 GetSystemDirectoryW (buf, sizeof (buf) / sizeof (wchar_t));
802 wcscat (buf, L"\\ntdll.dll");
803 }
b3c613f2
CF
804#else
805 {
806 GetSystemDirectoryA (buf, sizeof (buf) / sizeof (wchar_t));
807 strcat (buf, "\\ntdll.dll");
808 }
809#endif
d0d0ab16
CV
810 }
811#endif
41bf6aca 812 so = XCNEW (struct so_list);
f8fdb78e 813 lm_info_windows *li = new lm_info_windows;
d0e449a1
SM
814 so->lm_info = li;
815 li->load_addr = load_addr;
de1b3c3d 816 strcpy (so->so_original_name, name);
10325bc5
PA
817#ifndef __CYGWIN__
818 strcpy (so->so_name, buf);
819#else
d0d0ab16
CV
820 if (buf[0])
821 cygwin_conv_path (CCP_WIN_W_TO_POSIX, buf, so->so_name,
822 SO_NAME_MAX_PATH_SIZE);
823 else
824 {
60c5c021 825 char *rname = realpath (name, NULL);
d0d0ab16
CV
826 if (rname && strlen (rname) < SO_NAME_MAX_PATH_SIZE)
827 {
828 strcpy (so->so_name, rname);
829 free (rname);
830 }
831 else
a0e9b532
JT
832 {
833 warning (_("dll path for \"%s\" too long or inaccessible"), name);
834 strcpy (so->so_name, so->so_original_name);
835 }
d0d0ab16 836 }
de1b3c3d
PA
837 /* Record cygwin1.dll .text start/end. */
838 p = strchr (so->so_name, '\0') - (sizeof ("/cygwin1.dll") - 1);
839 if (p >= so->so_name && strcasecmp (p, "/cygwin1.dll") == 0)
840 {
de1b3c3d 841 asection *text = NULL;
8e860359 842
ad80db5b 843 gdb_bfd_ref_ptr abfd (gdb_bfd_open (so->so_name, "pei-i386"));
a244bdca 844
192b62ce 845 if (abfd == NULL)
de1b3c3d
PA
846 return so;
847
192b62ce
TT
848 if (bfd_check_format (abfd.get (), bfd_object))
849 text = bfd_get_section_by_name (abfd.get (), ".text");
de1b3c3d
PA
850
851 if (!text)
192b62ce 852 return so;
de1b3c3d 853
7a9dd1b2 854 /* The symbols in a dll are offset by 0x1000, which is the
de1b3c3d 855 offset from 0 of the first byte in an image - because of the
581e13c1
MS
856 file header and the section alignment. */
857 cygwin_load_start = (CORE_ADDR) (uintptr_t) ((char *)
858 load_addr + 0x1000);
fd361982 859 cygwin_load_end = cygwin_load_start + bfd_section_size (text);
de1b3c3d 860 }
10325bc5 861#endif
de1b3c3d
PA
862
863 return so;
8e860359
CF
864}
865
a816ba18 866/* See nat/windows-nat.h. */
1cd9feab 867
a816ba18
TT
868void
869windows_nat::handle_load_dll ()
24e60978 870{
3a4b77d8 871 LOAD_DLL_DEBUG_INFO *event = &current_event.u.LoadDll;
9d8679cc 872 const char *dll_name;
24e60978 873
94481b8c
JB
874 /* Try getting the DLL name via the lpImageName field of the event.
875 Note that Microsoft documents this fields as strictly optional,
876 in the sense that it might be NULL. And the first DLL event in
877 particular is explicitly documented as "likely not pass[ed]"
878 (source: MSDN LOAD_DLL_DEBUG_INFO structure). */
1cd9feab
JB
879 dll_name = get_image_name (current_process_handle,
880 event->lpImageName, event->fUnicode);
3cee93ac 881 if (!dll_name)
bf469271 882 return;
3cee93ac 883
dc05df57 884 solib_end->next = windows_make_so (dll_name, event->lpBaseOfDll);
de1b3c3d 885 solib_end = solib_end->next;
450005e7 886
d0e449a1
SM
887 lm_info_windows *li = (lm_info_windows *) solib_end->lm_info;
888
a74ce742 889 DEBUG_EVENTS (("gdb: Loading dll \"%s\" at %s.\n", solib_end->so_name,
d0e449a1 890 host_address_to_string (li->load_addr)));
450005e7
CF
891}
892
3ee6f623 893static void
dc05df57 894windows_free_so (struct so_list *so)
3ee6f623 895{
f8fdb78e
SM
896 lm_info_windows *li = (lm_info_windows *) so->lm_info;
897
898 delete li;
de1b3c3d 899 xfree (so);
3cb8e7f6
CF
900}
901
a816ba18 902/* See nat/windows-nat.h. */
3be75f87 903
a816ba18
TT
904void
905windows_nat::handle_unload_dll ()
d3ff4a77 906{
d3653bf6 907 LPVOID lpBaseOfDll = current_event.u.UnloadDll.lpBaseOfDll;
3ee6f623 908 struct so_list *so;
d3ff4a77
CF
909
910 for (so = &solib_start; so->next != NULL; so = so->next)
d0e449a1
SM
911 {
912 lm_info_windows *li_next = (lm_info_windows *) so->next->lm_info;
a25cd31f 913
d0e449a1
SM
914 if (li_next->load_addr == lpBaseOfDll)
915 {
916 struct so_list *sodel = so->next;
7488902c 917
d0e449a1
SM
918 so->next = sodel->next;
919 if (!so->next)
920 solib_end = so;
921 DEBUG_EVENTS (("gdb: Unloading dll \"%s\".\n", sodel->so_name));
922
923 windows_free_so (sodel);
bf469271 924 return;
d0e449a1
SM
925 }
926 }
3929abe9 927
ecc13e53
JB
928 /* We did not find any DLL that was previously loaded at this address,
929 so register a complaint. We do not report an error, because we have
930 observed that this may be happening under some circumstances. For
931 instance, running 32bit applications on x64 Windows causes us to receive
932 4 mysterious UNLOAD_DLL_DEBUG_EVENTs during the startup phase (these
933 events are apparently caused by the WOW layer, the interface between
934 32bit and 64bit worlds). */
b98664d3 935 complaint (_("dll starting at %s not found."),
ecc13e53 936 host_address_to_string (lpBaseOfDll));
bf469271
PA
937}
938
939/* Call FUNC wrapped in a TRY/CATCH that swallows all GDB
940 exceptions. */
d3ff4a77 941
bf469271
PA
942static void
943catch_errors (void (*func) ())
944{
a70b8144 945 try
bf469271
PA
946 {
947 func ();
948 }
230d2906 949 catch (const gdb_exception &ex)
bf469271
PA
950 {
951 exception_print (gdb_stderr, ex);
952 }
d3ff4a77
CF
953}
954
581e13c1 955/* Clear list of loaded DLLs. */
3ee6f623 956static void
dc05df57 957windows_clear_solib (void)
450005e7 958{
25057eb0
HD
959 struct so_list *so;
960
961 for (so = solib_start.next; so; so = solib_start.next)
962 {
963 solib_start.next = so->next;
964 windows_free_so (so);
965 }
966
450005e7 967 solib_end = &solib_start;
450005e7 968}
295732ea 969
463888ab 970static void
0b39b52e 971signal_event_command (const char *args, int from_tty)
463888ab
РИ
972{
973 uintptr_t event_id = 0;
974 char *endargs = NULL;
975
976 if (args == NULL)
977 error (_("signal-event requires an argument (integer event id)"));
978
979 event_id = strtoumax (args, &endargs, 10);
980
981 if ((errno == ERANGE) || (event_id == 0) || (event_id > UINTPTR_MAX) ||
982 ((HANDLE) event_id == INVALID_HANDLE_VALUE))
983 error (_("Failed to convert `%s' to event id"), args);
984
985 SetEvent ((HANDLE) event_id);
986 CloseHandle ((HANDLE) event_id);
987}
988
d41b524f
TT
989/* See nat/windows-nat.h. */
990
991int
992windows_nat::handle_output_debug_string (struct target_waitstatus *ourstatus)
3cee93ac 993{
a244bdca 994 int retval = 0;
3cee93ac 995
66920317
TT
996 gdb::unique_xmalloc_ptr<char> s
997 = (target_read_string
998 ((CORE_ADDR) (uintptr_t) current_event.u.DebugString.lpDebugStringData,
999 1024));
1000 if (s == nullptr || !*(s.get ()))
a244bdca 1001 /* nothing to do */;
e83e4e24 1002 else if (!startswith (s.get (), _CYGWIN_SIGNAL_STRING))
3cee93ac 1003 {
10325bc5 1004#ifdef __CYGWIN__
e83e4e24 1005 if (!startswith (s.get (), "cYg"))
10325bc5 1006#endif
040ea00b 1007 {
e83e4e24 1008 char *p = strchr (s.get (), '\0');
040ea00b 1009
e83e4e24 1010 if (p > s.get () && *--p == '\n')
040ea00b 1011 *p = '\0';
e83e4e24 1012 warning (("%s"), s.get ());
040ea00b 1013 }
3cee93ac 1014 }
f20c58f5 1015#ifdef __CYGWIN__
d3a09475 1016 else
3cee93ac 1017 {
581e13c1
MS
1018 /* Got a cygwin signal marker. A cygwin signal is followed by
1019 the signal number itself and then optionally followed by the
1020 thread id and address to saved context within the DLL. If
1021 these are supplied, then the given thread is assumed to have
1022 issued the signal and the context from the thread is assumed
1023 to be stored at the given address in the inferior. Tell gdb
1024 to treat this like a real signal. */
3cee93ac 1025 char *p;
e83e4e24 1026 int sig = strtol (s.get () + sizeof (_CYGWIN_SIGNAL_STRING) - 1, &p, 0);
0ae534d2 1027 gdb_signal gotasig = gdb_signal_from_host (sig);
c62fa0e2 1028
0714f9bf
SS
1029 ourstatus->value.sig = gotasig;
1030 if (gotasig)
a244bdca
CF
1031 {
1032 LPCVOID x;
2c15ef43 1033 SIZE_T n;
c62fa0e2 1034
a244bdca
CF
1035 ourstatus->kind = TARGET_WAITKIND_STOPPED;
1036 retval = strtoul (p, &p, 0);
1037 if (!retval)
ab4ee614 1038 retval = current_event.dwThreadId;
40653b35 1039 else if ((x = (LPCVOID) (uintptr_t) strtoull (p, NULL, 0))
a244bdca 1040 && ReadProcessMemory (current_process_handle, x,
581e13c1
MS
1041 &saved_context,
1042 __COPY_CONTEXT_SIZE, &n)
a244bdca
CF
1043 && n == __COPY_CONTEXT_SIZE)
1044 have_saved_context = 1;
a244bdca 1045 }
3cee93ac 1046 }
cb832706 1047#endif
3cee93ac 1048
a244bdca 1049 return retval;
3cee93ac 1050}
24e60978 1051
c1748f97
PM
1052static int
1053display_selector (HANDLE thread, DWORD sel)
1054{
1055 LDT_ENTRY info;
46f9f931
HD
1056 BOOL ret;
1057#ifdef __x86_64__
1058 if (wow64_process)
1059 ret = Wow64GetThreadSelectorEntry (thread, sel, &info);
1060 else
1061#endif
1062 ret = GetThreadSelectorEntry (thread, sel, &info);
1063 if (ret)
c1748f97
PM
1064 {
1065 int base, limit;
d50a0ce2 1066 printf_filtered ("0x%03x: ", (unsigned) sel);
c1748f97 1067 if (!info.HighWord.Bits.Pres)
baa93fa6
CF
1068 {
1069 puts_filtered ("Segment not present\n");
1070 return 0;
1071 }
c1748f97
PM
1072 base = (info.HighWord.Bits.BaseHi << 24) +
1073 (info.HighWord.Bits.BaseMid << 16)
1074 + info.BaseLow;
1075 limit = (info.HighWord.Bits.LimitHi << 16) + info.LimitLow;
1076 if (info.HighWord.Bits.Granularity)
caad7706 1077 limit = (limit << 12) | 0xfff;
c1748f97
PM
1078 printf_filtered ("base=0x%08x limit=0x%08x", base, limit);
1079 if (info.HighWord.Bits.Default_Big)
baa93fa6 1080 puts_filtered(" 32-bit ");
c1748f97 1081 else
baa93fa6 1082 puts_filtered(" 16-bit ");
c1748f97
PM
1083 switch ((info.HighWord.Bits.Type & 0xf) >> 1)
1084 {
1085 case 0:
baa93fa6
CF
1086 puts_filtered ("Data (Read-Only, Exp-up");
1087 break;
c1748f97 1088 case 1:
baa93fa6
CF
1089 puts_filtered ("Data (Read/Write, Exp-up");
1090 break;
c1748f97 1091 case 2:
baa93fa6
CF
1092 puts_filtered ("Unused segment (");
1093 break;
c1748f97 1094 case 3:
baa93fa6
CF
1095 puts_filtered ("Data (Read/Write, Exp-down");
1096 break;
c1748f97 1097 case 4:
baa93fa6
CF
1098 puts_filtered ("Code (Exec-Only, N.Conf");
1099 break;
c1748f97 1100 case 5:
baa93fa6 1101 puts_filtered ("Code (Exec/Read, N.Conf");
c1748f97
PM
1102 break;
1103 case 6:
baa93fa6 1104 puts_filtered ("Code (Exec-Only, Conf");
c1748f97
PM
1105 break;
1106 case 7:
baa93fa6 1107 puts_filtered ("Code (Exec/Read, Conf");
c1748f97
PM
1108 break;
1109 default:
e432ccf1
JT
1110 printf_filtered ("Unknown type 0x%lx",
1111 (unsigned long) info.HighWord.Bits.Type);
c1748f97
PM
1112 }
1113 if ((info.HighWord.Bits.Type & 0x1) == 0)
baa93fa6 1114 puts_filtered(", N.Acc");
c1748f97
PM
1115 puts_filtered (")\n");
1116 if ((info.HighWord.Bits.Type & 0x10) == 0)
1117 puts_filtered("System selector ");
e432ccf1
JT
1118 printf_filtered ("Priviledge level = %ld. ",
1119 (unsigned long) info.HighWord.Bits.Dpl);
c1748f97 1120 if (info.HighWord.Bits.Granularity)
baa93fa6 1121 puts_filtered ("Page granular.\n");
c1748f97
PM
1122 else
1123 puts_filtered ("Byte granular.\n");
1124 return 1;
1125 }
1126 else
1127 {
5572ce1f
PM
1128 DWORD err = GetLastError ();
1129 if (err == ERROR_NOT_SUPPORTED)
1130 printf_filtered ("Function not supported\n");
1131 else
d50a0ce2 1132 printf_filtered ("Invalid selector 0x%x.\n", (unsigned) sel);
c1748f97
PM
1133 return 0;
1134 }
1135}
1136
1137static void
5fed81ff 1138display_selectors (const char * args, int from_tty)
c1748f97 1139{
50838d1b 1140 if (inferior_ptid == null_ptid)
c1748f97
PM
1141 {
1142 puts_filtered ("Impossible to display selectors now.\n");
1143 return;
1144 }
50838d1b
PA
1145
1146 windows_thread_info *current_windows_thread
1147 = thread_rec (inferior_ptid, DONT_INVALIDATE_CONTEXT);
1148
c1748f97
PM
1149 if (!args)
1150 {
46f9f931
HD
1151#ifdef __x86_64__
1152 if (wow64_process)
1153 {
1154 puts_filtered ("Selector $cs\n");
3c76026d
TT
1155 display_selector (current_windows_thread->h,
1156 current_windows_thread->wow64_context.SegCs);
46f9f931 1157 puts_filtered ("Selector $ds\n");
3c76026d
TT
1158 display_selector (current_windows_thread->h,
1159 current_windows_thread->wow64_context.SegDs);
46f9f931 1160 puts_filtered ("Selector $es\n");
3c76026d
TT
1161 display_selector (current_windows_thread->h,
1162 current_windows_thread->wow64_context.SegEs);
46f9f931 1163 puts_filtered ("Selector $ss\n");
3c76026d
TT
1164 display_selector (current_windows_thread->h,
1165 current_windows_thread->wow64_context.SegSs);
46f9f931 1166 puts_filtered ("Selector $fs\n");
3c76026d
TT
1167 display_selector (current_windows_thread->h,
1168 current_windows_thread->wow64_context.SegFs);
46f9f931 1169 puts_filtered ("Selector $gs\n");
3c76026d
TT
1170 display_selector (current_windows_thread->h,
1171 current_windows_thread->wow64_context.SegGs);
46f9f931
HD
1172 }
1173 else
1174#endif
1175 {
1176 puts_filtered ("Selector $cs\n");
3c76026d
TT
1177 display_selector (current_windows_thread->h,
1178 current_windows_thread->context.SegCs);
46f9f931 1179 puts_filtered ("Selector $ds\n");
3c76026d
TT
1180 display_selector (current_windows_thread->h,
1181 current_windows_thread->context.SegDs);
46f9f931 1182 puts_filtered ("Selector $es\n");
3c76026d
TT
1183 display_selector (current_windows_thread->h,
1184 current_windows_thread->context.SegEs);
46f9f931 1185 puts_filtered ("Selector $ss\n");
3c76026d
TT
1186 display_selector (current_windows_thread->h,
1187 current_windows_thread->context.SegSs);
46f9f931 1188 puts_filtered ("Selector $fs\n");
3c76026d
TT
1189 display_selector (current_windows_thread->h,
1190 current_windows_thread->context.SegFs);
46f9f931 1191 puts_filtered ("Selector $gs\n");
3c76026d
TT
1192 display_selector (current_windows_thread->h,
1193 current_windows_thread->context.SegGs);
46f9f931 1194 }
c1748f97
PM
1195 }
1196 else
1197 {
1198 int sel;
1199 sel = parse_and_eval_long (args);
1200 printf_filtered ("Selector \"%s\"\n",args);
3c76026d 1201 display_selector (current_windows_thread->h, sel);
c1748f97
PM
1202 }
1203}
1204
8d30e395 1205/* See nat/windows-nat.h. */
7393af7c 1206
8d30e395
TT
1207bool
1208windows_nat::handle_ms_vc_exception (const EXCEPTION_RECORD *rec)
24e60978 1209{
8d30e395
TT
1210 if (rec->NumberParameters >= 3
1211 && (rec->ExceptionInformation[0] & 0xffffffff) == 0x1000)
24e60978 1212 {
8d30e395
TT
1213 DWORD named_thread_id;
1214 windows_thread_info *named_thread;
1215 CORE_ADDR thread_name_target;
24cdb46e 1216
8d30e395
TT
1217 thread_name_target = rec->ExceptionInformation[1];
1218 named_thread_id = (DWORD) (0xffffffff & rec->ExceptionInformation[2]);
24cdb46e 1219
8d30e395
TT
1220 if (named_thread_id == (DWORD) -1)
1221 named_thread_id = current_event.dwThreadId;
24cdb46e 1222
8d30e395
TT
1223 named_thread = thread_rec (ptid_t (current_event.dwProcessId,
1224 named_thread_id, 0),
1225 DONT_INVALIDATE_CONTEXT);
1226 if (named_thread != NULL)
1227 {
1228 int thread_name_len;
66920317
TT
1229 gdb::unique_xmalloc_ptr<char> thread_name
1230 = target_read_string (thread_name_target, 1025, &thread_name_len);
8d30e395 1231 if (thread_name_len > 0)
24cdb46e 1232 {
8d30e395
TT
1233 thread_name.get ()[thread_name_len - 1] = '\0';
1234 named_thread->name = std::move (thread_name);
24cdb46e 1235 }
24cdb46e 1236 }
8d30e395
TT
1237
1238 return true;
24e60978 1239 }
8d30e395
TT
1240
1241 return false;
24e60978
SC
1242}
1243
a010605f
TT
1244/* See nat/windows-nat.h. */
1245
1246bool
1247windows_nat::handle_access_violation (const EXCEPTION_RECORD *rec)
1248{
1249#ifdef __CYGWIN__
1250 /* See if the access violation happened within the cygwin DLL
1251 itself. Cygwin uses a kind of exception handling to deal with
1252 passed-in invalid addresses. gdb should not treat these as real
1253 SEGVs since they will be silently handled by cygwin. A real SEGV
1254 will (theoretically) be caught by cygwin later in the process and
1255 will be sent as a cygwin-specific-signal. So, ignore SEGVs if
1256 they show up within the text segment of the DLL itself. */
1257 const char *fn;
1258 CORE_ADDR addr = (CORE_ADDR) (uintptr_t) rec->ExceptionAddress;
1259
1260 if ((!cygwin_exceptions && (addr >= cygwin_load_start
1261 && addr < cygwin_load_end))
1262 || (find_pc_partial_function (addr, &fn, NULL, NULL)
1263 && startswith (fn, "KERNEL32!IsBad")))
1264 return true;
1265#endif
1266 return false;
1267}
1268
17617f2d
EZ
1269/* Resume thread specified by ID, or all artificially suspended
1270 threads, if we are continuing execution. KILLED non-zero means we
1271 have killed the inferior, so we should ignore weird errors due to
1272 threads shutting down. */
3cee93ac 1273static BOOL
17617f2d 1274windows_continue (DWORD continue_status, int id, int killed)
3cee93ac 1275{
3cee93ac
CF
1276 BOOL res;
1277
0a4afda3
TT
1278 desired_stop_thread_id = id;
1279
e758e19c
TT
1280 if (matching_pending_stop (debug_events))
1281 return TRUE;
6537bb24 1282
93366324 1283 for (windows_thread_info *th : thread_list)
0a4afda3 1284 if (id == -1 || id == (int) th->tid)
6537bb24 1285 {
0a4afda3
TT
1286 if (!th->suspended)
1287 continue;
46f9f931
HD
1288#ifdef __x86_64__
1289 if (wow64_process)
6537bb24 1290 {
46f9f931
HD
1291 if (debug_registers_changed)
1292 {
1293 th->wow64_context.ContextFlags |= CONTEXT_DEBUG_REGISTERS;
1294 th->wow64_context.Dr0 = dr[0];
1295 th->wow64_context.Dr1 = dr[1];
1296 th->wow64_context.Dr2 = dr[2];
1297 th->wow64_context.Dr3 = dr[3];
1298 th->wow64_context.Dr6 = DR6_CLEAR_VALUE;
1299 th->wow64_context.Dr7 = dr[7];
1300 }
1301 if (th->wow64_context.ContextFlags)
1302 {
1303 DWORD ec = 0;
1304
1305 if (GetExitCodeThread (th->h, &ec)
1306 && ec == STILL_ACTIVE)
1307 {
1308 BOOL status = Wow64SetThreadContext (th->h,
1309 &th->wow64_context);
1310
1311 if (!killed)
1312 CHECK (status);
1313 }
1314 th->wow64_context.ContextFlags = 0;
1315 }
6537bb24 1316 }
46f9f931
HD
1317 else
1318#endif
6537bb24 1319 {
46f9f931 1320 if (debug_registers_changed)
17617f2d 1321 {
46f9f931
HD
1322 th->context.ContextFlags |= CONTEXT_DEBUG_REGISTERS;
1323 th->context.Dr0 = dr[0];
1324 th->context.Dr1 = dr[1];
1325 th->context.Dr2 = dr[2];
1326 th->context.Dr3 = dr[3];
1327 th->context.Dr6 = DR6_CLEAR_VALUE;
1328 th->context.Dr7 = dr[7];
1329 }
1330 if (th->context.ContextFlags)
1331 {
1332 DWORD ec = 0;
1333
1334 if (GetExitCodeThread (th->h, &ec)
1335 && ec == STILL_ACTIVE)
1336 {
1337 BOOL status = SetThreadContext (th->h, &th->context);
17617f2d 1338
46f9f931
HD
1339 if (!killed)
1340 CHECK (status);
1341 }
1342 th->context.ContextFlags = 0;
17617f2d 1343 }
6537bb24 1344 }
98a03287 1345 th->resume ();
6537bb24 1346 }
0a4afda3
TT
1347 else
1348 {
1349 /* When single-stepping a specific thread, other threads must
1350 be suspended. */
1351 th->suspend ();
1352 }
6537bb24 1353
e758e19c 1354 res = continue_last_debug_event (continue_status, debug_events);
3cee93ac 1355
68ffc902
JT
1356 if (!res)
1357 error (_("Failed to resume program execution"
1358 " (ContinueDebugEvent failed, error %u)"),
1359 (unsigned int) GetLastError ());
1360
fa4ba8da 1361 debug_registers_changed = 0;
3cee93ac
CF
1362 return res;
1363}
1364
d6dc8049
CF
1365/* Called in pathological case where Windows fails to send a
1366 CREATE_PROCESS_DEBUG_EVENT after an attach. */
3ee6f623 1367static DWORD
5439edaa 1368fake_create_process (void)
3ade5333
CF
1369{
1370 current_process_handle = OpenProcess (PROCESS_ALL_ACCESS, FALSE,
1371 current_event.dwProcessId);
bf25528d
CF
1372 if (current_process_handle != NULL)
1373 open_process_used = 1;
1374 else
1375 {
d50a0ce2
CV
1376 error (_("OpenProcess call failed, GetLastError = %u"),
1377 (unsigned) GetLastError ());
bf25528d
CF
1378 /* We can not debug anything in that case. */
1379 }
50838d1b
PA
1380 windows_add_thread (ptid_t (current_event.dwProcessId, 0,
1381 current_event.dwThreadId),
1382 current_event.u.CreateThread.hThread,
1383 current_event.u.CreateThread.lpThreadLocalBase,
1384 true /* main_thread_p */);
ab4ee614 1385 return current_event.dwThreadId;
3ade5333
CF
1386}
1387
f6ac5f3d
PA
1388void
1389windows_nat_target::resume (ptid_t ptid, int step, enum gdb_signal sig)
a244bdca 1390{
876d1cd7 1391 windows_thread_info *th;
a244bdca
CF
1392 DWORD continue_status = DBG_CONTINUE;
1393
2dc38344 1394 /* A specific PTID means `step only this thread id'. */
d7e15655 1395 int resume_all = ptid == minus_one_ptid;
2dc38344
PA
1396
1397 /* If we're continuing all threads, it's the current inferior that
1398 should be handled specially. */
1399 if (resume_all)
1400 ptid = inferior_ptid;
a244bdca 1401
a493e3e2 1402 if (sig != GDB_SIGNAL_0)
a244bdca
CF
1403 {
1404 if (current_event.dwDebugEventCode != EXCEPTION_DEBUG_EVENT)
1405 {
1406 DEBUG_EXCEPT(("Cannot continue with signal %d here.\n",sig));
1407 }
1408 else if (sig == last_sig)
1409 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1410 else
1411#if 0
1412/* This code does not seem to work, because
1413 the kernel does probably not consider changes in the ExceptionRecord
1414 structure when passing the exception to the inferior.
1415 Note that this seems possible in the exception handler itself. */
1416 {
73c13fe6
TT
1417 for (const xlate_exception &x : xlate)
1418 if (x.us == sig)
a244bdca 1419 {
581e13c1 1420 current_event.u.Exception.ExceptionRecord.ExceptionCode
73c13fe6 1421 = x.them;
a244bdca
CF
1422 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1423 break;
1424 }
1425 if (continue_status == DBG_CONTINUE)
1426 {
1427 DEBUG_EXCEPT(("Cannot continue with signal %d.\n",sig));
1428 }
1429 }
1430#endif
23942819 1431 DEBUG_EXCEPT(("Can only continue with received signal %d.\n",
a244bdca
CF
1432 last_sig));
1433 }
1434
a493e3e2 1435 last_sig = GDB_SIGNAL_0;
a244bdca 1436
55dfc88f 1437 DEBUG_EXEC (("gdb: windows_resume (pid=%d, tid=0x%x, step=%d, sig=%d);\n",
7c7411bc 1438 ptid.pid (), (unsigned) ptid.lwp (), step, sig));
a244bdca 1439
581e13c1 1440 /* Get context for currently selected thread. */
28688adf 1441 th = thread_rec (inferior_ptid, DONT_INVALIDATE_CONTEXT);
a244bdca
CF
1442 if (th)
1443 {
46f9f931
HD
1444#ifdef __x86_64__
1445 if (wow64_process)
a244bdca 1446 {
46f9f931
HD
1447 if (step)
1448 {
1449 /* Single step by setting t bit. */
1450 struct regcache *regcache = get_current_regcache ();
1451 struct gdbarch *gdbarch = regcache->arch ();
1452 fetch_registers (regcache, gdbarch_ps_regnum (gdbarch));
1453 th->wow64_context.EFlags |= FLAG_TRACE_BIT;
1454 }
a244bdca 1455
46f9f931
HD
1456 if (th->wow64_context.ContextFlags)
1457 {
1458 if (debug_registers_changed)
1459 {
1460 th->wow64_context.Dr0 = dr[0];
1461 th->wow64_context.Dr1 = dr[1];
1462 th->wow64_context.Dr2 = dr[2];
1463 th->wow64_context.Dr3 = dr[3];
1464 th->wow64_context.Dr6 = DR6_CLEAR_VALUE;
1465 th->wow64_context.Dr7 = dr[7];
1466 }
1467 CHECK (Wow64SetThreadContext (th->h, &th->wow64_context));
1468 th->wow64_context.ContextFlags = 0;
1469 }
1470 }
1471 else
1472#endif
a244bdca 1473 {
46f9f931 1474 if (step)
a244bdca 1475 {
46f9f931
HD
1476 /* Single step by setting t bit. */
1477 struct regcache *regcache = get_current_regcache ();
1478 struct gdbarch *gdbarch = regcache->arch ();
1479 fetch_registers (regcache, gdbarch_ps_regnum (gdbarch));
1480 th->context.EFlags |= FLAG_TRACE_BIT;
1481 }
1482
1483 if (th->context.ContextFlags)
1484 {
1485 if (debug_registers_changed)
1486 {
1487 th->context.Dr0 = dr[0];
1488 th->context.Dr1 = dr[1];
1489 th->context.Dr2 = dr[2];
1490 th->context.Dr3 = dr[3];
1491 th->context.Dr6 = DR6_CLEAR_VALUE;
1492 th->context.Dr7 = dr[7];
1493 }
1494 CHECK (SetThreadContext (th->h, &th->context));
1495 th->context.ContextFlags = 0;
a244bdca 1496 }
a244bdca
CF
1497 }
1498 }
1499
1500 /* Allow continuing with the same signal that interrupted us.
581e13c1 1501 Otherwise complain. */
a244bdca 1502
2dc38344 1503 if (resume_all)
17617f2d 1504 windows_continue (continue_status, -1, 0);
2dc38344 1505 else
7c7411bc 1506 windows_continue (continue_status, ptid.lwp (), 0);
a244bdca
CF
1507}
1508
695de547
CF
1509/* Ctrl-C handler used when the inferior is not run in the same console. The
1510 handler is in charge of interrupting the inferior using DebugBreakProcess.
1511 Note that this function is not available prior to Windows XP. In this case
1512 we emit a warning. */
d603d4b3 1513static BOOL WINAPI
695de547
CF
1514ctrl_c_handler (DWORD event_type)
1515{
1516 const int attach_flag = current_inferior ()->attach_flag;
1517
bb0613a5
PM
1518 /* Only handle Ctrl-C and Ctrl-Break events. Ignore others. */
1519 if (event_type != CTRL_C_EVENT && event_type != CTRL_BREAK_EVENT)
695de547
CF
1520 return FALSE;
1521
1522 /* If the inferior and the debugger share the same console, do nothing as
1523 the inferior has also received the Ctrl-C event. */
1524 if (!new_console && !attach_flag)
1525 return TRUE;
1526
0363df3d
HD
1527#ifdef __x86_64__
1528 if (wow64_process)
1529 {
1530 /* Call DbgUiRemoteBreakin of the 32bit ntdll.dll in the target process.
1531 DebugBreakProcess would call the one of the 64bit ntdll.dll, which
1532 can't be correctly handled by gdb. */
1533 if (wow64_dbgbreak == nullptr)
1534 {
1535 CORE_ADDR addr;
1536 if (!find_minimal_symbol_address ("ntdll!DbgUiRemoteBreakin",
1537 &addr, 0))
1538 wow64_dbgbreak = (void *) addr;
1539 }
1540
1541 if (wow64_dbgbreak != nullptr)
1542 {
1543 HANDLE thread = CreateRemoteThread (current_process_handle, NULL,
1544 0, (LPTHREAD_START_ROUTINE)
1545 wow64_dbgbreak, NULL, 0, NULL);
1546 if (thread)
1547 CloseHandle (thread);
1548 }
1549 }
1550 else
1551#endif
1552 {
1553 if (!DebugBreakProcess (current_process_handle))
1554 warning (_("Could not interrupt program. "
1555 "Press Ctrl-c in the program console."));
1556 }
695de547
CF
1557
1558 /* Return true to tell that Ctrl-C has been handled. */
1559 return TRUE;
1560}
1561
e6ad66bd
JT
1562/* Get the next event from the child. Returns a non-zero thread id if the event
1563 requires handling by WFI (or whatever). */
5b6d1e4f
PA
1564
1565int
1566windows_nat_target::get_windows_debug_event (int pid,
1567 struct target_waitstatus *ourstatus)
1e37c281
JM
1568{
1569 BOOL debug_event;
8a892701 1570 DWORD continue_status, event_code;
e6ad66bd 1571 DWORD thread_id = 0;
1e37c281 1572
0a4afda3
TT
1573 /* If there is a relevant pending stop, report it now. See the
1574 comment by the definition of "pending_stops" for details on why
1575 this is needed. */
d2977bc4
TT
1576 gdb::optional<pending_stop> stop = fetch_pending_stop (debug_events);
1577 if (stop.has_value ())
0a4afda3 1578 {
d2977bc4
TT
1579 thread_id = stop->thread_id;
1580 *ourstatus = stop->status;
0a4afda3 1581
50838d1b
PA
1582 ptid_t ptid (current_event.dwProcessId, thread_id);
1583 windows_thread_info *th = thread_rec (ptid, INVALIDATE_CONTEXT);
1584 th->reload_context = 1;
0a4afda3 1585
d2977bc4 1586 return thread_id;
0a4afda3
TT
1587 }
1588
a493e3e2 1589 last_sig = GDB_SIGNAL_0;
9d3789f7 1590
0a4afda3 1591 if (!(debug_event = wait_for_debug_event (&current_event, 1000)))
29fe111d 1592 goto out;
1e37c281 1593
1e37c281 1594 continue_status = DBG_CONTINUE;
1e37c281 1595
8a892701 1596 event_code = current_event.dwDebugEventCode;
450005e7 1597 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
a244bdca 1598 have_saved_context = 0;
8a892701
CF
1599
1600 switch (event_code)
1e37c281
JM
1601 {
1602 case CREATE_THREAD_DEBUG_EVENT:
0c3d84be 1603 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
8a892701
CF
1604 (unsigned) current_event.dwProcessId,
1605 (unsigned) current_event.dwThreadId,
1606 "CREATE_THREAD_DEBUG_EVENT"));
dfe7f3ac 1607 if (saw_create != 1)
3ade5333 1608 {
5b6d1e4f 1609 inferior *inf = find_inferior_pid (this, current_event.dwProcessId);
181e7f93 1610 if (!saw_create && inf->attach_flag)
3ade5333 1611 {
d6dc8049
CF
1612 /* Kludge around a Windows bug where first event is a create
1613 thread event. Caused when attached process does not have
581e13c1 1614 a main thread. */
e6ad66bd
JT
1615 thread_id = fake_create_process ();
1616 if (thread_id)
181e7f93 1617 saw_create++;
3ade5333
CF
1618 }
1619 break;
1620 }
581e13c1 1621 /* Record the existence of this thread. */
e6ad66bd 1622 thread_id = current_event.dwThreadId;
50838d1b 1623 windows_add_thread
7c7411bc 1624 (ptid_t (current_event.dwProcessId, current_event.dwThreadId, 0),
c559d709
JB
1625 current_event.u.CreateThread.hThread,
1626 current_event.u.CreateThread.lpThreadLocalBase,
1627 false /* main_thread_p */);
711e434b 1628
1e37c281
JM
1629 break;
1630
1631 case EXIT_THREAD_DEBUG_EVENT:
0c3d84be 1632 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
8a892701
CF
1633 (unsigned) current_event.dwProcessId,
1634 (unsigned) current_event.dwThreadId,
1635 "EXIT_THREAD_DEBUG_EVENT"));
7c7411bc
TT
1636 windows_delete_thread (ptid_t (current_event.dwProcessId,
1637 current_event.dwThreadId, 0),
c559d709
JB
1638 current_event.u.ExitThread.dwExitCode,
1639 false /* main_thread_p */);
1e37c281
JM
1640 break;
1641
1642 case CREATE_PROCESS_DEBUG_EVENT:
0c3d84be 1643 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
8a892701
CF
1644 (unsigned) current_event.dwProcessId,
1645 (unsigned) current_event.dwThreadId,
1646 "CREATE_PROCESS_DEBUG_EVENT"));
700b351b 1647 CloseHandle (current_event.u.CreateProcessInfo.hFile);
dfe7f3ac 1648 if (++saw_create != 1)
bf25528d 1649 break;
1e37c281 1650
dfe7f3ac 1651 current_process_handle = current_event.u.CreateProcessInfo.hProcess;
581e13c1 1652 /* Add the main thread. */
50838d1b 1653 windows_add_thread
7c7411bc
TT
1654 (ptid_t (current_event.dwProcessId,
1655 current_event.dwThreadId, 0),
c559d709
JB
1656 current_event.u.CreateProcessInfo.hThread,
1657 current_event.u.CreateProcessInfo.lpThreadLocalBase,
1658 true /* main_thread_p */);
e6ad66bd 1659 thread_id = current_event.dwThreadId;
1e37c281
JM
1660 break;
1661
1662 case EXIT_PROCESS_DEBUG_EVENT:
0c3d84be 1663 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
8a892701
CF
1664 (unsigned) current_event.dwProcessId,
1665 (unsigned) current_event.dwThreadId,
1666 "EXIT_PROCESS_DEBUG_EVENT"));
16d905e2
CF
1667 if (!windows_initialization_done)
1668 {
223ffa71 1669 target_terminal::ours ();
bc1e6c81 1670 target_mourn_inferior (inferior_ptid);
16d905e2
CF
1671 error (_("During startup program exited with code 0x%x."),
1672 (unsigned int) current_event.u.ExitProcess.dwExitCode);
1673 }
1674 else if (saw_create == 1)
1675 {
7c7411bc
TT
1676 windows_delete_thread (ptid_t (current_event.dwProcessId,
1677 current_event.dwThreadId, 0),
c559d709 1678 0, true /* main_thread_p */);
559e7e50
EZ
1679 DWORD exit_status = current_event.u.ExitProcess.dwExitCode;
1680 /* If the exit status looks like a fatal exception, but we
1681 don't recognize the exception's code, make the original
1682 exit status value available, to avoid losing
1683 information. */
1684 int exit_signal
1685 = WIFSIGNALED (exit_status) ? WTERMSIG (exit_status) : -1;
1686 if (exit_signal == -1)
1687 {
1688 ourstatus->kind = TARGET_WAITKIND_EXITED;
1689 ourstatus->value.integer = exit_status;
1690 }
1691 else
1692 {
1693 ourstatus->kind = TARGET_WAITKIND_SIGNALLED;
1694 ourstatus->value.sig = gdb_signal_from_host (exit_signal);
1695 }
8ed5b76e 1696 thread_id = current_event.dwThreadId;
16d905e2 1697 }
8a892701 1698 break;
1e37c281
JM
1699
1700 case LOAD_DLL_DEBUG_EVENT:
0c3d84be 1701 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
8a892701
CF
1702 (unsigned) current_event.dwProcessId,
1703 (unsigned) current_event.dwThreadId,
1704 "LOAD_DLL_DEBUG_EVENT"));
700b351b 1705 CloseHandle (current_event.u.LoadDll.hFile);
ea39ad35 1706 if (saw_create != 1 || ! windows_initialization_done)
dfe7f3ac 1707 break;
bf469271 1708 catch_errors (handle_load_dll);
450005e7
CF
1709 ourstatus->kind = TARGET_WAITKIND_LOADED;
1710 ourstatus->value.integer = 0;
ab4ee614 1711 thread_id = current_event.dwThreadId;
1e37c281
JM
1712 break;
1713
1714 case UNLOAD_DLL_DEBUG_EVENT:
0c3d84be 1715 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
8a892701
CF
1716 (unsigned) current_event.dwProcessId,
1717 (unsigned) current_event.dwThreadId,
1718 "UNLOAD_DLL_DEBUG_EVENT"));
ea39ad35 1719 if (saw_create != 1 || ! windows_initialization_done)
dfe7f3ac 1720 break;
bf469271 1721 catch_errors (handle_unload_dll);
de1b3c3d
PA
1722 ourstatus->kind = TARGET_WAITKIND_LOADED;
1723 ourstatus->value.integer = 0;
ab4ee614 1724 thread_id = current_event.dwThreadId;
d3ff4a77 1725 break;
1e37c281
JM
1726
1727 case EXCEPTION_DEBUG_EVENT:
0c3d84be 1728 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
8a892701
CF
1729 (unsigned) current_event.dwProcessId,
1730 (unsigned) current_event.dwThreadId,
1731 "EXCEPTION_DEBUG_EVENT"));
dfe7f3ac
CF
1732 if (saw_create != 1)
1733 break;
8d30e395 1734 switch (handle_exception (ourstatus, debug_exceptions))
24cdb46e
РИ
1735 {
1736 case HANDLE_EXCEPTION_UNHANDLED:
1737 default:
1738 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1739 break;
1740 case HANDLE_EXCEPTION_HANDLED:
1741 thread_id = current_event.dwThreadId;
1742 break;
1743 case HANDLE_EXCEPTION_IGNORED:
1744 continue_status = DBG_CONTINUE;
1745 break;
1746 }
1e37c281
JM
1747 break;
1748
581e13c1 1749 case OUTPUT_DEBUG_STRING_EVENT: /* Message from the kernel. */
0c3d84be 1750 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
8a892701
CF
1751 (unsigned) current_event.dwProcessId,
1752 (unsigned) current_event.dwThreadId,
1753 "OUTPUT_DEBUG_STRING_EVENT"));
dfe7f3ac
CF
1754 if (saw_create != 1)
1755 break;
e6ad66bd 1756 thread_id = handle_output_debug_string (ourstatus);
1e37c281 1757 break;
9d3789f7 1758
1e37c281 1759 default:
dfe7f3ac
CF
1760 if (saw_create != 1)
1761 break;
0c3d84be 1762 printf_unfiltered ("gdb: kernel event for pid=%u tid=0x%x\n",
d50a0ce2
CV
1763 (unsigned) current_event.dwProcessId,
1764 (unsigned) current_event.dwThreadId);
1765 printf_unfiltered (" unknown event code %u\n",
1766 (unsigned) current_event.dwDebugEventCode);
1e37c281
JM
1767 break;
1768 }
1769
e6ad66bd 1770 if (!thread_id || saw_create != 1)
a244bdca 1771 {
0a4afda3
TT
1772 CHECK (windows_continue (continue_status, desired_stop_thread_id, 0));
1773 }
1774 else if (desired_stop_thread_id != -1 && desired_stop_thread_id != thread_id)
1775 {
1776 /* Pending stop. See the comment by the definition of
1777 "pending_stops" for details on why this is needed. */
1778 DEBUG_EVENTS (("get_windows_debug_event - "
1779 "unexpected stop in 0x%x (expecting 0x%x)\n",
1780 thread_id, desired_stop_thread_id));
1781
1782 if (current_event.dwDebugEventCode == EXCEPTION_DEBUG_EVENT
13302e95
HD
1783 && ((current_event.u.Exception.ExceptionRecord.ExceptionCode
1784 == EXCEPTION_BREAKPOINT)
1785 || (current_event.u.Exception.ExceptionRecord.ExceptionCode
1786 == STATUS_WX86_BREAKPOINT))
0a4afda3
TT
1787 && windows_initialization_done)
1788 {
28688adf 1789 ptid_t ptid = ptid_t (current_event.dwProcessId, thread_id, 0);
50838d1b 1790 windows_thread_info *th = thread_rec (ptid, INVALIDATE_CONTEXT);
0a4afda3 1791 th->stopped_at_software_breakpoint = true;
7be2bb4f 1792 th->pc_adjusted = false;
0a4afda3
TT
1793 }
1794 pending_stops.push_back ({thread_id, *ourstatus, current_event});
1795 thread_id = 0;
1796 CHECK (windows_continue (continue_status, desired_stop_thread_id, 0));
a244bdca 1797 }
1e37c281
JM
1798
1799out:
e6ad66bd 1800 return thread_id;
1e37c281
JM
1801}
1802
2dc38344 1803/* Wait for interesting events to occur in the target process. */
f6ac5f3d
PA
1804ptid_t
1805windows_nat_target::wait (ptid_t ptid, struct target_waitstatus *ourstatus,
1806 int options)
24e60978 1807{
2dc38344 1808 int pid = -1;
39f77062 1809
24e60978
SC
1810 /* We loop when we get a non-standard exception rather than return
1811 with a SPURIOUS because resume can try and step or modify things,
3cee93ac 1812 which needs a current_thread->h. But some of these exceptions mark
24e60978 1813 the birth or death of threads, which mean that the current thread
581e13c1 1814 isn't necessarily what you think it is. */
24e60978
SC
1815
1816 while (1)
450005e7 1817 {
c57918b2 1818 int retval;
2b008701 1819
695de547
CF
1820 /* If the user presses Ctrl-c while the debugger is waiting
1821 for an event, he expects the debugger to interrupt his program
1822 and to get the prompt back. There are two possible situations:
1823
1824 - The debugger and the program do not share the console, in
1825 which case the Ctrl-c event only reached the debugger.
1826 In that case, the ctrl_c handler will take care of interrupting
581e13c1
MS
1827 the inferior. Note that this case is working starting with
1828 Windows XP. For Windows 2000, Ctrl-C should be pressed in the
695de547
CF
1829 inferior console.
1830
1831 - The debugger and the program share the same console, in which
1832 case both debugger and inferior will receive the Ctrl-c event.
1833 In that case the ctrl_c handler will ignore the event, as the
1834 Ctrl-c event generated inside the inferior will trigger the
1835 expected debug event.
1836
1837 FIXME: brobecker/2008-05-20: If the inferior receives the
1838 signal first and the delay until GDB receives that signal
1839 is sufficiently long, GDB can sometimes receive the SIGINT
1840 after we have unblocked the CTRL+C handler. This would
1841 lead to the debugger stopping prematurely while handling
1842 the new-thread event that comes with the handling of the SIGINT
1843 inside the inferior, and then stop again immediately when
1844 the user tries to resume the execution in the inferior.
1845 This is a classic race that we should try to fix one day. */
1846 SetConsoleCtrlHandler (&ctrl_c_handler, TRUE);
5b6d1e4f 1847 retval = get_windows_debug_event (pid, ourstatus);
695de547 1848 SetConsoleCtrlHandler (&ctrl_c_handler, FALSE);
c57918b2 1849
450005e7 1850 if (retval)
0a4afda3
TT
1851 {
1852 ptid_t result = ptid_t (current_event.dwProcessId, retval, 0);
1853
50838d1b
PA
1854 if (ourstatus->kind != TARGET_WAITKIND_EXITED
1855 && ourstatus->kind != TARGET_WAITKIND_SIGNALLED)
0a4afda3 1856 {
50838d1b
PA
1857 windows_thread_info *th = thread_rec (result, INVALIDATE_CONTEXT);
1858
1859 if (th != nullptr)
7be2bb4f 1860 {
50838d1b
PA
1861 th->stopped_at_software_breakpoint = false;
1862 if (current_event.dwDebugEventCode == EXCEPTION_DEBUG_EVENT
1863 && ((current_event.u.Exception.ExceptionRecord.ExceptionCode
1864 == EXCEPTION_BREAKPOINT)
1865 || (current_event.u.Exception.ExceptionRecord.ExceptionCode
1866 == STATUS_WX86_BREAKPOINT))
1867 && windows_initialization_done)
1868 {
1869 th->stopped_at_software_breakpoint = true;
1870 th->pc_adjusted = false;
1871 }
7be2bb4f 1872 }
0a4afda3
TT
1873 }
1874
1875 return result;
1876 }
450005e7
CF
1877 else
1878 {
1879 int detach = 0;
3cee93ac 1880
98bbd631
AC
1881 if (deprecated_ui_loop_hook != NULL)
1882 detach = deprecated_ui_loop_hook (0);
0714f9bf 1883
450005e7 1884 if (detach)
f6ac5f3d 1885 kill ();
450005e7
CF
1886 }
1887 }
24e60978
SC
1888}
1889
ea39ad35
JB
1890/* Iterate over all DLLs currently mapped by our inferior, and
1891 add them to our list of solibs. */
94481b8c
JB
1892
1893static void
ea39ad35 1894windows_add_all_dlls (void)
94481b8c 1895{
94481b8c
JB
1896 HMODULE dummy_hmodule;
1897 DWORD cb_needed;
1898 HMODULE *hmodules;
1899 int i;
1900
46f9f931
HD
1901#ifdef __x86_64__
1902 if (wow64_process)
1903 {
1904 if (EnumProcessModulesEx (current_process_handle, &dummy_hmodule,
1905 sizeof (HMODULE), &cb_needed,
1906 LIST_MODULES_32BIT) == 0)
1907 return;
1908 }
1909 else
1910#endif
1911 {
1912 if (EnumProcessModules (current_process_handle, &dummy_hmodule,
1913 sizeof (HMODULE), &cb_needed) == 0)
1914 return;
1915 }
94481b8c
JB
1916
1917 if (cb_needed < 1)
1918 return;
1919
1920 hmodules = (HMODULE *) alloca (cb_needed);
46f9f931
HD
1921#ifdef __x86_64__
1922 if (wow64_process)
1923 {
1924 if (EnumProcessModulesEx (current_process_handle, hmodules,
1925 cb_needed, &cb_needed,
1926 LIST_MODULES_32BIT) == 0)
1927 return;
1928 }
1929 else
1930#endif
1931 {
1932 if (EnumProcessModules (current_process_handle, hmodules,
1933 cb_needed, &cb_needed) == 0)
1934 return;
1935 }
94481b8c 1936
d503b685
HD
1937 char system_dir[__PMAX];
1938 char syswow_dir[__PMAX];
1939 size_t system_dir_len = 0;
ebea7626
HD
1940 bool convert_syswow_dir = false;
1941#ifdef __x86_64__
d503b685 1942 if (wow64_process)
ebea7626 1943#endif
d503b685 1944 {
ebea7626
HD
1945 /* This fails on 32bit Windows because it has no SysWOW64 directory,
1946 and in this case a path conversion isn't necessary. */
1947 UINT len = GetSystemWow64DirectoryA (syswow_dir, sizeof (syswow_dir));
1948 if (len > 0)
1949 {
1950 /* Check that we have passed a large enough buffer. */
1951 gdb_assert (len < sizeof (syswow_dir));
1952
1953 len = GetSystemDirectoryA (system_dir, sizeof (system_dir));
1954 /* Error check. */
1955 gdb_assert (len != 0);
1956 /* Check that we have passed a large enough buffer. */
1957 gdb_assert (len < sizeof (system_dir));
1958
1959 strcat (system_dir, "\\");
1960 strcat (syswow_dir, "\\");
1961 system_dir_len = strlen (system_dir);
1962
1963 convert_syswow_dir = true;
1964 }
1965
d503b685 1966 }
ea39ad35 1967 for (i = 1; i < (int) (cb_needed / sizeof (HMODULE)); i++)
94481b8c
JB
1968 {
1969 MODULEINFO mi;
774f74c2
PM
1970#ifdef __USEWIDE
1971 wchar_t dll_name[__PMAX];
d503b685 1972 char dll_name_mb[__PMAX];
774f74c2 1973#else
94481b8c 1974 char dll_name[__PMAX];
774f74c2 1975#endif
d503b685 1976 const char *name;
94481b8c
JB
1977 if (GetModuleInformation (current_process_handle, hmodules[i],
1978 &mi, sizeof (mi)) == 0)
1979 continue;
1980 if (GetModuleFileNameEx (current_process_handle, hmodules[i],
1981 dll_name, sizeof (dll_name)) == 0)
1982 continue;
774f74c2 1983#ifdef __USEWIDE
d503b685
HD
1984 wcstombs (dll_name_mb, dll_name, __PMAX);
1985 name = dll_name_mb;
774f74c2
PM
1986#else
1987 name = dll_name;
1988#endif
ebea7626 1989 /* Convert the DLL path of 32bit processes returned by
d503b685
HD
1990 GetModuleFileNameEx from the 64bit system directory to the
1991 32bit syswow64 directory if necessary. */
1992 std::string syswow_dll_path;
ebea7626 1993 if (convert_syswow_dir
d503b685
HD
1994 && strncasecmp (name, system_dir, system_dir_len) == 0
1995 && strchr (name + system_dir_len, '\\') == nullptr)
1996 {
1997 syswow_dll_path = syswow_dir;
1998 syswow_dll_path += name + system_dir_len;
1999 name = syswow_dll_path.c_str();
2000 }
ea39ad35
JB
2001
2002 solib_end->next = windows_make_so (name, mi.lpBaseOfDll);
2003 solib_end = solib_end->next;
94481b8c
JB
2004 }
2005}
2006
50838d1b
PA
2007void
2008windows_nat_target::do_initial_windows_stuff (DWORD pid, bool attaching)
9d3789f7 2009{
fa4ba8da 2010 int i;
d6b48e9c 2011 struct inferior *inf;
9d3789f7 2012
a493e3e2 2013 last_sig = GDB_SIGNAL_0;
bf25528d 2014 open_process_used = 0;
fa4ba8da 2015 debug_registers_changed = 0;
dfe7f3ac 2016 debug_registers_used = 0;
fa4ba8da
PM
2017 for (i = 0; i < sizeof (dr) / sizeof (dr[0]); i++)
2018 dr[i] = 0;
10325bc5 2019#ifdef __CYGWIN__
de1b3c3d 2020 cygwin_load_start = cygwin_load_end = 0;
10325bc5 2021#endif
9d3789f7
CF
2022 current_event.dwProcessId = pid;
2023 memset (&current_event, 0, sizeof (current_event));
50838d1b
PA
2024 if (!target_is_pushed (this))
2025 push_target (this);
cb851954 2026 disable_breakpoints_in_shlibs ();
dc05df57 2027 windows_clear_solib ();
88056fbb 2028 clear_proceed_status (0);
9d3789f7
CF
2029 init_wait_for_inferior ();
2030
46f9f931
HD
2031#ifdef __x86_64__
2032 ignore_first_breakpoint = !attaching && wow64_process;
2033
2034 if (!wow64_process)
2035 {
2036 windows_set_context_register_offsets (amd64_mappings);
2037 windows_set_segment_register_p (amd64_windows_segment_register_p);
2038 }
2039 else
2040#endif
2041 {
2042 windows_set_context_register_offsets (i386_mappings);
2043 windows_set_segment_register_p (i386_windows_segment_register_p);
2044 }
2045
6c95b8df
PA
2046 inf = current_inferior ();
2047 inferior_appeared (inf, pid);
181e7f93 2048 inf->attach_flag = attaching;
7f9f62ba 2049
223ffa71
TT
2050 target_terminal::init ();
2051 target_terminal::inferior ();
9d3789f7 2052
16d905e2 2053 windows_initialization_done = 0;
c72f45d1 2054
50838d1b
PA
2055 ptid_t last_ptid;
2056
9d3789f7
CF
2057 while (1)
2058 {
c72f45d1
PA
2059 struct target_waitstatus status;
2060
50838d1b 2061 last_ptid = this->wait (minus_one_ptid, &status, 0);
c72f45d1
PA
2062
2063 /* Note windows_wait returns TARGET_WAITKIND_SPURIOUS for thread
2064 events. */
2065 if (status.kind != TARGET_WAITKIND_LOADED
2066 && status.kind != TARGET_WAITKIND_SPURIOUS)
9d3789f7 2067 break;
c72f45d1 2068
50838d1b 2069 this->resume (minus_one_ptid, 0, GDB_SIGNAL_0);
9d3789f7 2070 }
eff8332b 2071
50838d1b
PA
2072 switch_to_thread (find_thread_ptid (this, last_ptid));
2073
ea39ad35 2074 /* Now that the inferior has been started and all DLLs have been mapped,
3be75f87
JB
2075 we can iterate over all DLLs and load them in.
2076
2077 We avoid doing it any earlier because, on certain versions of Windows,
2078 LOAD_DLL_DEBUG_EVENTs are sometimes not complete. In particular,
2079 we have seen on Windows 8.1 that the ntdll.dll load event does not
2080 include the DLL name, preventing us from creating an associated SO.
2081 A possible explanation is that ntdll.dll might be mapped before
2082 the SO info gets created by the Windows system -- ntdll.dll is
2083 the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs
2084 do not seem to suffer from that problem.
2085
2086 Rather than try to work around this sort of issue, it is much
2087 simpler to just ignore DLL load/unload events during the startup
2088 phase, and then process them all in one batch now. */
ea39ad35 2089 windows_add_all_dlls ();
94481b8c 2090
16d905e2 2091 windows_initialization_done = 1;
9d3789f7
CF
2092 return;
2093}
2094
616a9dc4
CV
2095/* Try to set or remove a user privilege to the current process. Return -1
2096 if that fails, the previous setting of that privilege otherwise.
2097
2098 This code is copied from the Cygwin source code and rearranged to allow
2099 dynamically loading of the needed symbols from advapi32 which is only
581e13c1 2100 available on NT/2K/XP. */
616a9dc4
CV
2101static int
2102set_process_privilege (const char *privilege, BOOL enable)
2103{
616a9dc4
CV
2104 HANDLE token_hdl = NULL;
2105 LUID restore_priv;
2106 TOKEN_PRIVILEGES new_priv, orig_priv;
2107 int ret = -1;
2108 DWORD size;
2109
616a9dc4
CV
2110 if (!OpenProcessToken (GetCurrentProcess (),
2111 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
2112 &token_hdl))
2113 goto out;
2114
418c6cb3 2115 if (!LookupPrivilegeValueA (NULL, privilege, &restore_priv))
616a9dc4
CV
2116 goto out;
2117
2118 new_priv.PrivilegeCount = 1;
2119 new_priv.Privileges[0].Luid = restore_priv;
2120 new_priv.Privileges[0].Attributes = enable ? SE_PRIVILEGE_ENABLED : 0;
2121
2122 if (!AdjustTokenPrivileges (token_hdl, FALSE, &new_priv,
295732ea 2123 sizeof orig_priv, &orig_priv, &size))
616a9dc4
CV
2124 goto out;
2125#if 0
2126 /* Disabled, otherwise every `attach' in an unprivileged user session
2127 would raise the "Failed to get SE_DEBUG_NAME privilege" warning in
581e13c1 2128 windows_attach(). */
616a9dc4 2129 /* AdjustTokenPrivileges returns TRUE even if the privilege could not
581e13c1 2130 be enabled. GetLastError () returns an correct error code, though. */
616a9dc4
CV
2131 if (enable && GetLastError () == ERROR_NOT_ALL_ASSIGNED)
2132 goto out;
2133#endif
2134
2135 ret = orig_priv.Privileges[0].Attributes == SE_PRIVILEGE_ENABLED ? 1 : 0;
2136
2137out:
2138 if (token_hdl)
2139 CloseHandle (token_hdl);
2140
2141 return ret;
2142}
2143
02cc9f49 2144/* Attach to process PID, then initialize for debugging it. */
f6ac5f3d
PA
2145
2146void
2147windows_nat_target::attach (const char *args, int from_tty)
24e60978
SC
2148{
2149 BOOL ok;
559e75c0 2150 DWORD pid;
24e60978 2151
74164c56 2152 pid = parse_pid_to_attach (args);
24e60978 2153
616a9dc4
CV
2154 if (set_process_privilege (SE_DEBUG_NAME, TRUE) < 0)
2155 {
2156 printf_unfiltered ("Warning: Failed to get SE_DEBUG_NAME privilege\n");
581e13c1
MS
2157 printf_unfiltered ("This can cause attach to "
2158 "fail on Windows NT/2K/XP\n");
616a9dc4
CV
2159 }
2160
dc05df57 2161 windows_init_thread_list ();
9d3789f7 2162 ok = DebugActiveProcess (pid);
91a175b3 2163 saw_create = 0;
24e60978 2164
10325bc5 2165#ifdef __CYGWIN__
24e60978 2166 if (!ok)
baa93fa6 2167 {
581e13c1 2168 /* Try fall back to Cygwin pid. */
baa93fa6
CF
2169 pid = cygwin_internal (CW_CYGWIN_PID_TO_WINPID, pid);
2170
2171 if (pid > 0)
2172 ok = DebugActiveProcess (pid);
10325bc5
PA
2173 }
2174#endif
baa93fa6 2175
10325bc5 2176 if (!ok)
c9739b6a
TT
2177 error (_("Can't attach to process %u (error %u)"),
2178 (unsigned) pid, (unsigned) GetLastError ());
24e60978 2179
2b008701 2180 DebugSetProcessKillOnExit (FALSE);
3ade5333 2181
24e60978
SC
2182 if (from_tty)
2183 {
d9fa87f4 2184 const char *exec_file = get_exec_file (0);
24e60978
SC
2185
2186 if (exec_file)
2187 printf_unfiltered ("Attaching to program `%s', %s\n", exec_file,
a068643d 2188 target_pid_to_str (ptid_t (pid)).c_str ());
24e60978
SC
2189 else
2190 printf_unfiltered ("Attaching to %s\n",
a068643d 2191 target_pid_to_str (ptid_t (pid)).c_str ());
24e60978
SC
2192 }
2193
46f9f931
HD
2194#ifdef __x86_64__
2195 HANDLE h = OpenProcess (PROCESS_QUERY_INFORMATION, FALSE, pid);
2196 if (h != NULL)
2197 {
2198 BOOL wow64;
2199 if (IsWow64Process (h, &wow64))
2200 wow64_process = wow64;
2201 CloseHandle (h);
2202 }
2203#endif
2204
50838d1b 2205 do_initial_windows_stuff (pid, 1);
223ffa71 2206 target_terminal::ours ();
24e60978
SC
2207}
2208
f6ac5f3d
PA
2209void
2210windows_nat_target::detach (inferior *inf, int from_tty)
24e60978 2211{
02cc9f49
CV
2212 int detached = 1;
2213
8473b447 2214 ptid_t ptid = minus_one_ptid;
f6ac5f3d 2215 resume (ptid, 0, GDB_SIGNAL_0);
96998ce7 2216
2b008701
CF
2217 if (!DebugActiveProcessStop (current_event.dwProcessId))
2218 {
d50a0ce2
CV
2219 error (_("Can't detach process %u (error %u)"),
2220 (unsigned) current_event.dwProcessId, (unsigned) GetLastError ());
2b008701 2221 detached = 0;
02cc9f49 2222 }
2b008701
CF
2223 DebugSetProcessKillOnExit (FALSE);
2224
02cc9f49 2225 if (detached && from_tty)
24e60978 2226 {
a121b7c1 2227 const char *exec_file = get_exec_file (0);
24e60978
SC
2228 if (exec_file == 0)
2229 exec_file = "";
d50a0ce2
CV
2230 printf_unfiltered ("Detaching from program: %s, Pid %u\n", exec_file,
2231 (unsigned) current_event.dwProcessId);
24e60978 2232 }
7f9f62ba 2233
df7e5265 2234 x86_cleanup_dregs ();
50838d1b 2235 switch_to_no_thread ();
b7a08269 2236 detach_inferior (inf);
7f9f62ba 2237
f6ac5f3d 2238 maybe_unpush_target ();
24e60978
SC
2239}
2240
47f7ffdb
JB
2241/* Try to determine the executable filename.
2242
2243 EXE_NAME_RET is a pointer to a buffer whose size is EXE_NAME_MAX_LEN.
2244
2245 Upon success, the filename is stored inside EXE_NAME_RET, and
2246 this function returns nonzero.
2247
2248 Otherwise, this function returns zero and the contents of
2249 EXE_NAME_RET is undefined. */
2250
2251static int
2252windows_get_exec_module_filename (char *exe_name_ret, size_t exe_name_max_len)
2253{
2254 DWORD len;
2255 HMODULE dh_buf;
2256 DWORD cbNeeded;
2257
2258 cbNeeded = 0;
46f9f931
HD
2259#ifdef __x86_64__
2260 if (wow64_process)
2261 {
2262 if (!EnumProcessModulesEx (current_process_handle, &dh_buf,
2263 sizeof (HMODULE), &cbNeeded,
2264 LIST_MODULES_32BIT) || !cbNeeded)
2265 return 0;
2266 }
2267 else
2268#endif
2269 {
2270 if (!EnumProcessModules (current_process_handle, &dh_buf,
2271 sizeof (HMODULE), &cbNeeded) || !cbNeeded)
2272 return 0;
2273 }
47f7ffdb
JB
2274
2275 /* We know the executable is always first in the list of modules,
2276 which we just fetched. So no need to fetch more. */
2277
2278#ifdef __CYGWIN__
2279 {
2280 /* Cygwin prefers that the path be in /x/y/z format, so extract
2281 the filename into a temporary buffer first, and then convert it
2282 to POSIX format into the destination buffer. */
0ae534d2 2283 cygwin_buf_t *pathbuf = (cygwin_buf_t *) alloca (exe_name_max_len * sizeof (cygwin_buf_t));
47f7ffdb
JB
2284
2285 len = GetModuleFileNameEx (current_process_handle,
2286 dh_buf, pathbuf, exe_name_max_len);
2287 if (len == 0)
2288 error (_("Error getting executable filename: %u."),
2289 (unsigned) GetLastError ());
2290 if (cygwin_conv_path (CCP_WIN_W_TO_POSIX, pathbuf, exe_name_ret,
2291 exe_name_max_len) < 0)
2292 error (_("Error converting executable filename to POSIX: %d."), errno);
2293 }
2294#else
2295 len = GetModuleFileNameEx (current_process_handle,
2296 dh_buf, exe_name_ret, exe_name_max_len);
2297 if (len == 0)
2298 error (_("Error getting executable filename: %u."),
2299 (unsigned) GetLastError ());
2300#endif
2301
2302 return 1; /* success */
2303}
2304
2305/* The pid_to_exec_file target_ops method for this platform. */
2306
f6ac5f3d
PA
2307char *
2308windows_nat_target::pid_to_exec_file (int pid)
47216e51 2309{
b3c613f2 2310 static char path[__PMAX];
10325bc5 2311#ifdef __CYGWIN__
581e13c1 2312 /* Try to find exe name as symlink target of /proc/<pid>/exe. */
33605d39
CF
2313 int nchars;
2314 char procexe[sizeof ("/proc/4294967295/exe")];
08850b56
PM
2315
2316 xsnprintf (procexe, sizeof (procexe), "/proc/%u/exe", pid);
33605d39
CF
2317 nchars = readlink (procexe, path, sizeof(path));
2318 if (nchars > 0 && nchars < sizeof (path))
47216e51 2319 {
33605d39
CF
2320 path[nchars] = '\0'; /* Got it */
2321 return path;
47216e51 2322 }
10325bc5
PA
2323#endif
2324
33605d39 2325 /* If we get here then either Cygwin is hosed, this isn't a Cygwin version
581e13c1 2326 of gdb, or we're trying to debug a non-Cygwin windows executable. */
47f7ffdb 2327 if (!windows_get_exec_module_filename (path, sizeof (path)))
33605d39
CF
2328 path[0] = '\0';
2329
2330 return path;
47216e51
CV
2331}
2332
24e60978
SC
2333/* Print status information about what we're accessing. */
2334
f6ac5f3d
PA
2335void
2336windows_nat_target::files_info ()
24e60978 2337{
181e7f93
PA
2338 struct inferior *inf = current_inferior ();
2339
24e60978 2340 printf_unfiltered ("\tUsing the running image of %s %s.\n",
181e7f93 2341 inf->attach_flag ? "attached" : "child",
a068643d 2342 target_pid_to_str (inferior_ptid).c_str ());
24e60978
SC
2343}
2344
cd44747c
PM
2345/* Modify CreateProcess parameters for use of a new separate console.
2346 Parameters are:
2347 *FLAGS: DWORD parameter for general process creation flags.
2348 *SI: STARTUPINFO structure, for which the console window size and
2349 console buffer size is filled in if GDB is running in a console.
2350 to create the new console.
2351 The size of the used font is not available on all versions of
2352 Windows OS. Furthermore, the current font might not be the default
2353 font, but this is still better than before.
2354 If the windows and buffer sizes are computed,
2355 SI->DWFLAGS is changed so that this information is used
2356 by CreateProcess function. */
2357
2358static void
2359windows_set_console_info (STARTUPINFO *si, DWORD *flags)
2360{
2361 HANDLE hconsole = CreateFile ("CONOUT$", GENERIC_READ | GENERIC_WRITE,
2362 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
2363
2364 if (hconsole != INVALID_HANDLE_VALUE)
2365 {
2366 CONSOLE_SCREEN_BUFFER_INFO sbinfo;
2367 COORD font_size;
2368 CONSOLE_FONT_INFO cfi;
2369
2370 GetCurrentConsoleFont (hconsole, FALSE, &cfi);
2371 font_size = GetConsoleFontSize (hconsole, cfi.nFont);
2372 GetConsoleScreenBufferInfo(hconsole, &sbinfo);
2373 si->dwXSize = sbinfo.srWindow.Right - sbinfo.srWindow.Left + 1;
2374 si->dwYSize = sbinfo.srWindow.Bottom - sbinfo.srWindow.Top + 1;
2375 if (font_size.X)
2376 si->dwXSize *= font_size.X;
2377 else
2378 si->dwXSize *= 8;
2379 if (font_size.Y)
2380 si->dwYSize *= font_size.Y;
2381 else
2382 si->dwYSize *= 12;
2383 si->dwXCountChars = sbinfo.dwSize.X;
2384 si->dwYCountChars = sbinfo.dwSize.Y;
2385 si->dwFlags |= STARTF_USESIZE | STARTF_USECOUNTCHARS;
2386 }
2387 *flags |= CREATE_NEW_CONSOLE;
2388}
2389
c93dbcba
EZ
2390#ifndef __CYGWIN__
2391/* Function called by qsort to sort environment strings. */
2392
2393static int
2394envvar_cmp (const void *a, const void *b)
2395{
2396 const char **p = (const char **) a;
2397 const char **q = (const char **) b;
2398 return strcasecmp (*p, *q);
2399}
2400#endif
2401
b7ff339d
CV
2402#ifdef __CYGWIN__
2403static void
2404clear_win32_environment (char **env)
2405{
2406 int i;
2407 size_t len;
2408 wchar_t *copy = NULL, *equalpos;
2409
2410 for (i = 0; env[i] && *env[i]; i++)
2411 {
2412 len = mbstowcs (NULL, env[i], 0) + 1;
2413 copy = (wchar_t *) xrealloc (copy, len * sizeof (wchar_t));
2414 mbstowcs (copy, env[i], len);
2415 equalpos = wcschr (copy, L'=');
2416 if (equalpos)
2417 *equalpos = L'\0';
2418 SetEnvironmentVariableW (copy, NULL);
2419 }
2420 xfree (copy);
2421}
2422#endif
2423
8ba42bc5
EZ
2424#ifndef __CYGWIN__
2425
2426/* Redirection of inferior I/O streams for native MS-Windows programs.
2427 Unlike on Unix, where this is handled by invoking the inferior via
2428 the shell, on MS-Windows we need to emulate the cmd.exe shell.
2429
2430 The official documentation of the cmd.exe redirection features is here:
2431
2432 http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx
2433
2434 (That page talks about Windows XP, but there's no newer
2435 documentation, so we assume later versions of cmd.exe didn't change
2436 anything.)
2437
2438 Caveat: the documentation on that page seems to include a few lies.
2439 For example, it describes strange constructs 1<&2 and 2<&1, which
2440 seem to work only when 1>&2 resp. 2>&1 would make sense, and so I
2441 think the cmd.exe parser of the redirection symbols simply doesn't
2442 care about the < vs > distinction in these cases. Therefore, the
2443 supported features are explicitly documented below.
2444
2445 The emulation below aims at supporting all the valid use cases
2446 supported by cmd.exe, which include:
2447
2448 < FILE redirect standard input from FILE
2449 0< FILE redirect standard input from FILE
2450 <&N redirect standard input from file descriptor N
2451 0<&N redirect standard input from file descriptor N
2452 > FILE redirect standard output to FILE
2453 >> FILE append standard output to FILE
2454 1>> FILE append standard output to FILE
2455 >&N redirect standard output to file descriptor N
2456 1>&N redirect standard output to file descriptor N
2457 >>&N append standard output to file descriptor N
2458 1>>&N append standard output to file descriptor N
2459 2> FILE redirect standard error to FILE
2460 2>> FILE append standard error to FILE
2461 2>&N redirect standard error to file descriptor N
2462 2>>&N append standard error to file descriptor N
2463
2464 Note that using N > 2 in the above construct is supported, but
2465 requires that the corresponding file descriptor be open by some
2466 means elsewhere or outside GDB. Also note that using ">&0" or
2467 "<&2" will generally fail, because the file descriptor redirected
2468 from is normally open in an incompatible mode (e.g., FD 0 is open
2469 for reading only). IOW, use of such tricks is not recommended;
2470 you are on your own.
2471
2472 We do NOT support redirection of file descriptors above 2, as in
2473 "3>SOME-FILE", because MinGW compiled programs don't (supporting
2474 that needs special handling in the startup code that MinGW
2475 doesn't have). Pipes are also not supported.
2476
2477 As for invalid use cases, where the redirection contains some
2478 error, the emulation below will detect that and produce some
2479 error and/or failure. But the behavior in those cases is not
2480 bug-for-bug compatible with what cmd.exe does in those cases.
2481 That's because what cmd.exe does then is not well defined, and
2482 seems to be a side effect of the cmd.exe parsing of the command
2483 line more than anything else. For example, try redirecting to an
2484 invalid file name, as in "> foo:bar".
2485
2486 There are also minor syntactic deviations from what cmd.exe does
2487 in some corner cases. For example, it doesn't support the likes
2488 of "> &foo" to mean redirect to file named literally "&foo"; we
2489 do support that here, because that, too, sounds like some issue
2490 with the cmd.exe parser. Another nicety is that we support
2491 redirection targets that use file names with forward slashes,
2492 something cmd.exe doesn't -- this comes in handy since GDB
2493 file-name completion can be used when typing the command line for
2494 the inferior. */
2495
2496/* Support routines for redirecting standard handles of the inferior. */
2497
2498/* Parse a single redirection spec, open/duplicate the specified
2499 file/fd, and assign the appropriate value to one of the 3 standard
2500 file descriptors. */
2501static int
2502redir_open (const char *redir_string, int *inp, int *out, int *err)
2503{
2504 int *fd, ref_fd = -2;
2505 int mode;
2506 const char *fname = redir_string + 1;
2507 int rc = *redir_string;
2508
2509 switch (rc)
2510 {
2511 case '0':
2512 fname++;
2513 /* FALLTHROUGH */
2514 case '<':
2515 fd = inp;
2516 mode = O_RDONLY;
2517 break;
2518 case '1': case '2':
2519 fname++;
2520 /* FALLTHROUGH */
2521 case '>':
2522 fd = (rc == '2') ? err : out;
2523 mode = O_WRONLY | O_CREAT;
2524 if (*fname == '>')
2525 {
2526 fname++;
2527 mode |= O_APPEND;
2528 }
2529 else
2530 mode |= O_TRUNC;
2531 break;
2532 default:
2533 return -1;
2534 }
2535
2536 if (*fname == '&' && '0' <= fname[1] && fname[1] <= '9')
2537 {
2538 /* A reference to a file descriptor. */
2539 char *fdtail;
2540 ref_fd = (int) strtol (fname + 1, &fdtail, 10);
2541 if (fdtail > fname + 1 && *fdtail == '\0')
2542 {
2543 /* Don't allow redirection when open modes are incompatible. */
2544 if ((ref_fd == 0 && (fd == out || fd == err))
2545 || ((ref_fd == 1 || ref_fd == 2) && fd == inp))
2546 {
2547 errno = EPERM;
2548 return -1;
2549 }
2550 if (ref_fd == 0)
2551 ref_fd = *inp;
2552 else if (ref_fd == 1)
2553 ref_fd = *out;
2554 else if (ref_fd == 2)
2555 ref_fd = *err;
2556 }
2557 else
2558 {
2559 errno = EBADF;
2560 return -1;
2561 }
2562 }
2563 else
2564 fname++; /* skip the separator space */
2565 /* If the descriptor is already open, close it. This allows
2566 multiple specs of redirections for the same stream, which is
2567 somewhat nonsensical, but still valid and supported by cmd.exe.
2568 (But cmd.exe only opens a single file in this case, the one
2569 specified by the last redirection spec on the command line.) */
2570 if (*fd >= 0)
2571 _close (*fd);
2572 if (ref_fd == -2)
2573 {
2574 *fd = _open (fname, mode, _S_IREAD | _S_IWRITE);
2575 if (*fd < 0)
2576 return -1;
2577 }
2578 else if (ref_fd == -1)
2579 *fd = -1; /* reset to default destination */
2580 else
2581 {
2582 *fd = _dup (ref_fd);
2583 if (*fd < 0)
2584 return -1;
2585 }
2586 /* _open just sets a flag for O_APPEND, which won't be passed to the
2587 inferior, so we need to actually move the file pointer. */
2588 if ((mode & O_APPEND) != 0)
2589 _lseek (*fd, 0L, SEEK_END);
2590 return 0;
2591}
2592
2593/* Canonicalize a single redirection spec and set up the corresponding
2594 file descriptor as specified. */
2595static int
2596redir_set_redirection (const char *s, int *inp, int *out, int *err)
2597{
2598 char buf[__PMAX + 2 + 5]; /* extra space for quotes & redirection string */
2599 char *d = buf;
2600 const char *start = s;
2601 int quote = 0;
2602
2603 *d++ = *s++; /* copy the 1st character, < or > or a digit */
2604 if ((*start == '>' || *start == '1' || *start == '2')
2605 && *s == '>')
2606 {
2607 *d++ = *s++;
2608 if (*s == '>' && *start != '>')
2609 *d++ = *s++;
2610 }
2611 else if (*start == '0' && *s == '<')
2612 *d++ = *s++;
2613 /* cmd.exe recognizes "&N" only immediately after the redirection symbol. */
2614 if (*s != '&')
2615 {
2616 while (isspace (*s)) /* skip whitespace before file name */
2617 s++;
2618 *d++ = ' '; /* separate file name with a single space */
2619 }
2620
2621 /* Copy the file name. */
2622 while (*s)
2623 {
2624 /* Remove quoting characters from the file name in buf[]. */
2625 if (*s == '"') /* could support '..' quoting here */
2626 {
2627 if (!quote)
2628 quote = *s++;
2629 else if (*s == quote)
2630 {
2631 quote = 0;
2632 s++;
2633 }
2634 else
2635 *d++ = *s++;
2636 }
2637 else if (*s == '\\')
2638 {
2639 if (s[1] == '"') /* could support '..' here */
2640 s++;
2641 *d++ = *s++;
2642 }
2643 else if (isspace (*s) && !quote)
2644 break;
2645 else
2646 *d++ = *s++;
2647 if (d - buf >= sizeof (buf) - 1)
2648 {
2649 errno = ENAMETOOLONG;
2650 return 0;
2651 }
2652 }
2653 *d = '\0';
2654
2655 /* Windows doesn't allow redirection characters in file names, so we
2656 can bail out early if they use them, or if there's no target file
2657 name after the redirection symbol. */
2658 if (d[-1] == '>' || d[-1] == '<')
2659 {
2660 errno = ENOENT;
2661 return 0;
2662 }
2663 if (redir_open (buf, inp, out, err) == 0)
2664 return s - start;
2665 return 0;
2666}
2667
2668/* Parse the command line for redirection specs and prepare the file
2669 descriptors for the 3 standard streams accordingly. */
2670static bool
2671redirect_inferior_handles (const char *cmd_orig, char *cmd,
2672 int *inp, int *out, int *err)
2673{
2674 const char *s = cmd_orig;
2675 char *d = cmd;
2676 int quote = 0;
2677 bool retval = false;
2678
2679 while (isspace (*s))
2680 *d++ = *s++;
2681
2682 while (*s)
2683 {
2684 if (*s == '"') /* could also support '..' quoting here */
2685 {
2686 if (!quote)
2687 quote = *s;
2688 else if (*s == quote)
2689 quote = 0;
2690 }
2691 else if (*s == '\\')
2692 {
2693 if (s[1] == '"') /* escaped quote char */
2694 s++;
2695 }
2696 else if (!quote)
2697 {
2698 /* Process a single redirection candidate. */
2699 if (*s == '<' || *s == '>'
2700 || ((*s == '1' || *s == '2') && s[1] == '>')
2701 || (*s == '0' && s[1] == '<'))
2702 {
2703 int skip = redir_set_redirection (s, inp, out, err);
2704
2705 if (skip <= 0)
2706 return false;
2707 retval = true;
2708 s += skip;
2709 }
2710 }
2711 if (*s)
2712 *d++ = *s++;
2713 }
2714 *d = '\0';
2715 return retval;
2716}
2717#endif /* !__CYGWIN__ */
2718
dc05df57 2719/* Start an inferior windows child process and sets inferior_ptid to its pid.
24e60978
SC
2720 EXEC_FILE is the file to run.
2721 ALLARGS is a string containing the arguments to the program.
2722 ENV is the environment vector to pass. Errors reported with error(). */
2723
f6ac5f3d
PA
2724void
2725windows_nat_target::create_inferior (const char *exec_file,
2726 const std::string &origallargs,
2727 char **in_env, int from_tty)
24e60978 2728{
b3c613f2 2729 STARTUPINFO si;
41b4aadc 2730#ifdef __CYGWIN__
b3c613f2
CF
2731 cygwin_buf_t real_path[__PMAX];
2732 cygwin_buf_t shell[__PMAX]; /* Path to shell */
d092c5a2 2733 cygwin_buf_t infcwd[__PMAX];
d0d0ab16 2734 const char *sh;
b3c613f2
CF
2735 cygwin_buf_t *toexec;
2736 cygwin_buf_t *cygallargs;
2737 cygwin_buf_t *args;
b7ff339d
CV
2738 char **old_env = NULL;
2739 PWCHAR w32_env;
d0d0ab16 2740 size_t len;
2becadee
CF
2741 int tty;
2742 int ostdin, ostdout, ostderr;
8ba42bc5 2743#else /* !__CYGWIN__ */
b3c613f2 2744 char shell[__PMAX]; /* Path to shell */
5430098f 2745 const char *toexec;
8ba42bc5
EZ
2746 char *args, *allargs_copy;
2747 size_t args_len, allargs_len;
2748 int fd_inp = -1, fd_out = -1, fd_err = -1;
2749 HANDLE tty = INVALID_HANDLE_VALUE;
8ba42bc5 2750 bool redirected = false;
c93dbcba
EZ
2751 char *w32env;
2752 char *temp;
2753 size_t envlen;
2754 int i;
2755 size_t envsize;
2756 char **env;
8ba42bc5 2757#endif /* !__CYGWIN__ */
096c92dd 2758 const char *allargs = origallargs.c_str ();
d0d0ab16
CV
2759 PROCESS_INFORMATION pi;
2760 BOOL ret;
2761 DWORD flags = 0;
05779d57 2762 const char *inferior_tty = current_inferior ()->tty ();
24e60978
SC
2763
2764 if (!exec_file)
8a3fe4f8 2765 error (_("No executable specified, use `target exec'."));
24e60978 2766
d092c5a2
SDJ
2767 const char *inferior_cwd = get_inferior_cwd ();
2768 std::string expanded_infcwd;
2769 if (inferior_cwd != NULL)
2770 {
2771 expanded_infcwd = gdb_tilde_expand (inferior_cwd);
2772 /* Mirror slashes on inferior's cwd. */
2773 std::replace (expanded_infcwd.begin (), expanded_infcwd.end (),
2774 '/', '\\');
2775 inferior_cwd = expanded_infcwd.c_str ();
2776 }
2777
24e60978
SC
2778 memset (&si, 0, sizeof (si));
2779 si.cb = sizeof (si);
2780
d0d0ab16
CV
2781 if (new_group)
2782 flags |= CREATE_NEW_PROCESS_GROUP;
2783
2784 if (new_console)
cd44747c 2785 windows_set_console_info (&si, &flags);
d0d0ab16 2786
10325bc5 2787#ifdef __CYGWIN__
349b409f 2788 if (!useshell)
dfe7f3ac 2789 {
d0d0ab16
CV
2790 flags |= DEBUG_ONLY_THIS_PROCESS;
2791 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, exec_file, real_path,
b3c613f2 2792 __PMAX * sizeof (cygwin_buf_t)) < 0)
d0d0ab16 2793 error (_("Error starting executable: %d"), errno);
dfe7f3ac 2794 toexec = real_path;
b3c613f2 2795#ifdef __USEWIDE
d0d0ab16
CV
2796 len = mbstowcs (NULL, allargs, 0) + 1;
2797 if (len == (size_t) -1)
2798 error (_("Error starting executable: %d"), errno);
2799 cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
2800 mbstowcs (cygallargs, allargs, len);
8ba42bc5 2801#else /* !__USEWIDE */
60c5c021 2802 cygallargs = allargs;
b3c613f2 2803#endif
dfe7f3ac
CF
2804 }
2805 else
2806 {
974e6844 2807 sh = get_shell ();
b3c613f2 2808 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, sh, shell, __PMAX) < 0)
d0d0ab16 2809 error (_("Error starting executable via shell: %d"), errno);
b3c613f2 2810#ifdef __USEWIDE
d0d0ab16
CV
2811 len = sizeof (L" -c 'exec '") + mbstowcs (NULL, exec_file, 0)
2812 + mbstowcs (NULL, allargs, 0) + 2;
2813 cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
2814 swprintf (cygallargs, len, L" -c 'exec %s %s'", exec_file, allargs);
8ba42bc5 2815#else /* !__USEWIDE */
08850b56
PM
2816 len = (sizeof (" -c 'exec '") + strlen (exec_file)
2817 + strlen (allargs) + 2);
2818 cygallargs = (char *) alloca (len);
2819 xsnprintf (cygallargs, len, " -c 'exec %s %s'", exec_file, allargs);
8ba42bc5 2820#endif /* __USEWIDE */
dfe7f3ac 2821 toexec = shell;
d0d0ab16 2822 flags |= DEBUG_PROCESS;
dfe7f3ac 2823 }
b3c613f2 2824
d092c5a2
SDJ
2825 if (inferior_cwd != NULL
2826 && cygwin_conv_path (CCP_POSIX_TO_WIN_W, inferior_cwd,
2827 infcwd, strlen (inferior_cwd)) < 0)
2828 error (_("Error converting inferior cwd: %d"), errno);
2829
b3c613f2
CF
2830#ifdef __USEWIDE
2831 args = (cygwin_buf_t *) alloca ((wcslen (toexec) + wcslen (cygallargs) + 2)
2832 * sizeof (wchar_t));
d0d0ab16
CV
2833 wcscpy (args, toexec);
2834 wcscat (args, L" ");
2835 wcscat (args, cygallargs);
8ba42bc5 2836#else /* !__USEWIDE */
b3c613f2
CF
2837 args = (cygwin_buf_t *) alloca (strlen (toexec) + strlen (cygallargs) + 2);
2838 strcpy (args, toexec);
2839 strcat (args, " ");
2840 strcat (args, cygallargs);
8ba42bc5 2841#endif /* !__USEWIDE */
b3c613f2 2842
b7ff339d
CV
2843#ifdef CW_CVT_ENV_TO_WINENV
2844 /* First try to create a direct Win32 copy of the POSIX environment. */
2845 w32_env = (PWCHAR) cygwin_internal (CW_CVT_ENV_TO_WINENV, in_env);
2846 if (w32_env != (PWCHAR) -1)
2847 flags |= CREATE_UNICODE_ENVIRONMENT;
2848 else
2849 /* If that fails, fall back to old method tweaking GDB's environment. */
8ba42bc5 2850#endif /* CW_CVT_ENV_TO_WINENV */
b7ff339d
CV
2851 {
2852 /* Reset all Win32 environment variables to avoid leftover on next run. */
2853 clear_win32_environment (environ);
2854 /* Prepare the environment vars for CreateProcess. */
2855 old_env = environ;
2856 environ = in_env;
2857 cygwin_internal (CW_SYNC_WINENV);
2858 w32_env = NULL;
2859 }
1750a5ef 2860
05779d57 2861 if (inferior_tty == nullptr)
2becadee
CF
2862 tty = ostdin = ostdout = ostderr = -1;
2863 else
2864 {
05779d57 2865 tty = open (inferior_tty, O_RDWR | O_NOCTTY);
2becadee
CF
2866 if (tty < 0)
2867 {
05779d57 2868 print_sys_errmsg (inferior_tty, errno);
2becadee
CF
2869 ostdin = ostdout = ostderr = -1;
2870 }
2871 else
2872 {
2873 ostdin = dup (0);
2874 ostdout = dup (1);
2875 ostderr = dup (2);
2876 dup2 (tty, 0);
2877 dup2 (tty, 1);
2878 dup2 (tty, 2);
2879 }
2880 }
d0d0ab16
CV
2881
2882 windows_init_thread_list ();
b3c613f2
CF
2883 ret = CreateProcess (0,
2884 args, /* command line */
2885 NULL, /* Security */
2886 NULL, /* thread */
2887 TRUE, /* inherit handles */
2888 flags, /* start flags */
b7ff339d 2889 w32_env, /* environment */
d092c5a2
SDJ
2890 inferior_cwd != NULL ? infcwd : NULL, /* current
2891 directory */
b3c613f2
CF
2892 &si,
2893 &pi);
b7ff339d
CV
2894 if (w32_env)
2895 /* Just free the Win32 environment, if it could be created. */
2896 free (w32_env);
2897 else
2898 {
2899 /* Reset all environment variables to avoid leftover on next run. */
2900 clear_win32_environment (in_env);
2901 /* Restore normal GDB environment variables. */
2902 environ = old_env;
2903 cygwin_internal (CW_SYNC_WINENV);
2904 }
2905
d0d0ab16
CV
2906 if (tty >= 0)
2907 {
6af79d7b 2908 ::close (tty);
d0d0ab16
CV
2909 dup2 (ostdin, 0);
2910 dup2 (ostdout, 1);
2911 dup2 (ostderr, 2);
6af79d7b
JT
2912 ::close (ostdin);
2913 ::close (ostdout);
2914 ::close (ostderr);
d0d0ab16 2915 }
8ba42bc5
EZ
2916#else /* !__CYGWIN__ */
2917 allargs_len = strlen (allargs);
2918 allargs_copy = strcpy ((char *) alloca (allargs_len + 1), allargs);
2919 if (strpbrk (allargs_copy, "<>") != NULL)
2920 {
2921 int e = errno;
2922 errno = 0;
2923 redirected =
2924 redirect_inferior_handles (allargs, allargs_copy,
2925 &fd_inp, &fd_out, &fd_err);
2926 if (errno)
6d91ce9a 2927 warning (_("Error in redirection: %s."), safe_strerror (errno));
8ba42bc5
EZ
2928 else
2929 errno = e;
2930 allargs_len = strlen (allargs_copy);
2931 }
2932 /* If not all the standard streams are redirected by the command
05779d57
PA
2933 line, use INFERIOR_TTY for those which aren't. */
2934 if (inferior_tty != nullptr
8ba42bc5 2935 && !(fd_inp >= 0 && fd_out >= 0 && fd_err >= 0))
41b4aadc
CF
2936 {
2937 SECURITY_ATTRIBUTES sa;
2938 sa.nLength = sizeof(sa);
2939 sa.lpSecurityDescriptor = 0;
2940 sa.bInheritHandle = TRUE;
05779d57 2941 tty = CreateFileA (inferior_tty, GENERIC_READ | GENERIC_WRITE,
41b4aadc
CF
2942 0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
2943 if (tty == INVALID_HANDLE_VALUE)
2944 warning (_("Warning: Failed to open TTY %s, error %#x."),
05779d57 2945 inferior_tty, (unsigned) GetLastError ());
8ba42bc5
EZ
2946 }
2947 if (redirected || tty != INVALID_HANDLE_VALUE)
2948 {
2949 if (fd_inp >= 0)
2950 si.hStdInput = (HANDLE) _get_osfhandle (fd_inp);
2951 else if (tty != INVALID_HANDLE_VALUE)
2952 si.hStdInput = tty;
41b4aadc 2953 else
8ba42bc5
EZ
2954 si.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
2955 if (fd_out >= 0)
2956 si.hStdOutput = (HANDLE) _get_osfhandle (fd_out);
2957 else if (tty != INVALID_HANDLE_VALUE)
2958 si.hStdOutput = tty;
2959 else
2960 si.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
2961 if (fd_err >= 0)
2962 si.hStdError = (HANDLE) _get_osfhandle (fd_err);
2963 else if (tty != INVALID_HANDLE_VALUE)
2964 si.hStdError = tty;
2965 else
2966 si.hStdError = GetStdHandle (STD_ERROR_HANDLE);
2967 si.dwFlags |= STARTF_USESTDHANDLES;
41b4aadc 2968 }
2becadee 2969
8ba42bc5
EZ
2970 toexec = exec_file;
2971 /* Build the command line, a space-separated list of tokens where
2972 the first token is the name of the module to be executed.
2973 To avoid ambiguities introduced by spaces in the module name,
2974 we quote it. */
2975 args_len = strlen (toexec) + 2 /* quotes */ + allargs_len + 2;
2976 args = (char *) alloca (args_len);
2977 xsnprintf (args, args_len, "\"%s\" %s", toexec, allargs_copy);
2978
2979 flags |= DEBUG_ONLY_THIS_PROCESS;
2980
c93dbcba
EZ
2981 /* CreateProcess takes the environment list as a null terminated set of
2982 strings (i.e. two nulls terminate the list). */
2983
2984 /* Get total size for env strings. */
2985 for (envlen = 0, i = 0; in_env[i] && *in_env[i]; i++)
2986 envlen += strlen (in_env[i]) + 1;
2987
2988 envsize = sizeof (in_env[0]) * (i + 1);
2989 env = (char **) alloca (envsize);
2990 memcpy (env, in_env, envsize);
2991 /* Windows programs expect the environment block to be sorted. */
2992 qsort (env, i, sizeof (char *), envvar_cmp);
2993
0ae1c716 2994 w32env = (char *) alloca (envlen + 1);
c93dbcba
EZ
2995
2996 /* Copy env strings into new buffer. */
2997 for (temp = w32env, i = 0; env[i] && *env[i]; i++)
2998 {
2999 strcpy (temp, env[i]);
3000 temp += strlen (temp) + 1;
3001 }
3002
3003 /* Final nil string to terminate new env. */
3004 *temp = 0;
3005
dc05df57 3006 windows_init_thread_list ();
d0d0ab16
CV
3007 ret = CreateProcessA (0,
3008 args, /* command line */
3009 NULL, /* Security */
3010 NULL, /* thread */
3011 TRUE, /* inherit handles */
3012 flags, /* start flags */
c93dbcba 3013 w32env, /* environment */
d092c5a2 3014 inferior_cwd, /* current directory */
d0d0ab16
CV
3015 &si,
3016 &pi);
41b4aadc
CF
3017 if (tty != INVALID_HANDLE_VALUE)
3018 CloseHandle (tty);
8ba42bc5
EZ
3019 if (fd_inp >= 0)
3020 _close (fd_inp);
3021 if (fd_out >= 0)
3022 _close (fd_out);
3023 if (fd_err >= 0)
3024 _close (fd_err);
3025#endif /* !__CYGWIN__ */
2becadee 3026
24e60978 3027 if (!ret)
d50a0ce2 3028 error (_("Error creating process %s, (error %u)."),
8a3fe4f8 3029 exec_file, (unsigned) GetLastError ());
24e60978 3030
46f9f931
HD
3031#ifdef __x86_64__
3032 BOOL wow64;
3033 if (IsWow64Process (pi.hProcess, &wow64))
3034 wow64_process = wow64;
3035#endif
3036
c1766e7d
PM
3037 CloseHandle (pi.hThread);
3038 CloseHandle (pi.hProcess);
3039
dfe7f3ac
CF
3040 if (useshell && shell[0] != '\0')
3041 saw_create = -1;
3042 else
3043 saw_create = 0;
3044
50838d1b 3045 do_initial_windows_stuff (pi.dwProcessId, 0);
d3a09475 3046
17617f2d 3047 /* windows_continue (DBG_CONTINUE, -1, 0); */
24e60978
SC
3048}
3049
f6ac5f3d
PA
3050void
3051windows_nat_target::mourn_inferior ()
24e60978 3052{
17617f2d 3053 (void) windows_continue (DBG_CONTINUE, -1, 0);
df7e5265 3054 x86_cleanup_dregs();
bf25528d
CF
3055 if (open_process_used)
3056 {
3057 CHECK (CloseHandle (current_process_handle));
3058 open_process_used = 0;
3059 }
7928d571 3060 siginfo_er.ExceptionCode = 0;
f6ac5f3d 3061 inf_child_target::mourn_inferior ();
24e60978
SC
3062}
3063
24e60978 3064/* Send a SIGINT to the process group. This acts just like the user typed a
581e13c1 3065 ^C on the controlling terminal. */
24e60978 3066
f6ac5f3d
PA
3067void
3068windows_nat_target::interrupt ()
24e60978 3069{
1ef980b9 3070 DEBUG_EVENTS (("gdb: GenerateConsoleCtrlEvent (CTRLC_EVENT, 0)\n"));
1e37c281 3071 CHECK (GenerateConsoleCtrlEvent (CTRL_C_EVENT, current_event.dwProcessId));
3a4b77d8 3072 registers_changed (); /* refresh register state */
24e60978
SC
3073}
3074
44f38867
PA
3075/* Helper for windows_xfer_partial that handles memory transfers.
3076 Arguments are like target_xfer_partial. */
3077
9b409511 3078static enum target_xfer_status
44f38867 3079windows_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
9b409511 3080 ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
24e60978 3081{
5732a500 3082 SIZE_T done = 0;
44f38867 3083 BOOL success;
9e52adf9 3084 DWORD lasterror = 0;
44f38867
PA
3085
3086 if (writebuf != NULL)
24e60978 3087 {
a2388568 3088 DEBUG_MEM (("gdb: write target memory, %s bytes at %s\n",
b55e14c7 3089 pulongest (len), core_addr_to_string (memaddr)));
44f38867
PA
3090 success = WriteProcessMemory (current_process_handle,
3091 (LPVOID) (uintptr_t) memaddr, writebuf,
3092 len, &done);
9e52adf9 3093 if (!success)
7126d5c8 3094 lasterror = GetLastError ();
2b008701 3095 FlushInstructionCache (current_process_handle,
2c647436 3096 (LPCVOID) (uintptr_t) memaddr, len);
24e60978
SC
3097 }
3098 else
3099 {
a2388568 3100 DEBUG_MEM (("gdb: read target memory, %s bytes at %s\n",
b55e14c7 3101 pulongest (len), core_addr_to_string (memaddr)));
44f38867
PA
3102 success = ReadProcessMemory (current_process_handle,
3103 (LPCVOID) (uintptr_t) memaddr, readbuf,
3104 len, &done);
9e52adf9 3105 if (!success)
7126d5c8 3106 lasterror = GetLastError ();
24e60978 3107 }
9b409511 3108 *xfered_len = (ULONGEST) done;
9e52adf9 3109 if (!success && lasterror == ERROR_PARTIAL_COPY && done > 0)
9b409511 3110 return TARGET_XFER_OK;
9e52adf9 3111 else
9b409511 3112 return success ? TARGET_XFER_OK : TARGET_XFER_E_IO;
24e60978
SC
3113}
3114
f6ac5f3d
PA
3115void
3116windows_nat_target::kill ()
24e60978 3117{
3cee93ac
CF
3118 CHECK (TerminateProcess (current_process_handle, 0));
3119
b5edcb45
ILT
3120 for (;;)
3121 {
17617f2d 3122 if (!windows_continue (DBG_CONTINUE, -1, 1))
b5edcb45 3123 break;
0a4afda3 3124 if (!wait_for_debug_event (&current_event, INFINITE))
b5edcb45 3125 break;
3cee93ac 3126 if (current_event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
b5edcb45
ILT
3127 break;
3128 }
3129
9eee20eb 3130 target_mourn_inferior (inferior_ptid); /* Or just windows_mourn_inferior? */
24e60978
SC
3131}
3132
f6ac5f3d
PA
3133void
3134windows_nat_target::close ()
24e60978 3135{
dc05df57 3136 DEBUG_EVENTS (("gdb: windows_close, inferior_ptid=%d\n",
e99b03dc 3137 inferior_ptid.pid ()));
24e60978 3138}
1ef980b9 3139
581e13c1 3140/* Convert pid to printable format. */
a068643d 3141std::string
f6ac5f3d 3142windows_nat_target::pid_to_str (ptid_t ptid)
24e60978 3143{
7c7411bc
TT
3144 if (ptid.lwp () != 0)
3145 return string_printf ("Thread %d.0x%lx", ptid.pid (), ptid.lwp ());
2dc38344
PA
3146
3147 return normal_pid_to_str (ptid);
3ee6f623
CF
3148}
3149
9b409511 3150static enum target_xfer_status
dc05df57 3151windows_xfer_shared_libraries (struct target_ops *ops,
9b409511
YQ
3152 enum target_object object, const char *annex,
3153 gdb_byte *readbuf, const gdb_byte *writebuf,
3154 ULONGEST offset, ULONGEST len,
3155 ULONGEST *xfered_len)
3cb8e7f6 3156{
de1b3c3d
PA
3157 struct obstack obstack;
3158 const char *buf;
3159 LONGEST len_avail;
3cb8e7f6 3160 struct so_list *so;
3cb8e7f6 3161
de1b3c3d 3162 if (writebuf)
2ed4b548 3163 return TARGET_XFER_E_IO;
3cb8e7f6 3164
de1b3c3d
PA
3165 obstack_init (&obstack);
3166 obstack_grow_str (&obstack, "<library-list>\n");
3167 for (so = solib_start.next; so; so = so->next)
d0e449a1
SM
3168 {
3169 lm_info_windows *li = (lm_info_windows *) so->lm_info;
3170
3171 windows_xfer_shared_library (so->so_name, (CORE_ADDR)
3172 (uintptr_t) li->load_addr,
c162ed3e 3173 &li->text_offset,
d0e449a1
SM
3174 target_gdbarch (), &obstack);
3175 }
de1b3c3d 3176 obstack_grow_str0 (&obstack, "</library-list>\n");
3cb8e7f6 3177
0ae1c716 3178 buf = (const char *) obstack_finish (&obstack);
de1b3c3d
PA
3179 len_avail = strlen (buf);
3180 if (offset >= len_avail)
49dc7f4b
PM
3181 len= 0;
3182 else
3183 {
3184 if (len > len_avail - offset)
3185 len = len_avail - offset;
3186 memcpy (readbuf, buf + offset, len);
3187 }
3cb8e7f6 3188
de1b3c3d 3189 obstack_free (&obstack, NULL);
9b409511 3190 *xfered_len = (ULONGEST) len;
0837c976 3191 return len != 0 ? TARGET_XFER_OK : TARGET_XFER_EOF;
3cb8e7f6
CF
3192}
3193
7928d571
HD
3194/* Helper for windows_nat_target::xfer_partial that handles signal info. */
3195
3196static enum target_xfer_status
3197windows_xfer_siginfo (gdb_byte *readbuf, ULONGEST offset, ULONGEST len,
3198 ULONGEST *xfered_len)
3199{
46f9f931
HD
3200 char *buf = (char *) &siginfo_er;
3201 size_t bufsize = sizeof (siginfo_er);
3202
3203#ifdef __x86_64__
3204 EXCEPTION_RECORD32 er32;
3205 if (wow64_process)
3206 {
3207 buf = (char *) &er32;
3208 bufsize = sizeof (er32);
3209
3210 er32.ExceptionCode = siginfo_er.ExceptionCode;
3211 er32.ExceptionFlags = siginfo_er.ExceptionFlags;
3212 er32.ExceptionRecord = (uintptr_t) siginfo_er.ExceptionRecord;
3213 er32.ExceptionAddress = (uintptr_t) siginfo_er.ExceptionAddress;
3214 er32.NumberParameters = siginfo_er.NumberParameters;
3215 int i;
3216 for (i = 0; i < EXCEPTION_MAXIMUM_PARAMETERS; i++)
3217 er32.ExceptionInformation[i] = siginfo_er.ExceptionInformation[i];
3218 }
3219#endif
3220
7928d571
HD
3221 if (siginfo_er.ExceptionCode == 0)
3222 return TARGET_XFER_E_IO;
3223
3224 if (readbuf == nullptr)
3225 return TARGET_XFER_E_IO;
3226
46f9f931 3227 if (offset > bufsize)
7928d571
HD
3228 return TARGET_XFER_E_IO;
3229
46f9f931
HD
3230 if (offset + len > bufsize)
3231 len = bufsize - offset;
7928d571 3232
46f9f931 3233 memcpy (readbuf, buf + offset, len);
7928d571
HD
3234 *xfered_len = len;
3235
3236 return TARGET_XFER_OK;
3237}
3238
f6ac5f3d
PA
3239enum target_xfer_status
3240windows_nat_target::xfer_partial (enum target_object object,
3241 const char *annex, gdb_byte *readbuf,
2f4f025f
TT
3242 const gdb_byte *writebuf, ULONGEST offset,
3243 ULONGEST len, ULONGEST *xfered_len)
3cb8e7f6 3244{
de1b3c3d 3245 switch (object)
3cb8e7f6 3246 {
de1b3c3d 3247 case TARGET_OBJECT_MEMORY:
9b409511 3248 return windows_xfer_memory (readbuf, writebuf, offset, len, xfered_len);
de1b3c3d
PA
3249
3250 case TARGET_OBJECT_LIBRARIES:
f6ac5f3d 3251 return windows_xfer_shared_libraries (this, object, annex, readbuf,
9b409511 3252 writebuf, offset, len, xfered_len);
3929abe9 3253
7928d571
HD
3254 case TARGET_OBJECT_SIGNAL_INFO:
3255 return windows_xfer_siginfo (readbuf, offset, len, xfered_len);
3256
de1b3c3d 3257 default:
2f4f025f 3258 if (beneath () == NULL)
178d6a63
JB
3259 {
3260 /* This can happen when requesting the transfer of unsupported
3261 objects before a program has been started (and therefore
3262 with the current_target having no target beneath). */
3263 return TARGET_XFER_E_IO;
3264 }
2f4f025f
TT
3265 return beneath ()->xfer_partial (object, annex,
3266 readbuf, writebuf, offset, len,
3267 xfered_len);
3929abe9 3268 }
02c5aecd
CF
3269}
3270
711e434b
PM
3271/* Provide thread local base, i.e. Thread Information Block address.
3272 Returns 1 if ptid is found and sets *ADDR to thread_local_base. */
3273
57810aa7 3274bool
f6ac5f3d 3275windows_nat_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
711e434b 3276{
876d1cd7 3277 windows_thread_info *th;
711e434b 3278
28688adf 3279 th = thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
711e434b 3280 if (th == NULL)
57810aa7 3281 return false;
711e434b
PM
3282
3283 if (addr != NULL)
3284 *addr = th->thread_local_base;
3285
57810aa7 3286 return true;
711e434b
PM
3287}
3288
f6ac5f3d
PA
3289ptid_t
3290windows_nat_target::get_ada_task_ptid (long lwp, long thread)
1e2f1c5c 3291{
7c7411bc 3292 return ptid_t (inferior_ptid.pid (), lwp, 0);
1e2f1c5c
JB
3293}
3294
24cdb46e
РИ
3295/* Implementation of the to_thread_name method. */
3296
f6ac5f3d
PA
3297const char *
3298windows_nat_target::thread_name (struct thread_info *thr)
24cdb46e 3299{
28688adf 3300 return thread_rec (thr->ptid, DONT_INVALIDATE_CONTEXT)->name.get ();
24cdb46e
РИ
3301}
3302
24e60978 3303
6c265988 3304void _initialize_windows_nat ();
24e60978 3305void
6c265988 3306_initialize_windows_nat ()
24e60978 3307{
df7e5265
GB
3308 x86_dr_low.set_control = cygwin_set_dr7;
3309 x86_dr_low.set_addr = cygwin_set_dr;
3310 x86_dr_low.get_addr = cygwin_get_dr;
3311 x86_dr_low.get_status = cygwin_get_dr6;
3312 x86_dr_low.get_control = cygwin_get_dr7;
51a9c8c5 3313
df7e5265
GB
3314 /* x86_dr_low.debug_register_length field is set by
3315 calling x86_set_debug_register_length function
51a9c8c5 3316 in processor windows specific native file. */
fa58ee11 3317
d9f719f1 3318 add_inf_child_target (&the_windows_nat_target);
1ef980b9 3319
d0d0ab16
CV
3320#ifdef __CYGWIN__
3321 cygwin_internal (CW_SET_DOS_FILE_WARNING, 0);
3322#endif
3323
463888ab
РИ
3324 add_com ("signal-event", class_run, signal_event_command, _("\
3325Signal a crashed process with event ID, to allow its debugging.\n\
3326This command is needed in support of setting up GDB as JIT debugger on \
3327MS-Windows. The command should be invoked from the GDB command line using \
3328the '-ex' command-line option. The ID of the event that blocks the \
3329crashed process will be supplied by the Windows JIT debugging mechanism."));
3330
10325bc5 3331#ifdef __CYGWIN__
5bf193a2
AC
3332 add_setshow_boolean_cmd ("shell", class_support, &useshell, _("\
3333Set use of shell to start subprocess."), _("\
3334Show use of shell to start subprocess."), NULL,
3335 NULL,
3336 NULL, /* FIXME: i18n: */
3337 &setlist, &showlist);
3338
581e13c1
MS
3339 add_setshow_boolean_cmd ("cygwin-exceptions", class_support,
3340 &cygwin_exceptions, _("\
09280ddf
CF
3341Break when an exception is detected in the Cygwin DLL itself."), _("\
3342Show whether gdb breaks on exceptions in the Cygwin DLL itself."), NULL,
3343 NULL,
3344 NULL, /* FIXME: i18n: */
3345 &setlist, &showlist);
10325bc5 3346#endif
09280ddf 3347
5bf193a2
AC
3348 add_setshow_boolean_cmd ("new-console", class_support, &new_console, _("\
3349Set creation of new console when creating child process."), _("\
3350Show creation of new console when creating child process."), NULL,
3351 NULL,
3352 NULL, /* FIXME: i18n: */
3353 &setlist, &showlist);
3354
3355 add_setshow_boolean_cmd ("new-group", class_support, &new_group, _("\
3356Set creation of new group when creating child process."), _("\
3357Show creation of new group when creating child process."), NULL,
3358 NULL,
3359 NULL, /* FIXME: i18n: */
3360 &setlist, &showlist);
3361
3362 add_setshow_boolean_cmd ("debugexec", class_support, &debug_exec, _("\
3363Set whether to display execution in child process."), _("\
3364Show whether to display execution in child process."), NULL,
3365 NULL,
3366 NULL, /* FIXME: i18n: */
3367 &setlist, &showlist);
3368
3369 add_setshow_boolean_cmd ("debugevents", class_support, &debug_events, _("\
3370Set whether to display kernel events in child process."), _("\
3371Show whether to display kernel events in child process."), NULL,
3372 NULL,
3373 NULL, /* FIXME: i18n: */
3374 &setlist, &showlist);
3375
3376 add_setshow_boolean_cmd ("debugmemory", class_support, &debug_memory, _("\
3377Set whether to display memory accesses in child process."), _("\
3378Show whether to display memory accesses in child process."), NULL,
3379 NULL,
3380 NULL, /* FIXME: i18n: */
3381 &setlist, &showlist);
3382
3383 add_setshow_boolean_cmd ("debugexceptions", class_support,
3384 &debug_exceptions, _("\
3385Set whether to display kernel exceptions in child process."), _("\
3386Show whether to display kernel exceptions in child process."), NULL,
3387 NULL,
3388 NULL, /* FIXME: i18n: */
3389 &setlist, &showlist);
1ef980b9 3390
711e434b 3391 init_w32_command_list ();
c1748f97
PM
3392
3393 add_cmd ("selector", class_info, display_selectors,
1a966eab 3394 _("Display selectors infos."),
c1748f97 3395 &info_w32_cmdlist);
24e60978 3396}
3cee93ac 3397
fa4ba8da
PM
3398/* Hardware watchpoint support, adapted from go32-nat.c code. */
3399
3400/* Pass the address ADDR to the inferior in the I'th debug register.
3401 Here we just store the address in dr array, the registers will be
dc05df57 3402 actually set up when windows_continue is called. */
9bb9e8ad 3403static void
fa4ba8da
PM
3404cygwin_set_dr (int i, CORE_ADDR addr)
3405{
3406 if (i < 0 || i > 3)
3407 internal_error (__FILE__, __LINE__,
e2e0b3e5 3408 _("Invalid register %d in cygwin_set_dr.\n"), i);
41b4aadc 3409 dr[i] = addr;
fa4ba8da
PM
3410 debug_registers_changed = 1;
3411 debug_registers_used = 1;
3412}
3413
3414/* Pass the value VAL to the inferior in the DR7 debug control
3415 register. Here we just store the address in D_REGS, the watchpoint
dc05df57 3416 will be actually set up in windows_wait. */
9bb9e8ad
PM
3417static void
3418cygwin_set_dr7 (unsigned long val)
fa4ba8da 3419{
9bb9e8ad 3420 dr[7] = (CORE_ADDR) val;
fa4ba8da
PM
3421 debug_registers_changed = 1;
3422 debug_registers_used = 1;
3423}
3424
7b50312a
PA
3425/* Get the value of debug register I from the inferior. */
3426
3427static CORE_ADDR
3428cygwin_get_dr (int i)
3429{
3430 return dr[i];
3431}
3432
fa4ba8da
PM
3433/* Get the value of the DR6 debug status register from the inferior.
3434 Here we just return the value stored in dr[6]
3435 by the last call to thread_rec for current_event.dwThreadId id. */
9bb9e8ad 3436static unsigned long
fa4ba8da
PM
3437cygwin_get_dr6 (void)
3438{
9bb9e8ad 3439 return (unsigned long) dr[6];
fa4ba8da
PM
3440}
3441
7b50312a
PA
3442/* Get the value of the DR7 debug status register from the inferior.
3443 Here we just return the value stored in dr[7] by the last call to
3444 thread_rec for current_event.dwThreadId id. */
3445
3446static unsigned long
3447cygwin_get_dr7 (void)
3448{
3449 return (unsigned long) dr[7];
3450}
3451
2dc38344 3452/* Determine if the thread referenced by "ptid" is alive
3cee93ac 3453 by "polling" it. If WaitForSingleObject returns WAIT_OBJECT_0
581e13c1 3454 it means that the thread has died. Otherwise it is assumed to be alive. */
f6ac5f3d 3455
57810aa7 3456bool
f6ac5f3d 3457windows_nat_target::thread_alive (ptid_t ptid)
3cee93ac 3458{
7c7411bc 3459 gdb_assert (ptid.lwp () != 0);
39f77062 3460
28688adf 3461 return (WaitForSingleObject (thread_rec (ptid, DONT_INVALIDATE_CONTEXT)->h, 0)
8e61ebec 3462 != WAIT_OBJECT_0);
3cee93ac
CF
3463}
3464
6c265988 3465void _initialize_check_for_gdb_ini ();
2a3d5645 3466void
6c265988 3467_initialize_check_for_gdb_ini ()
2a3d5645
CF
3468{
3469 char *homedir;
3470 if (inhibit_gdbinit)
3471 return;
3472
3473 homedir = getenv ("HOME");
3474 if (homedir)
3475 {
3476 char *p;
3477 char *oldini = (char *) alloca (strlen (homedir) +
1270fac6 3478 sizeof ("gdb.ini") + 1);
2a3d5645
CF
3479 strcpy (oldini, homedir);
3480 p = strchr (oldini, '\0');
0ba1096a 3481 if (p > oldini && !IS_DIR_SEPARATOR (p[-1]))
2a3d5645
CF
3482 *p++ = '/';
3483 strcpy (p, "gdb.ini");
3484 if (access (oldini, 0) == 0)
3485 {
3486 int len = strlen (oldini);
1270fac6 3487 char *newini = (char *) alloca (len + 2);
08850b56 3488
1270fac6 3489 xsnprintf (newini, len + 2, "%.*s.gdbinit",
08850b56 3490 (int) (len - (sizeof ("gdb.ini") - 1)), oldini);
8a3fe4f8 3491 warning (_("obsolete '%s' found. Rename to '%s'."), oldini, newini);
2a3d5645
CF
3492 }
3493 }
3494}
33605d39 3495
2b008701 3496/* Define dummy functions which always return error for the rare cases where
581e13c1 3497 these functions could not be found. */
2b008701
CF
3498static BOOL WINAPI
3499bad_DebugActiveProcessStop (DWORD w)
3500{
3501 return FALSE;
3502}
3503static BOOL WINAPI
3504bad_DebugBreakProcess (HANDLE w)
3505{
3506 return FALSE;
3507}
3508static BOOL WINAPI
3509bad_DebugSetProcessKillOnExit (BOOL w)
3510{
3511 return FALSE;
3512}
3513static BOOL WINAPI
3514bad_EnumProcessModules (HANDLE w, HMODULE *x, DWORD y, LPDWORD z)
3515{
3516 return FALSE;
3517}
b3c613f2
CF
3518
3519#ifdef __USEWIDE
2b008701 3520static DWORD WINAPI
b3c613f2 3521bad_GetModuleFileNameExW (HANDLE w, HMODULE x, LPWSTR y, DWORD z)
2b008701
CF
3522{
3523 return 0;
3524}
d0d0ab16
CV
3525#else
3526static DWORD WINAPI
b3c613f2 3527bad_GetModuleFileNameExA (HANDLE w, HMODULE x, LPSTR y, DWORD z)
d0d0ab16
CV
3528{
3529 return 0;
3530}
3531#endif
b3c613f2 3532
2b008701
CF
3533static BOOL WINAPI
3534bad_GetModuleInformation (HANDLE w, HMODULE x, LPMODULEINFO y, DWORD z)
3535{
3536 return FALSE;
3537}
3538
418c6cb3
CF
3539static BOOL WINAPI
3540bad_OpenProcessToken (HANDLE w, DWORD x, PHANDLE y)
3541{
3542 return FALSE;
3543}
3544
cd44747c
PM
3545static BOOL WINAPI
3546bad_GetCurrentConsoleFont (HANDLE w, BOOL bMaxWindow, CONSOLE_FONT_INFO *f)
3547{
3548 f->nFont = 0;
3549 return 1;
3550}
3551static COORD WINAPI
3552bad_GetConsoleFontSize (HANDLE w, DWORD nFont)
3553{
3554 COORD size;
3555 size.X = 8;
3556 size.Y = 12;
3557 return size;
3558}
3559
2b008701 3560/* Load any functions which may not be available in ancient versions
581e13c1 3561 of Windows. */
d603d4b3 3562
6c265988 3563void _initialize_loadable ();
33605d39 3564void
6c265988 3565_initialize_loadable ()
33605d39 3566{
2b008701
CF
3567 HMODULE hm = NULL;
3568
43499ea3
PA
3569#define GPA(m, func) \
3570 func = (func ## _ftype *) GetProcAddress (m, #func)
3571
2b008701
CF
3572 hm = LoadLibrary ("kernel32.dll");
3573 if (hm)
33605d39 3574 {
43499ea3
PA
3575 GPA (hm, DebugActiveProcessStop);
3576 GPA (hm, DebugBreakProcess);
3577 GPA (hm, DebugSetProcessKillOnExit);
3578 GPA (hm, GetConsoleFontSize);
3579 GPA (hm, DebugActiveProcessStop);
3580 GPA (hm, GetCurrentConsoleFont);
46f9f931
HD
3581#ifdef __x86_64__
3582 GPA (hm, Wow64SuspendThread);
3583 GPA (hm, Wow64GetThreadContext);
3584 GPA (hm, Wow64SetThreadContext);
3585 GPA (hm, Wow64GetThreadSelectorEntry);
3586#endif
2b008701 3587 }
33605d39 3588
2b008701 3589 /* Set variables to dummy versions of these processes if the function
581e13c1 3590 wasn't found in kernel32.dll. */
b3c613f2
CF
3591 if (!DebugBreakProcess)
3592 DebugBreakProcess = bad_DebugBreakProcess;
3593 if (!DebugActiveProcessStop || !DebugSetProcessKillOnExit)
2b008701 3594 {
b3c613f2
CF
3595 DebugActiveProcessStop = bad_DebugActiveProcessStop;
3596 DebugSetProcessKillOnExit = bad_DebugSetProcessKillOnExit;
2b008701 3597 }
cd44747c
PM
3598 if (!GetConsoleFontSize)
3599 GetConsoleFontSize = bad_GetConsoleFontSize;
3600 if (!GetCurrentConsoleFont)
3601 GetCurrentConsoleFont = bad_GetCurrentConsoleFont;
33605d39 3602
2b008701 3603 /* Load optional functions used for retrieving filename information
581e13c1 3604 associated with the currently debugged process or its dlls. */
2b008701
CF
3605 hm = LoadLibrary ("psapi.dll");
3606 if (hm)
3607 {
43499ea3 3608 GPA (hm, EnumProcessModules);
46f9f931
HD
3609#ifdef __x86_64__
3610 GPA (hm, EnumProcessModulesEx);
3611#endif
43499ea3 3612 GPA (hm, GetModuleInformation);
aec47d1d
JB
3613 GetModuleFileNameEx = (GetModuleFileNameEx_ftype *)
3614 GetProcAddress (hm, GetModuleFileNameEx_name);
33605d39
CF
3615 }
3616
b3c613f2 3617 if (!EnumProcessModules || !GetModuleInformation || !GetModuleFileNameEx)
2b008701
CF
3618 {
3619 /* Set variables to dummy versions of these processes if the function
581e13c1 3620 wasn't found in psapi.dll. */
b3c613f2
CF
3621 EnumProcessModules = bad_EnumProcessModules;
3622 GetModuleInformation = bad_GetModuleInformation;
3623 GetModuleFileNameEx = bad_GetModuleFileNameEx;
581e13c1
MS
3624 /* This will probably fail on Windows 9x/Me. Let the user know
3625 that we're missing some functionality. */
3626 warning(_("\
3627cannot automatically find executable file or library to read symbols.\n\
3628Use \"file\" or \"dll\" command to load executable/libraries directly."));
418c6cb3
CF
3629 }
3630
3631 hm = LoadLibrary ("advapi32.dll");
3632 if (hm)
3633 {
43499ea3
PA
3634 GPA (hm, OpenProcessToken);
3635 GPA (hm, LookupPrivilegeValueA);
3636 GPA (hm, AdjustTokenPrivileges);
418c6cb3 3637 /* Only need to set one of these since if OpenProcessToken fails nothing
581e13c1
MS
3638 else is needed. */
3639 if (!OpenProcessToken || !LookupPrivilegeValueA
3640 || !AdjustTokenPrivileges)
b3c613f2 3641 OpenProcessToken = bad_OpenProcessToken;
2b008701 3642 }
43499ea3
PA
3643
3644#undef GPA
33605d39 3645}
This page took 2.770274 seconds and 4 git commands to generate.