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