GDB (xrefs)
Loading...
Searching...
No Matches
windows-nat.c
Go to the documentation of this file.
1/* Target-vector operations for controlling windows child processes, for GDB.
2
3 Copyright (C) 1995-2023 Free Software Foundation, Inc.
4
5 Contributed by Cygnus Solutions, A Red Hat Company.
6
7 This file is part of GDB.
8
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.
13
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.
18
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/>. */
21
22/* Originally by Steve Chamberlain, sac@cygnus.com */
23
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>
46#include <queue>
47
48#include "filenames.h"
49#include "symfile.h"
50#include "objfiles.h"
51#include "gdb_bfd.h"
52#include "gdbsupport/gdb_obstack.h"
53#include "gdbthread.h"
54#include "gdbcmd.h"
55#include <unistd.h>
56#include "exec.h"
57#include "solist.h"
58#include "solib.h"
59#include "xml-support.h"
60#include "inttypes.h"
61
62#include "i386-tdep.h"
63#include "i387-tdep.h"
64
65#include "windows-tdep.h"
66#include "windows-nat.h"
67#include "x86-nat.h"
68#include "complaints.h"
69#include "inf-child.h"
70#include "gdbsupport/gdb_tilde_expand.h"
71#include "gdbsupport/pathstuff.h"
72#include "gdbsupport/gdb_wait.h"
73#include "nat/windows-nat.h"
74#include "gdbsupport/symbol.h"
75#include "ser-event.h"
76#include "inf-loop.h"
77
78using namespace windows_nat;
79
80/* Maintain a linked list of "so" information. */
82{
83 LPVOID load_addr = 0;
84 CORE_ADDR text_offset = 0;
85
86 /* Original name. */
87 std::string original_name;
88 /* Expanded form of the name. */
89 std::string name;
90};
91
93{
94 windows_thread_info *thread_rec (ptid_t ptid,
95 thread_disposition_type disposition) override;
96 int handle_output_debug_string (struct target_waitstatus *ourstatus) override;
97 void handle_load_dll (const char *dll_name, LPVOID base) override;
98 void handle_unload_dll () override;
99 bool handle_access_violation (const EXCEPTION_RECORD *rec) override;
100
101
102 int have_saved_context = 0; /* True if we've saved context from a
103 cygwin signal. */
104
105 uintptr_t dr[8] {};
106
108
109 std::vector<std::unique_ptr<windows_thread_info>> thread_list;
110
111 /* Counts of things. */
112 int saw_create = 0;
114#ifdef __x86_64__
115 void *wow64_dbgbreak = nullptr;
116#endif
117
118 /* This vector maps GDB's idea of a register's number into an offset
119 in the windows exception context vector.
120
121 It also contains the bit mask needed to load the register in question.
122
123 The contents of this table can only be computed by the units
124 that provide CPU-specific support for Windows native debugging.
125
126 One day we could read a reg, we could inspect the context we
127 already have loaded, if it doesn't have the bit set that we need,
128 we read that set of registers in using GetThreadContext. If the
129 context already contains what we need, we just unpack it. Then to
130 write a register, first we have to ensure that the context contains
131 the other regs of the group, and then we copy the info in and set
132 out bit. */
133
134 const int *mappings = nullptr;
135
136 /* The function to use in order to determine whether a register is
137 a segment register or not. */
139
140 std::vector<windows_solib> solibs;
141
142#ifdef __CYGWIN__
143 CONTEXT saved_context {}; /* Contains the saved context from a
144 cygwin signal. */
145
146 /* The starting and ending address of the cygwin1.dll text segment. */
147 CORE_ADDR cygwin_load_start = 0;
148 CORE_ADDR cygwin_load_end = 0;
149#endif /* __CYGWIN__ */
150};
151
152/* The current process. */
154
155#undef STARTUPINFO
156
157#ifndef __CYGWIN__
158# define __PMAX (MAX_PATH + 1)
159# define STARTUPINFO STARTUPINFOA
160#else
161# define __PMAX PATH_MAX
162# define STARTUPINFO STARTUPINFOW
163#endif
164
165/* If we're not using the old Cygwin header file set, define the
166 following which never should have been in the generic Win32 API
167 headers in the first place since they were our own invention... */
168#ifndef _GNU_H_WINDOWS_H
169enum
170 {
172 };
173#endif
174
175#ifndef CONTEXT_EXTENDED_REGISTERS
176/* This macro is only defined on ia32. It only makes sense on this target,
177 so define it as zero if not already defined. */
178#define CONTEXT_EXTENDED_REGISTERS 0
179#endif
180
181#define CONTEXT_DEBUGGER_DR CONTEXT_FULL | CONTEXT_FLOATING_POINT \
182 | CONTEXT_SEGMENTS | CONTEXT_DEBUG_REGISTERS \
183 | CONTEXT_EXTENDED_REGISTERS
184
185#define DR6_CLEAR_VALUE 0xffff0ff0
186
187/* The string sent by cygwin when it processes a signal.
188 FIXME: This should be in a cygwin include file. */
189#ifndef _CYGWIN_SIGNAL_STRING
190#define _CYGWIN_SIGNAL_STRING "cYgSiGw00f"
191#endif
192
193#define CHECK(x) check (x, __FILE__,__LINE__)
194#define DEBUG_EXEC(fmt, ...) \
195 debug_prefixed_printf_cond (debug_exec, "windows exec", fmt, ## __VA_ARGS__)
196#define DEBUG_EVENTS(fmt, ...) \
197 debug_prefixed_printf_cond (debug_events, "windows events", fmt, \
198 ## __VA_ARGS__)
199#define DEBUG_MEM(fmt, ...) \
200 debug_prefixed_printf_cond (debug_memory, "windows mem", fmt, \
201 ## __VA_ARGS__)
202#define DEBUG_EXCEPT(fmt, ...) \
203 debug_prefixed_printf_cond (debug_exceptions, "windows except", fmt, \
204 ## __VA_ARGS__)
205
206static void cygwin_set_dr (int i, CORE_ADDR addr);
207static void cygwin_set_dr7 (unsigned long val);
208static CORE_ADDR cygwin_get_dr (int i);
209static unsigned long cygwin_get_dr6 (void);
210static unsigned long cygwin_get_dr7 (void);
211
212/* User options. */
213static bool new_console = false;
214#ifdef __CYGWIN__
215static bool cygwin_exceptions = false;
216#endif
217static bool new_group = true;
218static bool debug_exec = false; /* show execution */
219static bool debug_events = false; /* show events from kernel */
220static bool debug_memory = false; /* show target memory accesses */
221static bool debug_exceptions = false; /* show target exceptions */
222static bool useshell = false; /* use shell for subprocesses */
223
224/* See windows_nat_target::resume to understand why this is commented
225 out. */
226#if 0
227/* This vector maps the target's idea of an exception (extracted
228 from the DEBUG_EVENT structure) to GDB's idea. */
229
230struct xlate_exception
231 {
232 DWORD them;
233 enum gdb_signal us;
234 };
235
236static const struct xlate_exception xlate[] =
237{
238 {EXCEPTION_ACCESS_VIOLATION, GDB_SIGNAL_SEGV},
239 {STATUS_STACK_OVERFLOW, GDB_SIGNAL_SEGV},
240 {EXCEPTION_BREAKPOINT, GDB_SIGNAL_TRAP},
241 {DBG_CONTROL_C, GDB_SIGNAL_INT},
242 {EXCEPTION_SINGLE_STEP, GDB_SIGNAL_TRAP},
243 {STATUS_FLOAT_DIVIDE_BY_ZERO, GDB_SIGNAL_FPE}
244};
245
246#endif /* 0 */
247
248struct windows_nat_target final : public x86_nat_target<inf_child_target>
249{
251
252 void close () override;
253
254 void attach (const char *, int) override;
255
256 bool attach_no_wait () override
257 { return true; }
258
259 void detach (inferior *, int) override;
260
261 void resume (ptid_t, int , enum gdb_signal) override;
262
263 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
264
265 void fetch_registers (struct regcache *, int) override;
266 void store_registers (struct regcache *, int) override;
267
269 {
273 }
274
276 {
277 return true;
278 }
279
281 const char *annex,
282 gdb_byte *readbuf,
283 const gdb_byte *writebuf,
284 ULONGEST offset, ULONGEST len,
285 ULONGEST *xfered_len) override;
286
287 void files_info () override;
288
289 void kill () override;
290
291 void create_inferior (const char *, const std::string &,
292 char **, int) override;
293
294 void mourn_inferior () override;
295
296 bool thread_alive (ptid_t ptid) override;
297
298 std::string pid_to_str (ptid_t) override;
299
300 void interrupt () override;
301 void pass_ctrlc () override;
302
303 const char *pid_to_exec_file (int pid) override;
304
305 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
306
307 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
308
309 const char *thread_name (struct thread_info *) override;
310
311 ptid_t get_windows_debug_event (int pid, struct target_waitstatus *ourstatus,
312 target_wait_flags options);
313
314 void do_initial_windows_stuff (DWORD pid, bool attaching);
315
317 {
319 }
320
321 bool can_async_p () override
322 {
323 return true;
324 }
325
326 bool is_async_p () override
327 {
328 return m_is_async;
329 }
330
331 void async (bool enable) override;
332
333 int async_wait_fd () override
334 {
336 }
337
338private:
339
340 windows_thread_info *add_thread (ptid_t ptid, HANDLE h, void *tlb,
341 bool main_thread_p);
342 void delete_thread (ptid_t ptid, DWORD exit_code, bool main_thread_p);
343 DWORD fake_create_process ();
344
345 BOOL windows_continue (DWORD continue_status, int id, int killed,
346 bool last_call = false);
347
348 /* Helper function to start process_thread. */
349 static DWORD WINAPI process_thread_starter (LPVOID self);
350
351 /* This function implements the background thread that starts
352 inferiors and waits for events. */
353 void process_thread ();
354
355 /* Push FUNC onto the queue of requests for process_thread, and wait
356 until it has been called. On Windows, certain debugging
357 functions can only be called by the thread that started (or
358 attached to) the inferior. These are all done in the worker
359 thread, via calls to this method. If FUNC returns true,
360 process_thread will wait for debug events when FUNC returns. */
361 void do_synchronously (gdb::function_view<bool ()> func);
362
363 /* This waits for a debug event, dispatching to the worker thread as
364 needed. */
365 void wait_for_debug_event_main_thread (DEBUG_EVENT *event);
366
367 /* Queue used to send requests to process_thread. This is
368 implicitly locked. */
369 std::queue<gdb::function_view<bool ()>> m_queue;
370
371 /* Event used to signal process_thread that an item has been
372 pushed. */
374 /* Event used by process_thread to indicate that it has processed a
375 single function call. */
377
378 /* Serial event used to communicate wait event availability to the
379 main loop. */
380 serial_event *m_wait_event;
381
382 /* The last debug event, when M_WAIT_EVENT has been set. */
383 DEBUG_EVENT m_last_debug_event {};
384 /* True if a debug event is pending. */
385 std::atomic<bool> m_debug_event_pending { false };
386
387 /* True if currently in async mode. */
388 bool m_is_async = false;
389};
390
391static void
392check (BOOL ok, const char *file, int line)
393{
394 if (!ok)
395 {
396 unsigned err = (unsigned) GetLastError ();
397 gdb_printf ("error return %s:%d was %u: %s\n", file, line,
398 err, strwinerror (err));
399 }
400}
401
403 : m_pushed_event (CreateEvent (nullptr, false, false, nullptr)),
404 m_response_event (CreateEvent (nullptr, false, false, nullptr)),
405 m_wait_event (make_serial_event ())
406{
407 HANDLE bg_thread = CreateThread (nullptr, 64 * 1024,
408 process_thread_starter, this, 0, nullptr);
409 CloseHandle (bg_thread);
410}
411
412void
414{
415 if (enable == is_async_p ())
416 return;
417
418 if (enable)
419 add_file_handler (async_wait_fd (),
420 [] (int, gdb_client_data)
421 {
423 },
424 nullptr, "windows_nat_target");
425 else
426 delete_file_handler (async_wait_fd ());
427
429}
430
431/* A wrapper for WaitForSingleObject that issues a warning if
432 something unusual happens. */
433static void
434wait_for_single (HANDLE handle, DWORD howlong)
435{
436 while (true)
437 {
438 DWORD r = WaitForSingleObject (handle, howlong);
439 if (r == WAIT_OBJECT_0)
440 return;
441 if (r == WAIT_FAILED)
442 {
443 unsigned err = (unsigned) GetLastError ();
444 warning ("WaitForSingleObject failed (code %u): %s",
445 err, strwinerror (err));
446 }
447 else
448 warning ("unexpected result from WaitForSingleObject: %u",
449 (unsigned) r);
450 }
451}
452
453DWORD WINAPI
455{
456 ((windows_nat_target *) self)->process_thread ();
457 return 0;
458}
459
460void
462{
463 while (true)
464 {
466
467 gdb::function_view<bool ()> func = std::move (m_queue.front ());
468 m_queue.pop ();
469
470 bool should_wait = func ();
471 SetEvent (m_response_event);
472
473 if (should_wait)
474 {
476 {
479 }
481 }
482 }
483}
484
485void
486windows_nat_target::do_synchronously (gdb::function_view<bool ()> func)
487{
488 m_queue.emplace (std::move (func));
489 SetEvent (m_pushed_event);
491}
492
493void
495{
496 do_synchronously ([&] ()
497 {
499 {
500 *event = m_last_debug_event;
501 m_debug_event_pending = false;
503 }
504 else
505 wait_for_debug_event (event, INFINITE);
506 return false;
507 });
508}
509
510/* See nat/windows-nat.h. */
511
514 (ptid_t ptid, thread_disposition_type disposition)
515{
516 for (auto &th : thread_list)
517 if (th->tid == ptid.lwp ())
518 {
519 if (!th->suspended)
520 {
521 switch (disposition)
522 {
524 /* Nothing. */
525 break;
527 if (ptid.lwp () != current_event.dwThreadId)
528 th->suspend ();
529 th->reload_context = true;
530 break;
531 case DONT_SUSPEND:
532 th->reload_context = true;
533 th->suspended = -1;
534 break;
535 }
536 }
537 return th.get ();
538 }
539
540 return NULL;
541}
542
543/* Add a thread to the thread list.
544
545 PTID is the ptid of the thread to be added.
546 H is its Windows handle.
547 TLB is its thread local base.
548 MAIN_THREAD_P should be true if the thread to be added is
549 the main thread, false otherwise. */
550
552windows_nat_target::add_thread (ptid_t ptid, HANDLE h, void *tlb,
553 bool main_thread_p)
554{
556
557 gdb_assert (ptid.lwp () != 0);
558
560 return th;
561
562 CORE_ADDR base = (CORE_ADDR) (uintptr_t) tlb;
563#ifdef __x86_64__
564 /* For WOW64 processes, this is actually the pointer to the 64bit TIB,
565 and the 32bit TIB is exactly 2 pages after it. */
566 if (windows_process.wow64_process)
567 base += 0x2000;
568#endif
569 th = new windows_thread_info (ptid.lwp (), h, base);
570 windows_process.thread_list.emplace_back (th);
571
572 /* Add this new thread to the list of threads.
573
574 To be consistent with what's done on other platforms, we add
575 the main thread silently (in reality, this thread is really
576 more of a process to the user than a thread). */
577 if (main_thread_p)
578 add_thread_silent (this, ptid);
579 else
580 ::add_thread (this, ptid);
581
582 /* It's simplest to always set this and update the debug
583 registers. */
584 th->debug_registers_changed = true;
585
586 return th;
587}
588
589/* Clear out any old thread list and reinitialize it to a
590 pristine state. */
591static void
593{
594 DEBUG_EVENTS ("called");
596}
597
598/* Delete a thread from the list of threads.
599
600 PTID is the ptid of the thread to be deleted.
601 EXIT_CODE is the thread's exit code.
602 MAIN_THREAD_P should be true if the thread to be deleted is
603 the main thread, false otherwise. */
604
605void
606windows_nat_target::delete_thread (ptid_t ptid, DWORD exit_code,
607 bool main_thread_p)
608{
609 DWORD id;
610
611 gdb_assert (ptid.lwp () != 0);
612
613 id = ptid.lwp ();
614
615 /* Emit a notification about the thread being deleted.
616
617 Note that no notification was printed when the main thread
618 was created, and thus, unless in verbose mode, we should be
619 symmetrical, and avoid that notification for the main thread
620 here as well. */
621
622 if (info_verbose)
623 gdb_printf ("[Deleting %s]\n", target_pid_to_str (ptid).c_str ());
624 else if (print_thread_events && !main_thread_p)
625 gdb_printf (_("[%s exited with code %u]\n"),
626 target_pid_to_str (ptid).c_str (),
627 (unsigned) exit_code);
628
629 ::delete_thread (find_thread_ptid (this, ptid));
630
631 auto iter = std::find_if (windows_process.thread_list.begin (),
633 [=] (std::unique_ptr<windows_thread_info> &th)
634 {
635 return th->tid == id;
636 });
637
638 if (iter != windows_process.thread_list.end ())
639 windows_process.thread_list.erase (iter);
640}
641
642/* Fetches register number R from the given windows_thread_info,
643 and supplies its value to the given regcache.
644
645 This function assumes that R is non-negative. A failed assertion
646 is raised if that is not true.
647
648 This function assumes that TH->RELOAD_CONTEXT is not set, meaning
649 that the windows_thread_info has an up-to-date context. A failed
650 assertion is raised if that assumption is violated. */
651
652static void
654 windows_thread_info *th, int r)
655{
656 gdb_assert (r >= 0);
657 gdb_assert (!th->reload_context);
658
659 char *context_ptr = (char *) &th->context;
660#ifdef __x86_64__
661 if (windows_process.wow64_process)
662 context_ptr = (char *) &th->wow64_context;
663#endif
664
665 char *context_offset = context_ptr + windows_process.mappings[r];
666 struct gdbarch *gdbarch = regcache->arch ();
667 i386_gdbarch_tdep *tdep = gdbarch_tdep<i386_gdbarch_tdep> (gdbarch);
668
669 gdb_assert (!gdbarch_read_pc_p (gdbarch));
670 gdb_assert (gdbarch_pc_regnum (gdbarch) >= 0);
671 gdb_assert (!gdbarch_write_pc_p (gdbarch));
672
673 if (r == I387_FISEG_REGNUM (tdep))
674 {
675 long l = *((long *) context_offset) & 0xffff;
676 regcache->raw_supply (r, (char *) &l);
677 }
678 else if (r == I387_FOP_REGNUM (tdep))
679 {
680 long l = (*((long *) context_offset) >> 16) & ((1 << 11) - 1);
681 regcache->raw_supply (r, (char *) &l);
682 }
684 {
685 /* GDB treats segment registers as 32bit registers, but they are
686 in fact only 16 bits long. Make sure we do not read extra
687 bits from our source buffer. */
688 long l = *((long *) context_offset) & 0xffff;
689 regcache->raw_supply (r, (char *) &l);
690 }
691 else
692 {
694 && !th->pc_adjusted
695 && r == gdbarch_pc_regnum (gdbarch))
696 {
697 int size = register_size (gdbarch, r);
698 if (size == 4)
699 {
700 uint32_t value;
701 memcpy (&value, context_offset, size);
703 memcpy (context_offset, &value, size);
704 }
705 else
706 {
707 gdb_assert (size == 8);
708 uint64_t value;
709 memcpy (&value, context_offset, size);
711 memcpy (context_offset, &value, size);
712 }
713 /* Make sure we only rewrite the PC a single time. */
714 th->pc_adjusted = true;
715 }
717 }
718}
719
720void
722{
725
726 /* Check if TH exists. Windows sometimes uses a non-existent
727 thread id in its events. */
728 if (th == NULL)
729 return;
730
731 if (th->reload_context)
732 {
733#ifdef __CYGWIN__
735 {
736 /* Lie about where the program actually is stopped since
737 cygwin has informed us that we should consider the signal
738 to have occurred at another location which is stored in
739 "saved_context. */
740 memcpy (&th->context, &windows_process.saved_context,
741 __COPY_CONTEXT_SIZE);
743 }
744 else
745#endif
746#ifdef __x86_64__
747 if (windows_process.wow64_process)
748 {
749 th->wow64_context.ContextFlags = CONTEXT_DEBUGGER_DR;
750 CHECK (Wow64GetThreadContext (th->h, &th->wow64_context));
751 /* Copy dr values from that thread.
752 But only if there were not modified since last stop.
753 PR gdb/2388 */
755 {
756 windows_process.dr[0] = th->wow64_context.Dr0;
757 windows_process.dr[1] = th->wow64_context.Dr1;
758 windows_process.dr[2] = th->wow64_context.Dr2;
759 windows_process.dr[3] = th->wow64_context.Dr3;
760 windows_process.dr[6] = th->wow64_context.Dr6;
761 windows_process.dr[7] = th->wow64_context.Dr7;
762 }
763 }
764 else
765#endif
766 {
767 th->context.ContextFlags = CONTEXT_DEBUGGER_DR;
768 CHECK (GetThreadContext (th->h, &th->context));
769 /* Copy dr values from that thread.
770 But only if there were not modified since last stop.
771 PR gdb/2388 */
773 {
774 windows_process.dr[0] = th->context.Dr0;
775 windows_process.dr[1] = th->context.Dr1;
776 windows_process.dr[2] = th->context.Dr2;
777 windows_process.dr[3] = th->context.Dr3;
778 windows_process.dr[6] = th->context.Dr6;
779 windows_process.dr[7] = th->context.Dr7;
780 }
781 }
782 th->reload_context = false;
783 }
784
785 if (r < 0)
786 for (r = 0; r < gdbarch_num_regs (regcache->arch()); r++)
788 else
790}
791
792/* Collect the register number R from the given regcache, and store
793 its value into the corresponding area of the given thread's context.
794
795 This function assumes that R is non-negative. A failed assertion
796 assertion is raised if that is not true. */
797
798static void
800 windows_thread_info *th, int r)
801{
802 gdb_assert (r >= 0);
803
804 char *context_ptr = (char *) &th->context;
805#ifdef __x86_64__
806 if (windows_process.wow64_process)
807 context_ptr = (char *) &th->wow64_context;
808#endif
809
810 regcache->raw_collect (r, context_ptr + windows_process.mappings[r]);
811}
812
813/* Store a new register value into the context of the thread tied to
814 REGCACHE. */
815
816void
818{
821
822 /* Check if TH exists. Windows sometimes uses a non-existent
823 thread id in its events. */
824 if (th == NULL)
825 return;
826
827 if (r < 0)
828 for (r = 0; r < gdbarch_num_regs (regcache->arch ()); r++)
830 else
832}
833
834/* See nat/windows-nat.h. */
835
836static windows_solib *
837windows_make_so (const char *name, LPVOID load_addr)
838{
839#ifndef __CYGWIN__
840 char *p;
841 char buf[__PMAX];
842 char cwd[__PMAX];
843 WIN32_FIND_DATA w32_fd;
844 HANDLE h = FindFirstFile(name, &w32_fd);
845
846 if (h == INVALID_HANDLE_VALUE)
847 strcpy (buf, name);
848 else
849 {
850 FindClose (h);
851 strcpy (buf, name);
852 if (GetCurrentDirectory (MAX_PATH + 1, cwd))
853 {
854 p = strrchr (buf, '\\');
855 if (p)
856 p[1] = '\0';
857 SetCurrentDirectory (buf);
858 GetFullPathName (w32_fd.cFileName, MAX_PATH, buf, &p);
859 SetCurrentDirectory (cwd);
860 }
861 }
862 if (strcasecmp (buf, "ntdll.dll") == 0)
863 {
864 GetSystemDirectory (buf, sizeof (buf));
865 strcat (buf, "\\ntdll.dll");
866 }
867#else
868 wchar_t buf[__PMAX];
869
870 buf[0] = 0;
871 if (access (name, F_OK) != 0)
872 {
873 if (strcasecmp (name, "ntdll.dll") == 0)
874 {
875 GetSystemDirectoryW (buf, sizeof (buf) / sizeof (wchar_t));
876 wcscat (buf, L"\\ntdll.dll");
877 }
878 }
879#endif
880 windows_process.solibs.emplace_back ();
881 windows_solib *so = &windows_process.solibs.back ();
882 so->load_addr = load_addr;
883 so->original_name = name;
884#ifndef __CYGWIN__
885 so->name = buf;
886#else
887 if (buf[0])
888 {
889 char cname[SO_NAME_MAX_PATH_SIZE];
890 cygwin_conv_path (CCP_WIN_W_TO_POSIX, buf, cname,
892 so->name = cname;
893 }
894 else
895 {
896 char *rname = realpath (name, NULL);
897 if (rname && strlen (rname) < SO_NAME_MAX_PATH_SIZE)
898 {
899 so->name = rname;
900 free (rname);
901 }
902 else
903 {
904 warning (_("dll path for \"%s\" too long or inaccessible"), name);
905 so->name = so->original_name;
906 }
907 }
908 /* Record cygwin1.dll .text start/end. */
909 size_t len = sizeof ("/cygwin1.dll") - 1;
910 if (so->name.size () >= len
911 && strcasecmp (so->name.c_str () + so->name.size () - len,
912 "/cygwin1.dll") == 0)
913 {
914 asection *text = NULL;
915
916 gdb_bfd_ref_ptr abfd (gdb_bfd_open (so->name.c_str(), "pei-i386"));
917
918 if (abfd == NULL)
919 return so;
920
921 if (bfd_check_format (abfd.get (), bfd_object))
922 text = bfd_get_section_by_name (abfd.get (), ".text");
923
924 if (!text)
925 return so;
926
927 /* The symbols in a dll are offset by 0x1000, which is the
928 offset from 0 of the first byte in an image - because of the
929 file header and the section alignment. */
930 windows_process.cygwin_load_start = (CORE_ADDR) (uintptr_t) ((char *)
931 load_addr + 0x1000);
932 windows_process.cygwin_load_end = windows_process.cygwin_load_start +
933 bfd_section_size (text);
934 }
935#endif
936
937 return so;
938}
939
940/* See nat/windows-nat.h. */
941
942void
943windows_per_inferior::handle_load_dll (const char *dll_name, LPVOID base)
944{
945 windows_solib *solib = windows_make_so (dll_name, base);
946 DEBUG_EVENTS ("Loading dll \"%s\" at %s.", solib->name.c_str (),
947 host_address_to_string (solib->load_addr));
948}
949
950/* See nat/windows-nat.h. */
951
952void
954{
955 LPVOID lpBaseOfDll = current_event.u.UnloadDll.lpBaseOfDll;
956
957 auto iter = std::remove_if (windows_process.solibs.begin (),
958 windows_process.solibs.end (),
959 [&] (windows_solib &lib)
960 {
961 if (lib.load_addr == lpBaseOfDll)
962 {
963 DEBUG_EVENTS ("Unloading dll \"%s\".", lib.name.c_str ());
964 return true;
965 }
966 return false;
967 });
968
969 if (iter != windows_process.solibs.end ())
970 {
971 windows_process.solibs.erase (iter, windows_process.solibs.end ());
972 return;
973 }
974
975 /* We did not find any DLL that was previously loaded at this address,
976 so register a complaint. We do not report an error, because we have
977 observed that this may be happening under some circumstances. For
978 instance, running 32bit applications on x64 Windows causes us to receive
979 4 mysterious UNLOAD_DLL_DEBUG_EVENTs during the startup phase (these
980 events are apparently caused by the WOW layer, the interface between
981 32bit and 64bit worlds). */
982 complaint (_("dll starting at %s not found."),
983 host_address_to_string (lpBaseOfDll));
984}
985
986/* Clear list of loaded DLLs. */
987static void
989{
990 windows_process.solibs.clear ();
991}
992
993static void
994signal_event_command (const char *args, int from_tty)
995{
996 uintptr_t event_id = 0;
997 char *endargs = NULL;
998
999 if (args == NULL)
1000 error (_("signal-event requires an argument (integer event id)"));
1001
1002 event_id = strtoumax (args, &endargs, 10);
1003
1004 if ((errno == ERANGE) || (event_id == 0) || (event_id > UINTPTR_MAX) ||
1005 ((HANDLE) event_id == INVALID_HANDLE_VALUE))
1006 error (_("Failed to convert `%s' to event id"), args);
1007
1008 SetEvent ((HANDLE) event_id);
1009 CloseHandle ((HANDLE) event_id);
1010}
1011
1012/* See nat/windows-nat.h. */
1013
1014int
1016 (struct target_waitstatus *ourstatus)
1017{
1018 int retval = 0;
1019
1020 gdb::unique_xmalloc_ptr<char> s
1022 ((CORE_ADDR) (uintptr_t) current_event.u.DebugString.lpDebugStringData,
1023 1024));
1024 if (s == nullptr || !*(s.get ()))
1025 /* nothing to do */;
1026 else if (!startswith (s.get (), _CYGWIN_SIGNAL_STRING))
1027 {
1028#ifdef __CYGWIN__
1029 if (!startswith (s.get (), "cYg"))
1030#endif
1031 {
1032 char *p = strchr (s.get (), '\0');
1033
1034 if (p > s.get () && *--p == '\n')
1035 *p = '\0';
1036 warning (("%s"), s.get ());
1037 }
1038 }
1039#ifdef __CYGWIN__
1040 else
1041 {
1042 /* Got a cygwin signal marker. A cygwin signal is followed by
1043 the signal number itself and then optionally followed by the
1044 thread id and address to saved context within the DLL. If
1045 these are supplied, then the given thread is assumed to have
1046 issued the signal and the context from the thread is assumed
1047 to be stored at the given address in the inferior. Tell gdb
1048 to treat this like a real signal. */
1049 char *p;
1050 int sig = strtol (s.get () + sizeof (_CYGWIN_SIGNAL_STRING) - 1, &p, 0);
1051 gdb_signal gotasig = gdb_signal_from_host (sig);
1052
1053 if (gotasig)
1054 {
1055 LPCVOID x;
1056 SIZE_T n;
1057
1058 ourstatus->set_stopped (gotasig);
1059 retval = strtoul (p, &p, 0);
1060 if (!retval)
1061 retval = current_event.dwThreadId;
1062 else if ((x = (LPCVOID) (uintptr_t) strtoull (p, NULL, 0))
1063 && ReadProcessMemory (handle, x,
1064 &saved_context,
1065 __COPY_CONTEXT_SIZE, &n)
1066 && n == __COPY_CONTEXT_SIZE)
1068 }
1069 }
1070#endif
1071
1072 return retval;
1073}
1074
1075static int
1076display_selector (HANDLE thread, DWORD sel)
1077{
1078 LDT_ENTRY info;
1079 BOOL ret;
1080#ifdef __x86_64__
1081 if (windows_process.wow64_process)
1082 ret = Wow64GetThreadSelectorEntry (thread, sel, &info);
1083 else
1084#endif
1085 ret = GetThreadSelectorEntry (thread, sel, &info);
1086 if (ret)
1087 {
1088 int base, limit;
1089 gdb_printf ("0x%03x: ", (unsigned) sel);
1090 if (!info.HighWord.Bits.Pres)
1091 {
1092 gdb_puts ("Segment not present\n");
1093 return 0;
1094 }
1095 base = (info.HighWord.Bits.BaseHi << 24) +
1096 (info.HighWord.Bits.BaseMid << 16)
1097 + info.BaseLow;
1098 limit = (info.HighWord.Bits.LimitHi << 16) + info.LimitLow;
1099 if (info.HighWord.Bits.Granularity)
1100 limit = (limit << 12) | 0xfff;
1101 gdb_printf ("base=0x%08x limit=0x%08x", base, limit);
1102 if (info.HighWord.Bits.Default_Big)
1103 gdb_puts(" 32-bit ");
1104 else
1105 gdb_puts(" 16-bit ");
1106 switch ((info.HighWord.Bits.Type & 0xf) >> 1)
1107 {
1108 case 0:
1109 gdb_puts ("Data (Read-Only, Exp-up");
1110 break;
1111 case 1:
1112 gdb_puts ("Data (Read/Write, Exp-up");
1113 break;
1114 case 2:
1115 gdb_puts ("Unused segment (");
1116 break;
1117 case 3:
1118 gdb_puts ("Data (Read/Write, Exp-down");
1119 break;
1120 case 4:
1121 gdb_puts ("Code (Exec-Only, N.Conf");
1122 break;
1123 case 5:
1124 gdb_puts ("Code (Exec/Read, N.Conf");
1125 break;
1126 case 6:
1127 gdb_puts ("Code (Exec-Only, Conf");
1128 break;
1129 case 7:
1130 gdb_puts ("Code (Exec/Read, Conf");
1131 break;
1132 default:
1133 gdb_printf ("Unknown type 0x%lx",
1134 (unsigned long) info.HighWord.Bits.Type);
1135 }
1136 if ((info.HighWord.Bits.Type & 0x1) == 0)
1137 gdb_puts(", N.Acc");
1138 gdb_puts (")\n");
1139 if ((info.HighWord.Bits.Type & 0x10) == 0)
1140 gdb_puts("System selector ");
1141 gdb_printf ("Privilege level = %ld. ",
1142 (unsigned long) info.HighWord.Bits.Dpl);
1143 if (info.HighWord.Bits.Granularity)
1144 gdb_puts ("Page granular.\n");
1145 else
1146 gdb_puts ("Byte granular.\n");
1147 return 1;
1148 }
1149 else
1150 {
1151 DWORD err = GetLastError ();
1152 if (err == ERROR_NOT_SUPPORTED)
1153 gdb_printf ("Function not supported\n");
1154 else
1155 gdb_printf ("Invalid selector 0x%x.\n", (unsigned) sel);
1156 return 0;
1157 }
1158}
1159
1160static void
1161display_selectors (const char * args, int from_tty)
1162{
1163 if (inferior_ptid == null_ptid)
1164 {
1165 gdb_puts ("Impossible to display selectors now.\n");
1166 return;
1167 }
1168
1169 windows_thread_info *current_windows_thread
1171
1172 if (!args)
1173 {
1174#ifdef __x86_64__
1175 if (windows_process.wow64_process)
1176 {
1177 gdb_puts ("Selector $cs\n");
1178 display_selector (current_windows_thread->h,
1179 current_windows_thread->wow64_context.SegCs);
1180 gdb_puts ("Selector $ds\n");
1181 display_selector (current_windows_thread->h,
1182 current_windows_thread->wow64_context.SegDs);
1183 gdb_puts ("Selector $es\n");
1184 display_selector (current_windows_thread->h,
1185 current_windows_thread->wow64_context.SegEs);
1186 gdb_puts ("Selector $ss\n");
1187 display_selector (current_windows_thread->h,
1188 current_windows_thread->wow64_context.SegSs);
1189 gdb_puts ("Selector $fs\n");
1190 display_selector (current_windows_thread->h,
1191 current_windows_thread->wow64_context.SegFs);
1192 gdb_puts ("Selector $gs\n");
1193 display_selector (current_windows_thread->h,
1194 current_windows_thread->wow64_context.SegGs);
1195 }
1196 else
1197#endif
1198 {
1199 gdb_puts ("Selector $cs\n");
1200 display_selector (current_windows_thread->h,
1201 current_windows_thread->context.SegCs);
1202 gdb_puts ("Selector $ds\n");
1203 display_selector (current_windows_thread->h,
1204 current_windows_thread->context.SegDs);
1205 gdb_puts ("Selector $es\n");
1206 display_selector (current_windows_thread->h,
1207 current_windows_thread->context.SegEs);
1208 gdb_puts ("Selector $ss\n");
1209 display_selector (current_windows_thread->h,
1210 current_windows_thread->context.SegSs);
1211 gdb_puts ("Selector $fs\n");
1212 display_selector (current_windows_thread->h,
1213 current_windows_thread->context.SegFs);
1214 gdb_puts ("Selector $gs\n");
1215 display_selector (current_windows_thread->h,
1216 current_windows_thread->context.SegGs);
1217 }
1218 }
1219 else
1220 {
1221 int sel;
1222 sel = parse_and_eval_long (args);
1223 gdb_printf ("Selector \"%s\"\n",args);
1224 display_selector (current_windows_thread->h, sel);
1225 }
1226}
1227
1228/* See nat/windows-nat.h. */
1229
1230bool
1232 (const EXCEPTION_RECORD *rec)
1233{
1234#ifdef __CYGWIN__
1235 /* See if the access violation happened within the cygwin DLL
1236 itself. Cygwin uses a kind of exception handling to deal with
1237 passed-in invalid addresses. gdb should not treat these as real
1238 SEGVs since they will be silently handled by cygwin. A real SEGV
1239 will (theoretically) be caught by cygwin later in the process and
1240 will be sent as a cygwin-specific-signal. So, ignore SEGVs if
1241 they show up within the text segment of the DLL itself. */
1242 const char *fn;
1243 CORE_ADDR addr = (CORE_ADDR) (uintptr_t) rec->ExceptionAddress;
1244
1245 if ((!cygwin_exceptions && (addr >= cygwin_load_start
1246 && addr < cygwin_load_end))
1247 || (find_pc_partial_function (addr, &fn, NULL, NULL)
1248 && startswith (fn, "KERNEL32!IsBad")))
1249 return true;
1250#endif
1251 return false;
1252}
1253
1254/* Resume thread specified by ID, or all artificially suspended
1255 threads, if we are continuing execution. KILLED non-zero means we
1256 have killed the inferior, so we should ignore weird errors due to
1257 threads shutting down. LAST_CALL is true if we expect this to be
1258 the last call to continue the inferior -- we are either mourning it
1259 or detaching. */
1260BOOL
1261windows_nat_target::windows_continue (DWORD continue_status, int id,
1262 int killed, bool last_call)
1263{
1265
1267 {
1268 /* There's no need to really continue, because there's already
1269 another event pending. However, we do need to inform the
1270 event loop of this. */
1272 return TRUE;
1273 }
1274
1275 for (auto &th : windows_process.thread_list)
1276 if (id == -1 || id == (int) th->tid)
1277 {
1278#ifdef __x86_64__
1279 if (windows_process.wow64_process)
1280 {
1281 if (th->debug_registers_changed)
1282 {
1283 th->wow64_context.ContextFlags |= CONTEXT_DEBUG_REGISTERS;
1284 th->wow64_context.Dr0 = windows_process.dr[0];
1285 th->wow64_context.Dr1 = windows_process.dr[1];
1286 th->wow64_context.Dr2 = windows_process.dr[2];
1287 th->wow64_context.Dr3 = windows_process.dr[3];
1288 th->wow64_context.Dr6 = DR6_CLEAR_VALUE;
1289 th->wow64_context.Dr7 = windows_process.dr[7];
1290 th->debug_registers_changed = false;
1291 }
1292 if (th->wow64_context.ContextFlags)
1293 {
1294 DWORD ec = 0;
1295
1296 if (GetExitCodeThread (th->h, &ec)
1297 && ec == STILL_ACTIVE)
1298 {
1300 &th->wow64_context);
1301
1302 if (!killed)
1303 CHECK (status);
1304 }
1305 th->wow64_context.ContextFlags = 0;
1306 }
1307 }
1308 else
1309#endif
1310 {
1311 if (th->debug_registers_changed)
1312 {
1313 th->context.ContextFlags |= CONTEXT_DEBUG_REGISTERS;
1314 th->context.Dr0 = windows_process.dr[0];
1315 th->context.Dr1 = windows_process.dr[1];
1316 th->context.Dr2 = windows_process.dr[2];
1317 th->context.Dr3 = windows_process.dr[3];
1318 th->context.Dr6 = DR6_CLEAR_VALUE;
1319 th->context.Dr7 = windows_process.dr[7];
1320 th->debug_registers_changed = false;
1321 }
1322 if (th->context.ContextFlags)
1323 {
1324 DWORD ec = 0;
1325
1326 if (GetExitCodeThread (th->h, &ec)
1327 && ec == STILL_ACTIVE)
1328 {
1329 BOOL status = SetThreadContext (th->h, &th->context);
1330
1331 if (!killed)
1332 CHECK (status);
1333 }
1334 th->context.ContextFlags = 0;
1335 }
1336 }
1337 th->resume ();
1338 }
1339 else
1340 {
1341 /* When single-stepping a specific thread, other threads must
1342 be suspended. */
1343 th->suspend ();
1344 }
1345
1346 gdb::optional<unsigned> err;
1347 do_synchronously ([&] ()
1348 {
1349 if (!continue_last_debug_event (continue_status, debug_events))
1350 err = (unsigned) GetLastError ();
1351 /* On the last call, do not block waiting for an event that will
1352 never come. */
1353 return !last_call;
1354 });
1355
1356 if (err.has_value ())
1357 error (_("Failed to resume program execution"
1358 " (ContinueDebugEvent failed, error %u: %s)"),
1359 *err, strwinerror (*err));
1360
1361 return TRUE;
1362}
1363
1364/* Called in pathological case where Windows fails to send a
1365 CREATE_PROCESS_DEBUG_EVENT after an attach. */
1366DWORD
1368{
1370 = OpenProcess (PROCESS_ALL_ACCESS, FALSE,
1371 windows_process.current_event.dwProcessId);
1372 if (windows_process.handle != NULL)
1374 else
1375 {
1376 unsigned err = (unsigned) GetLastError ();
1377 error (_("OpenProcess call failed, GetLastError = %u: %s"),
1378 err, strwinerror (err));
1379 /* We can not debug anything in that case. */
1380 }
1381 add_thread (ptid_t (windows_process.current_event.dwProcessId, 0,
1382 windows_process.current_event.dwThreadId),
1383 windows_process.current_event.u.CreateThread.hThread,
1384 windows_process.current_event.u.CreateThread.lpThreadLocalBase,
1385 true /* main_thread_p */);
1386 return windows_process.current_event.dwThreadId;
1387}
1388
1389void
1390windows_nat_target::resume (ptid_t ptid, int step, enum gdb_signal sig)
1391{
1393 DWORD continue_status = DBG_CONTINUE;
1394
1395 /* A specific PTID means `step only this thread id'. */
1396 int resume_all = ptid == minus_one_ptid;
1397
1398 /* If we're continuing all threads, it's the current inferior that
1399 should be handled specially. */
1400 if (resume_all)
1401 ptid = inferior_ptid;
1402
1403 if (sig != GDB_SIGNAL_0)
1404 {
1405 if (windows_process.current_event.dwDebugEventCode
1406 != EXCEPTION_DEBUG_EVENT)
1407 {
1408 DEBUG_EXCEPT ("Cannot continue with signal %d here.", sig);
1409 }
1410 else if (sig == windows_process.last_sig)
1411 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1412 else
1413#if 0
1414/* This code does not seem to work, because
1415 the kernel does probably not consider changes in the ExceptionRecord
1416 structure when passing the exception to the inferior.
1417 Note that this seems possible in the exception handler itself. */
1418 {
1419 for (const xlate_exception &x : xlate)
1420 if (x.us == sig)
1421 {
1422 current_event.u.Exception.ExceptionRecord.ExceptionCode
1423 = x.them;
1424 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1425 break;
1426 }
1427 if (continue_status == DBG_CONTINUE)
1428 {
1429 DEBUG_EXCEPT ("Cannot continue with signal %d.", sig);
1430 }
1431 }
1432#endif
1433 DEBUG_EXCEPT ("Can only continue with received signal %d.",
1435 }
1436
1437 windows_process.last_sig = GDB_SIGNAL_0;
1438
1439 DEBUG_EXEC ("pid=%d, tid=0x%x, step=%d, sig=%d",
1440 ptid.pid (), (unsigned) ptid.lwp (), step, sig);
1441
1442 /* Get context for currently selected thread. */
1444 if (th)
1445 {
1446#ifdef __x86_64__
1447 if (windows_process.wow64_process)
1448 {
1449 if (step)
1450 {
1451 /* Single step by setting t bit. */
1453 struct gdbarch *gdbarch = regcache->arch ();
1455 th->wow64_context.EFlags |= FLAG_TRACE_BIT;
1456 }
1457
1458 if (th->wow64_context.ContextFlags)
1459 {
1461 {
1462 th->wow64_context.Dr0 = windows_process.dr[0];
1463 th->wow64_context.Dr1 = windows_process.dr[1];
1464 th->wow64_context.Dr2 = windows_process.dr[2];
1465 th->wow64_context.Dr3 = windows_process.dr[3];
1466 th->wow64_context.Dr6 = DR6_CLEAR_VALUE;
1467 th->wow64_context.Dr7 = windows_process.dr[7];
1468 th->debug_registers_changed = false;
1469 }
1470 CHECK (Wow64SetThreadContext (th->h, &th->wow64_context));
1471 th->wow64_context.ContextFlags = 0;
1472 }
1473 }
1474 else
1475#endif
1476 {
1477 if (step)
1478 {
1479 /* Single step by setting t bit. */
1481 struct gdbarch *gdbarch = regcache->arch ();
1483 th->context.EFlags |= FLAG_TRACE_BIT;
1484 }
1485
1486 if (th->context.ContextFlags)
1487 {
1489 {
1490 th->context.Dr0 = windows_process.dr[0];
1491 th->context.Dr1 = windows_process.dr[1];
1492 th->context.Dr2 = windows_process.dr[2];
1493 th->context.Dr3 = windows_process.dr[3];
1494 th->context.Dr6 = DR6_CLEAR_VALUE;
1495 th->context.Dr7 = windows_process.dr[7];
1496 th->debug_registers_changed = false;
1497 }
1498 CHECK (SetThreadContext (th->h, &th->context));
1499 th->context.ContextFlags = 0;
1500 }
1501 }
1502 }
1503
1504 /* Allow continuing with the same signal that interrupted us.
1505 Otherwise complain. */
1506
1507 if (resume_all)
1508 windows_continue (continue_status, -1, 0);
1509 else
1510 windows_continue (continue_status, ptid.lwp (), 0);
1511}
1512
1513/* Interrupt the inferior. */
1514
1515void
1517{
1518 DEBUG_EVENTS ("interrupt");
1519#ifdef __x86_64__
1520 if (windows_process.wow64_process)
1521 {
1522 /* Call DbgUiRemoteBreakin of the 32bit ntdll.dll in the target process.
1523 DebugBreakProcess would call the one of the 64bit ntdll.dll, which
1524 can't be correctly handled by gdb. */
1525 if (windows_process.wow64_dbgbreak == nullptr)
1526 {
1527 CORE_ADDR addr;
1528 if (!find_minimal_symbol_address ("ntdll!DbgUiRemoteBreakin",
1529 &addr, 0))
1530 windows_process.wow64_dbgbreak = (void *) addr;
1531 }
1532
1533 if (windows_process.wow64_dbgbreak != nullptr)
1534 {
1535 HANDLE thread = CreateRemoteThread (windows_process.handle, NULL,
1536 0, (LPTHREAD_START_ROUTINE)
1537 windows_process.wow64_dbgbreak,
1538 NULL, 0, NULL);
1539 if (thread)
1540 {
1541 CloseHandle (thread);
1542 return;
1543 }
1544 }
1545 }
1546 else
1547#endif
1549 return;
1550 warning (_("Could not interrupt program. "
1551 "Press Ctrl-c in the program console."));
1552}
1553
1554void
1556{
1557 interrupt ();
1558}
1559
1560/* Get the next event from the child. Returns the thread ptid. */
1561
1562ptid_t
1564 (int pid, struct target_waitstatus *ourstatus, target_wait_flags options)
1565{
1566 DWORD continue_status, event_code;
1567 DWORD thread_id = 0;
1568
1569 /* If there is a relevant pending stop, report it now. See the
1570 comment by the definition of "pending_stops" for details on why
1571 this is needed. */
1572 gdb::optional<pending_stop> stop
1574 if (stop.has_value ())
1575 {
1576 thread_id = stop->thread_id;
1577 *ourstatus = stop->status;
1578
1579 ptid_t ptid (windows_process.current_event.dwProcessId, thread_id);
1582 th->reload_context = true;
1583
1584 return ptid;
1585 }
1586
1587 windows_process.last_sig = GDB_SIGNAL_0;
1588 DEBUG_EVENT *current_event = &windows_process.current_event;
1589
1590 if ((options & TARGET_WNOHANG) != 0 && !m_debug_event_pending)
1591 {
1592 ourstatus->set_ignore ();
1593 return minus_one_ptid;
1594 }
1595
1597
1598 continue_status = DBG_CONTINUE;
1599
1600 event_code = windows_process.current_event.dwDebugEventCode;
1601 ourstatus->set_spurious ();
1603
1604 switch (event_code)
1605 {
1606 case CREATE_THREAD_DEBUG_EVENT:
1607 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1608 (unsigned) current_event->dwProcessId,
1609 (unsigned) current_event->dwThreadId,
1610 "CREATE_THREAD_DEBUG_EVENT");
1611 if (windows_process.saw_create != 1)
1612 {
1613 inferior *inf = find_inferior_pid (this, current_event->dwProcessId);
1614 if (!windows_process.saw_create && inf->attach_flag)
1615 {
1616 /* Kludge around a Windows bug where first event is a create
1617 thread event. Caused when attached process does not have
1618 a main thread. */
1619 thread_id = fake_create_process ();
1620 if (thread_id)
1622 }
1623 break;
1624 }
1625 /* Record the existence of this thread. */
1626 thread_id = current_event->dwThreadId;
1628 (ptid_t (current_event->dwProcessId, current_event->dwThreadId, 0),
1629 current_event->u.CreateThread.hThread,
1630 current_event->u.CreateThread.lpThreadLocalBase,
1631 false /* main_thread_p */);
1632
1633 break;
1634
1635 case EXIT_THREAD_DEBUG_EVENT:
1636 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1637 (unsigned) current_event->dwProcessId,
1638 (unsigned) current_event->dwThreadId,
1639 "EXIT_THREAD_DEBUG_EVENT");
1640 delete_thread (ptid_t (current_event->dwProcessId,
1641 current_event->dwThreadId, 0),
1642 current_event->u.ExitThread.dwExitCode,
1643 false /* main_thread_p */);
1644 break;
1645
1646 case CREATE_PROCESS_DEBUG_EVENT:
1647 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1648 (unsigned) current_event->dwProcessId,
1649 (unsigned) current_event->dwThreadId,
1650 "CREATE_PROCESS_DEBUG_EVENT");
1651 CloseHandle (current_event->u.CreateProcessInfo.hFile);
1652 if (++windows_process.saw_create != 1)
1653 break;
1654
1655 windows_process.handle = current_event->u.CreateProcessInfo.hProcess;
1656 /* Add the main thread. */
1658 (ptid_t (current_event->dwProcessId,
1659 current_event->dwThreadId, 0),
1660 current_event->u.CreateProcessInfo.hThread,
1661 current_event->u.CreateProcessInfo.lpThreadLocalBase,
1662 true /* main_thread_p */);
1663 thread_id = current_event->dwThreadId;
1664 break;
1665
1666 case EXIT_PROCESS_DEBUG_EVENT:
1667 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1668 (unsigned) current_event->dwProcessId,
1669 (unsigned) current_event->dwThreadId,
1670 "EXIT_PROCESS_DEBUG_EVENT");
1672 {
1675 error (_("During startup program exited with code 0x%x."),
1676 (unsigned int) current_event->u.ExitProcess.dwExitCode);
1677 }
1678 else if (windows_process.saw_create == 1)
1679 {
1680 delete_thread (ptid_t (current_event->dwProcessId,
1681 current_event->dwThreadId, 0),
1682 0, true /* main_thread_p */);
1683 DWORD exit_status = current_event->u.ExitProcess.dwExitCode;
1684 /* If the exit status looks like a fatal exception, but we
1685 don't recognize the exception's code, make the original
1686 exit status value available, to avoid losing
1687 information. */
1688 int exit_signal
1689 = WIFSIGNALED (exit_status) ? WTERMSIG (exit_status) : -1;
1690 if (exit_signal == -1)
1691 ourstatus->set_exited (exit_status);
1692 else
1693 ourstatus->set_signalled (gdb_signal_from_host (exit_signal));
1694
1695 thread_id = current_event->dwThreadId;
1696 }
1697 break;
1698
1699 case LOAD_DLL_DEBUG_EVENT:
1700 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1701 (unsigned) current_event->dwProcessId,
1702 (unsigned) current_event->dwThreadId,
1703 "LOAD_DLL_DEBUG_EVENT");
1704 CloseHandle (current_event->u.LoadDll.hFile);
1707 break;
1708 try
1709 {
1711 }
1712 catch (const gdb_exception &ex)
1713 {
1715 }
1716 ourstatus->set_loaded ();
1717 thread_id = current_event->dwThreadId;
1718 break;
1719
1720 case UNLOAD_DLL_DEBUG_EVENT:
1721 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1722 (unsigned) current_event->dwProcessId,
1723 (unsigned) current_event->dwThreadId,
1724 "UNLOAD_DLL_DEBUG_EVENT");
1727 break;
1728 try
1729 {
1731 }
1732 catch (const gdb_exception &ex)
1733 {
1735 }
1736 ourstatus->set_loaded ();
1737 thread_id = current_event->dwThreadId;
1738 break;
1739
1740 case EXCEPTION_DEBUG_EVENT:
1741 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1742 (unsigned) current_event->dwProcessId,
1743 (unsigned) current_event->dwThreadId,
1744 "EXCEPTION_DEBUG_EVENT");
1745 if (windows_process.saw_create != 1)
1746 break;
1748 {
1750 default:
1751 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1752 break;
1754 thread_id = current_event->dwThreadId;
1755 break;
1757 continue_status = DBG_CONTINUE;
1758 break;
1759 }
1760 break;
1761
1762 case OUTPUT_DEBUG_STRING_EVENT: /* Message from the kernel. */
1763 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
1764 (unsigned) current_event->dwProcessId,
1765 (unsigned) current_event->dwThreadId,
1766 "OUTPUT_DEBUG_STRING_EVENT");
1767 if (windows_process.saw_create != 1)
1768 break;
1769 thread_id = windows_process.handle_output_debug_string (ourstatus);
1770 break;
1771
1772 default:
1773 if (windows_process.saw_create != 1)
1774 break;
1775 gdb_printf ("gdb: kernel event for pid=%u tid=0x%x\n",
1776 (unsigned) current_event->dwProcessId,
1777 (unsigned) current_event->dwThreadId);
1778 gdb_printf (" unknown event code %u\n",
1779 (unsigned) current_event->dwDebugEventCode);
1780 break;
1781 }
1782
1783 if (!thread_id || windows_process.saw_create != 1)
1784 {
1785 CHECK (windows_continue (continue_status,
1787 }
1790 {
1791 /* Pending stop. See the comment by the definition of
1792 "pending_stops" for details on why this is needed. */
1793 DEBUG_EVENTS ("get_windows_debug_event - "
1794 "unexpected stop in 0x%x (expecting 0x%x)",
1796
1797 if (current_event->dwDebugEventCode == EXCEPTION_DEBUG_EVENT
1798 && ((current_event->u.Exception.ExceptionRecord.ExceptionCode
1799 == EXCEPTION_BREAKPOINT)
1800 || (current_event->u.Exception.ExceptionRecord.ExceptionCode
1803 {
1804 ptid_t ptid = ptid_t (current_event->dwProcessId, thread_id, 0);
1808 th->pc_adjusted = false;
1809 }
1811 ({thread_id, *ourstatus, windows_process.current_event});
1812 thread_id = 0;
1813 CHECK (windows_continue (continue_status,
1815 }
1816
1817 if (thread_id == 0)
1818 return null_ptid;
1819 return ptid_t (windows_process.current_event.dwProcessId, thread_id, 0);
1820}
1821
1822/* Wait for interesting events to occur in the target process. */
1823ptid_t
1824windows_nat_target::wait (ptid_t ptid, struct target_waitstatus *ourstatus,
1825 target_wait_flags options)
1826{
1827 int pid = -1;
1828
1829 /* We loop when we get a non-standard exception rather than return
1830 with a SPURIOUS because resume can try and step or modify things,
1831 which needs a current_thread->h. But some of these exceptions mark
1832 the birth or death of threads, which mean that the current thread
1833 isn't necessarily what you think it is. */
1834
1835 while (1)
1836 {
1837 ptid_t result = get_windows_debug_event (pid, ourstatus, options);
1838
1839 if (result != null_ptid)
1840 {
1841 if (ourstatus->kind () != TARGET_WAITKIND_EXITED
1842 && ourstatus->kind () != TARGET_WAITKIND_SIGNALLED)
1843 {
1846
1847 if (th != nullptr)
1848 {
1850 if (windows_process.current_event.dwDebugEventCode
1851 == EXCEPTION_DEBUG_EVENT
1852 && ((windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
1853 == EXCEPTION_BREAKPOINT)
1854 || (windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
1857 {
1859 th->pc_adjusted = false;
1860 }
1861 }
1862 }
1863
1864 return result;
1865 }
1866 else
1867 {
1868 int detach = 0;
1869
1870 if (deprecated_ui_loop_hook != NULL)
1872
1873 if (detach)
1874 kill ();
1875 }
1876 }
1877}
1878
1879void
1881{
1882 int i;
1883 struct inferior *inf;
1884
1885 windows_process.last_sig = GDB_SIGNAL_0;
1887 for (i = 0;
1888 i < sizeof (windows_process.dr) / sizeof (windows_process.dr[0]);
1889 i++)
1890 windows_process.dr[i] = 0;
1891#ifdef __CYGWIN__
1892 windows_process.cygwin_load_start = 0;
1893 windows_process.cygwin_load_end = 0;
1894#endif
1895 windows_process.current_event.dwProcessId = pid;
1896 memset (&windows_process.current_event, 0,
1898 inf = current_inferior ();
1899 if (!inf->target_is_pushed (this))
1900 inf->push_target (this);
1905
1906#ifdef __x86_64__
1907 windows_process.ignore_first_breakpoint
1908 = !attaching && windows_process.wow64_process;
1909
1910 if (!windows_process.wow64_process)
1911 {
1914 }
1915 else
1916#endif
1917 {
1920 }
1921
1923 inf->attach_flag = attaching;
1924
1927
1929
1930 ptid_t last_ptid;
1931
1932 while (1)
1933 {
1935
1936 last_ptid = this->wait (minus_one_ptid, &status, 0);
1937
1938 /* Note windows_wait returns TARGET_WAITKIND_SPURIOUS for thread
1939 events. */
1940 if (status.kind () != TARGET_WAITKIND_LOADED
1941 && status.kind () != TARGET_WAITKIND_SPURIOUS)
1942 break;
1943
1944 this->resume (minus_one_ptid, 0, GDB_SIGNAL_0);
1945 }
1946
1947 switch_to_thread (find_thread_ptid (this, last_ptid));
1948
1949 /* Now that the inferior has been started and all DLLs have been mapped,
1950 we can iterate over all DLLs and load them in.
1951
1952 We avoid doing it any earlier because, on certain versions of Windows,
1953 LOAD_DLL_DEBUG_EVENTs are sometimes not complete. In particular,
1954 we have seen on Windows 8.1 that the ntdll.dll load event does not
1955 include the DLL name, preventing us from creating an associated SO.
1956 A possible explanation is that ntdll.dll might be mapped before
1957 the SO info gets created by the Windows system -- ntdll.dll is
1958 the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs
1959 do not seem to suffer from that problem.
1960
1961 Rather than try to work around this sort of issue, it is much
1962 simpler to just ignore DLL load/unload events during the startup
1963 phase, and then process them all in one batch now. */
1965
1967 return;
1968}
1969
1970/* Try to set or remove a user privilege to the current process. Return -1
1971 if that fails, the previous setting of that privilege otherwise.
1972
1973 This code is copied from the Cygwin source code and rearranged to allow
1974 dynamically loading of the needed symbols from advapi32 which is only
1975 available on NT/2K/XP. */
1976static int
1977set_process_privilege (const char *privilege, BOOL enable)
1978{
1979 HANDLE token_hdl = NULL;
1980 LUID restore_priv;
1981 TOKEN_PRIVILEGES new_priv, orig_priv;
1982 int ret = -1;
1983 DWORD size;
1984
1985 if (!OpenProcessToken (GetCurrentProcess (),
1986 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
1987 &token_hdl))
1988 goto out;
1989
1990 if (!LookupPrivilegeValueA (NULL, privilege, &restore_priv))
1991 goto out;
1992
1993 new_priv.PrivilegeCount = 1;
1994 new_priv.Privileges[0].Luid = restore_priv;
1995 new_priv.Privileges[0].Attributes = enable ? SE_PRIVILEGE_ENABLED : 0;
1996
1997 if (!AdjustTokenPrivileges (token_hdl, FALSE, &new_priv,
1998 sizeof orig_priv, &orig_priv, &size))
1999 goto out;
2000#if 0
2001 /* Disabled, otherwise every `attach' in an unprivileged user session
2002 would raise the "Failed to get SE_DEBUG_NAME privilege" warning in
2003 windows_attach(). */
2004 /* AdjustTokenPrivileges returns TRUE even if the privilege could not
2005 be enabled. GetLastError () returns an correct error code, though. */
2006 if (enable && GetLastError () == ERROR_NOT_ALL_ASSIGNED)
2007 goto out;
2008#endif
2009
2010 ret = orig_priv.Privileges[0].Attributes == SE_PRIVILEGE_ENABLED ? 1 : 0;
2011
2012out:
2013 if (token_hdl)
2014 CloseHandle (token_hdl);
2015
2016 return ret;
2017}
2018
2019/* Attach to process PID, then initialize for debugging it. */
2020
2021void
2022windows_nat_target::attach (const char *args, int from_tty)
2023{
2024 DWORD pid;
2025
2026 pid = parse_pid_to_attach (args);
2027
2028 if (set_process_privilege (SE_DEBUG_NAME, TRUE) < 0)
2029 warning ("Failed to get SE_DEBUG_NAME privilege\n"
2030 "This can cause attach to fail on Windows NT/2K/XP");
2031
2034
2035 gdb::optional<unsigned> err;
2036 do_synchronously ([&] ()
2037 {
2038 BOOL ok = DebugActiveProcess (pid);
2039
2040#ifdef __CYGWIN__
2041 if (!ok)
2042 {
2043 /* Try fall back to Cygwin pid. */
2044 pid = cygwin_internal (CW_CYGWIN_PID_TO_WINPID, pid);
2045
2046 if (pid > 0)
2047 ok = DebugActiveProcess (pid);
2048 }
2049#endif
2050
2051 if (!ok)
2052 err = (unsigned) GetLastError ();
2053
2054 return true;
2055 });
2056
2057 if (err.has_value ())
2058 error (_("Can't attach to process %u (error %u: %s)"),
2059 (unsigned) pid, *err, strwinerror (*err));
2060
2062
2063 target_announce_attach (from_tty, pid);
2064
2065#ifdef __x86_64__
2066 HANDLE h = OpenProcess (PROCESS_QUERY_INFORMATION, FALSE, pid);
2067 if (h != NULL)
2068 {
2069 BOOL wow64;
2070 if (IsWow64Process (h, &wow64))
2071 windows_process.wow64_process = wow64;
2072 CloseHandle (h);
2073 }
2074#endif
2075
2078}
2079
2080void
2082{
2083 windows_continue (DBG_CONTINUE, -1, 0, true);
2084
2085 gdb::optional<unsigned> err;
2086 do_synchronously ([&] ()
2087 {
2089 err = (unsigned) GetLastError ();
2090 else
2092 return false;
2093 });
2094
2095 if (err.has_value ())
2096 error (_("Can't detach process %u (error %u: %s)"),
2097 (unsigned) windows_process.current_event.dwProcessId,
2098 *err, strwinerror (*err));
2099
2100 target_announce_detach (from_tty);
2101
2105
2107}
2108
2109/* The pid_to_exec_file target_ops method for this platform. */
2110
2111const char *
2113{
2115}
2116
2117/* Print status information about what we're accessing. */
2118
2119void
2121{
2122 struct inferior *inf = current_inferior ();
2123
2124 gdb_printf ("\tUsing the running image of %s %s.\n",
2125 inf->attach_flag ? "attached" : "child",
2126 target_pid_to_str (inferior_ptid).c_str ());
2127}
2128
2129/* Modify CreateProcess parameters for use of a new separate console.
2130 Parameters are:
2131 *FLAGS: DWORD parameter for general process creation flags.
2132 *SI: STARTUPINFO structure, for which the console window size and
2133 console buffer size is filled in if GDB is running in a console.
2134 to create the new console.
2135 The size of the used font is not available on all versions of
2136 Windows OS. Furthermore, the current font might not be the default
2137 font, but this is still better than before.
2138 If the windows and buffer sizes are computed,
2139 SI->DWFLAGS is changed so that this information is used
2140 by CreateProcess function. */
2141
2142static void
2144{
2145 HANDLE hconsole = CreateFile ("CONOUT$", GENERIC_READ | GENERIC_WRITE,
2146 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
2147
2148 if (hconsole != INVALID_HANDLE_VALUE)
2149 {
2150 CONSOLE_SCREEN_BUFFER_INFO sbinfo;
2151 COORD font_size;
2152 CONSOLE_FONT_INFO cfi;
2153
2154 GetCurrentConsoleFont (hconsole, FALSE, &cfi);
2155 font_size = GetConsoleFontSize (hconsole, cfi.nFont);
2156 GetConsoleScreenBufferInfo(hconsole, &sbinfo);
2157 si->dwXSize = sbinfo.srWindow.Right - sbinfo.srWindow.Left + 1;
2158 si->dwYSize = sbinfo.srWindow.Bottom - sbinfo.srWindow.Top + 1;
2159 if (font_size.X)
2160 si->dwXSize *= font_size.X;
2161 else
2162 si->dwXSize *= 8;
2163 if (font_size.Y)
2164 si->dwYSize *= font_size.Y;
2165 else
2166 si->dwYSize *= 12;
2167 si->dwXCountChars = sbinfo.dwSize.X;
2168 si->dwYCountChars = sbinfo.dwSize.Y;
2169 si->dwFlags |= STARTF_USESIZE | STARTF_USECOUNTCHARS;
2170 }
2171 *flags |= CREATE_NEW_CONSOLE;
2172}
2173
2174#ifndef __CYGWIN__
2175/* Function called by qsort to sort environment strings. */
2176
2177static int
2178envvar_cmp (const void *a, const void *b)
2179{
2180 const char **p = (const char **) a;
2181 const char **q = (const char **) b;
2182 return strcasecmp (*p, *q);
2183}
2184#endif
2185
2186#ifdef __CYGWIN__
2187static void
2188clear_win32_environment (char **env)
2189{
2190 int i;
2191 size_t len;
2192 wchar_t *copy = NULL, *equalpos;
2193
2194 for (i = 0; env[i] && *env[i]; i++)
2195 {
2196 len = mbstowcs (NULL, env[i], 0) + 1;
2197 copy = (wchar_t *) xrealloc (copy, len * sizeof (wchar_t));
2198 mbstowcs (copy, env[i], len);
2199 equalpos = wcschr (copy, L'=');
2200 if (equalpos)
2201 *equalpos = L'\0';
2202 SetEnvironmentVariableW (copy, NULL);
2203 }
2204 xfree (copy);
2205}
2206#endif
2207
2208#ifndef __CYGWIN__
2209
2210/* Redirection of inferior I/O streams for native MS-Windows programs.
2211 Unlike on Unix, where this is handled by invoking the inferior via
2212 the shell, on MS-Windows we need to emulate the cmd.exe shell.
2213
2214 The official documentation of the cmd.exe redirection features is here:
2215
2216 http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx
2217
2218 (That page talks about Windows XP, but there's no newer
2219 documentation, so we assume later versions of cmd.exe didn't change
2220 anything.)
2221
2222 Caveat: the documentation on that page seems to include a few lies.
2223 For example, it describes strange constructs 1<&2 and 2<&1, which
2224 seem to work only when 1>&2 resp. 2>&1 would make sense, and so I
2225 think the cmd.exe parser of the redirection symbols simply doesn't
2226 care about the < vs > distinction in these cases. Therefore, the
2227 supported features are explicitly documented below.
2228
2229 The emulation below aims at supporting all the valid use cases
2230 supported by cmd.exe, which include:
2231
2232 < FILE redirect standard input from FILE
2233 0< FILE redirect standard input from FILE
2234 <&N redirect standard input from file descriptor N
2235 0<&N redirect standard input from file descriptor N
2236 > FILE redirect standard output to FILE
2237 >> FILE append standard output to FILE
2238 1>> FILE append standard output to FILE
2239 >&N redirect standard output to file descriptor N
2240 1>&N redirect standard output to file descriptor N
2241 >>&N append standard output to file descriptor N
2242 1>>&N append standard output to file descriptor N
2243 2> FILE redirect standard error to FILE
2244 2>> FILE append standard error to FILE
2245 2>&N redirect standard error to file descriptor N
2246 2>>&N append standard error to file descriptor N
2247
2248 Note that using N > 2 in the above construct is supported, but
2249 requires that the corresponding file descriptor be open by some
2250 means elsewhere or outside GDB. Also note that using ">&0" or
2251 "<&2" will generally fail, because the file descriptor redirected
2252 from is normally open in an incompatible mode (e.g., FD 0 is open
2253 for reading only). IOW, use of such tricks is not recommended;
2254 you are on your own.
2255
2256 We do NOT support redirection of file descriptors above 2, as in
2257 "3>SOME-FILE", because MinGW compiled programs don't (supporting
2258 that needs special handling in the startup code that MinGW
2259 doesn't have). Pipes are also not supported.
2260
2261 As for invalid use cases, where the redirection contains some
2262 error, the emulation below will detect that and produce some
2263 error and/or failure. But the behavior in those cases is not
2264 bug-for-bug compatible with what cmd.exe does in those cases.
2265 That's because what cmd.exe does then is not well defined, and
2266 seems to be a side effect of the cmd.exe parsing of the command
2267 line more than anything else. For example, try redirecting to an
2268 invalid file name, as in "> foo:bar".
2269
2270 There are also minor syntactic deviations from what cmd.exe does
2271 in some corner cases. For example, it doesn't support the likes
2272 of "> &foo" to mean redirect to file named literally "&foo"; we
2273 do support that here, because that, too, sounds like some issue
2274 with the cmd.exe parser. Another nicety is that we support
2275 redirection targets that use file names with forward slashes,
2276 something cmd.exe doesn't -- this comes in handy since GDB
2277 file-name completion can be used when typing the command line for
2278 the inferior. */
2279
2280/* Support routines for redirecting standard handles of the inferior. */
2281
2282/* Parse a single redirection spec, open/duplicate the specified
2283 file/fd, and assign the appropriate value to one of the 3 standard
2284 file descriptors. */
2285static int
2286redir_open (const char *redir_string, int *inp, int *out, int *err)
2287{
2288 int *fd, ref_fd = -2;
2289 int mode;
2290 const char *fname = redir_string + 1;
2291 int rc = *redir_string;
2292
2293 switch (rc)
2294 {
2295 case '0':
2296 fname++;
2297 /* FALLTHROUGH */
2298 case '<':
2299 fd = inp;
2300 mode = O_RDONLY;
2301 break;
2302 case '1': case '2':
2303 fname++;
2304 /* FALLTHROUGH */
2305 case '>':
2306 fd = (rc == '2') ? err : out;
2307 mode = O_WRONLY | O_CREAT;
2308 if (*fname == '>')
2309 {
2310 fname++;
2311 mode |= O_APPEND;
2312 }
2313 else
2314 mode |= O_TRUNC;
2315 break;
2316 default:
2317 return -1;
2318 }
2319
2320 if (*fname == '&' && '0' <= fname[1] && fname[1] <= '9')
2321 {
2322 /* A reference to a file descriptor. */
2323 char *fdtail;
2324 ref_fd = (int) strtol (fname + 1, &fdtail, 10);
2325 if (fdtail > fname + 1 && *fdtail == '\0')
2326 {
2327 /* Don't allow redirection when open modes are incompatible. */
2328 if ((ref_fd == 0 && (fd == out || fd == err))
2329 || ((ref_fd == 1 || ref_fd == 2) && fd == inp))
2330 {
2331 errno = EPERM;
2332 return -1;
2333 }
2334 if (ref_fd == 0)
2335 ref_fd = *inp;
2336 else if (ref_fd == 1)
2337 ref_fd = *out;
2338 else if (ref_fd == 2)
2339 ref_fd = *err;
2340 }
2341 else
2342 {
2343 errno = EBADF;
2344 return -1;
2345 }
2346 }
2347 else
2348 fname++; /* skip the separator space */
2349 /* If the descriptor is already open, close it. This allows
2350 multiple specs of redirections for the same stream, which is
2351 somewhat nonsensical, but still valid and supported by cmd.exe.
2352 (But cmd.exe only opens a single file in this case, the one
2353 specified by the last redirection spec on the command line.) */
2354 if (*fd >= 0)
2355 _close (*fd);
2356 if (ref_fd == -2)
2357 {
2358 *fd = _open (fname, mode, _S_IREAD | _S_IWRITE);
2359 if (*fd < 0)
2360 return -1;
2361 }
2362 else if (ref_fd == -1)
2363 *fd = -1; /* reset to default destination */
2364 else
2365 {
2366 *fd = _dup (ref_fd);
2367 if (*fd < 0)
2368 return -1;
2369 }
2370 /* _open just sets a flag for O_APPEND, which won't be passed to the
2371 inferior, so we need to actually move the file pointer. */
2372 if ((mode & O_APPEND) != 0)
2373 _lseek (*fd, 0L, SEEK_END);
2374 return 0;
2375}
2376
2377/* Canonicalize a single redirection spec and set up the corresponding
2378 file descriptor as specified. */
2379static int
2380redir_set_redirection (const char *s, int *inp, int *out, int *err)
2381{
2382 char buf[__PMAX + 2 + 5]; /* extra space for quotes & redirection string */
2383 char *d = buf;
2384 const char *start = s;
2385 int quote = 0;
2386
2387 *d++ = *s++; /* copy the 1st character, < or > or a digit */
2388 if ((*start == '>' || *start == '1' || *start == '2')
2389 && *s == '>')
2390 {
2391 *d++ = *s++;
2392 if (*s == '>' && *start != '>')
2393 *d++ = *s++;
2394 }
2395 else if (*start == '0' && *s == '<')
2396 *d++ = *s++;
2397 /* cmd.exe recognizes "&N" only immediately after the redirection symbol. */
2398 if (*s != '&')
2399 {
2400 while (isspace (*s)) /* skip whitespace before file name */
2401 s++;
2402 *d++ = ' '; /* separate file name with a single space */
2403 }
2404
2405 /* Copy the file name. */
2406 while (*s)
2407 {
2408 /* Remove quoting characters from the file name in buf[]. */
2409 if (*s == '"') /* could support '..' quoting here */
2410 {
2411 if (!quote)
2412 quote = *s++;
2413 else if (*s == quote)
2414 {
2415 quote = 0;
2416 s++;
2417 }
2418 else
2419 *d++ = *s++;
2420 }
2421 else if (*s == '\\')
2422 {
2423 if (s[1] == '"') /* could support '..' here */
2424 s++;
2425 *d++ = *s++;
2426 }
2427 else if (isspace (*s) && !quote)
2428 break;
2429 else
2430 *d++ = *s++;
2431 if (d - buf >= sizeof (buf) - 1)
2432 {
2433 errno = ENAMETOOLONG;
2434 return 0;
2435 }
2436 }
2437 *d = '\0';
2438
2439 /* Windows doesn't allow redirection characters in file names, so we
2440 can bail out early if they use them, or if there's no target file
2441 name after the redirection symbol. */
2442 if (d[-1] == '>' || d[-1] == '<')
2443 {
2444 errno = ENOENT;
2445 return 0;
2446 }
2447 if (redir_open (buf, inp, out, err) == 0)
2448 return s - start;
2449 return 0;
2450}
2451
2452/* Parse the command line for redirection specs and prepare the file
2453 descriptors for the 3 standard streams accordingly. */
2454static bool
2455redirect_inferior_handles (const char *cmd_orig, char *cmd,
2456 int *inp, int *out, int *err)
2457{
2458 const char *s = cmd_orig;
2459 char *d = cmd;
2460 int quote = 0;
2461 bool retval = false;
2462
2463 while (isspace (*s))
2464 *d++ = *s++;
2465
2466 while (*s)
2467 {
2468 if (*s == '"') /* could also support '..' quoting here */
2469 {
2470 if (!quote)
2471 quote = *s;
2472 else if (*s == quote)
2473 quote = 0;
2474 }
2475 else if (*s == '\\')
2476 {
2477 if (s[1] == '"') /* escaped quote char */
2478 s++;
2479 }
2480 else if (!quote)
2481 {
2482 /* Process a single redirection candidate. */
2483 if (*s == '<' || *s == '>'
2484 || ((*s == '1' || *s == '2') && s[1] == '>')
2485 || (*s == '0' && s[1] == '<'))
2486 {
2487 int skip = redir_set_redirection (s, inp, out, err);
2488
2489 if (skip <= 0)
2490 return false;
2491 retval = true;
2492 s += skip;
2493 }
2494 }
2495 if (*s)
2496 *d++ = *s++;
2497 }
2498 *d = '\0';
2499 return retval;
2500}
2501#endif /* !__CYGWIN__ */
2502
2503/* Start an inferior windows child process and sets inferior_ptid to its pid.
2504 EXEC_FILE is the file to run.
2505 ALLARGS is a string containing the arguments to the program.
2506 ENV is the environment vector to pass. Errors reported with error(). */
2507
2508void
2510 const std::string &origallargs,
2511 char **in_env, int from_tty)
2512{
2513 STARTUPINFO si;
2514#ifdef __CYGWIN__
2515 wchar_t real_path[__PMAX];
2516 wchar_t shell[__PMAX]; /* Path to shell */
2517 wchar_t infcwd[__PMAX];
2518 const char *sh;
2519 wchar_t *toexec;
2520 wchar_t *cygallargs;
2521 wchar_t *args;
2522 char **old_env = NULL;
2523 PWCHAR w32_env;
2524 size_t len;
2525 int tty;
2526 int ostdin, ostdout, ostderr;
2527#else /* !__CYGWIN__ */
2528 char shell[__PMAX]; /* Path to shell */
2529 const char *toexec;
2530 char *args, *allargs_copy;
2531 size_t args_len, allargs_len;
2532 int fd_inp = -1, fd_out = -1, fd_err = -1;
2533 HANDLE tty = INVALID_HANDLE_VALUE;
2534 bool redirected = false;
2535 char *w32env;
2536 char *temp;
2537 size_t envlen;
2538 int i;
2539 size_t envsize;
2540 char **env;
2541#endif /* !__CYGWIN__ */
2542 const char *allargs = origallargs.c_str ();
2543 PROCESS_INFORMATION pi;
2544 gdb::optional<unsigned> ret;
2545 DWORD flags = 0;
2546 const std::string &inferior_tty = current_inferior ()->tty ();
2547
2548 if (!exec_file)
2549 error (_("No executable specified, use `target exec'."));
2550
2551 const char *inferior_cwd = current_inferior ()->cwd ().c_str ();
2552 std::string expanded_infcwd;
2553 if (*inferior_cwd == '\0')
2554 inferior_cwd = nullptr;
2555 else
2556 {
2557 expanded_infcwd = gdb_tilde_expand (inferior_cwd);
2558 /* Mirror slashes on inferior's cwd. */
2559 std::replace (expanded_infcwd.begin (), expanded_infcwd.end (),
2560 '/', '\\');
2561 inferior_cwd = expanded_infcwd.c_str ();
2562 }
2563
2564 memset (&si, 0, sizeof (si));
2565 si.cb = sizeof (si);
2566
2567 if (new_group)
2568 flags |= CREATE_NEW_PROCESS_GROUP;
2569
2570 if (new_console)
2572
2573#ifdef __CYGWIN__
2574 if (!useshell)
2575 {
2576 flags |= DEBUG_ONLY_THIS_PROCESS;
2577 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, exec_file, real_path,
2578 __PMAX * sizeof (wchar_t)) < 0)
2579 error (_("Error starting executable: %d"), errno);
2580 toexec = real_path;
2581 len = mbstowcs (NULL, allargs, 0) + 1;
2582 if (len == (size_t) -1)
2583 error (_("Error starting executable: %d"), errno);
2584 cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
2585 mbstowcs (cygallargs, allargs, len);
2586 }
2587 else
2588 {
2589 sh = get_shell ();
2590 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, sh, shell, __PMAX) < 0)
2591 error (_("Error starting executable via shell: %d"), errno);
2592 len = sizeof (L" -c 'exec '") + mbstowcs (NULL, exec_file, 0)
2593 + mbstowcs (NULL, allargs, 0) + 2;
2594 cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
2595 swprintf (cygallargs, len, L" -c 'exec %s %s'", exec_file, allargs);
2596 toexec = shell;
2597 flags |= DEBUG_PROCESS;
2598 }
2599
2600 if (inferior_cwd != NULL
2601 && cygwin_conv_path (CCP_POSIX_TO_WIN_W, inferior_cwd,
2602 infcwd, strlen (inferior_cwd)) < 0)
2603 error (_("Error converting inferior cwd: %d"), errno);
2604
2605 args = (wchar_t *) alloca ((wcslen (toexec) + wcslen (cygallargs) + 2)
2606 * sizeof (wchar_t));
2607 wcscpy (args, toexec);
2608 wcscat (args, L" ");
2609 wcscat (args, cygallargs);
2610
2611#ifdef CW_CVT_ENV_TO_WINENV
2612 /* First try to create a direct Win32 copy of the POSIX environment. */
2613 w32_env = (PWCHAR) cygwin_internal (CW_CVT_ENV_TO_WINENV, in_env);
2614 if (w32_env != (PWCHAR) -1)
2615 flags |= CREATE_UNICODE_ENVIRONMENT;
2616 else
2617 /* If that fails, fall back to old method tweaking GDB's environment. */
2618#endif /* CW_CVT_ENV_TO_WINENV */
2619 {
2620 /* Reset all Win32 environment variables to avoid leftover on next run. */
2621 clear_win32_environment (environ);
2622 /* Prepare the environment vars for CreateProcess. */
2623 old_env = environ;
2624 environ = in_env;
2625 cygwin_internal (CW_SYNC_WINENV);
2626 w32_env = NULL;
2627 }
2628
2629 if (inferior_tty.empty ())
2630 tty = ostdin = ostdout = ostderr = -1;
2631 else
2632 {
2633 tty = open (inferior_tty.c_str (), O_RDWR | O_NOCTTY);
2634 if (tty < 0)
2635 {
2636 print_sys_errmsg (inferior_tty.c_str (), errno);
2637 ostdin = ostdout = ostderr = -1;
2638 }
2639 else
2640 {
2641 ostdin = dup (0);
2642 ostdout = dup (1);
2643 ostderr = dup (2);
2644 dup2 (tty, 0);
2645 dup2 (tty, 1);
2646 dup2 (tty, 2);
2647 }
2648 }
2649
2651 do_synchronously ([&] ()
2652 {
2653 if (!create_process (nullptr, args, flags, w32_env,
2654 inferior_cwd != nullptr ? infcwd : nullptr,
2656 &si, &pi))
2657 ret = (unsigned) GetLastError ();
2658 return true;
2659 });
2660
2661 if (w32_env)
2662 /* Just free the Win32 environment, if it could be created. */
2663 free (w32_env);
2664 else
2665 {
2666 /* Reset all environment variables to avoid leftover on next run. */
2667 clear_win32_environment (in_env);
2668 /* Restore normal GDB environment variables. */
2669 environ = old_env;
2670 cygwin_internal (CW_SYNC_WINENV);
2671 }
2672
2673 if (tty >= 0)
2674 {
2675 ::close (tty);
2676 dup2 (ostdin, 0);
2677 dup2 (ostdout, 1);
2678 dup2 (ostderr, 2);
2679 ::close (ostdin);
2680 ::close (ostdout);
2681 ::close (ostderr);
2682 }
2683#else /* !__CYGWIN__ */
2684 allargs_len = strlen (allargs);
2685 allargs_copy = strcpy ((char *) alloca (allargs_len + 1), allargs);
2686 if (strpbrk (allargs_copy, "<>") != NULL)
2687 {
2688 int e = errno;
2689 errno = 0;
2690 redirected =
2691 redirect_inferior_handles (allargs, allargs_copy,
2692 &fd_inp, &fd_out, &fd_err);
2693 if (errno)
2694 warning (_("Error in redirection: %s."), safe_strerror (errno));
2695 else
2696 errno = e;
2697 allargs_len = strlen (allargs_copy);
2698 }
2699 /* If not all the standard streams are redirected by the command
2700 line, use INFERIOR_TTY for those which aren't. */
2701 if (!inferior_tty.empty ()
2702 && !(fd_inp >= 0 && fd_out >= 0 && fd_err >= 0))
2703 {
2704 SECURITY_ATTRIBUTES sa;
2705 sa.nLength = sizeof(sa);
2706 sa.lpSecurityDescriptor = 0;
2707 sa.bInheritHandle = TRUE;
2708 tty = CreateFileA (inferior_tty.c_str (), GENERIC_READ | GENERIC_WRITE,
2709 0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
2710 if (tty == INVALID_HANDLE_VALUE)
2711 {
2712 unsigned err = (unsigned) GetLastError ();
2713 warning (_("Warning: Failed to open TTY %s, error %#x: %s"),
2714 inferior_tty.c_str (), err, strwinerror (err));
2715 }
2716 }
2717 if (redirected || tty != INVALID_HANDLE_VALUE)
2718 {
2719 if (fd_inp >= 0)
2720 si.hStdInput = (HANDLE) _get_osfhandle (fd_inp);
2721 else if (tty != INVALID_HANDLE_VALUE)
2722 si.hStdInput = tty;
2723 else
2724 si.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
2725 if (fd_out >= 0)
2726 si.hStdOutput = (HANDLE) _get_osfhandle (fd_out);
2727 else if (tty != INVALID_HANDLE_VALUE)
2728 si.hStdOutput = tty;
2729 else
2730 si.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
2731 if (fd_err >= 0)
2732 si.hStdError = (HANDLE) _get_osfhandle (fd_err);
2733 else if (tty != INVALID_HANDLE_VALUE)
2734 si.hStdError = tty;
2735 else
2736 si.hStdError = GetStdHandle (STD_ERROR_HANDLE);
2737 si.dwFlags |= STARTF_USESTDHANDLES;
2738 }
2739
2740 toexec = exec_file;
2741 /* Build the command line, a space-separated list of tokens where
2742 the first token is the name of the module to be executed.
2743 To avoid ambiguities introduced by spaces in the module name,
2744 we quote it. */
2745 args_len = strlen (toexec) + 2 /* quotes */ + allargs_len + 2;
2746 args = (char *) alloca (args_len);
2747 xsnprintf (args, args_len, "\"%s\" %s", toexec, allargs_copy);
2748
2749 flags |= DEBUG_ONLY_THIS_PROCESS;
2750
2751 /* CreateProcess takes the environment list as a null terminated set of
2752 strings (i.e. two nulls terminate the list). */
2753
2754 /* Get total size for env strings. */
2755 for (envlen = 0, i = 0; in_env[i] && *in_env[i]; i++)
2756 envlen += strlen (in_env[i]) + 1;
2757
2758 envsize = sizeof (in_env[0]) * (i + 1);
2759 env = (char **) alloca (envsize);
2760 memcpy (env, in_env, envsize);
2761 /* Windows programs expect the environment block to be sorted. */
2762 qsort (env, i, sizeof (char *), envvar_cmp);
2763
2764 w32env = (char *) alloca (envlen + 1);
2765
2766 /* Copy env strings into new buffer. */
2767 for (temp = w32env, i = 0; env[i] && *env[i]; i++)
2768 {
2769 strcpy (temp, env[i]);
2770 temp += strlen (temp) + 1;
2771 }
2772
2773 /* Final nil string to terminate new env. */
2774 *temp = 0;
2775
2777 do_synchronously ([&] ()
2778 {
2779 if (!create_process (nullptr, /* image */
2780 args, /* command line */
2781 flags, /* start flags */
2782 w32env, /* environment */
2783 inferior_cwd, /* current directory */
2785 &si,
2786 &pi))
2787 ret = (unsigned) GetLastError ();
2788 return true;
2789 });
2790 if (tty != INVALID_HANDLE_VALUE)
2791 CloseHandle (tty);
2792 if (fd_inp >= 0)
2793 _close (fd_inp);
2794 if (fd_out >= 0)
2795 _close (fd_out);
2796 if (fd_err >= 0)
2797 _close (fd_err);
2798#endif /* !__CYGWIN__ */
2799
2800 if (ret.has_value ())
2801 error (_("Error creating process %s, (error %u: %s)"),
2802 exec_file, *ret, strwinerror (*ret));
2803
2804#ifdef __x86_64__
2805 BOOL wow64;
2806 if (IsWow64Process (pi.hProcess, &wow64))
2807 windows_process.wow64_process = wow64;
2808#endif
2809
2810 CloseHandle (pi.hThread);
2811 CloseHandle (pi.hProcess);
2812
2813 if (useshell && shell[0] != '\0')
2815 else
2817
2818 do_initial_windows_stuff (pi.dwProcessId, 0);
2819
2820 /* windows_continue (DBG_CONTINUE, -1, 0); */
2821}
2822
2823void
2825{
2826 (void) windows_continue (DBG_CONTINUE, -1, 0, true);
2829 {
2830 CHECK (CloseHandle (windows_process.handle));
2832 }
2833 windows_process.siginfo_er.ExceptionCode = 0;
2835}
2836
2837/* Helper for windows_xfer_partial that handles memory transfers.
2838 Arguments are like target_xfer_partial. */
2839
2840static enum target_xfer_status
2841windows_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
2842 ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
2843{
2844 SIZE_T done = 0;
2845 BOOL success;
2846 DWORD lasterror = 0;
2847
2848 if (writebuf != NULL)
2849 {
2850 DEBUG_MEM ("write target memory, %s bytes at %s",
2851 pulongest (len), core_addr_to_string (memaddr));
2852 success = WriteProcessMemory (windows_process.handle,
2853 (LPVOID) (uintptr_t) memaddr, writebuf,
2854 len, &done);
2855 if (!success)
2856 lasterror = GetLastError ();
2857 FlushInstructionCache (windows_process.handle,
2858 (LPCVOID) (uintptr_t) memaddr, len);
2859 }
2860 else
2861 {
2862 DEBUG_MEM ("read target memory, %s bytes at %s",
2863 pulongest (len), core_addr_to_string (memaddr));
2864 success = ReadProcessMemory (windows_process.handle,
2865 (LPCVOID) (uintptr_t) memaddr, readbuf,
2866 len, &done);
2867 if (!success)
2868 lasterror = GetLastError ();
2869 }
2870 *xfered_len = (ULONGEST) done;
2871 if (!success && lasterror == ERROR_PARTIAL_COPY && done > 0)
2872 return TARGET_XFER_OK;
2873 else
2874 return success ? TARGET_XFER_OK : TARGET_XFER_E_IO;
2875}
2876
2877void
2879{
2880 CHECK (TerminateProcess (windows_process.handle, 0));
2881
2882 for (;;)
2883 {
2884 if (!windows_continue (DBG_CONTINUE, -1, 1))
2885 break;
2887 if (windows_process.current_event.dwDebugEventCode
2888 == EXIT_PROCESS_DEBUG_EVENT)
2889 break;
2890 }
2891
2892 target_mourn_inferior (inferior_ptid); /* Or just windows_mourn_inferior? */
2893}
2894
2895void
2897{
2898 DEBUG_EVENTS ("inferior_ptid=%d\n", inferior_ptid.pid ());
2899 async (false);
2900}
2901
2902/* Convert pid to printable format. */
2903std::string
2905{
2906 if (ptid.lwp () != 0)
2907 return string_printf ("Thread %d.0x%lx", ptid.pid (), ptid.lwp ());
2908
2909 return normal_pid_to_str (ptid);
2910}
2911
2912static enum target_xfer_status
2914 enum target_object object, const char *annex,
2915 gdb_byte *readbuf, const gdb_byte *writebuf,
2916 ULONGEST offset, ULONGEST len,
2917 ULONGEST *xfered_len)
2918{
2919 auto_obstack obstack;
2920 const char *buf;
2921 LONGEST len_avail;
2922
2923 if (writebuf)
2924 return TARGET_XFER_E_IO;
2925
2926 obstack_grow_str (&obstack, "<library-list>\n");
2928 windows_xfer_shared_library (so.name.c_str (),
2929 (CORE_ADDR) (uintptr_t) so.load_addr,
2930 &so.text_offset,
2931 target_gdbarch (), &obstack);
2932 obstack_grow_str0 (&obstack, "</library-list>\n");
2933
2934 buf = (const char *) obstack_finish (&obstack);
2935 len_avail = strlen (buf);
2936 if (offset >= len_avail)
2937 len= 0;
2938 else
2939 {
2940 if (len > len_avail - offset)
2941 len = len_avail - offset;
2942 memcpy (readbuf, buf + offset, len);
2943 }
2944
2945 *xfered_len = (ULONGEST) len;
2946 return len != 0 ? TARGET_XFER_OK : TARGET_XFER_EOF;
2947}
2948
2949/* Helper for windows_nat_target::xfer_partial that handles signal info. */
2950
2951static enum target_xfer_status
2952windows_xfer_siginfo (gdb_byte *readbuf, ULONGEST offset, ULONGEST len,
2953 ULONGEST *xfered_len)
2954{
2955 char *buf = (char *) &windows_process.siginfo_er;
2956 size_t bufsize = sizeof (windows_process.siginfo_er);
2957
2958#ifdef __x86_64__
2959 EXCEPTION_RECORD32 er32;
2960 if (windows_process.wow64_process)
2961 {
2962 buf = (char *) &er32;
2963 bufsize = sizeof (er32);
2964
2965 er32.ExceptionCode = windows_process.siginfo_er.ExceptionCode;
2966 er32.ExceptionFlags = windows_process.siginfo_er.ExceptionFlags;
2967 er32.ExceptionRecord
2968 = (uintptr_t) windows_process.siginfo_er.ExceptionRecord;
2969 er32.ExceptionAddress
2970 = (uintptr_t) windows_process.siginfo_er.ExceptionAddress;
2971 er32.NumberParameters = windows_process.siginfo_er.NumberParameters;
2972 int i;
2973 for (i = 0; i < EXCEPTION_MAXIMUM_PARAMETERS; i++)
2974 er32.ExceptionInformation[i]
2975 = windows_process.siginfo_er.ExceptionInformation[i];
2976 }
2977#endif
2978
2979 if (windows_process.siginfo_er.ExceptionCode == 0)
2980 return TARGET_XFER_E_IO;
2981
2982 if (readbuf == nullptr)
2983 return TARGET_XFER_E_IO;
2984
2985 if (offset > bufsize)
2986 return TARGET_XFER_E_IO;
2987
2988 if (offset + len > bufsize)
2989 len = bufsize - offset;
2990
2991 memcpy (readbuf, buf + offset, len);
2992 *xfered_len = len;
2993
2994 return TARGET_XFER_OK;
2995}
2996
2999 const char *annex, gdb_byte *readbuf,
3000 const gdb_byte *writebuf, ULONGEST offset,
3001 ULONGEST len, ULONGEST *xfered_len)
3002{
3003 switch (object)
3004 {
3006 return windows_xfer_memory (readbuf, writebuf, offset, len, xfered_len);
3007
3009 return windows_xfer_shared_libraries (this, object, annex, readbuf,
3010 writebuf, offset, len, xfered_len);
3011
3013 return windows_xfer_siginfo (readbuf, offset, len, xfered_len);
3014
3015 default:
3016 if (beneath () == NULL)
3017 {
3018 /* This can happen when requesting the transfer of unsupported
3019 objects before a program has been started (and therefore
3020 with the current_target having no target beneath). */
3021 return TARGET_XFER_E_IO;
3022 }
3023 return beneath ()->xfer_partial (object, annex,
3024 readbuf, writebuf, offset, len,
3025 xfered_len);
3026 }
3027}
3028
3029/* Provide thread local base, i.e. Thread Information Block address.
3030 Returns 1 if ptid is found and sets *ADDR to thread_local_base. */
3031
3032bool
3033windows_nat_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
3034{
3036
3038 if (th == NULL)
3039 return false;
3040
3041 if (addr != NULL)
3042 *addr = th->thread_local_base;
3043
3044 return true;
3045}
3046
3047ptid_t
3048windows_nat_target::get_ada_task_ptid (long lwp, ULONGEST thread)
3049{
3050 return ptid_t (inferior_ptid.pid (), lwp, 0);
3051}
3052
3053/* Implementation of the to_thread_name method. */
3054
3055const char *
3057{
3061 return th->thread_name ();
3062}
3063
3064
3066void
3068{
3074
3075 /* x86_dr_low.debug_register_length field is set by
3076 calling x86_set_debug_register_length function
3077 in processor windows specific native file. */
3078
3079 /* The target is not a global specifically to avoid a C++ "static
3080 initializer fiasco" situation. */
3082
3083#ifdef __CYGWIN__
3084 cygwin_internal (CW_SET_DOS_FILE_WARNING, 0);
3085#endif
3086
3087 add_com ("signal-event", class_run, signal_event_command, _("\
3088Signal a crashed process with event ID, to allow its debugging.\n\
3089This command is needed in support of setting up GDB as JIT debugger on \
3090MS-Windows. The command should be invoked from the GDB command line using \
3091the '-ex' command-line option. The ID of the event that blocks the \
3092crashed process will be supplied by the Windows JIT debugging mechanism."));
3093
3094#ifdef __CYGWIN__
3096Set use of shell to start subprocess."), _("\
3097Show use of shell to start subprocess."), NULL,
3098 NULL,
3099 NULL, /* FIXME: i18n: */
3100 &setlist, &showlist);
3101
3102 add_setshow_boolean_cmd ("cygwin-exceptions", class_support,
3103 &cygwin_exceptions, _("\
3104Break when an exception is detected in the Cygwin DLL itself."), _("\
3105Show whether gdb breaks on exceptions in the Cygwin DLL itself."), NULL,
3106 NULL,
3107 NULL, /* FIXME: i18n: */
3108 &setlist, &showlist);
3109#endif
3110
3111 add_setshow_boolean_cmd ("new-console", class_support, &new_console, _("\
3112Set creation of new console when creating child process."), _("\
3113Show creation of new console when creating child process."), NULL,
3114 NULL,
3115 NULL, /* FIXME: i18n: */
3116 &setlist, &showlist);
3117
3118 add_setshow_boolean_cmd ("new-group", class_support, &new_group, _("\
3119Set creation of new group when creating child process."), _("\
3120Show creation of new group when creating child process."), NULL,
3121 NULL,
3122 NULL, /* FIXME: i18n: */
3123 &setlist, &showlist);
3124
3126Set whether to display execution in child process."), _("\
3127Show whether to display execution in child process."), NULL,
3128 NULL,
3129 NULL, /* FIXME: i18n: */
3130 &setlist, &showlist);
3131
3132 add_setshow_boolean_cmd ("debugevents", class_support, &debug_events, _("\
3133Set whether to display kernel events in child process."), _("\
3134Show whether to display kernel events in child process."), NULL,
3135 NULL,
3136 NULL, /* FIXME: i18n: */
3137 &setlist, &showlist);
3138
3139 add_setshow_boolean_cmd ("debugmemory", class_support, &debug_memory, _("\
3140Set whether to display memory accesses in child process."), _("\
3141Show whether to display memory accesses in child process."), NULL,
3142 NULL,
3143 NULL, /* FIXME: i18n: */
3144 &setlist, &showlist);
3145
3146 add_setshow_boolean_cmd ("debugexceptions", class_support,
3147 &debug_exceptions, _("\
3148Set whether to display kernel exceptions in child process."), _("\
3149Show whether to display kernel exceptions in child process."), NULL,
3150 NULL,
3151 NULL, /* FIXME: i18n: */
3152 &setlist, &showlist);
3153
3155
3156 add_cmd ("selector", class_info, display_selectors,
3157 _("Display selectors infos."),
3159
3160 if (!initialize_loadable ())
3161 {
3162 /* This will probably fail on Windows 9x/Me. Let the user know
3163 that we're missing some functionality. */
3164 warning(_("\
3165cannot automatically find executable file or library to read symbols.\n\
3166Use \"file\" or \"dll\" command to load executable/libraries directly."));
3167 }
3168}
3169
3170/* Hardware watchpoint support, adapted from go32-nat.c code. */
3171
3172/* Pass the address ADDR to the inferior in the I'th debug register.
3173 Here we just store the address in dr array, the registers will be
3174 actually set up when windows_continue is called. */
3175static void
3176cygwin_set_dr (int i, CORE_ADDR addr)
3177{
3178 if (i < 0 || i > 3)
3179 internal_error (_("Invalid register %d in cygwin_set_dr.\n"), i);
3180 windows_process.dr[i] = addr;
3181
3182 for (auto &th : windows_process.thread_list)
3183 th->debug_registers_changed = true;
3184}
3185
3186/* Pass the value VAL to the inferior in the DR7 debug control
3187 register. Here we just store the address in D_REGS, the watchpoint
3188 will be actually set up in windows_wait. */
3189static void
3190cygwin_set_dr7 (unsigned long val)
3191{
3192 windows_process.dr[7] = (CORE_ADDR) val;
3193
3194 for (auto &th : windows_process.thread_list)
3195 th->debug_registers_changed = true;
3196}
3197
3198/* Get the value of debug register I from the inferior. */
3199
3200static CORE_ADDR
3202{
3203 return windows_process.dr[i];
3204}
3205
3206/* Get the value of the DR6 debug status register from the inferior.
3207 Here we just return the value stored in dr[6]
3208 by the last call to thread_rec for current_event.dwThreadId id. */
3209static unsigned long
3211{
3212 return (unsigned long) windows_process.dr[6];
3213}
3214
3215/* Get the value of the DR7 debug status register from the inferior.
3216 Here we just return the value stored in dr[7] by the last call to
3217 thread_rec for current_event.dwThreadId id. */
3218
3219static unsigned long
3221{
3222 return (unsigned long) windows_process.dr[7];
3223}
3224
3225/* Determine if the thread referenced by "ptid" is alive
3226 by "polling" it. If WaitForSingleObject returns WAIT_OBJECT_0
3227 it means that the thread has died. Otherwise it is assumed to be alive. */
3228
3229bool
3231{
3232 gdb_assert (ptid.lwp () != 0);
3233
3236 return WaitForSingleObject (th->h, 0) != WAIT_OBJECT_0;
3237}
3238
3240void
3242{
3243 char *homedir;
3244 if (inhibit_gdbinit)
3245 return;
3246
3247 homedir = getenv ("HOME");
3248 if (homedir)
3249 {
3250 char *p;
3251 char *oldini = (char *) alloca (strlen (homedir) +
3252 sizeof ("gdb.ini") + 1);
3253 strcpy (oldini, homedir);
3254 p = strchr (oldini, '\0');
3255 if (p > oldini && !IS_DIR_SEPARATOR (p[-1]))
3256 *p++ = '/';
3257 strcpy (p, "gdb.ini");
3258 if (access (oldini, 0) == 0)
3259 {
3260 int len = strlen (oldini);
3261 char *newini = (char *) alloca (len + 2);
3262
3263 xsnprintf (newini, len + 2, "%.*s.gdbinit",
3264 (int) (len - (sizeof ("gdb.ini") - 1)), oldini);
3265 warning (_("obsolete '%s' found. Rename to '%s'."), oldini, newini);
3266 }
3267 }
3268}
const char *const name
#define qsort
Definition ada-exp.c:3060
void xfree(void *)
void * xrealloc(void *ptr, size_t size)
Definition alloc.c:65
const int amd64_mappings[]
#define context_offset(x)
int amd64_windows_segment_register_p(int regnum)
struct gdbarch * target_gdbarch(void)
bool find_pc_partial_function(CORE_ADDR pc, const char **name, CORE_ADDR *address, CORE_ADDR *endaddr, const struct block **block)
Definition blockframe.c:373
void disable_breakpoints_in_shlibs(void)
void mourn_inferior() override
Definition inf-child.c:190
void maybe_unpush_target()
Definition inf-child.c:199
const std::string & cwd() const
Definition inferior.h:515
const std::string & tty()
Definition inferior.c:165
gdbarch * arch() const
Definition regcache.c:230
void raw_collect(int regnum, void *buf) const override
Definition regcache.c:1118
void raw_supply(int regnum, const void *buf) override
Definition regcache.c:1053
ptid_t ptid() const
Definition regcache.h:407
static void inferior()
Definition target.c:947
static void init()
Definition target.c:937
static void ours()
Definition target.c:1065
ptid_t ptid
Definition gdbthread.h:256
struct cmd_list_element * showlist
Definition cli-cmds.c:125
struct cmd_list_element * setlist
Definition cli-cmds.c:117
struct cmd_list_element * add_cmd(const char *name, enum command_class theclass, const char *doc, struct cmd_list_element **list)
Definition cli-decode.c:233
struct cmd_list_element * add_com(const char *name, enum command_class theclass, cmd_simple_func_ftype *fun, const char *doc)
set_show_commands add_setshow_boolean_cmd(const char *name, enum command_class theclass, bool *var, const char *set_doc, const char *show_doc, const char *help_doc, cmd_func_ftype *set_func, show_value_ftype *show_func, struct cmd_list_element **set_list, struct cmd_list_element **show_list)
Definition cli-decode.c:739
@ class_support
Definition command.h:58
@ class_run
Definition command.h:54
@ class_info
Definition command.h:59
#define complaint(FMT,...)
Definition complaints.h:47
#define BOOL
bool info_verbose
Definition top.c:2022
int(* deprecated_ui_loop_hook)(int signo)
Definition top.c:208
LONGEST parse_and_eval_long(const char *exp)
Definition eval.c:62
void exception_print(struct ui_file *file, const struct gdb_exception &e)
Definition exceptions.c:105
char ** environ
gdb_bfd_ref_ptr gdb_bfd_open(const char *name, const char *target, int fd, bool warn_if_slow)
Definition gdb_bfd.c:491
gdb::ref_ptr< struct bfd, gdb_bfd_ref_policy > gdb_bfd_ref_ptr
Definition gdb_bfd.h:78
int gdbarch_pc_regnum(struct gdbarch *gdbarch)
Definition gdbarch.c:2023
bool gdbarch_read_pc_p(struct gdbarch *gdbarch)
Definition gdbarch.c:1762
int gdbarch_num_regs(struct gdbarch *gdbarch)
Definition gdbarch.c:1899
int gdbarch_ps_regnum(struct gdbarch *gdbarch)
Definition gdbarch.c:2040
CORE_ADDR gdbarch_decr_pc_after_break(struct gdbarch *gdbarch)
Definition gdbarch.c:2838
bool gdbarch_write_pc_p(struct gdbarch *gdbarch)
Definition gdbarch.c:1786
struct thread_info * add_thread_silent(process_stratum_target *targ, ptid_t ptid)
Definition thread.c:263
thread_info * find_thread_ptid(inferior *inf, ptid_t ptid)
Definition thread.c:528
void switch_to_thread(struct thread_info *thr)
Definition thread.c:1335
bool print_thread_events
Definition thread.c:1932
void switch_to_no_thread()
Definition thread.c:1320
mach_port_t mach_port_t name mach_port_t mach_port_t name kern_return_t err
Definition gnu-nat.c:1790
mach_port_t kern_return_t mach_port_t mach_msg_type_name_t msgportsPoly mach_port_t kern_return_t pid_t pid mach_port_t kern_return_t mach_port_t task mach_port_t kern_return_t int flags
Definition gnu-nat.c:1862
mach_port_t mach_port_t name mach_port_t mach_port_t name kern_return_t int int rusage_t pid_t pid
Definition gnu-nat.c:1792
mach_port_t mach_port_t name mach_port_t mach_port_t name kern_return_t int status
Definition gnu-nat.c:1791
size_t size
Definition go32-nat.c:241
const int i386_mappings[]
int i386_windows_segment_register_p(int regnum)
#define I387_FOP_REGNUM(tdep)
Definition i387-tdep.h:63
#define I387_FISEG_REGNUM(tdep)
Definition i387-tdep.h:59
@ L
Definition ia64-tdep.c:85
void add_inf_child_target(inf_child_target *target)
Definition inf-child.c:418
void inferior_event_handler(enum inferior_event_type event_type)
Definition inf-loop.c:36
ptid_t inferior_ptid
Definition infcmd.c:91
void inferior_appeared(struct inferior *inf, int pid)
Definition inferior.c:322
struct inferior * find_inferior_pid(process_stratum_target *targ, int pid)
Definition inferior.c:348
void detach_inferior(inferior *inf)
Definition inferior.c:308
struct inferior * current_inferior(void)
Definition inferior.c:54
#define O_NOCTTY
Definition inflow.c:44
void clear_proceed_status(int step)
Definition infrun.c:2760
bool disable_randomization
Definition infrun.c:174
void init_wait_for_inferior(void)
Definition infrun.c:3426
int find_minimal_symbol_address(const char *name, CORE_ADDR *addr, struct objfile *objfile)
Definition minsyms.c:489
info(c)
Definition gdbarch.py:184
BOOL create_process(const char *image, char *command_line, DWORD flags, void *environment, const char *cur_dir, bool no_randomization, STARTUPINFOA *startup_info, PROCESS_INFORMATION *process_info)
bool initialize_loadable()
BOOL wait_for_debug_event(DEBUG_EVENT *event, DWORD timeout)
@ HANDLE_EXCEPTION_IGNORED
@ HANDLE_EXCEPTION_HANDLED
@ HANDLE_EXCEPTION_UNHANDLED
@ DONT_INVALIDATE_CONTEXT
BOOL continue_last_debug_event(DWORD continue_status, bool debug_events)
bool disable_randomization_available()
#define Wow64GetThreadSelectorEntry
#define Wow64SetThreadContext
#define DebugSetProcessKillOnExit
#define DebugBreakProcess
#define AdjustTokenPrivileges
#define DebugActiveProcessStop
#define OpenProcessToken
#define LookupPrivilegeValueA
#define Wow64GetThreadContext
#define STATUS_WX86_BREAKPOINT
Definition windows-nat.h:29
#define GetCurrentConsoleFont
#define GetConsoleFontSize
int register_size(struct gdbarch *gdbarch, int regnum)
Definition regcache.c:170
struct regcache * get_current_regcache(void)
Definition regcache.c:426
void(* func)(remote_target *remote, char *)
void serial_event_set(struct serial_event *event)
Definition ser-event.c:180
void serial_event_clear(struct serial_event *event)
Definition ser-event.c:201
struct serial_event * make_serial_event(void)
Definition ser-event.c:162
int serial_event_fd(struct serial_event *event)
Definition ser-event.c:170
#define enable()
Definition ser-go32.c:239
#define SO_NAME_MAX_PATH_SIZE
Definition solist.h:22
Definition gnu-nat.c:154
target_ops * beneath() const
Definition target.c:3020
virtual enum target_xfer_status xfer_partial(enum target_object object, const char *annex, gdb_byte *readbuf, const gdb_byte *writebuf, ULONGEST offset, ULONGEST len, ULONGEST *xfered_len) TARGET_DEFAULT_RETURN(TARGET_XFER_E_IO)
virtual gdb::byte_vector virtual thread_info_to_thread_handle(struct thread_info *) TARGET_DEFAULT_RETURN(gdb voi stop)(ptid_t) TARGET_DEFAULT_IGNORE()
Definition target.h:684
target_waitstatus & set_exited(int exit_status)
Definition waitstatus.h:222
target_waitstatus & set_spurious()
Definition waitstatus.h:300
target_waitstatus & set_signalled(gdb_signal sig)
Definition waitstatus.h:238
target_waitstatus & set_stopped(gdb_signal sig)
Definition waitstatus.h:230
target_waitstatus & set_loaded()
Definition waitstatus.h:246
target_waitstatus & set_ignore()
Definition waitstatus.h:307
target_waitkind kind() const
Definition waitstatus.h:345
Definition value.c:181
bool matching_pending_stop(bool debug_events)
gdb::optional< pending_stop > fetch_pending_stop(bool debug_events)
handle_exception_result handle_exception(struct target_waitstatus *ourstatus, bool debug_exceptions)
std::vector< pending_stop > pending_stops
BOOL windows_continue(DWORD continue_status, int id, int killed, bool last_call=false)
void wait_for_debug_event_main_thread(DEBUG_EVENT *event)
void do_synchronously(gdb::function_view< bool()> func)
static DWORD WINAPI process_thread_starter(LPVOID self)
void do_initial_windows_stuff(DWORD pid, bool attaching)
windows_thread_info * add_thread(ptid_t ptid, HANDLE h, void *tlb, bool main_thread_p)
DWORD fake_create_process()
bool attach_no_wait() override
serial_event * m_wait_event
void resume(ptid_t, int, enum gdb_signal) override
bool can_async_p() override
std::queue< gdb::function_view< bool()> > m_queue
ptid_t wait(ptid_t, struct target_waitstatus *, target_wait_flags) override
ptid_t get_windows_debug_event(int pid, struct target_waitstatus *ourstatus, target_wait_flags options)
const char * pid_to_exec_file(int pid) override
bool supports_disable_randomization() override
int async_wait_fd() override
void async(bool enable) override
void close() override
void store_registers(struct regcache *, int) override
bool get_tib_address(ptid_t ptid, CORE_ADDR *addr) override
bool thread_alive(ptid_t ptid) override
void detach(inferior *, int) override
void interrupt() override
void create_inferior(const char *, const std::string &, char **, int) override
void files_info() override
bool stopped_by_sw_breakpoint() override
const char * thread_name(struct thread_info *) override
enum target_xfer_status xfer_partial(enum target_object object, const char *annex, gdb_byte *readbuf, const gdb_byte *writebuf, ULONGEST offset, ULONGEST len, ULONGEST *xfered_len) override
std::atomic< bool > m_debug_event_pending
DEBUG_EVENT m_last_debug_event
void pass_ctrlc() override
bool is_async_p() override
void kill() override
ptid_t get_ada_task_ptid(long lwp, ULONGEST thread) override
void mourn_inferior() override
void delete_thread(ptid_t ptid, DWORD exit_code, bool main_thread_p)
std::string pid_to_str(ptid_t) override
void fetch_registers(struct regcache *, int) override
void attach(const char *, int) override
bool supports_stopped_by_sw_breakpoint() override
std::vector< windows_solib > solibs
bool handle_access_violation(const EXCEPTION_RECORD *rec) override
segment_register_p_ftype * segment_register_p
void handle_unload_dll() override
windows_thread_info * thread_rec(ptid_t ptid, thread_disposition_type disposition) override
void handle_load_dll(const char *dll_name, LPVOID base) override
int handle_output_debug_string(struct target_waitstatus *ourstatus) override
std::vector< std::unique_ptr< windows_thread_info > > thread_list
std::string original_name
Definition windows-nat.c:87
CORE_ADDR text_offset
Definition windows-nat.c:84
LPVOID load_addr
Definition windows-nat.c:83
std::string name
Definition windows-nat.c:89
void(* set_addr)(int, CORE_ADDR)
Definition x86-dregs.h:49
unsigned long(* get_control)(void)
Definition x86-dregs.h:61
unsigned long(* get_status)(void)
Definition x86-dregs.h:57
void(* set_control)(unsigned long)
Definition x86-dregs.h:45
CORE_ADDR(* get_addr)(int)
Definition x86-dregs.h:53
int target_read_string(CORE_ADDR addr, int len, int width, unsigned int fetchlimit, gdb::unique_xmalloc_ptr< gdb_byte > *buffer, int *bytes_read)
Definition target.c:65
void target_announce_detach(int from_tty)
Definition target.c:3601
void target_announce_attach(int from_tty, int pid)
Definition target.c:3622
std::string target_pid_to_str(ptid_t ptid)
Definition target.c:2602
std::string normal_pid_to_str(ptid_t ptid)
Definition target.c:3672
void target_mourn_inferior(ptid_t ptid)
Definition target.c:2737
@ INF_REG_EVENT
Definition target.h:129
target_xfer_status
Definition target.h:214
@ TARGET_XFER_E_IO
Definition target.h:227
@ TARGET_XFER_EOF
Definition target.h:219
@ TARGET_XFER_OK
Definition target.h:216
target_object
Definition target.h:138
@ TARGET_OBJECT_SIGNAL_INFO
Definition target.h:182
@ TARGET_OBJECT_MEMORY
Definition target.h:142
@ TARGET_OBJECT_LIBRARIES
Definition target.h:171
int inhibit_gdbinit
Definition top.c:128
void print_sys_errmsg(const char *string, int errcode)
Definition utils.c:662
void gdb_printf(struct ui_file *stream, const char *format,...)
Definition utils.c:1865
void gdb_puts(const char *linebuffer, struct ui_file *stream)
Definition utils.c:1788
int parse_pid_to_attach(const char *args)
Definition utils.c:3279
#define gdb_stderr
Definition utils.h:193
@ TARGET_WNOHANG
Definition wait.h:32
@ TARGET_WAITKIND_SPURIOUS
Definition waitstatus.h:78
@ TARGET_WAITKIND_LOADED
Definition waitstatus.h:44
@ TARGET_WAITKIND_SIGNALLED
Definition waitstatus.h:40
@ TARGET_WAITKIND_EXITED
Definition waitstatus.h:32
static unsigned long cygwin_get_dr7(void)
#define DEBUG_EVENTS(fmt,...)
static bool new_group
static windows_per_inferior windows_process
static enum target_xfer_status windows_xfer_memory(gdb_byte *readbuf, const gdb_byte *writebuf, ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
static bool useshell
static int envvar_cmp(const void *a, const void *b)
static int redir_open(const char *redir_string, int *inp, int *out, int *err)
static bool new_console
static void display_selectors(const char *args, int from_tty)
@ FLAG_TRACE_BIT
static void signal_event_command(const char *args, int from_tty)
static int set_process_privilege(const char *privilege, BOOL enable)
static bool debug_exceptions
static void cygwin_set_dr7(unsigned long val)
static void windows_fetch_one_register(struct regcache *regcache, windows_thread_info *th, int r)
static bool debug_memory
void _initialize_windows_nat()
static unsigned long cygwin_get_dr6(void)
static enum target_xfer_status windows_xfer_shared_libraries(struct target_ops *ops, enum target_object object, const char *annex, gdb_byte *readbuf, const gdb_byte *writebuf, ULONGEST offset, ULONGEST len, ULONGEST *xfered_len)
#define DEBUG_EXEC(fmt,...)
static bool redirect_inferior_handles(const char *cmd_orig, char *cmd, int *inp, int *out, int *err)
#define CHECK(x)
static bool debug_exec
#define DEBUG_MEM(fmt,...)
static int display_selector(HANDLE thread, DWORD sel)
void _initialize_check_for_gdb_ini()
static void windows_init_thread_list(void)
static int redir_set_redirection(const char *s, int *inp, int *out, int *err)
#define STARTUPINFO
#define DEBUG_EXCEPT(fmt,...)
static void windows_clear_solib(void)
#define __PMAX
#define CONTEXT_DEBUGGER_DR
static void windows_store_one_register(const struct regcache *regcache, windows_thread_info *th, int r)
static CORE_ADDR cygwin_get_dr(int i)
#define DR6_CLEAR_VALUE
static enum target_xfer_status windows_xfer_siginfo(gdb_byte *readbuf, ULONGEST offset, ULONGEST len, ULONGEST *xfered_len)
static void cygwin_set_dr(int i, CORE_ADDR addr)
static void check(BOOL ok, const char *file, int line)
static void windows_set_console_info(STARTUPINFO *si, DWORD *flags)
static bool debug_events
static void wait_for_single(HANDLE handle, DWORD howlong)
#define _CYGWIN_SIGNAL_STRING
static windows_solib * windows_make_so(const char *name, LPVOID load_addr)
int() segment_register_p_ftype(int regnum)
Definition windows-nat.h:23
void windows_xfer_shared_library(const char *so_name, CORE_ADDR load_addr, CORE_ADDR *text_offset_cached, struct gdbarch *gdbarch, struct obstack *obstack)
void init_w32_command_list(void)
struct cmd_list_element * info_w32_cmdlist
struct x86_dr_low_type x86_dr_low
Definition x86-nat.c:39
void x86_cleanup_dregs(void)
Definition x86-nat.c:81