Automatic date update in version.in
[binutils-gdb.git] / gdb / windows-nat.c
blob9265ed9e632688b7c9900be33adcb8d1bb809ad5
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 */
24 #include "defs.h"
25 #include "frame.h" /* required by inferior.h */
26 #include "inferior.h"
27 #include "infrun.h"
28 #include "target.h"
29 #include "gdbcore.h"
30 #include "command.h"
31 #include "completer.h"
32 #include "regcache.h"
33 #include "top.h"
34 #include <signal.h>
35 #include <sys/types.h>
36 #include <fcntl.h>
37 #include <windows.h>
38 #include <imagehlp.h>
39 #ifdef __CYGWIN__
40 #include <wchar.h>
41 #include <sys/cygwin.h>
42 #include <cygwin/version.h>
43 #endif
44 #include <algorithm>
45 #include <vector>
47 #include "filenames.h"
48 #include "symfile.h"
49 #include "objfiles.h"
50 #include "gdb_bfd.h"
51 #include "gdbsupport/gdb_obstack.h"
52 #include "gdbthread.h"
53 #include "gdbcmd.h"
54 #include <unistd.h>
55 #include "exec.h"
56 #include "solist.h"
57 #include "solib.h"
58 #include "xml-support.h"
59 #include "inttypes.h"
61 #include "i386-tdep.h"
62 #include "i387-tdep.h"
64 #include "windows-tdep.h"
65 #include "windows-nat.h"
66 #include "x86-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 /* Maintain a linked list of "so" information. */
78 struct windows_solib
80 LPVOID load_addr = 0;
81 CORE_ADDR text_offset = 0;
83 /* Original name. */
84 std::string original_name;
85 /* Expanded form of the name. */
86 std::string name;
89 struct windows_per_inferior : public windows_process_info
91 windows_thread_info *thread_rec (ptid_t ptid,
92 thread_disposition_type disposition) override;
93 int handle_output_debug_string (struct target_waitstatus *ourstatus) override;
94 void handle_load_dll (const char *dll_name, LPVOID base) override;
95 void handle_unload_dll () override;
96 bool handle_access_violation (const EXCEPTION_RECORD *rec) override;
99 int have_saved_context = 0; /* True if we've saved context from a
100 cygwin signal. */
102 uintptr_t dr[8] {};
104 int windows_initialization_done = 0;
106 std::vector<std::unique_ptr<windows_thread_info>> thread_list;
108 /* Counts of things. */
109 int saw_create = 0;
110 int open_process_used = 0;
111 #ifdef __x86_64__
112 void *wow64_dbgbreak = nullptr;
113 #endif
115 /* This vector maps GDB's idea of a register's number into an offset
116 in the windows exception context vector.
118 It also contains the bit mask needed to load the register in question.
120 The contents of this table can only be computed by the units
121 that provide CPU-specific support for Windows native debugging.
123 One day we could read a reg, we could inspect the context we
124 already have loaded, if it doesn't have the bit set that we need,
125 we read that set of registers in using GetThreadContext. If the
126 context already contains what we need, we just unpack it. Then to
127 write a register, first we have to ensure that the context contains
128 the other regs of the group, and then we copy the info in and set
129 out bit. */
131 const int *mappings = nullptr;
133 /* The function to use in order to determine whether a register is
134 a segment register or not. */
135 segment_register_p_ftype *segment_register_p = nullptr;
137 std::vector<windows_solib> solibs;
139 #ifdef __CYGWIN__
140 CONTEXT saved_context {}; /* Contains the saved context from a
141 cygwin signal. */
143 /* The starting and ending address of the cygwin1.dll text segment. */
144 CORE_ADDR cygwin_load_start = 0;
145 CORE_ADDR cygwin_load_end = 0;
146 #endif /* __CYGWIN__ */
149 /* The current process. */
150 static windows_per_inferior windows_process;
152 #undef STARTUPINFO
154 #ifndef __CYGWIN__
155 # define __PMAX (MAX_PATH + 1)
156 # define STARTUPINFO STARTUPINFOA
157 #else
158 # define __PMAX PATH_MAX
159 # define STARTUPINFO STARTUPINFOW
160 #endif
162 /* If we're not using the old Cygwin header file set, define the
163 following which never should have been in the generic Win32 API
164 headers in the first place since they were our own invention... */
165 #ifndef _GNU_H_WINDOWS_H
166 enum
168 FLAG_TRACE_BIT = 0x100,
170 #endif
172 #ifndef CONTEXT_EXTENDED_REGISTERS
173 /* This macro is only defined on ia32. It only makes sense on this target,
174 so define it as zero if not already defined. */
175 #define CONTEXT_EXTENDED_REGISTERS 0
176 #endif
178 #define CONTEXT_DEBUGGER_DR CONTEXT_FULL | CONTEXT_FLOATING_POINT \
179 | CONTEXT_SEGMENTS | CONTEXT_DEBUG_REGISTERS \
180 | CONTEXT_EXTENDED_REGISTERS
182 #define DR6_CLEAR_VALUE 0xffff0ff0
184 /* The string sent by cygwin when it processes a signal.
185 FIXME: This should be in a cygwin include file. */
186 #ifndef _CYGWIN_SIGNAL_STRING
187 #define _CYGWIN_SIGNAL_STRING "cYgSiGw00f"
188 #endif
190 #define CHECK(x) check (x, __FILE__,__LINE__)
191 #define DEBUG_EXEC(fmt, ...) \
192 debug_prefixed_printf_cond (debug_exec, "windows exec", fmt, ## __VA_ARGS__)
193 #define DEBUG_EVENTS(fmt, ...) \
194 debug_prefixed_printf_cond (debug_events, "windows events", fmt, \
195 ## __VA_ARGS__)
196 #define DEBUG_MEM(fmt, ...) \
197 debug_prefixed_printf_cond (debug_memory, "windows mem", fmt, \
198 ## __VA_ARGS__)
199 #define DEBUG_EXCEPT(fmt, ...) \
200 debug_prefixed_printf_cond (debug_exceptions, "windows except", fmt, \
201 ## __VA_ARGS__)
203 static void cygwin_set_dr (int i, CORE_ADDR addr);
204 static void cygwin_set_dr7 (unsigned long val);
205 static CORE_ADDR cygwin_get_dr (int i);
206 static unsigned long cygwin_get_dr6 (void);
207 static unsigned long cygwin_get_dr7 (void);
209 /* User options. */
210 static bool new_console = false;
211 #ifdef __CYGWIN__
212 static bool cygwin_exceptions = false;
213 #endif
214 static bool new_group = true;
215 static bool debug_exec = false; /* show execution */
216 static bool debug_events = false; /* show events from kernel */
217 static bool debug_memory = false; /* show target memory accesses */
218 static bool debug_exceptions = false; /* show target exceptions */
219 static bool useshell = false; /* use shell for subprocesses */
221 /* See windows_nat_target::resume to understand why this is commented
222 out. */
223 #if 0
224 /* This vector maps the target's idea of an exception (extracted
225 from the DEBUG_EVENT structure) to GDB's idea. */
227 struct xlate_exception
229 DWORD them;
230 enum gdb_signal us;
233 static const struct xlate_exception xlate[] =
235 {EXCEPTION_ACCESS_VIOLATION, GDB_SIGNAL_SEGV},
236 {STATUS_STACK_OVERFLOW, GDB_SIGNAL_SEGV},
237 {EXCEPTION_BREAKPOINT, GDB_SIGNAL_TRAP},
238 {DBG_CONTROL_C, GDB_SIGNAL_INT},
239 {EXCEPTION_SINGLE_STEP, GDB_SIGNAL_TRAP},
240 {STATUS_FLOAT_DIVIDE_BY_ZERO, GDB_SIGNAL_FPE}
243 #endif /* 0 */
245 struct windows_nat_target final : public x86_nat_target<inf_child_target>
247 void close () override;
249 void attach (const char *, int) override;
251 bool attach_no_wait () override
252 { return true; }
254 void detach (inferior *, int) override;
256 void resume (ptid_t, int , enum gdb_signal) override;
258 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
260 void fetch_registers (struct regcache *, int) override;
261 void store_registers (struct regcache *, int) override;
263 bool stopped_by_sw_breakpoint () override
265 windows_thread_info *th
266 = windows_process.thread_rec (inferior_ptid, DONT_INVALIDATE_CONTEXT);
267 return th->stopped_at_software_breakpoint;
270 bool supports_stopped_by_sw_breakpoint () override
272 return true;
275 enum target_xfer_status xfer_partial (enum target_object object,
276 const char *annex,
277 gdb_byte *readbuf,
278 const gdb_byte *writebuf,
279 ULONGEST offset, ULONGEST len,
280 ULONGEST *xfered_len) override;
282 void files_info () override;
284 void kill () override;
286 void create_inferior (const char *, const std::string &,
287 char **, int) override;
289 void mourn_inferior () override;
291 bool thread_alive (ptid_t ptid) override;
293 std::string pid_to_str (ptid_t) override;
295 void interrupt () override;
297 const char *pid_to_exec_file (int pid) override;
299 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
301 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
303 const char *thread_name (struct thread_info *) override;
305 int get_windows_debug_event (int pid, struct target_waitstatus *ourstatus);
307 void do_initial_windows_stuff (DWORD pid, bool attaching);
309 bool supports_disable_randomization () override
311 return disable_randomization_available ();
314 private:
316 windows_thread_info *add_thread (ptid_t ptid, HANDLE h, void *tlb,
317 bool main_thread_p);
318 void delete_thread (ptid_t ptid, DWORD exit_code, bool main_thread_p);
319 DWORD fake_create_process ();
322 static windows_nat_target the_windows_nat_target;
324 static void
325 check (BOOL ok, const char *file, int line)
327 if (!ok)
328 gdb_printf ("error return %s:%d was %u\n", file, line,
329 (unsigned) GetLastError ());
332 /* See nat/windows-nat.h. */
334 windows_thread_info *
335 windows_per_inferior::thread_rec
336 (ptid_t ptid, thread_disposition_type disposition)
338 for (auto &th : thread_list)
339 if (th->tid == ptid.lwp ())
341 if (!th->suspended)
343 switch (disposition)
345 case DONT_INVALIDATE_CONTEXT:
346 /* Nothing. */
347 break;
348 case INVALIDATE_CONTEXT:
349 if (ptid.lwp () != current_event.dwThreadId)
350 th->suspend ();
351 th->reload_context = true;
352 break;
353 case DONT_SUSPEND:
354 th->reload_context = true;
355 th->suspended = -1;
356 break;
359 return th.get ();
362 return NULL;
365 /* Add a thread to the thread list.
367 PTID is the ptid of the thread to be added.
368 H is its Windows handle.
369 TLB is its thread local base.
370 MAIN_THREAD_P should be true if the thread to be added is
371 the main thread, false otherwise. */
373 windows_thread_info *
374 windows_nat_target::add_thread (ptid_t ptid, HANDLE h, void *tlb,
375 bool main_thread_p)
377 windows_thread_info *th;
379 gdb_assert (ptid.lwp () != 0);
381 if ((th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT)))
382 return th;
384 CORE_ADDR base = (CORE_ADDR) (uintptr_t) tlb;
385 #ifdef __x86_64__
386 /* For WOW64 processes, this is actually the pointer to the 64bit TIB,
387 and the 32bit TIB is exactly 2 pages after it. */
388 if (windows_process.wow64_process)
389 base += 0x2000;
390 #endif
391 th = new windows_thread_info (ptid.lwp (), h, base);
392 windows_process.thread_list.emplace_back (th);
394 /* Add this new thread to the list of threads.
396 To be consistent with what's done on other platforms, we add
397 the main thread silently (in reality, this thread is really
398 more of a process to the user than a thread). */
399 if (main_thread_p)
400 add_thread_silent (this, ptid);
401 else
402 ::add_thread (this, ptid);
404 /* It's simplest to always set this and update the debug
405 registers. */
406 th->debug_registers_changed = true;
408 return th;
411 /* Clear out any old thread list and reinitialize it to a
412 pristine state. */
413 static void
414 windows_init_thread_list (void)
416 DEBUG_EVENTS ("called");
417 windows_process.thread_list.clear ();
420 /* Delete a thread from the list of threads.
422 PTID is the ptid of the thread to be deleted.
423 EXIT_CODE is the thread's exit code.
424 MAIN_THREAD_P should be true if the thread to be deleted is
425 the main thread, false otherwise. */
427 void
428 windows_nat_target::delete_thread (ptid_t ptid, DWORD exit_code,
429 bool main_thread_p)
431 DWORD id;
433 gdb_assert (ptid.lwp () != 0);
435 id = ptid.lwp ();
437 /* Emit a notification about the thread being deleted.
439 Note that no notification was printed when the main thread
440 was created, and thus, unless in verbose mode, we should be
441 symmetrical, and avoid that notification for the main thread
442 here as well. */
444 if (info_verbose)
445 gdb_printf ("[Deleting %s]\n", target_pid_to_str (ptid).c_str ());
446 else if (print_thread_events && !main_thread_p)
447 gdb_printf (_("[%s exited with code %u]\n"),
448 target_pid_to_str (ptid).c_str (),
449 (unsigned) exit_code);
451 ::delete_thread (find_thread_ptid (&the_windows_nat_target, ptid));
453 auto iter = std::find_if (windows_process.thread_list.begin (),
454 windows_process.thread_list.end (),
455 [=] (auto &th)
457 return th->tid == id;
460 if (iter != windows_process.thread_list.end ())
461 windows_process.thread_list.erase (iter);
464 /* Fetches register number R from the given windows_thread_info,
465 and supplies its value to the given regcache.
467 This function assumes that R is non-negative. A failed assertion
468 is raised if that is not true.
470 This function assumes that TH->RELOAD_CONTEXT is not set, meaning
471 that the windows_thread_info has an up-to-date context. A failed
472 assertion is raised if that assumption is violated. */
474 static void
475 windows_fetch_one_register (struct regcache *regcache,
476 windows_thread_info *th, int r)
478 gdb_assert (r >= 0);
479 gdb_assert (!th->reload_context);
481 char *context_ptr = (char *) &th->context;
482 #ifdef __x86_64__
483 if (windows_process.wow64_process)
484 context_ptr = (char *) &th->wow64_context;
485 #endif
487 char *context_offset = context_ptr + windows_process.mappings[r];
488 struct gdbarch *gdbarch = regcache->arch ();
489 i386_gdbarch_tdep *tdep = gdbarch_tdep<i386_gdbarch_tdep> (gdbarch);
491 gdb_assert (!gdbarch_read_pc_p (gdbarch));
492 gdb_assert (gdbarch_pc_regnum (gdbarch) >= 0);
493 gdb_assert (!gdbarch_write_pc_p (gdbarch));
495 if (r == I387_FISEG_REGNUM (tdep))
497 long l = *((long *) context_offset) & 0xffff;
498 regcache->raw_supply (r, (char *) &l);
500 else if (r == I387_FOP_REGNUM (tdep))
502 long l = (*((long *) context_offset) >> 16) & ((1 << 11) - 1);
503 regcache->raw_supply (r, (char *) &l);
505 else if (windows_process.segment_register_p (r))
507 /* GDB treats segment registers as 32bit registers, but they are
508 in fact only 16 bits long. Make sure we do not read extra
509 bits from our source buffer. */
510 long l = *((long *) context_offset) & 0xffff;
511 regcache->raw_supply (r, (char *) &l);
513 else
515 if (th->stopped_at_software_breakpoint
516 && !th->pc_adjusted
517 && r == gdbarch_pc_regnum (gdbarch))
519 int size = register_size (gdbarch, r);
520 if (size == 4)
522 uint32_t value;
523 memcpy (&value, context_offset, size);
524 value -= gdbarch_decr_pc_after_break (gdbarch);
525 memcpy (context_offset, &value, size);
527 else
529 gdb_assert (size == 8);
530 uint64_t value;
531 memcpy (&value, context_offset, size);
532 value -= gdbarch_decr_pc_after_break (gdbarch);
533 memcpy (context_offset, &value, size);
535 /* Make sure we only rewrite the PC a single time. */
536 th->pc_adjusted = true;
538 regcache->raw_supply (r, context_offset);
542 void
543 windows_nat_target::fetch_registers (struct regcache *regcache, int r)
545 windows_thread_info *th
546 = windows_process.thread_rec (regcache->ptid (), INVALIDATE_CONTEXT);
548 /* Check if TH exists. Windows sometimes uses a non-existent
549 thread id in its events. */
550 if (th == NULL)
551 return;
553 if (th->reload_context)
555 #ifdef __CYGWIN__
556 if (have_saved_context)
558 /* Lie about where the program actually is stopped since
559 cygwin has informed us that we should consider the signal
560 to have occurred at another location which is stored in
561 "saved_context. */
562 memcpy (&th->context, &saved_context,
563 __COPY_CONTEXT_SIZE);
564 have_saved_context = 0;
566 else
567 #endif
568 #ifdef __x86_64__
569 if (windows_process.wow64_process)
571 th->wow64_context.ContextFlags = CONTEXT_DEBUGGER_DR;
572 CHECK (Wow64GetThreadContext (th->h, &th->wow64_context));
573 /* Copy dr values from that thread.
574 But only if there were not modified since last stop.
575 PR gdb/2388 */
576 if (!th->debug_registers_changed)
578 windows_process.dr[0] = th->wow64_context.Dr0;
579 windows_process.dr[1] = th->wow64_context.Dr1;
580 windows_process.dr[2] = th->wow64_context.Dr2;
581 windows_process.dr[3] = th->wow64_context.Dr3;
582 windows_process.dr[6] = th->wow64_context.Dr6;
583 windows_process.dr[7] = th->wow64_context.Dr7;
586 else
587 #endif
589 th->context.ContextFlags = CONTEXT_DEBUGGER_DR;
590 CHECK (GetThreadContext (th->h, &th->context));
591 /* Copy dr values from that thread.
592 But only if there were not modified since last stop.
593 PR gdb/2388 */
594 if (!th->debug_registers_changed)
596 windows_process.dr[0] = th->context.Dr0;
597 windows_process.dr[1] = th->context.Dr1;
598 windows_process.dr[2] = th->context.Dr2;
599 windows_process.dr[3] = th->context.Dr3;
600 windows_process.dr[6] = th->context.Dr6;
601 windows_process.dr[7] = th->context.Dr7;
604 th->reload_context = false;
607 if (r < 0)
608 for (r = 0; r < gdbarch_num_regs (regcache->arch()); r++)
609 windows_fetch_one_register (regcache, th, r);
610 else
611 windows_fetch_one_register (regcache, th, r);
614 /* Collect the register number R from the given regcache, and store
615 its value into the corresponding area of the given thread's context.
617 This function assumes that R is non-negative. A failed assertion
618 assertion is raised if that is not true. */
620 static void
621 windows_store_one_register (const struct regcache *regcache,
622 windows_thread_info *th, int r)
624 gdb_assert (r >= 0);
626 char *context_ptr = (char *) &th->context;
627 #ifdef __x86_64__
628 if (windows_process.wow64_process)
629 context_ptr = (char *) &th->wow64_context;
630 #endif
632 regcache->raw_collect (r, context_ptr + windows_process.mappings[r]);
635 /* Store a new register value into the context of the thread tied to
636 REGCACHE. */
638 void
639 windows_nat_target::store_registers (struct regcache *regcache, int r)
641 windows_thread_info *th
642 = windows_process.thread_rec (regcache->ptid (), INVALIDATE_CONTEXT);
644 /* Check if TH exists. Windows sometimes uses a non-existent
645 thread id in its events. */
646 if (th == NULL)
647 return;
649 if (r < 0)
650 for (r = 0; r < gdbarch_num_regs (regcache->arch ()); r++)
651 windows_store_one_register (regcache, th, r);
652 else
653 windows_store_one_register (regcache, th, r);
656 /* See nat/windows-nat.h. */
658 static windows_solib *
659 windows_make_so (const char *name, LPVOID load_addr)
661 #ifndef __CYGWIN__
662 char *p;
663 char buf[__PMAX];
664 char cwd[__PMAX];
665 WIN32_FIND_DATA w32_fd;
666 HANDLE h = FindFirstFile(name, &w32_fd);
668 if (h == INVALID_HANDLE_VALUE)
669 strcpy (buf, name);
670 else
672 FindClose (h);
673 strcpy (buf, name);
674 if (GetCurrentDirectory (MAX_PATH + 1, cwd))
676 p = strrchr (buf, '\\');
677 if (p)
678 p[1] = '\0';
679 SetCurrentDirectory (buf);
680 GetFullPathName (w32_fd.cFileName, MAX_PATH, buf, &p);
681 SetCurrentDirectory (cwd);
684 if (strcasecmp (buf, "ntdll.dll") == 0)
686 GetSystemDirectory (buf, sizeof (buf));
687 strcat (buf, "\\ntdll.dll");
689 #else
690 wchar_t buf[__PMAX];
692 buf[0] = 0;
693 if (access (name, F_OK) != 0)
695 if (strcasecmp (name, "ntdll.dll") == 0)
697 GetSystemDirectoryW (buf, sizeof (buf) / sizeof (wchar_t));
698 wcscat (buf, L"\\ntdll.dll");
701 #endif
702 windows_process.solibs.emplace_back ();
703 windows_solib *so = &windows_process.solibs.back ();
704 so->load_addr = load_addr;
705 so->original_name = name;
706 #ifndef __CYGWIN__
707 so->name = buf;
708 #else
709 if (buf[0])
711 char cname[SO_NAME_MAX_PATH_SIZE];
712 cygwin_conv_path (CCP_WIN_W_TO_POSIX, buf, cname,
713 SO_NAME_MAX_PATH_SIZE);
714 so->name = cname;
716 else
718 char *rname = realpath (name, NULL);
719 if (rname && strlen (rname) < SO_NAME_MAX_PATH_SIZE)
721 so->name = rname;
722 free (rname);
724 else
726 warning (_("dll path for \"%s\" too long or inaccessible"), name);
727 so->name = so->original_name;
730 /* Record cygwin1.dll .text start/end. */
731 size_t len = sizeof ("/cygwin1.dll") - 1;
732 if (so->name.size () >= len
733 && strcasecmp (so->name.c_str () + so->name.size () - len,
734 "/cygwin1.dll") == 0)
736 asection *text = NULL;
738 gdb_bfd_ref_ptr abfd (gdb_bfd_open (so->name.c_str(), "pei-i386"));
740 if (abfd == NULL)
741 return so;
743 if (bfd_check_format (abfd.get (), bfd_object))
744 text = bfd_get_section_by_name (abfd.get (), ".text");
746 if (!text)
747 return so;
749 /* The symbols in a dll are offset by 0x1000, which is the
750 offset from 0 of the first byte in an image - because of the
751 file header and the section alignment. */
752 cygwin_load_start = (CORE_ADDR) (uintptr_t) ((char *)
753 load_addr + 0x1000);
754 cygwin_load_end = cygwin_load_start + bfd_section_size (text);
756 #endif
758 return so;
761 /* See nat/windows-nat.h. */
763 void
764 windows_per_inferior::handle_load_dll (const char *dll_name, LPVOID base)
766 windows_solib *solib = windows_make_so (dll_name, base);
767 DEBUG_EVENTS ("Loading dll \"%s\" at %s.", solib->name.c_str (),
768 host_address_to_string (solib->load_addr));
771 /* See nat/windows-nat.h. */
773 void
774 windows_per_inferior::handle_unload_dll ()
776 LPVOID lpBaseOfDll = current_event.u.UnloadDll.lpBaseOfDll;
778 auto iter = std::remove_if (windows_process.solibs.begin (),
779 windows_process.solibs.end (),
780 [&] (windows_solib &lib)
782 if (lib.load_addr == lpBaseOfDll)
784 DEBUG_EVENTS ("Unloading dll \"%s\".", lib.name.c_str ());
785 return true;
787 return false;
790 if (iter != windows_process.solibs.end ())
792 windows_process.solibs.erase (iter, windows_process.solibs.end ());
793 return;
796 /* We did not find any DLL that was previously loaded at this address,
797 so register a complaint. We do not report an error, because we have
798 observed that this may be happening under some circumstances. For
799 instance, running 32bit applications on x64 Windows causes us to receive
800 4 mysterious UNLOAD_DLL_DEBUG_EVENTs during the startup phase (these
801 events are apparently caused by the WOW layer, the interface between
802 32bit and 64bit worlds). */
803 complaint (_("dll starting at %s not found."),
804 host_address_to_string (lpBaseOfDll));
807 /* Clear list of loaded DLLs. */
808 static void
809 windows_clear_solib (void)
811 windows_process.solibs.clear ();
814 static void
815 signal_event_command (const char *args, int from_tty)
817 uintptr_t event_id = 0;
818 char *endargs = NULL;
820 if (args == NULL)
821 error (_("signal-event requires an argument (integer event id)"));
823 event_id = strtoumax (args, &endargs, 10);
825 if ((errno == ERANGE) || (event_id == 0) || (event_id > UINTPTR_MAX) ||
826 ((HANDLE) event_id == INVALID_HANDLE_VALUE))
827 error (_("Failed to convert `%s' to event id"), args);
829 SetEvent ((HANDLE) event_id);
830 CloseHandle ((HANDLE) event_id);
833 /* See nat/windows-nat.h. */
836 windows_per_inferior::handle_output_debug_string
837 (struct target_waitstatus *ourstatus)
839 int retval = 0;
841 gdb::unique_xmalloc_ptr<char> s
842 = (target_read_string
843 ((CORE_ADDR) (uintptr_t) current_event.u.DebugString.lpDebugStringData,
844 1024));
845 if (s == nullptr || !*(s.get ()))
846 /* nothing to do */;
847 else if (!startswith (s.get (), _CYGWIN_SIGNAL_STRING))
849 #ifdef __CYGWIN__
850 if (!startswith (s.get (), "cYg"))
851 #endif
853 char *p = strchr (s.get (), '\0');
855 if (p > s.get () && *--p == '\n')
856 *p = '\0';
857 warning (("%s"), s.get ());
860 #ifdef __CYGWIN__
861 else
863 /* Got a cygwin signal marker. A cygwin signal is followed by
864 the signal number itself and then optionally followed by the
865 thread id and address to saved context within the DLL. If
866 these are supplied, then the given thread is assumed to have
867 issued the signal and the context from the thread is assumed
868 to be stored at the given address in the inferior. Tell gdb
869 to treat this like a real signal. */
870 char *p;
871 int sig = strtol (s.get () + sizeof (_CYGWIN_SIGNAL_STRING) - 1, &p, 0);
872 gdb_signal gotasig = gdb_signal_from_host (sig);
874 if (gotasig)
876 LPCVOID x;
877 SIZE_T n;
879 ourstatus->set_stopped (gotasig);
880 retval = strtoul (p, &p, 0);
881 if (!retval)
882 retval = current_event.dwThreadId;
883 else if ((x = (LPCVOID) (uintptr_t) strtoull (p, NULL, 0))
884 && ReadProcessMemory (handle, x,
885 &saved_context,
886 __COPY_CONTEXT_SIZE, &n)
887 && n == __COPY_CONTEXT_SIZE)
888 have_saved_context = 1;
891 #endif
893 return retval;
896 static int
897 display_selector (HANDLE thread, DWORD sel)
899 LDT_ENTRY info;
900 BOOL ret;
901 #ifdef __x86_64__
902 if (windows_process.wow64_process)
903 ret = Wow64GetThreadSelectorEntry (thread, sel, &info);
904 else
905 #endif
906 ret = GetThreadSelectorEntry (thread, sel, &info);
907 if (ret)
909 int base, limit;
910 gdb_printf ("0x%03x: ", (unsigned) sel);
911 if (!info.HighWord.Bits.Pres)
913 gdb_puts ("Segment not present\n");
914 return 0;
916 base = (info.HighWord.Bits.BaseHi << 24) +
917 (info.HighWord.Bits.BaseMid << 16)
918 + info.BaseLow;
919 limit = (info.HighWord.Bits.LimitHi << 16) + info.LimitLow;
920 if (info.HighWord.Bits.Granularity)
921 limit = (limit << 12) | 0xfff;
922 gdb_printf ("base=0x%08x limit=0x%08x", base, limit);
923 if (info.HighWord.Bits.Default_Big)
924 gdb_puts(" 32-bit ");
925 else
926 gdb_puts(" 16-bit ");
927 switch ((info.HighWord.Bits.Type & 0xf) >> 1)
929 case 0:
930 gdb_puts ("Data (Read-Only, Exp-up");
931 break;
932 case 1:
933 gdb_puts ("Data (Read/Write, Exp-up");
934 break;
935 case 2:
936 gdb_puts ("Unused segment (");
937 break;
938 case 3:
939 gdb_puts ("Data (Read/Write, Exp-down");
940 break;
941 case 4:
942 gdb_puts ("Code (Exec-Only, N.Conf");
943 break;
944 case 5:
945 gdb_puts ("Code (Exec/Read, N.Conf");
946 break;
947 case 6:
948 gdb_puts ("Code (Exec-Only, Conf");
949 break;
950 case 7:
951 gdb_puts ("Code (Exec/Read, Conf");
952 break;
953 default:
954 gdb_printf ("Unknown type 0x%lx",
955 (unsigned long) info.HighWord.Bits.Type);
957 if ((info.HighWord.Bits.Type & 0x1) == 0)
958 gdb_puts(", N.Acc");
959 gdb_puts (")\n");
960 if ((info.HighWord.Bits.Type & 0x10) == 0)
961 gdb_puts("System selector ");
962 gdb_printf ("Privilege level = %ld. ",
963 (unsigned long) info.HighWord.Bits.Dpl);
964 if (info.HighWord.Bits.Granularity)
965 gdb_puts ("Page granular.\n");
966 else
967 gdb_puts ("Byte granular.\n");
968 return 1;
970 else
972 DWORD err = GetLastError ();
973 if (err == ERROR_NOT_SUPPORTED)
974 gdb_printf ("Function not supported\n");
975 else
976 gdb_printf ("Invalid selector 0x%x.\n", (unsigned) sel);
977 return 0;
981 static void
982 display_selectors (const char * args, int from_tty)
984 if (inferior_ptid == null_ptid)
986 gdb_puts ("Impossible to display selectors now.\n");
987 return;
990 windows_thread_info *current_windows_thread
991 = windows_process.thread_rec (inferior_ptid, DONT_INVALIDATE_CONTEXT);
993 if (!args)
995 #ifdef __x86_64__
996 if (windows_process.wow64_process)
998 gdb_puts ("Selector $cs\n");
999 display_selector (current_windows_thread->h,
1000 current_windows_thread->wow64_context.SegCs);
1001 gdb_puts ("Selector $ds\n");
1002 display_selector (current_windows_thread->h,
1003 current_windows_thread->wow64_context.SegDs);
1004 gdb_puts ("Selector $es\n");
1005 display_selector (current_windows_thread->h,
1006 current_windows_thread->wow64_context.SegEs);
1007 gdb_puts ("Selector $ss\n");
1008 display_selector (current_windows_thread->h,
1009 current_windows_thread->wow64_context.SegSs);
1010 gdb_puts ("Selector $fs\n");
1011 display_selector (current_windows_thread->h,
1012 current_windows_thread->wow64_context.SegFs);
1013 gdb_puts ("Selector $gs\n");
1014 display_selector (current_windows_thread->h,
1015 current_windows_thread->wow64_context.SegGs);
1017 else
1018 #endif
1020 gdb_puts ("Selector $cs\n");
1021 display_selector (current_windows_thread->h,
1022 current_windows_thread->context.SegCs);
1023 gdb_puts ("Selector $ds\n");
1024 display_selector (current_windows_thread->h,
1025 current_windows_thread->context.SegDs);
1026 gdb_puts ("Selector $es\n");
1027 display_selector (current_windows_thread->h,
1028 current_windows_thread->context.SegEs);
1029 gdb_puts ("Selector $ss\n");
1030 display_selector (current_windows_thread->h,
1031 current_windows_thread->context.SegSs);
1032 gdb_puts ("Selector $fs\n");
1033 display_selector (current_windows_thread->h,
1034 current_windows_thread->context.SegFs);
1035 gdb_puts ("Selector $gs\n");
1036 display_selector (current_windows_thread->h,
1037 current_windows_thread->context.SegGs);
1040 else
1042 int sel;
1043 sel = parse_and_eval_long (args);
1044 gdb_printf ("Selector \"%s\"\n",args);
1045 display_selector (current_windows_thread->h, sel);
1049 /* See nat/windows-nat.h. */
1051 bool
1052 windows_per_inferior::handle_access_violation
1053 (const EXCEPTION_RECORD *rec)
1055 #ifdef __CYGWIN__
1056 /* See if the access violation happened within the cygwin DLL
1057 itself. Cygwin uses a kind of exception handling to deal with
1058 passed-in invalid addresses. gdb should not treat these as real
1059 SEGVs since they will be silently handled by cygwin. A real SEGV
1060 will (theoretically) be caught by cygwin later in the process and
1061 will be sent as a cygwin-specific-signal. So, ignore SEGVs if
1062 they show up within the text segment of the DLL itself. */
1063 const char *fn;
1064 CORE_ADDR addr = (CORE_ADDR) (uintptr_t) rec->ExceptionAddress;
1066 if ((!cygwin_exceptions && (addr >= cygwin_load_start
1067 && addr < cygwin_load_end))
1068 || (find_pc_partial_function (addr, &fn, NULL, NULL)
1069 && startswith (fn, "KERNEL32!IsBad")))
1070 return true;
1071 #endif
1072 return false;
1075 /* Resume thread specified by ID, or all artificially suspended
1076 threads, if we are continuing execution. KILLED non-zero means we
1077 have killed the inferior, so we should ignore weird errors due to
1078 threads shutting down. */
1079 static BOOL
1080 windows_continue (DWORD continue_status, int id, int killed)
1082 BOOL res;
1084 windows_process.desired_stop_thread_id = id;
1086 if (windows_process.matching_pending_stop (debug_events))
1087 return TRUE;
1089 for (auto &th : windows_process.thread_list)
1090 if (id == -1 || id == (int) th->tid)
1092 #ifdef __x86_64__
1093 if (windows_process.wow64_process)
1095 if (th->debug_registers_changed)
1097 th->wow64_context.ContextFlags |= CONTEXT_DEBUG_REGISTERS;
1098 th->wow64_context.Dr0 = windows_process.dr[0];
1099 th->wow64_context.Dr1 = windows_process.dr[1];
1100 th->wow64_context.Dr2 = windows_process.dr[2];
1101 th->wow64_context.Dr3 = windows_process.dr[3];
1102 th->wow64_context.Dr6 = DR6_CLEAR_VALUE;
1103 th->wow64_context.Dr7 = windows_process.dr[7];
1104 th->debug_registers_changed = false;
1106 if (th->wow64_context.ContextFlags)
1108 DWORD ec = 0;
1110 if (GetExitCodeThread (th->h, &ec)
1111 && ec == STILL_ACTIVE)
1113 BOOL status = Wow64SetThreadContext (th->h,
1114 &th->wow64_context);
1116 if (!killed)
1117 CHECK (status);
1119 th->wow64_context.ContextFlags = 0;
1122 else
1123 #endif
1125 if (th->debug_registers_changed)
1127 th->context.ContextFlags |= CONTEXT_DEBUG_REGISTERS;
1128 th->context.Dr0 = windows_process.dr[0];
1129 th->context.Dr1 = windows_process.dr[1];
1130 th->context.Dr2 = windows_process.dr[2];
1131 th->context.Dr3 = windows_process.dr[3];
1132 th->context.Dr6 = DR6_CLEAR_VALUE;
1133 th->context.Dr7 = windows_process.dr[7];
1134 th->debug_registers_changed = false;
1136 if (th->context.ContextFlags)
1138 DWORD ec = 0;
1140 if (GetExitCodeThread (th->h, &ec)
1141 && ec == STILL_ACTIVE)
1143 BOOL status = SetThreadContext (th->h, &th->context);
1145 if (!killed)
1146 CHECK (status);
1148 th->context.ContextFlags = 0;
1151 th->resume ();
1153 else
1155 /* When single-stepping a specific thread, other threads must
1156 be suspended. */
1157 th->suspend ();
1160 res = continue_last_debug_event (continue_status, debug_events);
1162 if (!res)
1163 error (_("Failed to resume program execution"
1164 " (ContinueDebugEvent failed, error %u)"),
1165 (unsigned int) GetLastError ());
1167 return res;
1170 /* Called in pathological case where Windows fails to send a
1171 CREATE_PROCESS_DEBUG_EVENT after an attach. */
1172 DWORD
1173 windows_nat_target::fake_create_process ()
1175 windows_process.handle
1176 = OpenProcess (PROCESS_ALL_ACCESS, FALSE,
1177 windows_process.current_event.dwProcessId);
1178 if (windows_process.handle != NULL)
1179 windows_process.open_process_used = 1;
1180 else
1182 error (_("OpenProcess call failed, GetLastError = %u"),
1183 (unsigned) GetLastError ());
1184 /* We can not debug anything in that case. */
1186 add_thread (ptid_t (windows_process.current_event.dwProcessId, 0,
1187 windows_process.current_event.dwThreadId),
1188 windows_process.current_event.u.CreateThread.hThread,
1189 windows_process.current_event.u.CreateThread.lpThreadLocalBase,
1190 true /* main_thread_p */);
1191 return windows_process.current_event.dwThreadId;
1194 void
1195 windows_nat_target::resume (ptid_t ptid, int step, enum gdb_signal sig)
1197 windows_thread_info *th;
1198 DWORD continue_status = DBG_CONTINUE;
1200 /* A specific PTID means `step only this thread id'. */
1201 int resume_all = ptid == minus_one_ptid;
1203 /* If we're continuing all threads, it's the current inferior that
1204 should be handled specially. */
1205 if (resume_all)
1206 ptid = inferior_ptid;
1208 if (sig != GDB_SIGNAL_0)
1210 if (windows_process.current_event.dwDebugEventCode
1211 != EXCEPTION_DEBUG_EVENT)
1213 DEBUG_EXCEPT ("Cannot continue with signal %d here.", sig);
1215 else if (sig == windows_process.last_sig)
1216 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1217 else
1218 #if 0
1219 /* This code does not seem to work, because
1220 the kernel does probably not consider changes in the ExceptionRecord
1221 structure when passing the exception to the inferior.
1222 Note that this seems possible in the exception handler itself. */
1224 for (const xlate_exception &x : xlate)
1225 if (x.us == sig)
1227 current_event.u.Exception.ExceptionRecord.ExceptionCode
1228 = x.them;
1229 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1230 break;
1232 if (continue_status == DBG_CONTINUE)
1234 DEBUG_EXCEPT ("Cannot continue with signal %d.", sig);
1237 #endif
1238 DEBUG_EXCEPT ("Can only continue with received signal %d.",
1239 windows_process.last_sig);
1242 windows_process.last_sig = GDB_SIGNAL_0;
1244 DEBUG_EXEC ("pid=%d, tid=0x%x, step=%d, sig=%d",
1245 ptid.pid (), (unsigned) ptid.lwp (), step, sig);
1247 /* Get context for currently selected thread. */
1248 th = windows_process.thread_rec (inferior_ptid, DONT_INVALIDATE_CONTEXT);
1249 if (th)
1251 #ifdef __x86_64__
1252 if (windows_process.wow64_process)
1254 if (step)
1256 /* Single step by setting t bit. */
1257 struct regcache *regcache = get_current_regcache ();
1258 struct gdbarch *gdbarch = regcache->arch ();
1259 fetch_registers (regcache, gdbarch_ps_regnum (gdbarch));
1260 th->wow64_context.EFlags |= FLAG_TRACE_BIT;
1263 if (th->wow64_context.ContextFlags)
1265 if (th->debug_registers_changed)
1267 th->wow64_context.Dr0 = windows_process.dr[0];
1268 th->wow64_context.Dr1 = windows_process.dr[1];
1269 th->wow64_context.Dr2 = windows_process.dr[2];
1270 th->wow64_context.Dr3 = windows_process.dr[3];
1271 th->wow64_context.Dr6 = DR6_CLEAR_VALUE;
1272 th->wow64_context.Dr7 = windows_process.dr[7];
1273 th->debug_registers_changed = false;
1275 CHECK (Wow64SetThreadContext (th->h, &th->wow64_context));
1276 th->wow64_context.ContextFlags = 0;
1279 else
1280 #endif
1282 if (step)
1284 /* Single step by setting t bit. */
1285 struct regcache *regcache = get_current_regcache ();
1286 struct gdbarch *gdbarch = regcache->arch ();
1287 fetch_registers (regcache, gdbarch_ps_regnum (gdbarch));
1288 th->context.EFlags |= FLAG_TRACE_BIT;
1291 if (th->context.ContextFlags)
1293 if (th->debug_registers_changed)
1295 th->context.Dr0 = windows_process.dr[0];
1296 th->context.Dr1 = windows_process.dr[1];
1297 th->context.Dr2 = windows_process.dr[2];
1298 th->context.Dr3 = windows_process.dr[3];
1299 th->context.Dr6 = DR6_CLEAR_VALUE;
1300 th->context.Dr7 = windows_process.dr[7];
1301 th->debug_registers_changed = false;
1303 CHECK (SetThreadContext (th->h, &th->context));
1304 th->context.ContextFlags = 0;
1309 /* Allow continuing with the same signal that interrupted us.
1310 Otherwise complain. */
1312 if (resume_all)
1313 windows_continue (continue_status, -1, 0);
1314 else
1315 windows_continue (continue_status, ptid.lwp (), 0);
1318 /* Ctrl-C handler used when the inferior is not run in the same console. The
1319 handler is in charge of interrupting the inferior using DebugBreakProcess.
1320 Note that this function is not available prior to Windows XP. In this case
1321 we emit a warning. */
1322 static BOOL WINAPI
1323 ctrl_c_handler (DWORD event_type)
1325 const int attach_flag = current_inferior ()->attach_flag;
1327 /* Only handle Ctrl-C and Ctrl-Break events. Ignore others. */
1328 if (event_type != CTRL_C_EVENT && event_type != CTRL_BREAK_EVENT)
1329 return FALSE;
1331 /* If the inferior and the debugger share the same console, do nothing as
1332 the inferior has also received the Ctrl-C event. */
1333 if (!new_console && !attach_flag)
1334 return TRUE;
1336 #ifdef __x86_64__
1337 if (windows_process.wow64_process)
1339 /* Call DbgUiRemoteBreakin of the 32bit ntdll.dll in the target process.
1340 DebugBreakProcess would call the one of the 64bit ntdll.dll, which
1341 can't be correctly handled by gdb. */
1342 if (windows_process.wow64_dbgbreak == nullptr)
1344 CORE_ADDR addr;
1345 if (!find_minimal_symbol_address ("ntdll!DbgUiRemoteBreakin",
1346 &addr, 0))
1347 windows_process.wow64_dbgbreak = (void *) addr;
1350 if (windows_process.wow64_dbgbreak != nullptr)
1352 HANDLE thread = CreateRemoteThread (windows_process.handle, NULL,
1353 0, (LPTHREAD_START_ROUTINE)
1354 windows_process.wow64_dbgbreak,
1355 NULL, 0, NULL);
1356 if (thread)
1357 CloseHandle (thread);
1360 else
1361 #endif
1363 if (!DebugBreakProcess (windows_process.handle))
1364 warning (_("Could not interrupt program. "
1365 "Press Ctrl-c in the program console."));
1368 /* Return true to tell that Ctrl-C has been handled. */
1369 return TRUE;
1372 /* Get the next event from the child. Returns a non-zero thread id if the event
1373 requires handling by WFI (or whatever). */
1376 windows_nat_target::get_windows_debug_event (int pid,
1377 struct target_waitstatus *ourstatus)
1379 BOOL debug_event;
1380 DWORD continue_status, event_code;
1381 DWORD thread_id = 0;
1383 /* If there is a relevant pending stop, report it now. See the
1384 comment by the definition of "pending_stops" for details on why
1385 this is needed. */
1386 gdb::optional<pending_stop> stop
1387 = windows_process.fetch_pending_stop (debug_events);
1388 if (stop.has_value ())
1390 thread_id = stop->thread_id;
1391 *ourstatus = stop->status;
1393 ptid_t ptid (windows_process.current_event.dwProcessId, thread_id);
1394 windows_thread_info *th
1395 = windows_process.thread_rec (ptid, INVALIDATE_CONTEXT);
1396 th->reload_context = true;
1398 return thread_id;
1401 windows_process.last_sig = GDB_SIGNAL_0;
1402 DEBUG_EVENT *current_event = &windows_process.current_event;
1404 if (!(debug_event = wait_for_debug_event (&windows_process.current_event,
1405 1000)))
1406 goto out;
1408 continue_status = DBG_CONTINUE;
1410 event_code = windows_process.current_event.dwDebugEventCode;
1411 ourstatus->set_spurious ();
1412 windows_process.have_saved_context = 0;
1414 switch (event_code)
1416 case CREATE_THREAD_DEBUG_EVENT:
1417 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1418 (unsigned) current_event->dwProcessId,
1419 (unsigned) current_event->dwThreadId,
1420 "CREATE_THREAD_DEBUG_EVENT");
1421 if (windows_process.saw_create != 1)
1423 inferior *inf = find_inferior_pid (this, current_event->dwProcessId);
1424 if (!windows_process.saw_create && inf->attach_flag)
1426 /* Kludge around a Windows bug where first event is a create
1427 thread event. Caused when attached process does not have
1428 a main thread. */
1429 thread_id = fake_create_process ();
1430 if (thread_id)
1431 windows_process.saw_create++;
1433 break;
1435 /* Record the existence of this thread. */
1436 thread_id = current_event->dwThreadId;
1437 add_thread
1438 (ptid_t (current_event->dwProcessId, current_event->dwThreadId, 0),
1439 current_event->u.CreateThread.hThread,
1440 current_event->u.CreateThread.lpThreadLocalBase,
1441 false /* main_thread_p */);
1443 break;
1445 case EXIT_THREAD_DEBUG_EVENT:
1446 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1447 (unsigned) current_event->dwProcessId,
1448 (unsigned) current_event->dwThreadId,
1449 "EXIT_THREAD_DEBUG_EVENT");
1450 delete_thread (ptid_t (current_event->dwProcessId,
1451 current_event->dwThreadId, 0),
1452 current_event->u.ExitThread.dwExitCode,
1453 false /* main_thread_p */);
1454 break;
1456 case CREATE_PROCESS_DEBUG_EVENT:
1457 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1458 (unsigned) current_event->dwProcessId,
1459 (unsigned) current_event->dwThreadId,
1460 "CREATE_PROCESS_DEBUG_EVENT");
1461 CloseHandle (current_event->u.CreateProcessInfo.hFile);
1462 if (++windows_process.saw_create != 1)
1463 break;
1465 windows_process.handle = current_event->u.CreateProcessInfo.hProcess;
1466 /* Add the main thread. */
1467 add_thread
1468 (ptid_t (current_event->dwProcessId,
1469 current_event->dwThreadId, 0),
1470 current_event->u.CreateProcessInfo.hThread,
1471 current_event->u.CreateProcessInfo.lpThreadLocalBase,
1472 true /* main_thread_p */);
1473 thread_id = current_event->dwThreadId;
1474 break;
1476 case EXIT_PROCESS_DEBUG_EVENT:
1477 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1478 (unsigned) current_event->dwProcessId,
1479 (unsigned) current_event->dwThreadId,
1480 "EXIT_PROCESS_DEBUG_EVENT");
1481 if (!windows_process.windows_initialization_done)
1483 target_terminal::ours ();
1484 target_mourn_inferior (inferior_ptid);
1485 error (_("During startup program exited with code 0x%x."),
1486 (unsigned int) current_event->u.ExitProcess.dwExitCode);
1488 else if (windows_process.saw_create == 1)
1490 delete_thread (ptid_t (current_event->dwProcessId,
1491 current_event->dwThreadId, 0),
1492 0, true /* main_thread_p */);
1493 DWORD exit_status = current_event->u.ExitProcess.dwExitCode;
1494 /* If the exit status looks like a fatal exception, but we
1495 don't recognize the exception's code, make the original
1496 exit status value available, to avoid losing
1497 information. */
1498 int exit_signal
1499 = WIFSIGNALED (exit_status) ? WTERMSIG (exit_status) : -1;
1500 if (exit_signal == -1)
1501 ourstatus->set_exited (exit_status);
1502 else
1503 ourstatus->set_signalled (gdb_signal_from_host (exit_signal));
1505 thread_id = current_event->dwThreadId;
1507 break;
1509 case LOAD_DLL_DEBUG_EVENT:
1510 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1511 (unsigned) current_event->dwProcessId,
1512 (unsigned) current_event->dwThreadId,
1513 "LOAD_DLL_DEBUG_EVENT");
1514 CloseHandle (current_event->u.LoadDll.hFile);
1515 if (windows_process.saw_create != 1
1516 || ! windows_process.windows_initialization_done)
1517 break;
1520 windows_process.dll_loaded_event ();
1522 catch (const gdb_exception &ex)
1524 exception_print (gdb_stderr, ex);
1526 ourstatus->set_loaded ();
1527 thread_id = current_event->dwThreadId;
1528 break;
1530 case UNLOAD_DLL_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 "UNLOAD_DLL_DEBUG_EVENT");
1535 if (windows_process.saw_create != 1
1536 || ! windows_process.windows_initialization_done)
1537 break;
1540 windows_process.handle_unload_dll ();
1542 catch (const gdb_exception &ex)
1544 exception_print (gdb_stderr, ex);
1546 ourstatus->set_loaded ();
1547 thread_id = current_event->dwThreadId;
1548 break;
1550 case EXCEPTION_DEBUG_EVENT:
1551 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1552 (unsigned) current_event->dwProcessId,
1553 (unsigned) current_event->dwThreadId,
1554 "EXCEPTION_DEBUG_EVENT");
1555 if (windows_process.saw_create != 1)
1556 break;
1557 switch (windows_process.handle_exception (ourstatus, debug_exceptions))
1559 case HANDLE_EXCEPTION_UNHANDLED:
1560 default:
1561 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1562 break;
1563 case HANDLE_EXCEPTION_HANDLED:
1564 thread_id = current_event->dwThreadId;
1565 break;
1566 case HANDLE_EXCEPTION_IGNORED:
1567 continue_status = DBG_CONTINUE;
1568 break;
1570 break;
1572 case OUTPUT_DEBUG_STRING_EVENT: /* Message from the kernel. */
1573 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1574 (unsigned) current_event->dwProcessId,
1575 (unsigned) current_event->dwThreadId,
1576 "OUTPUT_DEBUG_STRING_EVENT");
1577 if (windows_process.saw_create != 1)
1578 break;
1579 thread_id = windows_process.handle_output_debug_string (ourstatus);
1580 break;
1582 default:
1583 if (windows_process.saw_create != 1)
1584 break;
1585 gdb_printf ("gdb: kernel event for pid=%u tid=0x%x\n",
1586 (unsigned) current_event->dwProcessId,
1587 (unsigned) current_event->dwThreadId);
1588 gdb_printf (" unknown event code %u\n",
1589 (unsigned) current_event->dwDebugEventCode);
1590 break;
1593 if (!thread_id || windows_process.saw_create != 1)
1595 CHECK (windows_continue (continue_status,
1596 windows_process.desired_stop_thread_id, 0));
1598 else if (windows_process.desired_stop_thread_id != -1
1599 && windows_process.desired_stop_thread_id != thread_id)
1601 /* Pending stop. See the comment by the definition of
1602 "pending_stops" for details on why this is needed. */
1603 DEBUG_EVENTS ("get_windows_debug_event - "
1604 "unexpected stop in 0x%x (expecting 0x%x)",
1605 thread_id, windows_process.desired_stop_thread_id);
1607 if (current_event->dwDebugEventCode == EXCEPTION_DEBUG_EVENT
1608 && ((current_event->u.Exception.ExceptionRecord.ExceptionCode
1609 == EXCEPTION_BREAKPOINT)
1610 || (current_event->u.Exception.ExceptionRecord.ExceptionCode
1611 == STATUS_WX86_BREAKPOINT))
1612 && windows_process.windows_initialization_done)
1614 ptid_t ptid = ptid_t (current_event->dwProcessId, thread_id, 0);
1615 windows_thread_info *th
1616 = windows_process.thread_rec (ptid, INVALIDATE_CONTEXT);
1617 th->stopped_at_software_breakpoint = true;
1618 th->pc_adjusted = false;
1620 windows_process.pending_stops.push_back
1621 ({thread_id, *ourstatus, windows_process.current_event});
1622 thread_id = 0;
1623 CHECK (windows_continue (continue_status,
1624 windows_process.desired_stop_thread_id, 0));
1627 out:
1628 return thread_id;
1631 /* Wait for interesting events to occur in the target process. */
1632 ptid_t
1633 windows_nat_target::wait (ptid_t ptid, struct target_waitstatus *ourstatus,
1634 target_wait_flags options)
1636 int pid = -1;
1638 /* We loop when we get a non-standard exception rather than return
1639 with a SPURIOUS because resume can try and step or modify things,
1640 which needs a current_thread->h. But some of these exceptions mark
1641 the birth or death of threads, which mean that the current thread
1642 isn't necessarily what you think it is. */
1644 while (1)
1646 int retval;
1648 /* If the user presses Ctrl-c while the debugger is waiting
1649 for an event, he expects the debugger to interrupt his program
1650 and to get the prompt back. There are two possible situations:
1652 - The debugger and the program do not share the console, in
1653 which case the Ctrl-c event only reached the debugger.
1654 In that case, the ctrl_c handler will take care of interrupting
1655 the inferior. Note that this case is working starting with
1656 Windows XP. For Windows 2000, Ctrl-C should be pressed in the
1657 inferior console.
1659 - The debugger and the program share the same console, in which
1660 case both debugger and inferior will receive the Ctrl-c event.
1661 In that case the ctrl_c handler will ignore the event, as the
1662 Ctrl-c event generated inside the inferior will trigger the
1663 expected debug event.
1665 FIXME: brobecker/2008-05-20: If the inferior receives the
1666 signal first and the delay until GDB receives that signal
1667 is sufficiently long, GDB can sometimes receive the SIGINT
1668 after we have unblocked the CTRL+C handler. This would
1669 lead to the debugger stopping prematurely while handling
1670 the new-thread event that comes with the handling of the SIGINT
1671 inside the inferior, and then stop again immediately when
1672 the user tries to resume the execution in the inferior.
1673 This is a classic race that we should try to fix one day. */
1674 SetConsoleCtrlHandler (&ctrl_c_handler, TRUE);
1675 retval = get_windows_debug_event (pid, ourstatus);
1676 SetConsoleCtrlHandler (&ctrl_c_handler, FALSE);
1678 if (retval)
1680 ptid_t result = ptid_t (windows_process.current_event.dwProcessId,
1681 retval, 0);
1683 if (ourstatus->kind () != TARGET_WAITKIND_EXITED
1684 && ourstatus->kind () != TARGET_WAITKIND_SIGNALLED)
1686 windows_thread_info *th
1687 = windows_process.thread_rec (result, INVALIDATE_CONTEXT);
1689 if (th != nullptr)
1691 th->stopped_at_software_breakpoint = false;
1692 if (windows_process.current_event.dwDebugEventCode
1693 == EXCEPTION_DEBUG_EVENT
1694 && ((windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
1695 == EXCEPTION_BREAKPOINT)
1696 || (windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
1697 == STATUS_WX86_BREAKPOINT))
1698 && windows_process.windows_initialization_done)
1700 th->stopped_at_software_breakpoint = true;
1701 th->pc_adjusted = false;
1706 return result;
1708 else
1710 int detach = 0;
1712 if (deprecated_ui_loop_hook != NULL)
1713 detach = deprecated_ui_loop_hook (0);
1715 if (detach)
1716 kill ();
1721 void
1722 windows_nat_target::do_initial_windows_stuff (DWORD pid, bool attaching)
1724 int i;
1725 struct inferior *inf;
1727 windows_process.last_sig = GDB_SIGNAL_0;
1728 windows_process.open_process_used = 0;
1729 for (i = 0;
1730 i < sizeof (windows_process.dr) / sizeof (windows_process.dr[0]);
1731 i++)
1732 windows_process.dr[i] = 0;
1733 #ifdef __CYGWIN__
1734 cygwin_load_start = cygwin_load_end = 0;
1735 #endif
1736 windows_process.current_event.dwProcessId = pid;
1737 memset (&windows_process.current_event, 0,
1738 sizeof (windows_process.current_event));
1739 inf = current_inferior ();
1740 if (!inf->target_is_pushed (this))
1741 inf->push_target (this);
1742 disable_breakpoints_in_shlibs ();
1743 windows_clear_solib ();
1744 clear_proceed_status (0);
1745 init_wait_for_inferior ();
1747 #ifdef __x86_64__
1748 windows_process.ignore_first_breakpoint
1749 = !attaching && windows_process.wow64_process;
1751 if (!windows_process.wow64_process)
1753 windows_process.mappings = amd64_mappings;
1754 windows_process.segment_register_p = amd64_windows_segment_register_p;
1756 else
1757 #endif
1759 windows_process.mappings = i386_mappings;
1760 windows_process.segment_register_p = i386_windows_segment_register_p;
1763 inferior_appeared (inf, pid);
1764 inf->attach_flag = attaching;
1766 target_terminal::init ();
1767 target_terminal::inferior ();
1769 windows_process.windows_initialization_done = 0;
1771 ptid_t last_ptid;
1773 while (1)
1775 struct target_waitstatus status;
1777 last_ptid = this->wait (minus_one_ptid, &status, 0);
1779 /* Note windows_wait returns TARGET_WAITKIND_SPURIOUS for thread
1780 events. */
1781 if (status.kind () != TARGET_WAITKIND_LOADED
1782 && status.kind () != TARGET_WAITKIND_SPURIOUS)
1783 break;
1785 this->resume (minus_one_ptid, 0, GDB_SIGNAL_0);
1788 switch_to_thread (find_thread_ptid (this, last_ptid));
1790 /* Now that the inferior has been started and all DLLs have been mapped,
1791 we can iterate over all DLLs and load them in.
1793 We avoid doing it any earlier because, on certain versions of Windows,
1794 LOAD_DLL_DEBUG_EVENTs are sometimes not complete. In particular,
1795 we have seen on Windows 8.1 that the ntdll.dll load event does not
1796 include the DLL name, preventing us from creating an associated SO.
1797 A possible explanation is that ntdll.dll might be mapped before
1798 the SO info gets created by the Windows system -- ntdll.dll is
1799 the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs
1800 do not seem to suffer from that problem.
1802 Rather than try to work around this sort of issue, it is much
1803 simpler to just ignore DLL load/unload events during the startup
1804 phase, and then process them all in one batch now. */
1805 windows_process.add_all_dlls ();
1807 windows_process.windows_initialization_done = 1;
1808 return;
1811 /* Try to set or remove a user privilege to the current process. Return -1
1812 if that fails, the previous setting of that privilege otherwise.
1814 This code is copied from the Cygwin source code and rearranged to allow
1815 dynamically loading of the needed symbols from advapi32 which is only
1816 available on NT/2K/XP. */
1817 static int
1818 set_process_privilege (const char *privilege, BOOL enable)
1820 HANDLE token_hdl = NULL;
1821 LUID restore_priv;
1822 TOKEN_PRIVILEGES new_priv, orig_priv;
1823 int ret = -1;
1824 DWORD size;
1826 if (!OpenProcessToken (GetCurrentProcess (),
1827 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
1828 &token_hdl))
1829 goto out;
1831 if (!LookupPrivilegeValueA (NULL, privilege, &restore_priv))
1832 goto out;
1834 new_priv.PrivilegeCount = 1;
1835 new_priv.Privileges[0].Luid = restore_priv;
1836 new_priv.Privileges[0].Attributes = enable ? SE_PRIVILEGE_ENABLED : 0;
1838 if (!AdjustTokenPrivileges (token_hdl, FALSE, &new_priv,
1839 sizeof orig_priv, &orig_priv, &size))
1840 goto out;
1841 #if 0
1842 /* Disabled, otherwise every `attach' in an unprivileged user session
1843 would raise the "Failed to get SE_DEBUG_NAME privilege" warning in
1844 windows_attach(). */
1845 /* AdjustTokenPrivileges returns TRUE even if the privilege could not
1846 be enabled. GetLastError () returns an correct error code, though. */
1847 if (enable && GetLastError () == ERROR_NOT_ALL_ASSIGNED)
1848 goto out;
1849 #endif
1851 ret = orig_priv.Privileges[0].Attributes == SE_PRIVILEGE_ENABLED ? 1 : 0;
1853 out:
1854 if (token_hdl)
1855 CloseHandle (token_hdl);
1857 return ret;
1860 /* Attach to process PID, then initialize for debugging it. */
1862 void
1863 windows_nat_target::attach (const char *args, int from_tty)
1865 BOOL ok;
1866 DWORD pid;
1868 pid = parse_pid_to_attach (args);
1870 if (set_process_privilege (SE_DEBUG_NAME, TRUE) < 0)
1871 warning ("Failed to get SE_DEBUG_NAME privilege\n"
1872 "This can cause attach to fail on Windows NT/2K/XP");
1874 windows_init_thread_list ();
1875 ok = DebugActiveProcess (pid);
1876 windows_process.saw_create = 0;
1878 #ifdef __CYGWIN__
1879 if (!ok)
1881 /* Try fall back to Cygwin pid. */
1882 pid = cygwin_internal (CW_CYGWIN_PID_TO_WINPID, pid);
1884 if (pid > 0)
1885 ok = DebugActiveProcess (pid);
1887 #endif
1889 if (!ok)
1890 error (_("Can't attach to process %u (error %u)"),
1891 (unsigned) pid, (unsigned) GetLastError ());
1893 DebugSetProcessKillOnExit (FALSE);
1895 target_announce_attach (from_tty, pid);
1897 #ifdef __x86_64__
1898 HANDLE h = OpenProcess (PROCESS_QUERY_INFORMATION, FALSE, pid);
1899 if (h != NULL)
1901 BOOL wow64;
1902 if (IsWow64Process (h, &wow64))
1903 windows_process.wow64_process = wow64;
1904 CloseHandle (h);
1906 #endif
1908 do_initial_windows_stuff (pid, 1);
1909 target_terminal::ours ();
1912 void
1913 windows_nat_target::detach (inferior *inf, int from_tty)
1915 ptid_t ptid = minus_one_ptid;
1916 resume (ptid, 0, GDB_SIGNAL_0);
1918 if (!DebugActiveProcessStop (windows_process.current_event.dwProcessId))
1919 error (_("Can't detach process %u (error %u)"),
1920 (unsigned) windows_process.current_event.dwProcessId,
1921 (unsigned) GetLastError ());
1922 DebugSetProcessKillOnExit (FALSE);
1924 target_announce_detach (from_tty);
1926 x86_cleanup_dregs ();
1927 switch_to_no_thread ();
1928 detach_inferior (inf);
1930 maybe_unpush_target ();
1933 /* The pid_to_exec_file target_ops method for this platform. */
1935 const char *
1936 windows_nat_target::pid_to_exec_file (int pid)
1938 return windows_process.pid_to_exec_file (pid);
1941 /* Print status information about what we're accessing. */
1943 void
1944 windows_nat_target::files_info ()
1946 struct inferior *inf = current_inferior ();
1948 gdb_printf ("\tUsing the running image of %s %s.\n",
1949 inf->attach_flag ? "attached" : "child",
1950 target_pid_to_str (inferior_ptid).c_str ());
1953 /* Modify CreateProcess parameters for use of a new separate console.
1954 Parameters are:
1955 *FLAGS: DWORD parameter for general process creation flags.
1956 *SI: STARTUPINFO structure, for which the console window size and
1957 console buffer size is filled in if GDB is running in a console.
1958 to create the new console.
1959 The size of the used font is not available on all versions of
1960 Windows OS. Furthermore, the current font might not be the default
1961 font, but this is still better than before.
1962 If the windows and buffer sizes are computed,
1963 SI->DWFLAGS is changed so that this information is used
1964 by CreateProcess function. */
1966 static void
1967 windows_set_console_info (STARTUPINFO *si, DWORD *flags)
1969 HANDLE hconsole = CreateFile ("CONOUT$", GENERIC_READ | GENERIC_WRITE,
1970 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
1972 if (hconsole != INVALID_HANDLE_VALUE)
1974 CONSOLE_SCREEN_BUFFER_INFO sbinfo;
1975 COORD font_size;
1976 CONSOLE_FONT_INFO cfi;
1978 GetCurrentConsoleFont (hconsole, FALSE, &cfi);
1979 font_size = GetConsoleFontSize (hconsole, cfi.nFont);
1980 GetConsoleScreenBufferInfo(hconsole, &sbinfo);
1981 si->dwXSize = sbinfo.srWindow.Right - sbinfo.srWindow.Left + 1;
1982 si->dwYSize = sbinfo.srWindow.Bottom - sbinfo.srWindow.Top + 1;
1983 if (font_size.X)
1984 si->dwXSize *= font_size.X;
1985 else
1986 si->dwXSize *= 8;
1987 if (font_size.Y)
1988 si->dwYSize *= font_size.Y;
1989 else
1990 si->dwYSize *= 12;
1991 si->dwXCountChars = sbinfo.dwSize.X;
1992 si->dwYCountChars = sbinfo.dwSize.Y;
1993 si->dwFlags |= STARTF_USESIZE | STARTF_USECOUNTCHARS;
1995 *flags |= CREATE_NEW_CONSOLE;
1998 #ifndef __CYGWIN__
1999 /* Function called by qsort to sort environment strings. */
2001 static int
2002 envvar_cmp (const void *a, const void *b)
2004 const char **p = (const char **) a;
2005 const char **q = (const char **) b;
2006 return strcasecmp (*p, *q);
2008 #endif
2010 #ifdef __CYGWIN__
2011 static void
2012 clear_win32_environment (char **env)
2014 int i;
2015 size_t len;
2016 wchar_t *copy = NULL, *equalpos;
2018 for (i = 0; env[i] && *env[i]; i++)
2020 len = mbstowcs (NULL, env[i], 0) + 1;
2021 copy = (wchar_t *) xrealloc (copy, len * sizeof (wchar_t));
2022 mbstowcs (copy, env[i], len);
2023 equalpos = wcschr (copy, L'=');
2024 if (equalpos)
2025 *equalpos = L'\0';
2026 SetEnvironmentVariableW (copy, NULL);
2028 xfree (copy);
2030 #endif
2032 #ifndef __CYGWIN__
2034 /* Redirection of inferior I/O streams for native MS-Windows programs.
2035 Unlike on Unix, where this is handled by invoking the inferior via
2036 the shell, on MS-Windows we need to emulate the cmd.exe shell.
2038 The official documentation of the cmd.exe redirection features is here:
2040 http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx
2042 (That page talks about Windows XP, but there's no newer
2043 documentation, so we assume later versions of cmd.exe didn't change
2044 anything.)
2046 Caveat: the documentation on that page seems to include a few lies.
2047 For example, it describes strange constructs 1<&2 and 2<&1, which
2048 seem to work only when 1>&2 resp. 2>&1 would make sense, and so I
2049 think the cmd.exe parser of the redirection symbols simply doesn't
2050 care about the < vs > distinction in these cases. Therefore, the
2051 supported features are explicitly documented below.
2053 The emulation below aims at supporting all the valid use cases
2054 supported by cmd.exe, which include:
2056 < FILE redirect standard input from FILE
2057 0< FILE redirect standard input from FILE
2058 <&N redirect standard input from file descriptor N
2059 0<&N redirect standard input from file descriptor N
2060 > FILE redirect standard output to FILE
2061 >> FILE append standard output to FILE
2062 1>> FILE append standard output to FILE
2063 >&N redirect standard output to file descriptor N
2064 1>&N redirect standard output to file descriptor N
2065 >>&N append standard output to file descriptor N
2066 1>>&N append standard output to file descriptor N
2067 2> FILE redirect standard error to FILE
2068 2>> FILE append standard error to FILE
2069 2>&N redirect standard error to file descriptor N
2070 2>>&N append standard error to file descriptor N
2072 Note that using N > 2 in the above construct is supported, but
2073 requires that the corresponding file descriptor be open by some
2074 means elsewhere or outside GDB. Also note that using ">&0" or
2075 "<&2" will generally fail, because the file descriptor redirected
2076 from is normally open in an incompatible mode (e.g., FD 0 is open
2077 for reading only). IOW, use of such tricks is not recommended;
2078 you are on your own.
2080 We do NOT support redirection of file descriptors above 2, as in
2081 "3>SOME-FILE", because MinGW compiled programs don't (supporting
2082 that needs special handling in the startup code that MinGW
2083 doesn't have). Pipes are also not supported.
2085 As for invalid use cases, where the redirection contains some
2086 error, the emulation below will detect that and produce some
2087 error and/or failure. But the behavior in those cases is not
2088 bug-for-bug compatible with what cmd.exe does in those cases.
2089 That's because what cmd.exe does then is not well defined, and
2090 seems to be a side effect of the cmd.exe parsing of the command
2091 line more than anything else. For example, try redirecting to an
2092 invalid file name, as in "> foo:bar".
2094 There are also minor syntactic deviations from what cmd.exe does
2095 in some corner cases. For example, it doesn't support the likes
2096 of "> &foo" to mean redirect to file named literally "&foo"; we
2097 do support that here, because that, too, sounds like some issue
2098 with the cmd.exe parser. Another nicety is that we support
2099 redirection targets that use file names with forward slashes,
2100 something cmd.exe doesn't -- this comes in handy since GDB
2101 file-name completion can be used when typing the command line for
2102 the inferior. */
2104 /* Support routines for redirecting standard handles of the inferior. */
2106 /* Parse a single redirection spec, open/duplicate the specified
2107 file/fd, and assign the appropriate value to one of the 3 standard
2108 file descriptors. */
2109 static int
2110 redir_open (const char *redir_string, int *inp, int *out, int *err)
2112 int *fd, ref_fd = -2;
2113 int mode;
2114 const char *fname = redir_string + 1;
2115 int rc = *redir_string;
2117 switch (rc)
2119 case '0':
2120 fname++;
2121 /* FALLTHROUGH */
2122 case '<':
2123 fd = inp;
2124 mode = O_RDONLY;
2125 break;
2126 case '1': case '2':
2127 fname++;
2128 /* FALLTHROUGH */
2129 case '>':
2130 fd = (rc == '2') ? err : out;
2131 mode = O_WRONLY | O_CREAT;
2132 if (*fname == '>')
2134 fname++;
2135 mode |= O_APPEND;
2137 else
2138 mode |= O_TRUNC;
2139 break;
2140 default:
2141 return -1;
2144 if (*fname == '&' && '0' <= fname[1] && fname[1] <= '9')
2146 /* A reference to a file descriptor. */
2147 char *fdtail;
2148 ref_fd = (int) strtol (fname + 1, &fdtail, 10);
2149 if (fdtail > fname + 1 && *fdtail == '\0')
2151 /* Don't allow redirection when open modes are incompatible. */
2152 if ((ref_fd == 0 && (fd == out || fd == err))
2153 || ((ref_fd == 1 || ref_fd == 2) && fd == inp))
2155 errno = EPERM;
2156 return -1;
2158 if (ref_fd == 0)
2159 ref_fd = *inp;
2160 else if (ref_fd == 1)
2161 ref_fd = *out;
2162 else if (ref_fd == 2)
2163 ref_fd = *err;
2165 else
2167 errno = EBADF;
2168 return -1;
2171 else
2172 fname++; /* skip the separator space */
2173 /* If the descriptor is already open, close it. This allows
2174 multiple specs of redirections for the same stream, which is
2175 somewhat nonsensical, but still valid and supported by cmd.exe.
2176 (But cmd.exe only opens a single file in this case, the one
2177 specified by the last redirection spec on the command line.) */
2178 if (*fd >= 0)
2179 _close (*fd);
2180 if (ref_fd == -2)
2182 *fd = _open (fname, mode, _S_IREAD | _S_IWRITE);
2183 if (*fd < 0)
2184 return -1;
2186 else if (ref_fd == -1)
2187 *fd = -1; /* reset to default destination */
2188 else
2190 *fd = _dup (ref_fd);
2191 if (*fd < 0)
2192 return -1;
2194 /* _open just sets a flag for O_APPEND, which won't be passed to the
2195 inferior, so we need to actually move the file pointer. */
2196 if ((mode & O_APPEND) != 0)
2197 _lseek (*fd, 0L, SEEK_END);
2198 return 0;
2201 /* Canonicalize a single redirection spec and set up the corresponding
2202 file descriptor as specified. */
2203 static int
2204 redir_set_redirection (const char *s, int *inp, int *out, int *err)
2206 char buf[__PMAX + 2 + 5]; /* extra space for quotes & redirection string */
2207 char *d = buf;
2208 const char *start = s;
2209 int quote = 0;
2211 *d++ = *s++; /* copy the 1st character, < or > or a digit */
2212 if ((*start == '>' || *start == '1' || *start == '2')
2213 && *s == '>')
2215 *d++ = *s++;
2216 if (*s == '>' && *start != '>')
2217 *d++ = *s++;
2219 else if (*start == '0' && *s == '<')
2220 *d++ = *s++;
2221 /* cmd.exe recognizes "&N" only immediately after the redirection symbol. */
2222 if (*s != '&')
2224 while (isspace (*s)) /* skip whitespace before file name */
2225 s++;
2226 *d++ = ' '; /* separate file name with a single space */
2229 /* Copy the file name. */
2230 while (*s)
2232 /* Remove quoting characters from the file name in buf[]. */
2233 if (*s == '"') /* could support '..' quoting here */
2235 if (!quote)
2236 quote = *s++;
2237 else if (*s == quote)
2239 quote = 0;
2240 s++;
2242 else
2243 *d++ = *s++;
2245 else if (*s == '\\')
2247 if (s[1] == '"') /* could support '..' here */
2248 s++;
2249 *d++ = *s++;
2251 else if (isspace (*s) && !quote)
2252 break;
2253 else
2254 *d++ = *s++;
2255 if (d - buf >= sizeof (buf) - 1)
2257 errno = ENAMETOOLONG;
2258 return 0;
2261 *d = '\0';
2263 /* Windows doesn't allow redirection characters in file names, so we
2264 can bail out early if they use them, or if there's no target file
2265 name after the redirection symbol. */
2266 if (d[-1] == '>' || d[-1] == '<')
2268 errno = ENOENT;
2269 return 0;
2271 if (redir_open (buf, inp, out, err) == 0)
2272 return s - start;
2273 return 0;
2276 /* Parse the command line for redirection specs and prepare the file
2277 descriptors for the 3 standard streams accordingly. */
2278 static bool
2279 redirect_inferior_handles (const char *cmd_orig, char *cmd,
2280 int *inp, int *out, int *err)
2282 const char *s = cmd_orig;
2283 char *d = cmd;
2284 int quote = 0;
2285 bool retval = false;
2287 while (isspace (*s))
2288 *d++ = *s++;
2290 while (*s)
2292 if (*s == '"') /* could also support '..' quoting here */
2294 if (!quote)
2295 quote = *s;
2296 else if (*s == quote)
2297 quote = 0;
2299 else if (*s == '\\')
2301 if (s[1] == '"') /* escaped quote char */
2302 s++;
2304 else if (!quote)
2306 /* Process a single redirection candidate. */
2307 if (*s == '<' || *s == '>'
2308 || ((*s == '1' || *s == '2') && s[1] == '>')
2309 || (*s == '0' && s[1] == '<'))
2311 int skip = redir_set_redirection (s, inp, out, err);
2313 if (skip <= 0)
2314 return false;
2315 retval = true;
2316 s += skip;
2319 if (*s)
2320 *d++ = *s++;
2322 *d = '\0';
2323 return retval;
2325 #endif /* !__CYGWIN__ */
2327 /* Start an inferior windows child process and sets inferior_ptid to its pid.
2328 EXEC_FILE is the file to run.
2329 ALLARGS is a string containing the arguments to the program.
2330 ENV is the environment vector to pass. Errors reported with error(). */
2332 void
2333 windows_nat_target::create_inferior (const char *exec_file,
2334 const std::string &origallargs,
2335 char **in_env, int from_tty)
2337 STARTUPINFO si;
2338 #ifdef __CYGWIN__
2339 wchar_t real_path[__PMAX];
2340 wchar_t shell[__PMAX]; /* Path to shell */
2341 wchar_t infcwd[__PMAX];
2342 const char *sh;
2343 wchar_t *toexec;
2344 wchar_t *cygallargs;
2345 wchar_t *args;
2346 char **old_env = NULL;
2347 PWCHAR w32_env;
2348 size_t len;
2349 int tty;
2350 int ostdin, ostdout, ostderr;
2351 #else /* !__CYGWIN__ */
2352 char shell[__PMAX]; /* Path to shell */
2353 const char *toexec;
2354 char *args, *allargs_copy;
2355 size_t args_len, allargs_len;
2356 int fd_inp = -1, fd_out = -1, fd_err = -1;
2357 HANDLE tty = INVALID_HANDLE_VALUE;
2358 bool redirected = false;
2359 char *w32env;
2360 char *temp;
2361 size_t envlen;
2362 int i;
2363 size_t envsize;
2364 char **env;
2365 #endif /* !__CYGWIN__ */
2366 const char *allargs = origallargs.c_str ();
2367 PROCESS_INFORMATION pi;
2368 BOOL ret;
2369 DWORD flags = 0;
2370 const std::string &inferior_tty = current_inferior ()->tty ();
2372 if (!exec_file)
2373 error (_("No executable specified, use `target exec'."));
2375 const char *inferior_cwd = current_inferior ()->cwd ().c_str ();
2376 std::string expanded_infcwd;
2377 if (*inferior_cwd == '\0')
2378 inferior_cwd = nullptr;
2379 else
2381 expanded_infcwd = gdb_tilde_expand (inferior_cwd);
2382 /* Mirror slashes on inferior's cwd. */
2383 std::replace (expanded_infcwd.begin (), expanded_infcwd.end (),
2384 '/', '\\');
2385 inferior_cwd = expanded_infcwd.c_str ();
2388 memset (&si, 0, sizeof (si));
2389 si.cb = sizeof (si);
2391 if (new_group)
2392 flags |= CREATE_NEW_PROCESS_GROUP;
2394 if (new_console)
2395 windows_set_console_info (&si, &flags);
2397 #ifdef __CYGWIN__
2398 if (!useshell)
2400 flags |= DEBUG_ONLY_THIS_PROCESS;
2401 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, exec_file, real_path,
2402 __PMAX * sizeof (wchar_t)) < 0)
2403 error (_("Error starting executable: %d"), errno);
2404 toexec = real_path;
2405 len = mbstowcs (NULL, allargs, 0) + 1;
2406 if (len == (size_t) -1)
2407 error (_("Error starting executable: %d"), errno);
2408 cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
2409 mbstowcs (cygallargs, allargs, len);
2411 else
2413 sh = get_shell ();
2414 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, sh, shell, __PMAX) < 0)
2415 error (_("Error starting executable via shell: %d"), errno);
2416 len = sizeof (L" -c 'exec '") + mbstowcs (NULL, exec_file, 0)
2417 + mbstowcs (NULL, allargs, 0) + 2;
2418 cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
2419 swprintf (cygallargs, len, L" -c 'exec %s %s'", exec_file, allargs);
2420 toexec = shell;
2421 flags |= DEBUG_PROCESS;
2424 if (inferior_cwd != NULL
2425 && cygwin_conv_path (CCP_POSIX_TO_WIN_W, inferior_cwd,
2426 infcwd, strlen (inferior_cwd)) < 0)
2427 error (_("Error converting inferior cwd: %d"), errno);
2429 args = (wchar_t *) alloca ((wcslen (toexec) + wcslen (cygallargs) + 2)
2430 * sizeof (wchar_t));
2431 wcscpy (args, toexec);
2432 wcscat (args, L" ");
2433 wcscat (args, cygallargs);
2435 #ifdef CW_CVT_ENV_TO_WINENV
2436 /* First try to create a direct Win32 copy of the POSIX environment. */
2437 w32_env = (PWCHAR) cygwin_internal (CW_CVT_ENV_TO_WINENV, in_env);
2438 if (w32_env != (PWCHAR) -1)
2439 flags |= CREATE_UNICODE_ENVIRONMENT;
2440 else
2441 /* If that fails, fall back to old method tweaking GDB's environment. */
2442 #endif /* CW_CVT_ENV_TO_WINENV */
2444 /* Reset all Win32 environment variables to avoid leftover on next run. */
2445 clear_win32_environment (environ);
2446 /* Prepare the environment vars for CreateProcess. */
2447 old_env = environ;
2448 environ = in_env;
2449 cygwin_internal (CW_SYNC_WINENV);
2450 w32_env = NULL;
2453 if (inferior_tty.empty ())
2454 tty = ostdin = ostdout = ostderr = -1;
2455 else
2457 tty = open (inferior_tty.c_str (), O_RDWR | O_NOCTTY);
2458 if (tty < 0)
2460 print_sys_errmsg (inferior_tty.c_str (), errno);
2461 ostdin = ostdout = ostderr = -1;
2463 else
2465 ostdin = dup (0);
2466 ostdout = dup (1);
2467 ostderr = dup (2);
2468 dup2 (tty, 0);
2469 dup2 (tty, 1);
2470 dup2 (tty, 2);
2474 windows_init_thread_list ();
2475 ret = create_process (nullptr, args, flags, w32_env,
2476 inferior_cwd != nullptr ? infcwd : nullptr,
2477 disable_randomization,
2478 &si, &pi);
2479 if (w32_env)
2480 /* Just free the Win32 environment, if it could be created. */
2481 free (w32_env);
2482 else
2484 /* Reset all environment variables to avoid leftover on next run. */
2485 clear_win32_environment (in_env);
2486 /* Restore normal GDB environment variables. */
2487 environ = old_env;
2488 cygwin_internal (CW_SYNC_WINENV);
2491 if (tty >= 0)
2493 ::close (tty);
2494 dup2 (ostdin, 0);
2495 dup2 (ostdout, 1);
2496 dup2 (ostderr, 2);
2497 ::close (ostdin);
2498 ::close (ostdout);
2499 ::close (ostderr);
2501 #else /* !__CYGWIN__ */
2502 allargs_len = strlen (allargs);
2503 allargs_copy = strcpy ((char *) alloca (allargs_len + 1), allargs);
2504 if (strpbrk (allargs_copy, "<>") != NULL)
2506 int e = errno;
2507 errno = 0;
2508 redirected =
2509 redirect_inferior_handles (allargs, allargs_copy,
2510 &fd_inp, &fd_out, &fd_err);
2511 if (errno)
2512 warning (_("Error in redirection: %s."), safe_strerror (errno));
2513 else
2514 errno = e;
2515 allargs_len = strlen (allargs_copy);
2517 /* If not all the standard streams are redirected by the command
2518 line, use INFERIOR_TTY for those which aren't. */
2519 if (!inferior_tty.empty ()
2520 && !(fd_inp >= 0 && fd_out >= 0 && fd_err >= 0))
2522 SECURITY_ATTRIBUTES sa;
2523 sa.nLength = sizeof(sa);
2524 sa.lpSecurityDescriptor = 0;
2525 sa.bInheritHandle = TRUE;
2526 tty = CreateFileA (inferior_tty.c_str (), GENERIC_READ | GENERIC_WRITE,
2527 0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
2528 if (tty == INVALID_HANDLE_VALUE)
2529 warning (_("Warning: Failed to open TTY %s, error %#x."),
2530 inferior_tty.c_str (), (unsigned) GetLastError ());
2532 if (redirected || tty != INVALID_HANDLE_VALUE)
2534 if (fd_inp >= 0)
2535 si.hStdInput = (HANDLE) _get_osfhandle (fd_inp);
2536 else if (tty != INVALID_HANDLE_VALUE)
2537 si.hStdInput = tty;
2538 else
2539 si.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
2540 if (fd_out >= 0)
2541 si.hStdOutput = (HANDLE) _get_osfhandle (fd_out);
2542 else if (tty != INVALID_HANDLE_VALUE)
2543 si.hStdOutput = tty;
2544 else
2545 si.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
2546 if (fd_err >= 0)
2547 si.hStdError = (HANDLE) _get_osfhandle (fd_err);
2548 else if (tty != INVALID_HANDLE_VALUE)
2549 si.hStdError = tty;
2550 else
2551 si.hStdError = GetStdHandle (STD_ERROR_HANDLE);
2552 si.dwFlags |= STARTF_USESTDHANDLES;
2555 toexec = exec_file;
2556 /* Build the command line, a space-separated list of tokens where
2557 the first token is the name of the module to be executed.
2558 To avoid ambiguities introduced by spaces in the module name,
2559 we quote it. */
2560 args_len = strlen (toexec) + 2 /* quotes */ + allargs_len + 2;
2561 args = (char *) alloca (args_len);
2562 xsnprintf (args, args_len, "\"%s\" %s", toexec, allargs_copy);
2564 flags |= DEBUG_ONLY_THIS_PROCESS;
2566 /* CreateProcess takes the environment list as a null terminated set of
2567 strings (i.e. two nulls terminate the list). */
2569 /* Get total size for env strings. */
2570 for (envlen = 0, i = 0; in_env[i] && *in_env[i]; i++)
2571 envlen += strlen (in_env[i]) + 1;
2573 envsize = sizeof (in_env[0]) * (i + 1);
2574 env = (char **) alloca (envsize);
2575 memcpy (env, in_env, envsize);
2576 /* Windows programs expect the environment block to be sorted. */
2577 qsort (env, i, sizeof (char *), envvar_cmp);
2579 w32env = (char *) alloca (envlen + 1);
2581 /* Copy env strings into new buffer. */
2582 for (temp = w32env, i = 0; env[i] && *env[i]; i++)
2584 strcpy (temp, env[i]);
2585 temp += strlen (temp) + 1;
2588 /* Final nil string to terminate new env. */
2589 *temp = 0;
2591 windows_init_thread_list ();
2592 ret = create_process (nullptr, /* image */
2593 args, /* command line */
2594 flags, /* start flags */
2595 w32env, /* environment */
2596 inferior_cwd, /* current directory */
2597 disable_randomization,
2598 &si,
2599 &pi);
2600 if (tty != INVALID_HANDLE_VALUE)
2601 CloseHandle (tty);
2602 if (fd_inp >= 0)
2603 _close (fd_inp);
2604 if (fd_out >= 0)
2605 _close (fd_out);
2606 if (fd_err >= 0)
2607 _close (fd_err);
2608 #endif /* !__CYGWIN__ */
2610 if (!ret)
2611 error (_("Error creating process %s, (error %u)."),
2612 exec_file, (unsigned) GetLastError ());
2614 #ifdef __x86_64__
2615 BOOL wow64;
2616 if (IsWow64Process (pi.hProcess, &wow64))
2617 windows_process.wow64_process = wow64;
2618 #endif
2620 CloseHandle (pi.hThread);
2621 CloseHandle (pi.hProcess);
2623 if (useshell && shell[0] != '\0')
2624 windows_process.saw_create = -1;
2625 else
2626 windows_process.saw_create = 0;
2628 do_initial_windows_stuff (pi.dwProcessId, 0);
2630 /* windows_continue (DBG_CONTINUE, -1, 0); */
2633 void
2634 windows_nat_target::mourn_inferior ()
2636 (void) windows_continue (DBG_CONTINUE, -1, 0);
2637 x86_cleanup_dregs();
2638 if (windows_process.open_process_used)
2640 CHECK (CloseHandle (windows_process.handle));
2641 windows_process.open_process_used = 0;
2643 windows_process.siginfo_er.ExceptionCode = 0;
2644 inf_child_target::mourn_inferior ();
2647 /* Send a SIGINT to the process group. This acts just like the user typed a
2648 ^C on the controlling terminal. */
2650 void
2651 windows_nat_target::interrupt ()
2653 DEBUG_EVENTS ("GenerateConsoleCtrlEvent (CTRLC_EVENT, 0)");
2654 CHECK (GenerateConsoleCtrlEvent (CTRL_C_EVENT,
2655 windows_process.current_event.dwProcessId));
2656 registers_changed (); /* refresh register state */
2659 /* Helper for windows_xfer_partial that handles memory transfers.
2660 Arguments are like target_xfer_partial. */
2662 static enum target_xfer_status
2663 windows_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
2664 ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
2666 SIZE_T done = 0;
2667 BOOL success;
2668 DWORD lasterror = 0;
2670 if (writebuf != NULL)
2672 DEBUG_MEM ("write target memory, %s bytes at %s",
2673 pulongest (len), core_addr_to_string (memaddr));
2674 success = WriteProcessMemory (windows_process.handle,
2675 (LPVOID) (uintptr_t) memaddr, writebuf,
2676 len, &done);
2677 if (!success)
2678 lasterror = GetLastError ();
2679 FlushInstructionCache (windows_process.handle,
2680 (LPCVOID) (uintptr_t) memaddr, len);
2682 else
2684 DEBUG_MEM ("read target memory, %s bytes at %s",
2685 pulongest (len), core_addr_to_string (memaddr));
2686 success = ReadProcessMemory (windows_process.handle,
2687 (LPCVOID) (uintptr_t) memaddr, readbuf,
2688 len, &done);
2689 if (!success)
2690 lasterror = GetLastError ();
2692 *xfered_len = (ULONGEST) done;
2693 if (!success && lasterror == ERROR_PARTIAL_COPY && done > 0)
2694 return TARGET_XFER_OK;
2695 else
2696 return success ? TARGET_XFER_OK : TARGET_XFER_E_IO;
2699 void
2700 windows_nat_target::kill ()
2702 CHECK (TerminateProcess (windows_process.handle, 0));
2704 for (;;)
2706 if (!windows_continue (DBG_CONTINUE, -1, 1))
2707 break;
2708 if (!wait_for_debug_event (&windows_process.current_event, INFINITE))
2709 break;
2710 if (windows_process.current_event.dwDebugEventCode
2711 == EXIT_PROCESS_DEBUG_EVENT)
2712 break;
2715 target_mourn_inferior (inferior_ptid); /* Or just windows_mourn_inferior? */
2718 void
2719 windows_nat_target::close ()
2721 DEBUG_EVENTS ("inferior_ptid=%d\n", inferior_ptid.pid ());
2724 /* Convert pid to printable format. */
2725 std::string
2726 windows_nat_target::pid_to_str (ptid_t ptid)
2728 if (ptid.lwp () != 0)
2729 return string_printf ("Thread %d.0x%lx", ptid.pid (), ptid.lwp ());
2731 return normal_pid_to_str (ptid);
2734 static enum target_xfer_status
2735 windows_xfer_shared_libraries (struct target_ops *ops,
2736 enum target_object object, const char *annex,
2737 gdb_byte *readbuf, const gdb_byte *writebuf,
2738 ULONGEST offset, ULONGEST len,
2739 ULONGEST *xfered_len)
2741 auto_obstack obstack;
2742 const char *buf;
2743 LONGEST len_avail;
2745 if (writebuf)
2746 return TARGET_XFER_E_IO;
2748 obstack_grow_str (&obstack, "<library-list>\n");
2749 for (windows_solib &so : windows_process.solibs)
2750 windows_xfer_shared_library (so.name.c_str (),
2751 (CORE_ADDR) (uintptr_t) so.load_addr,
2752 &so.text_offset,
2753 target_gdbarch (), &obstack);
2754 obstack_grow_str0 (&obstack, "</library-list>\n");
2756 buf = (const char *) obstack_finish (&obstack);
2757 len_avail = strlen (buf);
2758 if (offset >= len_avail)
2759 len= 0;
2760 else
2762 if (len > len_avail - offset)
2763 len = len_avail - offset;
2764 memcpy (readbuf, buf + offset, len);
2767 *xfered_len = (ULONGEST) len;
2768 return len != 0 ? TARGET_XFER_OK : TARGET_XFER_EOF;
2771 /* Helper for windows_nat_target::xfer_partial that handles signal info. */
2773 static enum target_xfer_status
2774 windows_xfer_siginfo (gdb_byte *readbuf, ULONGEST offset, ULONGEST len,
2775 ULONGEST *xfered_len)
2777 char *buf = (char *) &windows_process.siginfo_er;
2778 size_t bufsize = sizeof (windows_process.siginfo_er);
2780 #ifdef __x86_64__
2781 EXCEPTION_RECORD32 er32;
2782 if (windows_process.wow64_process)
2784 buf = (char *) &er32;
2785 bufsize = sizeof (er32);
2787 er32.ExceptionCode = windows_process.siginfo_er.ExceptionCode;
2788 er32.ExceptionFlags = windows_process.siginfo_er.ExceptionFlags;
2789 er32.ExceptionRecord
2790 = (uintptr_t) windows_process.siginfo_er.ExceptionRecord;
2791 er32.ExceptionAddress
2792 = (uintptr_t) windows_process.siginfo_er.ExceptionAddress;
2793 er32.NumberParameters = windows_process.siginfo_er.NumberParameters;
2794 int i;
2795 for (i = 0; i < EXCEPTION_MAXIMUM_PARAMETERS; i++)
2796 er32.ExceptionInformation[i]
2797 = windows_process.siginfo_er.ExceptionInformation[i];
2799 #endif
2801 if (windows_process.siginfo_er.ExceptionCode == 0)
2802 return TARGET_XFER_E_IO;
2804 if (readbuf == nullptr)
2805 return TARGET_XFER_E_IO;
2807 if (offset > bufsize)
2808 return TARGET_XFER_E_IO;
2810 if (offset + len > bufsize)
2811 len = bufsize - offset;
2813 memcpy (readbuf, buf + offset, len);
2814 *xfered_len = len;
2816 return TARGET_XFER_OK;
2819 enum target_xfer_status
2820 windows_nat_target::xfer_partial (enum target_object object,
2821 const char *annex, gdb_byte *readbuf,
2822 const gdb_byte *writebuf, ULONGEST offset,
2823 ULONGEST len, ULONGEST *xfered_len)
2825 switch (object)
2827 case TARGET_OBJECT_MEMORY:
2828 return windows_xfer_memory (readbuf, writebuf, offset, len, xfered_len);
2830 case TARGET_OBJECT_LIBRARIES:
2831 return windows_xfer_shared_libraries (this, object, annex, readbuf,
2832 writebuf, offset, len, xfered_len);
2834 case TARGET_OBJECT_SIGNAL_INFO:
2835 return windows_xfer_siginfo (readbuf, offset, len, xfered_len);
2837 default:
2838 if (beneath () == NULL)
2840 /* This can happen when requesting the transfer of unsupported
2841 objects before a program has been started (and therefore
2842 with the current_target having no target beneath). */
2843 return TARGET_XFER_E_IO;
2845 return beneath ()->xfer_partial (object, annex,
2846 readbuf, writebuf, offset, len,
2847 xfered_len);
2851 /* Provide thread local base, i.e. Thread Information Block address.
2852 Returns 1 if ptid is found and sets *ADDR to thread_local_base. */
2854 bool
2855 windows_nat_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
2857 windows_thread_info *th;
2859 th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
2860 if (th == NULL)
2861 return false;
2863 if (addr != NULL)
2864 *addr = th->thread_local_base;
2866 return true;
2869 ptid_t
2870 windows_nat_target::get_ada_task_ptid (long lwp, ULONGEST thread)
2872 return ptid_t (inferior_ptid.pid (), lwp, 0);
2875 /* Implementation of the to_thread_name method. */
2877 const char *
2878 windows_nat_target::thread_name (struct thread_info *thr)
2880 windows_thread_info *th
2881 = windows_process.thread_rec (thr->ptid,
2882 DONT_INVALIDATE_CONTEXT);
2883 return th->thread_name ();
2887 void _initialize_windows_nat ();
2888 void
2889 _initialize_windows_nat ()
2891 x86_dr_low.set_control = cygwin_set_dr7;
2892 x86_dr_low.set_addr = cygwin_set_dr;
2893 x86_dr_low.get_addr = cygwin_get_dr;
2894 x86_dr_low.get_status = cygwin_get_dr6;
2895 x86_dr_low.get_control = cygwin_get_dr7;
2897 /* x86_dr_low.debug_register_length field is set by
2898 calling x86_set_debug_register_length function
2899 in processor windows specific native file. */
2901 add_inf_child_target (&the_windows_nat_target);
2903 #ifdef __CYGWIN__
2904 cygwin_internal (CW_SET_DOS_FILE_WARNING, 0);
2905 #endif
2907 add_com ("signal-event", class_run, signal_event_command, _("\
2908 Signal a crashed process with event ID, to allow its debugging.\n\
2909 This command is needed in support of setting up GDB as JIT debugger on \
2910 MS-Windows. The command should be invoked from the GDB command line using \
2911 the '-ex' command-line option. The ID of the event that blocks the \
2912 crashed process will be supplied by the Windows JIT debugging mechanism."));
2914 #ifdef __CYGWIN__
2915 add_setshow_boolean_cmd ("shell", class_support, &useshell, _("\
2916 Set use of shell to start subprocess."), _("\
2917 Show use of shell to start subprocess."), NULL,
2918 NULL,
2919 NULL, /* FIXME: i18n: */
2920 &setlist, &showlist);
2922 add_setshow_boolean_cmd ("cygwin-exceptions", class_support,
2923 &cygwin_exceptions, _("\
2924 Break when an exception is detected in the Cygwin DLL itself."), _("\
2925 Show whether gdb breaks on exceptions in the Cygwin DLL itself."), NULL,
2926 NULL,
2927 NULL, /* FIXME: i18n: */
2928 &setlist, &showlist);
2929 #endif
2931 add_setshow_boolean_cmd ("new-console", class_support, &new_console, _("\
2932 Set creation of new console when creating child process."), _("\
2933 Show creation of new console when creating child process."), NULL,
2934 NULL,
2935 NULL, /* FIXME: i18n: */
2936 &setlist, &showlist);
2938 add_setshow_boolean_cmd ("new-group", class_support, &new_group, _("\
2939 Set creation of new group when creating child process."), _("\
2940 Show creation of new group when creating child process."), NULL,
2941 NULL,
2942 NULL, /* FIXME: i18n: */
2943 &setlist, &showlist);
2945 add_setshow_boolean_cmd ("debugexec", class_support, &debug_exec, _("\
2946 Set whether to display execution in child process."), _("\
2947 Show whether to display execution in child process."), NULL,
2948 NULL,
2949 NULL, /* FIXME: i18n: */
2950 &setlist, &showlist);
2952 add_setshow_boolean_cmd ("debugevents", class_support, &debug_events, _("\
2953 Set whether to display kernel events in child process."), _("\
2954 Show whether to display kernel events in child process."), NULL,
2955 NULL,
2956 NULL, /* FIXME: i18n: */
2957 &setlist, &showlist);
2959 add_setshow_boolean_cmd ("debugmemory", class_support, &debug_memory, _("\
2960 Set whether to display memory accesses in child process."), _("\
2961 Show whether to display memory accesses in child process."), NULL,
2962 NULL,
2963 NULL, /* FIXME: i18n: */
2964 &setlist, &showlist);
2966 add_setshow_boolean_cmd ("debugexceptions", class_support,
2967 &debug_exceptions, _("\
2968 Set whether to display kernel exceptions in child process."), _("\
2969 Show whether to display kernel exceptions in child process."), NULL,
2970 NULL,
2971 NULL, /* FIXME: i18n: */
2972 &setlist, &showlist);
2974 init_w32_command_list ();
2976 add_cmd ("selector", class_info, display_selectors,
2977 _("Display selectors infos."),
2978 &info_w32_cmdlist);
2980 if (!initialize_loadable ())
2982 /* This will probably fail on Windows 9x/Me. Let the user know
2983 that we're missing some functionality. */
2984 warning(_("\
2985 cannot automatically find executable file or library to read symbols.\n\
2986 Use \"file\" or \"dll\" command to load executable/libraries directly."));
2990 /* Hardware watchpoint support, adapted from go32-nat.c code. */
2992 /* Pass the address ADDR to the inferior in the I'th debug register.
2993 Here we just store the address in dr array, the registers will be
2994 actually set up when windows_continue is called. */
2995 static void
2996 cygwin_set_dr (int i, CORE_ADDR addr)
2998 if (i < 0 || i > 3)
2999 internal_error (__FILE__, __LINE__,
3000 _("Invalid register %d in cygwin_set_dr.\n"), i);
3001 windows_process.dr[i] = addr;
3003 for (auto &th : windows_process.thread_list)
3004 th->debug_registers_changed = true;
3007 /* Pass the value VAL to the inferior in the DR7 debug control
3008 register. Here we just store the address in D_REGS, the watchpoint
3009 will be actually set up in windows_wait. */
3010 static void
3011 cygwin_set_dr7 (unsigned long val)
3013 windows_process.dr[7] = (CORE_ADDR) val;
3015 for (auto &th : windows_process.thread_list)
3016 th->debug_registers_changed = true;
3019 /* Get the value of debug register I from the inferior. */
3021 static CORE_ADDR
3022 cygwin_get_dr (int i)
3024 return windows_process.dr[i];
3027 /* Get the value of the DR6 debug status register from the inferior.
3028 Here we just return the value stored in dr[6]
3029 by the last call to thread_rec for current_event.dwThreadId id. */
3030 static unsigned long
3031 cygwin_get_dr6 (void)
3033 return (unsigned long) windows_process.dr[6];
3036 /* Get the value of the DR7 debug status register from the inferior.
3037 Here we just return the value stored in dr[7] by the last call to
3038 thread_rec for current_event.dwThreadId id. */
3040 static unsigned long
3041 cygwin_get_dr7 (void)
3043 return (unsigned long) windows_process.dr[7];
3046 /* Determine if the thread referenced by "ptid" is alive
3047 by "polling" it. If WaitForSingleObject returns WAIT_OBJECT_0
3048 it means that the thread has died. Otherwise it is assumed to be alive. */
3050 bool
3051 windows_nat_target::thread_alive (ptid_t ptid)
3053 gdb_assert (ptid.lwp () != 0);
3055 windows_thread_info *th
3056 = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
3057 return WaitForSingleObject (th->h, 0) != WAIT_OBJECT_0;
3060 void _initialize_check_for_gdb_ini ();
3061 void
3062 _initialize_check_for_gdb_ini ()
3064 char *homedir;
3065 if (inhibit_gdbinit)
3066 return;
3068 homedir = getenv ("HOME");
3069 if (homedir)
3071 char *p;
3072 char *oldini = (char *) alloca (strlen (homedir) +
3073 sizeof ("gdb.ini") + 1);
3074 strcpy (oldini, homedir);
3075 p = strchr (oldini, '\0');
3076 if (p > oldini && !IS_DIR_SEPARATOR (p[-1]))
3077 *p++ = '/';
3078 strcpy (p, "gdb.ini");
3079 if (access (oldini, 0) == 0)
3081 int len = strlen (oldini);
3082 char *newini = (char *) alloca (len + 2);
3084 xsnprintf (newini, len + 2, "%.*s.gdbinit",
3085 (int) (len - (sizeof ("gdb.ini") - 1)), oldini);
3086 warning (_("obsolete '%s' found. Rename to '%s'."), oldini, newini);