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