Update release README with new version numbers
[binutils-gdb.git] / gdb / windows-nat.c
blob9705fa33cc2f52f094d9362224d932ab30d2f6d1
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 = (i386_gdbarch_tdep *) 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 ("Priviledge 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 int detached = 1;
1917 ptid_t ptid = minus_one_ptid;
1918 resume (ptid, 0, GDB_SIGNAL_0);
1920 if (!DebugActiveProcessStop (windows_process.current_event.dwProcessId))
1922 error (_("Can't detach process %u (error %u)"),
1923 (unsigned) windows_process.current_event.dwProcessId,
1924 (unsigned) GetLastError ());
1925 detached = 0;
1927 DebugSetProcessKillOnExit (FALSE);
1929 if (detached)
1930 target_announce_detach (from_tty);
1932 x86_cleanup_dregs ();
1933 switch_to_no_thread ();
1934 detach_inferior (inf);
1936 maybe_unpush_target ();
1939 /* The pid_to_exec_file target_ops method for this platform. */
1941 const char *
1942 windows_nat_target::pid_to_exec_file (int pid)
1944 return windows_process.pid_to_exec_file (pid);
1947 /* Print status information about what we're accessing. */
1949 void
1950 windows_nat_target::files_info ()
1952 struct inferior *inf = current_inferior ();
1954 gdb_printf ("\tUsing the running image of %s %s.\n",
1955 inf->attach_flag ? "attached" : "child",
1956 target_pid_to_str (inferior_ptid).c_str ());
1959 /* Modify CreateProcess parameters for use of a new separate console.
1960 Parameters are:
1961 *FLAGS: DWORD parameter for general process creation flags.
1962 *SI: STARTUPINFO structure, for which the console window size and
1963 console buffer size is filled in if GDB is running in a console.
1964 to create the new console.
1965 The size of the used font is not available on all versions of
1966 Windows OS. Furthermore, the current font might not be the default
1967 font, but this is still better than before.
1968 If the windows and buffer sizes are computed,
1969 SI->DWFLAGS is changed so that this information is used
1970 by CreateProcess function. */
1972 static void
1973 windows_set_console_info (STARTUPINFO *si, DWORD *flags)
1975 HANDLE hconsole = CreateFile ("CONOUT$", GENERIC_READ | GENERIC_WRITE,
1976 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
1978 if (hconsole != INVALID_HANDLE_VALUE)
1980 CONSOLE_SCREEN_BUFFER_INFO sbinfo;
1981 COORD font_size;
1982 CONSOLE_FONT_INFO cfi;
1984 GetCurrentConsoleFont (hconsole, FALSE, &cfi);
1985 font_size = GetConsoleFontSize (hconsole, cfi.nFont);
1986 GetConsoleScreenBufferInfo(hconsole, &sbinfo);
1987 si->dwXSize = sbinfo.srWindow.Right - sbinfo.srWindow.Left + 1;
1988 si->dwYSize = sbinfo.srWindow.Bottom - sbinfo.srWindow.Top + 1;
1989 if (font_size.X)
1990 si->dwXSize *= font_size.X;
1991 else
1992 si->dwXSize *= 8;
1993 if (font_size.Y)
1994 si->dwYSize *= font_size.Y;
1995 else
1996 si->dwYSize *= 12;
1997 si->dwXCountChars = sbinfo.dwSize.X;
1998 si->dwYCountChars = sbinfo.dwSize.Y;
1999 si->dwFlags |= STARTF_USESIZE | STARTF_USECOUNTCHARS;
2001 *flags |= CREATE_NEW_CONSOLE;
2004 #ifndef __CYGWIN__
2005 /* Function called by qsort to sort environment strings. */
2007 static int
2008 envvar_cmp (const void *a, const void *b)
2010 const char **p = (const char **) a;
2011 const char **q = (const char **) b;
2012 return strcasecmp (*p, *q);
2014 #endif
2016 #ifdef __CYGWIN__
2017 static void
2018 clear_win32_environment (char **env)
2020 int i;
2021 size_t len;
2022 wchar_t *copy = NULL, *equalpos;
2024 for (i = 0; env[i] && *env[i]; i++)
2026 len = mbstowcs (NULL, env[i], 0) + 1;
2027 copy = (wchar_t *) xrealloc (copy, len * sizeof (wchar_t));
2028 mbstowcs (copy, env[i], len);
2029 equalpos = wcschr (copy, L'=');
2030 if (equalpos)
2031 *equalpos = L'\0';
2032 SetEnvironmentVariableW (copy, NULL);
2034 xfree (copy);
2036 #endif
2038 #ifndef __CYGWIN__
2040 /* Redirection of inferior I/O streams for native MS-Windows programs.
2041 Unlike on Unix, where this is handled by invoking the inferior via
2042 the shell, on MS-Windows we need to emulate the cmd.exe shell.
2044 The official documentation of the cmd.exe redirection features is here:
2046 http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx
2048 (That page talks about Windows XP, but there's no newer
2049 documentation, so we assume later versions of cmd.exe didn't change
2050 anything.)
2052 Caveat: the documentation on that page seems to include a few lies.
2053 For example, it describes strange constructs 1<&2 and 2<&1, which
2054 seem to work only when 1>&2 resp. 2>&1 would make sense, and so I
2055 think the cmd.exe parser of the redirection symbols simply doesn't
2056 care about the < vs > distinction in these cases. Therefore, the
2057 supported features are explicitly documented below.
2059 The emulation below aims at supporting all the valid use cases
2060 supported by cmd.exe, which include:
2062 < FILE redirect standard input from FILE
2063 0< FILE redirect standard input from FILE
2064 <&N redirect standard input from file descriptor N
2065 0<&N redirect standard input from file descriptor N
2066 > FILE redirect standard output to FILE
2067 >> FILE append standard output to FILE
2068 1>> FILE append standard output to FILE
2069 >&N redirect standard output to file descriptor N
2070 1>&N redirect standard output to file descriptor N
2071 >>&N append standard output to file descriptor N
2072 1>>&N append standard output to file descriptor N
2073 2> FILE redirect standard error to FILE
2074 2>> FILE append standard error to FILE
2075 2>&N redirect standard error to file descriptor N
2076 2>>&N append standard error to file descriptor N
2078 Note that using N > 2 in the above construct is supported, but
2079 requires that the corresponding file descriptor be open by some
2080 means elsewhere or outside GDB. Also note that using ">&0" or
2081 "<&2" will generally fail, because the file descriptor redirected
2082 from is normally open in an incompatible mode (e.g., FD 0 is open
2083 for reading only). IOW, use of such tricks is not recommended;
2084 you are on your own.
2086 We do NOT support redirection of file descriptors above 2, as in
2087 "3>SOME-FILE", because MinGW compiled programs don't (supporting
2088 that needs special handling in the startup code that MinGW
2089 doesn't have). Pipes are also not supported.
2091 As for invalid use cases, where the redirection contains some
2092 error, the emulation below will detect that and produce some
2093 error and/or failure. But the behavior in those cases is not
2094 bug-for-bug compatible with what cmd.exe does in those cases.
2095 That's because what cmd.exe does then is not well defined, and
2096 seems to be a side effect of the cmd.exe parsing of the command
2097 line more than anything else. For example, try redirecting to an
2098 invalid file name, as in "> foo:bar".
2100 There are also minor syntactic deviations from what cmd.exe does
2101 in some corner cases. For example, it doesn't support the likes
2102 of "> &foo" to mean redirect to file named literally "&foo"; we
2103 do support that here, because that, too, sounds like some issue
2104 with the cmd.exe parser. Another nicety is that we support
2105 redirection targets that use file names with forward slashes,
2106 something cmd.exe doesn't -- this comes in handy since GDB
2107 file-name completion can be used when typing the command line for
2108 the inferior. */
2110 /* Support routines for redirecting standard handles of the inferior. */
2112 /* Parse a single redirection spec, open/duplicate the specified
2113 file/fd, and assign the appropriate value to one of the 3 standard
2114 file descriptors. */
2115 static int
2116 redir_open (const char *redir_string, int *inp, int *out, int *err)
2118 int *fd, ref_fd = -2;
2119 int mode;
2120 const char *fname = redir_string + 1;
2121 int rc = *redir_string;
2123 switch (rc)
2125 case '0':
2126 fname++;
2127 /* FALLTHROUGH */
2128 case '<':
2129 fd = inp;
2130 mode = O_RDONLY;
2131 break;
2132 case '1': case '2':
2133 fname++;
2134 /* FALLTHROUGH */
2135 case '>':
2136 fd = (rc == '2') ? err : out;
2137 mode = O_WRONLY | O_CREAT;
2138 if (*fname == '>')
2140 fname++;
2141 mode |= O_APPEND;
2143 else
2144 mode |= O_TRUNC;
2145 break;
2146 default:
2147 return -1;
2150 if (*fname == '&' && '0' <= fname[1] && fname[1] <= '9')
2152 /* A reference to a file descriptor. */
2153 char *fdtail;
2154 ref_fd = (int) strtol (fname + 1, &fdtail, 10);
2155 if (fdtail > fname + 1 && *fdtail == '\0')
2157 /* Don't allow redirection when open modes are incompatible. */
2158 if ((ref_fd == 0 && (fd == out || fd == err))
2159 || ((ref_fd == 1 || ref_fd == 2) && fd == inp))
2161 errno = EPERM;
2162 return -1;
2164 if (ref_fd == 0)
2165 ref_fd = *inp;
2166 else if (ref_fd == 1)
2167 ref_fd = *out;
2168 else if (ref_fd == 2)
2169 ref_fd = *err;
2171 else
2173 errno = EBADF;
2174 return -1;
2177 else
2178 fname++; /* skip the separator space */
2179 /* If the descriptor is already open, close it. This allows
2180 multiple specs of redirections for the same stream, which is
2181 somewhat nonsensical, but still valid and supported by cmd.exe.
2182 (But cmd.exe only opens a single file in this case, the one
2183 specified by the last redirection spec on the command line.) */
2184 if (*fd >= 0)
2185 _close (*fd);
2186 if (ref_fd == -2)
2188 *fd = _open (fname, mode, _S_IREAD | _S_IWRITE);
2189 if (*fd < 0)
2190 return -1;
2192 else if (ref_fd == -1)
2193 *fd = -1; /* reset to default destination */
2194 else
2196 *fd = _dup (ref_fd);
2197 if (*fd < 0)
2198 return -1;
2200 /* _open just sets a flag for O_APPEND, which won't be passed to the
2201 inferior, so we need to actually move the file pointer. */
2202 if ((mode & O_APPEND) != 0)
2203 _lseek (*fd, 0L, SEEK_END);
2204 return 0;
2207 /* Canonicalize a single redirection spec and set up the corresponding
2208 file descriptor as specified. */
2209 static int
2210 redir_set_redirection (const char *s, int *inp, int *out, int *err)
2212 char buf[__PMAX + 2 + 5]; /* extra space for quotes & redirection string */
2213 char *d = buf;
2214 const char *start = s;
2215 int quote = 0;
2217 *d++ = *s++; /* copy the 1st character, < or > or a digit */
2218 if ((*start == '>' || *start == '1' || *start == '2')
2219 && *s == '>')
2221 *d++ = *s++;
2222 if (*s == '>' && *start != '>')
2223 *d++ = *s++;
2225 else if (*start == '0' && *s == '<')
2226 *d++ = *s++;
2227 /* cmd.exe recognizes "&N" only immediately after the redirection symbol. */
2228 if (*s != '&')
2230 while (isspace (*s)) /* skip whitespace before file name */
2231 s++;
2232 *d++ = ' '; /* separate file name with a single space */
2235 /* Copy the file name. */
2236 while (*s)
2238 /* Remove quoting characters from the file name in buf[]. */
2239 if (*s == '"') /* could support '..' quoting here */
2241 if (!quote)
2242 quote = *s++;
2243 else if (*s == quote)
2245 quote = 0;
2246 s++;
2248 else
2249 *d++ = *s++;
2251 else if (*s == '\\')
2253 if (s[1] == '"') /* could support '..' here */
2254 s++;
2255 *d++ = *s++;
2257 else if (isspace (*s) && !quote)
2258 break;
2259 else
2260 *d++ = *s++;
2261 if (d - buf >= sizeof (buf) - 1)
2263 errno = ENAMETOOLONG;
2264 return 0;
2267 *d = '\0';
2269 /* Windows doesn't allow redirection characters in file names, so we
2270 can bail out early if they use them, or if there's no target file
2271 name after the redirection symbol. */
2272 if (d[-1] == '>' || d[-1] == '<')
2274 errno = ENOENT;
2275 return 0;
2277 if (redir_open (buf, inp, out, err) == 0)
2278 return s - start;
2279 return 0;
2282 /* Parse the command line for redirection specs and prepare the file
2283 descriptors for the 3 standard streams accordingly. */
2284 static bool
2285 redirect_inferior_handles (const char *cmd_orig, char *cmd,
2286 int *inp, int *out, int *err)
2288 const char *s = cmd_orig;
2289 char *d = cmd;
2290 int quote = 0;
2291 bool retval = false;
2293 while (isspace (*s))
2294 *d++ = *s++;
2296 while (*s)
2298 if (*s == '"') /* could also support '..' quoting here */
2300 if (!quote)
2301 quote = *s;
2302 else if (*s == quote)
2303 quote = 0;
2305 else if (*s == '\\')
2307 if (s[1] == '"') /* escaped quote char */
2308 s++;
2310 else if (!quote)
2312 /* Process a single redirection candidate. */
2313 if (*s == '<' || *s == '>'
2314 || ((*s == '1' || *s == '2') && s[1] == '>')
2315 || (*s == '0' && s[1] == '<'))
2317 int skip = redir_set_redirection (s, inp, out, err);
2319 if (skip <= 0)
2320 return false;
2321 retval = true;
2322 s += skip;
2325 if (*s)
2326 *d++ = *s++;
2328 *d = '\0';
2329 return retval;
2331 #endif /* !__CYGWIN__ */
2333 /* Start an inferior windows child process and sets inferior_ptid to its pid.
2334 EXEC_FILE is the file to run.
2335 ALLARGS is a string containing the arguments to the program.
2336 ENV is the environment vector to pass. Errors reported with error(). */
2338 void
2339 windows_nat_target::create_inferior (const char *exec_file,
2340 const std::string &origallargs,
2341 char **in_env, int from_tty)
2343 STARTUPINFO si;
2344 #ifdef __CYGWIN__
2345 wchar_t real_path[__PMAX];
2346 wchar_t shell[__PMAX]; /* Path to shell */
2347 wchar_t infcwd[__PMAX];
2348 const char *sh;
2349 wchar_t *toexec;
2350 wchar_t *cygallargs;
2351 wchar_t *args;
2352 char **old_env = NULL;
2353 PWCHAR w32_env;
2354 size_t len;
2355 int tty;
2356 int ostdin, ostdout, ostderr;
2357 #else /* !__CYGWIN__ */
2358 char shell[__PMAX]; /* Path to shell */
2359 const char *toexec;
2360 char *args, *allargs_copy;
2361 size_t args_len, allargs_len;
2362 int fd_inp = -1, fd_out = -1, fd_err = -1;
2363 HANDLE tty = INVALID_HANDLE_VALUE;
2364 bool redirected = false;
2365 char *w32env;
2366 char *temp;
2367 size_t envlen;
2368 int i;
2369 size_t envsize;
2370 char **env;
2371 #endif /* !__CYGWIN__ */
2372 const char *allargs = origallargs.c_str ();
2373 PROCESS_INFORMATION pi;
2374 BOOL ret;
2375 DWORD flags = 0;
2376 const std::string &inferior_tty = current_inferior ()->tty ();
2378 if (!exec_file)
2379 error (_("No executable specified, use `target exec'."));
2381 const char *inferior_cwd = current_inferior ()->cwd ().c_str ();
2382 std::string expanded_infcwd;
2383 if (*inferior_cwd == '\0')
2384 inferior_cwd = nullptr;
2385 else
2387 expanded_infcwd = gdb_tilde_expand (inferior_cwd);
2388 /* Mirror slashes on inferior's cwd. */
2389 std::replace (expanded_infcwd.begin (), expanded_infcwd.end (),
2390 '/', '\\');
2391 inferior_cwd = expanded_infcwd.c_str ();
2394 memset (&si, 0, sizeof (si));
2395 si.cb = sizeof (si);
2397 if (new_group)
2398 flags |= CREATE_NEW_PROCESS_GROUP;
2400 if (new_console)
2401 windows_set_console_info (&si, &flags);
2403 #ifdef __CYGWIN__
2404 if (!useshell)
2406 flags |= DEBUG_ONLY_THIS_PROCESS;
2407 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, exec_file, real_path,
2408 __PMAX * sizeof (wchar_t)) < 0)
2409 error (_("Error starting executable: %d"), errno);
2410 toexec = real_path;
2411 len = mbstowcs (NULL, allargs, 0) + 1;
2412 if (len == (size_t) -1)
2413 error (_("Error starting executable: %d"), errno);
2414 cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
2415 mbstowcs (cygallargs, allargs, len);
2417 else
2419 sh = get_shell ();
2420 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, sh, shell, __PMAX) < 0)
2421 error (_("Error starting executable via shell: %d"), errno);
2422 len = sizeof (L" -c 'exec '") + mbstowcs (NULL, exec_file, 0)
2423 + mbstowcs (NULL, allargs, 0) + 2;
2424 cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
2425 swprintf (cygallargs, len, L" -c 'exec %s %s'", exec_file, allargs);
2426 toexec = shell;
2427 flags |= DEBUG_PROCESS;
2430 if (inferior_cwd != NULL
2431 && cygwin_conv_path (CCP_POSIX_TO_WIN_W, inferior_cwd,
2432 infcwd, strlen (inferior_cwd)) < 0)
2433 error (_("Error converting inferior cwd: %d"), errno);
2435 args = (wchar_t *) alloca ((wcslen (toexec) + wcslen (cygallargs) + 2)
2436 * sizeof (wchar_t));
2437 wcscpy (args, toexec);
2438 wcscat (args, L" ");
2439 wcscat (args, cygallargs);
2441 #ifdef CW_CVT_ENV_TO_WINENV
2442 /* First try to create a direct Win32 copy of the POSIX environment. */
2443 w32_env = (PWCHAR) cygwin_internal (CW_CVT_ENV_TO_WINENV, in_env);
2444 if (w32_env != (PWCHAR) -1)
2445 flags |= CREATE_UNICODE_ENVIRONMENT;
2446 else
2447 /* If that fails, fall back to old method tweaking GDB's environment. */
2448 #endif /* CW_CVT_ENV_TO_WINENV */
2450 /* Reset all Win32 environment variables to avoid leftover on next run. */
2451 clear_win32_environment (environ);
2452 /* Prepare the environment vars for CreateProcess. */
2453 old_env = environ;
2454 environ = in_env;
2455 cygwin_internal (CW_SYNC_WINENV);
2456 w32_env = NULL;
2459 if (inferior_tty.empty ())
2460 tty = ostdin = ostdout = ostderr = -1;
2461 else
2463 tty = open (inferior_tty.c_str (), O_RDWR | O_NOCTTY);
2464 if (tty < 0)
2466 print_sys_errmsg (inferior_tty.c_str (), errno);
2467 ostdin = ostdout = ostderr = -1;
2469 else
2471 ostdin = dup (0);
2472 ostdout = dup (1);
2473 ostderr = dup (2);
2474 dup2 (tty, 0);
2475 dup2 (tty, 1);
2476 dup2 (tty, 2);
2480 windows_init_thread_list ();
2481 ret = create_process (nullptr, args, flags, w32_env,
2482 inferior_cwd != nullptr ? infcwd : nullptr,
2483 disable_randomization,
2484 &si, &pi);
2485 if (w32_env)
2486 /* Just free the Win32 environment, if it could be created. */
2487 free (w32_env);
2488 else
2490 /* Reset all environment variables to avoid leftover on next run. */
2491 clear_win32_environment (in_env);
2492 /* Restore normal GDB environment variables. */
2493 environ = old_env;
2494 cygwin_internal (CW_SYNC_WINENV);
2497 if (tty >= 0)
2499 ::close (tty);
2500 dup2 (ostdin, 0);
2501 dup2 (ostdout, 1);
2502 dup2 (ostderr, 2);
2503 ::close (ostdin);
2504 ::close (ostdout);
2505 ::close (ostderr);
2507 #else /* !__CYGWIN__ */
2508 allargs_len = strlen (allargs);
2509 allargs_copy = strcpy ((char *) alloca (allargs_len + 1), allargs);
2510 if (strpbrk (allargs_copy, "<>") != NULL)
2512 int e = errno;
2513 errno = 0;
2514 redirected =
2515 redirect_inferior_handles (allargs, allargs_copy,
2516 &fd_inp, &fd_out, &fd_err);
2517 if (errno)
2518 warning (_("Error in redirection: %s."), safe_strerror (errno));
2519 else
2520 errno = e;
2521 allargs_len = strlen (allargs_copy);
2523 /* If not all the standard streams are redirected by the command
2524 line, use INFERIOR_TTY for those which aren't. */
2525 if (!inferior_tty.empty ()
2526 && !(fd_inp >= 0 && fd_out >= 0 && fd_err >= 0))
2528 SECURITY_ATTRIBUTES sa;
2529 sa.nLength = sizeof(sa);
2530 sa.lpSecurityDescriptor = 0;
2531 sa.bInheritHandle = TRUE;
2532 tty = CreateFileA (inferior_tty.c_str (), GENERIC_READ | GENERIC_WRITE,
2533 0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
2534 if (tty == INVALID_HANDLE_VALUE)
2535 warning (_("Warning: Failed to open TTY %s, error %#x."),
2536 inferior_tty.c_str (), (unsigned) GetLastError ());
2538 if (redirected || tty != INVALID_HANDLE_VALUE)
2540 if (fd_inp >= 0)
2541 si.hStdInput = (HANDLE) _get_osfhandle (fd_inp);
2542 else if (tty != INVALID_HANDLE_VALUE)
2543 si.hStdInput = tty;
2544 else
2545 si.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
2546 if (fd_out >= 0)
2547 si.hStdOutput = (HANDLE) _get_osfhandle (fd_out);
2548 else if (tty != INVALID_HANDLE_VALUE)
2549 si.hStdOutput = tty;
2550 else
2551 si.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
2552 if (fd_err >= 0)
2553 si.hStdError = (HANDLE) _get_osfhandle (fd_err);
2554 else if (tty != INVALID_HANDLE_VALUE)
2555 si.hStdError = tty;
2556 else
2557 si.hStdError = GetStdHandle (STD_ERROR_HANDLE);
2558 si.dwFlags |= STARTF_USESTDHANDLES;
2561 toexec = exec_file;
2562 /* Build the command line, a space-separated list of tokens where
2563 the first token is the name of the module to be executed.
2564 To avoid ambiguities introduced by spaces in the module name,
2565 we quote it. */
2566 args_len = strlen (toexec) + 2 /* quotes */ + allargs_len + 2;
2567 args = (char *) alloca (args_len);
2568 xsnprintf (args, args_len, "\"%s\" %s", toexec, allargs_copy);
2570 flags |= DEBUG_ONLY_THIS_PROCESS;
2572 /* CreateProcess takes the environment list as a null terminated set of
2573 strings (i.e. two nulls terminate the list). */
2575 /* Get total size for env strings. */
2576 for (envlen = 0, i = 0; in_env[i] && *in_env[i]; i++)
2577 envlen += strlen (in_env[i]) + 1;
2579 envsize = sizeof (in_env[0]) * (i + 1);
2580 env = (char **) alloca (envsize);
2581 memcpy (env, in_env, envsize);
2582 /* Windows programs expect the environment block to be sorted. */
2583 qsort (env, i, sizeof (char *), envvar_cmp);
2585 w32env = (char *) alloca (envlen + 1);
2587 /* Copy env strings into new buffer. */
2588 for (temp = w32env, i = 0; env[i] && *env[i]; i++)
2590 strcpy (temp, env[i]);
2591 temp += strlen (temp) + 1;
2594 /* Final nil string to terminate new env. */
2595 *temp = 0;
2597 windows_init_thread_list ();
2598 ret = create_process (nullptr, /* image */
2599 args, /* command line */
2600 flags, /* start flags */
2601 w32env, /* environment */
2602 inferior_cwd, /* current directory */
2603 disable_randomization,
2604 &si,
2605 &pi);
2606 if (tty != INVALID_HANDLE_VALUE)
2607 CloseHandle (tty);
2608 if (fd_inp >= 0)
2609 _close (fd_inp);
2610 if (fd_out >= 0)
2611 _close (fd_out);
2612 if (fd_err >= 0)
2613 _close (fd_err);
2614 #endif /* !__CYGWIN__ */
2616 if (!ret)
2617 error (_("Error creating process %s, (error %u)."),
2618 exec_file, (unsigned) GetLastError ());
2620 #ifdef __x86_64__
2621 BOOL wow64;
2622 if (IsWow64Process (pi.hProcess, &wow64))
2623 windows_process.wow64_process = wow64;
2624 #endif
2626 CloseHandle (pi.hThread);
2627 CloseHandle (pi.hProcess);
2629 if (useshell && shell[0] != '\0')
2630 windows_process.saw_create = -1;
2631 else
2632 windows_process.saw_create = 0;
2634 do_initial_windows_stuff (pi.dwProcessId, 0);
2636 /* windows_continue (DBG_CONTINUE, -1, 0); */
2639 void
2640 windows_nat_target::mourn_inferior ()
2642 (void) windows_continue (DBG_CONTINUE, -1, 0);
2643 x86_cleanup_dregs();
2644 if (windows_process.open_process_used)
2646 CHECK (CloseHandle (windows_process.handle));
2647 windows_process.open_process_used = 0;
2649 windows_process.siginfo_er.ExceptionCode = 0;
2650 inf_child_target::mourn_inferior ();
2653 /* Send a SIGINT to the process group. This acts just like the user typed a
2654 ^C on the controlling terminal. */
2656 void
2657 windows_nat_target::interrupt ()
2659 DEBUG_EVENTS ("GenerateConsoleCtrlEvent (CTRLC_EVENT, 0)");
2660 CHECK (GenerateConsoleCtrlEvent (CTRL_C_EVENT,
2661 windows_process.current_event.dwProcessId));
2662 registers_changed (); /* refresh register state */
2665 /* Helper for windows_xfer_partial that handles memory transfers.
2666 Arguments are like target_xfer_partial. */
2668 static enum target_xfer_status
2669 windows_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
2670 ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
2672 SIZE_T done = 0;
2673 BOOL success;
2674 DWORD lasterror = 0;
2676 if (writebuf != NULL)
2678 DEBUG_MEM ("write target memory, %s bytes at %s",
2679 pulongest (len), core_addr_to_string (memaddr));
2680 success = WriteProcessMemory (windows_process.handle,
2681 (LPVOID) (uintptr_t) memaddr, writebuf,
2682 len, &done);
2683 if (!success)
2684 lasterror = GetLastError ();
2685 FlushInstructionCache (windows_process.handle,
2686 (LPCVOID) (uintptr_t) memaddr, len);
2688 else
2690 DEBUG_MEM ("read target memory, %s bytes at %s",
2691 pulongest (len), core_addr_to_string (memaddr));
2692 success = ReadProcessMemory (windows_process.handle,
2693 (LPCVOID) (uintptr_t) memaddr, readbuf,
2694 len, &done);
2695 if (!success)
2696 lasterror = GetLastError ();
2698 *xfered_len = (ULONGEST) done;
2699 if (!success && lasterror == ERROR_PARTIAL_COPY && done > 0)
2700 return TARGET_XFER_OK;
2701 else
2702 return success ? TARGET_XFER_OK : TARGET_XFER_E_IO;
2705 void
2706 windows_nat_target::kill ()
2708 CHECK (TerminateProcess (windows_process.handle, 0));
2710 for (;;)
2712 if (!windows_continue (DBG_CONTINUE, -1, 1))
2713 break;
2714 if (!wait_for_debug_event (&windows_process.current_event, INFINITE))
2715 break;
2716 if (windows_process.current_event.dwDebugEventCode
2717 == EXIT_PROCESS_DEBUG_EVENT)
2718 break;
2721 target_mourn_inferior (inferior_ptid); /* Or just windows_mourn_inferior? */
2724 void
2725 windows_nat_target::close ()
2727 DEBUG_EVENTS ("inferior_ptid=%d\n", inferior_ptid.pid ());
2730 /* Convert pid to printable format. */
2731 std::string
2732 windows_nat_target::pid_to_str (ptid_t ptid)
2734 if (ptid.lwp () != 0)
2735 return string_printf ("Thread %d.0x%lx", ptid.pid (), ptid.lwp ());
2737 return normal_pid_to_str (ptid);
2740 static enum target_xfer_status
2741 windows_xfer_shared_libraries (struct target_ops *ops,
2742 enum target_object object, const char *annex,
2743 gdb_byte *readbuf, const gdb_byte *writebuf,
2744 ULONGEST offset, ULONGEST len,
2745 ULONGEST *xfered_len)
2747 auto_obstack obstack;
2748 const char *buf;
2749 LONGEST len_avail;
2751 if (writebuf)
2752 return TARGET_XFER_E_IO;
2754 obstack_grow_str (&obstack, "<library-list>\n");
2755 for (windows_solib &so : windows_process.solibs)
2756 windows_xfer_shared_library (so.name.c_str (),
2757 (CORE_ADDR) (uintptr_t) so.load_addr,
2758 &so.text_offset,
2759 target_gdbarch (), &obstack);
2760 obstack_grow_str0 (&obstack, "</library-list>\n");
2762 buf = (const char *) obstack_finish (&obstack);
2763 len_avail = strlen (buf);
2764 if (offset >= len_avail)
2765 len= 0;
2766 else
2768 if (len > len_avail - offset)
2769 len = len_avail - offset;
2770 memcpy (readbuf, buf + offset, len);
2773 *xfered_len = (ULONGEST) len;
2774 return len != 0 ? TARGET_XFER_OK : TARGET_XFER_EOF;
2777 /* Helper for windows_nat_target::xfer_partial that handles signal info. */
2779 static enum target_xfer_status
2780 windows_xfer_siginfo (gdb_byte *readbuf, ULONGEST offset, ULONGEST len,
2781 ULONGEST *xfered_len)
2783 char *buf = (char *) &windows_process.siginfo_er;
2784 size_t bufsize = sizeof (windows_process.siginfo_er);
2786 #ifdef __x86_64__
2787 EXCEPTION_RECORD32 er32;
2788 if (windows_process.wow64_process)
2790 buf = (char *) &er32;
2791 bufsize = sizeof (er32);
2793 er32.ExceptionCode = windows_process.siginfo_er.ExceptionCode;
2794 er32.ExceptionFlags = windows_process.siginfo_er.ExceptionFlags;
2795 er32.ExceptionRecord
2796 = (uintptr_t) windows_process.siginfo_er.ExceptionRecord;
2797 er32.ExceptionAddress
2798 = (uintptr_t) windows_process.siginfo_er.ExceptionAddress;
2799 er32.NumberParameters = windows_process.siginfo_er.NumberParameters;
2800 int i;
2801 for (i = 0; i < EXCEPTION_MAXIMUM_PARAMETERS; i++)
2802 er32.ExceptionInformation[i]
2803 = windows_process.siginfo_er.ExceptionInformation[i];
2805 #endif
2807 if (windows_process.siginfo_er.ExceptionCode == 0)
2808 return TARGET_XFER_E_IO;
2810 if (readbuf == nullptr)
2811 return TARGET_XFER_E_IO;
2813 if (offset > bufsize)
2814 return TARGET_XFER_E_IO;
2816 if (offset + len > bufsize)
2817 len = bufsize - offset;
2819 memcpy (readbuf, buf + offset, len);
2820 *xfered_len = len;
2822 return TARGET_XFER_OK;
2825 enum target_xfer_status
2826 windows_nat_target::xfer_partial (enum target_object object,
2827 const char *annex, gdb_byte *readbuf,
2828 const gdb_byte *writebuf, ULONGEST offset,
2829 ULONGEST len, ULONGEST *xfered_len)
2831 switch (object)
2833 case TARGET_OBJECT_MEMORY:
2834 return windows_xfer_memory (readbuf, writebuf, offset, len, xfered_len);
2836 case TARGET_OBJECT_LIBRARIES:
2837 return windows_xfer_shared_libraries (this, object, annex, readbuf,
2838 writebuf, offset, len, xfered_len);
2840 case TARGET_OBJECT_SIGNAL_INFO:
2841 return windows_xfer_siginfo (readbuf, offset, len, xfered_len);
2843 default:
2844 if (beneath () == NULL)
2846 /* This can happen when requesting the transfer of unsupported
2847 objects before a program has been started (and therefore
2848 with the current_target having no target beneath). */
2849 return TARGET_XFER_E_IO;
2851 return beneath ()->xfer_partial (object, annex,
2852 readbuf, writebuf, offset, len,
2853 xfered_len);
2857 /* Provide thread local base, i.e. Thread Information Block address.
2858 Returns 1 if ptid is found and sets *ADDR to thread_local_base. */
2860 bool
2861 windows_nat_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
2863 windows_thread_info *th;
2865 th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
2866 if (th == NULL)
2867 return false;
2869 if (addr != NULL)
2870 *addr = th->thread_local_base;
2872 return true;
2875 ptid_t
2876 windows_nat_target::get_ada_task_ptid (long lwp, ULONGEST thread)
2878 return ptid_t (inferior_ptid.pid (), lwp, 0);
2881 /* Implementation of the to_thread_name method. */
2883 const char *
2884 windows_nat_target::thread_name (struct thread_info *thr)
2886 windows_thread_info *th
2887 = windows_process.thread_rec (thr->ptid,
2888 DONT_INVALIDATE_CONTEXT);
2889 return th->thread_name ();
2893 void _initialize_windows_nat ();
2894 void
2895 _initialize_windows_nat ()
2897 x86_dr_low.set_control = cygwin_set_dr7;
2898 x86_dr_low.set_addr = cygwin_set_dr;
2899 x86_dr_low.get_addr = cygwin_get_dr;
2900 x86_dr_low.get_status = cygwin_get_dr6;
2901 x86_dr_low.get_control = cygwin_get_dr7;
2903 /* x86_dr_low.debug_register_length field is set by
2904 calling x86_set_debug_register_length function
2905 in processor windows specific native file. */
2907 add_inf_child_target (&the_windows_nat_target);
2909 #ifdef __CYGWIN__
2910 cygwin_internal (CW_SET_DOS_FILE_WARNING, 0);
2911 #endif
2913 add_com ("signal-event", class_run, signal_event_command, _("\
2914 Signal a crashed process with event ID, to allow its debugging.\n\
2915 This command is needed in support of setting up GDB as JIT debugger on \
2916 MS-Windows. The command should be invoked from the GDB command line using \
2917 the '-ex' command-line option. The ID of the event that blocks the \
2918 crashed process will be supplied by the Windows JIT debugging mechanism."));
2920 #ifdef __CYGWIN__
2921 add_setshow_boolean_cmd ("shell", class_support, &useshell, _("\
2922 Set use of shell to start subprocess."), _("\
2923 Show use of shell to start subprocess."), NULL,
2924 NULL,
2925 NULL, /* FIXME: i18n: */
2926 &setlist, &showlist);
2928 add_setshow_boolean_cmd ("cygwin-exceptions", class_support,
2929 &cygwin_exceptions, _("\
2930 Break when an exception is detected in the Cygwin DLL itself."), _("\
2931 Show whether gdb breaks on exceptions in the Cygwin DLL itself."), NULL,
2932 NULL,
2933 NULL, /* FIXME: i18n: */
2934 &setlist, &showlist);
2935 #endif
2937 add_setshow_boolean_cmd ("new-console", class_support, &new_console, _("\
2938 Set creation of new console when creating child process."), _("\
2939 Show creation of new console when creating child process."), NULL,
2940 NULL,
2941 NULL, /* FIXME: i18n: */
2942 &setlist, &showlist);
2944 add_setshow_boolean_cmd ("new-group", class_support, &new_group, _("\
2945 Set creation of new group when creating child process."), _("\
2946 Show creation of new group when creating child process."), NULL,
2947 NULL,
2948 NULL, /* FIXME: i18n: */
2949 &setlist, &showlist);
2951 add_setshow_boolean_cmd ("debugexec", class_support, &debug_exec, _("\
2952 Set whether to display execution in child process."), _("\
2953 Show whether to display execution in child process."), NULL,
2954 NULL,
2955 NULL, /* FIXME: i18n: */
2956 &setlist, &showlist);
2958 add_setshow_boolean_cmd ("debugevents", class_support, &debug_events, _("\
2959 Set whether to display kernel events in child process."), _("\
2960 Show whether to display kernel events in child process."), NULL,
2961 NULL,
2962 NULL, /* FIXME: i18n: */
2963 &setlist, &showlist);
2965 add_setshow_boolean_cmd ("debugmemory", class_support, &debug_memory, _("\
2966 Set whether to display memory accesses in child process."), _("\
2967 Show whether to display memory accesses in child process."), NULL,
2968 NULL,
2969 NULL, /* FIXME: i18n: */
2970 &setlist, &showlist);
2972 add_setshow_boolean_cmd ("debugexceptions", class_support,
2973 &debug_exceptions, _("\
2974 Set whether to display kernel exceptions in child process."), _("\
2975 Show whether to display kernel exceptions in child process."), NULL,
2976 NULL,
2977 NULL, /* FIXME: i18n: */
2978 &setlist, &showlist);
2980 init_w32_command_list ();
2982 add_cmd ("selector", class_info, display_selectors,
2983 _("Display selectors infos."),
2984 &info_w32_cmdlist);
2986 if (!initialize_loadable ())
2988 /* This will probably fail on Windows 9x/Me. Let the user know
2989 that we're missing some functionality. */
2990 warning(_("\
2991 cannot automatically find executable file or library to read symbols.\n\
2992 Use \"file\" or \"dll\" command to load executable/libraries directly."));
2996 /* Hardware watchpoint support, adapted from go32-nat.c code. */
2998 /* Pass the address ADDR to the inferior in the I'th debug register.
2999 Here we just store the address in dr array, the registers will be
3000 actually set up when windows_continue is called. */
3001 static void
3002 cygwin_set_dr (int i, CORE_ADDR addr)
3004 if (i < 0 || i > 3)
3005 internal_error (__FILE__, __LINE__,
3006 _("Invalid register %d in cygwin_set_dr.\n"), i);
3007 windows_process.dr[i] = addr;
3009 for (auto &th : windows_process.thread_list)
3010 th->debug_registers_changed = true;
3013 /* Pass the value VAL to the inferior in the DR7 debug control
3014 register. Here we just store the address in D_REGS, the watchpoint
3015 will be actually set up in windows_wait. */
3016 static void
3017 cygwin_set_dr7 (unsigned long val)
3019 windows_process.dr[7] = (CORE_ADDR) val;
3021 for (auto &th : windows_process.thread_list)
3022 th->debug_registers_changed = true;
3025 /* Get the value of debug register I from the inferior. */
3027 static CORE_ADDR
3028 cygwin_get_dr (int i)
3030 return windows_process.dr[i];
3033 /* Get the value of the DR6 debug status register from the inferior.
3034 Here we just return the value stored in dr[6]
3035 by the last call to thread_rec for current_event.dwThreadId id. */
3036 static unsigned long
3037 cygwin_get_dr6 (void)
3039 return (unsigned long) windows_process.dr[6];
3042 /* Get the value of the DR7 debug status register from the inferior.
3043 Here we just return the value stored in dr[7] by the last call to
3044 thread_rec for current_event.dwThreadId id. */
3046 static unsigned long
3047 cygwin_get_dr7 (void)
3049 return (unsigned long) windows_process.dr[7];
3052 /* Determine if the thread referenced by "ptid" is alive
3053 by "polling" it. If WaitForSingleObject returns WAIT_OBJECT_0
3054 it means that the thread has died. Otherwise it is assumed to be alive. */
3056 bool
3057 windows_nat_target::thread_alive (ptid_t ptid)
3059 gdb_assert (ptid.lwp () != 0);
3061 windows_thread_info *th
3062 = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
3063 return WaitForSingleObject (th->h, 0) != WAIT_OBJECT_0;
3066 void _initialize_check_for_gdb_ini ();
3067 void
3068 _initialize_check_for_gdb_ini ()
3070 char *homedir;
3071 if (inhibit_gdbinit)
3072 return;
3074 homedir = getenv ("HOME");
3075 if (homedir)
3077 char *p;
3078 char *oldini = (char *) alloca (strlen (homedir) +
3079 sizeof ("gdb.ini") + 1);
3080 strcpy (oldini, homedir);
3081 p = strchr (oldini, '\0');
3082 if (p > oldini && !IS_DIR_SEPARATOR (p[-1]))
3083 *p++ = '/';
3084 strcpy (p, "gdb.ini");
3085 if (access (oldini, 0) == 0)
3087 int len = strlen (oldini);
3088 char *newini = (char *) alloca (len + 2);
3090 xsnprintf (newini, len + 2, "%.*s.gdbinit",
3091 (int) (len - (sizeof ("gdb.ini") - 1)), oldini);
3092 warning (_("obsolete '%s' found. Rename to '%s'."), oldini, newini);