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