Automatic date update in version.in
[binutils-gdb.git] / gdb / windows-nat.c
blob6fdd1f3a1514876feaf07191871dfa44e399e123
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 "defs.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 <vector>
46 #include <queue>
48 #include "filenames.h"
49 #include "symfile.h"
50 #include "objfiles.h"
51 #include "gdb_bfd.h"
52 #include "gdbsupport/gdb_obstack.h"
53 #include "gdbthread.h"
54 #include "gdbcmd.h"
55 #include <unistd.h>
56 #include "exec.h"
57 #include "solist.h"
58 #include "solib.h"
59 #include "xml-support.h"
60 #include "inttypes.h"
62 #include "i386-tdep.h"
63 #include "i387-tdep.h"
65 #include "windows-tdep.h"
66 #include "windows-nat.h"
67 #include "x86-nat.h"
68 #include "complaints.h"
69 #include "inf-child.h"
70 #include "gdbsupport/gdb_tilde_expand.h"
71 #include "gdbsupport/pathstuff.h"
72 #include "gdbsupport/gdb_wait.h"
73 #include "nat/windows-nat.h"
74 #include "gdbsupport/symbol.h"
75 #include "ser-event.h"
76 #include "inf-loop.h"
78 using namespace windows_nat;
80 /* Maintain a linked list of "so" information. */
81 struct windows_solib
83 LPVOID load_addr = 0;
84 CORE_ADDR text_offset = 0;
86 /* Original name. */
87 std::string original_name;
88 /* Expanded form of the name. */
89 std::string name;
92 struct windows_per_inferior : public windows_process_info
94 windows_thread_info *thread_rec (ptid_t ptid,
95 thread_disposition_type disposition) override;
96 int handle_output_debug_string (struct target_waitstatus *ourstatus) override;
97 void handle_load_dll (const char *dll_name, LPVOID base) override;
98 void handle_unload_dll () override;
99 bool handle_access_violation (const EXCEPTION_RECORD *rec) override;
102 int have_saved_context = 0; /* True if we've saved context from a
103 cygwin signal. */
105 uintptr_t dr[8] {};
107 int windows_initialization_done = 0;
109 std::vector<std::unique_ptr<windows_thread_info>> thread_list;
111 /* Counts of things. */
112 int saw_create = 0;
113 int open_process_used = 0;
114 #ifdef __x86_64__
115 void *wow64_dbgbreak = nullptr;
116 #endif
118 /* This vector maps GDB's idea of a register's number into an offset
119 in the windows exception context vector.
121 It also contains the bit mask needed to load the register in question.
123 The contents of this table can only be computed by the units
124 that provide CPU-specific support for Windows native debugging.
126 One day we could read a reg, we could inspect the context we
127 already have loaded, if it doesn't have the bit set that we need,
128 we read that set of registers in using GetThreadContext. If the
129 context already contains what we need, we just unpack it. Then to
130 write a register, first we have to ensure that the context contains
131 the other regs of the group, and then we copy the info in and set
132 out bit. */
134 const int *mappings = nullptr;
136 /* The function to use in order to determine whether a register is
137 a segment register or not. */
138 segment_register_p_ftype *segment_register_p = nullptr;
140 std::vector<windows_solib> solibs;
142 #ifdef __CYGWIN__
143 CONTEXT saved_context {}; /* Contains the saved context from a
144 cygwin signal. */
146 /* The starting and ending address of the cygwin1.dll text segment. */
147 CORE_ADDR cygwin_load_start = 0;
148 CORE_ADDR cygwin_load_end = 0;
149 #endif /* __CYGWIN__ */
152 /* The current process. */
153 static windows_per_inferior windows_process;
155 #undef STARTUPINFO
157 #ifndef __CYGWIN__
158 # define __PMAX (MAX_PATH + 1)
159 # define STARTUPINFO STARTUPINFOA
160 #else
161 # define __PMAX PATH_MAX
162 # define STARTUPINFO STARTUPINFOW
163 #endif
165 /* If we're not using the old Cygwin header file set, define the
166 following which never should have been in the generic Win32 API
167 headers in the first place since they were our own invention... */
168 #ifndef _GNU_H_WINDOWS_H
169 enum
171 FLAG_TRACE_BIT = 0x100,
173 #endif
175 #ifndef CONTEXT_EXTENDED_REGISTERS
176 /* This macro is only defined on ia32. It only makes sense on this target,
177 so define it as zero if not already defined. */
178 #define CONTEXT_EXTENDED_REGISTERS 0
179 #endif
181 #define CONTEXT_DEBUGGER_DR CONTEXT_FULL | CONTEXT_FLOATING_POINT \
182 | CONTEXT_SEGMENTS | CONTEXT_DEBUG_REGISTERS \
183 | CONTEXT_EXTENDED_REGISTERS
185 #define DR6_CLEAR_VALUE 0xffff0ff0
187 /* The string sent by cygwin when it processes a signal.
188 FIXME: This should be in a cygwin include file. */
189 #ifndef _CYGWIN_SIGNAL_STRING
190 #define _CYGWIN_SIGNAL_STRING "cYgSiGw00f"
191 #endif
193 #define CHECK(x) check (x, __FILE__,__LINE__)
194 #define DEBUG_EXEC(fmt, ...) \
195 debug_prefixed_printf_cond (debug_exec, "windows exec", fmt, ## __VA_ARGS__)
196 #define DEBUG_EVENTS(fmt, ...) \
197 debug_prefixed_printf_cond (debug_events, "windows events", fmt, \
198 ## __VA_ARGS__)
199 #define DEBUG_MEM(fmt, ...) \
200 debug_prefixed_printf_cond (debug_memory, "windows mem", fmt, \
201 ## __VA_ARGS__)
202 #define DEBUG_EXCEPT(fmt, ...) \
203 debug_prefixed_printf_cond (debug_exceptions, "windows except", fmt, \
204 ## __VA_ARGS__)
206 static void cygwin_set_dr (int i, CORE_ADDR addr);
207 static void cygwin_set_dr7 (unsigned long val);
208 static CORE_ADDR cygwin_get_dr (int i);
209 static unsigned long cygwin_get_dr6 (void);
210 static unsigned long cygwin_get_dr7 (void);
212 /* User options. */
213 static bool new_console = false;
214 #ifdef __CYGWIN__
215 static bool cygwin_exceptions = false;
216 #endif
217 static bool new_group = true;
218 static bool debug_exec = false; /* show execution */
219 static bool debug_events = false; /* show events from kernel */
220 static bool debug_memory = false; /* show target memory accesses */
221 static bool debug_exceptions = false; /* show target exceptions */
222 static bool useshell = false; /* use shell for subprocesses */
224 /* See windows_nat_target::resume to understand why this is commented
225 out. */
226 #if 0
227 /* This vector maps the target's idea of an exception (extracted
228 from the DEBUG_EVENT structure) to GDB's idea. */
230 struct xlate_exception
232 DWORD them;
233 enum gdb_signal us;
236 static const struct xlate_exception xlate[] =
238 {EXCEPTION_ACCESS_VIOLATION, GDB_SIGNAL_SEGV},
239 {STATUS_STACK_OVERFLOW, GDB_SIGNAL_SEGV},
240 {EXCEPTION_BREAKPOINT, GDB_SIGNAL_TRAP},
241 {DBG_CONTROL_C, GDB_SIGNAL_INT},
242 {EXCEPTION_SINGLE_STEP, GDB_SIGNAL_TRAP},
243 {STATUS_FLOAT_DIVIDE_BY_ZERO, GDB_SIGNAL_FPE}
246 #endif /* 0 */
248 struct windows_nat_target final : public x86_nat_target<inf_child_target>
250 windows_nat_target ();
252 void close () override;
254 void attach (const char *, int) override;
256 bool attach_no_wait () override
257 { return true; }
259 void detach (inferior *, int) override;
261 void resume (ptid_t, int , enum gdb_signal) override;
263 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
265 void fetch_registers (struct regcache *, int) override;
266 void store_registers (struct regcache *, int) override;
268 bool stopped_by_sw_breakpoint () override
270 windows_thread_info *th
271 = windows_process.thread_rec (inferior_ptid, DONT_INVALIDATE_CONTEXT);
272 return th->stopped_at_software_breakpoint;
275 bool supports_stopped_by_sw_breakpoint () override
277 return true;
280 enum target_xfer_status xfer_partial (enum target_object object,
281 const char *annex,
282 gdb_byte *readbuf,
283 const gdb_byte *writebuf,
284 ULONGEST offset, ULONGEST len,
285 ULONGEST *xfered_len) override;
287 void files_info () override;
289 void kill () override;
291 void create_inferior (const char *, const std::string &,
292 char **, int) override;
294 void mourn_inferior () override;
296 bool thread_alive (ptid_t ptid) override;
298 std::string pid_to_str (ptid_t) override;
300 void interrupt () override;
301 void pass_ctrlc () override;
303 const char *pid_to_exec_file (int pid) override;
305 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
307 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
309 const char *thread_name (struct thread_info *) override;
311 ptid_t get_windows_debug_event (int pid, struct target_waitstatus *ourstatus,
312 target_wait_flags options);
314 void do_initial_windows_stuff (DWORD pid, bool attaching);
316 bool supports_disable_randomization () override
318 return disable_randomization_available ();
321 bool can_async_p () override
323 return true;
326 bool is_async_p () override
328 return m_is_async;
331 void async (bool enable) override;
333 int async_wait_fd () override
335 return serial_event_fd (m_wait_event);
338 private:
340 windows_thread_info *add_thread (ptid_t ptid, HANDLE h, void *tlb,
341 bool main_thread_p);
342 void delete_thread (ptid_t ptid, DWORD exit_code, bool main_thread_p);
343 DWORD fake_create_process ();
345 BOOL windows_continue (DWORD continue_status, int id, int killed,
346 bool last_call = false);
348 /* Helper function to start process_thread. */
349 static DWORD WINAPI process_thread_starter (LPVOID self);
351 /* This function implements the background thread that starts
352 inferiors and waits for events. */
353 void process_thread ();
355 /* Push FUNC onto the queue of requests for process_thread, and wait
356 until it has been called. On Windows, certain debugging
357 functions can only be called by the thread that started (or
358 attached to) the inferior. These are all done in the worker
359 thread, via calls to this method. If FUNC returns true,
360 process_thread will wait for debug events when FUNC returns. */
361 void do_synchronously (gdb::function_view<bool ()> func);
363 /* This waits for a debug event, dispatching to the worker thread as
364 needed. */
365 void wait_for_debug_event_main_thread (DEBUG_EVENT *event);
367 /* Queue used to send requests to process_thread. This is
368 implicitly locked. */
369 std::queue<gdb::function_view<bool ()>> m_queue;
371 /* Event used to signal process_thread that an item has been
372 pushed. */
373 HANDLE m_pushed_event;
374 /* Event used by process_thread to indicate that it has processed a
375 single function call. */
376 HANDLE m_response_event;
378 /* Serial event used to communicate wait event availability to the
379 main loop. */
380 serial_event *m_wait_event;
382 /* The last debug event, when M_WAIT_EVENT has been set. */
383 DEBUG_EVENT m_last_debug_event {};
384 /* True if a debug event is pending. */
385 std::atomic<bool> m_debug_event_pending { false };
387 /* True if currently in async mode. */
388 bool m_is_async = false;
391 static void
392 check (BOOL ok, const char *file, int line)
394 if (!ok)
396 unsigned err = (unsigned) GetLastError ();
397 gdb_printf ("error return %s:%d was %u: %s\n", file, line,
398 err, strwinerror (err));
402 windows_nat_target::windows_nat_target ()
403 : m_pushed_event (CreateEvent (nullptr, false, false, nullptr)),
404 m_response_event (CreateEvent (nullptr, false, false, nullptr)),
405 m_wait_event (make_serial_event ())
407 HANDLE bg_thread = CreateThread (nullptr, 64 * 1024,
408 process_thread_starter, this, 0, nullptr);
409 CloseHandle (bg_thread);
412 void
413 windows_nat_target::async (bool enable)
415 if (enable == is_async_p ())
416 return;
418 if (enable)
419 add_file_handler (async_wait_fd (),
420 [] (int, gdb_client_data)
422 inferior_event_handler (INF_REG_EVENT);
424 nullptr, "windows_nat_target");
425 else
426 delete_file_handler (async_wait_fd ());
428 m_is_async = enable;
431 /* A wrapper for WaitForSingleObject that issues a warning if
432 something unusual happens. */
433 static void
434 wait_for_single (HANDLE handle, DWORD howlong)
436 while (true)
438 DWORD r = WaitForSingleObject (handle, howlong);
439 if (r == WAIT_OBJECT_0)
440 return;
441 if (r == WAIT_FAILED)
443 unsigned err = (unsigned) GetLastError ();
444 warning ("WaitForSingleObject failed (code %u): %s",
445 err, strwinerror (err));
447 else
448 warning ("unexpected result from WaitForSingleObject: %u",
449 (unsigned) r);
453 DWORD WINAPI
454 windows_nat_target::process_thread_starter (LPVOID self)
456 ((windows_nat_target *) self)->process_thread ();
457 return 0;
460 void
461 windows_nat_target::process_thread ()
463 while (true)
465 wait_for_single (m_pushed_event, INFINITE);
467 gdb::function_view<bool ()> func = std::move (m_queue.front ());
468 m_queue.pop ();
470 bool should_wait = func ();
471 SetEvent (m_response_event);
473 if (should_wait)
475 if (!m_debug_event_pending)
477 wait_for_debug_event (&m_last_debug_event, INFINITE);
478 m_debug_event_pending = true;
480 serial_event_set (m_wait_event);
485 void
486 windows_nat_target::do_synchronously (gdb::function_view<bool ()> func)
488 m_queue.emplace (std::move (func));
489 SetEvent (m_pushed_event);
490 wait_for_single (m_response_event, INFINITE);
493 void
494 windows_nat_target::wait_for_debug_event_main_thread (DEBUG_EVENT *event)
496 do_synchronously ([&] ()
498 if (m_debug_event_pending)
500 *event = m_last_debug_event;
501 m_debug_event_pending = false;
502 serial_event_clear (m_wait_event);
504 else
505 wait_for_debug_event (event, INFINITE);
506 return false;
510 /* See nat/windows-nat.h. */
512 windows_thread_info *
513 windows_per_inferior::thread_rec
514 (ptid_t ptid, thread_disposition_type disposition)
516 for (auto &th : thread_list)
517 if (th->tid == ptid.lwp ())
519 if (!th->suspended)
521 switch (disposition)
523 case DONT_INVALIDATE_CONTEXT:
524 /* Nothing. */
525 break;
526 case INVALIDATE_CONTEXT:
527 if (ptid.lwp () != current_event.dwThreadId)
528 th->suspend ();
529 th->reload_context = true;
530 break;
531 case DONT_SUSPEND:
532 th->reload_context = true;
533 th->suspended = -1;
534 break;
537 return th.get ();
540 return NULL;
543 /* Add a thread to the thread list.
545 PTID is the ptid of the thread to be added.
546 H is its Windows handle.
547 TLB is its thread local base.
548 MAIN_THREAD_P should be true if the thread to be added is
549 the main thread, false otherwise. */
551 windows_thread_info *
552 windows_nat_target::add_thread (ptid_t ptid, HANDLE h, void *tlb,
553 bool main_thread_p)
555 windows_thread_info *th;
557 gdb_assert (ptid.lwp () != 0);
559 if ((th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT)))
560 return th;
562 CORE_ADDR base = (CORE_ADDR) (uintptr_t) tlb;
563 #ifdef __x86_64__
564 /* For WOW64 processes, this is actually the pointer to the 64bit TIB,
565 and the 32bit TIB is exactly 2 pages after it. */
566 if (windows_process.wow64_process)
567 base += 0x2000;
568 #endif
569 th = new windows_thread_info (ptid.lwp (), h, base);
570 windows_process.thread_list.emplace_back (th);
572 /* Add this new thread to the list of threads.
574 To be consistent with what's done on other platforms, we add
575 the main thread silently (in reality, this thread is really
576 more of a process to the user than a thread). */
577 if (main_thread_p)
578 add_thread_silent (this, ptid);
579 else
580 ::add_thread (this, ptid);
582 /* It's simplest to always set this and update the debug
583 registers. */
584 th->debug_registers_changed = true;
586 return th;
589 /* Clear out any old thread list and reinitialize it to a
590 pristine state. */
591 static void
592 windows_init_thread_list (void)
594 DEBUG_EVENTS ("called");
595 windows_process.thread_list.clear ();
598 /* Delete a thread from the list of threads.
600 PTID is the ptid of the thread to be deleted.
601 EXIT_CODE is the thread's exit code.
602 MAIN_THREAD_P should be true if the thread to be deleted is
603 the main thread, false otherwise. */
605 void
606 windows_nat_target::delete_thread (ptid_t ptid, DWORD exit_code,
607 bool main_thread_p)
609 DWORD id;
611 gdb_assert (ptid.lwp () != 0);
613 id = ptid.lwp ();
615 /* Note that no notification was printed when the main thread was
616 created, and thus, unless in verbose mode, we should be symmetrical,
617 and avoid an exit notification for the main thread here as well. */
619 bool silent = (main_thread_p && !info_verbose);
620 thread_info *to_del = this->find_thread (ptid);
621 delete_thread_with_exit_code (to_del, exit_code, silent);
623 auto iter = std::find_if (windows_process.thread_list.begin (),
624 windows_process.thread_list.end (),
625 [=] (std::unique_ptr<windows_thread_info> &th)
627 return th->tid == id;
630 if (iter != windows_process.thread_list.end ())
631 windows_process.thread_list.erase (iter);
634 /* Fetches register number R from the given windows_thread_info,
635 and supplies its value to the given regcache.
637 This function assumes that R is non-negative. A failed assertion
638 is raised if that is not true.
640 This function assumes that TH->RELOAD_CONTEXT is not set, meaning
641 that the windows_thread_info has an up-to-date context. A failed
642 assertion is raised if that assumption is violated. */
644 static void
645 windows_fetch_one_register (struct regcache *regcache,
646 windows_thread_info *th, int r)
648 gdb_assert (r >= 0);
649 gdb_assert (!th->reload_context);
651 char *context_ptr = (char *) &th->context;
652 #ifdef __x86_64__
653 if (windows_process.wow64_process)
654 context_ptr = (char *) &th->wow64_context;
655 #endif
657 char *context_offset = context_ptr + windows_process.mappings[r];
658 struct gdbarch *gdbarch = regcache->arch ();
659 i386_gdbarch_tdep *tdep = gdbarch_tdep<i386_gdbarch_tdep> (gdbarch);
661 gdb_assert (!gdbarch_read_pc_p (gdbarch));
662 gdb_assert (gdbarch_pc_regnum (gdbarch) >= 0);
663 gdb_assert (!gdbarch_write_pc_p (gdbarch));
665 /* GDB treats some registers as 32-bit, where they are in fact only
666 16 bits long. These cases must be handled specially to avoid
667 reading extraneous bits from the context. */
668 if (r == I387_FISEG_REGNUM (tdep) || windows_process.segment_register_p (r))
670 gdb_byte bytes[4] = {};
671 memcpy (bytes, context_offset, 2);
672 regcache->raw_supply (r, bytes);
674 else if (r == I387_FOP_REGNUM (tdep))
676 long l = (*((long *) context_offset) >> 16) & ((1 << 11) - 1);
677 regcache->raw_supply (r, &l);
679 else
681 if (th->stopped_at_software_breakpoint
682 && !th->pc_adjusted
683 && r == gdbarch_pc_regnum (gdbarch))
685 int size = register_size (gdbarch, r);
686 if (size == 4)
688 uint32_t value;
689 memcpy (&value, context_offset, size);
690 value -= gdbarch_decr_pc_after_break (gdbarch);
691 memcpy (context_offset, &value, size);
693 else
695 gdb_assert (size == 8);
696 uint64_t value;
697 memcpy (&value, context_offset, size);
698 value -= gdbarch_decr_pc_after_break (gdbarch);
699 memcpy (context_offset, &value, size);
701 /* Make sure we only rewrite the PC a single time. */
702 th->pc_adjusted = true;
704 regcache->raw_supply (r, context_offset);
708 void
709 windows_nat_target::fetch_registers (struct regcache *regcache, int r)
711 windows_thread_info *th
712 = windows_process.thread_rec (regcache->ptid (), INVALIDATE_CONTEXT);
714 /* Check if TH exists. Windows sometimes uses a non-existent
715 thread id in its events. */
716 if (th == NULL)
717 return;
719 if (th->reload_context)
721 #ifdef __CYGWIN__
722 if (windows_process.have_saved_context)
724 /* Lie about where the program actually is stopped since
725 cygwin has informed us that we should consider the signal
726 to have occurred at another location which is stored in
727 "saved_context. */
728 memcpy (&th->context, &windows_process.saved_context,
729 __COPY_CONTEXT_SIZE);
730 windows_process.have_saved_context = 0;
732 else
733 #endif
734 #ifdef __x86_64__
735 if (windows_process.wow64_process)
737 th->wow64_context.ContextFlags = CONTEXT_DEBUGGER_DR;
738 CHECK (Wow64GetThreadContext (th->h, &th->wow64_context));
739 /* Copy dr values from that thread.
740 But only if there were not modified since last stop.
741 PR gdb/2388 */
742 if (!th->debug_registers_changed)
744 windows_process.dr[0] = th->wow64_context.Dr0;
745 windows_process.dr[1] = th->wow64_context.Dr1;
746 windows_process.dr[2] = th->wow64_context.Dr2;
747 windows_process.dr[3] = th->wow64_context.Dr3;
748 windows_process.dr[6] = th->wow64_context.Dr6;
749 windows_process.dr[7] = th->wow64_context.Dr7;
752 else
753 #endif
755 th->context.ContextFlags = CONTEXT_DEBUGGER_DR;
756 CHECK (GetThreadContext (th->h, &th->context));
757 /* Copy dr values from that thread.
758 But only if there were not modified since last stop.
759 PR gdb/2388 */
760 if (!th->debug_registers_changed)
762 windows_process.dr[0] = th->context.Dr0;
763 windows_process.dr[1] = th->context.Dr1;
764 windows_process.dr[2] = th->context.Dr2;
765 windows_process.dr[3] = th->context.Dr3;
766 windows_process.dr[6] = th->context.Dr6;
767 windows_process.dr[7] = th->context.Dr7;
770 th->reload_context = false;
773 if (r < 0)
774 for (r = 0; r < gdbarch_num_regs (regcache->arch()); r++)
775 windows_fetch_one_register (regcache, th, r);
776 else
777 windows_fetch_one_register (regcache, th, r);
780 /* Collect the register number R from the given regcache, and store
781 its value into the corresponding area of the given thread's context.
783 This function assumes that R is non-negative. A failed assertion
784 assertion is raised if that is not true. */
786 static void
787 windows_store_one_register (const struct regcache *regcache,
788 windows_thread_info *th, int r)
790 gdb_assert (r >= 0);
792 char *context_ptr = (char *) &th->context;
793 #ifdef __x86_64__
794 if (windows_process.wow64_process)
795 context_ptr = (char *) &th->wow64_context;
796 #endif
798 struct gdbarch *gdbarch = regcache->arch ();
799 i386_gdbarch_tdep *tdep = gdbarch_tdep<i386_gdbarch_tdep> (gdbarch);
801 /* GDB treats some registers as 32-bit, where they are in fact only
802 16 bits long. These cases must be handled specially to avoid
803 overwriting other registers in the context. */
804 if (r == I387_FISEG_REGNUM (tdep) || windows_process.segment_register_p (r))
806 gdb_byte bytes[4];
807 regcache->raw_collect (r, bytes);
808 memcpy (context_ptr + windows_process.mappings[r], bytes, 2);
810 else if (r == I387_FOP_REGNUM (tdep))
812 gdb_byte bytes[4];
813 regcache->raw_collect (r, bytes);
814 /* The value of FOP occupies the top two bytes in the context,
815 so write the two low-order bytes from the cache into the
816 appropriate spot. */
817 memcpy (context_ptr + windows_process.mappings[r] + 2, bytes, 2);
819 else
820 regcache->raw_collect (r, context_ptr + windows_process.mappings[r]);
823 /* Store a new register value into the context of the thread tied to
824 REGCACHE. */
826 void
827 windows_nat_target::store_registers (struct regcache *regcache, int r)
829 windows_thread_info *th
830 = windows_process.thread_rec (regcache->ptid (), INVALIDATE_CONTEXT);
832 /* Check if TH exists. Windows sometimes uses a non-existent
833 thread id in its events. */
834 if (th == NULL)
835 return;
837 if (r < 0)
838 for (r = 0; r < gdbarch_num_regs (regcache->arch ()); r++)
839 windows_store_one_register (regcache, th, r);
840 else
841 windows_store_one_register (regcache, th, r);
844 /* See nat/windows-nat.h. */
846 static windows_solib *
847 windows_make_so (const char *name, LPVOID load_addr)
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");
877 #else
878 wchar_t buf[__PMAX];
880 buf[0] = 0;
881 if (access (name, F_OK) != 0)
883 if (strcasecmp (name, "ntdll.dll") == 0)
885 GetSystemDirectoryW (buf, sizeof (buf) / sizeof (wchar_t));
886 wcscat (buf, L"\\ntdll.dll");
889 #endif
890 windows_process.solibs.emplace_back ();
891 windows_solib *so = &windows_process.solibs.back ();
892 so->load_addr = load_addr;
893 so->original_name = name;
894 #ifndef __CYGWIN__
895 so->name = buf;
896 #else
897 if (buf[0])
899 char cname[SO_NAME_MAX_PATH_SIZE];
900 cygwin_conv_path (CCP_WIN_W_TO_POSIX, buf, cname,
901 SO_NAME_MAX_PATH_SIZE);
902 so->name = cname;
904 else
906 char *rname = realpath (name, NULL);
907 if (rname && strlen (rname) < SO_NAME_MAX_PATH_SIZE)
909 so->name = rname;
910 free (rname);
912 else
914 warning (_("dll path for \"%s\" too long or inaccessible"), name);
915 so->name = so->original_name;
918 /* Record cygwin1.dll .text start/end. */
919 size_t len = sizeof ("/cygwin1.dll") - 1;
920 if (so->name.size () >= len
921 && strcasecmp (so->name.c_str () + so->name.size () - len,
922 "/cygwin1.dll") == 0)
924 asection *text = NULL;
926 gdb_bfd_ref_ptr abfd (gdb_bfd_open (so->name.c_str(), "pei-i386"));
928 if (abfd == NULL)
929 return so;
931 if (bfd_check_format (abfd.get (), bfd_object))
932 text = bfd_get_section_by_name (abfd.get (), ".text");
934 if (!text)
935 return so;
937 /* The symbols in a dll are offset by 0x1000, which is the
938 offset from 0 of the first byte in an image - because of the
939 file header and the section alignment. */
940 windows_process.cygwin_load_start = (CORE_ADDR) (uintptr_t) ((char *)
941 load_addr + 0x1000);
942 windows_process.cygwin_load_end = windows_process.cygwin_load_start +
943 bfd_section_size (text);
945 #endif
947 return so;
950 /* See nat/windows-nat.h. */
952 void
953 windows_per_inferior::handle_load_dll (const char *dll_name, LPVOID base)
955 windows_solib *solib = windows_make_so (dll_name, base);
956 DEBUG_EVENTS ("Loading dll \"%s\" at %s.", solib->name.c_str (),
957 host_address_to_string (solib->load_addr));
960 /* See nat/windows-nat.h. */
962 void
963 windows_per_inferior::handle_unload_dll ()
965 LPVOID lpBaseOfDll = current_event.u.UnloadDll.lpBaseOfDll;
967 auto iter = std::remove_if (windows_process.solibs.begin (),
968 windows_process.solibs.end (),
969 [&] (windows_solib &lib)
971 if (lib.load_addr == lpBaseOfDll)
973 DEBUG_EVENTS ("Unloading dll \"%s\".", lib.name.c_str ());
974 return true;
976 return false;
979 if (iter != windows_process.solibs.end ())
981 windows_process.solibs.erase (iter, windows_process.solibs.end ());
982 return;
985 /* We did not find any DLL that was previously loaded at this address,
986 so register a complaint. We do not report an error, because we have
987 observed that this may be happening under some circumstances. For
988 instance, running 32bit applications on x64 Windows causes us to receive
989 4 mysterious UNLOAD_DLL_DEBUG_EVENTs during the startup phase (these
990 events are apparently caused by the WOW layer, the interface between
991 32bit and 64bit worlds). */
992 complaint (_("dll starting at %s not found."),
993 host_address_to_string (lpBaseOfDll));
996 /* Clear list of loaded DLLs. */
997 static void
998 windows_clear_solib (void)
1000 windows_process.solibs.clear ();
1003 static void
1004 signal_event_command (const char *args, int from_tty)
1006 uintptr_t event_id = 0;
1007 char *endargs = NULL;
1009 if (args == NULL)
1010 error (_("signal-event requires an argument (integer event id)"));
1012 event_id = strtoumax (args, &endargs, 10);
1014 if ((errno == ERANGE) || (event_id == 0) || (event_id > UINTPTR_MAX) ||
1015 ((HANDLE) event_id == INVALID_HANDLE_VALUE))
1016 error (_("Failed to convert `%s' to event id"), args);
1018 SetEvent ((HANDLE) event_id);
1019 CloseHandle ((HANDLE) event_id);
1022 /* See nat/windows-nat.h. */
1025 windows_per_inferior::handle_output_debug_string
1026 (struct target_waitstatus *ourstatus)
1028 int retval = 0;
1030 gdb::unique_xmalloc_ptr<char> s
1031 = (target_read_string
1032 ((CORE_ADDR) (uintptr_t) current_event.u.DebugString.lpDebugStringData,
1033 1024));
1034 if (s == nullptr || !*(s.get ()))
1035 /* nothing to do */;
1036 else if (!startswith (s.get (), _CYGWIN_SIGNAL_STRING))
1038 #ifdef __CYGWIN__
1039 if (!startswith (s.get (), "cYg"))
1040 #endif
1042 char *p = strchr (s.get (), '\0');
1044 if (p > s.get () && *--p == '\n')
1045 *p = '\0';
1046 warning (("%s"), s.get ());
1049 #ifdef __CYGWIN__
1050 else
1052 /* Got a cygwin signal marker. A cygwin signal is followed by
1053 the signal number itself and then optionally followed by the
1054 thread id and address to saved context within the DLL. If
1055 these are supplied, then the given thread is assumed to have
1056 issued the signal and the context from the thread is assumed
1057 to be stored at the given address in the inferior. Tell gdb
1058 to treat this like a real signal. */
1059 char *p;
1060 int sig = strtol (s.get () + sizeof (_CYGWIN_SIGNAL_STRING) - 1, &p, 0);
1061 gdb_signal gotasig = gdb_signal_from_host (sig);
1063 if (gotasig)
1065 LPCVOID x;
1066 SIZE_T n;
1068 ourstatus->set_stopped (gotasig);
1069 retval = strtoul (p, &p, 0);
1070 if (!retval)
1071 retval = current_event.dwThreadId;
1072 else if ((x = (LPCVOID) (uintptr_t) strtoull (p, NULL, 0))
1073 && ReadProcessMemory (handle, x,
1074 &saved_context,
1075 __COPY_CONTEXT_SIZE, &n)
1076 && n == __COPY_CONTEXT_SIZE)
1077 have_saved_context = 1;
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 return TRUE;
1374 /* Called in pathological case where Windows fails to send a
1375 CREATE_PROCESS_DEBUG_EVENT after an attach. */
1376 DWORD
1377 windows_nat_target::fake_create_process ()
1379 windows_process.handle
1380 = OpenProcess (PROCESS_ALL_ACCESS, FALSE,
1381 windows_process.current_event.dwProcessId);
1382 if (windows_process.handle != NULL)
1383 windows_process.open_process_used = 1;
1384 else
1386 unsigned err = (unsigned) GetLastError ();
1387 throw_winerror_with_name (_("OpenProcess call failed"), err);
1388 /* We can not debug anything in that case. */
1390 add_thread (ptid_t (windows_process.current_event.dwProcessId, 0,
1391 windows_process.current_event.dwThreadId),
1392 windows_process.current_event.u.CreateThread.hThread,
1393 windows_process.current_event.u.CreateThread.lpThreadLocalBase,
1394 true /* main_thread_p */);
1395 return windows_process.current_event.dwThreadId;
1398 void
1399 windows_nat_target::resume (ptid_t ptid, int step, enum gdb_signal sig)
1401 windows_thread_info *th;
1402 DWORD continue_status = DBG_CONTINUE;
1404 /* A specific PTID means `step only this thread id'. */
1405 int resume_all = ptid == minus_one_ptid;
1407 /* If we're continuing all threads, it's the current inferior that
1408 should be handled specially. */
1409 if (resume_all)
1410 ptid = inferior_ptid;
1412 if (sig != GDB_SIGNAL_0)
1414 if (windows_process.current_event.dwDebugEventCode
1415 != EXCEPTION_DEBUG_EVENT)
1417 DEBUG_EXCEPT ("Cannot continue with signal %d here.", sig);
1419 else if (sig == windows_process.last_sig)
1420 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1421 else
1422 #if 0
1423 /* This code does not seem to work, because
1424 the kernel does probably not consider changes in the ExceptionRecord
1425 structure when passing the exception to the inferior.
1426 Note that this seems possible in the exception handler itself. */
1428 for (const xlate_exception &x : xlate)
1429 if (x.us == sig)
1431 current_event.u.Exception.ExceptionRecord.ExceptionCode
1432 = x.them;
1433 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1434 break;
1436 if (continue_status == DBG_CONTINUE)
1438 DEBUG_EXCEPT ("Cannot continue with signal %d.", sig);
1441 #endif
1442 DEBUG_EXCEPT ("Can only continue with received signal %d.",
1443 windows_process.last_sig);
1446 windows_process.last_sig = GDB_SIGNAL_0;
1448 DEBUG_EXEC ("pid=%d, tid=0x%x, step=%d, sig=%d",
1449 ptid.pid (), (unsigned) ptid.lwp (), step, sig);
1451 /* Get context for currently selected thread. */
1452 th = windows_process.thread_rec (inferior_ptid, DONT_INVALIDATE_CONTEXT);
1453 if (th)
1455 #ifdef __x86_64__
1456 if (windows_process.wow64_process)
1458 if (step)
1460 /* Single step by setting t bit. */
1461 regcache *regcache = get_thread_regcache (inferior_thread ());
1462 struct gdbarch *gdbarch = regcache->arch ();
1463 fetch_registers (regcache, gdbarch_ps_regnum (gdbarch));
1464 th->wow64_context.EFlags |= FLAG_TRACE_BIT;
1467 if (th->wow64_context.ContextFlags)
1469 if (th->debug_registers_changed)
1471 th->wow64_context.Dr0 = windows_process.dr[0];
1472 th->wow64_context.Dr1 = windows_process.dr[1];
1473 th->wow64_context.Dr2 = windows_process.dr[2];
1474 th->wow64_context.Dr3 = windows_process.dr[3];
1475 th->wow64_context.Dr6 = DR6_CLEAR_VALUE;
1476 th->wow64_context.Dr7 = windows_process.dr[7];
1477 th->debug_registers_changed = false;
1479 CHECK (Wow64SetThreadContext (th->h, &th->wow64_context));
1480 th->wow64_context.ContextFlags = 0;
1483 else
1484 #endif
1486 if (step)
1488 /* Single step by setting t bit. */
1489 regcache *regcache = get_thread_regcache (inferior_thread ());
1490 struct gdbarch *gdbarch = regcache->arch ();
1491 fetch_registers (regcache, gdbarch_ps_regnum (gdbarch));
1492 th->context.EFlags |= FLAG_TRACE_BIT;
1495 if (th->context.ContextFlags)
1497 if (th->debug_registers_changed)
1499 th->context.Dr0 = windows_process.dr[0];
1500 th->context.Dr1 = windows_process.dr[1];
1501 th->context.Dr2 = windows_process.dr[2];
1502 th->context.Dr3 = windows_process.dr[3];
1503 th->context.Dr6 = DR6_CLEAR_VALUE;
1504 th->context.Dr7 = windows_process.dr[7];
1505 th->debug_registers_changed = false;
1507 CHECK (SetThreadContext (th->h, &th->context));
1508 th->context.ContextFlags = 0;
1513 /* Allow continuing with the same signal that interrupted us.
1514 Otherwise complain. */
1516 if (resume_all)
1517 windows_continue (continue_status, -1, 0);
1518 else
1519 windows_continue (continue_status, ptid.lwp (), 0);
1522 /* Interrupt the inferior. */
1524 void
1525 windows_nat_target::interrupt ()
1527 DEBUG_EVENTS ("interrupt");
1528 #ifdef __x86_64__
1529 if (windows_process.wow64_process)
1531 /* Call DbgUiRemoteBreakin of the 32bit ntdll.dll in the target process.
1532 DebugBreakProcess would call the one of the 64bit ntdll.dll, which
1533 can't be correctly handled by gdb. */
1534 if (windows_process.wow64_dbgbreak == nullptr)
1536 CORE_ADDR addr;
1537 if (!find_minimal_symbol_address ("ntdll!DbgUiRemoteBreakin",
1538 &addr, 0))
1539 windows_process.wow64_dbgbreak = (void *) addr;
1542 if (windows_process.wow64_dbgbreak != nullptr)
1544 HANDLE thread = CreateRemoteThread (windows_process.handle, NULL,
1545 0, (LPTHREAD_START_ROUTINE)
1546 windows_process.wow64_dbgbreak,
1547 NULL, 0, NULL);
1548 if (thread)
1550 CloseHandle (thread);
1551 return;
1555 else
1556 #endif
1557 if (DebugBreakProcess (windows_process.handle))
1558 return;
1559 warning (_("Could not interrupt program. "
1560 "Press Ctrl-c in the program console."));
1563 void
1564 windows_nat_target::pass_ctrlc ()
1566 interrupt ();
1569 /* Get the next event from the child. Returns the thread ptid. */
1571 ptid_t
1572 windows_nat_target::get_windows_debug_event
1573 (int pid, struct target_waitstatus *ourstatus, target_wait_flags options)
1575 DWORD continue_status, event_code;
1576 DWORD thread_id = 0;
1578 /* If there is a relevant pending stop, report it now. See the
1579 comment by the definition of "pending_stops" for details on why
1580 this is needed. */
1581 std::optional<pending_stop> stop
1582 = windows_process.fetch_pending_stop (debug_events);
1583 if (stop.has_value ())
1585 thread_id = stop->thread_id;
1586 *ourstatus = stop->status;
1588 ptid_t ptid (windows_process.current_event.dwProcessId, thread_id);
1589 windows_thread_info *th
1590 = windows_process.thread_rec (ptid, INVALIDATE_CONTEXT);
1591 th->reload_context = true;
1593 return ptid;
1596 windows_process.last_sig = GDB_SIGNAL_0;
1597 DEBUG_EVENT *current_event = &windows_process.current_event;
1599 if ((options & TARGET_WNOHANG) != 0 && !m_debug_event_pending)
1601 ourstatus->set_ignore ();
1602 return minus_one_ptid;
1605 wait_for_debug_event_main_thread (&windows_process.current_event);
1607 continue_status = DBG_CONTINUE;
1609 event_code = windows_process.current_event.dwDebugEventCode;
1610 ourstatus->set_spurious ();
1611 windows_process.have_saved_context = 0;
1613 switch (event_code)
1615 case CREATE_THREAD_DEBUG_EVENT:
1616 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1617 (unsigned) current_event->dwProcessId,
1618 (unsigned) current_event->dwThreadId,
1619 "CREATE_THREAD_DEBUG_EVENT");
1620 if (windows_process.saw_create != 1)
1622 inferior *inf = find_inferior_pid (this, current_event->dwProcessId);
1623 if (!windows_process.saw_create && inf->attach_flag)
1625 /* Kludge around a Windows bug where first event is a create
1626 thread event. Caused when attached process does not have
1627 a main thread. */
1628 thread_id = fake_create_process ();
1629 if (thread_id)
1630 windows_process.saw_create++;
1632 break;
1634 /* Record the existence of this thread. */
1635 thread_id = current_event->dwThreadId;
1636 add_thread
1637 (ptid_t (current_event->dwProcessId, current_event->dwThreadId, 0),
1638 current_event->u.CreateThread.hThread,
1639 current_event->u.CreateThread.lpThreadLocalBase,
1640 false /* main_thread_p */);
1642 break;
1644 case EXIT_THREAD_DEBUG_EVENT:
1645 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1646 (unsigned) current_event->dwProcessId,
1647 (unsigned) current_event->dwThreadId,
1648 "EXIT_THREAD_DEBUG_EVENT");
1649 delete_thread (ptid_t (current_event->dwProcessId,
1650 current_event->dwThreadId, 0),
1651 current_event->u.ExitThread.dwExitCode,
1652 false /* main_thread_p */);
1653 break;
1655 case CREATE_PROCESS_DEBUG_EVENT:
1656 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1657 (unsigned) current_event->dwProcessId,
1658 (unsigned) current_event->dwThreadId,
1659 "CREATE_PROCESS_DEBUG_EVENT");
1660 CloseHandle (current_event->u.CreateProcessInfo.hFile);
1661 if (++windows_process.saw_create != 1)
1662 break;
1664 windows_process.handle = current_event->u.CreateProcessInfo.hProcess;
1665 /* Add the main thread. */
1666 add_thread
1667 (ptid_t (current_event->dwProcessId,
1668 current_event->dwThreadId, 0),
1669 current_event->u.CreateProcessInfo.hThread,
1670 current_event->u.CreateProcessInfo.lpThreadLocalBase,
1671 true /* main_thread_p */);
1672 thread_id = current_event->dwThreadId;
1673 break;
1675 case EXIT_PROCESS_DEBUG_EVENT:
1676 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1677 (unsigned) current_event->dwProcessId,
1678 (unsigned) current_event->dwThreadId,
1679 "EXIT_PROCESS_DEBUG_EVENT");
1680 if (!windows_process.windows_initialization_done)
1682 target_terminal::ours ();
1683 target_mourn_inferior (inferior_ptid);
1684 error (_("During startup program exited with code 0x%x."),
1685 (unsigned int) current_event->u.ExitProcess.dwExitCode);
1687 else if (windows_process.saw_create == 1)
1689 delete_thread (ptid_t (current_event->dwProcessId,
1690 current_event->dwThreadId, 0),
1691 0, true /* main_thread_p */);
1692 DWORD exit_status = current_event->u.ExitProcess.dwExitCode;
1693 /* If the exit status looks like a fatal exception, but we
1694 don't recognize the exception's code, make the original
1695 exit status value available, to avoid losing
1696 information. */
1697 int exit_signal
1698 = WIFSIGNALED (exit_status) ? WTERMSIG (exit_status) : -1;
1699 if (exit_signal == -1)
1700 ourstatus->set_exited (exit_status);
1701 else
1702 ourstatus->set_signalled (gdb_signal_from_host (exit_signal));
1704 thread_id = current_event->dwThreadId;
1706 break;
1708 case LOAD_DLL_DEBUG_EVENT:
1709 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1710 (unsigned) current_event->dwProcessId,
1711 (unsigned) current_event->dwThreadId,
1712 "LOAD_DLL_DEBUG_EVENT");
1713 CloseHandle (current_event->u.LoadDll.hFile);
1714 if (windows_process.saw_create != 1
1715 || ! windows_process.windows_initialization_done)
1716 break;
1719 windows_process.dll_loaded_event ();
1721 catch (const gdb_exception &ex)
1723 exception_print (gdb_stderr, ex);
1725 ourstatus->set_loaded ();
1726 thread_id = current_event->dwThreadId;
1727 break;
1729 case UNLOAD_DLL_DEBUG_EVENT:
1730 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1731 (unsigned) current_event->dwProcessId,
1732 (unsigned) current_event->dwThreadId,
1733 "UNLOAD_DLL_DEBUG_EVENT");
1734 if (windows_process.saw_create != 1
1735 || ! windows_process.windows_initialization_done)
1736 break;
1739 windows_process.handle_unload_dll ();
1741 catch (const gdb_exception &ex)
1743 exception_print (gdb_stderr, ex);
1745 ourstatus->set_loaded ();
1746 thread_id = current_event->dwThreadId;
1747 break;
1749 case EXCEPTION_DEBUG_EVENT:
1750 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1751 (unsigned) current_event->dwProcessId,
1752 (unsigned) current_event->dwThreadId,
1753 "EXCEPTION_DEBUG_EVENT");
1754 if (windows_process.saw_create != 1)
1755 break;
1756 switch (windows_process.handle_exception (ourstatus, debug_exceptions))
1758 case HANDLE_EXCEPTION_UNHANDLED:
1759 default:
1760 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1761 break;
1762 case HANDLE_EXCEPTION_HANDLED:
1763 thread_id = current_event->dwThreadId;
1764 break;
1765 case HANDLE_EXCEPTION_IGNORED:
1766 continue_status = DBG_CONTINUE;
1767 break;
1769 break;
1771 case OUTPUT_DEBUG_STRING_EVENT: /* Message from the kernel. */
1772 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1773 (unsigned) current_event->dwProcessId,
1774 (unsigned) current_event->dwThreadId,
1775 "OUTPUT_DEBUG_STRING_EVENT");
1776 if (windows_process.saw_create != 1)
1777 break;
1778 thread_id = windows_process.handle_output_debug_string (ourstatus);
1779 break;
1781 default:
1782 if (windows_process.saw_create != 1)
1783 break;
1784 gdb_printf ("gdb: kernel event for pid=%u tid=0x%x\n",
1785 (unsigned) current_event->dwProcessId,
1786 (unsigned) current_event->dwThreadId);
1787 gdb_printf (" unknown event code %u\n",
1788 (unsigned) current_event->dwDebugEventCode);
1789 break;
1792 if (!thread_id || windows_process.saw_create != 1)
1794 CHECK (windows_continue (continue_status,
1795 windows_process.desired_stop_thread_id, 0));
1797 else if (windows_process.desired_stop_thread_id != -1
1798 && windows_process.desired_stop_thread_id != thread_id)
1800 /* Pending stop. See the comment by the definition of
1801 "pending_stops" for details on why this is needed. */
1802 DEBUG_EVENTS ("get_windows_debug_event - "
1803 "unexpected stop in 0x%x (expecting 0x%x)",
1804 thread_id, windows_process.desired_stop_thread_id);
1806 if (current_event->dwDebugEventCode == EXCEPTION_DEBUG_EVENT
1807 && ((current_event->u.Exception.ExceptionRecord.ExceptionCode
1808 == EXCEPTION_BREAKPOINT)
1809 || (current_event->u.Exception.ExceptionRecord.ExceptionCode
1810 == STATUS_WX86_BREAKPOINT))
1811 && windows_process.windows_initialization_done)
1813 ptid_t ptid = ptid_t (current_event->dwProcessId, thread_id, 0);
1814 windows_thread_info *th
1815 = windows_process.thread_rec (ptid, INVALIDATE_CONTEXT);
1816 th->stopped_at_software_breakpoint = true;
1817 th->pc_adjusted = false;
1819 windows_process.pending_stops.push_back
1820 ({thread_id, *ourstatus, windows_process.current_event});
1821 thread_id = 0;
1822 CHECK (windows_continue (continue_status,
1823 windows_process.desired_stop_thread_id, 0));
1826 if (thread_id == 0)
1827 return null_ptid;
1828 return ptid_t (windows_process.current_event.dwProcessId, thread_id, 0);
1831 /* Wait for interesting events to occur in the target process. */
1832 ptid_t
1833 windows_nat_target::wait (ptid_t ptid, struct target_waitstatus *ourstatus,
1834 target_wait_flags options)
1836 int pid = -1;
1838 /* We loop when we get a non-standard exception rather than return
1839 with a SPURIOUS because resume can try and step or modify things,
1840 which needs a current_thread->h. But some of these exceptions mark
1841 the birth or death of threads, which mean that the current thread
1842 isn't necessarily what you think it is. */
1844 while (1)
1846 ptid_t result = get_windows_debug_event (pid, ourstatus, options);
1848 if (result != null_ptid)
1850 if (ourstatus->kind () != TARGET_WAITKIND_EXITED
1851 && ourstatus->kind () != TARGET_WAITKIND_SIGNALLED)
1853 windows_thread_info *th
1854 = windows_process.thread_rec (result, INVALIDATE_CONTEXT);
1856 if (th != nullptr)
1858 th->stopped_at_software_breakpoint = false;
1859 if (windows_process.current_event.dwDebugEventCode
1860 == EXCEPTION_DEBUG_EVENT
1861 && ((windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
1862 == EXCEPTION_BREAKPOINT)
1863 || (windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
1864 == STATUS_WX86_BREAKPOINT))
1865 && windows_process.windows_initialization_done)
1867 th->stopped_at_software_breakpoint = true;
1868 th->pc_adjusted = false;
1873 return result;
1875 else
1877 int detach = 0;
1879 if (deprecated_ui_loop_hook != NULL)
1880 detach = deprecated_ui_loop_hook (0);
1882 if (detach)
1883 kill ();
1888 void
1889 windows_nat_target::do_initial_windows_stuff (DWORD pid, bool attaching)
1891 int i;
1892 struct inferior *inf;
1894 windows_process.last_sig = GDB_SIGNAL_0;
1895 windows_process.open_process_used = 0;
1896 for (i = 0;
1897 i < sizeof (windows_process.dr) / sizeof (windows_process.dr[0]);
1898 i++)
1899 windows_process.dr[i] = 0;
1900 #ifdef __CYGWIN__
1901 windows_process.cygwin_load_start = 0;
1902 windows_process.cygwin_load_end = 0;
1903 #endif
1904 windows_process.current_event.dwProcessId = pid;
1905 memset (&windows_process.current_event, 0,
1906 sizeof (windows_process.current_event));
1907 inf = current_inferior ();
1908 if (!inf->target_is_pushed (this))
1909 inf->push_target (this);
1910 disable_breakpoints_in_shlibs ();
1911 windows_clear_solib ();
1912 clear_proceed_status (0);
1913 init_wait_for_inferior ();
1915 #ifdef __x86_64__
1916 windows_process.ignore_first_breakpoint
1917 = !attaching && windows_process.wow64_process;
1919 if (!windows_process.wow64_process)
1921 windows_process.mappings = amd64_mappings;
1922 windows_process.segment_register_p = amd64_windows_segment_register_p;
1924 else
1925 #endif
1927 windows_process.mappings = i386_mappings;
1928 windows_process.segment_register_p = i386_windows_segment_register_p;
1931 inferior_appeared (inf, pid);
1932 inf->attach_flag = attaching;
1934 target_terminal::init ();
1935 target_terminal::inferior ();
1937 windows_process.windows_initialization_done = 0;
1939 ptid_t last_ptid;
1941 while (1)
1943 struct target_waitstatus status;
1945 last_ptid = this->wait (minus_one_ptid, &status, 0);
1947 /* Note windows_wait returns TARGET_WAITKIND_SPURIOUS for thread
1948 events. */
1949 if (status.kind () != TARGET_WAITKIND_LOADED
1950 && status.kind () != TARGET_WAITKIND_SPURIOUS)
1951 break;
1953 this->resume (minus_one_ptid, 0, GDB_SIGNAL_0);
1956 switch_to_thread (this->find_thread (last_ptid));
1958 /* Now that the inferior has been started and all DLLs have been mapped,
1959 we can iterate over all DLLs and load them in.
1961 We avoid doing it any earlier because, on certain versions of Windows,
1962 LOAD_DLL_DEBUG_EVENTs are sometimes not complete. In particular,
1963 we have seen on Windows 8.1 that the ntdll.dll load event does not
1964 include the DLL name, preventing us from creating an associated SO.
1965 A possible explanation is that ntdll.dll might be mapped before
1966 the SO info gets created by the Windows system -- ntdll.dll is
1967 the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs
1968 do not seem to suffer from that problem.
1970 Rather than try to work around this sort of issue, it is much
1971 simpler to just ignore DLL load/unload events during the startup
1972 phase, and then process them all in one batch now. */
1973 windows_process.add_all_dlls ();
1975 windows_process.windows_initialization_done = 1;
1976 return;
1979 /* Try to set or remove a user privilege to the current process. Return -1
1980 if that fails, the previous setting of that privilege otherwise.
1982 This code is copied from the Cygwin source code and rearranged to allow
1983 dynamically loading of the needed symbols from advapi32 which is only
1984 available on NT/2K/XP. */
1985 static int
1986 set_process_privilege (const char *privilege, BOOL enable)
1988 HANDLE token_hdl = NULL;
1989 LUID restore_priv;
1990 TOKEN_PRIVILEGES new_priv, orig_priv;
1991 int ret = -1;
1992 DWORD size;
1994 if (!OpenProcessToken (GetCurrentProcess (),
1995 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
1996 &token_hdl))
1997 goto out;
1999 if (!LookupPrivilegeValueA (NULL, privilege, &restore_priv))
2000 goto out;
2002 new_priv.PrivilegeCount = 1;
2003 new_priv.Privileges[0].Luid = restore_priv;
2004 new_priv.Privileges[0].Attributes = enable ? SE_PRIVILEGE_ENABLED : 0;
2006 if (!AdjustTokenPrivileges (token_hdl, FALSE, &new_priv,
2007 sizeof orig_priv, &orig_priv, &size))
2008 goto out;
2009 #if 0
2010 /* Disabled, otherwise every `attach' in an unprivileged user session
2011 would raise the "Failed to get SE_DEBUG_NAME privilege" warning in
2012 windows_attach(). */
2013 /* AdjustTokenPrivileges returns TRUE even if the privilege could not
2014 be enabled. GetLastError () returns an correct error code, though. */
2015 if (enable && GetLastError () == ERROR_NOT_ALL_ASSIGNED)
2016 goto out;
2017 #endif
2019 ret = orig_priv.Privileges[0].Attributes == SE_PRIVILEGE_ENABLED ? 1 : 0;
2021 out:
2022 if (token_hdl)
2023 CloseHandle (token_hdl);
2025 return ret;
2028 /* Attach to process PID, then initialize for debugging it. */
2030 void
2031 windows_nat_target::attach (const char *args, int from_tty)
2033 DWORD pid;
2035 pid = parse_pid_to_attach (args);
2037 if (set_process_privilege (SE_DEBUG_NAME, TRUE) < 0)
2038 warning ("Failed to get SE_DEBUG_NAME privilege\n"
2039 "This can cause attach to fail on Windows NT/2K/XP");
2041 windows_init_thread_list ();
2042 windows_process.saw_create = 0;
2044 std::optional<unsigned> err;
2045 do_synchronously ([&] ()
2047 BOOL ok = DebugActiveProcess (pid);
2049 #ifdef __CYGWIN__
2050 if (!ok)
2052 /* Try fall back to Cygwin pid. */
2053 pid = cygwin_internal (CW_CYGWIN_PID_TO_WINPID, pid);
2055 if (pid > 0)
2056 ok = DebugActiveProcess (pid);
2058 #endif
2060 if (!ok)
2061 err = (unsigned) GetLastError ();
2063 return true;
2066 if (err.has_value ())
2068 std::string msg = string_printf (_("Can't attach to process %u"),
2069 (unsigned) pid);
2070 throw_winerror_with_name (msg.c_str (), *err);
2073 DebugSetProcessKillOnExit (FALSE);
2075 target_announce_attach (from_tty, pid);
2077 #ifdef __x86_64__
2078 HANDLE h = OpenProcess (PROCESS_QUERY_INFORMATION, FALSE, pid);
2079 if (h != NULL)
2081 BOOL wow64;
2082 if (IsWow64Process (h, &wow64))
2083 windows_process.wow64_process = wow64;
2084 CloseHandle (h);
2086 #endif
2088 do_initial_windows_stuff (pid, 1);
2089 target_terminal::ours ();
2092 void
2093 windows_nat_target::detach (inferior *inf, int from_tty)
2095 windows_continue (DBG_CONTINUE, -1, 0, true);
2097 std::optional<unsigned> err;
2098 do_synchronously ([&] ()
2100 if (!DebugActiveProcessStop (windows_process.current_event.dwProcessId))
2101 err = (unsigned) GetLastError ();
2102 else
2103 DebugSetProcessKillOnExit (FALSE);
2104 return false;
2107 if (err.has_value ())
2109 std::string msg
2110 = string_printf (_("Can't detach process %u"),
2111 (unsigned) windows_process.current_event.dwProcessId);
2112 throw_winerror_with_name (msg.c_str (), *err);
2115 target_announce_detach (from_tty);
2117 x86_cleanup_dregs ();
2118 switch_to_no_thread ();
2119 detach_inferior (inf);
2121 maybe_unpush_target ();
2124 /* The pid_to_exec_file target_ops method for this platform. */
2126 const char *
2127 windows_nat_target::pid_to_exec_file (int pid)
2129 return windows_process.pid_to_exec_file (pid);
2132 /* Print status information about what we're accessing. */
2134 void
2135 windows_nat_target::files_info ()
2137 struct inferior *inf = current_inferior ();
2139 gdb_printf ("\tUsing the running image of %s %s.\n",
2140 inf->attach_flag ? "attached" : "child",
2141 target_pid_to_str (ptid_t (inf->pid)).c_str ());
2144 /* Modify CreateProcess parameters for use of a new separate console.
2145 Parameters are:
2146 *FLAGS: DWORD parameter for general process creation flags.
2147 *SI: STARTUPINFO structure, for which the console window size and
2148 console buffer size is filled in if GDB is running in a console.
2149 to create the new console.
2150 The size of the used font is not available on all versions of
2151 Windows OS. Furthermore, the current font might not be the default
2152 font, but this is still better than before.
2153 If the windows and buffer sizes are computed,
2154 SI->DWFLAGS is changed so that this information is used
2155 by CreateProcess function. */
2157 static void
2158 windows_set_console_info (STARTUPINFO *si, DWORD *flags)
2160 HANDLE hconsole = CreateFile ("CONOUT$", GENERIC_READ | GENERIC_WRITE,
2161 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
2163 if (hconsole != INVALID_HANDLE_VALUE)
2165 CONSOLE_SCREEN_BUFFER_INFO sbinfo;
2166 COORD font_size;
2167 CONSOLE_FONT_INFO cfi;
2169 GetCurrentConsoleFont (hconsole, FALSE, &cfi);
2170 font_size = GetConsoleFontSize (hconsole, cfi.nFont);
2171 GetConsoleScreenBufferInfo(hconsole, &sbinfo);
2172 si->dwXSize = sbinfo.srWindow.Right - sbinfo.srWindow.Left + 1;
2173 si->dwYSize = sbinfo.srWindow.Bottom - sbinfo.srWindow.Top + 1;
2174 if (font_size.X)
2175 si->dwXSize *= font_size.X;
2176 else
2177 si->dwXSize *= 8;
2178 if (font_size.Y)
2179 si->dwYSize *= font_size.Y;
2180 else
2181 si->dwYSize *= 12;
2182 si->dwXCountChars = sbinfo.dwSize.X;
2183 si->dwYCountChars = sbinfo.dwSize.Y;
2184 si->dwFlags |= STARTF_USESIZE | STARTF_USECOUNTCHARS;
2186 *flags |= CREATE_NEW_CONSOLE;
2189 #ifndef __CYGWIN__
2190 /* Function called by qsort to sort environment strings. */
2192 static int
2193 envvar_cmp (const void *a, const void *b)
2195 const char **p = (const char **) a;
2196 const char **q = (const char **) b;
2197 return strcasecmp (*p, *q);
2199 #endif
2201 #ifdef __CYGWIN__
2202 static void
2203 clear_win32_environment (char **env)
2205 int i;
2206 size_t len;
2207 wchar_t *copy = NULL, *equalpos;
2209 for (i = 0; env[i] && *env[i]; i++)
2211 len = mbstowcs (NULL, env[i], 0) + 1;
2212 copy = (wchar_t *) xrealloc (copy, len * sizeof (wchar_t));
2213 mbstowcs (copy, env[i], len);
2214 equalpos = wcschr (copy, L'=');
2215 if (equalpos)
2216 *equalpos = L'\0';
2217 SetEnvironmentVariableW (copy, NULL);
2219 xfree (copy);
2221 #endif
2223 #ifndef __CYGWIN__
2225 /* Redirection of inferior I/O streams for native MS-Windows programs.
2226 Unlike on Unix, where this is handled by invoking the inferior via
2227 the shell, on MS-Windows we need to emulate the cmd.exe shell.
2229 The official documentation of the cmd.exe redirection features is here:
2231 http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx
2233 (That page talks about Windows XP, but there's no newer
2234 documentation, so we assume later versions of cmd.exe didn't change
2235 anything.)
2237 Caveat: the documentation on that page seems to include a few lies.
2238 For example, it describes strange constructs 1<&2 and 2<&1, which
2239 seem to work only when 1>&2 resp. 2>&1 would make sense, and so I
2240 think the cmd.exe parser of the redirection symbols simply doesn't
2241 care about the < vs > distinction in these cases. Therefore, the
2242 supported features are explicitly documented below.
2244 The emulation below aims at supporting all the valid use cases
2245 supported by cmd.exe, which include:
2247 < FILE redirect standard input from FILE
2248 0< FILE redirect standard input from FILE
2249 <&N redirect standard input from file descriptor N
2250 0<&N redirect standard input from file descriptor N
2251 > FILE redirect standard output to FILE
2252 >> FILE append standard output to FILE
2253 1>> FILE append standard output to FILE
2254 >&N redirect standard output to file descriptor N
2255 1>&N redirect standard output to file descriptor N
2256 >>&N append standard output to file descriptor N
2257 1>>&N append standard output to file descriptor N
2258 2> FILE redirect standard error to FILE
2259 2>> FILE append standard error to FILE
2260 2>&N redirect standard error to file descriptor N
2261 2>>&N append standard error to file descriptor N
2263 Note that using N > 2 in the above construct is supported, but
2264 requires that the corresponding file descriptor be open by some
2265 means elsewhere or outside GDB. Also note that using ">&0" or
2266 "<&2" will generally fail, because the file descriptor redirected
2267 from is normally open in an incompatible mode (e.g., FD 0 is open
2268 for reading only). IOW, use of such tricks is not recommended;
2269 you are on your own.
2271 We do NOT support redirection of file descriptors above 2, as in
2272 "3>SOME-FILE", because MinGW compiled programs don't (supporting
2273 that needs special handling in the startup code that MinGW
2274 doesn't have). Pipes are also not supported.
2276 As for invalid use cases, where the redirection contains some
2277 error, the emulation below will detect that and produce some
2278 error and/or failure. But the behavior in those cases is not
2279 bug-for-bug compatible with what cmd.exe does in those cases.
2280 That's because what cmd.exe does then is not well defined, and
2281 seems to be a side effect of the cmd.exe parsing of the command
2282 line more than anything else. For example, try redirecting to an
2283 invalid file name, as in "> foo:bar".
2285 There are also minor syntactic deviations from what cmd.exe does
2286 in some corner cases. For example, it doesn't support the likes
2287 of "> &foo" to mean redirect to file named literally "&foo"; we
2288 do support that here, because that, too, sounds like some issue
2289 with the cmd.exe parser. Another nicety is that we support
2290 redirection targets that use file names with forward slashes,
2291 something cmd.exe doesn't -- this comes in handy since GDB
2292 file-name completion can be used when typing the command line for
2293 the inferior. */
2295 /* Support routines for redirecting standard handles of the inferior. */
2297 /* Parse a single redirection spec, open/duplicate the specified
2298 file/fd, and assign the appropriate value to one of the 3 standard
2299 file descriptors. */
2300 static int
2301 redir_open (const char *redir_string, int *inp, int *out, int *err)
2303 int *fd, ref_fd = -2;
2304 int mode;
2305 const char *fname = redir_string + 1;
2306 int rc = *redir_string;
2308 switch (rc)
2310 case '0':
2311 fname++;
2312 [[fallthrough]];
2313 case '<':
2314 fd = inp;
2315 mode = O_RDONLY;
2316 break;
2317 case '1': case '2':
2318 fname++;
2319 [[fallthrough]];
2320 case '>':
2321 fd = (rc == '2') ? err : out;
2322 mode = O_WRONLY | O_CREAT;
2323 if (*fname == '>')
2325 fname++;
2326 mode |= O_APPEND;
2328 else
2329 mode |= O_TRUNC;
2330 break;
2331 default:
2332 return -1;
2335 if (*fname == '&' && '0' <= fname[1] && fname[1] <= '9')
2337 /* A reference to a file descriptor. */
2338 char *fdtail;
2339 ref_fd = (int) strtol (fname + 1, &fdtail, 10);
2340 if (fdtail > fname + 1 && *fdtail == '\0')
2342 /* Don't allow redirection when open modes are incompatible. */
2343 if ((ref_fd == 0 && (fd == out || fd == err))
2344 || ((ref_fd == 1 || ref_fd == 2) && fd == inp))
2346 errno = EPERM;
2347 return -1;
2349 if (ref_fd == 0)
2350 ref_fd = *inp;
2351 else if (ref_fd == 1)
2352 ref_fd = *out;
2353 else if (ref_fd == 2)
2354 ref_fd = *err;
2356 else
2358 errno = EBADF;
2359 return -1;
2362 else
2363 fname++; /* skip the separator space */
2364 /* If the descriptor is already open, close it. This allows
2365 multiple specs of redirections for the same stream, which is
2366 somewhat nonsensical, but still valid and supported by cmd.exe.
2367 (But cmd.exe only opens a single file in this case, the one
2368 specified by the last redirection spec on the command line.) */
2369 if (*fd >= 0)
2370 _close (*fd);
2371 if (ref_fd == -2)
2373 *fd = _open (fname, mode, _S_IREAD | _S_IWRITE);
2374 if (*fd < 0)
2375 return -1;
2377 else if (ref_fd == -1)
2378 *fd = -1; /* reset to default destination */
2379 else
2381 *fd = _dup (ref_fd);
2382 if (*fd < 0)
2383 return -1;
2385 /* _open just sets a flag for O_APPEND, which won't be passed to the
2386 inferior, so we need to actually move the file pointer. */
2387 if ((mode & O_APPEND) != 0)
2388 _lseek (*fd, 0L, SEEK_END);
2389 return 0;
2392 /* Canonicalize a single redirection spec and set up the corresponding
2393 file descriptor as specified. */
2394 static int
2395 redir_set_redirection (const char *s, int *inp, int *out, int *err)
2397 char buf[__PMAX + 2 + 5]; /* extra space for quotes & redirection string */
2398 char *d = buf;
2399 const char *start = s;
2400 int quote = 0;
2402 *d++ = *s++; /* copy the 1st character, < or > or a digit */
2403 if ((*start == '>' || *start == '1' || *start == '2')
2404 && *s == '>')
2406 *d++ = *s++;
2407 if (*s == '>' && *start != '>')
2408 *d++ = *s++;
2410 else if (*start == '0' && *s == '<')
2411 *d++ = *s++;
2412 /* cmd.exe recognizes "&N" only immediately after the redirection symbol. */
2413 if (*s != '&')
2415 while (isspace (*s)) /* skip whitespace before file name */
2416 s++;
2417 *d++ = ' '; /* separate file name with a single space */
2420 /* Copy the file name. */
2421 while (*s)
2423 /* Remove quoting characters from the file name in buf[]. */
2424 if (*s == '"') /* could support '..' quoting here */
2426 if (!quote)
2427 quote = *s++;
2428 else if (*s == quote)
2430 quote = 0;
2431 s++;
2433 else
2434 *d++ = *s++;
2436 else if (*s == '\\')
2438 if (s[1] == '"') /* could support '..' here */
2439 s++;
2440 *d++ = *s++;
2442 else if (isspace (*s) && !quote)
2443 break;
2444 else
2445 *d++ = *s++;
2446 if (d - buf >= sizeof (buf) - 1)
2448 errno = ENAMETOOLONG;
2449 return 0;
2452 *d = '\0';
2454 /* Windows doesn't allow redirection characters in file names, so we
2455 can bail out early if they use them, or if there's no target file
2456 name after the redirection symbol. */
2457 if (d[-1] == '>' || d[-1] == '<')
2459 errno = ENOENT;
2460 return 0;
2462 if (redir_open (buf, inp, out, err) == 0)
2463 return s - start;
2464 return 0;
2467 /* Parse the command line for redirection specs and prepare the file
2468 descriptors for the 3 standard streams accordingly. */
2469 static bool
2470 redirect_inferior_handles (const char *cmd_orig, char *cmd,
2471 int *inp, int *out, int *err)
2473 const char *s = cmd_orig;
2474 char *d = cmd;
2475 int quote = 0;
2476 bool retval = false;
2478 while (isspace (*s))
2479 *d++ = *s++;
2481 while (*s)
2483 if (*s == '"') /* could also support '..' quoting here */
2485 if (!quote)
2486 quote = *s;
2487 else if (*s == quote)
2488 quote = 0;
2490 else if (*s == '\\')
2492 if (s[1] == '"') /* escaped quote char */
2493 s++;
2495 else if (!quote)
2497 /* Process a single redirection candidate. */
2498 if (*s == '<' || *s == '>'
2499 || ((*s == '1' || *s == '2') && s[1] == '>')
2500 || (*s == '0' && s[1] == '<'))
2502 int skip = redir_set_redirection (s, inp, out, err);
2504 if (skip <= 0)
2505 return false;
2506 retval = true;
2507 s += skip;
2510 if (*s)
2511 *d++ = *s++;
2513 *d = '\0';
2514 return retval;
2516 #endif /* !__CYGWIN__ */
2518 /* Start an inferior windows child process and sets inferior_ptid to its pid.
2519 EXEC_FILE is the file to run.
2520 ALLARGS is a string containing the arguments to the program.
2521 ENV is the environment vector to pass. Errors reported with error(). */
2523 void
2524 windows_nat_target::create_inferior (const char *exec_file,
2525 const std::string &origallargs,
2526 char **in_env, int from_tty)
2528 STARTUPINFO si;
2529 #ifdef __CYGWIN__
2530 wchar_t real_path[__PMAX];
2531 wchar_t shell[__PMAX]; /* Path to shell */
2532 wchar_t infcwd[__PMAX];
2533 const char *sh;
2534 wchar_t *toexec;
2535 wchar_t *cygallargs;
2536 wchar_t *args;
2537 char **old_env = NULL;
2538 PWCHAR w32_env;
2539 size_t len;
2540 int tty;
2541 int ostdin, ostdout, ostderr;
2542 #else /* !__CYGWIN__ */
2543 char shell[__PMAX]; /* Path to shell */
2544 const char *toexec;
2545 char *args, *allargs_copy;
2546 size_t args_len, allargs_len;
2547 int fd_inp = -1, fd_out = -1, fd_err = -1;
2548 HANDLE tty = INVALID_HANDLE_VALUE;
2549 bool redirected = false;
2550 char *w32env;
2551 char *temp;
2552 size_t envlen;
2553 int i;
2554 size_t envsize;
2555 char **env;
2556 #endif /* !__CYGWIN__ */
2557 const char *allargs = origallargs.c_str ();
2558 PROCESS_INFORMATION pi;
2559 std::optional<unsigned> ret;
2560 DWORD flags = 0;
2561 const std::string &inferior_tty = current_inferior ()->tty ();
2563 if (!exec_file)
2564 error (_("No executable specified, use `target exec'."));
2566 const char *inferior_cwd = current_inferior ()->cwd ().c_str ();
2567 std::string expanded_infcwd;
2568 if (*inferior_cwd == '\0')
2569 inferior_cwd = nullptr;
2570 else
2572 expanded_infcwd = gdb_tilde_expand (inferior_cwd);
2573 /* Mirror slashes on inferior's cwd. */
2574 std::replace (expanded_infcwd.begin (), expanded_infcwd.end (),
2575 '/', '\\');
2576 inferior_cwd = expanded_infcwd.c_str ();
2579 memset (&si, 0, sizeof (si));
2580 si.cb = sizeof (si);
2582 if (new_group)
2583 flags |= CREATE_NEW_PROCESS_GROUP;
2585 if (new_console)
2586 windows_set_console_info (&si, &flags);
2588 #ifdef __CYGWIN__
2589 if (!useshell)
2591 flags |= DEBUG_ONLY_THIS_PROCESS;
2592 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, exec_file, real_path,
2593 __PMAX * sizeof (wchar_t)) < 0)
2594 error (_("Error starting executable: %d"), errno);
2595 toexec = real_path;
2596 len = mbstowcs (NULL, allargs, 0) + 1;
2597 if (len == (size_t) -1)
2598 error (_("Error starting executable: %d"), errno);
2599 cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
2600 mbstowcs (cygallargs, allargs, len);
2602 else
2604 sh = get_shell ();
2605 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, sh, shell, __PMAX) < 0)
2606 error (_("Error starting executable via shell: %d"), errno);
2607 len = sizeof (L" -c 'exec '") + mbstowcs (NULL, exec_file, 0)
2608 + mbstowcs (NULL, allargs, 0) + 2;
2609 cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
2610 swprintf (cygallargs, len, L" -c 'exec %s %s'", exec_file, allargs);
2611 toexec = shell;
2612 flags |= DEBUG_PROCESS;
2615 if (inferior_cwd != NULL
2616 && cygwin_conv_path (CCP_POSIX_TO_WIN_W, inferior_cwd,
2617 infcwd, strlen (inferior_cwd)) < 0)
2618 error (_("Error converting inferior cwd: %d"), errno);
2620 args = (wchar_t *) alloca ((wcslen (toexec) + wcslen (cygallargs) + 2)
2621 * sizeof (wchar_t));
2622 wcscpy (args, toexec);
2623 wcscat (args, L" ");
2624 wcscat (args, cygallargs);
2626 #ifdef CW_CVT_ENV_TO_WINENV
2627 /* First try to create a direct Win32 copy of the POSIX environment. */
2628 w32_env = (PWCHAR) cygwin_internal (CW_CVT_ENV_TO_WINENV, in_env);
2629 if (w32_env != (PWCHAR) -1)
2630 flags |= CREATE_UNICODE_ENVIRONMENT;
2631 else
2632 /* If that fails, fall back to old method tweaking GDB's environment. */
2633 #endif /* CW_CVT_ENV_TO_WINENV */
2635 /* Reset all Win32 environment variables to avoid leftover on next run. */
2636 clear_win32_environment (environ);
2637 /* Prepare the environment vars for CreateProcess. */
2638 old_env = environ;
2639 environ = in_env;
2640 cygwin_internal (CW_SYNC_WINENV);
2641 w32_env = NULL;
2644 if (inferior_tty.empty ())
2645 tty = ostdin = ostdout = ostderr = -1;
2646 else
2648 tty = open (inferior_tty.c_str (), O_RDWR | O_NOCTTY);
2649 if (tty < 0)
2651 warning_filename_and_errno (inferior_tty.c_str (), errno);
2652 ostdin = ostdout = ostderr = -1;
2654 else
2656 ostdin = dup (0);
2657 ostdout = dup (1);
2658 ostderr = dup (2);
2659 dup2 (tty, 0);
2660 dup2 (tty, 1);
2661 dup2 (tty, 2);
2665 windows_init_thread_list ();
2666 do_synchronously ([&] ()
2668 if (!create_process (nullptr, args, flags, w32_env,
2669 inferior_cwd != nullptr ? infcwd : nullptr,
2670 disable_randomization,
2671 &si, &pi))
2672 ret = (unsigned) GetLastError ();
2673 return true;
2676 if (w32_env)
2677 /* Just free the Win32 environment, if it could be created. */
2678 free (w32_env);
2679 else
2681 /* Reset all environment variables to avoid leftover on next run. */
2682 clear_win32_environment (in_env);
2683 /* Restore normal GDB environment variables. */
2684 environ = old_env;
2685 cygwin_internal (CW_SYNC_WINENV);
2688 if (tty >= 0)
2690 ::close (tty);
2691 dup2 (ostdin, 0);
2692 dup2 (ostdout, 1);
2693 dup2 (ostderr, 2);
2694 ::close (ostdin);
2695 ::close (ostdout);
2696 ::close (ostderr);
2698 #else /* !__CYGWIN__ */
2699 allargs_len = strlen (allargs);
2700 allargs_copy = strcpy ((char *) alloca (allargs_len + 1), allargs);
2701 if (strpbrk (allargs_copy, "<>") != NULL)
2703 int e = errno;
2704 errno = 0;
2705 redirected =
2706 redirect_inferior_handles (allargs, allargs_copy,
2707 &fd_inp, &fd_out, &fd_err);
2708 if (errno)
2709 warning (_("Error in redirection: %s."), safe_strerror (errno));
2710 else
2711 errno = e;
2712 allargs_len = strlen (allargs_copy);
2714 /* If not all the standard streams are redirected by the command
2715 line, use INFERIOR_TTY for those which aren't. */
2716 if (!inferior_tty.empty ()
2717 && !(fd_inp >= 0 && fd_out >= 0 && fd_err >= 0))
2719 SECURITY_ATTRIBUTES sa;
2720 sa.nLength = sizeof(sa);
2721 sa.lpSecurityDescriptor = 0;
2722 sa.bInheritHandle = TRUE;
2723 tty = CreateFileA (inferior_tty.c_str (), GENERIC_READ | GENERIC_WRITE,
2724 0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
2725 if (tty == INVALID_HANDLE_VALUE)
2727 unsigned err = (unsigned) GetLastError ();
2728 warning (_("Warning: Failed to open TTY %s, error %#x: %s"),
2729 inferior_tty.c_str (), err, strwinerror (err));
2732 if (redirected || tty != INVALID_HANDLE_VALUE)
2734 if (fd_inp >= 0)
2735 si.hStdInput = (HANDLE) _get_osfhandle (fd_inp);
2736 else if (tty != INVALID_HANDLE_VALUE)
2737 si.hStdInput = tty;
2738 else
2739 si.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
2740 if (fd_out >= 0)
2741 si.hStdOutput = (HANDLE) _get_osfhandle (fd_out);
2742 else if (tty != INVALID_HANDLE_VALUE)
2743 si.hStdOutput = tty;
2744 else
2745 si.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
2746 if (fd_err >= 0)
2747 si.hStdError = (HANDLE) _get_osfhandle (fd_err);
2748 else if (tty != INVALID_HANDLE_VALUE)
2749 si.hStdError = tty;
2750 else
2751 si.hStdError = GetStdHandle (STD_ERROR_HANDLE);
2752 si.dwFlags |= STARTF_USESTDHANDLES;
2755 toexec = exec_file;
2756 /* Build the command line, a space-separated list of tokens where
2757 the first token is the name of the module to be executed.
2758 To avoid ambiguities introduced by spaces in the module name,
2759 we quote it. */
2760 args_len = strlen (toexec) + 2 /* quotes */ + allargs_len + 2;
2761 args = (char *) alloca (args_len);
2762 xsnprintf (args, args_len, "\"%s\" %s", toexec, allargs_copy);
2764 flags |= DEBUG_ONLY_THIS_PROCESS;
2766 /* CreateProcess takes the environment list as a null terminated set of
2767 strings (i.e. two nulls terminate the list). */
2769 /* Get total size for env strings. */
2770 for (envlen = 0, i = 0; in_env[i] && *in_env[i]; i++)
2771 envlen += strlen (in_env[i]) + 1;
2773 envsize = sizeof (in_env[0]) * (i + 1);
2774 env = (char **) alloca (envsize);
2775 memcpy (env, in_env, envsize);
2776 /* Windows programs expect the environment block to be sorted. */
2777 qsort (env, i, sizeof (char *), envvar_cmp);
2779 w32env = (char *) alloca (envlen + 1);
2781 /* Copy env strings into new buffer. */
2782 for (temp = w32env, i = 0; env[i] && *env[i]; i++)
2784 strcpy (temp, env[i]);
2785 temp += strlen (temp) + 1;
2788 /* Final nil string to terminate new env. */
2789 *temp = 0;
2791 windows_init_thread_list ();
2792 do_synchronously ([&] ()
2794 if (!create_process (nullptr, /* image */
2795 args, /* command line */
2796 flags, /* start flags */
2797 w32env, /* environment */
2798 inferior_cwd, /* current directory */
2799 disable_randomization,
2800 &si,
2801 &pi))
2802 ret = (unsigned) GetLastError ();
2803 return true;
2805 if (tty != INVALID_HANDLE_VALUE)
2806 CloseHandle (tty);
2807 if (fd_inp >= 0)
2808 _close (fd_inp);
2809 if (fd_out >= 0)
2810 _close (fd_out);
2811 if (fd_err >= 0)
2812 _close (fd_err);
2813 #endif /* !__CYGWIN__ */
2815 if (ret.has_value ())
2817 std::string msg = _("Error creating process ") + std::string (exec_file);
2818 throw_winerror_with_name (msg.c_str (), *ret);
2821 #ifdef __x86_64__
2822 BOOL wow64;
2823 if (IsWow64Process (pi.hProcess, &wow64))
2824 windows_process.wow64_process = wow64;
2825 #endif
2827 CloseHandle (pi.hThread);
2828 CloseHandle (pi.hProcess);
2830 if (useshell && shell[0] != '\0')
2831 windows_process.saw_create = -1;
2832 else
2833 windows_process.saw_create = 0;
2835 do_initial_windows_stuff (pi.dwProcessId, 0);
2837 /* windows_continue (DBG_CONTINUE, -1, 0); */
2840 void
2841 windows_nat_target::mourn_inferior ()
2843 (void) windows_continue (DBG_CONTINUE, -1, 0, true);
2844 x86_cleanup_dregs();
2845 if (windows_process.open_process_used)
2847 CHECK (CloseHandle (windows_process.handle));
2848 windows_process.open_process_used = 0;
2850 windows_process.siginfo_er.ExceptionCode = 0;
2851 inf_child_target::mourn_inferior ();
2854 /* Helper for windows_xfer_partial that handles memory transfers.
2855 Arguments are like target_xfer_partial. */
2857 static enum target_xfer_status
2858 windows_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
2859 ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
2861 SIZE_T done = 0;
2862 BOOL success;
2863 DWORD lasterror = 0;
2865 if (writebuf != NULL)
2867 DEBUG_MEM ("write target memory, %s bytes at %s",
2868 pulongest (len), core_addr_to_string (memaddr));
2869 success = WriteProcessMemory (windows_process.handle,
2870 (LPVOID) (uintptr_t) memaddr, writebuf,
2871 len, &done);
2872 if (!success)
2873 lasterror = GetLastError ();
2874 FlushInstructionCache (windows_process.handle,
2875 (LPCVOID) (uintptr_t) memaddr, len);
2877 else
2879 DEBUG_MEM ("read target memory, %s bytes at %s",
2880 pulongest (len), core_addr_to_string (memaddr));
2881 success = ReadProcessMemory (windows_process.handle,
2882 (LPCVOID) (uintptr_t) memaddr, readbuf,
2883 len, &done);
2884 if (!success)
2885 lasterror = GetLastError ();
2887 *xfered_len = (ULONGEST) done;
2888 if (!success && lasterror == ERROR_PARTIAL_COPY && done > 0)
2889 return TARGET_XFER_OK;
2890 else
2891 return success ? TARGET_XFER_OK : TARGET_XFER_E_IO;
2894 void
2895 windows_nat_target::kill ()
2897 CHECK (TerminateProcess (windows_process.handle, 0));
2899 for (;;)
2901 if (!windows_continue (DBG_CONTINUE, -1, 1))
2902 break;
2903 wait_for_debug_event_main_thread (&windows_process.current_event);
2904 if (windows_process.current_event.dwDebugEventCode
2905 == EXIT_PROCESS_DEBUG_EVENT)
2906 break;
2909 target_mourn_inferior (inferior_ptid); /* Or just windows_mourn_inferior? */
2912 void
2913 windows_nat_target::close ()
2915 DEBUG_EVENTS ("inferior_ptid=%d\n", inferior_ptid.pid ());
2916 async (false);
2919 /* Convert pid to printable format. */
2920 std::string
2921 windows_nat_target::pid_to_str (ptid_t ptid)
2923 if (ptid.lwp () != 0)
2924 return string_printf ("Thread %d.0x%lx", ptid.pid (), ptid.lwp ());
2926 return normal_pid_to_str (ptid);
2929 static enum target_xfer_status
2930 windows_xfer_shared_libraries (struct target_ops *ops,
2931 enum target_object object, const char *annex,
2932 gdb_byte *readbuf, const gdb_byte *writebuf,
2933 ULONGEST offset, ULONGEST len,
2934 ULONGEST *xfered_len)
2936 if (writebuf)
2937 return TARGET_XFER_E_IO;
2939 std::string xml = "<library-list>\n";
2940 for (windows_solib &so : windows_process.solibs)
2941 windows_xfer_shared_library (so.name.c_str (),
2942 (CORE_ADDR) (uintptr_t) so.load_addr,
2943 &so.text_offset,
2944 current_inferior ()->arch (), xml);
2945 xml += "</library-list>\n";
2947 ULONGEST len_avail = xml.size ();
2948 if (offset >= len_avail)
2949 len = 0;
2950 else
2952 if (len > len_avail - offset)
2953 len = len_avail - offset;
2954 memcpy (readbuf, xml.data () + offset, len);
2957 *xfered_len = (ULONGEST) len;
2958 return len != 0 ? TARGET_XFER_OK : TARGET_XFER_EOF;
2961 /* Helper for windows_nat_target::xfer_partial that handles signal info. */
2963 static enum target_xfer_status
2964 windows_xfer_siginfo (gdb_byte *readbuf, ULONGEST offset, ULONGEST len,
2965 ULONGEST *xfered_len)
2967 char *buf = (char *) &windows_process.siginfo_er;
2968 size_t bufsize = sizeof (windows_process.siginfo_er);
2970 #ifdef __x86_64__
2971 EXCEPTION_RECORD32 er32;
2972 if (windows_process.wow64_process)
2974 buf = (char *) &er32;
2975 bufsize = sizeof (er32);
2977 er32.ExceptionCode = windows_process.siginfo_er.ExceptionCode;
2978 er32.ExceptionFlags = windows_process.siginfo_er.ExceptionFlags;
2979 er32.ExceptionRecord
2980 = (uintptr_t) windows_process.siginfo_er.ExceptionRecord;
2981 er32.ExceptionAddress
2982 = (uintptr_t) windows_process.siginfo_er.ExceptionAddress;
2983 er32.NumberParameters = windows_process.siginfo_er.NumberParameters;
2984 int i;
2985 for (i = 0; i < EXCEPTION_MAXIMUM_PARAMETERS; i++)
2986 er32.ExceptionInformation[i]
2987 = windows_process.siginfo_er.ExceptionInformation[i];
2989 #endif
2991 if (windows_process.siginfo_er.ExceptionCode == 0)
2992 return TARGET_XFER_E_IO;
2994 if (readbuf == nullptr)
2995 return TARGET_XFER_E_IO;
2997 if (offset > bufsize)
2998 return TARGET_XFER_E_IO;
3000 if (offset + len > bufsize)
3001 len = bufsize - offset;
3003 memcpy (readbuf, buf + offset, len);
3004 *xfered_len = len;
3006 return TARGET_XFER_OK;
3009 enum target_xfer_status
3010 windows_nat_target::xfer_partial (enum target_object object,
3011 const char *annex, gdb_byte *readbuf,
3012 const gdb_byte *writebuf, ULONGEST offset,
3013 ULONGEST len, ULONGEST *xfered_len)
3015 switch (object)
3017 case TARGET_OBJECT_MEMORY:
3018 return windows_xfer_memory (readbuf, writebuf, offset, len, xfered_len);
3020 case TARGET_OBJECT_LIBRARIES:
3021 return windows_xfer_shared_libraries (this, object, annex, readbuf,
3022 writebuf, offset, len, xfered_len);
3024 case TARGET_OBJECT_SIGNAL_INFO:
3025 return windows_xfer_siginfo (readbuf, offset, len, xfered_len);
3027 default:
3028 if (beneath () == NULL)
3030 /* This can happen when requesting the transfer of unsupported
3031 objects before a program has been started (and therefore
3032 with the current_target having no target beneath). */
3033 return TARGET_XFER_E_IO;
3035 return beneath ()->xfer_partial (object, annex,
3036 readbuf, writebuf, offset, len,
3037 xfered_len);
3041 /* Provide thread local base, i.e. Thread Information Block address.
3042 Returns 1 if ptid is found and sets *ADDR to thread_local_base. */
3044 bool
3045 windows_nat_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
3047 windows_thread_info *th;
3049 th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
3050 if (th == NULL)
3051 return false;
3053 if (addr != NULL)
3054 *addr = th->thread_local_base;
3056 return true;
3059 ptid_t
3060 windows_nat_target::get_ada_task_ptid (long lwp, ULONGEST thread)
3062 return ptid_t (inferior_ptid.pid (), lwp, 0);
3065 /* Implementation of the to_thread_name method. */
3067 const char *
3068 windows_nat_target::thread_name (struct thread_info *thr)
3070 windows_thread_info *th
3071 = windows_process.thread_rec (thr->ptid,
3072 DONT_INVALIDATE_CONTEXT);
3073 return th->thread_name ();
3077 void _initialize_windows_nat ();
3078 void
3079 _initialize_windows_nat ()
3081 x86_dr_low.set_control = cygwin_set_dr7;
3082 x86_dr_low.set_addr = cygwin_set_dr;
3083 x86_dr_low.get_addr = cygwin_get_dr;
3084 x86_dr_low.get_status = cygwin_get_dr6;
3085 x86_dr_low.get_control = cygwin_get_dr7;
3087 /* x86_dr_low.debug_register_length field is set by
3088 calling x86_set_debug_register_length function
3089 in processor windows specific native file. */
3091 /* The target is not a global specifically to avoid a C++ "static
3092 initializer fiasco" situation. */
3093 add_inf_child_target (new windows_nat_target);
3095 #ifdef __CYGWIN__
3096 cygwin_internal (CW_SET_DOS_FILE_WARNING, 0);
3097 #endif
3099 add_com ("signal-event", class_run, signal_event_command, _("\
3100 Signal a crashed process with event ID, to allow its debugging.\n\
3101 This command is needed in support of setting up GDB as JIT debugger on \
3102 MS-Windows. The command should be invoked from the GDB command line using \
3103 the '-ex' command-line option. The ID of the event that blocks the \
3104 crashed process will be supplied by the Windows JIT debugging mechanism."));
3106 #ifdef __CYGWIN__
3107 add_setshow_boolean_cmd ("shell", class_support, &useshell, _("\
3108 Set use of shell to start subprocess."), _("\
3109 Show use of shell to start subprocess."), NULL,
3110 NULL,
3111 NULL, /* FIXME: i18n: */
3112 &setlist, &showlist);
3114 add_setshow_boolean_cmd ("cygwin-exceptions", class_support,
3115 &cygwin_exceptions, _("\
3116 Break when an exception is detected in the Cygwin DLL itself."), _("\
3117 Show whether gdb breaks on exceptions in the Cygwin DLL itself."), NULL,
3118 NULL,
3119 NULL, /* FIXME: i18n: */
3120 &setlist, &showlist);
3121 #endif
3123 add_setshow_boolean_cmd ("new-console", class_support, &new_console, _("\
3124 Set creation of new console when creating child process."), _("\
3125 Show creation of new console when creating child process."), NULL,
3126 NULL,
3127 NULL, /* FIXME: i18n: */
3128 &setlist, &showlist);
3130 add_setshow_boolean_cmd ("new-group", class_support, &new_group, _("\
3131 Set creation of new group when creating child process."), _("\
3132 Show creation of new group when creating child process."), NULL,
3133 NULL,
3134 NULL, /* FIXME: i18n: */
3135 &setlist, &showlist);
3137 add_setshow_boolean_cmd ("debugexec", class_support, &debug_exec, _("\
3138 Set whether to display execution in child process."), _("\
3139 Show whether to display execution in child process."), NULL,
3140 NULL,
3141 NULL, /* FIXME: i18n: */
3142 &setlist, &showlist);
3144 add_setshow_boolean_cmd ("debugevents", class_support, &debug_events, _("\
3145 Set whether to display kernel events in child process."), _("\
3146 Show whether to display kernel events in child process."), NULL,
3147 NULL,
3148 NULL, /* FIXME: i18n: */
3149 &setlist, &showlist);
3151 add_setshow_boolean_cmd ("debugmemory", class_support, &debug_memory, _("\
3152 Set whether to display memory accesses in child process."), _("\
3153 Show whether to display memory accesses in child process."), NULL,
3154 NULL,
3155 NULL, /* FIXME: i18n: */
3156 &setlist, &showlist);
3158 add_setshow_boolean_cmd ("debugexceptions", class_support,
3159 &debug_exceptions, _("\
3160 Set whether to display kernel exceptions in child process."), _("\
3161 Show whether to display kernel exceptions in child process."), NULL,
3162 NULL,
3163 NULL, /* FIXME: i18n: */
3164 &setlist, &showlist);
3166 init_w32_command_list ();
3168 add_cmd ("selector", class_info, display_selectors,
3169 _("Display selectors infos."),
3170 &info_w32_cmdlist);
3172 if (!initialize_loadable ())
3174 /* This will probably fail on Windows 9x/Me. Let the user know
3175 that we're missing some functionality. */
3176 warning(_("\
3177 cannot automatically find executable file or library to read symbols.\n\
3178 Use \"file\" or \"dll\" command to load executable/libraries directly."));
3182 /* Hardware watchpoint support, adapted from go32-nat.c code. */
3184 /* Pass the address ADDR to the inferior in the I'th debug register.
3185 Here we just store the address in dr array, the registers will be
3186 actually set up when windows_continue is called. */
3187 static void
3188 cygwin_set_dr (int i, CORE_ADDR addr)
3190 if (i < 0 || i > 3)
3191 internal_error (_("Invalid register %d in cygwin_set_dr.\n"), i);
3192 windows_process.dr[i] = addr;
3194 for (auto &th : windows_process.thread_list)
3195 th->debug_registers_changed = true;
3198 /* Pass the value VAL to the inferior in the DR7 debug control
3199 register. Here we just store the address in D_REGS, the watchpoint
3200 will be actually set up in windows_wait. */
3201 static void
3202 cygwin_set_dr7 (unsigned long val)
3204 windows_process.dr[7] = (CORE_ADDR) val;
3206 for (auto &th : windows_process.thread_list)
3207 th->debug_registers_changed = true;
3210 /* Get the value of debug register I from the inferior. */
3212 static CORE_ADDR
3213 cygwin_get_dr (int i)
3215 return windows_process.dr[i];
3218 /* Get the value of the DR6 debug status register from the inferior.
3219 Here we just return the value stored in dr[6]
3220 by the last call to thread_rec for current_event.dwThreadId id. */
3221 static unsigned long
3222 cygwin_get_dr6 (void)
3224 return (unsigned long) windows_process.dr[6];
3227 /* Get the value of the DR7 debug status register from the inferior.
3228 Here we just return the value stored in dr[7] by the last call to
3229 thread_rec for current_event.dwThreadId id. */
3231 static unsigned long
3232 cygwin_get_dr7 (void)
3234 return (unsigned long) windows_process.dr[7];
3237 /* Determine if the thread referenced by "ptid" is alive
3238 by "polling" it. If WaitForSingleObject returns WAIT_OBJECT_0
3239 it means that the thread has died. Otherwise it is assumed to be alive. */
3241 bool
3242 windows_nat_target::thread_alive (ptid_t ptid)
3244 gdb_assert (ptid.lwp () != 0);
3246 windows_thread_info *th
3247 = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
3248 return WaitForSingleObject (th->h, 0) != WAIT_OBJECT_0;
3251 void _initialize_check_for_gdb_ini ();
3252 void
3253 _initialize_check_for_gdb_ini ()
3255 char *homedir;
3256 if (inhibit_gdbinit)
3257 return;
3259 homedir = getenv ("HOME");
3260 if (homedir)
3262 char *p;
3263 char *oldini = (char *) alloca (strlen (homedir) +
3264 sizeof ("gdb.ini") + 1);
3265 strcpy (oldini, homedir);
3266 p = strchr (oldini, '\0');
3267 if (p > oldini && !IS_DIR_SEPARATOR (p[-1]))
3268 *p++ = '/';
3269 strcpy (p, "gdb.ini");
3270 if (access (oldini, 0) == 0)
3272 int len = strlen (oldini);
3273 char *newini = (char *) alloca (len + 2);
3275 xsnprintf (newini, len + 2, "%.*s.gdbinit",
3276 (int) (len - (sizeof ("gdb.ini") - 1)), oldini);
3277 warning (_("obsolete '%s' found. Rename to '%s'."), oldini, newini);