1 /* Target-vector operations for controlling windows child processes, for GDB.
3 Copyright (C) 1995-2022 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 */
25 #include "frame.h" /* required by inferior.h */
31 #include "completer.h"
35 #include <sys/types.h>
41 #include <sys/cygwin.h>
42 #include <cygwin/version.h>
47 #include "filenames.h"
51 #include "gdbsupport/gdb_obstack.h"
52 #include "gdbthread.h"
58 #include "xml-support.h"
61 #include "i386-tdep.h"
62 #include "i387-tdep.h"
64 #include "windows-tdep.h"
65 #include "windows-nat.h"
67 #include "complaints.h"
68 #include "inf-child.h"
69 #include "gdbsupport/gdb_tilde_expand.h"
70 #include "gdbsupport/pathstuff.h"
71 #include "gdbsupport/gdb_wait.h"
72 #include "nat/windows-nat.h"
73 #include "gdbsupport/symbol.h"
75 using namespace windows_nat
;
77 /* The current process. */
78 static windows_process_info windows_process
;
82 #undef GetModuleFileNameEx
85 # define __PMAX (MAX_PATH + 1)
86 # define GetModuleFileNameEx GetModuleFileNameExA
87 # define STARTUPINFO STARTUPINFOA
88 # define CreateProcess CreateProcessA
90 # define __PMAX PATH_MAX
91 /* The starting and ending address of the cygwin1.dll text segment. */
92 static CORE_ADDR cygwin_load_start
;
93 static CORE_ADDR cygwin_load_end
;
95 typedef wchar_t cygwin_buf_t
;
96 # define GetModuleFileNameEx GetModuleFileNameExW
97 # define STARTUPINFO STARTUPINFOW
98 # define CreateProcess CreateProcessW
101 static int have_saved_context
; /* True if we've saved context from a
104 static CONTEXT saved_context
; /* Contains the saved context from a
108 /* If we're not using the old Cygwin header file set, define the
109 following which never should have been in the generic Win32 API
110 headers in the first place since they were our own invention... */
111 #ifndef _GNU_H_WINDOWS_H
114 FLAG_TRACE_BIT
= 0x100,
118 #ifndef CONTEXT_EXTENDED_REGISTERS
119 /* This macro is only defined on ia32. It only makes sense on this target,
120 so define it as zero if not already defined. */
121 #define CONTEXT_EXTENDED_REGISTERS 0
124 #define CONTEXT_DEBUGGER_DR CONTEXT_FULL | CONTEXT_FLOATING_POINT \
125 | CONTEXT_SEGMENTS | CONTEXT_DEBUG_REGISTERS \
126 | CONTEXT_EXTENDED_REGISTERS
128 static uintptr_t dr
[8];
130 static int windows_initialization_done
;
131 #define DR6_CLEAR_VALUE 0xffff0ff0
133 /* The string sent by cygwin when it processes a signal.
134 FIXME: This should be in a cygwin include file. */
135 #ifndef _CYGWIN_SIGNAL_STRING
136 #define _CYGWIN_SIGNAL_STRING "cYgSiGw00f"
139 #define CHECK(x) check (x, __FILE__,__LINE__)
140 #define DEBUG_EXEC(fmt, ...) \
141 debug_prefixed_printf_cond (debug_exec, "windows exec", fmt, ## __VA_ARGS__)
142 #define DEBUG_EVENTS(fmt, ...) \
143 debug_prefixed_printf_cond (debug_events, "windows events", fmt, \
145 #define DEBUG_MEM(fmt, ...) \
146 debug_prefixed_printf_cond (debug_memory, "windows mem", fmt, \
148 #define DEBUG_EXCEPT(fmt, ...) \
149 debug_prefixed_printf_cond (debug_exceptions, "windows except", fmt, \
152 static void cygwin_set_dr (int i
, CORE_ADDR addr
);
153 static void cygwin_set_dr7 (unsigned long val
);
154 static CORE_ADDR
cygwin_get_dr (int i
);
155 static unsigned long cygwin_get_dr6 (void);
156 static unsigned long cygwin_get_dr7 (void);
158 static std::vector
<std::unique_ptr
<windows_thread_info
>> thread_list
;
160 /* Counts of things. */
161 static int saw_create
;
162 static int open_process_used
= 0;
164 static void *wow64_dbgbreak
;
168 static bool new_console
= false;
170 static bool cygwin_exceptions
= false;
172 static bool new_group
= true;
173 static bool debug_exec
= false; /* show execution */
174 static bool debug_events
= false; /* show events from kernel */
175 static bool debug_memory
= false; /* show target memory accesses */
176 static bool debug_exceptions
= false; /* show target exceptions */
177 static bool useshell
= false; /* use shell for subprocesses */
179 /* This vector maps GDB's idea of a register's number into an offset
180 in the windows exception context vector.
182 It also contains the bit mask needed to load the register in question.
184 The contents of this table can only be computed by the units
185 that provide CPU-specific support for Windows native debugging.
186 These units should set the table by calling
187 windows_set_context_register_offsets.
189 One day we could read a reg, we could inspect the context we
190 already have loaded, if it doesn't have the bit set that we need,
191 we read that set of registers in using GetThreadContext. If the
192 context already contains what we need, we just unpack it. Then to
193 write a register, first we have to ensure that the context contains
194 the other regs of the group, and then we copy the info in and set
197 static const int *mappings
;
199 /* The function to use in order to determine whether a register is
200 a segment register or not. */
201 static segment_register_p_ftype
*segment_register_p
;
203 /* See windows_nat_target::resume to understand why this is commented
206 /* This vector maps the target's idea of an exception (extracted
207 from the DEBUG_EVENT structure) to GDB's idea. */
209 struct xlate_exception
215 static const struct xlate_exception xlate
[] =
217 {EXCEPTION_ACCESS_VIOLATION
, GDB_SIGNAL_SEGV
},
218 {STATUS_STACK_OVERFLOW
, GDB_SIGNAL_SEGV
},
219 {EXCEPTION_BREAKPOINT
, GDB_SIGNAL_TRAP
},
220 {DBG_CONTROL_C
, GDB_SIGNAL_INT
},
221 {EXCEPTION_SINGLE_STEP
, GDB_SIGNAL_TRAP
},
222 {STATUS_FLOAT_DIVIDE_BY_ZERO
, GDB_SIGNAL_FPE
}
227 struct windows_nat_target final
: public x86_nat_target
<inf_child_target
>
229 void close () override
;
231 void attach (const char *, int) override
;
233 bool attach_no_wait () override
236 void detach (inferior
*, int) override
;
238 void resume (ptid_t
, int , enum gdb_signal
) override
;
240 ptid_t
wait (ptid_t
, struct target_waitstatus
*, target_wait_flags
) override
;
242 void fetch_registers (struct regcache
*, int) override
;
243 void store_registers (struct regcache
*, int) override
;
245 bool stopped_by_sw_breakpoint () override
247 windows_thread_info
*th
248 = windows_process
.thread_rec (inferior_ptid
, DONT_INVALIDATE_CONTEXT
);
249 return th
->stopped_at_software_breakpoint
;
252 bool supports_stopped_by_sw_breakpoint () override
257 enum target_xfer_status
xfer_partial (enum target_object object
,
260 const gdb_byte
*writebuf
,
261 ULONGEST offset
, ULONGEST len
,
262 ULONGEST
*xfered_len
) override
;
264 void files_info () override
;
266 void kill () override
;
268 void create_inferior (const char *, const std::string
&,
269 char **, int) override
;
271 void mourn_inferior () override
;
273 bool thread_alive (ptid_t ptid
) override
;
275 std::string
pid_to_str (ptid_t
) override
;
277 void interrupt () override
;
279 const char *pid_to_exec_file (int pid
) override
;
281 ptid_t
get_ada_task_ptid (long lwp
, ULONGEST thread
) override
;
283 bool get_tib_address (ptid_t ptid
, CORE_ADDR
*addr
) override
;
285 const char *thread_name (struct thread_info
*) override
;
287 int get_windows_debug_event (int pid
, struct target_waitstatus
*ourstatus
);
289 void do_initial_windows_stuff (DWORD pid
, bool attaching
);
292 static windows_nat_target the_windows_nat_target
;
294 /* Set the MAPPINGS static global to OFFSETS.
295 See the description of MAPPINGS for more details. */
298 windows_set_context_register_offsets (const int *offsets
)
303 /* Set the function that should be used by this module to determine
304 whether a given register is a segment register or not. */
307 windows_set_segment_register_p (segment_register_p_ftype
*fun
)
309 segment_register_p
= fun
;
313 check (BOOL ok
, const char *file
, int line
)
316 gdb_printf ("error return %s:%d was %u\n", file
, line
,
317 (unsigned) GetLastError ());
320 /* See nat/windows-nat.h. */
322 windows_thread_info
*
323 windows_nat::windows_process_info::thread_rec
324 (ptid_t ptid
, thread_disposition_type disposition
)
326 for (auto &th
: thread_list
)
327 if (th
->tid
== ptid
.lwp ())
333 case DONT_INVALIDATE_CONTEXT
:
336 case INVALIDATE_CONTEXT
:
337 if (ptid
.lwp () != current_event
.dwThreadId
)
339 th
->reload_context
= true;
342 th
->reload_context
= true;
353 /* Add a thread to the thread list.
355 PTID is the ptid of the thread to be added.
356 H is its Windows handle.
357 TLB is its thread local base.
358 MAIN_THREAD_P should be true if the thread to be added is
359 the main thread, false otherwise. */
361 static windows_thread_info
*
362 windows_add_thread (ptid_t ptid
, HANDLE h
, void *tlb
, bool main_thread_p
)
364 windows_thread_info
*th
;
366 gdb_assert (ptid
.lwp () != 0);
368 if ((th
= windows_process
.thread_rec (ptid
, DONT_INVALIDATE_CONTEXT
)))
371 CORE_ADDR base
= (CORE_ADDR
) (uintptr_t) tlb
;
373 /* For WOW64 processes, this is actually the pointer to the 64bit TIB,
374 and the 32bit TIB is exactly 2 pages after it. */
375 if (windows_process
.wow64_process
)
378 th
= new windows_thread_info (ptid
.lwp (), h
, base
);
379 thread_list
.emplace_back (th
);
381 /* Add this new thread to the list of threads.
383 To be consistent with what's done on other platforms, we add
384 the main thread silently (in reality, this thread is really
385 more of a process to the user than a thread). */
387 add_thread_silent (&the_windows_nat_target
, ptid
);
389 add_thread (&the_windows_nat_target
, ptid
);
391 /* It's simplest to always set this and update the debug
393 th
->debug_registers_changed
= true;
398 /* Clear out any old thread list and reinitialize it to a
401 windows_init_thread_list (void)
403 DEBUG_EVENTS ("called");
404 thread_list
.clear ();
407 /* Delete a thread from the list of threads.
409 PTID is the ptid of the thread to be deleted.
410 EXIT_CODE is the thread's exit code.
411 MAIN_THREAD_P should be true if the thread to be deleted is
412 the main thread, false otherwise. */
415 windows_delete_thread (ptid_t ptid
, DWORD exit_code
, bool main_thread_p
)
419 gdb_assert (ptid
.lwp () != 0);
423 /* Emit a notification about the thread being deleted.
425 Note that no notification was printed when the main thread
426 was created, and thus, unless in verbose mode, we should be
427 symmetrical, and avoid that notification for the main thread
431 gdb_printf ("[Deleting %s]\n", target_pid_to_str (ptid
).c_str ());
432 else if (print_thread_events
&& !main_thread_p
)
433 gdb_printf (_("[%s exited with code %u]\n"),
434 target_pid_to_str (ptid
).c_str (),
435 (unsigned) exit_code
);
437 delete_thread (find_thread_ptid (&the_windows_nat_target
, ptid
));
439 auto iter
= std::find_if (thread_list
.begin (), thread_list
.end (),
442 return th
->tid
== id
;
445 if (iter
!= thread_list
.end ())
446 thread_list
.erase (iter
);
449 /* Fetches register number R from the given windows_thread_info,
450 and supplies its value to the given regcache.
452 This function assumes that R is non-negative. A failed assertion
453 is raised if that is not true.
455 This function assumes that TH->RELOAD_CONTEXT is not set, meaning
456 that the windows_thread_info has an up-to-date context. A failed
457 assertion is raised if that assumption is violated. */
460 windows_fetch_one_register (struct regcache
*regcache
,
461 windows_thread_info
*th
, int r
)
464 gdb_assert (!th
->reload_context
);
466 char *context_ptr
= (char *) &th
->context
;
468 if (windows_process
.wow64_process
)
469 context_ptr
= (char *) &th
->wow64_context
;
472 char *context_offset
= context_ptr
+ mappings
[r
];
473 struct gdbarch
*gdbarch
= regcache
->arch ();
474 i386_gdbarch_tdep
*tdep
= (i386_gdbarch_tdep
*) gdbarch_tdep (gdbarch
);
476 gdb_assert (!gdbarch_read_pc_p (gdbarch
));
477 gdb_assert (gdbarch_pc_regnum (gdbarch
) >= 0);
478 gdb_assert (!gdbarch_write_pc_p (gdbarch
));
480 if (r
== I387_FISEG_REGNUM (tdep
))
482 long l
= *((long *) context_offset
) & 0xffff;
483 regcache
->raw_supply (r
, (char *) &l
);
485 else if (r
== I387_FOP_REGNUM (tdep
))
487 long l
= (*((long *) context_offset
) >> 16) & ((1 << 11) - 1);
488 regcache
->raw_supply (r
, (char *) &l
);
490 else if (segment_register_p (r
))
492 /* GDB treats segment registers as 32bit registers, but they are
493 in fact only 16 bits long. Make sure we do not read extra
494 bits from our source buffer. */
495 long l
= *((long *) context_offset
) & 0xffff;
496 regcache
->raw_supply (r
, (char *) &l
);
500 if (th
->stopped_at_software_breakpoint
502 && r
== gdbarch_pc_regnum (gdbarch
))
504 int size
= register_size (gdbarch
, r
);
508 memcpy (&value
, context_offset
, size
);
509 value
-= gdbarch_decr_pc_after_break (gdbarch
);
510 memcpy (context_offset
, &value
, size
);
514 gdb_assert (size
== 8);
516 memcpy (&value
, context_offset
, size
);
517 value
-= gdbarch_decr_pc_after_break (gdbarch
);
518 memcpy (context_offset
, &value
, size
);
520 /* Make sure we only rewrite the PC a single time. */
521 th
->pc_adjusted
= true;
523 regcache
->raw_supply (r
, context_offset
);
528 windows_nat_target::fetch_registers (struct regcache
*regcache
, int r
)
530 windows_thread_info
*th
531 = windows_process
.thread_rec (regcache
->ptid (), INVALIDATE_CONTEXT
);
533 /* Check if TH exists. Windows sometimes uses a non-existent
534 thread id in its events. */
538 if (th
->reload_context
)
541 if (have_saved_context
)
543 /* Lie about where the program actually is stopped since
544 cygwin has informed us that we should consider the signal
545 to have occurred at another location which is stored in
547 memcpy (&th
->context
, &saved_context
,
548 __COPY_CONTEXT_SIZE
);
549 have_saved_context
= 0;
554 if (windows_process
.wow64_process
)
556 th
->wow64_context
.ContextFlags
= CONTEXT_DEBUGGER_DR
;
557 CHECK (Wow64GetThreadContext (th
->h
, &th
->wow64_context
));
558 /* Copy dr values from that thread.
559 But only if there were not modified since last stop.
561 if (!th
->debug_registers_changed
)
563 dr
[0] = th
->wow64_context
.Dr0
;
564 dr
[1] = th
->wow64_context
.Dr1
;
565 dr
[2] = th
->wow64_context
.Dr2
;
566 dr
[3] = th
->wow64_context
.Dr3
;
567 dr
[6] = th
->wow64_context
.Dr6
;
568 dr
[7] = th
->wow64_context
.Dr7
;
574 th
->context
.ContextFlags
= CONTEXT_DEBUGGER_DR
;
575 CHECK (GetThreadContext (th
->h
, &th
->context
));
576 /* Copy dr values from that thread.
577 But only if there were not modified since last stop.
579 if (!th
->debug_registers_changed
)
581 dr
[0] = th
->context
.Dr0
;
582 dr
[1] = th
->context
.Dr1
;
583 dr
[2] = th
->context
.Dr2
;
584 dr
[3] = th
->context
.Dr3
;
585 dr
[6] = th
->context
.Dr6
;
586 dr
[7] = th
->context
.Dr7
;
589 th
->reload_context
= false;
593 for (r
= 0; r
< gdbarch_num_regs (regcache
->arch()); r
++)
594 windows_fetch_one_register (regcache
, th
, r
);
596 windows_fetch_one_register (regcache
, th
, r
);
599 /* Collect the register number R from the given regcache, and store
600 its value into the corresponding area of the given thread's context.
602 This function assumes that R is non-negative. A failed assertion
603 assertion is raised if that is not true. */
606 windows_store_one_register (const struct regcache
*regcache
,
607 windows_thread_info
*th
, int r
)
611 char *context_ptr
= (char *) &th
->context
;
613 if (windows_process
.wow64_process
)
614 context_ptr
= (char *) &th
->wow64_context
;
617 regcache
->raw_collect (r
, context_ptr
+ mappings
[r
]);
620 /* Store a new register value into the context of the thread tied to
624 windows_nat_target::store_registers (struct regcache
*regcache
, int r
)
626 windows_thread_info
*th
627 = windows_process
.thread_rec (regcache
->ptid (), INVALIDATE_CONTEXT
);
629 /* Check if TH exists. Windows sometimes uses a non-existent
630 thread id in its events. */
635 for (r
= 0; r
< gdbarch_num_regs (regcache
->arch ()); r
++)
636 windows_store_one_register (regcache
, th
, r
);
638 windows_store_one_register (regcache
, th
, r
);
641 /* Maintain a linked list of "so" information. */
644 LPVOID load_addr
= 0;
645 CORE_ADDR text_offset
= 0;
648 std::string original_name
;
649 /* Expanded form of the name. */
653 static std::vector
<windows_solib
> solibs
;
655 /* See nat/windows-nat.h. */
657 static windows_solib
*
658 windows_make_so (const char *name
, LPVOID load_addr
)
664 WIN32_FIND_DATA w32_fd
;
665 HANDLE h
= FindFirstFile(name
, &w32_fd
);
667 if (h
== INVALID_HANDLE_VALUE
)
673 if (GetCurrentDirectory (MAX_PATH
+ 1, cwd
))
675 p
= strrchr (buf
, '\\');
678 SetCurrentDirectory (buf
);
679 GetFullPathName (w32_fd
.cFileName
, MAX_PATH
, buf
, &p
);
680 SetCurrentDirectory (cwd
);
683 if (strcasecmp (buf
, "ntdll.dll") == 0)
685 GetSystemDirectory (buf
, sizeof (buf
));
686 strcat (buf
, "\\ntdll.dll");
689 cygwin_buf_t buf
[__PMAX
];
692 if (access (name
, F_OK
) != 0)
694 if (strcasecmp (name
, "ntdll.dll") == 0)
697 GetSystemDirectoryW (buf
, sizeof (buf
) / sizeof (wchar_t));
698 wcscat (buf
, L
"\\ntdll.dll");
702 GetSystemDirectoryA (buf
, sizeof (buf
) / sizeof (wchar_t));
703 strcat (buf
, "\\ntdll.dll");
708 solibs
.emplace_back ();
709 windows_solib
*so
= &solibs
.back ();
710 so
->load_addr
= load_addr
;
711 so
->original_name
= name
;
717 char name
[SO_NAME_MAX_PATH_SIZE
];
718 cygwin_conv_path (CCP_WIN_W_TO_POSIX
, buf
, name
,
719 SO_NAME_MAX_PATH_SIZE
);
724 char *rname
= realpath (name
, NULL
);
725 if (rname
&& strlen (rname
) < SO_NAME_MAX_PATH_SIZE
)
732 warning (_("dll path for \"%s\" too long or inaccessible"), name
);
733 so
->name
= so
->original_name
;
736 /* Record cygwin1.dll .text start/end. */
737 size_t len
= sizeof ("/cygwin1.dll") - 1;
738 if (so
->name
.size () >= len
739 && strcasecmp (so
->name
.c_str () + so
->name
.size () - len
,
740 "/cygwin1.dll") == 0)
742 asection
*text
= NULL
;
744 gdb_bfd_ref_ptr
abfd (gdb_bfd_open (so
->name
, "pei-i386"));
749 if (bfd_check_format (abfd
.get (), bfd_object
))
750 text
= bfd_get_section_by_name (abfd
.get (), ".text");
755 /* The symbols in a dll are offset by 0x1000, which is the
756 offset from 0 of the first byte in an image - because of the
757 file header and the section alignment. */
758 cygwin_load_start
= (CORE_ADDR
) (uintptr_t) ((char *)
760 cygwin_load_end
= cygwin_load_start
+ bfd_section_size (text
);
767 /* See nat/windows-nat.h. */
770 windows_nat::windows_process_info::handle_load_dll (const char *dll_name
,
773 windows_solib
*solib
= windows_make_so (dll_name
, base
);
774 DEBUG_EVENTS ("Loading dll \"%s\" at %s.", solib
->name
.c_str (),
775 host_address_to_string (solib
->load_addr
));
778 /* See nat/windows-nat.h. */
781 windows_nat::windows_process_info::handle_unload_dll ()
783 LPVOID lpBaseOfDll
= current_event
.u
.UnloadDll
.lpBaseOfDll
;
785 auto iter
= std::remove_if (solibs
.begin (), solibs
.end (),
786 [&] (windows_solib
&lib
)
788 if (lib
.load_addr
== lpBaseOfDll
)
790 DEBUG_EVENTS ("Unloading dll \"%s\".", lib
.name
.c_str ());
796 if (iter
!= solibs
.end ())
798 solibs
.erase (iter
, solibs
.end ());
802 /* We did not find any DLL that was previously loaded at this address,
803 so register a complaint. We do not report an error, because we have
804 observed that this may be happening under some circumstances. For
805 instance, running 32bit applications on x64 Windows causes us to receive
806 4 mysterious UNLOAD_DLL_DEBUG_EVENTs during the startup phase (these
807 events are apparently caused by the WOW layer, the interface between
808 32bit and 64bit worlds). */
809 complaint (_("dll starting at %s not found."),
810 host_address_to_string (lpBaseOfDll
));
813 /* Clear list of loaded DLLs. */
815 windows_clear_solib (void)
821 signal_event_command (const char *args
, int from_tty
)
823 uintptr_t event_id
= 0;
824 char *endargs
= NULL
;
827 error (_("signal-event requires an argument (integer event id)"));
829 event_id
= strtoumax (args
, &endargs
, 10);
831 if ((errno
== ERANGE
) || (event_id
== 0) || (event_id
> UINTPTR_MAX
) ||
832 ((HANDLE
) event_id
== INVALID_HANDLE_VALUE
))
833 error (_("Failed to convert `%s' to event id"), args
);
835 SetEvent ((HANDLE
) event_id
);
836 CloseHandle ((HANDLE
) event_id
);
839 /* See nat/windows-nat.h. */
842 windows_nat::windows_process_info::handle_output_debug_string
843 (struct target_waitstatus
*ourstatus
)
847 gdb::unique_xmalloc_ptr
<char> s
848 = (target_read_string
849 ((CORE_ADDR
) (uintptr_t) current_event
.u
.DebugString
.lpDebugStringData
,
851 if (s
== nullptr || !*(s
.get ()))
853 else if (!startswith (s
.get (), _CYGWIN_SIGNAL_STRING
))
856 if (!startswith (s
.get (), "cYg"))
859 char *p
= strchr (s
.get (), '\0');
861 if (p
> s
.get () && *--p
== '\n')
863 warning (("%s"), s
.get ());
869 /* Got a cygwin signal marker. A cygwin signal is followed by
870 the signal number itself and then optionally followed by the
871 thread id and address to saved context within the DLL. If
872 these are supplied, then the given thread is assumed to have
873 issued the signal and the context from the thread is assumed
874 to be stored at the given address in the inferior. Tell gdb
875 to treat this like a real signal. */
877 int sig
= strtol (s
.get () + sizeof (_CYGWIN_SIGNAL_STRING
) - 1, &p
, 0);
878 gdb_signal gotasig
= gdb_signal_from_host (sig
);
885 ourstatus
->set_stopped (gotasig
);
886 retval
= strtoul (p
, &p
, 0);
888 retval
= current_event
.dwThreadId
;
889 else if ((x
= (LPCVOID
) (uintptr_t) strtoull (p
, NULL
, 0))
890 && ReadProcessMemory (current_process_handle
, x
,
892 __COPY_CONTEXT_SIZE
, &n
)
893 && n
== __COPY_CONTEXT_SIZE
)
894 have_saved_context
= 1;
903 display_selector (HANDLE thread
, DWORD sel
)
908 if (windows_process
.wow64_process
)
909 ret
= Wow64GetThreadSelectorEntry (thread
, sel
, &info
);
912 ret
= GetThreadSelectorEntry (thread
, sel
, &info
);
916 gdb_printf ("0x%03x: ", (unsigned) sel
);
917 if (!info
.HighWord
.Bits
.Pres
)
919 gdb_puts ("Segment not present\n");
922 base
= (info
.HighWord
.Bits
.BaseHi
<< 24) +
923 (info
.HighWord
.Bits
.BaseMid
<< 16)
925 limit
= (info
.HighWord
.Bits
.LimitHi
<< 16) + info
.LimitLow
;
926 if (info
.HighWord
.Bits
.Granularity
)
927 limit
= (limit
<< 12) | 0xfff;
928 gdb_printf ("base=0x%08x limit=0x%08x", base
, limit
);
929 if (info
.HighWord
.Bits
.Default_Big
)
930 gdb_puts(" 32-bit ");
932 gdb_puts(" 16-bit ");
933 switch ((info
.HighWord
.Bits
.Type
& 0xf) >> 1)
936 gdb_puts ("Data (Read-Only, Exp-up");
939 gdb_puts ("Data (Read/Write, Exp-up");
942 gdb_puts ("Unused segment (");
945 gdb_puts ("Data (Read/Write, Exp-down");
948 gdb_puts ("Code (Exec-Only, N.Conf");
951 gdb_puts ("Code (Exec/Read, N.Conf");
954 gdb_puts ("Code (Exec-Only, Conf");
957 gdb_puts ("Code (Exec/Read, Conf");
960 gdb_printf ("Unknown type 0x%lx",
961 (unsigned long) info
.HighWord
.Bits
.Type
);
963 if ((info
.HighWord
.Bits
.Type
& 0x1) == 0)
966 if ((info
.HighWord
.Bits
.Type
& 0x10) == 0)
967 gdb_puts("System selector ");
968 gdb_printf ("Priviledge level = %ld. ",
969 (unsigned long) info
.HighWord
.Bits
.Dpl
);
970 if (info
.HighWord
.Bits
.Granularity
)
971 gdb_puts ("Page granular.\n");
973 gdb_puts ("Byte granular.\n");
978 DWORD err
= GetLastError ();
979 if (err
== ERROR_NOT_SUPPORTED
)
980 gdb_printf ("Function not supported\n");
982 gdb_printf ("Invalid selector 0x%x.\n", (unsigned) sel
);
988 display_selectors (const char * args
, int from_tty
)
990 if (inferior_ptid
== null_ptid
)
992 gdb_puts ("Impossible to display selectors now.\n");
996 windows_thread_info
*current_windows_thread
997 = windows_process
.thread_rec (inferior_ptid
, DONT_INVALIDATE_CONTEXT
);
1002 if (windows_process
.wow64_process
)
1004 gdb_puts ("Selector $cs\n");
1005 display_selector (current_windows_thread
->h
,
1006 current_windows_thread
->wow64_context
.SegCs
);
1007 gdb_puts ("Selector $ds\n");
1008 display_selector (current_windows_thread
->h
,
1009 current_windows_thread
->wow64_context
.SegDs
);
1010 gdb_puts ("Selector $es\n");
1011 display_selector (current_windows_thread
->h
,
1012 current_windows_thread
->wow64_context
.SegEs
);
1013 gdb_puts ("Selector $ss\n");
1014 display_selector (current_windows_thread
->h
,
1015 current_windows_thread
->wow64_context
.SegSs
);
1016 gdb_puts ("Selector $fs\n");
1017 display_selector (current_windows_thread
->h
,
1018 current_windows_thread
->wow64_context
.SegFs
);
1019 gdb_puts ("Selector $gs\n");
1020 display_selector (current_windows_thread
->h
,
1021 current_windows_thread
->wow64_context
.SegGs
);
1026 gdb_puts ("Selector $cs\n");
1027 display_selector (current_windows_thread
->h
,
1028 current_windows_thread
->context
.SegCs
);
1029 gdb_puts ("Selector $ds\n");
1030 display_selector (current_windows_thread
->h
,
1031 current_windows_thread
->context
.SegDs
);
1032 gdb_puts ("Selector $es\n");
1033 display_selector (current_windows_thread
->h
,
1034 current_windows_thread
->context
.SegEs
);
1035 gdb_puts ("Selector $ss\n");
1036 display_selector (current_windows_thread
->h
,
1037 current_windows_thread
->context
.SegSs
);
1038 gdb_puts ("Selector $fs\n");
1039 display_selector (current_windows_thread
->h
,
1040 current_windows_thread
->context
.SegFs
);
1041 gdb_puts ("Selector $gs\n");
1042 display_selector (current_windows_thread
->h
,
1043 current_windows_thread
->context
.SegGs
);
1049 sel
= parse_and_eval_long (args
);
1050 gdb_printf ("Selector \"%s\"\n",args
);
1051 display_selector (current_windows_thread
->h
, sel
);
1055 /* See nat/windows-nat.h. */
1058 windows_nat::windows_process_info::handle_access_violation
1059 (const EXCEPTION_RECORD
*rec
)
1062 /* See if the access violation happened within the cygwin DLL
1063 itself. Cygwin uses a kind of exception handling to deal with
1064 passed-in invalid addresses. gdb should not treat these as real
1065 SEGVs since they will be silently handled by cygwin. A real SEGV
1066 will (theoretically) be caught by cygwin later in the process and
1067 will be sent as a cygwin-specific-signal. So, ignore SEGVs if
1068 they show up within the text segment of the DLL itself. */
1070 CORE_ADDR addr
= (CORE_ADDR
) (uintptr_t) rec
->ExceptionAddress
;
1072 if ((!cygwin_exceptions
&& (addr
>= cygwin_load_start
1073 && addr
< cygwin_load_end
))
1074 || (find_pc_partial_function (addr
, &fn
, NULL
, NULL
)
1075 && startswith (fn
, "KERNEL32!IsBad")))
1081 /* Resume thread specified by ID, or all artificially suspended
1082 threads, if we are continuing execution. KILLED non-zero means we
1083 have killed the inferior, so we should ignore weird errors due to
1084 threads shutting down. */
1086 windows_continue (DWORD continue_status
, int id
, int killed
)
1090 windows_process
.desired_stop_thread_id
= id
;
1092 if (windows_process
.matching_pending_stop (debug_events
))
1095 for (auto &th
: thread_list
)
1096 if (id
== -1 || id
== (int) th
->tid
)
1099 if (windows_process
.wow64_process
)
1101 if (th
->debug_registers_changed
)
1103 th
->wow64_context
.ContextFlags
|= CONTEXT_DEBUG_REGISTERS
;
1104 th
->wow64_context
.Dr0
= dr
[0];
1105 th
->wow64_context
.Dr1
= dr
[1];
1106 th
->wow64_context
.Dr2
= dr
[2];
1107 th
->wow64_context
.Dr3
= dr
[3];
1108 th
->wow64_context
.Dr6
= DR6_CLEAR_VALUE
;
1109 th
->wow64_context
.Dr7
= dr
[7];
1110 th
->debug_registers_changed
= false;
1112 if (th
->wow64_context
.ContextFlags
)
1116 if (GetExitCodeThread (th
->h
, &ec
)
1117 && ec
== STILL_ACTIVE
)
1119 BOOL status
= Wow64SetThreadContext (th
->h
,
1120 &th
->wow64_context
);
1125 th
->wow64_context
.ContextFlags
= 0;
1131 if (th
->debug_registers_changed
)
1133 th
->context
.ContextFlags
|= CONTEXT_DEBUG_REGISTERS
;
1134 th
->context
.Dr0
= dr
[0];
1135 th
->context
.Dr1
= dr
[1];
1136 th
->context
.Dr2
= dr
[2];
1137 th
->context
.Dr3
= dr
[3];
1138 th
->context
.Dr6
= DR6_CLEAR_VALUE
;
1139 th
->context
.Dr7
= dr
[7];
1140 th
->debug_registers_changed
= false;
1142 if (th
->context
.ContextFlags
)
1146 if (GetExitCodeThread (th
->h
, &ec
)
1147 && ec
== STILL_ACTIVE
)
1149 BOOL status
= SetThreadContext (th
->h
, &th
->context
);
1154 th
->context
.ContextFlags
= 0;
1161 /* When single-stepping a specific thread, other threads must
1166 res
= continue_last_debug_event (continue_status
, debug_events
);
1169 error (_("Failed to resume program execution"
1170 " (ContinueDebugEvent failed, error %u)"),
1171 (unsigned int) GetLastError ());
1176 /* Called in pathological case where Windows fails to send a
1177 CREATE_PROCESS_DEBUG_EVENT after an attach. */
1179 fake_create_process (void)
1181 windows_process
.handle
1182 = OpenProcess (PROCESS_ALL_ACCESS
, FALSE
,
1183 windows_process
.current_event
.dwProcessId
);
1184 if (windows_process
.handle
!= NULL
)
1185 open_process_used
= 1;
1188 error (_("OpenProcess call failed, GetLastError = %u"),
1189 (unsigned) GetLastError ());
1190 /* We can not debug anything in that case. */
1192 windows_add_thread (ptid_t (windows_process
.current_event
.dwProcessId
, 0,
1193 windows_process
.current_event
.dwThreadId
),
1194 windows_process
.current_event
.u
.CreateThread
.hThread
,
1195 windows_process
.current_event
.u
.CreateThread
.lpThreadLocalBase
,
1196 true /* main_thread_p */);
1197 return windows_process
.current_event
.dwThreadId
;
1201 windows_nat_target::resume (ptid_t ptid
, int step
, enum gdb_signal sig
)
1203 windows_thread_info
*th
;
1204 DWORD continue_status
= DBG_CONTINUE
;
1206 /* A specific PTID means `step only this thread id'. */
1207 int resume_all
= ptid
== minus_one_ptid
;
1209 /* If we're continuing all threads, it's the current inferior that
1210 should be handled specially. */
1212 ptid
= inferior_ptid
;
1214 if (sig
!= GDB_SIGNAL_0
)
1216 if (windows_process
.current_event
.dwDebugEventCode
1217 != EXCEPTION_DEBUG_EVENT
)
1219 DEBUG_EXCEPT ("Cannot continue with signal %d here.", sig
);
1221 else if (sig
== windows_process
.last_sig
)
1222 continue_status
= DBG_EXCEPTION_NOT_HANDLED
;
1225 /* This code does not seem to work, because
1226 the kernel does probably not consider changes in the ExceptionRecord
1227 structure when passing the exception to the inferior.
1228 Note that this seems possible in the exception handler itself. */
1230 for (const xlate_exception
&x
: xlate
)
1233 current_event
.u
.Exception
.ExceptionRecord
.ExceptionCode
1235 continue_status
= DBG_EXCEPTION_NOT_HANDLED
;
1238 if (continue_status
== DBG_CONTINUE
)
1240 DEBUG_EXCEPT ("Cannot continue with signal %d.", sig
);
1244 DEBUG_EXCEPT ("Can only continue with received signal %d.",
1245 windows_process
.last_sig
);
1248 windows_process
.last_sig
= GDB_SIGNAL_0
;
1250 DEBUG_EXEC ("pid=%d, tid=0x%x, step=%d, sig=%d",
1251 ptid
.pid (), (unsigned) ptid
.lwp (), step
, sig
);
1253 /* Get context for currently selected thread. */
1254 th
= windows_process
.thread_rec (inferior_ptid
, DONT_INVALIDATE_CONTEXT
);
1258 if (windows_process
.wow64_process
)
1262 /* Single step by setting t bit. */
1263 struct regcache
*regcache
= get_current_regcache ();
1264 struct gdbarch
*gdbarch
= regcache
->arch ();
1265 fetch_registers (regcache
, gdbarch_ps_regnum (gdbarch
));
1266 th
->wow64_context
.EFlags
|= FLAG_TRACE_BIT
;
1269 if (th
->wow64_context
.ContextFlags
)
1271 if (th
->debug_registers_changed
)
1273 th
->wow64_context
.Dr0
= dr
[0];
1274 th
->wow64_context
.Dr1
= dr
[1];
1275 th
->wow64_context
.Dr2
= dr
[2];
1276 th
->wow64_context
.Dr3
= dr
[3];
1277 th
->wow64_context
.Dr6
= DR6_CLEAR_VALUE
;
1278 th
->wow64_context
.Dr7
= dr
[7];
1279 th
->debug_registers_changed
= false;
1281 CHECK (Wow64SetThreadContext (th
->h
, &th
->wow64_context
));
1282 th
->wow64_context
.ContextFlags
= 0;
1290 /* Single step by setting t bit. */
1291 struct regcache
*regcache
= get_current_regcache ();
1292 struct gdbarch
*gdbarch
= regcache
->arch ();
1293 fetch_registers (regcache
, gdbarch_ps_regnum (gdbarch
));
1294 th
->context
.EFlags
|= FLAG_TRACE_BIT
;
1297 if (th
->context
.ContextFlags
)
1299 if (th
->debug_registers_changed
)
1301 th
->context
.Dr0
= dr
[0];
1302 th
->context
.Dr1
= dr
[1];
1303 th
->context
.Dr2
= dr
[2];
1304 th
->context
.Dr3
= dr
[3];
1305 th
->context
.Dr6
= DR6_CLEAR_VALUE
;
1306 th
->context
.Dr7
= dr
[7];
1307 th
->debug_registers_changed
= false;
1309 CHECK (SetThreadContext (th
->h
, &th
->context
));
1310 th
->context
.ContextFlags
= 0;
1315 /* Allow continuing with the same signal that interrupted us.
1316 Otherwise complain. */
1319 windows_continue (continue_status
, -1, 0);
1321 windows_continue (continue_status
, ptid
.lwp (), 0);
1324 /* Ctrl-C handler used when the inferior is not run in the same console. The
1325 handler is in charge of interrupting the inferior using DebugBreakProcess.
1326 Note that this function is not available prior to Windows XP. In this case
1327 we emit a warning. */
1329 ctrl_c_handler (DWORD event_type
)
1331 const int attach_flag
= current_inferior ()->attach_flag
;
1333 /* Only handle Ctrl-C and Ctrl-Break events. Ignore others. */
1334 if (event_type
!= CTRL_C_EVENT
&& event_type
!= CTRL_BREAK_EVENT
)
1337 /* If the inferior and the debugger share the same console, do nothing as
1338 the inferior has also received the Ctrl-C event. */
1339 if (!new_console
&& !attach_flag
)
1343 if (windows_process
.wow64_process
)
1345 /* Call DbgUiRemoteBreakin of the 32bit ntdll.dll in the target process.
1346 DebugBreakProcess would call the one of the 64bit ntdll.dll, which
1347 can't be correctly handled by gdb. */
1348 if (wow64_dbgbreak
== nullptr)
1351 if (!find_minimal_symbol_address ("ntdll!DbgUiRemoteBreakin",
1353 wow64_dbgbreak
= (void *) addr
;
1356 if (wow64_dbgbreak
!= nullptr)
1358 HANDLE thread
= CreateRemoteThread (windows_process
.handle
, NULL
,
1359 0, (LPTHREAD_START_ROUTINE
)
1360 wow64_dbgbreak
, NULL
, 0, NULL
);
1362 CloseHandle (thread
);
1368 if (!DebugBreakProcess (windows_process
.handle
))
1369 warning (_("Could not interrupt program. "
1370 "Press Ctrl-c in the program console."));
1373 /* Return true to tell that Ctrl-C has been handled. */
1377 /* Get the next event from the child. Returns a non-zero thread id if the event
1378 requires handling by WFI (or whatever). */
1381 windows_nat_target::get_windows_debug_event (int pid
,
1382 struct target_waitstatus
*ourstatus
)
1385 DWORD continue_status
, event_code
;
1386 DWORD thread_id
= 0;
1388 /* If there is a relevant pending stop, report it now. See the
1389 comment by the definition of "pending_stops" for details on why
1391 gdb::optional
<pending_stop
> stop
1392 = windows_process
.fetch_pending_stop (debug_events
);
1393 if (stop
.has_value ())
1395 thread_id
= stop
->thread_id
;
1396 *ourstatus
= stop
->status
;
1398 ptid_t
ptid (windows_process
.current_event
.dwProcessId
, thread_id
);
1399 windows_thread_info
*th
1400 = windows_process
.thread_rec (ptid
, INVALIDATE_CONTEXT
);
1401 th
->reload_context
= true;
1406 windows_process
.last_sig
= GDB_SIGNAL_0
;
1407 DEBUG_EVENT
*current_event
= &windows_process
.current_event
;
1409 if (!(debug_event
= wait_for_debug_event (&windows_process
.current_event
,
1413 continue_status
= DBG_CONTINUE
;
1415 event_code
= windows_process
.current_event
.dwDebugEventCode
;
1416 ourstatus
->set_spurious ();
1417 have_saved_context
= 0;
1421 case CREATE_THREAD_DEBUG_EVENT
:
1422 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1423 (unsigned) current_event
->dwProcessId
,
1424 (unsigned) current_event
->dwThreadId
,
1425 "CREATE_THREAD_DEBUG_EVENT");
1426 if (saw_create
!= 1)
1428 inferior
*inf
= find_inferior_pid (this, current_event
->dwProcessId
);
1429 if (!saw_create
&& inf
->attach_flag
)
1431 /* Kludge around a Windows bug where first event is a create
1432 thread event. Caused when attached process does not have
1434 thread_id
= fake_create_process ();
1440 /* Record the existence of this thread. */
1441 thread_id
= current_event
->dwThreadId
;
1443 (ptid_t (current_event
->dwProcessId
, current_event
->dwThreadId
, 0),
1444 current_event
->u
.CreateThread
.hThread
,
1445 current_event
->u
.CreateThread
.lpThreadLocalBase
,
1446 false /* main_thread_p */);
1450 case EXIT_THREAD_DEBUG_EVENT
:
1451 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1452 (unsigned) current_event
->dwProcessId
,
1453 (unsigned) current_event
->dwThreadId
,
1454 "EXIT_THREAD_DEBUG_EVENT");
1455 windows_delete_thread (ptid_t (current_event
->dwProcessId
,
1456 current_event
->dwThreadId
, 0),
1457 current_event
->u
.ExitThread
.dwExitCode
,
1458 false /* main_thread_p */);
1461 case CREATE_PROCESS_DEBUG_EVENT
:
1462 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1463 (unsigned) current_event
->dwProcessId
,
1464 (unsigned) current_event
->dwThreadId
,
1465 "CREATE_PROCESS_DEBUG_EVENT");
1466 CloseHandle (current_event
->u
.CreateProcessInfo
.hFile
);
1467 if (++saw_create
!= 1)
1470 windows_process
.handle
= current_event
->u
.CreateProcessInfo
.hProcess
;
1471 /* Add the main thread. */
1473 (ptid_t (current_event
->dwProcessId
,
1474 current_event
->dwThreadId
, 0),
1475 current_event
->u
.CreateProcessInfo
.hThread
,
1476 current_event
->u
.CreateProcessInfo
.lpThreadLocalBase
,
1477 true /* main_thread_p */);
1478 thread_id
= current_event
->dwThreadId
;
1481 case EXIT_PROCESS_DEBUG_EVENT
:
1482 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1483 (unsigned) current_event
->dwProcessId
,
1484 (unsigned) current_event
->dwThreadId
,
1485 "EXIT_PROCESS_DEBUG_EVENT");
1486 if (!windows_initialization_done
)
1488 target_terminal::ours ();
1489 target_mourn_inferior (inferior_ptid
);
1490 error (_("During startup program exited with code 0x%x."),
1491 (unsigned int) current_event
->u
.ExitProcess
.dwExitCode
);
1493 else if (saw_create
== 1)
1495 windows_delete_thread (ptid_t (current_event
->dwProcessId
,
1496 current_event
->dwThreadId
, 0),
1497 0, true /* main_thread_p */);
1498 DWORD exit_status
= current_event
->u
.ExitProcess
.dwExitCode
;
1499 /* If the exit status looks like a fatal exception, but we
1500 don't recognize the exception's code, make the original
1501 exit status value available, to avoid losing
1504 = WIFSIGNALED (exit_status
) ? WTERMSIG (exit_status
) : -1;
1505 if (exit_signal
== -1)
1506 ourstatus
->set_exited (exit_status
);
1508 ourstatus
->set_signalled (gdb_signal_from_host (exit_signal
));
1510 thread_id
= current_event
->dwThreadId
;
1514 case LOAD_DLL_DEBUG_EVENT
:
1515 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1516 (unsigned) current_event
->dwProcessId
,
1517 (unsigned) current_event
->dwThreadId
,
1518 "LOAD_DLL_DEBUG_EVENT");
1519 CloseHandle (current_event
->u
.LoadDll
.hFile
);
1520 if (saw_create
!= 1 || ! windows_initialization_done
)
1524 windows_process
.dll_loaded_event ();
1526 catch (const gdb_exception
&ex
)
1528 exception_print (gdb_stderr
, ex
);
1530 ourstatus
->set_loaded ();
1531 thread_id
= current_event
->dwThreadId
;
1534 case UNLOAD_DLL_DEBUG_EVENT
:
1535 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1536 (unsigned) current_event
->dwProcessId
,
1537 (unsigned) current_event
->dwThreadId
,
1538 "UNLOAD_DLL_DEBUG_EVENT");
1539 if (saw_create
!= 1 || ! windows_initialization_done
)
1543 windows_process
.handle_unload_dll ();
1545 catch (const gdb_exception
&ex
)
1547 exception_print (gdb_stderr
, ex
);
1549 ourstatus
->set_loaded ();
1550 thread_id
= current_event
->dwThreadId
;
1553 case EXCEPTION_DEBUG_EVENT
:
1554 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1555 (unsigned) current_event
->dwProcessId
,
1556 (unsigned) current_event
->dwThreadId
,
1557 "EXCEPTION_DEBUG_EVENT");
1558 if (saw_create
!= 1)
1560 switch (windows_process
.handle_exception (ourstatus
, debug_exceptions
))
1562 case HANDLE_EXCEPTION_UNHANDLED
:
1564 continue_status
= DBG_EXCEPTION_NOT_HANDLED
;
1566 case HANDLE_EXCEPTION_HANDLED
:
1567 thread_id
= current_event
->dwThreadId
;
1569 case HANDLE_EXCEPTION_IGNORED
:
1570 continue_status
= DBG_CONTINUE
;
1575 case OUTPUT_DEBUG_STRING_EVENT
: /* Message from the kernel. */
1576 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1577 (unsigned) current_event
->dwProcessId
,
1578 (unsigned) current_event
->dwThreadId
,
1579 "OUTPUT_DEBUG_STRING_EVENT");
1580 if (saw_create
!= 1)
1582 thread_id
= windows_process
.handle_output_debug_string (ourstatus
);
1586 if (saw_create
!= 1)
1588 gdb_printf ("gdb: kernel event for pid=%u tid=0x%x\n",
1589 (unsigned) current_event
->dwProcessId
,
1590 (unsigned) current_event
->dwThreadId
);
1591 gdb_printf (" unknown event code %u\n",
1592 (unsigned) current_event
->dwDebugEventCode
);
1596 if (!thread_id
|| saw_create
!= 1)
1598 CHECK (windows_continue (continue_status
,
1599 windows_process
.desired_stop_thread_id
, 0));
1601 else if (windows_process
.desired_stop_thread_id
!= -1
1602 && windows_process
.desired_stop_thread_id
!= thread_id
)
1604 /* Pending stop. See the comment by the definition of
1605 "pending_stops" for details on why this is needed. */
1606 DEBUG_EVENTS ("get_windows_debug_event - "
1607 "unexpected stop in 0x%x (expecting 0x%x)",
1608 thread_id
, windows_process
.desired_stop_thread_id
);
1610 if (current_event
->dwDebugEventCode
== EXCEPTION_DEBUG_EVENT
1611 && ((current_event
->u
.Exception
.ExceptionRecord
.ExceptionCode
1612 == EXCEPTION_BREAKPOINT
)
1613 || (current_event
->u
.Exception
.ExceptionRecord
.ExceptionCode
1614 == STATUS_WX86_BREAKPOINT
))
1615 && windows_initialization_done
)
1617 ptid_t ptid
= ptid_t (current_event
->dwProcessId
, thread_id
, 0);
1618 windows_thread_info
*th
1619 = windows_process
.thread_rec (ptid
, INVALIDATE_CONTEXT
);
1620 th
->stopped_at_software_breakpoint
= true;
1621 th
->pc_adjusted
= false;
1623 windows_process
.pending_stops
.push_back
1624 ({thread_id
, *ourstatus
, windows_process
.current_event
});
1626 CHECK (windows_continue (continue_status
,
1627 windows_process
.desired_stop_thread_id
, 0));
1634 /* Wait for interesting events to occur in the target process. */
1636 windows_nat_target::wait (ptid_t ptid
, struct target_waitstatus
*ourstatus
,
1637 target_wait_flags options
)
1641 /* We loop when we get a non-standard exception rather than return
1642 with a SPURIOUS because resume can try and step or modify things,
1643 which needs a current_thread->h. But some of these exceptions mark
1644 the birth or death of threads, which mean that the current thread
1645 isn't necessarily what you think it is. */
1651 /* If the user presses Ctrl-c while the debugger is waiting
1652 for an event, he expects the debugger to interrupt his program
1653 and to get the prompt back. There are two possible situations:
1655 - The debugger and the program do not share the console, in
1656 which case the Ctrl-c event only reached the debugger.
1657 In that case, the ctrl_c handler will take care of interrupting
1658 the inferior. Note that this case is working starting with
1659 Windows XP. For Windows 2000, Ctrl-C should be pressed in the
1662 - The debugger and the program share the same console, in which
1663 case both debugger and inferior will receive the Ctrl-c event.
1664 In that case the ctrl_c handler will ignore the event, as the
1665 Ctrl-c event generated inside the inferior will trigger the
1666 expected debug event.
1668 FIXME: brobecker/2008-05-20: If the inferior receives the
1669 signal first and the delay until GDB receives that signal
1670 is sufficiently long, GDB can sometimes receive the SIGINT
1671 after we have unblocked the CTRL+C handler. This would
1672 lead to the debugger stopping prematurely while handling
1673 the new-thread event that comes with the handling of the SIGINT
1674 inside the inferior, and then stop again immediately when
1675 the user tries to resume the execution in the inferior.
1676 This is a classic race that we should try to fix one day. */
1677 SetConsoleCtrlHandler (&ctrl_c_handler
, TRUE
);
1678 retval
= get_windows_debug_event (pid
, ourstatus
);
1679 SetConsoleCtrlHandler (&ctrl_c_handler
, FALSE
);
1683 ptid_t result
= ptid_t (windows_process
.current_event
.dwProcessId
,
1686 if (ourstatus
->kind () != TARGET_WAITKIND_EXITED
1687 && ourstatus
->kind () != TARGET_WAITKIND_SIGNALLED
)
1689 windows_thread_info
*th
1690 = windows_process
.thread_rec (result
, INVALIDATE_CONTEXT
);
1694 th
->stopped_at_software_breakpoint
= false;
1695 if (windows_process
.current_event
.dwDebugEventCode
1696 == EXCEPTION_DEBUG_EVENT
1697 && ((windows_process
.current_event
.u
.Exception
.ExceptionRecord
.ExceptionCode
1698 == EXCEPTION_BREAKPOINT
)
1699 || (windows_process
.current_event
.u
.Exception
.ExceptionRecord
.ExceptionCode
1700 == STATUS_WX86_BREAKPOINT
))
1701 && windows_initialization_done
)
1703 th
->stopped_at_software_breakpoint
= true;
1704 th
->pc_adjusted
= false;
1715 if (deprecated_ui_loop_hook
!= NULL
)
1716 detach
= deprecated_ui_loop_hook (0);
1725 windows_nat_target::do_initial_windows_stuff (DWORD pid
, bool attaching
)
1728 struct inferior
*inf
;
1730 windows_process
.last_sig
= GDB_SIGNAL_0
;
1731 open_process_used
= 0;
1732 for (i
= 0; i
< sizeof (dr
) / sizeof (dr
[0]); i
++)
1735 cygwin_load_start
= cygwin_load_end
= 0;
1737 windows_process
.current_event
.dwProcessId
= pid
;
1738 memset (&windows_process
.current_event
, 0,
1739 sizeof (windows_process
.current_event
));
1740 inf
= current_inferior ();
1741 if (!inf
->target_is_pushed (this))
1742 inf
->push_target (this);
1743 disable_breakpoints_in_shlibs ();
1744 windows_clear_solib ();
1745 clear_proceed_status (0);
1746 init_wait_for_inferior ();
1749 windows_process
.ignore_first_breakpoint
1750 = !attaching
&& windows_process
.wow64_process
;
1752 if (!windows_process
.wow64_process
)
1754 windows_set_context_register_offsets (amd64_mappings
);
1755 windows_set_segment_register_p (amd64_windows_segment_register_p
);
1760 windows_set_context_register_offsets (i386_mappings
);
1761 windows_set_segment_register_p (i386_windows_segment_register_p
);
1764 inferior_appeared (inf
, pid
);
1765 inf
->attach_flag
= attaching
;
1767 target_terminal::init ();
1768 target_terminal::inferior ();
1770 windows_initialization_done
= 0;
1776 struct target_waitstatus status
;
1778 last_ptid
= this->wait (minus_one_ptid
, &status
, 0);
1780 /* Note windows_wait returns TARGET_WAITKIND_SPURIOUS for thread
1782 if (status
.kind () != TARGET_WAITKIND_LOADED
1783 && status
.kind () != TARGET_WAITKIND_SPURIOUS
)
1786 this->resume (minus_one_ptid
, 0, GDB_SIGNAL_0
);
1789 switch_to_thread (find_thread_ptid (this, last_ptid
));
1791 /* Now that the inferior has been started and all DLLs have been mapped,
1792 we can iterate over all DLLs and load them in.
1794 We avoid doing it any earlier because, on certain versions of Windows,
1795 LOAD_DLL_DEBUG_EVENTs are sometimes not complete. In particular,
1796 we have seen on Windows 8.1 that the ntdll.dll load event does not
1797 include the DLL name, preventing us from creating an associated SO.
1798 A possible explanation is that ntdll.dll might be mapped before
1799 the SO info gets created by the Windows system -- ntdll.dll is
1800 the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs
1801 do not seem to suffer from that problem.
1803 Rather than try to work around this sort of issue, it is much
1804 simpler to just ignore DLL load/unload events during the startup
1805 phase, and then process them all in one batch now. */
1806 windows_process
.add_all_dlls ();
1808 windows_initialization_done
= 1;
1812 /* Try to set or remove a user privilege to the current process. Return -1
1813 if that fails, the previous setting of that privilege otherwise.
1815 This code is copied from the Cygwin source code and rearranged to allow
1816 dynamically loading of the needed symbols from advapi32 which is only
1817 available on NT/2K/XP. */
1819 set_process_privilege (const char *privilege
, BOOL enable
)
1821 HANDLE token_hdl
= NULL
;
1823 TOKEN_PRIVILEGES new_priv
, orig_priv
;
1827 if (!OpenProcessToken (GetCurrentProcess (),
1828 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
1832 if (!LookupPrivilegeValueA (NULL
, privilege
, &restore_priv
))
1835 new_priv
.PrivilegeCount
= 1;
1836 new_priv
.Privileges
[0].Luid
= restore_priv
;
1837 new_priv
.Privileges
[0].Attributes
= enable
? SE_PRIVILEGE_ENABLED
: 0;
1839 if (!AdjustTokenPrivileges (token_hdl
, FALSE
, &new_priv
,
1840 sizeof orig_priv
, &orig_priv
, &size
))
1843 /* Disabled, otherwise every `attach' in an unprivileged user session
1844 would raise the "Failed to get SE_DEBUG_NAME privilege" warning in
1845 windows_attach(). */
1846 /* AdjustTokenPrivileges returns TRUE even if the privilege could not
1847 be enabled. GetLastError () returns an correct error code, though. */
1848 if (enable
&& GetLastError () == ERROR_NOT_ALL_ASSIGNED
)
1852 ret
= orig_priv
.Privileges
[0].Attributes
== SE_PRIVILEGE_ENABLED
? 1 : 0;
1856 CloseHandle (token_hdl
);
1861 /* Attach to process PID, then initialize for debugging it. */
1864 windows_nat_target::attach (const char *args
, int from_tty
)
1869 pid
= parse_pid_to_attach (args
);
1871 if (set_process_privilege (SE_DEBUG_NAME
, TRUE
) < 0)
1872 warning ("Failed to get SE_DEBUG_NAME privilege\n"
1873 "This can cause attach to fail on Windows NT/2K/XP");
1875 windows_init_thread_list ();
1876 ok
= DebugActiveProcess (pid
);
1882 /* Try fall back to Cygwin pid. */
1883 pid
= cygwin_internal (CW_CYGWIN_PID_TO_WINPID
, pid
);
1886 ok
= DebugActiveProcess (pid
);
1891 error (_("Can't attach to process %u (error %u)"),
1892 (unsigned) pid
, (unsigned) GetLastError ());
1894 DebugSetProcessKillOnExit (FALSE
);
1896 target_announce_attach (from_tty
, pid
);
1899 HANDLE h
= OpenProcess (PROCESS_QUERY_INFORMATION
, FALSE
, pid
);
1903 if (IsWow64Process (h
, &wow64
))
1904 windows_process
.wow64_process
= wow64
;
1909 do_initial_windows_stuff (pid
, 1);
1910 target_terminal::ours ();
1914 windows_nat_target::detach (inferior
*inf
, int from_tty
)
1918 ptid_t ptid
= minus_one_ptid
;
1919 resume (ptid
, 0, GDB_SIGNAL_0
);
1921 if (!DebugActiveProcessStop (windows_process
.current_event
.dwProcessId
))
1923 error (_("Can't detach process %u (error %u)"),
1924 (unsigned) windows_process
.current_event
.dwProcessId
,
1925 (unsigned) GetLastError ());
1928 DebugSetProcessKillOnExit (FALSE
);
1931 target_announce_detach (from_tty
);
1933 x86_cleanup_dregs ();
1934 switch_to_no_thread ();
1935 detach_inferior (inf
);
1937 maybe_unpush_target ();
1940 /* The pid_to_exec_file target_ops method for this platform. */
1943 windows_nat_target::pid_to_exec_file (int pid
)
1945 return windows_process
.pid_to_exec_file (pid
);
1948 /* Print status information about what we're accessing. */
1951 windows_nat_target::files_info ()
1953 struct inferior
*inf
= current_inferior ();
1955 gdb_printf ("\tUsing the running image of %s %s.\n",
1956 inf
->attach_flag
? "attached" : "child",
1957 target_pid_to_str (inferior_ptid
).c_str ());
1960 /* Modify CreateProcess parameters for use of a new separate console.
1962 *FLAGS: DWORD parameter for general process creation flags.
1963 *SI: STARTUPINFO structure, for which the console window size and
1964 console buffer size is filled in if GDB is running in a console.
1965 to create the new console.
1966 The size of the used font is not available on all versions of
1967 Windows OS. Furthermore, the current font might not be the default
1968 font, but this is still better than before.
1969 If the windows and buffer sizes are computed,
1970 SI->DWFLAGS is changed so that this information is used
1971 by CreateProcess function. */
1974 windows_set_console_info (STARTUPINFO
*si
, DWORD
*flags
)
1976 HANDLE hconsole
= CreateFile ("CONOUT$", GENERIC_READ
| GENERIC_WRITE
,
1977 FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, 0, 0);
1979 if (hconsole
!= INVALID_HANDLE_VALUE
)
1981 CONSOLE_SCREEN_BUFFER_INFO sbinfo
;
1983 CONSOLE_FONT_INFO cfi
;
1985 GetCurrentConsoleFont (hconsole
, FALSE
, &cfi
);
1986 font_size
= GetConsoleFontSize (hconsole
, cfi
.nFont
);
1987 GetConsoleScreenBufferInfo(hconsole
, &sbinfo
);
1988 si
->dwXSize
= sbinfo
.srWindow
.Right
- sbinfo
.srWindow
.Left
+ 1;
1989 si
->dwYSize
= sbinfo
.srWindow
.Bottom
- sbinfo
.srWindow
.Top
+ 1;
1991 si
->dwXSize
*= font_size
.X
;
1995 si
->dwYSize
*= font_size
.Y
;
1998 si
->dwXCountChars
= sbinfo
.dwSize
.X
;
1999 si
->dwYCountChars
= sbinfo
.dwSize
.Y
;
2000 si
->dwFlags
|= STARTF_USESIZE
| STARTF_USECOUNTCHARS
;
2002 *flags
|= CREATE_NEW_CONSOLE
;
2006 /* Function called by qsort to sort environment strings. */
2009 envvar_cmp (const void *a
, const void *b
)
2011 const char **p
= (const char **) a
;
2012 const char **q
= (const char **) b
;
2013 return strcasecmp (*p
, *q
);
2019 clear_win32_environment (char **env
)
2023 wchar_t *copy
= NULL
, *equalpos
;
2025 for (i
= 0; env
[i
] && *env
[i
]; i
++)
2027 len
= mbstowcs (NULL
, env
[i
], 0) + 1;
2028 copy
= (wchar_t *) xrealloc (copy
, len
* sizeof (wchar_t));
2029 mbstowcs (copy
, env
[i
], len
);
2030 equalpos
= wcschr (copy
, L
'=');
2033 SetEnvironmentVariableW (copy
, NULL
);
2041 /* Redirection of inferior I/O streams for native MS-Windows programs.
2042 Unlike on Unix, where this is handled by invoking the inferior via
2043 the shell, on MS-Windows we need to emulate the cmd.exe shell.
2045 The official documentation of the cmd.exe redirection features is here:
2047 http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx
2049 (That page talks about Windows XP, but there's no newer
2050 documentation, so we assume later versions of cmd.exe didn't change
2053 Caveat: the documentation on that page seems to include a few lies.
2054 For example, it describes strange constructs 1<&2 and 2<&1, which
2055 seem to work only when 1>&2 resp. 2>&1 would make sense, and so I
2056 think the cmd.exe parser of the redirection symbols simply doesn't
2057 care about the < vs > distinction in these cases. Therefore, the
2058 supported features are explicitly documented below.
2060 The emulation below aims at supporting all the valid use cases
2061 supported by cmd.exe, which include:
2063 < FILE redirect standard input from FILE
2064 0< FILE redirect standard input from FILE
2065 <&N redirect standard input from file descriptor N
2066 0<&N redirect standard input from file descriptor N
2067 > FILE redirect standard output to FILE
2068 >> FILE append standard output to FILE
2069 1>> FILE append standard output to FILE
2070 >&N redirect standard output to file descriptor N
2071 1>&N redirect standard output to file descriptor N
2072 >>&N append standard output to file descriptor N
2073 1>>&N append standard output to file descriptor N
2074 2> FILE redirect standard error to FILE
2075 2>> FILE append standard error to FILE
2076 2>&N redirect standard error to file descriptor N
2077 2>>&N append standard error to file descriptor N
2079 Note that using N > 2 in the above construct is supported, but
2080 requires that the corresponding file descriptor be open by some
2081 means elsewhere or outside GDB. Also note that using ">&0" or
2082 "<&2" will generally fail, because the file descriptor redirected
2083 from is normally open in an incompatible mode (e.g., FD 0 is open
2084 for reading only). IOW, use of such tricks is not recommended;
2085 you are on your own.
2087 We do NOT support redirection of file descriptors above 2, as in
2088 "3>SOME-FILE", because MinGW compiled programs don't (supporting
2089 that needs special handling in the startup code that MinGW
2090 doesn't have). Pipes are also not supported.
2092 As for invalid use cases, where the redirection contains some
2093 error, the emulation below will detect that and produce some
2094 error and/or failure. But the behavior in those cases is not
2095 bug-for-bug compatible with what cmd.exe does in those cases.
2096 That's because what cmd.exe does then is not well defined, and
2097 seems to be a side effect of the cmd.exe parsing of the command
2098 line more than anything else. For example, try redirecting to an
2099 invalid file name, as in "> foo:bar".
2101 There are also minor syntactic deviations from what cmd.exe does
2102 in some corner cases. For example, it doesn't support the likes
2103 of "> &foo" to mean redirect to file named literally "&foo"; we
2104 do support that here, because that, too, sounds like some issue
2105 with the cmd.exe parser. Another nicety is that we support
2106 redirection targets that use file names with forward slashes,
2107 something cmd.exe doesn't -- this comes in handy since GDB
2108 file-name completion can be used when typing the command line for
2111 /* Support routines for redirecting standard handles of the inferior. */
2113 /* Parse a single redirection spec, open/duplicate the specified
2114 file/fd, and assign the appropriate value to one of the 3 standard
2115 file descriptors. */
2117 redir_open (const char *redir_string
, int *inp
, int *out
, int *err
)
2119 int *fd
, ref_fd
= -2;
2121 const char *fname
= redir_string
+ 1;
2122 int rc
= *redir_string
;
2137 fd
= (rc
== '2') ? err
: out
;
2138 mode
= O_WRONLY
| O_CREAT
;
2151 if (*fname
== '&' && '0' <= fname
[1] && fname
[1] <= '9')
2153 /* A reference to a file descriptor. */
2155 ref_fd
= (int) strtol (fname
+ 1, &fdtail
, 10);
2156 if (fdtail
> fname
+ 1 && *fdtail
== '\0')
2158 /* Don't allow redirection when open modes are incompatible. */
2159 if ((ref_fd
== 0 && (fd
== out
|| fd
== err
))
2160 || ((ref_fd
== 1 || ref_fd
== 2) && fd
== inp
))
2167 else if (ref_fd
== 1)
2169 else if (ref_fd
== 2)
2179 fname
++; /* skip the separator space */
2180 /* If the descriptor is already open, close it. This allows
2181 multiple specs of redirections for the same stream, which is
2182 somewhat nonsensical, but still valid and supported by cmd.exe.
2183 (But cmd.exe only opens a single file in this case, the one
2184 specified by the last redirection spec on the command line.) */
2189 *fd
= _open (fname
, mode
, _S_IREAD
| _S_IWRITE
);
2193 else if (ref_fd
== -1)
2194 *fd
= -1; /* reset to default destination */
2197 *fd
= _dup (ref_fd
);
2201 /* _open just sets a flag for O_APPEND, which won't be passed to the
2202 inferior, so we need to actually move the file pointer. */
2203 if ((mode
& O_APPEND
) != 0)
2204 _lseek (*fd
, 0L, SEEK_END
);
2208 /* Canonicalize a single redirection spec and set up the corresponding
2209 file descriptor as specified. */
2211 redir_set_redirection (const char *s
, int *inp
, int *out
, int *err
)
2213 char buf
[__PMAX
+ 2 + 5]; /* extra space for quotes & redirection string */
2215 const char *start
= s
;
2218 *d
++ = *s
++; /* copy the 1st character, < or > or a digit */
2219 if ((*start
== '>' || *start
== '1' || *start
== '2')
2223 if (*s
== '>' && *start
!= '>')
2226 else if (*start
== '0' && *s
== '<')
2228 /* cmd.exe recognizes "&N" only immediately after the redirection symbol. */
2231 while (isspace (*s
)) /* skip whitespace before file name */
2233 *d
++ = ' '; /* separate file name with a single space */
2236 /* Copy the file name. */
2239 /* Remove quoting characters from the file name in buf[]. */
2240 if (*s
== '"') /* could support '..' quoting here */
2244 else if (*s
== quote
)
2252 else if (*s
== '\\')
2254 if (s
[1] == '"') /* could support '..' here */
2258 else if (isspace (*s
) && !quote
)
2262 if (d
- buf
>= sizeof (buf
) - 1)
2264 errno
= ENAMETOOLONG
;
2270 /* Windows doesn't allow redirection characters in file names, so we
2271 can bail out early if they use them, or if there's no target file
2272 name after the redirection symbol. */
2273 if (d
[-1] == '>' || d
[-1] == '<')
2278 if (redir_open (buf
, inp
, out
, err
) == 0)
2283 /* Parse the command line for redirection specs and prepare the file
2284 descriptors for the 3 standard streams accordingly. */
2286 redirect_inferior_handles (const char *cmd_orig
, char *cmd
,
2287 int *inp
, int *out
, int *err
)
2289 const char *s
= cmd_orig
;
2292 bool retval
= false;
2294 while (isspace (*s
))
2299 if (*s
== '"') /* could also support '..' quoting here */
2303 else if (*s
== quote
)
2306 else if (*s
== '\\')
2308 if (s
[1] == '"') /* escaped quote char */
2313 /* Process a single redirection candidate. */
2314 if (*s
== '<' || *s
== '>'
2315 || ((*s
== '1' || *s
== '2') && s
[1] == '>')
2316 || (*s
== '0' && s
[1] == '<'))
2318 int skip
= redir_set_redirection (s
, inp
, out
, err
);
2332 #endif /* !__CYGWIN__ */
2334 /* Start an inferior windows child process and sets inferior_ptid to its pid.
2335 EXEC_FILE is the file to run.
2336 ALLARGS is a string containing the arguments to the program.
2337 ENV is the environment vector to pass. Errors reported with error(). */
2340 windows_nat_target::create_inferior (const char *exec_file
,
2341 const std::string
&origallargs
,
2342 char **in_env
, int from_tty
)
2346 cygwin_buf_t real_path
[__PMAX
];
2347 cygwin_buf_t shell
[__PMAX
]; /* Path to shell */
2348 cygwin_buf_t infcwd
[__PMAX
];
2350 cygwin_buf_t
*toexec
;
2351 cygwin_buf_t
*cygallargs
;
2353 char **old_env
= NULL
;
2357 int ostdin
, ostdout
, ostderr
;
2358 #else /* !__CYGWIN__ */
2359 char shell
[__PMAX
]; /* Path to shell */
2361 char *args
, *allargs_copy
;
2362 size_t args_len
, allargs_len
;
2363 int fd_inp
= -1, fd_out
= -1, fd_err
= -1;
2364 HANDLE tty
= INVALID_HANDLE_VALUE
;
2365 bool redirected
= false;
2372 #endif /* !__CYGWIN__ */
2373 const char *allargs
= origallargs
.c_str ();
2374 PROCESS_INFORMATION pi
;
2377 const std::string
&inferior_tty
= current_inferior ()->tty ();
2380 error (_("No executable specified, use `target exec'."));
2382 const char *inferior_cwd
= current_inferior ()->cwd ().c_str ();
2383 std::string expanded_infcwd
;
2384 if (*inferior_cwd
== '\0')
2385 inferior_cwd
= nullptr;
2388 expanded_infcwd
= gdb_tilde_expand (inferior_cwd
);
2389 /* Mirror slashes on inferior's cwd. */
2390 std::replace (expanded_infcwd
.begin (), expanded_infcwd
.end (),
2392 inferior_cwd
= expanded_infcwd
.c_str ();
2395 memset (&si
, 0, sizeof (si
));
2396 si
.cb
= sizeof (si
);
2399 flags
|= CREATE_NEW_PROCESS_GROUP
;
2402 windows_set_console_info (&si
, &flags
);
2407 flags
|= DEBUG_ONLY_THIS_PROCESS
;
2408 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W
, exec_file
, real_path
,
2409 __PMAX
* sizeof (cygwin_buf_t
)) < 0)
2410 error (_("Error starting executable: %d"), errno
);
2413 len
= mbstowcs (NULL
, allargs
, 0) + 1;
2414 if (len
== (size_t) -1)
2415 error (_("Error starting executable: %d"), errno
);
2416 cygallargs
= (wchar_t *) alloca (len
* sizeof (wchar_t));
2417 mbstowcs (cygallargs
, allargs
, len
);
2418 #else /* !__USEWIDE */
2419 cygallargs
= allargs
;
2425 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W
, sh
, shell
, __PMAX
) < 0)
2426 error (_("Error starting executable via shell: %d"), errno
);
2428 len
= sizeof (L
" -c 'exec '") + mbstowcs (NULL
, exec_file
, 0)
2429 + mbstowcs (NULL
, allargs
, 0) + 2;
2430 cygallargs
= (wchar_t *) alloca (len
* sizeof (wchar_t));
2431 swprintf (cygallargs
, len
, L
" -c 'exec %s %s'", exec_file
, allargs
);
2432 #else /* !__USEWIDE */
2433 len
= (sizeof (" -c 'exec '") + strlen (exec_file
)
2434 + strlen (allargs
) + 2);
2435 cygallargs
= (char *) alloca (len
);
2436 xsnprintf (cygallargs
, len
, " -c 'exec %s %s'", exec_file
, allargs
);
2437 #endif /* __USEWIDE */
2439 flags
|= DEBUG_PROCESS
;
2442 if (inferior_cwd
!= NULL
2443 && cygwin_conv_path (CCP_POSIX_TO_WIN_W
, inferior_cwd
,
2444 infcwd
, strlen (inferior_cwd
)) < 0)
2445 error (_("Error converting inferior cwd: %d"), errno
);
2448 args
= (cygwin_buf_t
*) alloca ((wcslen (toexec
) + wcslen (cygallargs
) + 2)
2449 * sizeof (wchar_t));
2450 wcscpy (args
, toexec
);
2451 wcscat (args
, L
" ");
2452 wcscat (args
, cygallargs
);
2453 #else /* !__USEWIDE */
2454 args
= (cygwin_buf_t
*) alloca (strlen (toexec
) + strlen (cygallargs
) + 2);
2455 strcpy (args
, toexec
);
2457 strcat (args
, cygallargs
);
2458 #endif /* !__USEWIDE */
2460 #ifdef CW_CVT_ENV_TO_WINENV
2461 /* First try to create a direct Win32 copy of the POSIX environment. */
2462 w32_env
= (PWCHAR
) cygwin_internal (CW_CVT_ENV_TO_WINENV
, in_env
);
2463 if (w32_env
!= (PWCHAR
) -1)
2464 flags
|= CREATE_UNICODE_ENVIRONMENT
;
2466 /* If that fails, fall back to old method tweaking GDB's environment. */
2467 #endif /* CW_CVT_ENV_TO_WINENV */
2469 /* Reset all Win32 environment variables to avoid leftover on next run. */
2470 clear_win32_environment (environ
);
2471 /* Prepare the environment vars for CreateProcess. */
2474 cygwin_internal (CW_SYNC_WINENV
);
2478 if (inferior_tty
.empty ())
2479 tty
= ostdin
= ostdout
= ostderr
= -1;
2482 tty
= open (inferior_tty
.c_str (), O_RDWR
| O_NOCTTY
);
2485 print_sys_errmsg (inferior_tty
.c_str (), errno
);
2486 ostdin
= ostdout
= ostderr
= -1;
2499 windows_init_thread_list ();
2500 ret
= CreateProcess (0,
2501 args
, /* command line */
2502 NULL
, /* Security */
2504 TRUE
, /* inherit handles */
2505 flags
, /* start flags */
2506 w32_env
, /* environment */
2507 inferior_cwd
!= NULL
? infcwd
: NULL
, /* current
2512 /* Just free the Win32 environment, if it could be created. */
2516 /* Reset all environment variables to avoid leftover on next run. */
2517 clear_win32_environment (in_env
);
2518 /* Restore normal GDB environment variables. */
2520 cygwin_internal (CW_SYNC_WINENV
);
2533 #else /* !__CYGWIN__ */
2534 allargs_len
= strlen (allargs
);
2535 allargs_copy
= strcpy ((char *) alloca (allargs_len
+ 1), allargs
);
2536 if (strpbrk (allargs_copy
, "<>") != NULL
)
2541 redirect_inferior_handles (allargs
, allargs_copy
,
2542 &fd_inp
, &fd_out
, &fd_err
);
2544 warning (_("Error in redirection: %s."), safe_strerror (errno
));
2547 allargs_len
= strlen (allargs_copy
);
2549 /* If not all the standard streams are redirected by the command
2550 line, use INFERIOR_TTY for those which aren't. */
2551 if (!inferior_tty
.empty ()
2552 && !(fd_inp
>= 0 && fd_out
>= 0 && fd_err
>= 0))
2554 SECURITY_ATTRIBUTES sa
;
2555 sa
.nLength
= sizeof(sa
);
2556 sa
.lpSecurityDescriptor
= 0;
2557 sa
.bInheritHandle
= TRUE
;
2558 tty
= CreateFileA (inferior_tty
.c_str (), GENERIC_READ
| GENERIC_WRITE
,
2559 0, &sa
, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
2560 if (tty
== INVALID_HANDLE_VALUE
)
2561 warning (_("Warning: Failed to open TTY %s, error %#x."),
2562 inferior_tty
.c_str (), (unsigned) GetLastError ());
2564 if (redirected
|| tty
!= INVALID_HANDLE_VALUE
)
2567 si
.hStdInput
= (HANDLE
) _get_osfhandle (fd_inp
);
2568 else if (tty
!= INVALID_HANDLE_VALUE
)
2571 si
.hStdInput
= GetStdHandle (STD_INPUT_HANDLE
);
2573 si
.hStdOutput
= (HANDLE
) _get_osfhandle (fd_out
);
2574 else if (tty
!= INVALID_HANDLE_VALUE
)
2575 si
.hStdOutput
= tty
;
2577 si
.hStdOutput
= GetStdHandle (STD_OUTPUT_HANDLE
);
2579 si
.hStdError
= (HANDLE
) _get_osfhandle (fd_err
);
2580 else if (tty
!= INVALID_HANDLE_VALUE
)
2583 si
.hStdError
= GetStdHandle (STD_ERROR_HANDLE
);
2584 si
.dwFlags
|= STARTF_USESTDHANDLES
;
2588 /* Build the command line, a space-separated list of tokens where
2589 the first token is the name of the module to be executed.
2590 To avoid ambiguities introduced by spaces in the module name,
2592 args_len
= strlen (toexec
) + 2 /* quotes */ + allargs_len
+ 2;
2593 args
= (char *) alloca (args_len
);
2594 xsnprintf (args
, args_len
, "\"%s\" %s", toexec
, allargs_copy
);
2596 flags
|= DEBUG_ONLY_THIS_PROCESS
;
2598 /* CreateProcess takes the environment list as a null terminated set of
2599 strings (i.e. two nulls terminate the list). */
2601 /* Get total size for env strings. */
2602 for (envlen
= 0, i
= 0; in_env
[i
] && *in_env
[i
]; i
++)
2603 envlen
+= strlen (in_env
[i
]) + 1;
2605 envsize
= sizeof (in_env
[0]) * (i
+ 1);
2606 env
= (char **) alloca (envsize
);
2607 memcpy (env
, in_env
, envsize
);
2608 /* Windows programs expect the environment block to be sorted. */
2609 qsort (env
, i
, sizeof (char *), envvar_cmp
);
2611 w32env
= (char *) alloca (envlen
+ 1);
2613 /* Copy env strings into new buffer. */
2614 for (temp
= w32env
, i
= 0; env
[i
] && *env
[i
]; i
++)
2616 strcpy (temp
, env
[i
]);
2617 temp
+= strlen (temp
) + 1;
2620 /* Final nil string to terminate new env. */
2623 windows_init_thread_list ();
2624 ret
= CreateProcessA (0,
2625 args
, /* command line */
2626 NULL
, /* Security */
2628 TRUE
, /* inherit handles */
2629 flags
, /* start flags */
2630 w32env
, /* environment */
2631 inferior_cwd
, /* current directory */
2634 if (tty
!= INVALID_HANDLE_VALUE
)
2642 #endif /* !__CYGWIN__ */
2645 error (_("Error creating process %s, (error %u)."),
2646 exec_file
, (unsigned) GetLastError ());
2650 if (IsWow64Process (pi
.hProcess
, &wow64
))
2651 windows_process
.wow64_process
= wow64
;
2654 CloseHandle (pi
.hThread
);
2655 CloseHandle (pi
.hProcess
);
2657 if (useshell
&& shell
[0] != '\0')
2662 do_initial_windows_stuff (pi
.dwProcessId
, 0);
2664 /* windows_continue (DBG_CONTINUE, -1, 0); */
2668 windows_nat_target::mourn_inferior ()
2670 (void) windows_continue (DBG_CONTINUE
, -1, 0);
2671 x86_cleanup_dregs();
2672 if (open_process_used
)
2674 CHECK (CloseHandle (windows_process
.handle
));
2675 open_process_used
= 0;
2677 windows_process
.siginfo_er
.ExceptionCode
= 0;
2678 inf_child_target::mourn_inferior ();
2681 /* Send a SIGINT to the process group. This acts just like the user typed a
2682 ^C on the controlling terminal. */
2685 windows_nat_target::interrupt ()
2687 DEBUG_EVENTS ("GenerateConsoleCtrlEvent (CTRLC_EVENT, 0)");
2688 CHECK (GenerateConsoleCtrlEvent (CTRL_C_EVENT
,
2689 windows_process
.current_event
.dwProcessId
));
2690 registers_changed (); /* refresh register state */
2693 /* Helper for windows_xfer_partial that handles memory transfers.
2694 Arguments are like target_xfer_partial. */
2696 static enum target_xfer_status
2697 windows_xfer_memory (gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
2698 ULONGEST memaddr
, ULONGEST len
, ULONGEST
*xfered_len
)
2702 DWORD lasterror
= 0;
2704 if (writebuf
!= NULL
)
2706 DEBUG_MEM ("write target memory, %s bytes at %s",
2707 pulongest (len
), core_addr_to_string (memaddr
));
2708 success
= WriteProcessMemory (windows_process
.handle
,
2709 (LPVOID
) (uintptr_t) memaddr
, writebuf
,
2712 lasterror
= GetLastError ();
2713 FlushInstructionCache (windows_process
.handle
,
2714 (LPCVOID
) (uintptr_t) memaddr
, len
);
2718 DEBUG_MEM ("read target memory, %s bytes at %s",
2719 pulongest (len
), core_addr_to_string (memaddr
));
2720 success
= ReadProcessMemory (windows_process
.handle
,
2721 (LPCVOID
) (uintptr_t) memaddr
, readbuf
,
2724 lasterror
= GetLastError ();
2726 *xfered_len
= (ULONGEST
) done
;
2727 if (!success
&& lasterror
== ERROR_PARTIAL_COPY
&& done
> 0)
2728 return TARGET_XFER_OK
;
2730 return success
? TARGET_XFER_OK
: TARGET_XFER_E_IO
;
2734 windows_nat_target::kill ()
2736 CHECK (TerminateProcess (windows_process
.handle
, 0));
2740 if (!windows_continue (DBG_CONTINUE
, -1, 1))
2742 if (!wait_for_debug_event (&windows_process
.current_event
, INFINITE
))
2744 if (windows_process
.current_event
.dwDebugEventCode
2745 == EXIT_PROCESS_DEBUG_EVENT
)
2749 target_mourn_inferior (inferior_ptid
); /* Or just windows_mourn_inferior? */
2753 windows_nat_target::close ()
2755 DEBUG_EVENTS ("inferior_ptid=%d\n", inferior_ptid
.pid ());
2758 /* Convert pid to printable format. */
2760 windows_nat_target::pid_to_str (ptid_t ptid
)
2762 if (ptid
.lwp () != 0)
2763 return string_printf ("Thread %d.0x%lx", ptid
.pid (), ptid
.lwp ());
2765 return normal_pid_to_str (ptid
);
2768 static enum target_xfer_status
2769 windows_xfer_shared_libraries (struct target_ops
*ops
,
2770 enum target_object object
, const char *annex
,
2771 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
2772 ULONGEST offset
, ULONGEST len
,
2773 ULONGEST
*xfered_len
)
2775 auto_obstack obstack
;
2780 return TARGET_XFER_E_IO
;
2782 obstack_grow_str (&obstack
, "<library-list>\n");
2783 for (windows_solib
&so
: solibs
)
2784 windows_xfer_shared_library (so
.name
.c_str (),
2785 (CORE_ADDR
) (uintptr_t) so
.load_addr
,
2787 target_gdbarch (), &obstack
);
2788 obstack_grow_str0 (&obstack
, "</library-list>\n");
2790 buf
= (const char *) obstack_finish (&obstack
);
2791 len_avail
= strlen (buf
);
2792 if (offset
>= len_avail
)
2796 if (len
> len_avail
- offset
)
2797 len
= len_avail
- offset
;
2798 memcpy (readbuf
, buf
+ offset
, len
);
2801 *xfered_len
= (ULONGEST
) len
;
2802 return len
!= 0 ? TARGET_XFER_OK
: TARGET_XFER_EOF
;
2805 /* Helper for windows_nat_target::xfer_partial that handles signal info. */
2807 static enum target_xfer_status
2808 windows_xfer_siginfo (gdb_byte
*readbuf
, ULONGEST offset
, ULONGEST len
,
2809 ULONGEST
*xfered_len
)
2811 char *buf
= (char *) &windows_process
.siginfo_er
;
2812 size_t bufsize
= sizeof (windows_process
.siginfo_er
);
2815 EXCEPTION_RECORD32 er32
;
2816 if (windows_process
.wow64_process
)
2818 buf
= (char *) &er32
;
2819 bufsize
= sizeof (er32
);
2821 er32
.ExceptionCode
= windows_process
.siginfo_er
.ExceptionCode
;
2822 er32
.ExceptionFlags
= windows_process
.siginfo_er
.ExceptionFlags
;
2823 er32
.ExceptionRecord
2824 = (uintptr_t) windows_process
.siginfo_er
.ExceptionRecord
;
2825 er32
.ExceptionAddress
2826 = (uintptr_t) windows_process
.siginfo_er
.ExceptionAddress
;
2827 er32
.NumberParameters
= windows_process
.siginfo_er
.NumberParameters
;
2829 for (i
= 0; i
< EXCEPTION_MAXIMUM_PARAMETERS
; i
++)
2830 er32
.ExceptionInformation
[i
]
2831 = windows_process
.siginfo_er
.ExceptionInformation
[i
];
2835 if (windows_process
.siginfo_er
.ExceptionCode
== 0)
2836 return TARGET_XFER_E_IO
;
2838 if (readbuf
== nullptr)
2839 return TARGET_XFER_E_IO
;
2841 if (offset
> bufsize
)
2842 return TARGET_XFER_E_IO
;
2844 if (offset
+ len
> bufsize
)
2845 len
= bufsize
- offset
;
2847 memcpy (readbuf
, buf
+ offset
, len
);
2850 return TARGET_XFER_OK
;
2853 enum target_xfer_status
2854 windows_nat_target::xfer_partial (enum target_object object
,
2855 const char *annex
, gdb_byte
*readbuf
,
2856 const gdb_byte
*writebuf
, ULONGEST offset
,
2857 ULONGEST len
, ULONGEST
*xfered_len
)
2861 case TARGET_OBJECT_MEMORY
:
2862 return windows_xfer_memory (readbuf
, writebuf
, offset
, len
, xfered_len
);
2864 case TARGET_OBJECT_LIBRARIES
:
2865 return windows_xfer_shared_libraries (this, object
, annex
, readbuf
,
2866 writebuf
, offset
, len
, xfered_len
);
2868 case TARGET_OBJECT_SIGNAL_INFO
:
2869 return windows_xfer_siginfo (readbuf
, offset
, len
, xfered_len
);
2872 if (beneath () == NULL
)
2874 /* This can happen when requesting the transfer of unsupported
2875 objects before a program has been started (and therefore
2876 with the current_target having no target beneath). */
2877 return TARGET_XFER_E_IO
;
2879 return beneath ()->xfer_partial (object
, annex
,
2880 readbuf
, writebuf
, offset
, len
,
2885 /* Provide thread local base, i.e. Thread Information Block address.
2886 Returns 1 if ptid is found and sets *ADDR to thread_local_base. */
2889 windows_nat_target::get_tib_address (ptid_t ptid
, CORE_ADDR
*addr
)
2891 windows_thread_info
*th
;
2893 th
= windows_process
.thread_rec (ptid
, DONT_INVALIDATE_CONTEXT
);
2898 *addr
= th
->thread_local_base
;
2904 windows_nat_target::get_ada_task_ptid (long lwp
, ULONGEST thread
)
2906 return ptid_t (inferior_ptid
.pid (), lwp
, 0);
2909 /* Implementation of the to_thread_name method. */
2912 windows_nat_target::thread_name (struct thread_info
*thr
)
2914 windows_thread_info
*th
2915 = windows_process
.thread_rec (thr
->ptid
,
2916 DONT_INVALIDATE_CONTEXT
);
2917 return th
->thread_name ();
2921 void _initialize_windows_nat ();
2923 _initialize_windows_nat ()
2925 x86_dr_low
.set_control
= cygwin_set_dr7
;
2926 x86_dr_low
.set_addr
= cygwin_set_dr
;
2927 x86_dr_low
.get_addr
= cygwin_get_dr
;
2928 x86_dr_low
.get_status
= cygwin_get_dr6
;
2929 x86_dr_low
.get_control
= cygwin_get_dr7
;
2931 /* x86_dr_low.debug_register_length field is set by
2932 calling x86_set_debug_register_length function
2933 in processor windows specific native file. */
2935 add_inf_child_target (&the_windows_nat_target
);
2938 cygwin_internal (CW_SET_DOS_FILE_WARNING
, 0);
2941 add_com ("signal-event", class_run
, signal_event_command
, _("\
2942 Signal a crashed process with event ID, to allow its debugging.\n\
2943 This command is needed in support of setting up GDB as JIT debugger on \
2944 MS-Windows. The command should be invoked from the GDB command line using \
2945 the '-ex' command-line option. The ID of the event that blocks the \
2946 crashed process will be supplied by the Windows JIT debugging mechanism."));
2949 add_setshow_boolean_cmd ("shell", class_support
, &useshell
, _("\
2950 Set use of shell to start subprocess."), _("\
2951 Show use of shell to start subprocess."), NULL
,
2953 NULL
, /* FIXME: i18n: */
2954 &setlist
, &showlist
);
2956 add_setshow_boolean_cmd ("cygwin-exceptions", class_support
,
2957 &cygwin_exceptions
, _("\
2958 Break when an exception is detected in the Cygwin DLL itself."), _("\
2959 Show whether gdb breaks on exceptions in the Cygwin DLL itself."), NULL
,
2961 NULL
, /* FIXME: i18n: */
2962 &setlist
, &showlist
);
2965 add_setshow_boolean_cmd ("new-console", class_support
, &new_console
, _("\
2966 Set creation of new console when creating child process."), _("\
2967 Show creation of new console when creating child process."), NULL
,
2969 NULL
, /* FIXME: i18n: */
2970 &setlist
, &showlist
);
2972 add_setshow_boolean_cmd ("new-group", class_support
, &new_group
, _("\
2973 Set creation of new group when creating child process."), _("\
2974 Show creation of new group when creating child process."), NULL
,
2976 NULL
, /* FIXME: i18n: */
2977 &setlist
, &showlist
);
2979 add_setshow_boolean_cmd ("debugexec", class_support
, &debug_exec
, _("\
2980 Set whether to display execution in child process."), _("\
2981 Show whether to display execution in child process."), NULL
,
2983 NULL
, /* FIXME: i18n: */
2984 &setlist
, &showlist
);
2986 add_setshow_boolean_cmd ("debugevents", class_support
, &debug_events
, _("\
2987 Set whether to display kernel events in child process."), _("\
2988 Show whether to display kernel events in child process."), NULL
,
2990 NULL
, /* FIXME: i18n: */
2991 &setlist
, &showlist
);
2993 add_setshow_boolean_cmd ("debugmemory", class_support
, &debug_memory
, _("\
2994 Set whether to display memory accesses in child process."), _("\
2995 Show whether to display memory accesses in child process."), NULL
,
2997 NULL
, /* FIXME: i18n: */
2998 &setlist
, &showlist
);
3000 add_setshow_boolean_cmd ("debugexceptions", class_support
,
3001 &debug_exceptions
, _("\
3002 Set whether to display kernel exceptions in child process."), _("\
3003 Show whether to display kernel exceptions in child process."), NULL
,
3005 NULL
, /* FIXME: i18n: */
3006 &setlist
, &showlist
);
3008 init_w32_command_list ();
3010 add_cmd ("selector", class_info
, display_selectors
,
3011 _("Display selectors infos."),
3014 if (!initialize_loadable ())
3016 /* This will probably fail on Windows 9x/Me. Let the user know
3017 that we're missing some functionality. */
3019 cannot automatically find executable file or library to read symbols.\n\
3020 Use \"file\" or \"dll\" command to load executable/libraries directly."));
3024 /* Hardware watchpoint support, adapted from go32-nat.c code. */
3026 /* Pass the address ADDR to the inferior in the I'th debug register.
3027 Here we just store the address in dr array, the registers will be
3028 actually set up when windows_continue is called. */
3030 cygwin_set_dr (int i
, CORE_ADDR addr
)
3033 internal_error (__FILE__
, __LINE__
,
3034 _("Invalid register %d in cygwin_set_dr.\n"), i
);
3037 for (auto &th
: thread_list
)
3038 th
->debug_registers_changed
= true;
3041 /* Pass the value VAL to the inferior in the DR7 debug control
3042 register. Here we just store the address in D_REGS, the watchpoint
3043 will be actually set up in windows_wait. */
3045 cygwin_set_dr7 (unsigned long val
)
3047 dr
[7] = (CORE_ADDR
) val
;
3049 for (auto &th
: thread_list
)
3050 th
->debug_registers_changed
= true;
3053 /* Get the value of debug register I from the inferior. */
3056 cygwin_get_dr (int i
)
3061 /* Get the value of the DR6 debug status register from the inferior.
3062 Here we just return the value stored in dr[6]
3063 by the last call to thread_rec for current_event.dwThreadId id. */
3064 static unsigned long
3065 cygwin_get_dr6 (void)
3067 return (unsigned long) dr
[6];
3070 /* Get the value of the DR7 debug status register from the inferior.
3071 Here we just return the value stored in dr[7] by the last call to
3072 thread_rec for current_event.dwThreadId id. */
3074 static unsigned long
3075 cygwin_get_dr7 (void)
3077 return (unsigned long) dr
[7];
3080 /* Determine if the thread referenced by "ptid" is alive
3081 by "polling" it. If WaitForSingleObject returns WAIT_OBJECT_0
3082 it means that the thread has died. Otherwise it is assumed to be alive. */
3085 windows_nat_target::thread_alive (ptid_t ptid
)
3087 gdb_assert (ptid
.lwp () != 0);
3089 windows_thread_info
*th
3090 = windows_process
.thread_rec (ptid
, DONT_INVALIDATE_CONTEXT
);
3091 return WaitForSingleObject (th
->h
, 0) != WAIT_OBJECT_0
;
3094 void _initialize_check_for_gdb_ini ();
3096 _initialize_check_for_gdb_ini ()
3099 if (inhibit_gdbinit
)
3102 homedir
= getenv ("HOME");
3106 char *oldini
= (char *) alloca (strlen (homedir
) +
3107 sizeof ("gdb.ini") + 1);
3108 strcpy (oldini
, homedir
);
3109 p
= strchr (oldini
, '\0');
3110 if (p
> oldini
&& !IS_DIR_SEPARATOR (p
[-1]))
3112 strcpy (p
, "gdb.ini");
3113 if (access (oldini
, 0) == 0)
3115 int len
= strlen (oldini
);
3116 char *newini
= (char *) alloca (len
+ 2);
3118 xsnprintf (newini
, len
+ 2, "%.*s.gdbinit",
3119 (int) (len
- (sizeof ("gdb.ini") - 1)), oldini
);
3120 warning (_("obsolete '%s' found. Rename to '%s'."), oldini
, newini
);