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