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