RISC-V: Don't report warnings when linking different privileged spec objects.
[binutils-gdb.git] / gdb / windows-nat.c
blob37c1f46be35cace6a2ff11616ba38d48da2f68e4
1 /* Target-vector operations for controlling windows child processes, for GDB.
3 Copyright (C) 1995-2024 Free Software Foundation, Inc.
5 Contributed by Cygnus Solutions, A Red Hat Company.
7 This file is part of GDB.
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.
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.
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/>. */
22 /* Originally by Steve Chamberlain, sac@cygnus.com */
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>
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 <unistd.h>
57 #include "exec.h"
58 #include "solist.h"
59 #include "solib.h"
60 #include "xml-support.h"
61 #include "inttypes.h"
63 #include "i386-tdep.h"
64 #include "i387-tdep.h"
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"
79 using namespace windows_nat;
81 /* Maintain a linked list of "so" information. */
82 struct windows_solib
84 LPVOID load_addr = 0;
85 CORE_ADDR text_offset = 0;
87 /* Original name. */
88 std::string original_name;
89 /* Expanded form of the name. */
90 std::string name;
93 struct windows_per_inferior : public windows_process_info
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;
102 uintptr_t dr[8] {};
104 int windows_initialization_done = 0;
106 std::vector<std::unique_ptr<windows_thread_info>> thread_list;
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
115 /* This vector maps GDB's idea of a register's number into an offset
116 in the windows exception context vector.
118 It also contains the bit mask needed to load the register in question.
120 The contents of this table can only be computed by the units
121 that provide CPU-specific support for Windows native debugging.
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. */
131 const int *mappings = nullptr;
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;
137 std::vector<windows_solib> solibs;
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__ */
146 /* The current process. */
147 static windows_per_inferior windows_process;
149 #undef STARTUPINFO
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
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
163 enum
165 FLAG_TRACE_BIT = 0x100,
167 #endif
169 #ifndef CONTEXT_EXTENDED_REGISTERS
170 /* This macro is only defined on ia32. It only makes sense on this target,
171 so define it as zero if not already defined. */
172 #define CONTEXT_EXTENDED_REGISTERS 0
173 #endif
175 #define CONTEXT_DEBUGGER_DR CONTEXT_FULL | CONTEXT_FLOATING_POINT \
176 | CONTEXT_SEGMENTS | CONTEXT_DEBUG_REGISTERS \
177 | CONTEXT_EXTENDED_REGISTERS
179 #define DR6_CLEAR_VALUE 0xffff0ff0
181 /* The string sent by cygwin when it processes a signal.
182 FIXME: This should be in a cygwin include file. */
183 #ifndef _CYGWIN_SIGNAL_STRING
184 #define _CYGWIN_SIGNAL_STRING "cYgSiGw00f"
185 #endif
187 #define CHECK(x) check (x, __FILE__,__LINE__)
188 #define DEBUG_EXEC(fmt, ...) \
189 debug_prefixed_printf_cond (debug_exec, "windows exec", fmt, ## __VA_ARGS__)
190 #define DEBUG_EVENTS(fmt, ...) \
191 debug_prefixed_printf_cond (debug_events, "windows events", fmt, \
192 ## __VA_ARGS__)
193 #define DEBUG_MEM(fmt, ...) \
194 debug_prefixed_printf_cond (debug_memory, "windows mem", fmt, \
195 ## __VA_ARGS__)
196 #define DEBUG_EXCEPT(fmt, ...) \
197 debug_prefixed_printf_cond (debug_exceptions, "windows except", fmt, \
198 ## __VA_ARGS__)
200 static void cygwin_set_dr (int i, CORE_ADDR addr);
201 static void cygwin_set_dr7 (unsigned long val);
202 static CORE_ADDR cygwin_get_dr (int i);
203 static unsigned long cygwin_get_dr6 (void);
204 static unsigned long cygwin_get_dr7 (void);
206 /* User options. */
207 static bool new_console = false;
208 #ifdef __CYGWIN__
209 static bool cygwin_exceptions = false;
210 #endif
211 static bool new_group = true;
212 static bool debug_exec = false; /* show execution */
213 static bool debug_events = false; /* show events from kernel */
214 static bool debug_memory = false; /* show target memory accesses */
215 static bool debug_exceptions = false; /* show target exceptions */
216 static bool useshell = false; /* use shell for subprocesses */
218 /* See windows_nat_target::resume to understand why this is commented
219 out. */
220 #if 0
221 /* This vector maps the target's idea of an exception (extracted
222 from the DEBUG_EVENT structure) to GDB's idea. */
224 struct xlate_exception
226 DWORD them;
227 enum gdb_signal us;
230 static const struct xlate_exception xlate[] =
232 {EXCEPTION_ACCESS_VIOLATION, GDB_SIGNAL_SEGV},
233 {STATUS_STACK_OVERFLOW, GDB_SIGNAL_SEGV},
234 {EXCEPTION_BREAKPOINT, GDB_SIGNAL_TRAP},
235 {DBG_CONTROL_C, GDB_SIGNAL_INT},
236 {EXCEPTION_SINGLE_STEP, GDB_SIGNAL_TRAP},
237 {STATUS_FLOAT_DIVIDE_BY_ZERO, GDB_SIGNAL_FPE}
240 #endif /* 0 */
242 struct windows_nat_target final : public x86_nat_target<inf_child_target>
244 windows_nat_target ();
246 void close () override;
248 void attach (const char *, int) override;
250 bool attach_no_wait () override
251 { return true; }
253 void detach (inferior *, int) override;
255 void resume (ptid_t, int , enum gdb_signal) override;
257 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
259 void fetch_registers (struct regcache *, int) override;
260 void store_registers (struct regcache *, int) override;
262 bool stopped_by_sw_breakpoint () override
264 windows_thread_info *th
265 = windows_process.thread_rec (inferior_ptid, DONT_INVALIDATE_CONTEXT);
266 return th->stopped_at_software_breakpoint;
269 bool supports_stopped_by_sw_breakpoint () override
271 return true;
274 enum target_xfer_status xfer_partial (enum target_object object,
275 const char *annex,
276 gdb_byte *readbuf,
277 const gdb_byte *writebuf,
278 ULONGEST offset, ULONGEST len,
279 ULONGEST *xfered_len) override;
281 void files_info () override;
283 void kill () override;
285 void create_inferior (const char *, const std::string &,
286 char **, int) override;
288 void mourn_inferior () override;
290 bool thread_alive (ptid_t ptid) override;
292 std::string pid_to_str (ptid_t) override;
294 void interrupt () override;
295 void pass_ctrlc () override;
297 const char *pid_to_exec_file (int pid) override;
299 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
301 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
303 const char *thread_name (struct thread_info *) override;
305 ptid_t get_windows_debug_event (int pid, struct target_waitstatus *ourstatus,
306 target_wait_flags options);
308 void do_initial_windows_stuff (DWORD pid, bool attaching);
310 bool supports_disable_randomization () override
312 return disable_randomization_available ();
315 bool can_async_p () override
317 return true;
320 bool is_async_p () override
322 return m_is_async;
325 void async (bool enable) override;
327 int async_wait_fd () override
329 return serial_event_fd (m_wait_event);
332 private:
334 windows_thread_info *add_thread (ptid_t ptid, HANDLE h, void *tlb,
335 bool main_thread_p);
336 void delete_thread (ptid_t ptid, DWORD exit_code, bool main_thread_p);
337 DWORD fake_create_process ();
339 BOOL windows_continue (DWORD continue_status, int id, int killed,
340 bool last_call = false);
342 /* Helper function to start process_thread. */
343 static DWORD WINAPI process_thread_starter (LPVOID self);
345 /* This function implements the background thread that starts
346 inferiors and waits for events. */
347 void process_thread ();
349 /* Push FUNC onto the queue of requests for process_thread, and wait
350 until it has been called. On Windows, certain debugging
351 functions can only be called by the thread that started (or
352 attached to) the inferior. These are all done in the worker
353 thread, via calls to this method. If FUNC returns true,
354 process_thread will wait for debug events when FUNC returns. */
355 void do_synchronously (gdb::function_view<bool ()> func);
357 /* This waits for a debug event, dispatching to the worker thread as
358 needed. */
359 void wait_for_debug_event_main_thread (DEBUG_EVENT *event);
361 /* Force the process_thread thread to return from WaitForDebugEvent.
362 PROCESS_ALIVE is set to false if the inferior process exits while
363 we're trying to break out the process_thread thread. This can
364 happen because this is called while all threads are running free,
365 while we're trying to detach. */
366 void break_out_process_thread (bool &process_alive);
368 /* Queue used to send requests to process_thread. This is
369 implicitly locked. */
370 std::queue<gdb::function_view<bool ()>> m_queue;
372 /* Event used to signal process_thread that an item has been
373 pushed. */
374 HANDLE m_pushed_event;
375 /* Event used by process_thread to indicate that it has processed a
376 single function call. */
377 HANDLE m_response_event;
379 /* Serial event used to communicate wait event availability to the
380 main loop. */
381 serial_event *m_wait_event;
383 /* The last debug event, when M_WAIT_EVENT has been set. */
384 DEBUG_EVENT m_last_debug_event {};
385 /* True if a debug event is pending. */
386 std::atomic<bool> m_debug_event_pending { false };
388 /* True if currently in async mode. */
389 bool m_is_async = false;
391 /* True if we last called ContinueDebugEvent and the process_thread
392 thread is now waiting for events. False if WaitForDebugEvent
393 already returned an event, and we need to ContinueDebugEvent
394 again to restart the inferior. */
395 bool m_continued = false;
398 static void
399 check (BOOL ok, const char *file, int line)
401 if (!ok)
403 unsigned err = (unsigned) GetLastError ();
404 gdb_printf ("error return %s:%d was %u: %s\n", file, line,
405 err, strwinerror (err));
409 windows_nat_target::windows_nat_target ()
410 : m_pushed_event (CreateEvent (nullptr, false, false, nullptr)),
411 m_response_event (CreateEvent (nullptr, false, false, nullptr)),
412 m_wait_event (make_serial_event ())
414 HANDLE bg_thread = CreateThread (nullptr, 64 * 1024,
415 process_thread_starter, this, 0, nullptr);
416 CloseHandle (bg_thread);
419 void
420 windows_nat_target::async (bool enable)
422 if (enable == is_async_p ())
423 return;
425 if (enable)
426 add_file_handler (async_wait_fd (),
427 [] (int, gdb_client_data)
429 inferior_event_handler (INF_REG_EVENT);
431 nullptr, "windows_nat_target");
432 else
433 delete_file_handler (async_wait_fd ());
435 m_is_async = enable;
438 /* A wrapper for WaitForSingleObject that issues a warning if
439 something unusual happens. */
440 static void
441 wait_for_single (HANDLE handle, DWORD howlong)
443 while (true)
445 DWORD r = WaitForSingleObject (handle, howlong);
446 if (r == WAIT_OBJECT_0)
447 return;
448 if (r == WAIT_FAILED)
450 unsigned err = (unsigned) GetLastError ();
451 warning ("WaitForSingleObject failed (code %u): %s",
452 err, strwinerror (err));
454 else
455 warning ("unexpected result from WaitForSingleObject: %u",
456 (unsigned) r);
460 DWORD WINAPI
461 windows_nat_target::process_thread_starter (LPVOID self)
463 ((windows_nat_target *) self)->process_thread ();
464 return 0;
467 void
468 windows_nat_target::process_thread ()
470 while (true)
472 wait_for_single (m_pushed_event, INFINITE);
474 gdb::function_view<bool ()> func = std::move (m_queue.front ());
475 m_queue.pop ();
477 bool should_wait = func ();
478 SetEvent (m_response_event);
480 if (should_wait)
482 if (!m_debug_event_pending)
484 wait_for_debug_event (&m_last_debug_event, INFINITE);
485 m_debug_event_pending = true;
487 serial_event_set (m_wait_event);
492 void
493 windows_nat_target::do_synchronously (gdb::function_view<bool ()> func)
495 m_queue.emplace (std::move (func));
496 SetEvent (m_pushed_event);
497 wait_for_single (m_response_event, INFINITE);
500 void
501 windows_nat_target::wait_for_debug_event_main_thread (DEBUG_EVENT *event)
503 do_synchronously ([&] ()
505 if (m_debug_event_pending)
507 *event = m_last_debug_event;
508 m_debug_event_pending = false;
509 serial_event_clear (m_wait_event);
511 else
512 wait_for_debug_event (event, INFINITE);
513 return false;
516 m_continued = false;
519 /* See nat/windows-nat.h. */
521 windows_thread_info *
522 windows_per_inferior::thread_rec
523 (ptid_t ptid, thread_disposition_type disposition)
525 for (auto &th : thread_list)
526 if (th->tid == ptid.lwp ())
528 if (!th->suspended)
530 switch (disposition)
532 case DONT_INVALIDATE_CONTEXT:
533 /* Nothing. */
534 break;
535 case INVALIDATE_CONTEXT:
536 if (ptid.lwp () != current_event.dwThreadId)
537 th->suspend ();
538 th->reload_context = true;
539 break;
540 case DONT_SUSPEND:
541 th->reload_context = true;
542 th->suspended = -1;
543 break;
546 return th.get ();
549 return NULL;
552 /* Add a thread to the thread list.
554 PTID is the ptid of the thread to be added.
555 H is its Windows handle.
556 TLB is its thread local base.
557 MAIN_THREAD_P should be true if the thread to be added is
558 the main thread, false otherwise. */
560 windows_thread_info *
561 windows_nat_target::add_thread (ptid_t ptid, HANDLE h, void *tlb,
562 bool main_thread_p)
564 windows_thread_info *th;
566 gdb_assert (ptid.lwp () != 0);
568 if ((th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT)))
569 return th;
571 CORE_ADDR base = (CORE_ADDR) (uintptr_t) tlb;
572 #ifdef __x86_64__
573 /* For WOW64 processes, this is actually the pointer to the 64bit TIB,
574 and the 32bit TIB is exactly 2 pages after it. */
575 if (windows_process.wow64_process)
576 base += 0x2000;
577 #endif
578 th = new windows_thread_info (ptid.lwp (), h, base);
579 windows_process.thread_list.emplace_back (th);
581 /* Add this new thread to the list of threads.
583 To be consistent with what's done on other platforms, we add
584 the main thread silently (in reality, this thread is really
585 more of a process to the user than a thread). */
586 if (main_thread_p)
587 add_thread_silent (this, ptid);
588 else
589 ::add_thread (this, ptid);
591 /* It's simplest to always set this and update the debug
592 registers. */
593 th->debug_registers_changed = true;
595 return th;
598 /* Clear out any old thread list and reinitialize it to a
599 pristine state. */
600 static void
601 windows_init_thread_list (void)
603 DEBUG_EVENTS ("called");
604 windows_process.thread_list.clear ();
607 /* Delete a thread from the list of threads.
609 PTID is the ptid of the thread to be deleted.
610 EXIT_CODE is the thread's exit code.
611 MAIN_THREAD_P should be true if the thread to be deleted is
612 the main thread, false otherwise. */
614 void
615 windows_nat_target::delete_thread (ptid_t ptid, DWORD exit_code,
616 bool main_thread_p)
618 DWORD id;
620 gdb_assert (ptid.lwp () != 0);
622 id = ptid.lwp ();
624 /* Note that no notification was printed when the main thread was
625 created, and thus, unless in verbose mode, we should be symmetrical,
626 and avoid an exit notification for the main thread here as well. */
628 bool silent = (main_thread_p && !info_verbose);
629 thread_info *to_del = this->find_thread (ptid);
630 delete_thread_with_exit_code (to_del, exit_code, silent);
632 auto iter = std::find_if (windows_process.thread_list.begin (),
633 windows_process.thread_list.end (),
634 [=] (std::unique_ptr<windows_thread_info> &th)
636 return th->tid == id;
639 if (iter != windows_process.thread_list.end ())
640 windows_process.thread_list.erase (iter);
643 /* Fetches register number R from the given windows_thread_info,
644 and supplies its value to the given regcache.
646 This function assumes that R is non-negative. A failed assertion
647 is raised if that is not true.
649 This function assumes that TH->RELOAD_CONTEXT is not set, meaning
650 that the windows_thread_info has an up-to-date context. A failed
651 assertion is raised if that assumption is violated. */
653 static void
654 windows_fetch_one_register (struct regcache *regcache,
655 windows_thread_info *th, int r)
657 gdb_assert (r >= 0);
658 gdb_assert (!th->reload_context);
660 char *context_ptr = (char *) &th->context;
661 #ifdef __x86_64__
662 if (windows_process.wow64_process)
663 context_ptr = (char *) &th->wow64_context;
664 #endif
666 char *context_offset = context_ptr + windows_process.mappings[r];
667 struct gdbarch *gdbarch = regcache->arch ();
668 i386_gdbarch_tdep *tdep = gdbarch_tdep<i386_gdbarch_tdep> (gdbarch);
670 gdb_assert (!gdbarch_read_pc_p (gdbarch));
671 gdb_assert (gdbarch_pc_regnum (gdbarch) >= 0);
672 gdb_assert (!gdbarch_write_pc_p (gdbarch));
674 /* GDB treats some registers as 32-bit, where they are in fact only
675 16 bits long. These cases must be handled specially to avoid
676 reading extraneous bits from the context. */
677 if (r == I387_FISEG_REGNUM (tdep) || windows_process.segment_register_p (r))
679 gdb_byte bytes[4] = {};
680 memcpy (bytes, context_offset, 2);
681 regcache->raw_supply (r, bytes);
683 else if (r == I387_FOP_REGNUM (tdep))
685 long l = (*((long *) context_offset) >> 16) & ((1 << 11) - 1);
686 regcache->raw_supply (r, &l);
688 else
690 if (th->stopped_at_software_breakpoint
691 && !th->pc_adjusted
692 && r == gdbarch_pc_regnum (gdbarch))
694 int size = register_size (gdbarch, r);
695 if (size == 4)
697 uint32_t value;
698 memcpy (&value, context_offset, size);
699 value -= gdbarch_decr_pc_after_break (gdbarch);
700 memcpy (context_offset, &value, size);
702 else
704 gdb_assert (size == 8);
705 uint64_t value;
706 memcpy (&value, context_offset, size);
707 value -= gdbarch_decr_pc_after_break (gdbarch);
708 memcpy (context_offset, &value, size);
710 /* Make sure we only rewrite the PC a single time. */
711 th->pc_adjusted = true;
713 regcache->raw_supply (r, context_offset);
717 void
718 windows_nat_target::fetch_registers (struct regcache *regcache, int r)
720 windows_thread_info *th
721 = windows_process.thread_rec (regcache->ptid (), INVALIDATE_CONTEXT);
723 /* Check if TH exists. Windows sometimes uses a non-existent
724 thread id in its events. */
725 if (th == NULL)
726 return;
728 if (th->reload_context)
730 #ifdef __x86_64__
731 if (windows_process.wow64_process)
733 th->wow64_context.ContextFlags = CONTEXT_DEBUGGER_DR;
734 CHECK (Wow64GetThreadContext (th->h, &th->wow64_context));
735 /* Copy dr values from that thread.
736 But only if there were not modified since last stop.
737 PR gdb/2388 */
738 if (!th->debug_registers_changed)
740 windows_process.dr[0] = th->wow64_context.Dr0;
741 windows_process.dr[1] = th->wow64_context.Dr1;
742 windows_process.dr[2] = th->wow64_context.Dr2;
743 windows_process.dr[3] = th->wow64_context.Dr3;
744 windows_process.dr[6] = th->wow64_context.Dr6;
745 windows_process.dr[7] = th->wow64_context.Dr7;
748 else
749 #endif
751 th->context.ContextFlags = CONTEXT_DEBUGGER_DR;
752 CHECK (GetThreadContext (th->h, &th->context));
753 /* Copy dr values from that thread.
754 But only if there were not modified since last stop.
755 PR gdb/2388 */
756 if (!th->debug_registers_changed)
758 windows_process.dr[0] = th->context.Dr0;
759 windows_process.dr[1] = th->context.Dr1;
760 windows_process.dr[2] = th->context.Dr2;
761 windows_process.dr[3] = th->context.Dr3;
762 windows_process.dr[6] = th->context.Dr6;
763 windows_process.dr[7] = th->context.Dr7;
766 th->reload_context = false;
769 if (r < 0)
770 for (r = 0; r < gdbarch_num_regs (regcache->arch()); r++)
771 windows_fetch_one_register (regcache, th, r);
772 else
773 windows_fetch_one_register (regcache, th, r);
776 /* Collect the register number R from the given regcache, and store
777 its value into the corresponding area of the given thread's context.
779 This function assumes that R is non-negative. A failed assertion
780 assertion is raised if that is not true. */
782 static void
783 windows_store_one_register (const struct regcache *regcache,
784 windows_thread_info *th, int r)
786 gdb_assert (r >= 0);
788 char *context_ptr = (char *) &th->context;
789 #ifdef __x86_64__
790 if (windows_process.wow64_process)
791 context_ptr = (char *) &th->wow64_context;
792 #endif
794 struct gdbarch *gdbarch = regcache->arch ();
795 i386_gdbarch_tdep *tdep = gdbarch_tdep<i386_gdbarch_tdep> (gdbarch);
797 /* GDB treats some registers as 32-bit, where they are in fact only
798 16 bits long. These cases must be handled specially to avoid
799 overwriting other registers in the context. */
800 if (r == I387_FISEG_REGNUM (tdep) || windows_process.segment_register_p (r))
802 gdb_byte bytes[4];
803 regcache->raw_collect (r, bytes);
804 memcpy (context_ptr + windows_process.mappings[r], bytes, 2);
806 else if (r == I387_FOP_REGNUM (tdep))
808 gdb_byte bytes[4];
809 regcache->raw_collect (r, bytes);
810 /* The value of FOP occupies the top two bytes in the context,
811 so write the two low-order bytes from the cache into the
812 appropriate spot. */
813 memcpy (context_ptr + windows_process.mappings[r] + 2, bytes, 2);
815 else
816 regcache->raw_collect (r, context_ptr + windows_process.mappings[r]);
819 /* Store a new register value into the context of the thread tied to
820 REGCACHE. */
822 void
823 windows_nat_target::store_registers (struct regcache *regcache, int r)
825 windows_thread_info *th
826 = windows_process.thread_rec (regcache->ptid (), INVALIDATE_CONTEXT);
828 /* Check if TH exists. Windows sometimes uses a non-existent
829 thread id in its events. */
830 if (th == NULL)
831 return;
833 if (r < 0)
834 for (r = 0; r < gdbarch_num_regs (regcache->arch ()); r++)
835 windows_store_one_register (regcache, th, r);
836 else
837 windows_store_one_register (regcache, th, r);
840 /* See nat/windows-nat.h. */
842 static windows_solib *
843 windows_make_so (const char *name, LPVOID load_addr)
845 windows_solib *so = &windows_process.solibs.emplace_back ();
846 so->load_addr = load_addr;
847 so->original_name = name;
849 #ifndef __CYGWIN__
850 char *p;
851 char buf[__PMAX];
852 char cwd[__PMAX];
853 WIN32_FIND_DATA w32_fd;
854 HANDLE h = FindFirstFile(name, &w32_fd);
856 if (h == INVALID_HANDLE_VALUE)
857 strcpy (buf, name);
858 else
860 FindClose (h);
861 strcpy (buf, name);
862 if (GetCurrentDirectory (MAX_PATH + 1, cwd))
864 p = strrchr (buf, '\\');
865 if (p)
866 p[1] = '\0';
867 SetCurrentDirectory (buf);
868 GetFullPathName (w32_fd.cFileName, MAX_PATH, buf, &p);
869 SetCurrentDirectory (cwd);
872 if (strcasecmp (buf, "ntdll.dll") == 0)
874 GetSystemDirectory (buf, sizeof (buf));
875 strcat (buf, "\\ntdll.dll");
878 so->name = buf;
879 #else
880 wchar_t buf[__PMAX];
882 buf[0] = 0;
883 if (access (name, F_OK) != 0)
885 if (strcasecmp (name, "ntdll.dll") == 0)
887 GetSystemDirectoryW (buf, sizeof (buf) / sizeof (wchar_t));
888 wcscat (buf, L"\\ntdll.dll");
891 if (buf[0])
893 bool ok = false;
895 /* Check how big the output buffer has to be. */
896 ssize_t size = cygwin_conv_path (CCP_WIN_W_TO_POSIX, buf, nullptr, 0);
897 if (size > 0)
899 /* SIZE includes the null terminator. */
900 so->name.resize (size - 1);
901 if (cygwin_conv_path (CCP_WIN_W_TO_POSIX, buf, so->name.data (),
902 size) == 0)
903 ok = true;
905 if (!ok)
906 so->name = so->original_name;
908 else
910 gdb::unique_xmalloc_ptr<char> rname = gdb_realpath (name);
911 if (rname != nullptr)
912 so->name = rname.get ();
913 else
915 warning (_("dll path for \"%s\" inaccessible"), name);
916 so->name = so->original_name;
919 /* Record cygwin1.dll .text start/end. */
920 size_t len = sizeof ("/cygwin1.dll") - 1;
921 if (so->name.size () >= len
922 && strcasecmp (so->name.c_str () + so->name.size () - len,
923 "/cygwin1.dll") == 0)
925 asection *text = NULL;
927 gdb_bfd_ref_ptr abfd (gdb_bfd_open (so->name.c_str(), "pei-i386"));
929 if (abfd == NULL)
930 return so;
932 if (bfd_check_format (abfd.get (), bfd_object))
933 text = bfd_get_section_by_name (abfd.get (), ".text");
935 if (!text)
936 return so;
938 /* The symbols in a dll are offset by 0x1000, which is the
939 offset from 0 of the first byte in an image - because of the
940 file header and the section alignment. */
941 windows_process.cygwin_load_start = (CORE_ADDR) (uintptr_t) ((char *)
942 load_addr + 0x1000);
943 windows_process.cygwin_load_end = windows_process.cygwin_load_start +
944 bfd_section_size (text);
946 #endif
948 return so;
951 /* See nat/windows-nat.h. */
953 void
954 windows_per_inferior::handle_load_dll (const char *dll_name, LPVOID base)
956 windows_solib *solib = windows_make_so (dll_name, base);
957 DEBUG_EVENTS ("Loading dll \"%s\" at %s.", solib->name.c_str (),
958 host_address_to_string (solib->load_addr));
961 /* See nat/windows-nat.h. */
963 void
964 windows_per_inferior::handle_unload_dll ()
966 LPVOID lpBaseOfDll = current_event.u.UnloadDll.lpBaseOfDll;
968 auto iter = std::remove_if (windows_process.solibs.begin (),
969 windows_process.solibs.end (),
970 [&] (windows_solib &lib)
972 if (lib.load_addr == lpBaseOfDll)
974 DEBUG_EVENTS ("Unloading dll \"%s\".", lib.name.c_str ());
975 return true;
977 return false;
980 if (iter != windows_process.solibs.end ())
982 windows_process.solibs.erase (iter, windows_process.solibs.end ());
983 return;
986 /* We did not find any DLL that was previously loaded at this address,
987 so register a complaint. We do not report an error, because we have
988 observed that this may be happening under some circumstances. For
989 instance, running 32bit applications on x64 Windows causes us to receive
990 4 mysterious UNLOAD_DLL_DEBUG_EVENTs during the startup phase (these
991 events are apparently caused by the WOW layer, the interface between
992 32bit and 64bit worlds). */
993 complaint (_("dll starting at %s not found."),
994 host_address_to_string (lpBaseOfDll));
997 /* Clear list of loaded DLLs. */
998 static void
999 windows_clear_solib (void)
1001 windows_process.solibs.clear ();
1004 static void
1005 signal_event_command (const char *args, int from_tty)
1007 uintptr_t event_id = 0;
1008 char *endargs = NULL;
1010 if (args == NULL)
1011 error (_("signal-event requires an argument (integer event id)"));
1013 event_id = strtoumax (args, &endargs, 10);
1015 if ((errno == ERANGE) || (event_id == 0) || (event_id > UINTPTR_MAX) ||
1016 ((HANDLE) event_id == INVALID_HANDLE_VALUE))
1017 error (_("Failed to convert `%s' to event id"), args);
1019 SetEvent ((HANDLE) event_id);
1020 CloseHandle ((HANDLE) event_id);
1023 /* See nat/windows-nat.h. */
1026 windows_per_inferior::handle_output_debug_string
1027 (struct target_waitstatus *ourstatus)
1029 int retval = 0;
1031 gdb::unique_xmalloc_ptr<char> s
1032 = (target_read_string
1033 ((CORE_ADDR) (uintptr_t) current_event.u.DebugString.lpDebugStringData,
1034 1024));
1035 if (s == nullptr || !*(s.get ()))
1036 /* nothing to do */;
1037 else if (!startswith (s.get (), _CYGWIN_SIGNAL_STRING))
1039 #ifdef __CYGWIN__
1040 if (!startswith (s.get (), "cYg"))
1041 #endif
1043 char *p = strchr (s.get (), '\0');
1045 if (p > s.get () && *--p == '\n')
1046 *p = '\0';
1047 warning (("%s"), s.get ());
1050 #ifdef __CYGWIN__
1051 else
1053 /* Got a cygwin signal marker. A cygwin signal marker is
1054 followed by the signal number itself, and (since Cygwin 1.7)
1055 the thread id, and the address of a saved context in the
1056 inferior (That context has an IP which is the return address
1057 in "user" code of the cygwin internal signal handling code,
1058 but is not otherwise usable).
1060 Tell gdb to treat this like the given thread issued a real
1061 signal. */
1062 char *p;
1063 int sig = strtol (s.get () + sizeof (_CYGWIN_SIGNAL_STRING) - 1, &p, 0);
1064 gdb_signal gotasig = gdb_signal_from_host (sig);
1065 LPCVOID x = 0;
1067 if (gotasig)
1069 ourstatus->set_stopped (gotasig);
1070 retval = strtoul (p, &p, 0);
1071 if (!retval)
1072 retval = current_event.dwThreadId;
1073 else
1074 x = (LPCVOID) (uintptr_t) strtoull (p, NULL, 0);
1077 DEBUG_EVENTS ("gdb: cygwin signal %d, thread 0x%x, CONTEXT @ %p",
1078 gotasig, retval, x);
1080 #endif
1082 return retval;
1085 static int
1086 display_selector (HANDLE thread, DWORD sel)
1088 LDT_ENTRY info;
1089 BOOL ret;
1090 #ifdef __x86_64__
1091 if (windows_process.wow64_process)
1092 ret = Wow64GetThreadSelectorEntry (thread, sel, &info);
1093 else
1094 #endif
1095 ret = GetThreadSelectorEntry (thread, sel, &info);
1096 if (ret)
1098 int base, limit;
1099 gdb_printf ("0x%03x: ", (unsigned) sel);
1100 if (!info.HighWord.Bits.Pres)
1102 gdb_puts ("Segment not present\n");
1103 return 0;
1105 base = (info.HighWord.Bits.BaseHi << 24) +
1106 (info.HighWord.Bits.BaseMid << 16)
1107 + info.BaseLow;
1108 limit = (info.HighWord.Bits.LimitHi << 16) + info.LimitLow;
1109 if (info.HighWord.Bits.Granularity)
1110 limit = (limit << 12) | 0xfff;
1111 gdb_printf ("base=0x%08x limit=0x%08x", base, limit);
1112 if (info.HighWord.Bits.Default_Big)
1113 gdb_puts(" 32-bit ");
1114 else
1115 gdb_puts(" 16-bit ");
1116 switch ((info.HighWord.Bits.Type & 0xf) >> 1)
1118 case 0:
1119 gdb_puts ("Data (Read-Only, Exp-up");
1120 break;
1121 case 1:
1122 gdb_puts ("Data (Read/Write, Exp-up");
1123 break;
1124 case 2:
1125 gdb_puts ("Unused segment (");
1126 break;
1127 case 3:
1128 gdb_puts ("Data (Read/Write, Exp-down");
1129 break;
1130 case 4:
1131 gdb_puts ("Code (Exec-Only, N.Conf");
1132 break;
1133 case 5:
1134 gdb_puts ("Code (Exec/Read, N.Conf");
1135 break;
1136 case 6:
1137 gdb_puts ("Code (Exec-Only, Conf");
1138 break;
1139 case 7:
1140 gdb_puts ("Code (Exec/Read, Conf");
1141 break;
1142 default:
1143 gdb_printf ("Unknown type 0x%lx",
1144 (unsigned long) info.HighWord.Bits.Type);
1146 if ((info.HighWord.Bits.Type & 0x1) == 0)
1147 gdb_puts(", N.Acc");
1148 gdb_puts (")\n");
1149 if ((info.HighWord.Bits.Type & 0x10) == 0)
1150 gdb_puts("System selector ");
1151 gdb_printf ("Privilege level = %ld. ",
1152 (unsigned long) info.HighWord.Bits.Dpl);
1153 if (info.HighWord.Bits.Granularity)
1154 gdb_puts ("Page granular.\n");
1155 else
1156 gdb_puts ("Byte granular.\n");
1157 return 1;
1159 else
1161 DWORD err = GetLastError ();
1162 if (err == ERROR_NOT_SUPPORTED)
1163 gdb_printf ("Function not supported\n");
1164 else
1165 gdb_printf ("Invalid selector 0x%x.\n", (unsigned) sel);
1166 return 0;
1170 static void
1171 display_selectors (const char * args, int from_tty)
1173 if (inferior_ptid == null_ptid)
1175 gdb_puts ("Impossible to display selectors now.\n");
1176 return;
1179 windows_thread_info *current_windows_thread
1180 = windows_process.thread_rec (inferior_ptid, DONT_INVALIDATE_CONTEXT);
1182 if (!args)
1184 #ifdef __x86_64__
1185 if (windows_process.wow64_process)
1187 gdb_puts ("Selector $cs\n");
1188 display_selector (current_windows_thread->h,
1189 current_windows_thread->wow64_context.SegCs);
1190 gdb_puts ("Selector $ds\n");
1191 display_selector (current_windows_thread->h,
1192 current_windows_thread->wow64_context.SegDs);
1193 gdb_puts ("Selector $es\n");
1194 display_selector (current_windows_thread->h,
1195 current_windows_thread->wow64_context.SegEs);
1196 gdb_puts ("Selector $ss\n");
1197 display_selector (current_windows_thread->h,
1198 current_windows_thread->wow64_context.SegSs);
1199 gdb_puts ("Selector $fs\n");
1200 display_selector (current_windows_thread->h,
1201 current_windows_thread->wow64_context.SegFs);
1202 gdb_puts ("Selector $gs\n");
1203 display_selector (current_windows_thread->h,
1204 current_windows_thread->wow64_context.SegGs);
1206 else
1207 #endif
1209 gdb_puts ("Selector $cs\n");
1210 display_selector (current_windows_thread->h,
1211 current_windows_thread->context.SegCs);
1212 gdb_puts ("Selector $ds\n");
1213 display_selector (current_windows_thread->h,
1214 current_windows_thread->context.SegDs);
1215 gdb_puts ("Selector $es\n");
1216 display_selector (current_windows_thread->h,
1217 current_windows_thread->context.SegEs);
1218 gdb_puts ("Selector $ss\n");
1219 display_selector (current_windows_thread->h,
1220 current_windows_thread->context.SegSs);
1221 gdb_puts ("Selector $fs\n");
1222 display_selector (current_windows_thread->h,
1223 current_windows_thread->context.SegFs);
1224 gdb_puts ("Selector $gs\n");
1225 display_selector (current_windows_thread->h,
1226 current_windows_thread->context.SegGs);
1229 else
1231 int sel;
1232 sel = parse_and_eval_long (args);
1233 gdb_printf ("Selector \"%s\"\n",args);
1234 display_selector (current_windows_thread->h, sel);
1238 /* See nat/windows-nat.h. */
1240 bool
1241 windows_per_inferior::handle_access_violation
1242 (const EXCEPTION_RECORD *rec)
1244 #ifdef __CYGWIN__
1245 /* See if the access violation happened within the cygwin DLL
1246 itself. Cygwin uses a kind of exception handling to deal with
1247 passed-in invalid addresses. gdb should not treat these as real
1248 SEGVs since they will be silently handled by cygwin. A real SEGV
1249 will (theoretically) be caught by cygwin later in the process and
1250 will be sent as a cygwin-specific-signal. So, ignore SEGVs if
1251 they show up within the text segment of the DLL itself. */
1252 const char *fn;
1253 CORE_ADDR addr = (CORE_ADDR) (uintptr_t) rec->ExceptionAddress;
1255 if ((!cygwin_exceptions && (addr >= cygwin_load_start
1256 && addr < cygwin_load_end))
1257 || (find_pc_partial_function (addr, &fn, NULL, NULL)
1258 && startswith (fn, "KERNEL32!IsBad")))
1259 return true;
1260 #endif
1261 return false;
1264 /* Resume thread specified by ID, or all artificially suspended
1265 threads, if we are continuing execution. KILLED non-zero means we
1266 have killed the inferior, so we should ignore weird errors due to
1267 threads shutting down. LAST_CALL is true if we expect this to be
1268 the last call to continue the inferior -- we are either mourning it
1269 or detaching. */
1270 BOOL
1271 windows_nat_target::windows_continue (DWORD continue_status, int id,
1272 int killed, bool last_call)
1274 windows_process.desired_stop_thread_id = id;
1276 if (windows_process.matching_pending_stop (debug_events))
1278 /* There's no need to really continue, because there's already
1279 another event pending. However, we do need to inform the
1280 event loop of this. */
1281 serial_event_set (m_wait_event);
1282 return TRUE;
1285 for (auto &th : windows_process.thread_list)
1286 if (id == -1 || id == (int) th->tid)
1288 #ifdef __x86_64__
1289 if (windows_process.wow64_process)
1291 if (th->debug_registers_changed)
1293 th->wow64_context.ContextFlags |= CONTEXT_DEBUG_REGISTERS;
1294 th->wow64_context.Dr0 = windows_process.dr[0];
1295 th->wow64_context.Dr1 = windows_process.dr[1];
1296 th->wow64_context.Dr2 = windows_process.dr[2];
1297 th->wow64_context.Dr3 = windows_process.dr[3];
1298 th->wow64_context.Dr6 = DR6_CLEAR_VALUE;
1299 th->wow64_context.Dr7 = windows_process.dr[7];
1300 th->debug_registers_changed = false;
1302 if (th->wow64_context.ContextFlags)
1304 DWORD ec = 0;
1306 if (GetExitCodeThread (th->h, &ec)
1307 && ec == STILL_ACTIVE)
1309 BOOL status = Wow64SetThreadContext (th->h,
1310 &th->wow64_context);
1312 if (!killed)
1313 CHECK (status);
1315 th->wow64_context.ContextFlags = 0;
1318 else
1319 #endif
1321 if (th->debug_registers_changed)
1323 th->context.ContextFlags |= CONTEXT_DEBUG_REGISTERS;
1324 th->context.Dr0 = windows_process.dr[0];
1325 th->context.Dr1 = windows_process.dr[1];
1326 th->context.Dr2 = windows_process.dr[2];
1327 th->context.Dr3 = windows_process.dr[3];
1328 th->context.Dr6 = DR6_CLEAR_VALUE;
1329 th->context.Dr7 = windows_process.dr[7];
1330 th->debug_registers_changed = false;
1332 if (th->context.ContextFlags)
1334 DWORD ec = 0;
1336 if (GetExitCodeThread (th->h, &ec)
1337 && ec == STILL_ACTIVE)
1339 BOOL status = SetThreadContext (th->h, &th->context);
1341 if (!killed)
1342 CHECK (status);
1344 th->context.ContextFlags = 0;
1347 th->resume ();
1349 else
1351 /* When single-stepping a specific thread, other threads must
1352 be suspended. */
1353 th->suspend ();
1356 std::optional<unsigned> err;
1357 do_synchronously ([&] ()
1359 if (!continue_last_debug_event (continue_status, debug_events))
1360 err = (unsigned) GetLastError ();
1361 /* On the last call, do not block waiting for an event that will
1362 never come. */
1363 return !last_call;
1366 if (err.has_value ())
1367 throw_winerror_with_name (_("Failed to resume program execution"
1368 " - ContinueDebugEvent failed"),
1369 *err);
1371 m_continued = !last_call;
1373 return TRUE;
1376 /* Called in pathological case where Windows fails to send a
1377 CREATE_PROCESS_DEBUG_EVENT after an attach. */
1378 DWORD
1379 windows_nat_target::fake_create_process ()
1381 windows_process.handle
1382 = OpenProcess (PROCESS_ALL_ACCESS, FALSE,
1383 windows_process.current_event.dwProcessId);
1384 if (windows_process.handle != NULL)
1385 windows_process.open_process_used = 1;
1386 else
1388 unsigned err = (unsigned) GetLastError ();
1389 throw_winerror_with_name (_("OpenProcess call failed"), err);
1390 /* We can not debug anything in that case. */
1392 add_thread (ptid_t (windows_process.current_event.dwProcessId,
1393 windows_process.current_event.dwThreadId, 0),
1394 windows_process.current_event.u.CreateThread.hThread,
1395 windows_process.current_event.u.CreateThread.lpThreadLocalBase,
1396 true /* main_thread_p */);
1397 return windows_process.current_event.dwThreadId;
1400 void
1401 windows_nat_target::resume (ptid_t ptid, int step, enum gdb_signal sig)
1403 windows_thread_info *th;
1404 DWORD continue_status = DBG_CONTINUE;
1406 /* A specific PTID means `step only this thread id'. */
1407 int resume_all = ptid == minus_one_ptid;
1409 /* If we're continuing all threads, it's the current inferior that
1410 should be handled specially. */
1411 if (resume_all)
1412 ptid = inferior_ptid;
1414 if (sig != GDB_SIGNAL_0)
1416 if (windows_process.current_event.dwDebugEventCode
1417 != EXCEPTION_DEBUG_EVENT)
1419 DEBUG_EXCEPT ("Cannot continue with signal %d here.", sig);
1421 else if (sig == windows_process.last_sig)
1422 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1423 else
1424 #if 0
1425 /* This code does not seem to work, because
1426 the kernel does probably not consider changes in the ExceptionRecord
1427 structure when passing the exception to the inferior.
1428 Note that this seems possible in the exception handler itself. */
1430 for (const xlate_exception &x : xlate)
1431 if (x.us == sig)
1433 current_event.u.Exception.ExceptionRecord.ExceptionCode
1434 = x.them;
1435 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1436 break;
1438 if (continue_status == DBG_CONTINUE)
1440 DEBUG_EXCEPT ("Cannot continue with signal %d.", sig);
1443 #endif
1444 DEBUG_EXCEPT ("Can only continue with received signal %d.",
1445 windows_process.last_sig);
1448 windows_process.last_sig = GDB_SIGNAL_0;
1450 DEBUG_EXEC ("pid=%d, tid=0x%x, step=%d, sig=%d",
1451 ptid.pid (), (unsigned) ptid.lwp (), step, sig);
1453 /* Get context for currently selected thread. */
1454 th = windows_process.thread_rec (inferior_ptid, DONT_INVALIDATE_CONTEXT);
1455 if (th)
1457 #ifdef __x86_64__
1458 if (windows_process.wow64_process)
1460 if (step)
1462 /* Single step by setting t bit. */
1463 regcache *regcache = get_thread_regcache (inferior_thread ());
1464 struct gdbarch *gdbarch = regcache->arch ();
1465 fetch_registers (regcache, gdbarch_ps_regnum (gdbarch));
1466 th->wow64_context.EFlags |= FLAG_TRACE_BIT;
1469 if (th->wow64_context.ContextFlags)
1471 if (th->debug_registers_changed)
1473 th->wow64_context.Dr0 = windows_process.dr[0];
1474 th->wow64_context.Dr1 = windows_process.dr[1];
1475 th->wow64_context.Dr2 = windows_process.dr[2];
1476 th->wow64_context.Dr3 = windows_process.dr[3];
1477 th->wow64_context.Dr6 = DR6_CLEAR_VALUE;
1478 th->wow64_context.Dr7 = windows_process.dr[7];
1479 th->debug_registers_changed = false;
1481 CHECK (Wow64SetThreadContext (th->h, &th->wow64_context));
1482 th->wow64_context.ContextFlags = 0;
1485 else
1486 #endif
1488 if (step)
1490 /* Single step by setting t bit. */
1491 regcache *regcache = get_thread_regcache (inferior_thread ());
1492 struct gdbarch *gdbarch = regcache->arch ();
1493 fetch_registers (regcache, gdbarch_ps_regnum (gdbarch));
1494 th->context.EFlags |= FLAG_TRACE_BIT;
1497 if (th->context.ContextFlags)
1499 if (th->debug_registers_changed)
1501 th->context.Dr0 = windows_process.dr[0];
1502 th->context.Dr1 = windows_process.dr[1];
1503 th->context.Dr2 = windows_process.dr[2];
1504 th->context.Dr3 = windows_process.dr[3];
1505 th->context.Dr6 = DR6_CLEAR_VALUE;
1506 th->context.Dr7 = windows_process.dr[7];
1507 th->debug_registers_changed = false;
1509 CHECK (SetThreadContext (th->h, &th->context));
1510 th->context.ContextFlags = 0;
1515 /* Allow continuing with the same signal that interrupted us.
1516 Otherwise complain. */
1518 if (resume_all)
1519 windows_continue (continue_status, -1, 0);
1520 else
1521 windows_continue (continue_status, ptid.lwp (), 0);
1524 /* Interrupt the inferior. */
1526 void
1527 windows_nat_target::interrupt ()
1529 DEBUG_EVENTS ("interrupt");
1530 #ifdef __x86_64__
1531 if (windows_process.wow64_process)
1533 /* Call DbgUiRemoteBreakin of the 32bit ntdll.dll in the target process.
1534 DebugBreakProcess would call the one of the 64bit ntdll.dll, which
1535 can't be correctly handled by gdb. */
1536 if (windows_process.wow64_dbgbreak == nullptr)
1538 CORE_ADDR addr;
1539 if (!find_minimal_symbol_address ("ntdll!DbgUiRemoteBreakin",
1540 &addr, 0))
1541 windows_process.wow64_dbgbreak = (void *) addr;
1544 if (windows_process.wow64_dbgbreak != nullptr)
1546 HANDLE thread = CreateRemoteThread (windows_process.handle, NULL,
1547 0, (LPTHREAD_START_ROUTINE)
1548 windows_process.wow64_dbgbreak,
1549 NULL, 0, NULL);
1550 if (thread)
1552 CloseHandle (thread);
1553 return;
1557 else
1558 #endif
1559 if (DebugBreakProcess (windows_process.handle))
1560 return;
1561 warning (_("Could not interrupt program. "
1562 "Press Ctrl-c in the program console."));
1565 void
1566 windows_nat_target::pass_ctrlc ()
1568 interrupt ();
1571 /* Get the next event from the child. Returns the thread ptid. */
1573 ptid_t
1574 windows_nat_target::get_windows_debug_event
1575 (int pid, struct target_waitstatus *ourstatus, target_wait_flags options)
1577 DWORD continue_status, event_code;
1578 DWORD thread_id = 0;
1580 /* If there is a relevant pending stop, report it now. See the
1581 comment by the definition of "pending_stops" for details on why
1582 this is needed. */
1583 std::optional<pending_stop> stop
1584 = windows_process.fetch_pending_stop (debug_events);
1585 if (stop.has_value ())
1587 thread_id = stop->thread_id;
1588 *ourstatus = stop->status;
1590 ptid_t ptid (windows_process.current_event.dwProcessId, thread_id);
1591 windows_thread_info *th
1592 = windows_process.thread_rec (ptid, INVALIDATE_CONTEXT);
1593 th->reload_context = true;
1595 return ptid;
1598 windows_process.last_sig = GDB_SIGNAL_0;
1599 DEBUG_EVENT *current_event = &windows_process.current_event;
1601 if ((options & TARGET_WNOHANG) != 0 && !m_debug_event_pending)
1603 ourstatus->set_ignore ();
1604 return minus_one_ptid;
1607 wait_for_debug_event_main_thread (&windows_process.current_event);
1609 continue_status = DBG_CONTINUE;
1611 event_code = windows_process.current_event.dwDebugEventCode;
1612 ourstatus->set_spurious ();
1614 switch (event_code)
1616 case CREATE_THREAD_DEBUG_EVENT:
1617 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1618 (unsigned) current_event->dwProcessId,
1619 (unsigned) current_event->dwThreadId,
1620 "CREATE_THREAD_DEBUG_EVENT");
1621 if (windows_process.saw_create != 1)
1623 inferior *inf = find_inferior_pid (this, current_event->dwProcessId);
1624 if (!windows_process.saw_create && inf->attach_flag)
1626 /* Kludge around a Windows bug where first event is a create
1627 thread event. Caused when attached process does not have
1628 a main thread. */
1629 thread_id = fake_create_process ();
1630 if (thread_id)
1631 windows_process.saw_create++;
1633 break;
1635 /* Record the existence of this thread. */
1636 thread_id = current_event->dwThreadId;
1637 add_thread
1638 (ptid_t (current_event->dwProcessId, current_event->dwThreadId, 0),
1639 current_event->u.CreateThread.hThread,
1640 current_event->u.CreateThread.lpThreadLocalBase,
1641 false /* main_thread_p */);
1643 break;
1645 case EXIT_THREAD_DEBUG_EVENT:
1646 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1647 (unsigned) current_event->dwProcessId,
1648 (unsigned) current_event->dwThreadId,
1649 "EXIT_THREAD_DEBUG_EVENT");
1650 delete_thread (ptid_t (current_event->dwProcessId,
1651 current_event->dwThreadId, 0),
1652 current_event->u.ExitThread.dwExitCode,
1653 false /* main_thread_p */);
1654 break;
1656 case CREATE_PROCESS_DEBUG_EVENT:
1657 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1658 (unsigned) current_event->dwProcessId,
1659 (unsigned) current_event->dwThreadId,
1660 "CREATE_PROCESS_DEBUG_EVENT");
1661 CloseHandle (current_event->u.CreateProcessInfo.hFile);
1662 if (++windows_process.saw_create != 1)
1663 break;
1665 windows_process.handle = current_event->u.CreateProcessInfo.hProcess;
1666 /* Add the main thread. */
1667 add_thread
1668 (ptid_t (current_event->dwProcessId,
1669 current_event->dwThreadId, 0),
1670 current_event->u.CreateProcessInfo.hThread,
1671 current_event->u.CreateProcessInfo.lpThreadLocalBase,
1672 true /* main_thread_p */);
1673 thread_id = current_event->dwThreadId;
1674 break;
1676 case EXIT_PROCESS_DEBUG_EVENT:
1677 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1678 (unsigned) current_event->dwProcessId,
1679 (unsigned) current_event->dwThreadId,
1680 "EXIT_PROCESS_DEBUG_EVENT");
1681 if (!windows_process.windows_initialization_done)
1683 target_terminal::ours ();
1684 target_mourn_inferior (inferior_ptid);
1685 error (_("During startup program exited with code 0x%x."),
1686 (unsigned int) current_event->u.ExitProcess.dwExitCode);
1688 else if (windows_process.saw_create == 1)
1690 delete_thread (ptid_t (current_event->dwProcessId,
1691 current_event->dwThreadId, 0),
1692 0, true /* main_thread_p */);
1693 DWORD exit_status = current_event->u.ExitProcess.dwExitCode;
1694 /* If the exit status looks like a fatal exception, but we
1695 don't recognize the exception's code, make the original
1696 exit status value available, to avoid losing
1697 information. */
1698 int exit_signal
1699 = WIFSIGNALED (exit_status) ? WTERMSIG (exit_status) : -1;
1700 if (exit_signal == -1)
1701 ourstatus->set_exited (exit_status);
1702 else
1703 ourstatus->set_signalled (gdb_signal_from_host (exit_signal));
1705 thread_id = current_event->dwThreadId;
1707 break;
1709 case LOAD_DLL_DEBUG_EVENT:
1710 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1711 (unsigned) current_event->dwProcessId,
1712 (unsigned) current_event->dwThreadId,
1713 "LOAD_DLL_DEBUG_EVENT");
1714 CloseHandle (current_event->u.LoadDll.hFile);
1715 if (windows_process.saw_create != 1
1716 || ! windows_process.windows_initialization_done)
1717 break;
1720 windows_process.dll_loaded_event ();
1722 catch (const gdb_exception &ex)
1724 exception_print (gdb_stderr, ex);
1726 ourstatus->set_loaded ();
1727 thread_id = current_event->dwThreadId;
1728 break;
1730 case UNLOAD_DLL_DEBUG_EVENT:
1731 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1732 (unsigned) current_event->dwProcessId,
1733 (unsigned) current_event->dwThreadId,
1734 "UNLOAD_DLL_DEBUG_EVENT");
1735 if (windows_process.saw_create != 1
1736 || ! windows_process.windows_initialization_done)
1737 break;
1740 windows_process.handle_unload_dll ();
1742 catch (const gdb_exception &ex)
1744 exception_print (gdb_stderr, ex);
1746 ourstatus->set_loaded ();
1747 thread_id = current_event->dwThreadId;
1748 break;
1750 case EXCEPTION_DEBUG_EVENT:
1751 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1752 (unsigned) current_event->dwProcessId,
1753 (unsigned) current_event->dwThreadId,
1754 "EXCEPTION_DEBUG_EVENT");
1755 if (windows_process.saw_create != 1)
1756 break;
1757 switch (windows_process.handle_exception (ourstatus, debug_exceptions))
1759 case HANDLE_EXCEPTION_UNHANDLED:
1760 default:
1761 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1762 break;
1763 case HANDLE_EXCEPTION_HANDLED:
1764 thread_id = current_event->dwThreadId;
1765 break;
1766 case HANDLE_EXCEPTION_IGNORED:
1767 continue_status = DBG_CONTINUE;
1768 break;
1770 break;
1772 case OUTPUT_DEBUG_STRING_EVENT: /* Message from the kernel. */
1773 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1774 (unsigned) current_event->dwProcessId,
1775 (unsigned) current_event->dwThreadId,
1776 "OUTPUT_DEBUG_STRING_EVENT");
1777 if (windows_process.saw_create != 1)
1778 break;
1779 thread_id = windows_process.handle_output_debug_string (ourstatus);
1780 break;
1782 default:
1783 if (windows_process.saw_create != 1)
1784 break;
1785 gdb_printf ("gdb: kernel event for pid=%u tid=0x%x\n",
1786 (unsigned) current_event->dwProcessId,
1787 (unsigned) current_event->dwThreadId);
1788 gdb_printf (" unknown event code %u\n",
1789 (unsigned) current_event->dwDebugEventCode);
1790 break;
1793 if (!thread_id || windows_process.saw_create != 1)
1795 CHECK (windows_continue (continue_status,
1796 windows_process.desired_stop_thread_id, 0));
1798 else if (windows_process.desired_stop_thread_id != -1
1799 && windows_process.desired_stop_thread_id != thread_id)
1801 /* Pending stop. See the comment by the definition of
1802 "pending_stops" for details on why this is needed. */
1803 DEBUG_EVENTS ("get_windows_debug_event - "
1804 "unexpected stop in 0x%x (expecting 0x%x)",
1805 thread_id, windows_process.desired_stop_thread_id);
1807 if (current_event->dwDebugEventCode == EXCEPTION_DEBUG_EVENT
1808 && ((current_event->u.Exception.ExceptionRecord.ExceptionCode
1809 == EXCEPTION_BREAKPOINT)
1810 || (current_event->u.Exception.ExceptionRecord.ExceptionCode
1811 == STATUS_WX86_BREAKPOINT))
1812 && windows_process.windows_initialization_done)
1814 ptid_t ptid = ptid_t (current_event->dwProcessId, thread_id, 0);
1815 windows_thread_info *th
1816 = windows_process.thread_rec (ptid, INVALIDATE_CONTEXT);
1817 th->stopped_at_software_breakpoint = true;
1818 th->pc_adjusted = false;
1820 windows_process.pending_stops.push_back
1821 ({thread_id, *ourstatus, windows_process.current_event});
1822 thread_id = 0;
1823 CHECK (windows_continue (continue_status,
1824 windows_process.desired_stop_thread_id, 0));
1827 if (thread_id == 0)
1828 return null_ptid;
1829 return ptid_t (windows_process.current_event.dwProcessId, thread_id, 0);
1832 /* Wait for interesting events to occur in the target process. */
1833 ptid_t
1834 windows_nat_target::wait (ptid_t ptid, struct target_waitstatus *ourstatus,
1835 target_wait_flags options)
1837 int pid = -1;
1839 /* We loop when we get a non-standard exception rather than return
1840 with a SPURIOUS because resume can try and step or modify things,
1841 which needs a current_thread->h. But some of these exceptions mark
1842 the birth or death of threads, which mean that the current thread
1843 isn't necessarily what you think it is. */
1845 while (1)
1847 ptid_t result = get_windows_debug_event (pid, ourstatus, options);
1849 if (result != null_ptid)
1851 if (ourstatus->kind () != TARGET_WAITKIND_EXITED
1852 && ourstatus->kind () != TARGET_WAITKIND_SIGNALLED)
1854 windows_thread_info *th
1855 = windows_process.thread_rec (result, INVALIDATE_CONTEXT);
1857 if (th != nullptr)
1859 th->stopped_at_software_breakpoint = false;
1860 if (windows_process.current_event.dwDebugEventCode
1861 == EXCEPTION_DEBUG_EVENT
1862 && ((windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
1863 == EXCEPTION_BREAKPOINT)
1864 || (windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
1865 == STATUS_WX86_BREAKPOINT))
1866 && windows_process.windows_initialization_done)
1868 th->stopped_at_software_breakpoint = true;
1869 th->pc_adjusted = false;
1874 return result;
1876 else
1878 int detach = 0;
1880 if (deprecated_ui_loop_hook != NULL)
1881 detach = deprecated_ui_loop_hook (0);
1883 if (detach)
1884 kill ();
1889 void
1890 windows_nat_target::do_initial_windows_stuff (DWORD pid, bool attaching)
1892 int i;
1893 struct inferior *inf;
1895 windows_process.last_sig = GDB_SIGNAL_0;
1896 windows_process.open_process_used = 0;
1897 for (i = 0;
1898 i < sizeof (windows_process.dr) / sizeof (windows_process.dr[0]);
1899 i++)
1900 windows_process.dr[i] = 0;
1901 #ifdef __CYGWIN__
1902 windows_process.cygwin_load_start = 0;
1903 windows_process.cygwin_load_end = 0;
1904 #endif
1905 windows_process.current_event.dwProcessId = pid;
1906 memset (&windows_process.current_event, 0,
1907 sizeof (windows_process.current_event));
1908 inf = current_inferior ();
1909 if (!inf->target_is_pushed (this))
1910 inf->push_target (this);
1911 disable_breakpoints_in_shlibs (current_program_space);
1912 windows_clear_solib ();
1913 clear_proceed_status (0);
1914 init_wait_for_inferior ();
1916 #ifdef __x86_64__
1917 windows_process.ignore_first_breakpoint
1918 = !attaching && windows_process.wow64_process;
1920 if (!windows_process.wow64_process)
1922 windows_process.mappings = amd64_mappings;
1923 windows_process.segment_register_p = amd64_windows_segment_register_p;
1925 else
1926 #endif
1928 windows_process.mappings = i386_mappings;
1929 windows_process.segment_register_p = i386_windows_segment_register_p;
1932 inferior_appeared (inf, pid);
1933 inf->attach_flag = attaching;
1935 target_terminal::init ();
1936 target_terminal::inferior ();
1938 windows_process.windows_initialization_done = 0;
1940 ptid_t last_ptid;
1942 while (1)
1944 struct target_waitstatus status;
1946 last_ptid = this->wait (minus_one_ptid, &status, 0);
1948 /* Note windows_wait returns TARGET_WAITKIND_SPURIOUS for thread
1949 events. */
1950 if (status.kind () != TARGET_WAITKIND_LOADED
1951 && status.kind () != TARGET_WAITKIND_SPURIOUS)
1952 break;
1954 this->resume (minus_one_ptid, 0, GDB_SIGNAL_0);
1957 switch_to_thread (this->find_thread (last_ptid));
1959 /* Now that the inferior has been started and all DLLs have been mapped,
1960 we can iterate over all DLLs and load them in.
1962 We avoid doing it any earlier because, on certain versions of Windows,
1963 LOAD_DLL_DEBUG_EVENTs are sometimes not complete. In particular,
1964 we have seen on Windows 8.1 that the ntdll.dll load event does not
1965 include the DLL name, preventing us from creating an associated SO.
1966 A possible explanation is that ntdll.dll might be mapped before
1967 the SO info gets created by the Windows system -- ntdll.dll is
1968 the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs
1969 do not seem to suffer from that problem.
1971 Rather than try to work around this sort of issue, it is much
1972 simpler to just ignore DLL load/unload events during the startup
1973 phase, and then process them all in one batch now. */
1974 windows_process.add_all_dlls ();
1976 windows_process.windows_initialization_done = 1;
1977 return;
1980 /* Try to set or remove a user privilege to the current process. Return -1
1981 if that fails, the previous setting of that privilege otherwise.
1983 This code is copied from the Cygwin source code and rearranged to allow
1984 dynamically loading of the needed symbols from advapi32 which is only
1985 available on NT/2K/XP. */
1986 static int
1987 set_process_privilege (const char *privilege, BOOL enable)
1989 HANDLE token_hdl = NULL;
1990 LUID restore_priv;
1991 TOKEN_PRIVILEGES new_priv, orig_priv;
1992 int ret = -1;
1993 DWORD size;
1995 if (!OpenProcessToken (GetCurrentProcess (),
1996 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
1997 &token_hdl))
1998 goto out;
2000 if (!LookupPrivilegeValueA (NULL, privilege, &restore_priv))
2001 goto out;
2003 new_priv.PrivilegeCount = 1;
2004 new_priv.Privileges[0].Luid = restore_priv;
2005 new_priv.Privileges[0].Attributes = enable ? SE_PRIVILEGE_ENABLED : 0;
2007 if (!AdjustTokenPrivileges (token_hdl, FALSE, &new_priv,
2008 sizeof orig_priv, &orig_priv, &size))
2009 goto out;
2010 #if 0
2011 /* Disabled, otherwise every `attach' in an unprivileged user session
2012 would raise the "Failed to get SE_DEBUG_NAME privilege" warning in
2013 windows_attach(). */
2014 /* AdjustTokenPrivileges returns TRUE even if the privilege could not
2015 be enabled. GetLastError () returns an correct error code, though. */
2016 if (enable && GetLastError () == ERROR_NOT_ALL_ASSIGNED)
2017 goto out;
2018 #endif
2020 ret = orig_priv.Privileges[0].Attributes == SE_PRIVILEGE_ENABLED ? 1 : 0;
2022 out:
2023 if (token_hdl)
2024 CloseHandle (token_hdl);
2026 return ret;
2029 /* Attach to process PID, then initialize for debugging it. */
2031 void
2032 windows_nat_target::attach (const char *args, int from_tty)
2034 DWORD pid;
2036 pid = parse_pid_to_attach (args);
2038 if (set_process_privilege (SE_DEBUG_NAME, TRUE) < 0)
2039 warning ("Failed to get SE_DEBUG_NAME privilege\n"
2040 "This can cause attach to fail on Windows NT/2K/XP");
2042 windows_init_thread_list ();
2043 windows_process.saw_create = 0;
2045 std::optional<unsigned> err;
2046 do_synchronously ([&] ()
2048 BOOL ok = DebugActiveProcess (pid);
2050 #ifdef __CYGWIN__
2051 if (!ok)
2053 /* Maybe PID was a Cygwin PID. Try the corresponding native
2054 Windows PID. */
2055 DWORD winpid = cygwin_internal (CW_CYGWIN_PID_TO_WINPID, pid);
2057 if (winpid != 0)
2059 /* It was indeed a Cygwin PID. Fully switch to the
2060 Windows PID from here on. We don't do this
2061 unconditionally to avoid ending up with PID=0 in the
2062 error message below. */
2063 pid = winpid;
2065 ok = DebugActiveProcess (winpid);
2068 #endif
2070 if (!ok)
2071 err = (unsigned) GetLastError ();
2073 return ok;
2076 if (err.has_value ())
2078 std::string msg = string_printf (_("Can't attach to process %u"),
2079 (unsigned) pid);
2080 throw_winerror_with_name (msg.c_str (), *err);
2083 DebugSetProcessKillOnExit (FALSE);
2085 target_announce_attach (from_tty, pid);
2087 #ifdef __x86_64__
2088 HANDLE h = OpenProcess (PROCESS_QUERY_INFORMATION, FALSE, pid);
2089 if (h != NULL)
2091 BOOL wow64;
2092 if (IsWow64Process (h, &wow64))
2093 windows_process.wow64_process = wow64;
2094 CloseHandle (h);
2096 #endif
2098 do_initial_windows_stuff (pid, 1);
2099 target_terminal::ours ();
2102 void
2103 windows_nat_target::break_out_process_thread (bool &process_alive)
2105 /* This is called when the process_thread thread is blocked in
2106 WaitForDebugEvent (unless it already returned some event we
2107 haven't consumed yet), and we need to unblock it so that we can
2108 have it call DebugActiveProcessStop.
2110 To make WaitForDebugEvent return, we need to force some event in
2111 the inferior. Any method that lets us do that (without
2112 disturbing the other threads), injects a new thread in the
2113 inferior.
2115 We don't use DebugBreakProcess for this, because that injects a
2116 thread that ends up executing a breakpoint instruction. We can't
2117 let the injected thread hit that breakpoint _after_ we've
2118 detached. Consuming events until we see a breakpoint trap isn't
2119 100% reliable, because we can't distinguish it from some other
2120 thread itself deciding to call int3 while we're detaching, unless
2121 we temporarily suspend all threads. It's just a lot of
2122 complication, and there's an easier way.
2124 Important observation: the thread creation event for the newly
2125 injected thread is sufficient to unblock WaitForDebugEvent.
2127 Instead of DebugBreakProcess, we can instead use
2128 CreateRemoteThread to control the code that the injected thread
2129 runs ourselves. We could consider pointing the injected thread
2130 at some side-effect-free Win32 function as entry point. However,
2131 finding the address of such a function requires having at least
2132 minimal symbols loaded for ntdll.dll. Having a way that avoids
2133 that is better, so that detach always works correctly even when
2134 we don't have any symbols loaded.
2136 So what we do is inject a thread that doesn't actually run ANY
2137 userspace code, because we force-terminate it as soon as we see
2138 its corresponding thread creation event. CreateRemoteThread
2139 gives us the new thread's ID, which we can match with the thread
2140 associated with the CREATE_THREAD_DEBUG_EVENT event. */
2142 DWORD injected_thread_id = 0;
2143 HANDLE injected_thread_handle
2144 = CreateRemoteThread (windows_process.handle, NULL,
2145 0, (LPTHREAD_START_ROUTINE) 0,
2146 NULL, 0, &injected_thread_id);
2148 if (injected_thread_handle == NULL)
2150 DWORD err = GetLastError ();
2152 DEBUG_EVENTS ("CreateRemoteThread failed with %u", err);
2154 if (err == ERROR_ACCESS_DENIED)
2156 /* Creating the remote thread fails with ERROR_ACCESS_DENIED
2157 if the process exited before we had a chance to inject
2158 the thread. Continue with the loop below and consume the
2159 process exit event anyhow, so that our caller can always
2160 call windows_continue. */
2162 else
2163 throw_winerror_with_name (_("Can't detach from running process. "
2164 "Interrupt it first."),
2165 err);
2168 process_alive = true;
2170 /* At this point, the user has declared that they want to detach, so
2171 any event that happens from this point on should be forwarded to
2172 the inferior. */
2174 for (;;)
2176 DEBUG_EVENT current_event;
2177 wait_for_debug_event_main_thread (&current_event);
2179 if (current_event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
2181 DEBUG_EVENTS ("got EXIT_PROCESS_DEBUG_EVENT");
2182 process_alive = false;
2183 break;
2186 if (current_event.dwDebugEventCode == CREATE_THREAD_DEBUG_EVENT
2187 && current_event.dwThreadId == injected_thread_id)
2189 DEBUG_EVENTS ("got CREATE_THREAD_DEBUG_EVENT for injected thread");
2191 /* Terminate the injected thread, so it doesn't run any code
2192 at all. All we wanted was some event, and
2193 CREATE_THREAD_DEBUG_EVENT is sufficient. */
2194 CHECK (TerminateThread (injected_thread_handle, 0));
2195 break;
2198 DEBUG_EVENTS ("got unrelated event, code %u",
2199 current_event.dwDebugEventCode);
2200 windows_continue (DBG_CONTINUE, -1, 0);
2203 if (injected_thread_handle != NULL)
2204 CHECK (CloseHandle (injected_thread_handle));
2207 void
2208 windows_nat_target::detach (inferior *inf, int from_tty)
2210 /* If we see the process exit while unblocking the process_thread
2211 helper thread, then we should skip the actual
2212 DebugActiveProcessStop call. But don't report an error. Just
2213 pretend the process exited shortly after the detach. */
2214 bool process_alive = true;
2216 /* The process_thread helper thread will be blocked in
2217 WaitForDebugEvent waiting for events if we've resumed the target
2218 before we get here, e.g., with "attach&" or "c&". We need to
2219 unblock it so that we can have it call DebugActiveProcessStop
2220 below, in the do_synchronously block. */
2221 if (m_continued)
2222 break_out_process_thread (process_alive);
2224 windows_continue (DBG_CONTINUE, -1, 0, true);
2226 std::optional<unsigned> err;
2227 if (process_alive)
2228 do_synchronously ([&] ()
2230 if (!DebugActiveProcessStop (windows_process.current_event.dwProcessId))
2231 err = (unsigned) GetLastError ();
2232 else
2233 DebugSetProcessKillOnExit (FALSE);
2234 return false;
2237 if (err.has_value ())
2239 std::string msg
2240 = string_printf (_("Can't detach process %u"),
2241 (unsigned) windows_process.current_event.dwProcessId);
2242 throw_winerror_with_name (msg.c_str (), *err);
2245 target_announce_detach (from_tty);
2247 x86_cleanup_dregs ();
2248 switch_to_no_thread ();
2249 detach_inferior (inf);
2251 maybe_unpush_target ();
2254 /* The pid_to_exec_file target_ops method for this platform. */
2256 const char *
2257 windows_nat_target::pid_to_exec_file (int pid)
2259 return windows_process.pid_to_exec_file (pid);
2262 /* Print status information about what we're accessing. */
2264 void
2265 windows_nat_target::files_info ()
2267 struct inferior *inf = current_inferior ();
2269 gdb_printf ("\tUsing the running image of %s %s.\n",
2270 inf->attach_flag ? "attached" : "child",
2271 target_pid_to_str (ptid_t (inf->pid)).c_str ());
2274 /* Modify CreateProcess parameters for use of a new separate console.
2275 Parameters are:
2276 *FLAGS: DWORD parameter for general process creation flags.
2277 *SI: STARTUPINFO structure, for which the console window size and
2278 console buffer size is filled in if GDB is running in a console.
2279 to create the new console.
2280 The size of the used font is not available on all versions of
2281 Windows OS. Furthermore, the current font might not be the default
2282 font, but this is still better than before.
2283 If the windows and buffer sizes are computed,
2284 SI->DWFLAGS is changed so that this information is used
2285 by CreateProcess function. */
2287 static void
2288 windows_set_console_info (STARTUPINFO *si, DWORD *flags)
2290 HANDLE hconsole = CreateFile ("CONOUT$", GENERIC_READ | GENERIC_WRITE,
2291 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
2293 if (hconsole != INVALID_HANDLE_VALUE)
2295 CONSOLE_SCREEN_BUFFER_INFO sbinfo;
2296 COORD font_size;
2297 CONSOLE_FONT_INFO cfi;
2299 GetCurrentConsoleFont (hconsole, FALSE, &cfi);
2300 font_size = GetConsoleFontSize (hconsole, cfi.nFont);
2301 GetConsoleScreenBufferInfo(hconsole, &sbinfo);
2302 si->dwXSize = sbinfo.srWindow.Right - sbinfo.srWindow.Left + 1;
2303 si->dwYSize = sbinfo.srWindow.Bottom - sbinfo.srWindow.Top + 1;
2304 if (font_size.X)
2305 si->dwXSize *= font_size.X;
2306 else
2307 si->dwXSize *= 8;
2308 if (font_size.Y)
2309 si->dwYSize *= font_size.Y;
2310 else
2311 si->dwYSize *= 12;
2312 si->dwXCountChars = sbinfo.dwSize.X;
2313 si->dwYCountChars = sbinfo.dwSize.Y;
2314 si->dwFlags |= STARTF_USESIZE | STARTF_USECOUNTCHARS;
2316 *flags |= CREATE_NEW_CONSOLE;
2319 #ifndef __CYGWIN__
2320 /* Function called by qsort to sort environment strings. */
2322 static int
2323 envvar_cmp (const void *a, const void *b)
2325 const char **p = (const char **) a;
2326 const char **q = (const char **) b;
2327 return strcasecmp (*p, *q);
2329 #endif
2331 #ifdef __CYGWIN__
2332 static void
2333 clear_win32_environment (char **env)
2335 int i;
2336 size_t len;
2337 wchar_t *copy = NULL, *equalpos;
2339 for (i = 0; env[i] && *env[i]; i++)
2341 len = mbstowcs (NULL, env[i], 0) + 1;
2342 copy = (wchar_t *) xrealloc (copy, len * sizeof (wchar_t));
2343 mbstowcs (copy, env[i], len);
2344 equalpos = wcschr (copy, L'=');
2345 if (equalpos)
2346 *equalpos = L'\0';
2347 SetEnvironmentVariableW (copy, NULL);
2349 xfree (copy);
2351 #endif
2353 #ifndef __CYGWIN__
2355 /* Redirection of inferior I/O streams for native MS-Windows programs.
2356 Unlike on Unix, where this is handled by invoking the inferior via
2357 the shell, on MS-Windows we need to emulate the cmd.exe shell.
2359 The official documentation of the cmd.exe redirection features is here:
2361 http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx
2363 (That page talks about Windows XP, but there's no newer
2364 documentation, so we assume later versions of cmd.exe didn't change
2365 anything.)
2367 Caveat: the documentation on that page seems to include a few lies.
2368 For example, it describes strange constructs 1<&2 and 2<&1, which
2369 seem to work only when 1>&2 resp. 2>&1 would make sense, and so I
2370 think the cmd.exe parser of the redirection symbols simply doesn't
2371 care about the < vs > distinction in these cases. Therefore, the
2372 supported features are explicitly documented below.
2374 The emulation below aims at supporting all the valid use cases
2375 supported by cmd.exe, which include:
2377 < FILE redirect standard input from FILE
2378 0< FILE redirect standard input from FILE
2379 <&N redirect standard input from file descriptor N
2380 0<&N redirect standard input from file descriptor N
2381 > FILE redirect standard output to FILE
2382 >> FILE append standard output to FILE
2383 1>> FILE append standard output to FILE
2384 >&N redirect standard output to file descriptor N
2385 1>&N redirect standard output to file descriptor N
2386 >>&N append standard output to file descriptor N
2387 1>>&N append standard output to file descriptor N
2388 2> FILE redirect standard error to FILE
2389 2>> FILE append standard error to FILE
2390 2>&N redirect standard error to file descriptor N
2391 2>>&N append standard error to file descriptor N
2393 Note that using N > 2 in the above construct is supported, but
2394 requires that the corresponding file descriptor be open by some
2395 means elsewhere or outside GDB. Also note that using ">&0" or
2396 "<&2" will generally fail, because the file descriptor redirected
2397 from is normally open in an incompatible mode (e.g., FD 0 is open
2398 for reading only). IOW, use of such tricks is not recommended;
2399 you are on your own.
2401 We do NOT support redirection of file descriptors above 2, as in
2402 "3>SOME-FILE", because MinGW compiled programs don't (supporting
2403 that needs special handling in the startup code that MinGW
2404 doesn't have). Pipes are also not supported.
2406 As for invalid use cases, where the redirection contains some
2407 error, the emulation below will detect that and produce some
2408 error and/or failure. But the behavior in those cases is not
2409 bug-for-bug compatible with what cmd.exe does in those cases.
2410 That's because what cmd.exe does then is not well defined, and
2411 seems to be a side effect of the cmd.exe parsing of the command
2412 line more than anything else. For example, try redirecting to an
2413 invalid file name, as in "> foo:bar".
2415 There are also minor syntactic deviations from what cmd.exe does
2416 in some corner cases. For example, it doesn't support the likes
2417 of "> &foo" to mean redirect to file named literally "&foo"; we
2418 do support that here, because that, too, sounds like some issue
2419 with the cmd.exe parser. Another nicety is that we support
2420 redirection targets that use file names with forward slashes,
2421 something cmd.exe doesn't -- this comes in handy since GDB
2422 file-name completion can be used when typing the command line for
2423 the inferior. */
2425 /* Support routines for redirecting standard handles of the inferior. */
2427 /* Parse a single redirection spec, open/duplicate the specified
2428 file/fd, and assign the appropriate value to one of the 3 standard
2429 file descriptors. */
2430 static int
2431 redir_open (const char *redir_string, int *inp, int *out, int *err)
2433 int *fd, ref_fd = -2;
2434 int mode;
2435 const char *fname = redir_string + 1;
2436 int rc = *redir_string;
2438 switch (rc)
2440 case '0':
2441 fname++;
2442 [[fallthrough]];
2443 case '<':
2444 fd = inp;
2445 mode = O_RDONLY;
2446 break;
2447 case '1': case '2':
2448 fname++;
2449 [[fallthrough]];
2450 case '>':
2451 fd = (rc == '2') ? err : out;
2452 mode = O_WRONLY | O_CREAT;
2453 if (*fname == '>')
2455 fname++;
2456 mode |= O_APPEND;
2458 else
2459 mode |= O_TRUNC;
2460 break;
2461 default:
2462 return -1;
2465 if (*fname == '&' && '0' <= fname[1] && fname[1] <= '9')
2467 /* A reference to a file descriptor. */
2468 char *fdtail;
2469 ref_fd = (int) strtol (fname + 1, &fdtail, 10);
2470 if (fdtail > fname + 1 && *fdtail == '\0')
2472 /* Don't allow redirection when open modes are incompatible. */
2473 if ((ref_fd == 0 && (fd == out || fd == err))
2474 || ((ref_fd == 1 || ref_fd == 2) && fd == inp))
2476 errno = EPERM;
2477 return -1;
2479 if (ref_fd == 0)
2480 ref_fd = *inp;
2481 else if (ref_fd == 1)
2482 ref_fd = *out;
2483 else if (ref_fd == 2)
2484 ref_fd = *err;
2486 else
2488 errno = EBADF;
2489 return -1;
2492 else
2493 fname++; /* skip the separator space */
2494 /* If the descriptor is already open, close it. This allows
2495 multiple specs of redirections for the same stream, which is
2496 somewhat nonsensical, but still valid and supported by cmd.exe.
2497 (But cmd.exe only opens a single file in this case, the one
2498 specified by the last redirection spec on the command line.) */
2499 if (*fd >= 0)
2500 _close (*fd);
2501 if (ref_fd == -2)
2503 *fd = _open (fname, mode, _S_IREAD | _S_IWRITE);
2504 if (*fd < 0)
2505 return -1;
2507 else if (ref_fd == -1)
2508 *fd = -1; /* reset to default destination */
2509 else
2511 *fd = _dup (ref_fd);
2512 if (*fd < 0)
2513 return -1;
2515 /* _open just sets a flag for O_APPEND, which won't be passed to the
2516 inferior, so we need to actually move the file pointer. */
2517 if ((mode & O_APPEND) != 0)
2518 _lseek (*fd, 0L, SEEK_END);
2519 return 0;
2522 /* Canonicalize a single redirection spec and set up the corresponding
2523 file descriptor as specified. */
2524 static int
2525 redir_set_redirection (const char *s, int *inp, int *out, int *err)
2527 char buf[__PMAX + 2 + 5]; /* extra space for quotes & redirection string */
2528 char *d = buf;
2529 const char *start = s;
2530 int quote = 0;
2532 *d++ = *s++; /* copy the 1st character, < or > or a digit */
2533 if ((*start == '>' || *start == '1' || *start == '2')
2534 && *s == '>')
2536 *d++ = *s++;
2537 if (*s == '>' && *start != '>')
2538 *d++ = *s++;
2540 else if (*start == '0' && *s == '<')
2541 *d++ = *s++;
2542 /* cmd.exe recognizes "&N" only immediately after the redirection symbol. */
2543 if (*s != '&')
2545 while (isspace (*s)) /* skip whitespace before file name */
2546 s++;
2547 *d++ = ' '; /* separate file name with a single space */
2550 /* Copy the file name. */
2551 while (*s)
2553 /* Remove quoting characters from the file name in buf[]. */
2554 if (*s == '"') /* could support '..' quoting here */
2556 if (!quote)
2557 quote = *s++;
2558 else if (*s == quote)
2560 quote = 0;
2561 s++;
2563 else
2564 *d++ = *s++;
2566 else if (*s == '\\')
2568 if (s[1] == '"') /* could support '..' here */
2569 s++;
2570 *d++ = *s++;
2572 else if (isspace (*s) && !quote)
2573 break;
2574 else
2575 *d++ = *s++;
2576 if (d - buf >= sizeof (buf) - 1)
2578 errno = ENAMETOOLONG;
2579 return 0;
2582 *d = '\0';
2584 /* Windows doesn't allow redirection characters in file names, so we
2585 can bail out early if they use them, or if there's no target file
2586 name after the redirection symbol. */
2587 if (d[-1] == '>' || d[-1] == '<')
2589 errno = ENOENT;
2590 return 0;
2592 if (redir_open (buf, inp, out, err) == 0)
2593 return s - start;
2594 return 0;
2597 /* Parse the command line for redirection specs and prepare the file
2598 descriptors for the 3 standard streams accordingly. */
2599 static bool
2600 redirect_inferior_handles (const char *cmd_orig, char *cmd,
2601 int *inp, int *out, int *err)
2603 const char *s = cmd_orig;
2604 char *d = cmd;
2605 int quote = 0;
2606 bool retval = false;
2608 while (isspace (*s))
2609 *d++ = *s++;
2611 while (*s)
2613 if (*s == '"') /* could also support '..' quoting here */
2615 if (!quote)
2616 quote = *s;
2617 else if (*s == quote)
2618 quote = 0;
2620 else if (*s == '\\')
2622 if (s[1] == '"') /* escaped quote char */
2623 s++;
2625 else if (!quote)
2627 /* Process a single redirection candidate. */
2628 if (*s == '<' || *s == '>'
2629 || ((*s == '1' || *s == '2') && s[1] == '>')
2630 || (*s == '0' && s[1] == '<'))
2632 int skip = redir_set_redirection (s, inp, out, err);
2634 if (skip <= 0)
2635 return false;
2636 retval = true;
2637 s += skip;
2640 if (*s)
2641 *d++ = *s++;
2643 *d = '\0';
2644 return retval;
2646 #endif /* !__CYGWIN__ */
2648 /* Start an inferior windows child process and sets inferior_ptid to its pid.
2649 EXEC_FILE is the file to run.
2650 ALLARGS is a string containing the arguments to the program.
2651 ENV is the environment vector to pass. Errors reported with error(). */
2653 void
2654 windows_nat_target::create_inferior (const char *exec_file,
2655 const std::string &origallargs,
2656 char **in_env, int from_tty)
2658 STARTUPINFO si;
2659 #ifdef __CYGWIN__
2660 wchar_t real_path[__PMAX];
2661 wchar_t shell[__PMAX]; /* Path to shell */
2662 wchar_t infcwd[__PMAX];
2663 const char *sh;
2664 wchar_t *toexec;
2665 wchar_t *cygallargs;
2666 wchar_t *args;
2667 char **old_env = NULL;
2668 PWCHAR w32_env;
2669 size_t len;
2670 int tty;
2671 int ostdin, ostdout, ostderr;
2672 #else /* !__CYGWIN__ */
2673 char shell[__PMAX]; /* Path to shell */
2674 const char *toexec;
2675 char *args, *allargs_copy;
2676 size_t args_len, allargs_len;
2677 int fd_inp = -1, fd_out = -1, fd_err = -1;
2678 HANDLE tty = INVALID_HANDLE_VALUE;
2679 bool redirected = false;
2680 char *w32env;
2681 char *temp;
2682 size_t envlen;
2683 int i;
2684 size_t envsize;
2685 char **env;
2686 #endif /* !__CYGWIN__ */
2687 const char *allargs = origallargs.c_str ();
2688 PROCESS_INFORMATION pi;
2689 std::optional<unsigned> ret;
2690 DWORD flags = 0;
2691 const std::string &inferior_tty = current_inferior ()->tty ();
2693 if (!exec_file)
2694 error (_("No executable specified, use `target exec'."));
2696 const char *inferior_cwd = current_inferior ()->cwd ().c_str ();
2697 std::string expanded_infcwd;
2698 if (*inferior_cwd == '\0')
2699 inferior_cwd = nullptr;
2700 else
2702 expanded_infcwd = gdb_tilde_expand (inferior_cwd);
2703 /* Mirror slashes on inferior's cwd. */
2704 std::replace (expanded_infcwd.begin (), expanded_infcwd.end (),
2705 '/', '\\');
2706 inferior_cwd = expanded_infcwd.c_str ();
2709 memset (&si, 0, sizeof (si));
2710 si.cb = sizeof (si);
2712 if (new_group)
2713 flags |= CREATE_NEW_PROCESS_GROUP;
2715 if (new_console)
2716 windows_set_console_info (&si, &flags);
2718 #ifdef __CYGWIN__
2719 if (!useshell)
2721 flags |= DEBUG_ONLY_THIS_PROCESS;
2722 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, exec_file, real_path,
2723 __PMAX * sizeof (wchar_t)) < 0)
2724 error (_("Error starting executable: %d"), errno);
2725 toexec = real_path;
2726 len = mbstowcs (NULL, allargs, 0) + 1;
2727 if (len == (size_t) -1)
2728 error (_("Error starting executable: %d"), errno);
2729 cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
2730 mbstowcs (cygallargs, allargs, len);
2732 else
2734 sh = get_shell ();
2735 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, sh, shell, __PMAX) < 0)
2736 error (_("Error starting executable via shell: %d"), errno);
2737 len = sizeof (L" -c 'exec '") + mbstowcs (NULL, exec_file, 0)
2738 + mbstowcs (NULL, allargs, 0) + 2;
2739 cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
2740 swprintf (cygallargs, len, L" -c 'exec %s %s'", exec_file, allargs);
2741 toexec = shell;
2742 flags |= DEBUG_PROCESS;
2745 if (inferior_cwd != NULL
2746 && cygwin_conv_path (CCP_POSIX_TO_WIN_W, inferior_cwd,
2747 infcwd, strlen (inferior_cwd)) < 0)
2748 error (_("Error converting inferior cwd: %d"), errno);
2750 args = (wchar_t *) alloca ((wcslen (toexec) + wcslen (cygallargs) + 2)
2751 * sizeof (wchar_t));
2752 wcscpy (args, toexec);
2753 wcscat (args, L" ");
2754 wcscat (args, cygallargs);
2756 #ifdef CW_CVT_ENV_TO_WINENV
2757 /* First try to create a direct Win32 copy of the POSIX environment. */
2758 w32_env = (PWCHAR) cygwin_internal (CW_CVT_ENV_TO_WINENV, in_env);
2759 if (w32_env != (PWCHAR) -1)
2760 flags |= CREATE_UNICODE_ENVIRONMENT;
2761 else
2762 /* If that fails, fall back to old method tweaking GDB's environment. */
2763 #endif /* CW_CVT_ENV_TO_WINENV */
2765 /* Reset all Win32 environment variables to avoid leftover on next run. */
2766 clear_win32_environment (environ);
2767 /* Prepare the environment vars for CreateProcess. */
2768 old_env = environ;
2769 environ = in_env;
2770 cygwin_internal (CW_SYNC_WINENV);
2771 w32_env = NULL;
2774 if (inferior_tty.empty ())
2775 tty = ostdin = ostdout = ostderr = -1;
2776 else
2778 tty = open (inferior_tty.c_str (), O_RDWR | O_NOCTTY);
2779 if (tty < 0)
2781 warning_filename_and_errno (inferior_tty.c_str (), errno);
2782 ostdin = ostdout = ostderr = -1;
2784 else
2786 ostdin = dup (0);
2787 ostdout = dup (1);
2788 ostderr = dup (2);
2789 dup2 (tty, 0);
2790 dup2 (tty, 1);
2791 dup2 (tty, 2);
2795 windows_init_thread_list ();
2796 do_synchronously ([&] ()
2798 BOOL ok = create_process (nullptr, args, flags, w32_env,
2799 inferior_cwd != nullptr ? infcwd : nullptr,
2800 disable_randomization,
2801 &si, &pi);
2803 if (!ok)
2804 ret = (unsigned) GetLastError ();
2806 return ok;
2809 if (w32_env)
2810 /* Just free the Win32 environment, if it could be created. */
2811 free (w32_env);
2812 else
2814 /* Reset all environment variables to avoid leftover on next run. */
2815 clear_win32_environment (in_env);
2816 /* Restore normal GDB environment variables. */
2817 environ = old_env;
2818 cygwin_internal (CW_SYNC_WINENV);
2821 if (tty >= 0)
2823 ::close (tty);
2824 dup2 (ostdin, 0);
2825 dup2 (ostdout, 1);
2826 dup2 (ostderr, 2);
2827 ::close (ostdin);
2828 ::close (ostdout);
2829 ::close (ostderr);
2831 #else /* !__CYGWIN__ */
2832 allargs_len = strlen (allargs);
2833 allargs_copy = strcpy ((char *) alloca (allargs_len + 1), allargs);
2834 if (strpbrk (allargs_copy, "<>") != NULL)
2836 int e = errno;
2837 errno = 0;
2838 redirected =
2839 redirect_inferior_handles (allargs, allargs_copy,
2840 &fd_inp, &fd_out, &fd_err);
2841 if (errno)
2842 warning (_("Error in redirection: %s."), safe_strerror (errno));
2843 else
2844 errno = e;
2845 allargs_len = strlen (allargs_copy);
2847 /* If not all the standard streams are redirected by the command
2848 line, use INFERIOR_TTY for those which aren't. */
2849 if (!inferior_tty.empty ()
2850 && !(fd_inp >= 0 && fd_out >= 0 && fd_err >= 0))
2852 SECURITY_ATTRIBUTES sa;
2853 sa.nLength = sizeof(sa);
2854 sa.lpSecurityDescriptor = 0;
2855 sa.bInheritHandle = TRUE;
2856 tty = CreateFileA (inferior_tty.c_str (), GENERIC_READ | GENERIC_WRITE,
2857 0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
2858 if (tty == INVALID_HANDLE_VALUE)
2860 unsigned err = (unsigned) GetLastError ();
2861 warning (_("Warning: Failed to open TTY %s, error %#x: %s"),
2862 inferior_tty.c_str (), err, strwinerror (err));
2865 if (redirected || tty != INVALID_HANDLE_VALUE)
2867 if (fd_inp >= 0)
2868 si.hStdInput = (HANDLE) _get_osfhandle (fd_inp);
2869 else if (tty != INVALID_HANDLE_VALUE)
2870 si.hStdInput = tty;
2871 else
2872 si.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
2873 if (fd_out >= 0)
2874 si.hStdOutput = (HANDLE) _get_osfhandle (fd_out);
2875 else if (tty != INVALID_HANDLE_VALUE)
2876 si.hStdOutput = tty;
2877 else
2878 si.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
2879 if (fd_err >= 0)
2880 si.hStdError = (HANDLE) _get_osfhandle (fd_err);
2881 else if (tty != INVALID_HANDLE_VALUE)
2882 si.hStdError = tty;
2883 else
2884 si.hStdError = GetStdHandle (STD_ERROR_HANDLE);
2885 si.dwFlags |= STARTF_USESTDHANDLES;
2888 toexec = exec_file;
2889 /* Build the command line, a space-separated list of tokens where
2890 the first token is the name of the module to be executed.
2891 To avoid ambiguities introduced by spaces in the module name,
2892 we quote it. */
2893 args_len = strlen (toexec) + 2 /* quotes */ + allargs_len + 2;
2894 args = (char *) alloca (args_len);
2895 xsnprintf (args, args_len, "\"%s\" %s", toexec, allargs_copy);
2897 flags |= DEBUG_ONLY_THIS_PROCESS;
2899 /* CreateProcess takes the environment list as a null terminated set of
2900 strings (i.e. two nulls terminate the list). */
2902 /* Get total size for env strings. */
2903 for (envlen = 0, i = 0; in_env[i] && *in_env[i]; i++)
2904 envlen += strlen (in_env[i]) + 1;
2906 envsize = sizeof (in_env[0]) * (i + 1);
2907 env = (char **) alloca (envsize);
2908 memcpy (env, in_env, envsize);
2909 /* Windows programs expect the environment block to be sorted. */
2910 qsort (env, i, sizeof (char *), envvar_cmp);
2912 w32env = (char *) alloca (envlen + 1);
2914 /* Copy env strings into new buffer. */
2915 for (temp = w32env, i = 0; env[i] && *env[i]; i++)
2917 strcpy (temp, env[i]);
2918 temp += strlen (temp) + 1;
2921 /* Final nil string to terminate new env. */
2922 *temp = 0;
2924 windows_init_thread_list ();
2925 do_synchronously ([&] ()
2927 BOOL ok = create_process (nullptr, /* image */
2928 args, /* command line */
2929 flags, /* start flags */
2930 w32env, /* environment */
2931 inferior_cwd, /* current directory */
2932 disable_randomization,
2933 &si,
2934 &pi);
2935 if (!ok)
2936 ret = (unsigned) GetLastError ();
2938 return ok;
2940 if (tty != INVALID_HANDLE_VALUE)
2941 CloseHandle (tty);
2942 if (fd_inp >= 0)
2943 _close (fd_inp);
2944 if (fd_out >= 0)
2945 _close (fd_out);
2946 if (fd_err >= 0)
2947 _close (fd_err);
2948 #endif /* !__CYGWIN__ */
2950 if (ret.has_value ())
2952 std::string msg = _("Error creating process ") + std::string (exec_file);
2953 throw_winerror_with_name (msg.c_str (), *ret);
2956 #ifdef __x86_64__
2957 BOOL wow64;
2958 if (IsWow64Process (pi.hProcess, &wow64))
2959 windows_process.wow64_process = wow64;
2960 #endif
2962 CloseHandle (pi.hThread);
2963 CloseHandle (pi.hProcess);
2965 if (useshell && shell[0] != '\0')
2966 windows_process.saw_create = -1;
2967 else
2968 windows_process.saw_create = 0;
2970 do_initial_windows_stuff (pi.dwProcessId, 0);
2972 /* windows_continue (DBG_CONTINUE, -1, 0); */
2975 void
2976 windows_nat_target::mourn_inferior ()
2978 (void) windows_continue (DBG_CONTINUE, -1, 0, true);
2979 x86_cleanup_dregs();
2980 if (windows_process.open_process_used)
2982 CHECK (CloseHandle (windows_process.handle));
2983 windows_process.open_process_used = 0;
2985 windows_process.siginfo_er.ExceptionCode = 0;
2986 inf_child_target::mourn_inferior ();
2989 /* Helper for windows_xfer_partial that handles memory transfers.
2990 Arguments are like target_xfer_partial. */
2992 static enum target_xfer_status
2993 windows_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
2994 ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
2996 SIZE_T done = 0;
2997 BOOL success;
2998 DWORD lasterror = 0;
3000 if (writebuf != NULL)
3002 DEBUG_MEM ("write target memory, %s bytes at %s",
3003 pulongest (len), core_addr_to_string (memaddr));
3004 success = WriteProcessMemory (windows_process.handle,
3005 (LPVOID) (uintptr_t) memaddr, writebuf,
3006 len, &done);
3007 if (!success)
3008 lasterror = GetLastError ();
3009 FlushInstructionCache (windows_process.handle,
3010 (LPCVOID) (uintptr_t) memaddr, len);
3012 else
3014 DEBUG_MEM ("read target memory, %s bytes at %s",
3015 pulongest (len), core_addr_to_string (memaddr));
3016 success = ReadProcessMemory (windows_process.handle,
3017 (LPCVOID) (uintptr_t) memaddr, readbuf,
3018 len, &done);
3019 if (!success)
3020 lasterror = GetLastError ();
3022 *xfered_len = (ULONGEST) done;
3023 if (!success && lasterror == ERROR_PARTIAL_COPY && done > 0)
3024 return TARGET_XFER_OK;
3025 else
3026 return success ? TARGET_XFER_OK : TARGET_XFER_E_IO;
3029 void
3030 windows_nat_target::kill ()
3032 CHECK (TerminateProcess (windows_process.handle, 0));
3034 for (;;)
3036 if (!windows_continue (DBG_CONTINUE, -1, 1))
3037 break;
3038 wait_for_debug_event_main_thread (&windows_process.current_event);
3039 if (windows_process.current_event.dwDebugEventCode
3040 == EXIT_PROCESS_DEBUG_EVENT)
3041 break;
3044 target_mourn_inferior (inferior_ptid); /* Or just windows_mourn_inferior? */
3047 void
3048 windows_nat_target::close ()
3050 DEBUG_EVENTS ("inferior_ptid=%d\n", inferior_ptid.pid ());
3051 async (false);
3054 /* Convert pid to printable format. */
3055 std::string
3056 windows_nat_target::pid_to_str (ptid_t ptid)
3058 if (ptid.lwp () != 0)
3059 return string_printf ("Thread %d.0x%lx", ptid.pid (), ptid.lwp ());
3061 return normal_pid_to_str (ptid);
3064 static enum target_xfer_status
3065 windows_xfer_shared_libraries (struct target_ops *ops,
3066 enum target_object object, const char *annex,
3067 gdb_byte *readbuf, const gdb_byte *writebuf,
3068 ULONGEST offset, ULONGEST len,
3069 ULONGEST *xfered_len)
3071 if (writebuf)
3072 return TARGET_XFER_E_IO;
3074 std::string xml = "<library-list>\n";
3075 for (windows_solib &so : windows_process.solibs)
3076 windows_xfer_shared_library (so.name.c_str (),
3077 (CORE_ADDR) (uintptr_t) so.load_addr,
3078 &so.text_offset,
3079 current_inferior ()->arch (), xml);
3080 xml += "</library-list>\n";
3082 ULONGEST len_avail = xml.size ();
3083 if (offset >= len_avail)
3084 len = 0;
3085 else
3087 if (len > len_avail - offset)
3088 len = len_avail - offset;
3089 memcpy (readbuf, xml.data () + offset, len);
3092 *xfered_len = (ULONGEST) len;
3093 return len != 0 ? TARGET_XFER_OK : TARGET_XFER_EOF;
3096 /* Helper for windows_nat_target::xfer_partial that handles signal info. */
3098 static enum target_xfer_status
3099 windows_xfer_siginfo (gdb_byte *readbuf, ULONGEST offset, ULONGEST len,
3100 ULONGEST *xfered_len)
3102 char *buf = (char *) &windows_process.siginfo_er;
3103 size_t bufsize = sizeof (windows_process.siginfo_er);
3105 #ifdef __x86_64__
3106 EXCEPTION_RECORD32 er32;
3107 if (windows_process.wow64_process)
3109 buf = (char *) &er32;
3110 bufsize = sizeof (er32);
3112 er32.ExceptionCode = windows_process.siginfo_er.ExceptionCode;
3113 er32.ExceptionFlags = windows_process.siginfo_er.ExceptionFlags;
3114 er32.ExceptionRecord
3115 = (uintptr_t) windows_process.siginfo_er.ExceptionRecord;
3116 er32.ExceptionAddress
3117 = (uintptr_t) windows_process.siginfo_er.ExceptionAddress;
3118 er32.NumberParameters = windows_process.siginfo_er.NumberParameters;
3119 int i;
3120 for (i = 0; i < EXCEPTION_MAXIMUM_PARAMETERS; i++)
3121 er32.ExceptionInformation[i]
3122 = windows_process.siginfo_er.ExceptionInformation[i];
3124 #endif
3126 if (windows_process.siginfo_er.ExceptionCode == 0)
3127 return TARGET_XFER_E_IO;
3129 if (readbuf == nullptr)
3130 return TARGET_XFER_E_IO;
3132 if (offset > bufsize)
3133 return TARGET_XFER_E_IO;
3135 if (offset + len > bufsize)
3136 len = bufsize - offset;
3138 memcpy (readbuf, buf + offset, len);
3139 *xfered_len = len;
3141 return TARGET_XFER_OK;
3144 enum target_xfer_status
3145 windows_nat_target::xfer_partial (enum target_object object,
3146 const char *annex, gdb_byte *readbuf,
3147 const gdb_byte *writebuf, ULONGEST offset,
3148 ULONGEST len, ULONGEST *xfered_len)
3150 switch (object)
3152 case TARGET_OBJECT_MEMORY:
3153 return windows_xfer_memory (readbuf, writebuf, offset, len, xfered_len);
3155 case TARGET_OBJECT_LIBRARIES:
3156 return windows_xfer_shared_libraries (this, object, annex, readbuf,
3157 writebuf, offset, len, xfered_len);
3159 case TARGET_OBJECT_SIGNAL_INFO:
3160 return windows_xfer_siginfo (readbuf, offset, len, xfered_len);
3162 default:
3163 if (beneath () == NULL)
3165 /* This can happen when requesting the transfer of unsupported
3166 objects before a program has been started (and therefore
3167 with the current_target having no target beneath). */
3168 return TARGET_XFER_E_IO;
3170 return beneath ()->xfer_partial (object, annex,
3171 readbuf, writebuf, offset, len,
3172 xfered_len);
3176 /* Provide thread local base, i.e. Thread Information Block address.
3177 Returns 1 if ptid is found and sets *ADDR to thread_local_base. */
3179 bool
3180 windows_nat_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
3182 windows_thread_info *th;
3184 th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
3185 if (th == NULL)
3186 return false;
3188 if (addr != NULL)
3189 *addr = th->thread_local_base;
3191 return true;
3194 ptid_t
3195 windows_nat_target::get_ada_task_ptid (long lwp, ULONGEST thread)
3197 return ptid_t (inferior_ptid.pid (), lwp, 0);
3200 /* Implementation of the to_thread_name method. */
3202 const char *
3203 windows_nat_target::thread_name (struct thread_info *thr)
3205 windows_thread_info *th
3206 = windows_process.thread_rec (thr->ptid,
3207 DONT_INVALIDATE_CONTEXT);
3208 return th->thread_name ();
3212 void _initialize_windows_nat ();
3213 void
3214 _initialize_windows_nat ()
3216 x86_dr_low.set_control = cygwin_set_dr7;
3217 x86_dr_low.set_addr = cygwin_set_dr;
3218 x86_dr_low.get_addr = cygwin_get_dr;
3219 x86_dr_low.get_status = cygwin_get_dr6;
3220 x86_dr_low.get_control = cygwin_get_dr7;
3222 /* x86_dr_low.debug_register_length field is set by
3223 calling x86_set_debug_register_length function
3224 in processor windows specific native file. */
3226 /* The target is not a global specifically to avoid a C++ "static
3227 initializer fiasco" situation. */
3228 add_inf_child_target (new windows_nat_target);
3230 #ifdef __CYGWIN__
3231 cygwin_internal (CW_SET_DOS_FILE_WARNING, 0);
3232 #endif
3234 add_com ("signal-event", class_run, signal_event_command, _("\
3235 Signal a crashed process with event ID, to allow its debugging.\n\
3236 This command is needed in support of setting up GDB as JIT debugger on \
3237 MS-Windows. The command should be invoked from the GDB command line using \
3238 the '-ex' command-line option. The ID of the event that blocks the \
3239 crashed process will be supplied by the Windows JIT debugging mechanism."));
3241 #ifdef __CYGWIN__
3242 add_setshow_boolean_cmd ("shell", class_support, &useshell, _("\
3243 Set use of shell to start subprocess."), _("\
3244 Show use of shell to start subprocess."), NULL,
3245 NULL,
3246 NULL, /* FIXME: i18n: */
3247 &setlist, &showlist);
3249 add_setshow_boolean_cmd ("cygwin-exceptions", class_support,
3250 &cygwin_exceptions, _("\
3251 Break when an exception is detected in the Cygwin DLL itself."), _("\
3252 Show whether gdb breaks on exceptions in the Cygwin DLL itself."), NULL,
3253 NULL,
3254 NULL, /* FIXME: i18n: */
3255 &setlist, &showlist);
3256 #endif
3258 add_setshow_boolean_cmd ("new-console", class_support, &new_console, _("\
3259 Set creation of new console when creating child process."), _("\
3260 Show creation of new console when creating child process."), NULL,
3261 NULL,
3262 NULL, /* FIXME: i18n: */
3263 &setlist, &showlist);
3265 add_setshow_boolean_cmd ("new-group", class_support, &new_group, _("\
3266 Set creation of new group when creating child process."), _("\
3267 Show creation of new group when creating child process."), NULL,
3268 NULL,
3269 NULL, /* FIXME: i18n: */
3270 &setlist, &showlist);
3272 add_setshow_boolean_cmd ("debugexec", class_support, &debug_exec, _("\
3273 Set whether to display execution in child process."), _("\
3274 Show whether to display execution in child process."), NULL,
3275 NULL,
3276 NULL, /* FIXME: i18n: */
3277 &setlist, &showlist);
3279 add_setshow_boolean_cmd ("debugevents", class_support, &debug_events, _("\
3280 Set whether to display kernel events in child process."), _("\
3281 Show whether to display kernel events in child process."), NULL,
3282 NULL,
3283 NULL, /* FIXME: i18n: */
3284 &setlist, &showlist);
3286 add_setshow_boolean_cmd ("debugmemory", class_support, &debug_memory, _("\
3287 Set whether to display memory accesses in child process."), _("\
3288 Show whether to display memory accesses in child process."), NULL,
3289 NULL,
3290 NULL, /* FIXME: i18n: */
3291 &setlist, &showlist);
3293 add_setshow_boolean_cmd ("debugexceptions", class_support,
3294 &debug_exceptions, _("\
3295 Set whether to display kernel exceptions in child process."), _("\
3296 Show whether to display kernel exceptions in child process."), NULL,
3297 NULL,
3298 NULL, /* FIXME: i18n: */
3299 &setlist, &showlist);
3301 init_w32_command_list ();
3303 add_cmd ("selector", class_info, display_selectors,
3304 _("Display selectors infos."),
3305 &info_w32_cmdlist);
3307 if (!initialize_loadable ())
3309 /* This will probably fail on Windows 9x/Me. Let the user know
3310 that we're missing some functionality. */
3311 warning(_("\
3312 cannot automatically find executable file or library to read symbols.\n\
3313 Use \"file\" or \"dll\" command to load executable/libraries directly."));
3317 /* Hardware watchpoint support, adapted from go32-nat.c code. */
3319 /* Pass the address ADDR to the inferior in the I'th debug register.
3320 Here we just store the address in dr array, the registers will be
3321 actually set up when windows_continue is called. */
3322 static void
3323 cygwin_set_dr (int i, CORE_ADDR addr)
3325 if (i < 0 || i > 3)
3326 internal_error (_("Invalid register %d in cygwin_set_dr.\n"), i);
3327 windows_process.dr[i] = addr;
3329 for (auto &th : windows_process.thread_list)
3330 th->debug_registers_changed = true;
3333 /* Pass the value VAL to the inferior in the DR7 debug control
3334 register. Here we just store the address in D_REGS, the watchpoint
3335 will be actually set up in windows_wait. */
3336 static void
3337 cygwin_set_dr7 (unsigned long val)
3339 windows_process.dr[7] = (CORE_ADDR) val;
3341 for (auto &th : windows_process.thread_list)
3342 th->debug_registers_changed = true;
3345 /* Get the value of debug register I from the inferior. */
3347 static CORE_ADDR
3348 cygwin_get_dr (int i)
3350 return windows_process.dr[i];
3353 /* Get the value of the DR6 debug status register from the inferior.
3354 Here we just return the value stored in dr[6]
3355 by the last call to thread_rec for current_event.dwThreadId id. */
3356 static unsigned long
3357 cygwin_get_dr6 (void)
3359 return (unsigned long) windows_process.dr[6];
3362 /* Get the value of the DR7 debug status register from the inferior.
3363 Here we just return the value stored in dr[7] by the last call to
3364 thread_rec for current_event.dwThreadId id. */
3366 static unsigned long
3367 cygwin_get_dr7 (void)
3369 return (unsigned long) windows_process.dr[7];
3372 /* Determine if the thread referenced by "ptid" is alive
3373 by "polling" it. If WaitForSingleObject returns WAIT_OBJECT_0
3374 it means that the thread has died. Otherwise it is assumed to be alive. */
3376 bool
3377 windows_nat_target::thread_alive (ptid_t ptid)
3379 gdb_assert (ptid.lwp () != 0);
3381 windows_thread_info *th
3382 = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
3383 return WaitForSingleObject (th->h, 0) != WAIT_OBJECT_0;
3386 void _initialize_check_for_gdb_ini ();
3387 void
3388 _initialize_check_for_gdb_ini ()
3390 char *homedir;
3391 if (inhibit_gdbinit)
3392 return;
3394 homedir = getenv ("HOME");
3395 if (homedir)
3397 char *p;
3398 char *oldini = (char *) alloca (strlen (homedir) +
3399 sizeof ("gdb.ini") + 1);
3400 strcpy (oldini, homedir);
3401 p = strchr (oldini, '\0');
3402 if (p > oldini && !IS_DIR_SEPARATOR (p[-1]))
3403 *p++ = '/';
3404 strcpy (p, "gdb.ini");
3405 if (access (oldini, 0) == 0)
3407 int len = strlen (oldini);
3408 char *newini = (char *) alloca (len + 2);
3410 xsnprintf (newini, len + 2, "%.*s.gdbinit",
3411 (int) (len - (sizeof ("gdb.ini") - 1)), oldini);
3412 warning (_("obsolete '%s' found. Rename to '%s'."), oldini, newini);