]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame_incremental - gdb/windows-nat.c
Automatic date update in version.in
[thirdparty/binutils-gdb.git] / gdb / windows-nat.c
... / ...
CommitLineData
1/* Target-vector operations for controlling windows child processes, for GDB.
2
3 Copyright (C) 1995-2025 Free Software Foundation, Inc.
4
5 Contributed by Cygnus Solutions, A Red Hat Company.
6
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
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
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
20 along with this program. If not, see <http://www.gnu.org/licenses/>. */
21
22/* Originally by Steve Chamberlain, sac@cygnus.com */
23
24#include "exceptions.h"
25#include "frame.h"
26#include "inferior.h"
27#include "infrun.h"
28#include "target.h"
29#include "gdbcore.h"
30#include "command.h"
31#include "completer.h"
32#include "regcache.h"
33#include "top.h"
34#include <signal.h>
35#include <sys/types.h>
36#include <fcntl.h>
37#include <windows.h>
38#include <imagehlp.h>
39#ifdef __CYGWIN__
40#include <wchar.h>
41#include <sys/cygwin.h>
42#include <cygwin/version.h>
43#endif
44#include <algorithm>
45#include <atomic>
46#include <vector>
47#include <queue>
48
49#include "filenames.h"
50#include "symfile.h"
51#include "objfiles.h"
52#include "gdb_bfd.h"
53#include "gdbsupport/gdb_obstack.h"
54#include "gdbthread.h"
55#include "cli/cli-cmds.h"
56#include "cli/cli-style.h"
57#include <unistd.h>
58#include "exec.h"
59#include "solib.h"
60#include "xml-support.h"
61#include "inttypes.h"
62
63#include "i386-tdep.h"
64#include "i387-tdep.h"
65
66#include "windows-tdep.h"
67#include "windows-nat.h"
68#include "x86-nat.h"
69#include "complaints.h"
70#include "inf-child.h"
71#include "gdbsupport/gdb_tilde_expand.h"
72#include "gdbsupport/pathstuff.h"
73#include "gdbsupport/gdb_wait.h"
74#include "nat/windows-nat.h"
75#include "gdbsupport/symbol.h"
76#include "ser-event.h"
77#include "inf-loop.h"
78
79using namespace windows_nat;
80
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
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__
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
146/* The current process. */
147static windows_per_inferior windows_process;
148
149#undef STARTUPINFO
150
151#ifndef __CYGWIN__
152# define __PMAX (MAX_PATH + 1)
153# define STARTUPINFO STARTUPINFOA
154#else
155# define __PMAX PATH_MAX
156# define STARTUPINFO STARTUPINFOW
157#endif
158
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
161 headers in the first place since they were our own invention... */
162#ifndef _GNU_H_WINDOWS_H
163enum
164 {
165 FLAG_TRACE_BIT = 0x100,
166 };
167#endif
168
169#define DR6_CLEAR_VALUE 0xffff0ff0
170
171/* The string sent by cygwin when it processes a signal.
172 FIXME: This should be in a cygwin include file. */
173#ifndef _CYGWIN_SIGNAL_STRING
174#define _CYGWIN_SIGNAL_STRING "cYgSiGw00f"
175#endif
176
177#define CHECK(x) check (x, __FILE__,__LINE__)
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__)
189
190static void cygwin_set_dr (int i, CORE_ADDR addr);
191static void cygwin_set_dr7 (unsigned long val);
192static CORE_ADDR cygwin_get_dr (int i);
193static unsigned long cygwin_get_dr6 (void);
194static unsigned long cygwin_get_dr7 (void);
195
196/* User options. */
197static bool new_console = false;
198#ifdef __CYGWIN__
199static bool cygwin_exceptions = false;
200#endif
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 */
207
208/* See windows_nat_target::resume to understand why this is commented
209 out. */
210#if 0
211/* This vector maps the target's idea of an exception (extracted
212 from the DEBUG_EVENT structure) to GDB's idea. */
213
214struct xlate_exception
215 {
216 DWORD them;
217 enum gdb_signal us;
218 };
219
220static const struct xlate_exception xlate[] =
221{
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},
227 {STATUS_FLOAT_DIVIDE_BY_ZERO, GDB_SIGNAL_FPE}
228};
229
230#endif /* 0 */
231
232struct windows_nat_target final : public x86_nat_target<inf_child_target>
233{
234 windows_nat_target ();
235
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
247 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
248
249 void fetch_registers (struct regcache *, int) override;
250 void store_registers (struct regcache *, int) override;
251
252 bool stopped_by_sw_breakpoint () override
253 {
254 windows_thread_info *th
255 = windows_process.thread_rec (inferior_ptid, DONT_INVALIDATE_CONTEXT);
256 return th->stopped_at_software_breakpoint;
257 }
258
259 bool supports_stopped_by_sw_breakpoint () override
260 {
261 return true;
262 }
263
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
280 bool thread_alive (ptid_t ptid) override;
281
282 std::string pid_to_str (ptid_t) override;
283
284 void interrupt () override;
285 void pass_ctrlc () override;
286
287 const char *pid_to_exec_file (int pid) override;
288
289 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
290
291 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
292
293 const char *thread_name (struct thread_info *) override;
294
295 ptid_t get_windows_debug_event (int pid, struct target_waitstatus *ourstatus,
296 target_wait_flags options);
297
298 void do_initial_windows_stuff (DWORD pid, bool attaching);
299
300 bool supports_disable_randomization () override
301 {
302 return disable_randomization_available ();
303 }
304
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
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 ();
328
329 BOOL windows_continue (DWORD continue_status, int id, int killed,
330 bool last_call = false);
331
332 /* Helper function to start process_thread. */
333 static DWORD WINAPI process_thread_starter (LPVOID self);
334
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
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);
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
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
358 /* Queue used to send requests to process_thread. This is
359 implicitly locked. */
360 std::queue<gdb::function_view<bool ()>> m_queue;
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;
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;
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;
386};
387
388static void
389check (BOOL ok, const char *file, int line)
390{
391 if (!ok)
392 {
393 unsigned err = (unsigned) GetLastError ();
394 gdb_printf ("error return %s:%d was %u: %s\n", file, line,
395 err, strwinerror (err));
396 }
397}
398
399windows_nat_target::windows_nat_target ()
400 : m_pushed_event (CreateEvent (nullptr, false, false, nullptr)),
401 m_response_event (CreateEvent (nullptr, false, false, nullptr)),
402 m_wait_event (make_serial_event ())
403{
404 HANDLE bg_thread = CreateThread (nullptr, 64 * 1024,
405 process_thread_starter, this, 0, nullptr);
406 CloseHandle (bg_thread);
407}
408
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 ());
424
425 m_is_async = enable;
426}
427
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 {
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;
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
455DWORD WINAPI
456windows_nat_target::process_thread_starter (LPVOID self)
457{
458 ((windows_nat_target *) self)->process_thread ();
459 return 0;
460}
461
462void
463windows_nat_target::process_thread ()
464{
465 while (true)
466 {
467 wait_for_single (m_pushed_event, INFINITE);
468
469 gdb::function_view<bool ()> func = std::move (m_queue.front ());
470 m_queue.pop ();
471
472 bool should_wait = func ();
473 SetEvent (m_response_event);
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 }
484 }
485}
486
487void
488windows_nat_target::do_synchronously (gdb::function_view<bool ()> func)
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 {
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;
509 });
510
511 m_continued = false;
512}
513
514/* See nat/windows-nat.h. */
515
516windows_thread_info *
517windows_per_inferior::thread_rec
518 (ptid_t ptid, thread_disposition_type disposition)
519{
520 for (auto &th : thread_list)
521 if (th->tid == ptid.lwp ())
522 {
523 if (!th->suspended)
524 {
525 switch (disposition)
526 {
527 case DONT_INVALIDATE_CONTEXT:
528 /* Nothing. */
529 break;
530 case INVALIDATE_CONTEXT:
531 if (ptid.lwp () != current_event.dwThreadId)
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 }
540 }
541 return th.get ();
542 }
543
544 return NULL;
545}
546
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
555windows_thread_info *
556windows_nat_target::add_thread (ptid_t ptid, HANDLE h, void *tlb,
557 bool main_thread_p)
558{
559 windows_thread_info *th;
560
561 gdb_assert (ptid.lwp () != 0);
562
563 if ((th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT)))
564 return th;
565
566 CORE_ADDR base = (CORE_ADDR) (uintptr_t) tlb;
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. */
570 if (windows_process.wow64_process)
571 base += 0x2000;
572#endif
573 th = new windows_thread_info (ptid.lwp (), h, base);
574 windows_process.thread_list.emplace_back (th);
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)
582 add_thread_silent (this, ptid);
583 else
584 ::add_thread (this, ptid);
585
586 /* It's simplest to always set this and update the debug
587 registers. */
588 th->debug_registers_changed = true;
589
590 return th;
591}
592
593/* Clear out any old thread list and reinitialize it to a
594 pristine state. */
595static void
596windows_init_thread_list (void)
597{
598 DEBUG_EVENTS ("called");
599 windows_process.thread_list.clear ();
600}
601
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
609void
610windows_nat_target::delete_thread (ptid_t ptid, DWORD exit_code,
611 bool main_thread_p)
612{
613 DWORD id;
614
615 gdb_assert (ptid.lwp () != 0);
616
617 id = ptid.lwp ();
618
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. */
622
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);
626
627 auto iter = std::find_if (windows_process.thread_list.begin (),
628 windows_process.thread_list.end (),
629 [=] (std::unique_ptr<windows_thread_info> &th)
630 {
631 return th->tid == id;
632 });
633
634 if (iter != windows_process.thread_list.end ())
635 windows_process.thread_list.erase (iter);
636}
637
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
648static void
649windows_fetch_one_register (struct regcache *regcache,
650 windows_thread_info *th, int r)
651{
652 gdb_assert (r >= 0);
653 gdb_assert (!th->reload_context);
654
655 char *context_ptr = windows_process.with_context (th, [] (auto *context)
656 {
657 return (char *) context;
658 });
659
660 char *context_offset = context_ptr + windows_process.mappings[r];
661 struct gdbarch *gdbarch = regcache->arch ();
662 i386_gdbarch_tdep *tdep = gdbarch_tdep<i386_gdbarch_tdep> (gdbarch);
663
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
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))
672 {
673 gdb_byte bytes[4] = {};
674 memcpy (bytes, context_offset, 2);
675 regcache->raw_supply (r, bytes);
676 }
677 else if (r == I387_FOP_REGNUM (tdep))
678 {
679 long l = (*((long *) context_offset) >> 16) & ((1 << 11) - 1);
680 regcache->raw_supply (r, &l);
681 }
682 else
683 {
684 if (th->stopped_at_software_breakpoint
685 && !th->pc_adjusted
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 }
704 /* Make sure we only rewrite the PC a single time. */
705 th->pc_adjusted = true;
706 }
707 regcache->raw_supply (r, context_offset);
708 }
709}
710
711void
712windows_nat_target::fetch_registers (struct regcache *regcache, int r)
713{
714 windows_thread_info *th
715 = windows_process.thread_rec (regcache->ptid (), INVALIDATE_CONTEXT);
716
717 /* Check if TH exists. Windows sometimes uses a non-existent
718 thread id in its events. */
719 if (th == NULL)
720 return;
721
722 if (th->reload_context)
723 {
724 windows_process.with_context (th, [&] (auto *context)
725 {
726 context->ContextFlags = WindowsContext<decltype(context)>::all;
727 CHECK (get_thread_context (th->h, context));
728 /* Copy dr values from that thread.
729 But only if there were not modified since last stop.
730 PR gdb/2388 */
731 if (!th->debug_registers_changed)
732 {
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;
739 }
740 });
741
742 th->reload_context = false;
743 }
744
745 if (r < 0)
746 for (r = 0; r < gdbarch_num_regs (regcache->arch()); r++)
747 windows_fetch_one_register (regcache, th, r);
748 else
749 windows_fetch_one_register (regcache, th, r);
750}
751
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.
754
755 This function assumes that R is non-negative. A failed assertion
756 assertion is raised if that is not true. */
757
758static void
759windows_store_one_register (const struct regcache *regcache,
760 windows_thread_info *th, int r)
761{
762 gdb_assert (r >= 0);
763
764 char *context_ptr = windows_process.with_context (th, [] (auto *context)
765 {
766 return (char *) context;
767 });
768
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]);
792}
793
794/* Store a new register value into the context of the thread tied to
795 REGCACHE. */
796
797void
798windows_nat_target::store_registers (struct regcache *regcache, int r)
799{
800 windows_thread_info *th
801 = windows_process.thread_rec (regcache->ptid (), INVALIDATE_CONTEXT);
802
803 /* Check if TH exists. Windows sometimes uses a non-existent
804 thread id in its events. */
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);
813}
814
815/* See nat/windows-nat.h. */
816
817static windows_solib *
818windows_make_so (const char *name, LPVOID load_addr)
819{
820 windows_solib *so = &windows_process.solibs.emplace_back ();
821 so->load_addr = load_addr;
822 so->original_name = name;
823
824#ifndef __CYGWIN__
825 char *p;
826 char buf[__PMAX];
827 char cwd[__PMAX];
828 WIN32_FIND_DATA w32_fd;
829 HANDLE h = FindFirstFile(name, &w32_fd);
830
831 if (h == INVALID_HANDLE_VALUE)
832 strcpy (buf, name);
833 else
834 {
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 }
846 }
847 if (strcasecmp (buf, "ntdll.dll") == 0)
848 {
849 GetSystemDirectory (buf, sizeof (buf));
850 strcat (buf, "\\ntdll.dll");
851 }
852
853 so->name = buf;
854#else
855 wchar_t buf[__PMAX];
856
857 buf[0] = 0;
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 }
866 if (buf[0])
867 {
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;
882 }
883 else
884 {
885 gdb::unique_xmalloc_ptr<char> rname = gdb_realpath (name);
886 if (rname != nullptr)
887 so->name = rname.get ();
888 else
889 {
890 warning (_("dll path for \"%s\" inaccessible"), name);
891 so->name = so->original_name;
892 }
893 }
894 /* Record cygwin1.dll .text start/end. */
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)
899 {
900 asection *text = NULL;
901
902 gdb_bfd_ref_ptr abfd (gdb_bfd_open (so->name.c_str(), "pei-i386"));
903
904 if (abfd == NULL)
905 return so;
906
907 if (bfd_check_format (abfd.get (), bfd_object))
908 text = bfd_get_section_by_name (abfd.get (), ".text");
909
910 if (!text)
911 return so;
912
913 /* The symbols in a dll are offset by 0x1000, which is the
914 offset from 0 of the first byte in an image - because of the
915 file header and the section alignment. */
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);
920 }
921#endif
922
923 return so;
924}
925
926/* See nat/windows-nat.h. */
927
928void
929windows_per_inferior::handle_load_dll (const char *dll_name, LPVOID base)
930{
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));
934}
935
936/* See nat/windows-nat.h. */
937
938void
939windows_per_inferior::handle_unload_dll ()
940{
941 LPVOID lpBaseOfDll = current_event.u.UnloadDll.lpBaseOfDll;
942
943 auto iter = std::remove_if (windows_process.solibs.begin (),
944 windows_process.solibs.end (),
945 [&] (windows_solib &lib)
946 {
947 if (lib.load_addr == lpBaseOfDll)
948 {
949 DEBUG_EVENTS ("Unloading dll \"%s\".", lib.name.c_str ());
950 return true;
951 }
952 return false;
953 });
954
955 if (iter != windows_process.solibs.end ())
956 {
957 windows_process.solibs.erase (iter, windows_process.solibs.end ());
958 return;
959 }
960
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). */
968 complaint (_("dll starting at %s not found."),
969 host_address_to_string (lpBaseOfDll));
970}
971
972/* Clear list of loaded DLLs. */
973static void
974windows_clear_solib (void)
975{
976 windows_process.solibs.clear ();
977}
978
979static void
980signal_event_command (const char *args, int from_tty)
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
998/* See nat/windows-nat.h. */
999
1000int
1001windows_per_inferior::handle_output_debug_string
1002 (struct target_waitstatus *ourstatus)
1003{
1004 int retval = 0;
1005
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 ()))
1011 /* nothing to do */;
1012 else if (!startswith (s.get (), _CYGWIN_SIGNAL_STRING))
1013 {
1014#ifdef __CYGWIN__
1015 if (!startswith (s.get (), "cYg"))
1016#endif
1017 {
1018 char *p = strchr (s.get (), '\0');
1019
1020 if (p > s.get () && *--p == '\n')
1021 *p = '\0';
1022 warning (("%s"), s.get ());
1023 }
1024 }
1025#ifdef __CYGWIN__
1026 else
1027 {
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. */
1037 char *p;
1038 int sig = strtol (s.get () + sizeof (_CYGWIN_SIGNAL_STRING) - 1, &p, 0);
1039 gdb_signal gotasig = gdb_signal_from_host (sig);
1040 LPCVOID x = 0;
1041
1042 if (gotasig)
1043 {
1044 ourstatus->set_stopped (gotasig);
1045 retval = strtoul (p, &p, 0);
1046 if (!retval)
1047 retval = current_event.dwThreadId;
1048 else
1049 x = (LPCVOID) (uintptr_t) strtoull (p, NULL, 0);
1050 }
1051
1052 DEBUG_EVENTS ("gdb: cygwin signal %d, thread 0x%x, CONTEXT @ %p",
1053 gotasig, retval, x);
1054 }
1055#endif
1056
1057 return retval;
1058}
1059
1060static int
1061display_selector (HANDLE thread, DWORD sel)
1062{
1063 LDT_ENTRY info;
1064 BOOL ret = windows_process.with_context (nullptr, [&] (auto *context)
1065 {
1066 return get_thread_selector_entry (context, thread, sel, &info);
1067 });
1068 if (ret)
1069 {
1070 int base, limit;
1071 gdb_printf ("0x%03x: ", (unsigned) sel);
1072 if (!info.HighWord.Bits.Pres)
1073 {
1074 gdb_puts ("Segment not present\n");
1075 return 0;
1076 }
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)
1082 limit = (limit << 12) | 0xfff;
1083 gdb_printf ("base=0x%08x limit=0x%08x", base, limit);
1084 if (info.HighWord.Bits.Default_Big)
1085 gdb_puts(" 32-bit ");
1086 else
1087 gdb_puts(" 16-bit ");
1088 switch ((info.HighWord.Bits.Type & 0xf) >> 1)
1089 {
1090 case 0:
1091 gdb_puts ("Data (Read-Only, Exp-up");
1092 break;
1093 case 1:
1094 gdb_puts ("Data (Read/Write, Exp-up");
1095 break;
1096 case 2:
1097 gdb_puts ("Unused segment (");
1098 break;
1099 case 3:
1100 gdb_puts ("Data (Read/Write, Exp-down");
1101 break;
1102 case 4:
1103 gdb_puts ("Code (Exec-Only, N.Conf");
1104 break;
1105 case 5:
1106 gdb_puts ("Code (Exec/Read, N.Conf");
1107 break;
1108 case 6:
1109 gdb_puts ("Code (Exec-Only, Conf");
1110 break;
1111 case 7:
1112 gdb_puts ("Code (Exec/Read, Conf");
1113 break;
1114 default:
1115 gdb_printf ("Unknown type 0x%lx",
1116 (unsigned long) info.HighWord.Bits.Type);
1117 }
1118 if ((info.HighWord.Bits.Type & 0x1) == 0)
1119 gdb_puts(", N.Acc");
1120 gdb_puts (")\n");
1121 if ((info.HighWord.Bits.Type & 0x10) == 0)
1122 gdb_puts("System selector ");
1123 gdb_printf ("Privilege level = %ld. ",
1124 (unsigned long) info.HighWord.Bits.Dpl);
1125 if (info.HighWord.Bits.Granularity)
1126 gdb_puts ("Page granular.\n");
1127 else
1128 gdb_puts ("Byte granular.\n");
1129 return 1;
1130 }
1131 else
1132 {
1133 DWORD err = GetLastError ();
1134 if (err == ERROR_NOT_SUPPORTED)
1135 gdb_printf ("Function not supported\n");
1136 else
1137 gdb_printf ("Invalid selector 0x%x.\n", (unsigned) sel);
1138 return 0;
1139 }
1140}
1141
1142static void
1143display_selectors (const char * args, int from_tty)
1144{
1145 if (inferior_ptid == null_ptid)
1146 {
1147 gdb_puts ("Impossible to display selectors now.\n");
1148 return;
1149 }
1150
1151 windows_thread_info *current_windows_thread
1152 = windows_process.thread_rec (inferior_ptid, DONT_INVALIDATE_CONTEXT);
1153
1154 if (!args)
1155 {
1156 windows_process.with_context (current_windows_thread, [&] (auto *context)
1157 {
1158 gdb_puts ("Selector $cs\n");
1159 display_selector (current_windows_thread->h, context->SegCs);
1160 gdb_puts ("Selector $ds\n");
1161 display_selector (current_windows_thread->h, context->SegDs);
1162 gdb_puts ("Selector $es\n");
1163 display_selector (current_windows_thread->h, context->SegEs);
1164 gdb_puts ("Selector $ss\n");
1165 display_selector (current_windows_thread->h, context->SegSs);
1166 gdb_puts ("Selector $fs\n");
1167 display_selector (current_windows_thread->h, context->SegFs);
1168 gdb_puts ("Selector $gs\n");
1169 display_selector (current_windows_thread->h, context->SegGs);
1170 });
1171 }
1172 else
1173 {
1174 int sel;
1175 sel = parse_and_eval_long (args);
1176 gdb_printf ("Selector \"%s\"\n",args);
1177 display_selector (current_windows_thread->h, sel);
1178 }
1179}
1180
1181/* See nat/windows-nat.h. */
1182
1183bool
1184windows_per_inferior::handle_access_violation
1185 (const EXCEPTION_RECORD *rec)
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
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
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. */
1213BOOL
1214windows_nat_target::windows_continue (DWORD continue_status, int id,
1215 int killed, bool last_call)
1216{
1217 windows_process.desired_stop_thread_id = id;
1218
1219 if (windows_process.matching_pending_stop (debug_events))
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 }
1227
1228 for (auto &th : windows_process.thread_list)
1229 if (id == -1 || id == (int) th->tid)
1230 {
1231 windows_process.with_context (th.get (), [&] (auto *context)
1232 {
1233 if (th->debug_registers_changed)
1234 {
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];
1243 th->debug_registers_changed = false;
1244 }
1245 if (context->ContextFlags)
1246 {
1247 DWORD ec = 0;
1248
1249 if (GetExitCodeThread (th->h, &ec)
1250 && ec == STILL_ACTIVE)
1251 {
1252 BOOL status = set_thread_context (th->h, context);
1253
1254 if (!killed)
1255 CHECK (status);
1256 }
1257 context->ContextFlags = 0;
1258 }
1259 });
1260
1261 th->resume ();
1262 }
1263 else
1264 {
1265 /* When single-stepping a specific thread, other threads must
1266 be suspended. */
1267 th->suspend ();
1268 }
1269
1270 std::optional<unsigned> err;
1271 do_synchronously ([&] ()
1272 {
1273 if (!continue_last_debug_event (continue_status, debug_events))
1274 err = (unsigned) GetLastError ();
1275 /* On the last call, do not block waiting for an event that will
1276 never come. */
1277 return !last_call;
1278 });
1279
1280 if (err.has_value ())
1281 throw_winerror_with_name (_("Failed to resume program execution"
1282 " - ContinueDebugEvent failed"),
1283 *err);
1284
1285 m_continued = !last_call;
1286
1287 return TRUE;
1288}
1289
1290/* Called in pathological case where Windows fails to send a
1291 CREATE_PROCESS_DEBUG_EVENT after an attach. */
1292DWORD
1293windows_nat_target::fake_create_process ()
1294{
1295 windows_process.handle
1296 = OpenProcess (PROCESS_ALL_ACCESS, FALSE,
1297 windows_process.current_event.dwProcessId);
1298 if (windows_process.handle != NULL)
1299 windows_process.open_process_used = 1;
1300 else
1301 {
1302 unsigned err = (unsigned) GetLastError ();
1303 throw_winerror_with_name (_("OpenProcess call failed"), err);
1304 /* We can not debug anything in that case. */
1305 }
1306 add_thread (ptid_t (windows_process.current_event.dwProcessId,
1307 windows_process.current_event.dwThreadId, 0),
1308 windows_process.current_event.u.CreateThread.hThread,
1309 windows_process.current_event.u.CreateThread.lpThreadLocalBase,
1310 true /* main_thread_p */);
1311 return windows_process.current_event.dwThreadId;
1312}
1313
1314void
1315windows_nat_target::resume (ptid_t ptid, int step, enum gdb_signal sig)
1316{
1317 windows_thread_info *th;
1318 DWORD continue_status = DBG_CONTINUE;
1319
1320 /* A specific PTID means `step only this thread id'. */
1321 int resume_all = ptid == minus_one_ptid;
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;
1327
1328 if (sig != GDB_SIGNAL_0)
1329 {
1330 if (windows_process.current_event.dwDebugEventCode
1331 != EXCEPTION_DEBUG_EVENT)
1332 {
1333 DEBUG_EXCEPT ("Cannot continue with signal %d here.", sig);
1334 }
1335 else if (sig == windows_process.last_sig)
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 {
1344 for (const xlate_exception &x : xlate)
1345 if (x.us == sig)
1346 {
1347 current_event.u.Exception.ExceptionRecord.ExceptionCode
1348 = x.them;
1349 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1350 break;
1351 }
1352 if (continue_status == DBG_CONTINUE)
1353 {
1354 DEBUG_EXCEPT ("Cannot continue with signal %d.", sig);
1355 }
1356 }
1357#endif
1358 DEBUG_EXCEPT ("Can only continue with received signal %d.",
1359 windows_process.last_sig);
1360 }
1361
1362 windows_process.last_sig = GDB_SIGNAL_0;
1363
1364 DEBUG_EXEC ("pid=%d, tid=0x%x, step=%d, sig=%d",
1365 ptid.pid (), (unsigned) ptid.lwp (), step, sig);
1366
1367 /* Get context for currently selected thread. */
1368 th = windows_process.thread_rec (inferior_ptid, DONT_INVALIDATE_CONTEXT);
1369 if (th)
1370 {
1371 windows_process.with_context (th, [&] (auto *context)
1372 {
1373 if (step)
1374 {
1375 /* Single step by setting t bit. */
1376 regcache *regcache = get_thread_regcache (inferior_thread ());
1377 struct gdbarch *gdbarch = regcache->arch ();
1378 fetch_registers (regcache, gdbarch_ps_regnum (gdbarch));
1379 context->EFlags |= FLAG_TRACE_BIT;
1380 }
1381
1382 if (context->ContextFlags)
1383 {
1384 if (th->debug_registers_changed)
1385 {
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];
1392 th->debug_registers_changed = false;
1393 }
1394 CHECK (set_thread_context (th->h, context));
1395 context->ContextFlags = 0;
1396 }
1397 });
1398 }
1399
1400 /* Allow continuing with the same signal that interrupted us.
1401 Otherwise complain. */
1402
1403 if (resume_all)
1404 windows_continue (continue_status, -1, 0);
1405 else
1406 windows_continue (continue_status, ptid.lwp (), 0);
1407}
1408
1409/* Interrupt the inferior. */
1410
1411void
1412windows_nat_target::interrupt ()
1413{
1414 DEBUG_EVENTS ("interrupt");
1415#ifdef __x86_64__
1416 if (windows_process.wow64_process)
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. */
1421 if (windows_process.wow64_dbgbreak == nullptr)
1422 {
1423 CORE_ADDR addr;
1424 if (!find_minimal_symbol_address ("ntdll!DbgUiRemoteBreakin",
1425 &addr, 0))
1426 windows_process.wow64_dbgbreak = (void *) addr;
1427 }
1428
1429 if (windows_process.wow64_dbgbreak != nullptr)
1430 {
1431 HANDLE thread = CreateRemoteThread (windows_process.handle, NULL,
1432 0, (LPTHREAD_START_ROUTINE)
1433 windows_process.wow64_dbgbreak,
1434 NULL, 0, NULL);
1435 if (thread)
1436 {
1437 CloseHandle (thread);
1438 return;
1439 }
1440 }
1441 }
1442 else
1443#endif
1444 if (DebugBreakProcess (windows_process.handle))
1445 return;
1446 warning (_("Could not interrupt program. "
1447 "Press Ctrl-c in the program console."));
1448}
1449
1450void
1451windows_nat_target::pass_ctrlc ()
1452{
1453 interrupt ();
1454}
1455
1456/* Get the next event from the child. Returns the thread ptid. */
1457
1458ptid_t
1459windows_nat_target::get_windows_debug_event
1460 (int pid, struct target_waitstatus *ourstatus, target_wait_flags options)
1461{
1462 DWORD continue_status, event_code;
1463 DWORD thread_id = 0;
1464
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. */
1468 std::optional<pending_stop> stop
1469 = windows_process.fetch_pending_stop (debug_events);
1470 if (stop.has_value ())
1471 {
1472 thread_id = stop->thread_id;
1473 *ourstatus = stop->status;
1474
1475 ptid_t ptid (windows_process.current_event.dwProcessId, thread_id);
1476 windows_thread_info *th
1477 = windows_process.thread_rec (ptid, INVALIDATE_CONTEXT);
1478 th->reload_context = true;
1479
1480 return ptid;
1481 }
1482
1483 windows_process.last_sig = GDB_SIGNAL_0;
1484 DEBUG_EVENT *current_event = &windows_process.current_event;
1485
1486 if ((options & TARGET_WNOHANG) != 0 && !m_debug_event_pending)
1487 {
1488 ourstatus->set_ignore ();
1489 return minus_one_ptid;
1490 }
1491
1492 wait_for_debug_event_main_thread (&windows_process.current_event);
1493
1494 continue_status = DBG_CONTINUE;
1495
1496 event_code = windows_process.current_event.dwDebugEventCode;
1497 ourstatus->set_spurious ();
1498
1499 switch (event_code)
1500 {
1501 case CREATE_THREAD_DEBUG_EVENT:
1502 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1503 (unsigned) current_event->dwProcessId,
1504 (unsigned) current_event->dwThreadId,
1505 "CREATE_THREAD_DEBUG_EVENT");
1506 if (windows_process.saw_create != 1)
1507 {
1508 inferior *inf = find_inferior_pid (this, current_event->dwProcessId);
1509 if (!windows_process.saw_create && inf->attach_flag)
1510 {
1511 /* Kludge around a Windows bug where first event is a create
1512 thread event. Caused when attached process does not have
1513 a main thread. */
1514 thread_id = fake_create_process ();
1515 if (thread_id)
1516 windows_process.saw_create++;
1517 }
1518 break;
1519 }
1520 /* Record the existence of this thread. */
1521 thread_id = current_event->dwThreadId;
1522 add_thread
1523 (ptid_t (current_event->dwProcessId, current_event->dwThreadId, 0),
1524 current_event->u.CreateThread.hThread,
1525 current_event->u.CreateThread.lpThreadLocalBase,
1526 false /* main_thread_p */);
1527
1528 break;
1529
1530 case EXIT_THREAD_DEBUG_EVENT:
1531 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1532 (unsigned) current_event->dwProcessId,
1533 (unsigned) current_event->dwThreadId,
1534 "EXIT_THREAD_DEBUG_EVENT");
1535 delete_thread (ptid_t (current_event->dwProcessId,
1536 current_event->dwThreadId, 0),
1537 current_event->u.ExitThread.dwExitCode,
1538 false /* main_thread_p */);
1539 break;
1540
1541 case CREATE_PROCESS_DEBUG_EVENT:
1542 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1543 (unsigned) current_event->dwProcessId,
1544 (unsigned) current_event->dwThreadId,
1545 "CREATE_PROCESS_DEBUG_EVENT");
1546 CloseHandle (current_event->u.CreateProcessInfo.hFile);
1547 if (++windows_process.saw_create != 1)
1548 break;
1549
1550 windows_process.handle = current_event->u.CreateProcessInfo.hProcess;
1551 /* Add the main thread. */
1552 add_thread
1553 (ptid_t (current_event->dwProcessId,
1554 current_event->dwThreadId, 0),
1555 current_event->u.CreateProcessInfo.hThread,
1556 current_event->u.CreateProcessInfo.lpThreadLocalBase,
1557 true /* main_thread_p */);
1558 thread_id = current_event->dwThreadId;
1559 break;
1560
1561 case EXIT_PROCESS_DEBUG_EVENT:
1562 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1563 (unsigned) current_event->dwProcessId,
1564 (unsigned) current_event->dwThreadId,
1565 "EXIT_PROCESS_DEBUG_EVENT");
1566 if (!windows_process.windows_initialization_done)
1567 {
1568 target_terminal::ours ();
1569 target_mourn_inferior (inferior_ptid);
1570 error (_("During startup program exited with code 0x%x."),
1571 (unsigned int) current_event->u.ExitProcess.dwExitCode);
1572 }
1573 else if (windows_process.saw_create == 1)
1574 {
1575 delete_thread (ptid_t (current_event->dwProcessId,
1576 current_event->dwThreadId, 0),
1577 0, true /* main_thread_p */);
1578 DWORD exit_status = current_event->u.ExitProcess.dwExitCode;
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)
1586 ourstatus->set_exited (exit_status);
1587 else
1588 ourstatus->set_signalled (gdb_signal_from_host (exit_signal));
1589
1590 thread_id = current_event->dwThreadId;
1591 }
1592 break;
1593
1594 case LOAD_DLL_DEBUG_EVENT:
1595 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1596 (unsigned) current_event->dwProcessId,
1597 (unsigned) current_event->dwThreadId,
1598 "LOAD_DLL_DEBUG_EVENT");
1599 CloseHandle (current_event->u.LoadDll.hFile);
1600 if (windows_process.saw_create != 1
1601 || ! windows_process.windows_initialization_done)
1602 break;
1603 try
1604 {
1605 windows_process.dll_loaded_event ();
1606 }
1607 catch (const gdb_exception &ex)
1608 {
1609 exception_print (gdb_stderr, ex);
1610 }
1611 ourstatus->set_loaded ();
1612 thread_id = current_event->dwThreadId;
1613 break;
1614
1615 case UNLOAD_DLL_DEBUG_EVENT:
1616 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1617 (unsigned) current_event->dwProcessId,
1618 (unsigned) current_event->dwThreadId,
1619 "UNLOAD_DLL_DEBUG_EVENT");
1620 if (windows_process.saw_create != 1
1621 || ! windows_process.windows_initialization_done)
1622 break;
1623 try
1624 {
1625 windows_process.handle_unload_dll ();
1626 }
1627 catch (const gdb_exception &ex)
1628 {
1629 exception_print (gdb_stderr, ex);
1630 }
1631 ourstatus->set_loaded ();
1632 thread_id = current_event->dwThreadId;
1633 break;
1634
1635 case EXCEPTION_DEBUG_EVENT:
1636 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1637 (unsigned) current_event->dwProcessId,
1638 (unsigned) current_event->dwThreadId,
1639 "EXCEPTION_DEBUG_EVENT");
1640 if (windows_process.saw_create != 1)
1641 break;
1642 switch (windows_process.handle_exception (ourstatus, debug_exceptions))
1643 {
1644 case HANDLE_EXCEPTION_UNHANDLED:
1645 default:
1646 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1647 break;
1648 case HANDLE_EXCEPTION_HANDLED:
1649 thread_id = current_event->dwThreadId;
1650 break;
1651 case HANDLE_EXCEPTION_IGNORED:
1652 continue_status = DBG_CONTINUE;
1653 break;
1654 }
1655 break;
1656
1657 case OUTPUT_DEBUG_STRING_EVENT: /* Message from the kernel. */
1658 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1659 (unsigned) current_event->dwProcessId,
1660 (unsigned) current_event->dwThreadId,
1661 "OUTPUT_DEBUG_STRING_EVENT");
1662 if (windows_process.saw_create != 1)
1663 break;
1664 thread_id = windows_process.handle_output_debug_string (ourstatus);
1665 break;
1666
1667 default:
1668 if (windows_process.saw_create != 1)
1669 break;
1670 gdb_printf ("gdb: kernel event for pid=%u tid=0x%x\n",
1671 (unsigned) current_event->dwProcessId,
1672 (unsigned) current_event->dwThreadId);
1673 gdb_printf (" unknown event code %u\n",
1674 (unsigned) current_event->dwDebugEventCode);
1675 break;
1676 }
1677
1678 if (!thread_id || windows_process.saw_create != 1)
1679 {
1680 CHECK (windows_continue (continue_status,
1681 windows_process.desired_stop_thread_id, 0));
1682 }
1683 else if (windows_process.desired_stop_thread_id != -1
1684 && windows_process.desired_stop_thread_id != thread_id)
1685 {
1686 /* Pending stop. See the comment by the definition of
1687 "pending_stops" for details on why this is needed. */
1688 DEBUG_EVENTS ("get_windows_debug_event - "
1689 "unexpected stop in 0x%x (expecting 0x%x)",
1690 thread_id, windows_process.desired_stop_thread_id);
1691
1692 if (current_event->dwDebugEventCode == EXCEPTION_DEBUG_EVENT
1693 && ((current_event->u.Exception.ExceptionRecord.ExceptionCode
1694 == EXCEPTION_BREAKPOINT)
1695 || (current_event->u.Exception.ExceptionRecord.ExceptionCode
1696 == STATUS_WX86_BREAKPOINT))
1697 && windows_process.windows_initialization_done)
1698 {
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);
1702 th->stopped_at_software_breakpoint = true;
1703 th->pc_adjusted = false;
1704 }
1705 windows_process.pending_stops.push_back
1706 ({thread_id, *ourstatus, windows_process.current_event});
1707 thread_id = 0;
1708 CHECK (windows_continue (continue_status,
1709 windows_process.desired_stop_thread_id, 0));
1710 }
1711
1712 if (thread_id == 0)
1713 return null_ptid;
1714 return ptid_t (windows_process.current_event.dwProcessId, thread_id, 0);
1715}
1716
1717/* Wait for interesting events to occur in the target process. */
1718ptid_t
1719windows_nat_target::wait (ptid_t ptid, struct target_waitstatus *ourstatus,
1720 target_wait_flags options)
1721{
1722 int pid = -1;
1723
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,
1726 which needs a current_thread->h. But some of these exceptions mark
1727 the birth or death of threads, which mean that the current thread
1728 isn't necessarily what you think it is. */
1729
1730 while (1)
1731 {
1732 ptid_t result = get_windows_debug_event (pid, ourstatus, options);
1733
1734 if (result != null_ptid)
1735 {
1736 if (ourstatus->kind () != TARGET_WAITKIND_EXITED
1737 && ourstatus->kind () != TARGET_WAITKIND_SIGNALLED)
1738 {
1739 windows_thread_info *th
1740 = windows_process.thread_rec (result, INVALIDATE_CONTEXT);
1741
1742 if (th != nullptr)
1743 {
1744 th->stopped_at_software_breakpoint = false;
1745 if (windows_process.current_event.dwDebugEventCode
1746 == EXCEPTION_DEBUG_EVENT
1747 && ((windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
1748 == EXCEPTION_BREAKPOINT)
1749 || (windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
1750 == STATUS_WX86_BREAKPOINT))
1751 && windows_process.windows_initialization_done)
1752 {
1753 th->stopped_at_software_breakpoint = true;
1754 th->pc_adjusted = false;
1755 }
1756 }
1757 }
1758
1759 return result;
1760 }
1761 else
1762 {
1763 int detach = 0;
1764
1765 if (deprecated_ui_loop_hook != NULL)
1766 detach = deprecated_ui_loop_hook (0);
1767
1768 if (detach)
1769 kill ();
1770 }
1771 }
1772}
1773
1774void
1775windows_nat_target::do_initial_windows_stuff (DWORD pid, bool attaching)
1776{
1777 int i;
1778 struct inferior *inf;
1779
1780 windows_process.last_sig = GDB_SIGNAL_0;
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;
1786#ifdef __CYGWIN__
1787 windows_process.cygwin_load_start = 0;
1788 windows_process.cygwin_load_end = 0;
1789#endif
1790 windows_process.current_event.dwProcessId = pid;
1791 memset (&windows_process.current_event, 0,
1792 sizeof (windows_process.current_event));
1793 inf = current_inferior ();
1794 if (!inf->target_is_pushed (this))
1795 inf->push_target (this);
1796 windows_clear_solib ();
1797 clear_proceed_status (0);
1798 init_wait_for_inferior ();
1799
1800#ifdef __x86_64__
1801 windows_process.ignore_first_breakpoint
1802 = !attaching && windows_process.wow64_process;
1803
1804 if (!windows_process.wow64_process)
1805 {
1806 windows_process.mappings = amd64_mappings;
1807 windows_process.segment_register_p = amd64_windows_segment_register_p;
1808 }
1809 else
1810#endif
1811 {
1812 windows_process.mappings = i386_mappings;
1813 windows_process.segment_register_p = i386_windows_segment_register_p;
1814 }
1815
1816 inferior_appeared (inf, pid);
1817 inf->attach_flag = attaching;
1818
1819 target_terminal::init ();
1820 target_terminal::inferior ();
1821
1822 windows_process.windows_initialization_done = 0;
1823
1824 ptid_t last_ptid;
1825
1826 while (1)
1827 {
1828 struct target_waitstatus status;
1829
1830 last_ptid = this->wait (minus_one_ptid, &status, 0);
1831
1832 /* Note windows_wait returns TARGET_WAITKIND_SPURIOUS for thread
1833 events. */
1834 if (status.kind () != TARGET_WAITKIND_LOADED
1835 && status.kind () != TARGET_WAITKIND_SPURIOUS)
1836 break;
1837
1838 this->resume (minus_one_ptid, 0, GDB_SIGNAL_0);
1839 }
1840
1841 switch_to_thread (this->find_thread (last_ptid));
1842
1843 /* Now that the inferior has been started and all DLLs have been mapped,
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. */
1858 windows_process.add_all_dlls ();
1859
1860 windows_process.windows_initialization_done = 1;
1861 return;
1862}
1863
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
1869 available on NT/2K/XP. */
1870static int
1871set_process_privilege (const char *privilege, BOOL enable)
1872{
1873 HANDLE token_hdl = NULL;
1874 LUID restore_priv;
1875 TOKEN_PRIVILEGES new_priv, orig_priv;
1876 int ret = -1;
1877 DWORD size;
1878
1879 if (!OpenProcessToken (GetCurrentProcess (),
1880 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
1881 &token_hdl))
1882 goto out;
1883
1884 if (!LookupPrivilegeValueA (NULL, privilege, &restore_priv))
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,
1892 sizeof orig_priv, &orig_priv, &size))
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
1897 windows_attach(). */
1898 /* AdjustTokenPrivileges returns TRUE even if the privilege could not
1899 be enabled. GetLastError () returns an correct error code, though. */
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
1913/* Attach to process PID, then initialize for debugging it. */
1914
1915void
1916windows_nat_target::attach (const char *args, int from_tty)
1917{
1918 DWORD pid;
1919
1920 pid = parse_pid_to_attach (args);
1921
1922 if (set_process_privilege (SE_DEBUG_NAME, TRUE) < 0)
1923 warning ("Failed to get SE_DEBUG_NAME privilege\n"
1924 "This can cause attach to fail on Windows NT/2K/XP");
1925
1926 windows_init_thread_list ();
1927 windows_process.saw_create = 0;
1928
1929 std::optional<unsigned> err;
1930 do_synchronously ([&] ()
1931 {
1932 BOOL ok = DebugActiveProcess (pid);
1933
1934#ifdef __CYGWIN__
1935 if (!ok)
1936 {
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);
1940
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 }
1951 }
1952#endif
1953
1954 if (!ok)
1955 err = (unsigned) GetLastError ();
1956
1957 return ok;
1958 });
1959
1960 if (err.has_value ())
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 }
1966
1967 DebugSetProcessKillOnExit (FALSE);
1968
1969 target_announce_attach (from_tty, pid);
1970
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))
1977 windows_process.wow64_process = wow64;
1978 CloseHandle (h);
1979 }
1980#endif
1981
1982 do_initial_windows_stuff (pid, 1);
1983 target_terminal::ours ();
1984}
1985
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
2091void
2092windows_nat_target::detach (inferior *inf, int from_tty)
2093{
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
2108 windows_continue (DBG_CONTINUE, -1, 0, true);
2109
2110 std::optional<unsigned> err;
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 });
2120
2121 if (err.has_value ())
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 }
2128
2129 target_announce_detach (from_tty);
2130
2131 x86_cleanup_dregs ();
2132 switch_to_no_thread ();
2133 detach_inferior (inf);
2134
2135 maybe_unpush_target ();
2136}
2137
2138/* The pid_to_exec_file target_ops method for this platform. */
2139
2140const char *
2141windows_nat_target::pid_to_exec_file (int pid)
2142{
2143 return windows_process.pid_to_exec_file (pid);
2144}
2145
2146/* Print status information about what we're accessing. */
2147
2148void
2149windows_nat_target::files_info ()
2150{
2151 struct inferior *inf = current_inferior ();
2152
2153 gdb_printf ("\tUsing the running image of %s %s.\n",
2154 inf->attach_flag ? "attached" : "child",
2155 target_pid_to_str (ptid_t (inf->pid)).c_str ());
2156}
2157
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
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
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)
2230 *equalpos = L'\0';
2231 SetEnvironmentVariableW (copy, NULL);
2232 }
2233 xfree (copy);
2234}
2235#endif
2236
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++;
2326 [[fallthrough]];
2327 case '<':
2328 fd = inp;
2329 mode = O_RDONLY;
2330 break;
2331 case '1': case '2':
2332 fname++;
2333 [[fallthrough]];
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
2532/* Start an inferior windows child process and sets inferior_ptid to its pid.
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
2537void
2538windows_nat_target::create_inferior (const char *exec_file,
2539 const std::string &origallargs,
2540 char **in_env, int from_tty)
2541{
2542 STARTUPINFO si;
2543#ifdef __CYGWIN__
2544 wchar_t real_path[__PMAX];
2545 wchar_t shell[__PMAX]; /* Path to shell */
2546 wchar_t infcwd[__PMAX];
2547 const char *sh;
2548 wchar_t *toexec;
2549 wchar_t *cygallargs;
2550 wchar_t *args;
2551 char **old_env = NULL;
2552 PWCHAR w32_env;
2553 size_t len;
2554 int tty;
2555 int ostdin, ostdout, ostderr;
2556#else /* !__CYGWIN__ */
2557 char shell[__PMAX]; /* Path to shell */
2558 const char *toexec;
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;
2563 bool redirected = false;
2564 char *w32env;
2565 char *temp;
2566 size_t envlen;
2567 int i;
2568 size_t envsize;
2569 char **env;
2570#endif /* !__CYGWIN__ */
2571 const char *allargs = origallargs.c_str ();
2572 PROCESS_INFORMATION pi;
2573 std::optional<unsigned> ret;
2574 DWORD flags = 0;
2575 const std::string &inferior_tty = current_inferior ()->tty ();
2576
2577 if (!exec_file)
2578 error (_("No executable specified, use `target exec'."));
2579
2580 const char *inferior_cwd = current_inferior ()->cwd ().c_str ();
2581 std::string expanded_infcwd;
2582 if (*inferior_cwd == '\0')
2583 inferior_cwd = nullptr;
2584 else
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
2593 memset (&si, 0, sizeof (si));
2594 si.cb = sizeof (si);
2595
2596 if (new_group)
2597 flags |= CREATE_NEW_PROCESS_GROUP;
2598
2599 if (new_console)
2600 windows_set_console_info (&si, &flags);
2601
2602#ifdef __CYGWIN__
2603 if (!useshell)
2604 {
2605 flags |= DEBUG_ONLY_THIS_PROCESS;
2606 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, exec_file, real_path,
2607 __PMAX * sizeof (wchar_t)) < 0)
2608 error (_("Error starting executable: %d"), errno);
2609 toexec = real_path;
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);
2615 }
2616 else
2617 {
2618 sh = get_shell ();
2619 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, sh, shell, __PMAX) < 0)
2620 error (_("Error starting executable via shell: %d"), errno);
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);
2625 toexec = shell;
2626 flags |= DEBUG_PROCESS;
2627 }
2628
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
2634 args = (wchar_t *) alloca ((wcslen (toexec) + wcslen (cygallargs) + 2)
2635 * sizeof (wchar_t));
2636 wcscpy (args, toexec);
2637 wcscat (args, L" ");
2638 wcscat (args, cygallargs);
2639
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. */
2647#endif /* CW_CVT_ENV_TO_WINENV */
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 }
2657
2658 if (inferior_tty.empty ())
2659 tty = ostdin = ostdout = ostderr = -1;
2660 else
2661 {
2662 tty = open (inferior_tty.c_str (), O_RDWR | O_NOCTTY);
2663 if (tty < 0)
2664 {
2665 warning_filename_and_errno (inferior_tty.c_str (), errno);
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 }
2678
2679 windows_init_thread_list ();
2680 do_synchronously ([&] ()
2681 {
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)
2688 ret = (unsigned) GetLastError ();
2689
2690 return ok;
2691 });
2692
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
2705 if (tty >= 0)
2706 {
2707 ::close (tty);
2708 dup2 (ostdin, 0);
2709 dup2 (ostdout, 1);
2710 dup2 (ostderr, 2);
2711 ::close (ostdin);
2712 ::close (ostdout);
2713 ::close (ostderr);
2714 }
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)
2726 warning (_("Error in redirection: %s."), safe_strerror (errno));
2727 else
2728 errno = e;
2729 allargs_len = strlen (allargs_copy);
2730 }
2731 /* If not all the standard streams are redirected by the command
2732 line, use INFERIOR_TTY for those which aren't. */
2733 if (!inferior_tty.empty ()
2734 && !(fd_inp >= 0 && fd_out >= 0 && fd_err >= 0))
2735 {
2736 SECURITY_ATTRIBUTES sa;
2737 sa.nLength = sizeof(sa);
2738 sa.lpSecurityDescriptor = 0;
2739 sa.bInheritHandle = TRUE;
2740 tty = CreateFileA (inferior_tty.c_str (), GENERIC_READ | GENERIC_WRITE,
2741 0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
2742 if (tty == INVALID_HANDLE_VALUE)
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 }
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;
2755 else
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;
2770 }
2771
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
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
2796 w32env = (char *) alloca (envlen + 1);
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
2808 windows_init_thread_list ();
2809 do_synchronously ([&] ()
2810 {
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)
2820 ret = (unsigned) GetLastError ();
2821
2822 return ok;
2823 });
2824 if (tty != INVALID_HANDLE_VALUE)
2825 CloseHandle (tty);
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__ */
2833
2834 if (ret.has_value ())
2835 {
2836 std::string msg = _("Error creating process ") + std::string (exec_file);
2837 throw_winerror_with_name (msg.c_str (), *ret);
2838 }
2839
2840#ifdef __x86_64__
2841 BOOL wow64;
2842 if (IsWow64Process (pi.hProcess, &wow64))
2843 windows_process.wow64_process = wow64;
2844#endif
2845
2846 CloseHandle (pi.hThread);
2847 CloseHandle (pi.hProcess);
2848
2849 if (useshell && shell[0] != '\0')
2850 windows_process.saw_create = -1;
2851 else
2852 windows_process.saw_create = 0;
2853
2854 do_initial_windows_stuff (pi.dwProcessId, 0);
2855
2856 /* windows_continue (DBG_CONTINUE, -1, 0); */
2857}
2858
2859void
2860windows_nat_target::mourn_inferior ()
2861{
2862 (void) windows_continue (DBG_CONTINUE, -1, 0, true);
2863 x86_cleanup_dregs();
2864 if (windows_process.open_process_used)
2865 {
2866 CHECK (CloseHandle (windows_process.handle));
2867 windows_process.open_process_used = 0;
2868 }
2869 windows_process.siginfo_er.ExceptionCode = 0;
2870 inf_child_target::mourn_inferior ();
2871}
2872
2873/* Helper for windows_xfer_partial that handles memory transfers.
2874 Arguments are like target_xfer_partial. */
2875
2876static enum target_xfer_status
2877windows_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
2878 ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
2879{
2880 SIZE_T done = 0;
2881 BOOL success;
2882 DWORD lasterror = 0;
2883
2884 if (writebuf != NULL)
2885 {
2886 DEBUG_MEM ("write target memory, %s bytes at %s",
2887 pulongest (len), core_addr_to_string (memaddr));
2888 success = WriteProcessMemory (windows_process.handle,
2889 (LPVOID) (uintptr_t) memaddr, writebuf,
2890 len, &done);
2891 if (!success)
2892 lasterror = GetLastError ();
2893 FlushInstructionCache (windows_process.handle,
2894 (LPCVOID) (uintptr_t) memaddr, len);
2895 }
2896 else
2897 {
2898 DEBUG_MEM ("read target memory, %s bytes at %s",
2899 pulongest (len), core_addr_to_string (memaddr));
2900 success = ReadProcessMemory (windows_process.handle,
2901 (LPCVOID) (uintptr_t) memaddr, readbuf,
2902 len, &done);
2903 if (!success)
2904 lasterror = GetLastError ();
2905 }
2906 *xfered_len = (ULONGEST) done;
2907 if (!success && lasterror == ERROR_PARTIAL_COPY && done > 0)
2908 return TARGET_XFER_OK;
2909 else
2910 return success ? TARGET_XFER_OK : TARGET_XFER_E_IO;
2911}
2912
2913void
2914windows_nat_target::kill ()
2915{
2916 CHECK (TerminateProcess (windows_process.handle, 0));
2917
2918 for (;;)
2919 {
2920 if (!windows_continue (DBG_CONTINUE, -1, 1))
2921 break;
2922 wait_for_debug_event_main_thread (&windows_process.current_event);
2923 if (windows_process.current_event.dwDebugEventCode
2924 == EXIT_PROCESS_DEBUG_EVENT)
2925 break;
2926 }
2927
2928 target_mourn_inferior (inferior_ptid); /* Or just windows_mourn_inferior? */
2929}
2930
2931void
2932windows_nat_target::close ()
2933{
2934 DEBUG_EVENTS ("inferior_ptid=%d\n", inferior_ptid.pid ());
2935 async (false);
2936}
2937
2938/* Convert pid to printable format. */
2939std::string
2940windows_nat_target::pid_to_str (ptid_t ptid)
2941{
2942 if (ptid.lwp () != 0)
2943 return string_printf ("Thread %d.0x%lx", ptid.pid (), ptid.lwp ());
2944
2945 return normal_pid_to_str (ptid);
2946}
2947
2948static enum target_xfer_status
2949windows_xfer_shared_libraries (struct target_ops *ops,
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)
2954{
2955 if (writebuf)
2956 return TARGET_XFER_E_IO;
2957
2958 std::string xml = "<library-list>\n";
2959 for (windows_solib &so : windows_process.solibs)
2960 windows_xfer_shared_library (so.name.c_str (),
2961 (CORE_ADDR) (uintptr_t) so.load_addr,
2962 &so.text_offset,
2963 current_inferior ()->arch (), xml);
2964 xml += "</library-list>\n";
2965
2966 ULONGEST len_avail = xml.size ();
2967 if (offset >= len_avail)
2968 len = 0;
2969 else
2970 {
2971 if (len > len_avail - offset)
2972 len = len_avail - offset;
2973 memcpy (readbuf, xml.data () + offset, len);
2974 }
2975
2976 *xfered_len = (ULONGEST) len;
2977 return len != 0 ? TARGET_XFER_OK : TARGET_XFER_EOF;
2978}
2979
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{
2986 char *buf = (char *) &windows_process.siginfo_er;
2987 size_t bufsize = sizeof (windows_process.siginfo_er);
2988
2989#ifdef __x86_64__
2990 EXCEPTION_RECORD32 er32;
2991 if (windows_process.wow64_process)
2992 {
2993 buf = (char *) &er32;
2994 bufsize = sizeof (er32);
2995
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;
3003 int i;
3004 for (i = 0; i < EXCEPTION_MAXIMUM_PARAMETERS; i++)
3005 er32.ExceptionInformation[i]
3006 = windows_process.siginfo_er.ExceptionInformation[i];
3007 }
3008#endif
3009
3010 if (windows_process.siginfo_er.ExceptionCode == 0)
3011 return TARGET_XFER_E_IO;
3012
3013 if (readbuf == nullptr)
3014 return TARGET_XFER_E_IO;
3015
3016 if (offset > bufsize)
3017 return TARGET_XFER_E_IO;
3018
3019 if (offset + len > bufsize)
3020 len = bufsize - offset;
3021
3022 memcpy (readbuf, buf + offset, len);
3023 *xfered_len = len;
3024
3025 return TARGET_XFER_OK;
3026}
3027
3028enum target_xfer_status
3029windows_nat_target::xfer_partial (enum target_object object,
3030 const char *annex, gdb_byte *readbuf,
3031 const gdb_byte *writebuf, ULONGEST offset,
3032 ULONGEST len, ULONGEST *xfered_len)
3033{
3034 switch (object)
3035 {
3036 case TARGET_OBJECT_MEMORY:
3037 return windows_xfer_memory (readbuf, writebuf, offset, len, xfered_len);
3038
3039 case TARGET_OBJECT_LIBRARIES:
3040 return windows_xfer_shared_libraries (this, object, annex, readbuf,
3041 writebuf, offset, len, xfered_len);
3042
3043 case TARGET_OBJECT_SIGNAL_INFO:
3044 return windows_xfer_siginfo (readbuf, offset, len, xfered_len);
3045
3046 default:
3047 if (beneath () == NULL)
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 }
3054 return beneath ()->xfer_partial (object, annex,
3055 readbuf, writebuf, offset, len,
3056 xfered_len);
3057 }
3058}
3059
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
3063bool
3064windows_nat_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
3065{
3066 windows_thread_info *th;
3067
3068 th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
3069 if (th == NULL)
3070 return false;
3071
3072 if (addr != NULL)
3073 *addr = th->thread_local_base;
3074
3075 return true;
3076}
3077
3078ptid_t
3079windows_nat_target::get_ada_task_ptid (long lwp, ULONGEST thread)
3080{
3081 return ptid_t (inferior_ptid.pid (), lwp, 0);
3082}
3083
3084/* Implementation of the to_thread_name method. */
3085
3086const char *
3087windows_nat_target::thread_name (struct thread_info *thr)
3088{
3089 windows_thread_info *th
3090 = windows_process.thread_rec (thr->ptid,
3091 DONT_INVALIDATE_CONTEXT);
3092 return th->thread_name ();
3093}
3094
3095
3096INIT_GDB_FILE (windows_nat)
3097{
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;
3103
3104 /* x86_dr_low.debug_register_length field is set by
3105 calling x86_set_debug_register_length function
3106 in processor windows specific native file. */
3107
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);
3111
3112#ifdef __CYGWIN__
3113 cygwin_internal (CW_SET_DOS_FILE_WARNING, 0);
3114#endif
3115
3116 add_com ("signal-event", class_run, signal_event_command, _("\
3117Signal a crashed process with event ID, to allow its debugging.\n\
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\
3121crashed process will be supplied by the Windows JIT debugging mechanism."));
3122
3123#ifdef __CYGWIN__
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
3131 add_setshow_boolean_cmd ("cygwin-exceptions", class_support,
3132 &cygwin_exceptions, _("\
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);
3138#endif
3139
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);
3182
3183 init_w32_command_list ();
3184
3185 add_cmd ("selector", class_info, display_selectors,
3186 _("Display selectors infos."),
3187 &info_w32_cmdlist);
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\
3195Use \"%ps\" or \"%ps\" command to load executable/libraries directly."),
3196 styled_string (command_style.style (), "file"),
3197 styled_string (command_style.style (), "dll"));
3198 }
3199}
3200
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
3205 actually set up when windows_continue is called. */
3206static void
3207cygwin_set_dr (int i, CORE_ADDR addr)
3208{
3209 if (i < 0 || i > 3)
3210 internal_error (_("Invalid register %d in cygwin_set_dr.\n"), i);
3211 windows_process.dr[i] = addr;
3212
3213 for (auto &th : windows_process.thread_list)
3214 th->debug_registers_changed = true;
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
3219 will be actually set up in windows_wait. */
3220static void
3221cygwin_set_dr7 (unsigned long val)
3222{
3223 windows_process.dr[7] = (CORE_ADDR) val;
3224
3225 for (auto &th : windows_process.thread_list)
3226 th->debug_registers_changed = true;
3227}
3228
3229/* Get the value of debug register I from the inferior. */
3230
3231static CORE_ADDR
3232cygwin_get_dr (int i)
3233{
3234 return windows_process.dr[i];
3235}
3236
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. */
3240static unsigned long
3241cygwin_get_dr6 (void)
3242{
3243 return (unsigned long) windows_process.dr[6];
3244}
3245
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{
3253 return (unsigned long) windows_process.dr[7];
3254}
3255
3256/* Determine if the thread referenced by "ptid" is alive
3257 by "polling" it. If WaitForSingleObject returns WAIT_OBJECT_0
3258 it means that the thread has died. Otherwise it is assumed to be alive. */
3259
3260bool
3261windows_nat_target::thread_alive (ptid_t ptid)
3262{
3263 gdb_assert (ptid.lwp () != 0);
3264
3265 windows_thread_info *th
3266 = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
3267 return WaitForSingleObject (th->h, 0) != WAIT_OBJECT_0;
3268}
3269
3270INIT_GDB_FILE (check_for_gdb_ini)
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) +
3281 sizeof ("gdb.ini") + 1);
3282 strcpy (oldini, homedir);
3283 p = strchr (oldini, '\0');
3284 if (p > oldini && !IS_DIR_SEPARATOR (p[-1]))
3285 *p++ = '/';
3286 strcpy (p, "gdb.ini");
3287 if (access (oldini, 0) == 0)
3288 {
3289 int len = strlen (oldini);
3290 char *newini = (char *) alloca (len + 2);
3291
3292 xsnprintf (newini, len + 2, "%.*s.gdbinit",
3293 (int) (len - (sizeof ("gdb.ini") - 1)), oldini);
3294 warning (_("obsolete '%s' found. Rename to '%s'."), oldini, newini);
3295 }
3296 }
3297}