1 /* Target-vector operations for controlling windows child processes, for GDB.
3 Copyright (C) 1995-2025 Free Software Foundation, Inc.
5 Contributed by Cygnus Solutions, A Red Hat Company.
7 This file is part of GDB.
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>. */
22 /* Originally by Steve Chamberlain, sac@cygnus.com */
24 #include "exceptions.h"
31 #include "completer.h"
35 #include <sys/types.h>
41 #include <sys/cygwin.h>
42 #include <cygwin/version.h>
49 #include "filenames.h"
53 #include "gdbsupport/gdb_obstack.h"
54 #include "gdbthread.h"
55 #include "cli/cli-cmds.h"
56 #include "cli/cli-style.h"
60 #include "xml-support.h"
63 #include "i386-tdep.h"
64 #include "i387-tdep.h"
66 #include "windows-tdep.h"
67 #include "windows-nat.h"
69 #include "complaints.h"
70 #include "inf-child.h"
71 #include "gdbsupport/gdb_tilde_expand.h"
72 #include "gdbsupport/pathstuff.h"
73 #include "gdbsupport/gdb_wait.h"
74 #include "nat/windows-nat.h"
75 #include "gdbsupport/symbol.h"
76 #include "ser-event.h"
79 using namespace windows_nat
;
81 /* Maintain a linked list of "so" information. */
85 CORE_ADDR text_offset
= 0;
88 std::string original_name
;
89 /* Expanded form of the name. */
93 struct windows_per_inferior
: public windows_process_info
95 windows_thread_info
*thread_rec (ptid_t ptid
,
96 thread_disposition_type disposition
) override
;
97 int handle_output_debug_string (struct target_waitstatus
*ourstatus
) override
;
98 void handle_load_dll (const char *dll_name
, LPVOID base
) override
;
99 void handle_unload_dll () override
;
100 bool handle_access_violation (const EXCEPTION_RECORD
*rec
) override
;
104 int windows_initialization_done
= 0;
106 std::vector
<std::unique_ptr
<windows_thread_info
>> thread_list
;
108 /* Counts of things. */
110 int open_process_used
= 0;
112 void *wow64_dbgbreak
= nullptr;
115 /* This vector maps GDB's idea of a register's number into an offset
116 in the windows exception context vector.
118 It also contains the bit mask needed to load the register in question.
120 The contents of this table can only be computed by the units
121 that provide CPU-specific support for Windows native debugging.
123 One day we could read a reg, we could inspect the context we
124 already have loaded, if it doesn't have the bit set that we need,
125 we read that set of registers in using GetThreadContext. If the
126 context already contains what we need, we just unpack it. Then to
127 write a register, first we have to ensure that the context contains
128 the other regs of the group, and then we copy the info in and set
131 const int *mappings
= nullptr;
133 /* The function to use in order to determine whether a register is
134 a segment register or not. */
135 segment_register_p_ftype
*segment_register_p
= nullptr;
137 std::vector
<windows_solib
> solibs
;
140 /* The starting and ending address of the cygwin1.dll text segment. */
141 CORE_ADDR cygwin_load_start
= 0;
142 CORE_ADDR cygwin_load_end
= 0;
143 #endif /* __CYGWIN__ */
146 /* The current process. */
147 static windows_per_inferior windows_process
;
152 # define __PMAX (MAX_PATH + 1)
153 # define STARTUPINFO STARTUPINFOA
155 # define __PMAX PATH_MAX
156 # define STARTUPINFO STARTUPINFOW
159 /* If we're not using the old Cygwin header file set, define the
160 following which never should have been in the generic Win32 API
161 headers in the first place since they were our own invention... */
162 #ifndef _GNU_H_WINDOWS_H
165 FLAG_TRACE_BIT
= 0x100,
169 #define DR6_CLEAR_VALUE 0xffff0ff0
171 /* The string sent by cygwin when it processes a signal.
172 FIXME: This should be in a cygwin include file. */
173 #ifndef _CYGWIN_SIGNAL_STRING
174 #define _CYGWIN_SIGNAL_STRING "cYgSiGw00f"
177 #define CHECK(x) check (x, __FILE__,__LINE__)
178 #define DEBUG_EXEC(fmt, ...) \
179 debug_prefixed_printf_cond (debug_exec, "windows exec", fmt, ## __VA_ARGS__)
180 #define DEBUG_EVENTS(fmt, ...) \
181 debug_prefixed_printf_cond (debug_events, "windows events", fmt, \
183 #define DEBUG_MEM(fmt, ...) \
184 debug_prefixed_printf_cond (debug_memory, "windows mem", fmt, \
186 #define DEBUG_EXCEPT(fmt, ...) \
187 debug_prefixed_printf_cond (debug_exceptions, "windows except", fmt, \
190 static void cygwin_set_dr (int i
, CORE_ADDR addr
);
191 static void cygwin_set_dr7 (unsigned long val
);
192 static CORE_ADDR
cygwin_get_dr (int i
);
193 static unsigned long cygwin_get_dr6 (void);
194 static unsigned long cygwin_get_dr7 (void);
197 static bool new_console
= false;
199 static bool cygwin_exceptions
= false;
201 static bool new_group
= true;
202 static bool debug_exec
= false; /* show execution */
203 static bool debug_events
= false; /* show events from kernel */
204 static bool debug_memory
= false; /* show target memory accesses */
205 static bool debug_exceptions
= false; /* show target exceptions */
206 static bool useshell
= false; /* use shell for subprocesses */
208 /* See windows_nat_target::resume to understand why this is commented
211 /* This vector maps the target's idea of an exception (extracted
212 from the DEBUG_EVENT structure) to GDB's idea. */
214 struct xlate_exception
220 static const struct xlate_exception xlate
[] =
222 {EXCEPTION_ACCESS_VIOLATION
, GDB_SIGNAL_SEGV
},
223 {STATUS_STACK_OVERFLOW
, GDB_SIGNAL_SEGV
},
224 {EXCEPTION_BREAKPOINT
, GDB_SIGNAL_TRAP
},
225 {DBG_CONTROL_C
, GDB_SIGNAL_INT
},
226 {EXCEPTION_SINGLE_STEP
, GDB_SIGNAL_TRAP
},
227 {STATUS_FLOAT_DIVIDE_BY_ZERO
, GDB_SIGNAL_FPE
}
232 struct windows_nat_target final
: public x86_nat_target
<inf_child_target
>
234 windows_nat_target ();
236 void close () override
;
238 void attach (const char *, int) override
;
240 bool attach_no_wait () override
243 void detach (inferior
*, int) override
;
245 void resume (ptid_t
, int , enum gdb_signal
) override
;
247 ptid_t
wait (ptid_t
, struct target_waitstatus
*, target_wait_flags
) override
;
249 void fetch_registers (struct regcache
*, int) override
;
250 void store_registers (struct regcache
*, int) override
;
252 bool stopped_by_sw_breakpoint () override
254 windows_thread_info
*th
255 = windows_process
.thread_rec (inferior_ptid
, DONT_INVALIDATE_CONTEXT
);
256 return th
->stopped_at_software_breakpoint
;
259 bool supports_stopped_by_sw_breakpoint () override
264 enum target_xfer_status
xfer_partial (enum target_object object
,
267 const gdb_byte
*writebuf
,
268 ULONGEST offset
, ULONGEST len
,
269 ULONGEST
*xfered_len
) override
;
271 void files_info () override
;
273 void kill () override
;
275 void create_inferior (const char *, const std::string
&,
276 char **, int) override
;
278 void mourn_inferior () override
;
280 bool thread_alive (ptid_t ptid
) override
;
282 std::string
pid_to_str (ptid_t
) override
;
284 void interrupt () override
;
285 void pass_ctrlc () override
;
287 const char *pid_to_exec_file (int pid
) override
;
289 ptid_t
get_ada_task_ptid (long lwp
, ULONGEST thread
) override
;
291 bool get_tib_address (ptid_t ptid
, CORE_ADDR
*addr
) override
;
293 const char *thread_name (struct thread_info
*) override
;
295 ptid_t
get_windows_debug_event (int pid
, struct target_waitstatus
*ourstatus
,
296 target_wait_flags options
);
298 void do_initial_windows_stuff (DWORD pid
, bool attaching
);
300 bool supports_disable_randomization () override
302 return disable_randomization_available ();
305 bool can_async_p () override
310 bool is_async_p () override
315 void async (bool enable
) override
;
317 int async_wait_fd () override
319 return serial_event_fd (m_wait_event
);
324 windows_thread_info
*add_thread (ptid_t ptid
, HANDLE h
, void *tlb
,
326 void delete_thread (ptid_t ptid
, DWORD exit_code
, bool main_thread_p
);
327 DWORD
fake_create_process ();
329 BOOL
windows_continue (DWORD continue_status
, int id
, int killed
,
330 bool last_call
= false);
332 /* Helper function to start process_thread. */
333 static DWORD WINAPI
process_thread_starter (LPVOID self
);
335 /* This function implements the background thread that starts
336 inferiors and waits for events. */
337 void process_thread ();
339 /* Push FUNC onto the queue of requests for process_thread, and wait
340 until it has been called. On Windows, certain debugging
341 functions can only be called by the thread that started (or
342 attached to) the inferior. These are all done in the worker
343 thread, via calls to this method. If FUNC returns true,
344 process_thread will wait for debug events when FUNC returns. */
345 void do_synchronously (gdb::function_view
<bool ()> func
);
347 /* This waits for a debug event, dispatching to the worker thread as
349 void wait_for_debug_event_main_thread (DEBUG_EVENT
*event
);
351 /* Force the process_thread thread to return from WaitForDebugEvent.
352 PROCESS_ALIVE is set to false if the inferior process exits while
353 we're trying to break out the process_thread thread. This can
354 happen because this is called while all threads are running free,
355 while we're trying to detach. */
356 void break_out_process_thread (bool &process_alive
);
358 /* Queue used to send requests to process_thread. This is
359 implicitly locked. */
360 std::queue
<gdb::function_view
<bool ()>> m_queue
;
362 /* Event used to signal process_thread that an item has been
364 HANDLE m_pushed_event
;
365 /* Event used by process_thread to indicate that it has processed a
366 single function call. */
367 HANDLE m_response_event
;
369 /* Serial event used to communicate wait event availability to the
371 serial_event
*m_wait_event
;
373 /* The last debug event, when M_WAIT_EVENT has been set. */
374 DEBUG_EVENT m_last_debug_event
{};
375 /* True if a debug event is pending. */
376 std::atomic
<bool> m_debug_event_pending
{ false };
378 /* True if currently in async mode. */
379 bool m_is_async
= false;
381 /* True if we last called ContinueDebugEvent and the process_thread
382 thread is now waiting for events. False if WaitForDebugEvent
383 already returned an event, and we need to ContinueDebugEvent
384 again to restart the inferior. */
385 bool m_continued
= false;
389 check (BOOL ok
, const char *file
, int line
)
393 unsigned err
= (unsigned) GetLastError ();
394 gdb_printf ("error return %s:%d was %u: %s\n", file
, line
,
395 err
, strwinerror (err
));
399 windows_nat_target::windows_nat_target ()
400 : m_pushed_event (CreateEvent (nullptr, false, false, nullptr)),
401 m_response_event (CreateEvent (nullptr, false, false, nullptr)),
402 m_wait_event (make_serial_event ())
404 HANDLE bg_thread
= CreateThread (nullptr, 64 * 1024,
405 process_thread_starter
, this, 0, nullptr);
406 CloseHandle (bg_thread
);
410 windows_nat_target::async (bool enable
)
412 if (enable
== is_async_p ())
416 add_file_handler (async_wait_fd (),
417 [] (int, gdb_client_data
)
419 inferior_event_handler (INF_REG_EVENT
);
421 nullptr, "windows_nat_target");
423 delete_file_handler (async_wait_fd ());
428 /* A wrapper for WaitForSingleObject that issues a warning if
429 something unusual happens. */
431 wait_for_single (HANDLE handle
, DWORD howlong
)
435 /* Using an INFINITE argument to WaitForSingleObject may cause a system
436 deadlock. Avoid it by waiting for a bit in a loop instead. */
437 DWORD milliseconds
= howlong
== INFINITE
? 100 : howlong
;
438 DWORD r
= WaitForSingleObject (handle
, milliseconds
);
439 if (howlong
== INFINITE
&& r
== WAIT_TIMEOUT
)
441 if (r
== WAIT_OBJECT_0
)
443 if (r
== WAIT_FAILED
)
445 unsigned err
= (unsigned) GetLastError ();
446 warning ("WaitForSingleObject failed (code %u): %s",
447 err
, strwinerror (err
));
450 warning ("unexpected result from WaitForSingleObject: %u",
456 windows_nat_target::process_thread_starter (LPVOID self
)
458 ((windows_nat_target
*) self
)->process_thread ();
463 windows_nat_target::process_thread ()
467 wait_for_single (m_pushed_event
, INFINITE
);
469 gdb::function_view
<bool ()> func
= std::move (m_queue
.front ());
472 bool should_wait
= func ();
473 SetEvent (m_response_event
);
477 if (!m_debug_event_pending
)
479 wait_for_debug_event (&m_last_debug_event
, INFINITE
);
480 m_debug_event_pending
= true;
482 serial_event_set (m_wait_event
);
488 windows_nat_target::do_synchronously (gdb::function_view
<bool ()> func
)
490 m_queue
.emplace (std::move (func
));
491 SetEvent (m_pushed_event
);
492 wait_for_single (m_response_event
, INFINITE
);
496 windows_nat_target::wait_for_debug_event_main_thread (DEBUG_EVENT
*event
)
498 do_synchronously ([&] ()
500 if (m_debug_event_pending
)
502 *event
= m_last_debug_event
;
503 m_debug_event_pending
= false;
504 serial_event_clear (m_wait_event
);
507 wait_for_debug_event (event
, INFINITE
);
514 /* See nat/windows-nat.h. */
516 windows_thread_info
*
517 windows_per_inferior::thread_rec
518 (ptid_t ptid
, thread_disposition_type disposition
)
520 for (auto &th
: thread_list
)
521 if (th
->tid
== ptid
.lwp ())
527 case DONT_INVALIDATE_CONTEXT
:
530 case INVALIDATE_CONTEXT
:
531 if (ptid
.lwp () != current_event
.dwThreadId
)
533 th
->reload_context
= true;
536 th
->reload_context
= true;
547 /* Add a thread to the thread list.
549 PTID is the ptid of the thread to be added.
550 H is its Windows handle.
551 TLB is its thread local base.
552 MAIN_THREAD_P should be true if the thread to be added is
553 the main thread, false otherwise. */
555 windows_thread_info
*
556 windows_nat_target::add_thread (ptid_t ptid
, HANDLE h
, void *tlb
,
559 windows_thread_info
*th
;
561 gdb_assert (ptid
.lwp () != 0);
563 if ((th
= windows_process
.thread_rec (ptid
, DONT_INVALIDATE_CONTEXT
)))
566 CORE_ADDR base
= (CORE_ADDR
) (uintptr_t) tlb
;
568 /* For WOW64 processes, this is actually the pointer to the 64bit TIB,
569 and the 32bit TIB is exactly 2 pages after it. */
570 if (windows_process
.wow64_process
)
573 th
= new windows_thread_info (ptid
.lwp (), h
, base
);
574 windows_process
.thread_list
.emplace_back (th
);
576 /* Add this new thread to the list of threads.
578 To be consistent with what's done on other platforms, we add
579 the main thread silently (in reality, this thread is really
580 more of a process to the user than a thread). */
582 add_thread_silent (this, ptid
);
584 ::add_thread (this, ptid
);
586 /* It's simplest to always set this and update the debug
588 th
->debug_registers_changed
= true;
593 /* Clear out any old thread list and reinitialize it to a
596 windows_init_thread_list (void)
598 DEBUG_EVENTS ("called");
599 windows_process
.thread_list
.clear ();
602 /* Delete a thread from the list of threads.
604 PTID is the ptid of the thread to be deleted.
605 EXIT_CODE is the thread's exit code.
606 MAIN_THREAD_P should be true if the thread to be deleted is
607 the main thread, false otherwise. */
610 windows_nat_target::delete_thread (ptid_t ptid
, DWORD exit_code
,
615 gdb_assert (ptid
.lwp () != 0);
619 /* Note that no notification was printed when the main thread was
620 created, and thus, unless in verbose mode, we should be symmetrical,
621 and avoid an exit notification for the main thread here as well. */
623 bool silent
= (main_thread_p
&& !info_verbose
);
624 thread_info
*to_del
= this->find_thread (ptid
);
625 delete_thread_with_exit_code (to_del
, exit_code
, silent
);
627 auto iter
= std::find_if (windows_process
.thread_list
.begin (),
628 windows_process
.thread_list
.end (),
629 [=] (std::unique_ptr
<windows_thread_info
> &th
)
631 return th
->tid
== id
;
634 if (iter
!= windows_process
.thread_list
.end ())
635 windows_process
.thread_list
.erase (iter
);
638 /* Fetches register number R from the given windows_thread_info,
639 and supplies its value to the given regcache.
641 This function assumes that R is non-negative. A failed assertion
642 is raised if that is not true.
644 This function assumes that TH->RELOAD_CONTEXT is not set, meaning
645 that the windows_thread_info has an up-to-date context. A failed
646 assertion is raised if that assumption is violated. */
649 windows_fetch_one_register (struct regcache
*regcache
,
650 windows_thread_info
*th
, int r
)
653 gdb_assert (!th
->reload_context
);
655 char *context_ptr
= windows_process
.with_context (th
, [] (auto *context
)
657 return (char *) context
;
660 char *context_offset
= context_ptr
+ windows_process
.mappings
[r
];
661 struct gdbarch
*gdbarch
= regcache
->arch ();
662 i386_gdbarch_tdep
*tdep
= gdbarch_tdep
<i386_gdbarch_tdep
> (gdbarch
);
664 gdb_assert (!gdbarch_read_pc_p (gdbarch
));
665 gdb_assert (gdbarch_pc_regnum (gdbarch
) >= 0);
666 gdb_assert (!gdbarch_write_pc_p (gdbarch
));
668 /* GDB treats some registers as 32-bit, where they are in fact only
669 16 bits long. These cases must be handled specially to avoid
670 reading extraneous bits from the context. */
671 if (r
== I387_FISEG_REGNUM (tdep
) || windows_process
.segment_register_p (r
))
673 gdb_byte bytes
[4] = {};
674 memcpy (bytes
, context_offset
, 2);
675 regcache
->raw_supply (r
, bytes
);
677 else if (r
== I387_FOP_REGNUM (tdep
))
679 long l
= (*((long *) context_offset
) >> 16) & ((1 << 11) - 1);
680 regcache
->raw_supply (r
, &l
);
684 if (th
->stopped_at_software_breakpoint
686 && r
== gdbarch_pc_regnum (gdbarch
))
688 int size
= register_size (gdbarch
, r
);
692 memcpy (&value
, context_offset
, size
);
693 value
-= gdbarch_decr_pc_after_break (gdbarch
);
694 memcpy (context_offset
, &value
, size
);
698 gdb_assert (size
== 8);
700 memcpy (&value
, context_offset
, size
);
701 value
-= gdbarch_decr_pc_after_break (gdbarch
);
702 memcpy (context_offset
, &value
, size
);
704 /* Make sure we only rewrite the PC a single time. */
705 th
->pc_adjusted
= true;
707 regcache
->raw_supply (r
, context_offset
);
712 windows_nat_target::fetch_registers (struct regcache
*regcache
, int r
)
714 windows_thread_info
*th
715 = windows_process
.thread_rec (regcache
->ptid (), INVALIDATE_CONTEXT
);
717 /* Check if TH exists. Windows sometimes uses a non-existent
718 thread id in its events. */
722 if (th
->reload_context
)
724 windows_process
.with_context (th
, [&] (auto *context
)
726 context
->ContextFlags
= WindowsContext
<decltype(context
)>::all
;
727 CHECK (get_thread_context (th
->h
, context
));
728 /* Copy dr values from that thread.
729 But only if there were not modified since last stop.
731 if (!th
->debug_registers_changed
)
733 windows_process
.dr
[0] = context
->Dr0
;
734 windows_process
.dr
[1] = context
->Dr1
;
735 windows_process
.dr
[2] = context
->Dr2
;
736 windows_process
.dr
[3] = context
->Dr3
;
737 windows_process
.dr
[6] = context
->Dr6
;
738 windows_process
.dr
[7] = context
->Dr7
;
742 th
->reload_context
= false;
746 for (r
= 0; r
< gdbarch_num_regs (regcache
->arch()); r
++)
747 windows_fetch_one_register (regcache
, th
, r
);
749 windows_fetch_one_register (regcache
, th
, r
);
752 /* Collect the register number R from the given regcache, and store
753 its value into the corresponding area of the given thread's context.
755 This function assumes that R is non-negative. A failed assertion
756 assertion is raised if that is not true. */
759 windows_store_one_register (const struct regcache
*regcache
,
760 windows_thread_info
*th
, int r
)
764 char *context_ptr
= windows_process
.with_context (th
, [] (auto *context
)
766 return (char *) context
;
769 struct gdbarch
*gdbarch
= regcache
->arch ();
770 i386_gdbarch_tdep
*tdep
= gdbarch_tdep
<i386_gdbarch_tdep
> (gdbarch
);
772 /* GDB treats some registers as 32-bit, where they are in fact only
773 16 bits long. These cases must be handled specially to avoid
774 overwriting other registers in the context. */
775 if (r
== I387_FISEG_REGNUM (tdep
) || windows_process
.segment_register_p (r
))
778 regcache
->raw_collect (r
, bytes
);
779 memcpy (context_ptr
+ windows_process
.mappings
[r
], bytes
, 2);
781 else if (r
== I387_FOP_REGNUM (tdep
))
784 regcache
->raw_collect (r
, bytes
);
785 /* The value of FOP occupies the top two bytes in the context,
786 so write the two low-order bytes from the cache into the
788 memcpy (context_ptr
+ windows_process
.mappings
[r
] + 2, bytes
, 2);
791 regcache
->raw_collect (r
, context_ptr
+ windows_process
.mappings
[r
]);
794 /* Store a new register value into the context of the thread tied to
798 windows_nat_target::store_registers (struct regcache
*regcache
, int r
)
800 windows_thread_info
*th
801 = windows_process
.thread_rec (regcache
->ptid (), INVALIDATE_CONTEXT
);
803 /* Check if TH exists. Windows sometimes uses a non-existent
804 thread id in its events. */
809 for (r
= 0; r
< gdbarch_num_regs (regcache
->arch ()); r
++)
810 windows_store_one_register (regcache
, th
, r
);
812 windows_store_one_register (regcache
, th
, r
);
815 /* See nat/windows-nat.h. */
817 static windows_solib
*
818 windows_make_so (const char *name
, LPVOID load_addr
)
820 windows_solib
*so
= &windows_process
.solibs
.emplace_back ();
821 so
->load_addr
= load_addr
;
822 so
->original_name
= name
;
828 WIN32_FIND_DATA w32_fd
;
829 HANDLE h
= FindFirstFile(name
, &w32_fd
);
831 if (h
== INVALID_HANDLE_VALUE
)
837 if (GetCurrentDirectory (MAX_PATH
+ 1, cwd
))
839 p
= strrchr (buf
, '\\');
842 SetCurrentDirectory (buf
);
843 GetFullPathName (w32_fd
.cFileName
, MAX_PATH
, buf
, &p
);
844 SetCurrentDirectory (cwd
);
847 if (strcasecmp (buf
, "ntdll.dll") == 0)
849 GetSystemDirectory (buf
, sizeof (buf
));
850 strcat (buf
, "\\ntdll.dll");
858 if (access (name
, F_OK
) != 0)
860 if (strcasecmp (name
, "ntdll.dll") == 0)
862 GetSystemDirectoryW (buf
, sizeof (buf
) / sizeof (wchar_t));
863 wcscat (buf
, L
"\\ntdll.dll");
870 /* Check how big the output buffer has to be. */
871 ssize_t size
= cygwin_conv_path (CCP_WIN_W_TO_POSIX
, buf
, nullptr, 0);
874 /* SIZE includes the null terminator. */
875 so
->name
.resize (size
- 1);
876 if (cygwin_conv_path (CCP_WIN_W_TO_POSIX
, buf
, so
->name
.data (),
881 so
->name
= so
->original_name
;
885 gdb::unique_xmalloc_ptr
<char> rname
= gdb_realpath (name
);
886 if (rname
!= nullptr)
887 so
->name
= rname
.get ();
890 warning (_("dll path for \"%s\" inaccessible"), name
);
891 so
->name
= so
->original_name
;
894 /* Record cygwin1.dll .text start/end. */
895 size_t len
= sizeof ("/cygwin1.dll") - 1;
896 if (so
->name
.size () >= len
897 && strcasecmp (so
->name
.c_str () + so
->name
.size () - len
,
898 "/cygwin1.dll") == 0)
900 asection
*text
= NULL
;
902 gdb_bfd_ref_ptr
abfd (gdb_bfd_open (so
->name
.c_str(), "pei-i386"));
907 if (bfd_check_format (abfd
.get (), bfd_object
))
908 text
= bfd_get_section_by_name (abfd
.get (), ".text");
913 /* The symbols in a dll are offset by 0x1000, which is the
914 offset from 0 of the first byte in an image - because of the
915 file header and the section alignment. */
916 windows_process
.cygwin_load_start
= (CORE_ADDR
) (uintptr_t) ((char *)
918 windows_process
.cygwin_load_end
= windows_process
.cygwin_load_start
+
919 bfd_section_size (text
);
926 /* See nat/windows-nat.h. */
929 windows_per_inferior::handle_load_dll (const char *dll_name
, LPVOID base
)
931 windows_solib
*solib
= windows_make_so (dll_name
, base
);
932 DEBUG_EVENTS ("Loading dll \"%s\" at %s.", solib
->name
.c_str (),
933 host_address_to_string (solib
->load_addr
));
936 /* See nat/windows-nat.h. */
939 windows_per_inferior::handle_unload_dll ()
941 LPVOID lpBaseOfDll
= current_event
.u
.UnloadDll
.lpBaseOfDll
;
943 auto iter
= std::remove_if (windows_process
.solibs
.begin (),
944 windows_process
.solibs
.end (),
945 [&] (windows_solib
&lib
)
947 if (lib
.load_addr
== lpBaseOfDll
)
949 DEBUG_EVENTS ("Unloading dll \"%s\".", lib
.name
.c_str ());
955 if (iter
!= windows_process
.solibs
.end ())
957 windows_process
.solibs
.erase (iter
, windows_process
.solibs
.end ());
961 /* We did not find any DLL that was previously loaded at this address,
962 so register a complaint. We do not report an error, because we have
963 observed that this may be happening under some circumstances. For
964 instance, running 32bit applications on x64 Windows causes us to receive
965 4 mysterious UNLOAD_DLL_DEBUG_EVENTs during the startup phase (these
966 events are apparently caused by the WOW layer, the interface between
967 32bit and 64bit worlds). */
968 complaint (_("dll starting at %s not found."),
969 host_address_to_string (lpBaseOfDll
));
972 /* Clear list of loaded DLLs. */
974 windows_clear_solib (void)
976 windows_process
.solibs
.clear ();
980 signal_event_command (const char *args
, int from_tty
)
982 uintptr_t event_id
= 0;
983 char *endargs
= NULL
;
986 error (_("signal-event requires an argument (integer event id)"));
988 event_id
= strtoumax (args
, &endargs
, 10);
990 if ((errno
== ERANGE
) || (event_id
== 0) || (event_id
> UINTPTR_MAX
) ||
991 ((HANDLE
) event_id
== INVALID_HANDLE_VALUE
))
992 error (_("Failed to convert `%s' to event id"), args
);
994 SetEvent ((HANDLE
) event_id
);
995 CloseHandle ((HANDLE
) event_id
);
998 /* See nat/windows-nat.h. */
1001 windows_per_inferior::handle_output_debug_string
1002 (struct target_waitstatus
*ourstatus
)
1006 gdb::unique_xmalloc_ptr
<char> s
1007 = (target_read_string
1008 ((CORE_ADDR
) (uintptr_t) current_event
.u
.DebugString
.lpDebugStringData
,
1010 if (s
== nullptr || !*(s
.get ()))
1011 /* nothing to do */;
1012 else if (!startswith (s
.get (), _CYGWIN_SIGNAL_STRING
))
1015 if (!startswith (s
.get (), "cYg"))
1018 char *p
= strchr (s
.get (), '\0');
1020 if (p
> s
.get () && *--p
== '\n')
1022 warning (("%s"), s
.get ());
1028 /* Got a cygwin signal marker. A cygwin signal marker is
1029 followed by the signal number itself, and (since Cygwin 1.7)
1030 the thread id, and the address of a saved context in the
1031 inferior (That context has an IP which is the return address
1032 in "user" code of the cygwin internal signal handling code,
1033 but is not otherwise usable).
1035 Tell gdb to treat this like the given thread issued a real
1038 int sig
= strtol (s
.get () + sizeof (_CYGWIN_SIGNAL_STRING
) - 1, &p
, 0);
1039 gdb_signal gotasig
= gdb_signal_from_host (sig
);
1044 ourstatus
->set_stopped (gotasig
);
1045 retval
= strtoul (p
, &p
, 0);
1047 retval
= current_event
.dwThreadId
;
1049 x
= (LPCVOID
) (uintptr_t) strtoull (p
, NULL
, 0);
1052 DEBUG_EVENTS ("gdb: cygwin signal %d, thread 0x%x, CONTEXT @ %p",
1053 gotasig
, retval
, x
);
1061 display_selector (HANDLE thread
, DWORD sel
)
1064 BOOL ret
= windows_process
.with_context (nullptr, [&] (auto *context
)
1066 return get_thread_selector_entry (context
, thread
, sel
, &info
);
1071 gdb_printf ("0x%03x: ", (unsigned) sel
);
1072 if (!info
.HighWord
.Bits
.Pres
)
1074 gdb_puts ("Segment not present\n");
1077 base
= (info
.HighWord
.Bits
.BaseHi
<< 24) +
1078 (info
.HighWord
.Bits
.BaseMid
<< 16)
1080 limit
= (info
.HighWord
.Bits
.LimitHi
<< 16) + info
.LimitLow
;
1081 if (info
.HighWord
.Bits
.Granularity
)
1082 limit
= (limit
<< 12) | 0xfff;
1083 gdb_printf ("base=0x%08x limit=0x%08x", base
, limit
);
1084 if (info
.HighWord
.Bits
.Default_Big
)
1085 gdb_puts(" 32-bit ");
1087 gdb_puts(" 16-bit ");
1088 switch ((info
.HighWord
.Bits
.Type
& 0xf) >> 1)
1091 gdb_puts ("Data (Read-Only, Exp-up");
1094 gdb_puts ("Data (Read/Write, Exp-up");
1097 gdb_puts ("Unused segment (");
1100 gdb_puts ("Data (Read/Write, Exp-down");
1103 gdb_puts ("Code (Exec-Only, N.Conf");
1106 gdb_puts ("Code (Exec/Read, N.Conf");
1109 gdb_puts ("Code (Exec-Only, Conf");
1112 gdb_puts ("Code (Exec/Read, Conf");
1115 gdb_printf ("Unknown type 0x%lx",
1116 (unsigned long) info
.HighWord
.Bits
.Type
);
1118 if ((info
.HighWord
.Bits
.Type
& 0x1) == 0)
1119 gdb_puts(", N.Acc");
1121 if ((info
.HighWord
.Bits
.Type
& 0x10) == 0)
1122 gdb_puts("System selector ");
1123 gdb_printf ("Privilege level = %ld. ",
1124 (unsigned long) info
.HighWord
.Bits
.Dpl
);
1125 if (info
.HighWord
.Bits
.Granularity
)
1126 gdb_puts ("Page granular.\n");
1128 gdb_puts ("Byte granular.\n");
1133 DWORD err
= GetLastError ();
1134 if (err
== ERROR_NOT_SUPPORTED
)
1135 gdb_printf ("Function not supported\n");
1137 gdb_printf ("Invalid selector 0x%x.\n", (unsigned) sel
);
1143 display_selectors (const char * args
, int from_tty
)
1145 if (inferior_ptid
== null_ptid
)
1147 gdb_puts ("Impossible to display selectors now.\n");
1151 windows_thread_info
*current_windows_thread
1152 = windows_process
.thread_rec (inferior_ptid
, DONT_INVALIDATE_CONTEXT
);
1156 windows_process
.with_context (current_windows_thread
, [&] (auto *context
)
1158 gdb_puts ("Selector $cs\n");
1159 display_selector (current_windows_thread
->h
, context
->SegCs
);
1160 gdb_puts ("Selector $ds\n");
1161 display_selector (current_windows_thread
->h
, context
->SegDs
);
1162 gdb_puts ("Selector $es\n");
1163 display_selector (current_windows_thread
->h
, context
->SegEs
);
1164 gdb_puts ("Selector $ss\n");
1165 display_selector (current_windows_thread
->h
, context
->SegSs
);
1166 gdb_puts ("Selector $fs\n");
1167 display_selector (current_windows_thread
->h
, context
->SegFs
);
1168 gdb_puts ("Selector $gs\n");
1169 display_selector (current_windows_thread
->h
, context
->SegGs
);
1175 sel
= parse_and_eval_long (args
);
1176 gdb_printf ("Selector \"%s\"\n",args
);
1177 display_selector (current_windows_thread
->h
, sel
);
1181 /* See nat/windows-nat.h. */
1184 windows_per_inferior::handle_access_violation
1185 (const EXCEPTION_RECORD
*rec
)
1188 /* See if the access violation happened within the cygwin DLL
1189 itself. Cygwin uses a kind of exception handling to deal with
1190 passed-in invalid addresses. gdb should not treat these as real
1191 SEGVs since they will be silently handled by cygwin. A real SEGV
1192 will (theoretically) be caught by cygwin later in the process and
1193 will be sent as a cygwin-specific-signal. So, ignore SEGVs if
1194 they show up within the text segment of the DLL itself. */
1196 CORE_ADDR addr
= (CORE_ADDR
) (uintptr_t) rec
->ExceptionAddress
;
1198 if ((!cygwin_exceptions
&& (addr
>= cygwin_load_start
1199 && addr
< cygwin_load_end
))
1200 || (find_pc_partial_function (addr
, &fn
, NULL
, NULL
)
1201 && startswith (fn
, "KERNEL32!IsBad")))
1207 /* Resume thread specified by ID, or all artificially suspended
1208 threads, if we are continuing execution. KILLED non-zero means we
1209 have killed the inferior, so we should ignore weird errors due to
1210 threads shutting down. LAST_CALL is true if we expect this to be
1211 the last call to continue the inferior -- we are either mourning it
1214 windows_nat_target::windows_continue (DWORD continue_status
, int id
,
1215 int killed
, bool last_call
)
1217 windows_process
.desired_stop_thread_id
= id
;
1219 if (windows_process
.matching_pending_stop (debug_events
))
1221 /* There's no need to really continue, because there's already
1222 another event pending. However, we do need to inform the
1223 event loop of this. */
1224 serial_event_set (m_wait_event
);
1228 for (auto &th
: windows_process
.thread_list
)
1229 if (id
== -1 || id
== (int) th
->tid
)
1231 windows_process
.with_context (th
.get (), [&] (auto *context
)
1233 if (th
->debug_registers_changed
)
1235 context
->ContextFlags
1236 |= WindowsContext
<decltype(context
)>::debug
;
1237 context
->Dr0
= windows_process
.dr
[0];
1238 context
->Dr1
= windows_process
.dr
[1];
1239 context
->Dr2
= windows_process
.dr
[2];
1240 context
->Dr3
= windows_process
.dr
[3];
1241 context
->Dr6
= DR6_CLEAR_VALUE
;
1242 context
->Dr7
= windows_process
.dr
[7];
1243 th
->debug_registers_changed
= false;
1245 if (context
->ContextFlags
)
1249 if (GetExitCodeThread (th
->h
, &ec
)
1250 && ec
== STILL_ACTIVE
)
1252 BOOL status
= set_thread_context (th
->h
, context
);
1257 context
->ContextFlags
= 0;
1265 /* When single-stepping a specific thread, other threads must
1270 std::optional
<unsigned> err
;
1271 do_synchronously ([&] ()
1273 if (!continue_last_debug_event (continue_status
, debug_events
))
1274 err
= (unsigned) GetLastError ();
1275 /* On the last call, do not block waiting for an event that will
1280 if (err
.has_value ())
1281 throw_winerror_with_name (_("Failed to resume program execution"
1282 " - ContinueDebugEvent failed"),
1285 m_continued
= !last_call
;
1290 /* Called in pathological case where Windows fails to send a
1291 CREATE_PROCESS_DEBUG_EVENT after an attach. */
1293 windows_nat_target::fake_create_process ()
1295 windows_process
.handle
1296 = OpenProcess (PROCESS_ALL_ACCESS
, FALSE
,
1297 windows_process
.current_event
.dwProcessId
);
1298 if (windows_process
.handle
!= NULL
)
1299 windows_process
.open_process_used
= 1;
1302 unsigned err
= (unsigned) GetLastError ();
1303 throw_winerror_with_name (_("OpenProcess call failed"), err
);
1304 /* We can not debug anything in that case. */
1306 add_thread (ptid_t (windows_process
.current_event
.dwProcessId
,
1307 windows_process
.current_event
.dwThreadId
, 0),
1308 windows_process
.current_event
.u
.CreateThread
.hThread
,
1309 windows_process
.current_event
.u
.CreateThread
.lpThreadLocalBase
,
1310 true /* main_thread_p */);
1311 return windows_process
.current_event
.dwThreadId
;
1315 windows_nat_target::resume (ptid_t ptid
, int step
, enum gdb_signal sig
)
1317 windows_thread_info
*th
;
1318 DWORD continue_status
= DBG_CONTINUE
;
1320 /* A specific PTID means `step only this thread id'. */
1321 int resume_all
= ptid
== minus_one_ptid
;
1323 /* If we're continuing all threads, it's the current inferior that
1324 should be handled specially. */
1326 ptid
= inferior_ptid
;
1328 if (sig
!= GDB_SIGNAL_0
)
1330 if (windows_process
.current_event
.dwDebugEventCode
1331 != EXCEPTION_DEBUG_EVENT
)
1333 DEBUG_EXCEPT ("Cannot continue with signal %d here.", sig
);
1335 else if (sig
== windows_process
.last_sig
)
1336 continue_status
= DBG_EXCEPTION_NOT_HANDLED
;
1339 /* This code does not seem to work, because
1340 the kernel does probably not consider changes in the ExceptionRecord
1341 structure when passing the exception to the inferior.
1342 Note that this seems possible in the exception handler itself. */
1344 for (const xlate_exception
&x
: xlate
)
1347 current_event
.u
.Exception
.ExceptionRecord
.ExceptionCode
1349 continue_status
= DBG_EXCEPTION_NOT_HANDLED
;
1352 if (continue_status
== DBG_CONTINUE
)
1354 DEBUG_EXCEPT ("Cannot continue with signal %d.", sig
);
1358 DEBUG_EXCEPT ("Can only continue with received signal %d.",
1359 windows_process
.last_sig
);
1362 windows_process
.last_sig
= GDB_SIGNAL_0
;
1364 DEBUG_EXEC ("pid=%d, tid=0x%x, step=%d, sig=%d",
1365 ptid
.pid (), (unsigned) ptid
.lwp (), step
, sig
);
1367 /* Get context for currently selected thread. */
1368 th
= windows_process
.thread_rec (inferior_ptid
, DONT_INVALIDATE_CONTEXT
);
1371 windows_process
.with_context (th
, [&] (auto *context
)
1375 /* Single step by setting t bit. */
1376 regcache
*regcache
= get_thread_regcache (inferior_thread ());
1377 struct gdbarch
*gdbarch
= regcache
->arch ();
1378 fetch_registers (regcache
, gdbarch_ps_regnum (gdbarch
));
1379 context
->EFlags
|= FLAG_TRACE_BIT
;
1382 if (context
->ContextFlags
)
1384 if (th
->debug_registers_changed
)
1386 context
->Dr0
= windows_process
.dr
[0];
1387 context
->Dr1
= windows_process
.dr
[1];
1388 context
->Dr2
= windows_process
.dr
[2];
1389 context
->Dr3
= windows_process
.dr
[3];
1390 context
->Dr6
= DR6_CLEAR_VALUE
;
1391 context
->Dr7
= windows_process
.dr
[7];
1392 th
->debug_registers_changed
= false;
1394 CHECK (set_thread_context (th
->h
, context
));
1395 context
->ContextFlags
= 0;
1400 /* Allow continuing with the same signal that interrupted us.
1401 Otherwise complain. */
1404 windows_continue (continue_status
, -1, 0);
1406 windows_continue (continue_status
, ptid
.lwp (), 0);
1409 /* Interrupt the inferior. */
1412 windows_nat_target::interrupt ()
1414 DEBUG_EVENTS ("interrupt");
1416 if (windows_process
.wow64_process
)
1418 /* Call DbgUiRemoteBreakin of the 32bit ntdll.dll in the target process.
1419 DebugBreakProcess would call the one of the 64bit ntdll.dll, which
1420 can't be correctly handled by gdb. */
1421 if (windows_process
.wow64_dbgbreak
== nullptr)
1424 if (!find_minimal_symbol_address ("ntdll!DbgUiRemoteBreakin",
1426 windows_process
.wow64_dbgbreak
= (void *) addr
;
1429 if (windows_process
.wow64_dbgbreak
!= nullptr)
1431 HANDLE thread
= CreateRemoteThread (windows_process
.handle
, NULL
,
1432 0, (LPTHREAD_START_ROUTINE
)
1433 windows_process
.wow64_dbgbreak
,
1437 CloseHandle (thread
);
1444 if (DebugBreakProcess (windows_process
.handle
))
1446 warning (_("Could not interrupt program. "
1447 "Press Ctrl-c in the program console."));
1451 windows_nat_target::pass_ctrlc ()
1456 /* Get the next event from the child. Returns the thread ptid. */
1459 windows_nat_target::get_windows_debug_event
1460 (int pid
, struct target_waitstatus
*ourstatus
, target_wait_flags options
)
1462 DWORD continue_status
, event_code
;
1463 DWORD thread_id
= 0;
1465 /* If there is a relevant pending stop, report it now. See the
1466 comment by the definition of "pending_stops" for details on why
1468 std::optional
<pending_stop
> stop
1469 = windows_process
.fetch_pending_stop (debug_events
);
1470 if (stop
.has_value ())
1472 thread_id
= stop
->thread_id
;
1473 *ourstatus
= stop
->status
;
1475 ptid_t
ptid (windows_process
.current_event
.dwProcessId
, thread_id
);
1476 windows_thread_info
*th
1477 = windows_process
.thread_rec (ptid
, INVALIDATE_CONTEXT
);
1478 th
->reload_context
= true;
1483 windows_process
.last_sig
= GDB_SIGNAL_0
;
1484 DEBUG_EVENT
*current_event
= &windows_process
.current_event
;
1486 if ((options
& TARGET_WNOHANG
) != 0 && !m_debug_event_pending
)
1488 ourstatus
->set_ignore ();
1489 return minus_one_ptid
;
1492 wait_for_debug_event_main_thread (&windows_process
.current_event
);
1494 continue_status
= DBG_CONTINUE
;
1496 event_code
= windows_process
.current_event
.dwDebugEventCode
;
1497 ourstatus
->set_spurious ();
1501 case CREATE_THREAD_DEBUG_EVENT
:
1502 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1503 (unsigned) current_event
->dwProcessId
,
1504 (unsigned) current_event
->dwThreadId
,
1505 "CREATE_THREAD_DEBUG_EVENT");
1506 if (windows_process
.saw_create
!= 1)
1508 inferior
*inf
= find_inferior_pid (this, current_event
->dwProcessId
);
1509 if (!windows_process
.saw_create
&& inf
->attach_flag
)
1511 /* Kludge around a Windows bug where first event is a create
1512 thread event. Caused when attached process does not have
1514 thread_id
= fake_create_process ();
1516 windows_process
.saw_create
++;
1520 /* Record the existence of this thread. */
1521 thread_id
= current_event
->dwThreadId
;
1523 (ptid_t (current_event
->dwProcessId
, current_event
->dwThreadId
, 0),
1524 current_event
->u
.CreateThread
.hThread
,
1525 current_event
->u
.CreateThread
.lpThreadLocalBase
,
1526 false /* main_thread_p */);
1530 case EXIT_THREAD_DEBUG_EVENT
:
1531 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1532 (unsigned) current_event
->dwProcessId
,
1533 (unsigned) current_event
->dwThreadId
,
1534 "EXIT_THREAD_DEBUG_EVENT");
1535 delete_thread (ptid_t (current_event
->dwProcessId
,
1536 current_event
->dwThreadId
, 0),
1537 current_event
->u
.ExitThread
.dwExitCode
,
1538 false /* main_thread_p */);
1541 case CREATE_PROCESS_DEBUG_EVENT
:
1542 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1543 (unsigned) current_event
->dwProcessId
,
1544 (unsigned) current_event
->dwThreadId
,
1545 "CREATE_PROCESS_DEBUG_EVENT");
1546 CloseHandle (current_event
->u
.CreateProcessInfo
.hFile
);
1547 if (++windows_process
.saw_create
!= 1)
1550 windows_process
.handle
= current_event
->u
.CreateProcessInfo
.hProcess
;
1551 /* Add the main thread. */
1553 (ptid_t (current_event
->dwProcessId
,
1554 current_event
->dwThreadId
, 0),
1555 current_event
->u
.CreateProcessInfo
.hThread
,
1556 current_event
->u
.CreateProcessInfo
.lpThreadLocalBase
,
1557 true /* main_thread_p */);
1558 thread_id
= current_event
->dwThreadId
;
1561 case EXIT_PROCESS_DEBUG_EVENT
:
1562 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1563 (unsigned) current_event
->dwProcessId
,
1564 (unsigned) current_event
->dwThreadId
,
1565 "EXIT_PROCESS_DEBUG_EVENT");
1566 if (!windows_process
.windows_initialization_done
)
1568 target_terminal::ours ();
1569 target_mourn_inferior (inferior_ptid
);
1570 error (_("During startup program exited with code 0x%x."),
1571 (unsigned int) current_event
->u
.ExitProcess
.dwExitCode
);
1573 else if (windows_process
.saw_create
== 1)
1575 delete_thread (ptid_t (current_event
->dwProcessId
,
1576 current_event
->dwThreadId
, 0),
1577 0, true /* main_thread_p */);
1578 DWORD exit_status
= current_event
->u
.ExitProcess
.dwExitCode
;
1579 /* If the exit status looks like a fatal exception, but we
1580 don't recognize the exception's code, make the original
1581 exit status value available, to avoid losing
1584 = WIFSIGNALED (exit_status
) ? WTERMSIG (exit_status
) : -1;
1585 if (exit_signal
== -1)
1586 ourstatus
->set_exited (exit_status
);
1588 ourstatus
->set_signalled (gdb_signal_from_host (exit_signal
));
1590 thread_id
= current_event
->dwThreadId
;
1594 case LOAD_DLL_DEBUG_EVENT
:
1595 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1596 (unsigned) current_event
->dwProcessId
,
1597 (unsigned) current_event
->dwThreadId
,
1598 "LOAD_DLL_DEBUG_EVENT");
1599 CloseHandle (current_event
->u
.LoadDll
.hFile
);
1600 if (windows_process
.saw_create
!= 1
1601 || ! windows_process
.windows_initialization_done
)
1605 windows_process
.dll_loaded_event ();
1607 catch (const gdb_exception
&ex
)
1609 exception_print (gdb_stderr
, ex
);
1611 ourstatus
->set_loaded ();
1612 thread_id
= current_event
->dwThreadId
;
1615 case UNLOAD_DLL_DEBUG_EVENT
:
1616 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1617 (unsigned) current_event
->dwProcessId
,
1618 (unsigned) current_event
->dwThreadId
,
1619 "UNLOAD_DLL_DEBUG_EVENT");
1620 if (windows_process
.saw_create
!= 1
1621 || ! windows_process
.windows_initialization_done
)
1625 windows_process
.handle_unload_dll ();
1627 catch (const gdb_exception
&ex
)
1629 exception_print (gdb_stderr
, ex
);
1631 ourstatus
->set_loaded ();
1632 thread_id
= current_event
->dwThreadId
;
1635 case EXCEPTION_DEBUG_EVENT
:
1636 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1637 (unsigned) current_event
->dwProcessId
,
1638 (unsigned) current_event
->dwThreadId
,
1639 "EXCEPTION_DEBUG_EVENT");
1640 if (windows_process
.saw_create
!= 1)
1642 switch (windows_process
.handle_exception (ourstatus
, debug_exceptions
))
1644 case HANDLE_EXCEPTION_UNHANDLED
:
1646 continue_status
= DBG_EXCEPTION_NOT_HANDLED
;
1648 case HANDLE_EXCEPTION_HANDLED
:
1649 thread_id
= current_event
->dwThreadId
;
1651 case HANDLE_EXCEPTION_IGNORED
:
1652 continue_status
= DBG_CONTINUE
;
1657 case OUTPUT_DEBUG_STRING_EVENT
: /* Message from the kernel. */
1658 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1659 (unsigned) current_event
->dwProcessId
,
1660 (unsigned) current_event
->dwThreadId
,
1661 "OUTPUT_DEBUG_STRING_EVENT");
1662 if (windows_process
.saw_create
!= 1)
1664 thread_id
= windows_process
.handle_output_debug_string (ourstatus
);
1668 if (windows_process
.saw_create
!= 1)
1670 gdb_printf ("gdb: kernel event for pid=%u tid=0x%x\n",
1671 (unsigned) current_event
->dwProcessId
,
1672 (unsigned) current_event
->dwThreadId
);
1673 gdb_printf (" unknown event code %u\n",
1674 (unsigned) current_event
->dwDebugEventCode
);
1678 if (!thread_id
|| windows_process
.saw_create
!= 1)
1680 CHECK (windows_continue (continue_status
,
1681 windows_process
.desired_stop_thread_id
, 0));
1683 else if (windows_process
.desired_stop_thread_id
!= -1
1684 && windows_process
.desired_stop_thread_id
!= thread_id
)
1686 /* Pending stop. See the comment by the definition of
1687 "pending_stops" for details on why this is needed. */
1688 DEBUG_EVENTS ("get_windows_debug_event - "
1689 "unexpected stop in 0x%x (expecting 0x%x)",
1690 thread_id
, windows_process
.desired_stop_thread_id
);
1692 if (current_event
->dwDebugEventCode
== EXCEPTION_DEBUG_EVENT
1693 && ((current_event
->u
.Exception
.ExceptionRecord
.ExceptionCode
1694 == EXCEPTION_BREAKPOINT
)
1695 || (current_event
->u
.Exception
.ExceptionRecord
.ExceptionCode
1696 == STATUS_WX86_BREAKPOINT
))
1697 && windows_process
.windows_initialization_done
)
1699 ptid_t ptid
= ptid_t (current_event
->dwProcessId
, thread_id
, 0);
1700 windows_thread_info
*th
1701 = windows_process
.thread_rec (ptid
, INVALIDATE_CONTEXT
);
1702 th
->stopped_at_software_breakpoint
= true;
1703 th
->pc_adjusted
= false;
1705 windows_process
.pending_stops
.push_back
1706 ({thread_id
, *ourstatus
, windows_process
.current_event
});
1708 CHECK (windows_continue (continue_status
,
1709 windows_process
.desired_stop_thread_id
, 0));
1714 return ptid_t (windows_process
.current_event
.dwProcessId
, thread_id
, 0);
1717 /* Wait for interesting events to occur in the target process. */
1719 windows_nat_target::wait (ptid_t ptid
, struct target_waitstatus
*ourstatus
,
1720 target_wait_flags options
)
1724 /* We loop when we get a non-standard exception rather than return
1725 with a SPURIOUS because resume can try and step or modify things,
1726 which needs a current_thread->h. But some of these exceptions mark
1727 the birth or death of threads, which mean that the current thread
1728 isn't necessarily what you think it is. */
1732 ptid_t result
= get_windows_debug_event (pid
, ourstatus
, options
);
1734 if (result
!= null_ptid
)
1736 if (ourstatus
->kind () != TARGET_WAITKIND_EXITED
1737 && ourstatus
->kind () != TARGET_WAITKIND_SIGNALLED
)
1739 windows_thread_info
*th
1740 = windows_process
.thread_rec (result
, INVALIDATE_CONTEXT
);
1744 th
->stopped_at_software_breakpoint
= false;
1745 if (windows_process
.current_event
.dwDebugEventCode
1746 == EXCEPTION_DEBUG_EVENT
1747 && ((windows_process
.current_event
.u
.Exception
.ExceptionRecord
.ExceptionCode
1748 == EXCEPTION_BREAKPOINT
)
1749 || (windows_process
.current_event
.u
.Exception
.ExceptionRecord
.ExceptionCode
1750 == STATUS_WX86_BREAKPOINT
))
1751 && windows_process
.windows_initialization_done
)
1753 th
->stopped_at_software_breakpoint
= true;
1754 th
->pc_adjusted
= false;
1765 if (deprecated_ui_loop_hook
!= NULL
)
1766 detach
= deprecated_ui_loop_hook (0);
1775 windows_nat_target::do_initial_windows_stuff (DWORD pid
, bool attaching
)
1778 struct inferior
*inf
;
1780 windows_process
.last_sig
= GDB_SIGNAL_0
;
1781 windows_process
.open_process_used
= 0;
1783 i
< sizeof (windows_process
.dr
) / sizeof (windows_process
.dr
[0]);
1785 windows_process
.dr
[i
] = 0;
1787 windows_process
.cygwin_load_start
= 0;
1788 windows_process
.cygwin_load_end
= 0;
1790 windows_process
.current_event
.dwProcessId
= pid
;
1791 memset (&windows_process
.current_event
, 0,
1792 sizeof (windows_process
.current_event
));
1793 inf
= current_inferior ();
1794 if (!inf
->target_is_pushed (this))
1795 inf
->push_target (this);
1796 windows_clear_solib ();
1797 clear_proceed_status (0);
1798 init_wait_for_inferior ();
1801 windows_process
.ignore_first_breakpoint
1802 = !attaching
&& windows_process
.wow64_process
;
1804 if (!windows_process
.wow64_process
)
1806 windows_process
.mappings
= amd64_mappings
;
1807 windows_process
.segment_register_p
= amd64_windows_segment_register_p
;
1812 windows_process
.mappings
= i386_mappings
;
1813 windows_process
.segment_register_p
= i386_windows_segment_register_p
;
1816 inferior_appeared (inf
, pid
);
1817 inf
->attach_flag
= attaching
;
1819 target_terminal::init ();
1820 target_terminal::inferior ();
1822 windows_process
.windows_initialization_done
= 0;
1828 struct target_waitstatus status
;
1830 last_ptid
= this->wait (minus_one_ptid
, &status
, 0);
1832 /* Note windows_wait returns TARGET_WAITKIND_SPURIOUS for thread
1834 if (status
.kind () != TARGET_WAITKIND_LOADED
1835 && status
.kind () != TARGET_WAITKIND_SPURIOUS
)
1838 this->resume (minus_one_ptid
, 0, GDB_SIGNAL_0
);
1841 switch_to_thread (this->find_thread (last_ptid
));
1843 /* Now that the inferior has been started and all DLLs have been mapped,
1844 we can iterate over all DLLs and load them in.
1846 We avoid doing it any earlier because, on certain versions of Windows,
1847 LOAD_DLL_DEBUG_EVENTs are sometimes not complete. In particular,
1848 we have seen on Windows 8.1 that the ntdll.dll load event does not
1849 include the DLL name, preventing us from creating an associated SO.
1850 A possible explanation is that ntdll.dll might be mapped before
1851 the SO info gets created by the Windows system -- ntdll.dll is
1852 the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs
1853 do not seem to suffer from that problem.
1855 Rather than try to work around this sort of issue, it is much
1856 simpler to just ignore DLL load/unload events during the startup
1857 phase, and then process them all in one batch now. */
1858 windows_process
.add_all_dlls ();
1860 windows_process
.windows_initialization_done
= 1;
1864 /* Try to set or remove a user privilege to the current process. Return -1
1865 if that fails, the previous setting of that privilege otherwise.
1867 This code is copied from the Cygwin source code and rearranged to allow
1868 dynamically loading of the needed symbols from advapi32 which is only
1869 available on NT/2K/XP. */
1871 set_process_privilege (const char *privilege
, BOOL enable
)
1873 HANDLE token_hdl
= NULL
;
1875 TOKEN_PRIVILEGES new_priv
, orig_priv
;
1879 if (!OpenProcessToken (GetCurrentProcess (),
1880 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
1884 if (!LookupPrivilegeValueA (NULL
, privilege
, &restore_priv
))
1887 new_priv
.PrivilegeCount
= 1;
1888 new_priv
.Privileges
[0].Luid
= restore_priv
;
1889 new_priv
.Privileges
[0].Attributes
= enable
? SE_PRIVILEGE_ENABLED
: 0;
1891 if (!AdjustTokenPrivileges (token_hdl
, FALSE
, &new_priv
,
1892 sizeof orig_priv
, &orig_priv
, &size
))
1895 /* Disabled, otherwise every `attach' in an unprivileged user session
1896 would raise the "Failed to get SE_DEBUG_NAME privilege" warning in
1897 windows_attach(). */
1898 /* AdjustTokenPrivileges returns TRUE even if the privilege could not
1899 be enabled. GetLastError () returns an correct error code, though. */
1900 if (enable
&& GetLastError () == ERROR_NOT_ALL_ASSIGNED
)
1904 ret
= orig_priv
.Privileges
[0].Attributes
== SE_PRIVILEGE_ENABLED
? 1 : 0;
1908 CloseHandle (token_hdl
);
1913 /* Attach to process PID, then initialize for debugging it. */
1916 windows_nat_target::attach (const char *args
, int from_tty
)
1920 pid
= parse_pid_to_attach (args
);
1922 if (set_process_privilege (SE_DEBUG_NAME
, TRUE
) < 0)
1923 warning ("Failed to get SE_DEBUG_NAME privilege\n"
1924 "This can cause attach to fail on Windows NT/2K/XP");
1926 windows_init_thread_list ();
1927 windows_process
.saw_create
= 0;
1929 std::optional
<unsigned> err
;
1930 do_synchronously ([&] ()
1932 BOOL ok
= DebugActiveProcess (pid
);
1937 /* Maybe PID was a Cygwin PID. Try the corresponding native
1939 DWORD winpid
= cygwin_internal (CW_CYGWIN_PID_TO_WINPID
, pid
);
1943 /* It was indeed a Cygwin PID. Fully switch to the
1944 Windows PID from here on. We don't do this
1945 unconditionally to avoid ending up with PID=0 in the
1946 error message below. */
1949 ok
= DebugActiveProcess (winpid
);
1955 err
= (unsigned) GetLastError ();
1960 if (err
.has_value ())
1962 std::string msg
= string_printf (_("Can't attach to process %u"),
1964 throw_winerror_with_name (msg
.c_str (), *err
);
1967 DebugSetProcessKillOnExit (FALSE
);
1969 target_announce_attach (from_tty
, pid
);
1972 HANDLE h
= OpenProcess (PROCESS_QUERY_INFORMATION
, FALSE
, pid
);
1976 if (IsWow64Process (h
, &wow64
))
1977 windows_process
.wow64_process
= wow64
;
1982 do_initial_windows_stuff (pid
, 1);
1983 target_terminal::ours ();
1987 windows_nat_target::break_out_process_thread (bool &process_alive
)
1989 /* This is called when the process_thread thread is blocked in
1990 WaitForDebugEvent (unless it already returned some event we
1991 haven't consumed yet), and we need to unblock it so that we can
1992 have it call DebugActiveProcessStop.
1994 To make WaitForDebugEvent return, we need to force some event in
1995 the inferior. Any method that lets us do that (without
1996 disturbing the other threads), injects a new thread in the
1999 We don't use DebugBreakProcess for this, because that injects a
2000 thread that ends up executing a breakpoint instruction. We can't
2001 let the injected thread hit that breakpoint _after_ we've
2002 detached. Consuming events until we see a breakpoint trap isn't
2003 100% reliable, because we can't distinguish it from some other
2004 thread itself deciding to call int3 while we're detaching, unless
2005 we temporarily suspend all threads. It's just a lot of
2006 complication, and there's an easier way.
2008 Important observation: the thread creation event for the newly
2009 injected thread is sufficient to unblock WaitForDebugEvent.
2011 Instead of DebugBreakProcess, we can instead use
2012 CreateRemoteThread to control the code that the injected thread
2013 runs ourselves. We could consider pointing the injected thread
2014 at some side-effect-free Win32 function as entry point. However,
2015 finding the address of such a function requires having at least
2016 minimal symbols loaded for ntdll.dll. Having a way that avoids
2017 that is better, so that detach always works correctly even when
2018 we don't have any symbols loaded.
2020 So what we do is inject a thread that doesn't actually run ANY
2021 userspace code, because we force-terminate it as soon as we see
2022 its corresponding thread creation event. CreateRemoteThread
2023 gives us the new thread's ID, which we can match with the thread
2024 associated with the CREATE_THREAD_DEBUG_EVENT event. */
2026 DWORD injected_thread_id
= 0;
2027 HANDLE injected_thread_handle
2028 = CreateRemoteThread (windows_process
.handle
, NULL
,
2029 0, (LPTHREAD_START_ROUTINE
) 0,
2030 NULL
, 0, &injected_thread_id
);
2032 if (injected_thread_handle
== NULL
)
2034 DWORD err
= GetLastError ();
2036 DEBUG_EVENTS ("CreateRemoteThread failed with %u", err
);
2038 if (err
== ERROR_ACCESS_DENIED
)
2040 /* Creating the remote thread fails with ERROR_ACCESS_DENIED
2041 if the process exited before we had a chance to inject
2042 the thread. Continue with the loop below and consume the
2043 process exit event anyhow, so that our caller can always
2044 call windows_continue. */
2047 throw_winerror_with_name (_("Can't detach from running process. "
2048 "Interrupt it first."),
2052 process_alive
= true;
2054 /* At this point, the user has declared that they want to detach, so
2055 any event that happens from this point on should be forwarded to
2060 DEBUG_EVENT current_event
;
2061 wait_for_debug_event_main_thread (¤t_event
);
2063 if (current_event
.dwDebugEventCode
== EXIT_PROCESS_DEBUG_EVENT
)
2065 DEBUG_EVENTS ("got EXIT_PROCESS_DEBUG_EVENT");
2066 process_alive
= false;
2070 if (current_event
.dwDebugEventCode
== CREATE_THREAD_DEBUG_EVENT
2071 && current_event
.dwThreadId
== injected_thread_id
)
2073 DEBUG_EVENTS ("got CREATE_THREAD_DEBUG_EVENT for injected thread");
2075 /* Terminate the injected thread, so it doesn't run any code
2076 at all. All we wanted was some event, and
2077 CREATE_THREAD_DEBUG_EVENT is sufficient. */
2078 CHECK (TerminateThread (injected_thread_handle
, 0));
2082 DEBUG_EVENTS ("got unrelated event, code %u",
2083 current_event
.dwDebugEventCode
);
2084 windows_continue (DBG_CONTINUE
, -1, 0);
2087 if (injected_thread_handle
!= NULL
)
2088 CHECK (CloseHandle (injected_thread_handle
));
2092 windows_nat_target::detach (inferior
*inf
, int from_tty
)
2094 /* If we see the process exit while unblocking the process_thread
2095 helper thread, then we should skip the actual
2096 DebugActiveProcessStop call. But don't report an error. Just
2097 pretend the process exited shortly after the detach. */
2098 bool process_alive
= true;
2100 /* The process_thread helper thread will be blocked in
2101 WaitForDebugEvent waiting for events if we've resumed the target
2102 before we get here, e.g., with "attach&" or "c&". We need to
2103 unblock it so that we can have it call DebugActiveProcessStop
2104 below, in the do_synchronously block. */
2106 break_out_process_thread (process_alive
);
2108 windows_continue (DBG_CONTINUE
, -1, 0, true);
2110 std::optional
<unsigned> err
;
2112 do_synchronously ([&] ()
2114 if (!DebugActiveProcessStop (windows_process
.current_event
.dwProcessId
))
2115 err
= (unsigned) GetLastError ();
2117 DebugSetProcessKillOnExit (FALSE
);
2121 if (err
.has_value ())
2124 = string_printf (_("Can't detach process %u"),
2125 (unsigned) windows_process
.current_event
.dwProcessId
);
2126 throw_winerror_with_name (msg
.c_str (), *err
);
2129 target_announce_detach (from_tty
);
2131 x86_cleanup_dregs ();
2132 switch_to_no_thread ();
2133 detach_inferior (inf
);
2135 maybe_unpush_target ();
2138 /* The pid_to_exec_file target_ops method for this platform. */
2141 windows_nat_target::pid_to_exec_file (int pid
)
2143 return windows_process
.pid_to_exec_file (pid
);
2146 /* Print status information about what we're accessing. */
2149 windows_nat_target::files_info ()
2151 struct inferior
*inf
= current_inferior ();
2153 gdb_printf ("\tUsing the running image of %s %s.\n",
2154 inf
->attach_flag
? "attached" : "child",
2155 target_pid_to_str (ptid_t (inf
->pid
)).c_str ());
2158 /* Modify CreateProcess parameters for use of a new separate console.
2160 *FLAGS: DWORD parameter for general process creation flags.
2161 *SI: STARTUPINFO structure, for which the console window size and
2162 console buffer size is filled in if GDB is running in a console.
2163 to create the new console.
2164 The size of the used font is not available on all versions of
2165 Windows OS. Furthermore, the current font might not be the default
2166 font, but this is still better than before.
2167 If the windows and buffer sizes are computed,
2168 SI->DWFLAGS is changed so that this information is used
2169 by CreateProcess function. */
2172 windows_set_console_info (STARTUPINFO
*si
, DWORD
*flags
)
2174 HANDLE hconsole
= CreateFile ("CONOUT$", GENERIC_READ
| GENERIC_WRITE
,
2175 FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, 0, 0);
2177 if (hconsole
!= INVALID_HANDLE_VALUE
)
2179 CONSOLE_SCREEN_BUFFER_INFO sbinfo
;
2181 CONSOLE_FONT_INFO cfi
;
2183 GetCurrentConsoleFont (hconsole
, FALSE
, &cfi
);
2184 font_size
= GetConsoleFontSize (hconsole
, cfi
.nFont
);
2185 GetConsoleScreenBufferInfo(hconsole
, &sbinfo
);
2186 si
->dwXSize
= sbinfo
.srWindow
.Right
- sbinfo
.srWindow
.Left
+ 1;
2187 si
->dwYSize
= sbinfo
.srWindow
.Bottom
- sbinfo
.srWindow
.Top
+ 1;
2189 si
->dwXSize
*= font_size
.X
;
2193 si
->dwYSize
*= font_size
.Y
;
2196 si
->dwXCountChars
= sbinfo
.dwSize
.X
;
2197 si
->dwYCountChars
= sbinfo
.dwSize
.Y
;
2198 si
->dwFlags
|= STARTF_USESIZE
| STARTF_USECOUNTCHARS
;
2200 *flags
|= CREATE_NEW_CONSOLE
;
2204 /* Function called by qsort to sort environment strings. */
2207 envvar_cmp (const void *a
, const void *b
)
2209 const char **p
= (const char **) a
;
2210 const char **q
= (const char **) b
;
2211 return strcasecmp (*p
, *q
);
2217 clear_win32_environment (char **env
)
2221 wchar_t *copy
= NULL
, *equalpos
;
2223 for (i
= 0; env
[i
] && *env
[i
]; i
++)
2225 len
= mbstowcs (NULL
, env
[i
], 0) + 1;
2226 copy
= (wchar_t *) xrealloc (copy
, len
* sizeof (wchar_t));
2227 mbstowcs (copy
, env
[i
], len
);
2228 equalpos
= wcschr (copy
, L
'=');
2231 SetEnvironmentVariableW (copy
, NULL
);
2239 /* Redirection of inferior I/O streams for native MS-Windows programs.
2240 Unlike on Unix, where this is handled by invoking the inferior via
2241 the shell, on MS-Windows we need to emulate the cmd.exe shell.
2243 The official documentation of the cmd.exe redirection features is here:
2245 http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx
2247 (That page talks about Windows XP, but there's no newer
2248 documentation, so we assume later versions of cmd.exe didn't change
2251 Caveat: the documentation on that page seems to include a few lies.
2252 For example, it describes strange constructs 1<&2 and 2<&1, which
2253 seem to work only when 1>&2 resp. 2>&1 would make sense, and so I
2254 think the cmd.exe parser of the redirection symbols simply doesn't
2255 care about the < vs > distinction in these cases. Therefore, the
2256 supported features are explicitly documented below.
2258 The emulation below aims at supporting all the valid use cases
2259 supported by cmd.exe, which include:
2261 < FILE redirect standard input from FILE
2262 0< FILE redirect standard input from FILE
2263 <&N redirect standard input from file descriptor N
2264 0<&N redirect standard input from file descriptor N
2265 > FILE redirect standard output to FILE
2266 >> FILE append standard output to FILE
2267 1>> FILE append standard output to FILE
2268 >&N redirect standard output to file descriptor N
2269 1>&N redirect standard output to file descriptor N
2270 >>&N append standard output to file descriptor N
2271 1>>&N append standard output to file descriptor N
2272 2> FILE redirect standard error to FILE
2273 2>> FILE append standard error to FILE
2274 2>&N redirect standard error to file descriptor N
2275 2>>&N append standard error to file descriptor N
2277 Note that using N > 2 in the above construct is supported, but
2278 requires that the corresponding file descriptor be open by some
2279 means elsewhere or outside GDB. Also note that using ">&0" or
2280 "<&2" will generally fail, because the file descriptor redirected
2281 from is normally open in an incompatible mode (e.g., FD 0 is open
2282 for reading only). IOW, use of such tricks is not recommended;
2283 you are on your own.
2285 We do NOT support redirection of file descriptors above 2, as in
2286 "3>SOME-FILE", because MinGW compiled programs don't (supporting
2287 that needs special handling in the startup code that MinGW
2288 doesn't have). Pipes are also not supported.
2290 As for invalid use cases, where the redirection contains some
2291 error, the emulation below will detect that and produce some
2292 error and/or failure. But the behavior in those cases is not
2293 bug-for-bug compatible with what cmd.exe does in those cases.
2294 That's because what cmd.exe does then is not well defined, and
2295 seems to be a side effect of the cmd.exe parsing of the command
2296 line more than anything else. For example, try redirecting to an
2297 invalid file name, as in "> foo:bar".
2299 There are also minor syntactic deviations from what cmd.exe does
2300 in some corner cases. For example, it doesn't support the likes
2301 of "> &foo" to mean redirect to file named literally "&foo"; we
2302 do support that here, because that, too, sounds like some issue
2303 with the cmd.exe parser. Another nicety is that we support
2304 redirection targets that use file names with forward slashes,
2305 something cmd.exe doesn't -- this comes in handy since GDB
2306 file-name completion can be used when typing the command line for
2309 /* Support routines for redirecting standard handles of the inferior. */
2311 /* Parse a single redirection spec, open/duplicate the specified
2312 file/fd, and assign the appropriate value to one of the 3 standard
2313 file descriptors. */
2315 redir_open (const char *redir_string
, int *inp
, int *out
, int *err
)
2317 int *fd
, ref_fd
= -2;
2319 const char *fname
= redir_string
+ 1;
2320 int rc
= *redir_string
;
2335 fd
= (rc
== '2') ? err
: out
;
2336 mode
= O_WRONLY
| O_CREAT
;
2349 if (*fname
== '&' && '0' <= fname
[1] && fname
[1] <= '9')
2351 /* A reference to a file descriptor. */
2353 ref_fd
= (int) strtol (fname
+ 1, &fdtail
, 10);
2354 if (fdtail
> fname
+ 1 && *fdtail
== '\0')
2356 /* Don't allow redirection when open modes are incompatible. */
2357 if ((ref_fd
== 0 && (fd
== out
|| fd
== err
))
2358 || ((ref_fd
== 1 || ref_fd
== 2) && fd
== inp
))
2365 else if (ref_fd
== 1)
2367 else if (ref_fd
== 2)
2377 fname
++; /* skip the separator space */
2378 /* If the descriptor is already open, close it. This allows
2379 multiple specs of redirections for the same stream, which is
2380 somewhat nonsensical, but still valid and supported by cmd.exe.
2381 (But cmd.exe only opens a single file in this case, the one
2382 specified by the last redirection spec on the command line.) */
2387 *fd
= _open (fname
, mode
, _S_IREAD
| _S_IWRITE
);
2391 else if (ref_fd
== -1)
2392 *fd
= -1; /* reset to default destination */
2395 *fd
= _dup (ref_fd
);
2399 /* _open just sets a flag for O_APPEND, which won't be passed to the
2400 inferior, so we need to actually move the file pointer. */
2401 if ((mode
& O_APPEND
) != 0)
2402 _lseek (*fd
, 0L, SEEK_END
);
2406 /* Canonicalize a single redirection spec and set up the corresponding
2407 file descriptor as specified. */
2409 redir_set_redirection (const char *s
, int *inp
, int *out
, int *err
)
2411 char buf
[__PMAX
+ 2 + 5]; /* extra space for quotes & redirection string */
2413 const char *start
= s
;
2416 *d
++ = *s
++; /* copy the 1st character, < or > or a digit */
2417 if ((*start
== '>' || *start
== '1' || *start
== '2')
2421 if (*s
== '>' && *start
!= '>')
2424 else if (*start
== '0' && *s
== '<')
2426 /* cmd.exe recognizes "&N" only immediately after the redirection symbol. */
2429 while (isspace (*s
)) /* skip whitespace before file name */
2431 *d
++ = ' '; /* separate file name with a single space */
2434 /* Copy the file name. */
2437 /* Remove quoting characters from the file name in buf[]. */
2438 if (*s
== '"') /* could support '..' quoting here */
2442 else if (*s
== quote
)
2450 else if (*s
== '\\')
2452 if (s
[1] == '"') /* could support '..' here */
2456 else if (isspace (*s
) && !quote
)
2460 if (d
- buf
>= sizeof (buf
) - 1)
2462 errno
= ENAMETOOLONG
;
2468 /* Windows doesn't allow redirection characters in file names, so we
2469 can bail out early if they use them, or if there's no target file
2470 name after the redirection symbol. */
2471 if (d
[-1] == '>' || d
[-1] == '<')
2476 if (redir_open (buf
, inp
, out
, err
) == 0)
2481 /* Parse the command line for redirection specs and prepare the file
2482 descriptors for the 3 standard streams accordingly. */
2484 redirect_inferior_handles (const char *cmd_orig
, char *cmd
,
2485 int *inp
, int *out
, int *err
)
2487 const char *s
= cmd_orig
;
2490 bool retval
= false;
2492 while (isspace (*s
))
2497 if (*s
== '"') /* could also support '..' quoting here */
2501 else if (*s
== quote
)
2504 else if (*s
== '\\')
2506 if (s
[1] == '"') /* escaped quote char */
2511 /* Process a single redirection candidate. */
2512 if (*s
== '<' || *s
== '>'
2513 || ((*s
== '1' || *s
== '2') && s
[1] == '>')
2514 || (*s
== '0' && s
[1] == '<'))
2516 int skip
= redir_set_redirection (s
, inp
, out
, err
);
2530 #endif /* !__CYGWIN__ */
2532 /* Start an inferior windows child process and sets inferior_ptid to its pid.
2533 EXEC_FILE is the file to run.
2534 ALLARGS is a string containing the arguments to the program.
2535 ENV is the environment vector to pass. Errors reported with error(). */
2538 windows_nat_target::create_inferior (const char *exec_file
,
2539 const std::string
&origallargs
,
2540 char **in_env
, int from_tty
)
2544 wchar_t real_path
[__PMAX
];
2545 wchar_t shell
[__PMAX
]; /* Path to shell */
2546 wchar_t infcwd
[__PMAX
];
2549 wchar_t *cygallargs
;
2551 char **old_env
= NULL
;
2555 int ostdin
, ostdout
, ostderr
;
2556 #else /* !__CYGWIN__ */
2557 char shell
[__PMAX
]; /* Path to shell */
2559 char *args
, *allargs_copy
;
2560 size_t args_len
, allargs_len
;
2561 int fd_inp
= -1, fd_out
= -1, fd_err
= -1;
2562 HANDLE tty
= INVALID_HANDLE_VALUE
;
2563 bool redirected
= false;
2570 #endif /* !__CYGWIN__ */
2571 const char *allargs
= origallargs
.c_str ();
2572 PROCESS_INFORMATION pi
;
2573 std::optional
<unsigned> ret
;
2575 const std::string
&inferior_tty
= current_inferior ()->tty ();
2578 error (_("No executable specified, use `target exec'."));
2580 const char *inferior_cwd
= current_inferior ()->cwd ().c_str ();
2581 std::string expanded_infcwd
;
2582 if (*inferior_cwd
== '\0')
2583 inferior_cwd
= nullptr;
2586 expanded_infcwd
= gdb_tilde_expand (inferior_cwd
);
2587 /* Mirror slashes on inferior's cwd. */
2588 std::replace (expanded_infcwd
.begin (), expanded_infcwd
.end (),
2590 inferior_cwd
= expanded_infcwd
.c_str ();
2593 memset (&si
, 0, sizeof (si
));
2594 si
.cb
= sizeof (si
);
2597 flags
|= CREATE_NEW_PROCESS_GROUP
;
2600 windows_set_console_info (&si
, &flags
);
2605 flags
|= DEBUG_ONLY_THIS_PROCESS
;
2606 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W
, exec_file
, real_path
,
2607 __PMAX
* sizeof (wchar_t)) < 0)
2608 error (_("Error starting executable: %d"), errno
);
2610 len
= mbstowcs (NULL
, allargs
, 0) + 1;
2611 if (len
== (size_t) -1)
2612 error (_("Error starting executable: %d"), errno
);
2613 cygallargs
= (wchar_t *) alloca (len
* sizeof (wchar_t));
2614 mbstowcs (cygallargs
, allargs
, len
);
2619 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W
, sh
, shell
, __PMAX
) < 0)
2620 error (_("Error starting executable via shell: %d"), errno
);
2621 len
= sizeof (L
" -c 'exec '") + mbstowcs (NULL
, exec_file
, 0)
2622 + mbstowcs (NULL
, allargs
, 0) + 2;
2623 cygallargs
= (wchar_t *) alloca (len
* sizeof (wchar_t));
2624 swprintf (cygallargs
, len
, L
" -c 'exec %s %s'", exec_file
, allargs
);
2626 flags
|= DEBUG_PROCESS
;
2629 if (inferior_cwd
!= NULL
2630 && cygwin_conv_path (CCP_POSIX_TO_WIN_W
, inferior_cwd
,
2631 infcwd
, strlen (inferior_cwd
)) < 0)
2632 error (_("Error converting inferior cwd: %d"), errno
);
2634 args
= (wchar_t *) alloca ((wcslen (toexec
) + wcslen (cygallargs
) + 2)
2635 * sizeof (wchar_t));
2636 wcscpy (args
, toexec
);
2637 wcscat (args
, L
" ");
2638 wcscat (args
, cygallargs
);
2640 #ifdef CW_CVT_ENV_TO_WINENV
2641 /* First try to create a direct Win32 copy of the POSIX environment. */
2642 w32_env
= (PWCHAR
) cygwin_internal (CW_CVT_ENV_TO_WINENV
, in_env
);
2643 if (w32_env
!= (PWCHAR
) -1)
2644 flags
|= CREATE_UNICODE_ENVIRONMENT
;
2646 /* If that fails, fall back to old method tweaking GDB's environment. */
2647 #endif /* CW_CVT_ENV_TO_WINENV */
2649 /* Reset all Win32 environment variables to avoid leftover on next run. */
2650 clear_win32_environment (environ
);
2651 /* Prepare the environment vars for CreateProcess. */
2654 cygwin_internal (CW_SYNC_WINENV
);
2658 if (inferior_tty
.empty ())
2659 tty
= ostdin
= ostdout
= ostderr
= -1;
2662 tty
= open (inferior_tty
.c_str (), O_RDWR
| O_NOCTTY
);
2665 warning_filename_and_errno (inferior_tty
.c_str (), errno
);
2666 ostdin
= ostdout
= ostderr
= -1;
2679 windows_init_thread_list ();
2680 do_synchronously ([&] ()
2682 BOOL ok
= create_process (nullptr, args
, flags
, w32_env
,
2683 inferior_cwd
!= nullptr ? infcwd
: nullptr,
2684 disable_randomization
,
2688 ret
= (unsigned) GetLastError ();
2694 /* Just free the Win32 environment, if it could be created. */
2698 /* Reset all environment variables to avoid leftover on next run. */
2699 clear_win32_environment (in_env
);
2700 /* Restore normal GDB environment variables. */
2702 cygwin_internal (CW_SYNC_WINENV
);
2715 #else /* !__CYGWIN__ */
2716 allargs_len
= strlen (allargs
);
2717 allargs_copy
= strcpy ((char *) alloca (allargs_len
+ 1), allargs
);
2718 if (strpbrk (allargs_copy
, "<>") != NULL
)
2723 redirect_inferior_handles (allargs
, allargs_copy
,
2724 &fd_inp
, &fd_out
, &fd_err
);
2726 warning (_("Error in redirection: %s."), safe_strerror (errno
));
2729 allargs_len
= strlen (allargs_copy
);
2731 /* If not all the standard streams are redirected by the command
2732 line, use INFERIOR_TTY for those which aren't. */
2733 if (!inferior_tty
.empty ()
2734 && !(fd_inp
>= 0 && fd_out
>= 0 && fd_err
>= 0))
2736 SECURITY_ATTRIBUTES sa
;
2737 sa
.nLength
= sizeof(sa
);
2738 sa
.lpSecurityDescriptor
= 0;
2739 sa
.bInheritHandle
= TRUE
;
2740 tty
= CreateFileA (inferior_tty
.c_str (), GENERIC_READ
| GENERIC_WRITE
,
2741 0, &sa
, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
2742 if (tty
== INVALID_HANDLE_VALUE
)
2744 unsigned err
= (unsigned) GetLastError ();
2745 warning (_("Warning: Failed to open TTY %s, error %#x: %s"),
2746 inferior_tty
.c_str (), err
, strwinerror (err
));
2749 if (redirected
|| tty
!= INVALID_HANDLE_VALUE
)
2752 si
.hStdInput
= (HANDLE
) _get_osfhandle (fd_inp
);
2753 else if (tty
!= INVALID_HANDLE_VALUE
)
2756 si
.hStdInput
= GetStdHandle (STD_INPUT_HANDLE
);
2758 si
.hStdOutput
= (HANDLE
) _get_osfhandle (fd_out
);
2759 else if (tty
!= INVALID_HANDLE_VALUE
)
2760 si
.hStdOutput
= tty
;
2762 si
.hStdOutput
= GetStdHandle (STD_OUTPUT_HANDLE
);
2764 si
.hStdError
= (HANDLE
) _get_osfhandle (fd_err
);
2765 else if (tty
!= INVALID_HANDLE_VALUE
)
2768 si
.hStdError
= GetStdHandle (STD_ERROR_HANDLE
);
2769 si
.dwFlags
|= STARTF_USESTDHANDLES
;
2773 /* Build the command line, a space-separated list of tokens where
2774 the first token is the name of the module to be executed.
2775 To avoid ambiguities introduced by spaces in the module name,
2777 args_len
= strlen (toexec
) + 2 /* quotes */ + allargs_len
+ 2;
2778 args
= (char *) alloca (args_len
);
2779 xsnprintf (args
, args_len
, "\"%s\" %s", toexec
, allargs_copy
);
2781 flags
|= DEBUG_ONLY_THIS_PROCESS
;
2783 /* CreateProcess takes the environment list as a null terminated set of
2784 strings (i.e. two nulls terminate the list). */
2786 /* Get total size for env strings. */
2787 for (envlen
= 0, i
= 0; in_env
[i
] && *in_env
[i
]; i
++)
2788 envlen
+= strlen (in_env
[i
]) + 1;
2790 envsize
= sizeof (in_env
[0]) * (i
+ 1);
2791 env
= (char **) alloca (envsize
);
2792 memcpy (env
, in_env
, envsize
);
2793 /* Windows programs expect the environment block to be sorted. */
2794 qsort (env
, i
, sizeof (char *), envvar_cmp
);
2796 w32env
= (char *) alloca (envlen
+ 1);
2798 /* Copy env strings into new buffer. */
2799 for (temp
= w32env
, i
= 0; env
[i
] && *env
[i
]; i
++)
2801 strcpy (temp
, env
[i
]);
2802 temp
+= strlen (temp
) + 1;
2805 /* Final nil string to terminate new env. */
2808 windows_init_thread_list ();
2809 do_synchronously ([&] ()
2811 BOOL ok
= create_process (nullptr, /* image */
2812 args
, /* command line */
2813 flags
, /* start flags */
2814 w32env
, /* environment */
2815 inferior_cwd
, /* current directory */
2816 disable_randomization
,
2820 ret
= (unsigned) GetLastError ();
2824 if (tty
!= INVALID_HANDLE_VALUE
)
2832 #endif /* !__CYGWIN__ */
2834 if (ret
.has_value ())
2836 std::string msg
= _("Error creating process ") + std::string (exec_file
);
2837 throw_winerror_with_name (msg
.c_str (), *ret
);
2842 if (IsWow64Process (pi
.hProcess
, &wow64
))
2843 windows_process
.wow64_process
= wow64
;
2846 CloseHandle (pi
.hThread
);
2847 CloseHandle (pi
.hProcess
);
2849 if (useshell
&& shell
[0] != '\0')
2850 windows_process
.saw_create
= -1;
2852 windows_process
.saw_create
= 0;
2854 do_initial_windows_stuff (pi
.dwProcessId
, 0);
2856 /* windows_continue (DBG_CONTINUE, -1, 0); */
2860 windows_nat_target::mourn_inferior ()
2862 (void) windows_continue (DBG_CONTINUE
, -1, 0, true);
2863 x86_cleanup_dregs();
2864 if (windows_process
.open_process_used
)
2866 CHECK (CloseHandle (windows_process
.handle
));
2867 windows_process
.open_process_used
= 0;
2869 windows_process
.siginfo_er
.ExceptionCode
= 0;
2870 inf_child_target::mourn_inferior ();
2873 /* Helper for windows_xfer_partial that handles memory transfers.
2874 Arguments are like target_xfer_partial. */
2876 static enum target_xfer_status
2877 windows_xfer_memory (gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
2878 ULONGEST memaddr
, ULONGEST len
, ULONGEST
*xfered_len
)
2882 DWORD lasterror
= 0;
2884 if (writebuf
!= NULL
)
2886 DEBUG_MEM ("write target memory, %s bytes at %s",
2887 pulongest (len
), core_addr_to_string (memaddr
));
2888 success
= WriteProcessMemory (windows_process
.handle
,
2889 (LPVOID
) (uintptr_t) memaddr
, writebuf
,
2892 lasterror
= GetLastError ();
2893 FlushInstructionCache (windows_process
.handle
,
2894 (LPCVOID
) (uintptr_t) memaddr
, len
);
2898 DEBUG_MEM ("read target memory, %s bytes at %s",
2899 pulongest (len
), core_addr_to_string (memaddr
));
2900 success
= ReadProcessMemory (windows_process
.handle
,
2901 (LPCVOID
) (uintptr_t) memaddr
, readbuf
,
2904 lasterror
= GetLastError ();
2906 *xfered_len
= (ULONGEST
) done
;
2907 if (!success
&& lasterror
== ERROR_PARTIAL_COPY
&& done
> 0)
2908 return TARGET_XFER_OK
;
2910 return success
? TARGET_XFER_OK
: TARGET_XFER_E_IO
;
2914 windows_nat_target::kill ()
2916 CHECK (TerminateProcess (windows_process
.handle
, 0));
2920 if (!windows_continue (DBG_CONTINUE
, -1, 1))
2922 wait_for_debug_event_main_thread (&windows_process
.current_event
);
2923 if (windows_process
.current_event
.dwDebugEventCode
2924 == EXIT_PROCESS_DEBUG_EVENT
)
2928 target_mourn_inferior (inferior_ptid
); /* Or just windows_mourn_inferior? */
2932 windows_nat_target::close ()
2934 DEBUG_EVENTS ("inferior_ptid=%d\n", inferior_ptid
.pid ());
2938 /* Convert pid to printable format. */
2940 windows_nat_target::pid_to_str (ptid_t ptid
)
2942 if (ptid
.lwp () != 0)
2943 return string_printf ("Thread %d.0x%lx", ptid
.pid (), ptid
.lwp ());
2945 return normal_pid_to_str (ptid
);
2948 static enum target_xfer_status
2949 windows_xfer_shared_libraries (struct target_ops
*ops
,
2950 enum target_object object
, const char *annex
,
2951 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
2952 ULONGEST offset
, ULONGEST len
,
2953 ULONGEST
*xfered_len
)
2956 return TARGET_XFER_E_IO
;
2958 std::string xml
= "<library-list>\n";
2959 for (windows_solib
&so
: windows_process
.solibs
)
2960 windows_xfer_shared_library (so
.name
.c_str (),
2961 (CORE_ADDR
) (uintptr_t) so
.load_addr
,
2963 current_inferior ()->arch (), xml
);
2964 xml
+= "</library-list>\n";
2966 ULONGEST len_avail
= xml
.size ();
2967 if (offset
>= len_avail
)
2971 if (len
> len_avail
- offset
)
2972 len
= len_avail
- offset
;
2973 memcpy (readbuf
, xml
.data () + offset
, len
);
2976 *xfered_len
= (ULONGEST
) len
;
2977 return len
!= 0 ? TARGET_XFER_OK
: TARGET_XFER_EOF
;
2980 /* Helper for windows_nat_target::xfer_partial that handles signal info. */
2982 static enum target_xfer_status
2983 windows_xfer_siginfo (gdb_byte
*readbuf
, ULONGEST offset
, ULONGEST len
,
2984 ULONGEST
*xfered_len
)
2986 char *buf
= (char *) &windows_process
.siginfo_er
;
2987 size_t bufsize
= sizeof (windows_process
.siginfo_er
);
2990 EXCEPTION_RECORD32 er32
;
2991 if (windows_process
.wow64_process
)
2993 buf
= (char *) &er32
;
2994 bufsize
= sizeof (er32
);
2996 er32
.ExceptionCode
= windows_process
.siginfo_er
.ExceptionCode
;
2997 er32
.ExceptionFlags
= windows_process
.siginfo_er
.ExceptionFlags
;
2998 er32
.ExceptionRecord
2999 = (uintptr_t) windows_process
.siginfo_er
.ExceptionRecord
;
3000 er32
.ExceptionAddress
3001 = (uintptr_t) windows_process
.siginfo_er
.ExceptionAddress
;
3002 er32
.NumberParameters
= windows_process
.siginfo_er
.NumberParameters
;
3004 for (i
= 0; i
< EXCEPTION_MAXIMUM_PARAMETERS
; i
++)
3005 er32
.ExceptionInformation
[i
]
3006 = windows_process
.siginfo_er
.ExceptionInformation
[i
];
3010 if (windows_process
.siginfo_er
.ExceptionCode
== 0)
3011 return TARGET_XFER_E_IO
;
3013 if (readbuf
== nullptr)
3014 return TARGET_XFER_E_IO
;
3016 if (offset
> bufsize
)
3017 return TARGET_XFER_E_IO
;
3019 if (offset
+ len
> bufsize
)
3020 len
= bufsize
- offset
;
3022 memcpy (readbuf
, buf
+ offset
, len
);
3025 return TARGET_XFER_OK
;
3028 enum target_xfer_status
3029 windows_nat_target::xfer_partial (enum target_object object
,
3030 const char *annex
, gdb_byte
*readbuf
,
3031 const gdb_byte
*writebuf
, ULONGEST offset
,
3032 ULONGEST len
, ULONGEST
*xfered_len
)
3036 case TARGET_OBJECT_MEMORY
:
3037 return windows_xfer_memory (readbuf
, writebuf
, offset
, len
, xfered_len
);
3039 case TARGET_OBJECT_LIBRARIES
:
3040 return windows_xfer_shared_libraries (this, object
, annex
, readbuf
,
3041 writebuf
, offset
, len
, xfered_len
);
3043 case TARGET_OBJECT_SIGNAL_INFO
:
3044 return windows_xfer_siginfo (readbuf
, offset
, len
, xfered_len
);
3047 if (beneath () == NULL
)
3049 /* This can happen when requesting the transfer of unsupported
3050 objects before a program has been started (and therefore
3051 with the current_target having no target beneath). */
3052 return TARGET_XFER_E_IO
;
3054 return beneath ()->xfer_partial (object
, annex
,
3055 readbuf
, writebuf
, offset
, len
,
3060 /* Provide thread local base, i.e. Thread Information Block address.
3061 Returns 1 if ptid is found and sets *ADDR to thread_local_base. */
3064 windows_nat_target::get_tib_address (ptid_t ptid
, CORE_ADDR
*addr
)
3066 windows_thread_info
*th
;
3068 th
= windows_process
.thread_rec (ptid
, DONT_INVALIDATE_CONTEXT
);
3073 *addr
= th
->thread_local_base
;
3079 windows_nat_target::get_ada_task_ptid (long lwp
, ULONGEST thread
)
3081 return ptid_t (inferior_ptid
.pid (), lwp
, 0);
3084 /* Implementation of the to_thread_name method. */
3087 windows_nat_target::thread_name (struct thread_info
*thr
)
3089 windows_thread_info
*th
3090 = windows_process
.thread_rec (thr
->ptid
,
3091 DONT_INVALIDATE_CONTEXT
);
3092 return th
->thread_name ();
3096 INIT_GDB_FILE (windows_nat
)
3098 x86_dr_low
.set_control
= cygwin_set_dr7
;
3099 x86_dr_low
.set_addr
= cygwin_set_dr
;
3100 x86_dr_low
.get_addr
= cygwin_get_dr
;
3101 x86_dr_low
.get_status
= cygwin_get_dr6
;
3102 x86_dr_low
.get_control
= cygwin_get_dr7
;
3104 /* x86_dr_low.debug_register_length field is set by
3105 calling x86_set_debug_register_length function
3106 in processor windows specific native file. */
3108 /* The target is not a global specifically to avoid a C++ "static
3109 initializer fiasco" situation. */
3110 add_inf_child_target (new windows_nat_target
);
3113 cygwin_internal (CW_SET_DOS_FILE_WARNING
, 0);
3116 add_com ("signal-event", class_run
, signal_event_command
, _("\
3117 Signal a crashed process with event ID, to allow its debugging.\n\
3118 This command is needed in support of setting up GDB as JIT debugger on\n\
3119 MS-Windows. The command should be invoked from the GDB command line using\n\
3120 the '-ex' command-line option. The ID of the event that blocks the\n\
3121 crashed process will be supplied by the Windows JIT debugging mechanism."));
3124 add_setshow_boolean_cmd ("shell", class_support
, &useshell
, _("\
3125 Set use of shell to start subprocess."), _("\
3126 Show use of shell to start subprocess."), NULL
,
3128 NULL
, /* FIXME: i18n: */
3129 &setlist
, &showlist
);
3131 add_setshow_boolean_cmd ("cygwin-exceptions", class_support
,
3132 &cygwin_exceptions
, _("\
3133 Break when an exception is detected in the Cygwin DLL itself."), _("\
3134 Show whether gdb breaks on exceptions in the Cygwin DLL itself."), NULL
,
3136 NULL
, /* FIXME: i18n: */
3137 &setlist
, &showlist
);
3140 add_setshow_boolean_cmd ("new-console", class_support
, &new_console
, _("\
3141 Set creation of new console when creating child process."), _("\
3142 Show creation of new console when creating child process."), NULL
,
3144 NULL
, /* FIXME: i18n: */
3145 &setlist
, &showlist
);
3147 add_setshow_boolean_cmd ("new-group", class_support
, &new_group
, _("\
3148 Set creation of new group when creating child process."), _("\
3149 Show creation of new group when creating child process."), NULL
,
3151 NULL
, /* FIXME: i18n: */
3152 &setlist
, &showlist
);
3154 add_setshow_boolean_cmd ("debugexec", class_support
, &debug_exec
, _("\
3155 Set whether to display execution in child process."), _("\
3156 Show whether to display execution in child process."), NULL
,
3158 NULL
, /* FIXME: i18n: */
3159 &setlist
, &showlist
);
3161 add_setshow_boolean_cmd ("debugevents", class_support
, &debug_events
, _("\
3162 Set whether to display kernel events in child process."), _("\
3163 Show whether to display kernel events in child process."), NULL
,
3165 NULL
, /* FIXME: i18n: */
3166 &setlist
, &showlist
);
3168 add_setshow_boolean_cmd ("debugmemory", class_support
, &debug_memory
, _("\
3169 Set whether to display memory accesses in child process."), _("\
3170 Show whether to display memory accesses in child process."), NULL
,
3172 NULL
, /* FIXME: i18n: */
3173 &setlist
, &showlist
);
3175 add_setshow_boolean_cmd ("debugexceptions", class_support
,
3176 &debug_exceptions
, _("\
3177 Set whether to display kernel exceptions in child process."), _("\
3178 Show whether to display kernel exceptions in child process."), NULL
,
3180 NULL
, /* FIXME: i18n: */
3181 &setlist
, &showlist
);
3183 init_w32_command_list ();
3185 add_cmd ("selector", class_info
, display_selectors
,
3186 _("Display selectors infos."),
3189 if (!initialize_loadable ())
3191 /* This will probably fail on Windows 9x/Me. Let the user know
3192 that we're missing some functionality. */
3194 cannot automatically find executable file or library to read symbols.\n\
3195 Use \"%ps\" or \"%ps\" command to load executable/libraries directly."),
3196 styled_string (command_style
.style (), "file"),
3197 styled_string (command_style
.style (), "dll"));
3201 /* Hardware watchpoint support, adapted from go32-nat.c code. */
3203 /* Pass the address ADDR to the inferior in the I'th debug register.
3204 Here we just store the address in dr array, the registers will be
3205 actually set up when windows_continue is called. */
3207 cygwin_set_dr (int i
, CORE_ADDR addr
)
3210 internal_error (_("Invalid register %d in cygwin_set_dr.\n"), i
);
3211 windows_process
.dr
[i
] = addr
;
3213 for (auto &th
: windows_process
.thread_list
)
3214 th
->debug_registers_changed
= true;
3217 /* Pass the value VAL to the inferior in the DR7 debug control
3218 register. Here we just store the address in D_REGS, the watchpoint
3219 will be actually set up in windows_wait. */
3221 cygwin_set_dr7 (unsigned long val
)
3223 windows_process
.dr
[7] = (CORE_ADDR
) val
;
3225 for (auto &th
: windows_process
.thread_list
)
3226 th
->debug_registers_changed
= true;
3229 /* Get the value of debug register I from the inferior. */
3232 cygwin_get_dr (int i
)
3234 return windows_process
.dr
[i
];
3237 /* Get the value of the DR6 debug status register from the inferior.
3238 Here we just return the value stored in dr[6]
3239 by the last call to thread_rec for current_event.dwThreadId id. */
3240 static unsigned long
3241 cygwin_get_dr6 (void)
3243 return (unsigned long) windows_process
.dr
[6];
3246 /* Get the value of the DR7 debug status register from the inferior.
3247 Here we just return the value stored in dr[7] by the last call to
3248 thread_rec for current_event.dwThreadId id. */
3250 static unsigned long
3251 cygwin_get_dr7 (void)
3253 return (unsigned long) windows_process
.dr
[7];
3256 /* Determine if the thread referenced by "ptid" is alive
3257 by "polling" it. If WaitForSingleObject returns WAIT_OBJECT_0
3258 it means that the thread has died. Otherwise it is assumed to be alive. */
3261 windows_nat_target::thread_alive (ptid_t ptid
)
3263 gdb_assert (ptid
.lwp () != 0);
3265 windows_thread_info
*th
3266 = windows_process
.thread_rec (ptid
, DONT_INVALIDATE_CONTEXT
);
3267 return WaitForSingleObject (th
->h
, 0) != WAIT_OBJECT_0
;
3270 INIT_GDB_FILE (check_for_gdb_ini
)
3273 if (inhibit_gdbinit
)
3276 homedir
= getenv ("HOME");
3280 char *oldini
= (char *) alloca (strlen (homedir
) +
3281 sizeof ("gdb.ini") + 1);
3282 strcpy (oldini
, homedir
);
3283 p
= strchr (oldini
, '\0');
3284 if (p
> oldini
&& !IS_DIR_SEPARATOR (p
[-1]))
3286 strcpy (p
, "gdb.ini");
3287 if (access (oldini
, 0) == 0)
3289 int len
= strlen (oldini
);
3290 char *newini
= (char *) alloca (len
+ 2);
3292 xsnprintf (newini
, len
+ 2, "%.*s.gdbinit",
3293 (int) (len
- (sizeof ("gdb.ini") - 1)), oldini
);
3294 warning (_("obsolete '%s' found. Rename to '%s'."), oldini
, newini
);