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