win32-low.cc revision 1.1.1.4 1 /* Low level interface to Windows debugging, for gdbserver.
2 Copyright (C) 2006-2024 Free Software Foundation, Inc.
3
4 Contributed by Leo Zayas. Based on "win32-nat.c" from GDB.
5
6 This file is part of GDB.
7
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or
11 (at your option) any later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20
21 #include "regcache.h"
22 #include "gdbsupport/fileio.h"
23 #include "mem-break.h"
24 #include "win32-low.h"
25 #include "gdbthread.h"
26 #include "dll.h"
27 #include "hostio.h"
28 #include <windows.h>
29 #include <winnt.h>
30 #include <imagehlp.h>
31 #include <tlhelp32.h>
32 #include <psapi.h>
33 #include <process.h>
34 #include "gdbsupport/gdb_tilde_expand.h"
35 #include "gdbsupport/common-inferior.h"
36 #include "gdbsupport/gdb_wait.h"
37
38 using namespace windows_nat;
39
40 /* See win32-low.h. */
41 gdbserver_windows_process windows_process;
42
43 #ifndef USE_WIN32API
44 #include <sys/cygwin.h>
45 #endif
46
47 #define OUTMSG(X) do { printf X; fflush (stderr); } while (0)
48
49 #define OUTMSG2(X) \
50 do \
51 { \
52 if (debug_threads) \
53 { \
54 printf X; \
55 fflush (stderr); \
56 } \
57 } while (0)
58
59 #ifndef _T
60 #define _T(x) TEXT (x)
61 #endif
62
63 int using_threads = 1;
64
65 const struct target_desc *win32_tdesc;
66 #ifdef __x86_64__
67 const struct target_desc *wow64_win32_tdesc;
68 #endif
69
70 #define NUM_REGS (the_low_target.num_regs ())
71
72 /* The current debug event from WaitForDebugEvent. */
73 static ptid_t
74 debug_event_ptid (DEBUG_EVENT *event)
75 {
76 return ptid_t (event->dwProcessId, event->dwThreadId, 0);
77 }
78
79 /* Get the thread context of the thread associated with TH. */
80
81 static void
82 win32_get_thread_context (windows_thread_info *th)
83 {
84 windows_process.with_context (th, [] (auto *context)
85 {
86 memset (context, 0, sizeof (*context));
87 });
88 (*the_low_target.get_thread_context) (th);
89 }
90
91 /* Set the thread context of the thread associated with TH. */
92
93 static void
94 win32_set_thread_context (windows_thread_info *th)
95 {
96 windows_process.with_context (th, [&] (auto *context)
97 {
98 set_thread_context (th->h, context);
99 });
100 }
101
102 /* Set the thread context of the thread associated with TH. */
103
104 static void
105 win32_prepare_to_resume (windows_thread_info *th)
106 {
107 if (the_low_target.prepare_to_resume != NULL)
108 (*the_low_target.prepare_to_resume) (th);
109 }
110
111 /* See win32-low.h. */
112
113 void
114 win32_require_context (windows_thread_info *th)
115 {
116 DWORD context_flags = *windows_process.context_flags_ptr (th);
117 if (context_flags == 0)
118 {
119 th->suspend ();
120 win32_get_thread_context (th);
121 }
122 }
123
124 /* See nat/windows-nat.h. */
125
126 windows_thread_info *
127 gdbserver_windows_process::thread_rec
128 (ptid_t ptid, thread_disposition_type disposition)
129 {
130 thread_info *thread = find_thread_ptid (ptid);
131 if (thread == NULL)
132 return NULL;
133
134 auto th = static_cast<windows_thread_info *> (thread->target_data ());
135 if (disposition != DONT_INVALIDATE_CONTEXT)
136 win32_require_context (th);
137 return th;
138 }
139
140 /* Add a thread to the thread list. */
141 static windows_thread_info *
142 child_add_thread (DWORD pid, DWORD tid, HANDLE h, void *tlb)
143 {
144 windows_thread_info *th;
145 ptid_t ptid = ptid_t (pid, tid, 0);
146
147 if ((th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT)))
148 return th;
149
150 CORE_ADDR base = (CORE_ADDR) (uintptr_t) tlb;
151 #ifdef __x86_64__
152 /* For WOW64 processes, this is actually the pointer to the 64bit TIB,
153 and the 32bit TIB is exactly 2 pages after it. */
154 if (windows_process.wow64_process)
155 base += 2 * 4096; /* page size = 4096 */
156 #endif
157 th = new windows_thread_info (tid, h, base);
158
159 find_process_pid (pid)->add_thread (ptid, th);
160
161 if (the_low_target.thread_added != NULL)
162 (*the_low_target.thread_added) (th);
163
164 return th;
165 }
166
167 /* Delete a thread from the list of threads. */
168 static void
169 delete_thread_info (thread_info *thread)
170 {
171 auto th = static_cast<windows_thread_info *> (thread->target_data ());
172
173 thread->process ()->remove_thread (thread);
174 delete th;
175 }
176
177 /* Delete a thread from the list of threads. */
178 static void
179 child_delete_thread (DWORD pid, DWORD tid)
180 {
181 process_info *process = find_process_pid (pid);
182
183 if (process == nullptr)
184 return;
185
186 /* If the last thread is exiting, just return. */
187 if (process->thread_count () == 1)
188 return;
189
190 thread_info *thread = process->find_thread (ptid_t (pid, tid));
191 if (thread == nullptr)
192 return;
193
194 delete_thread_info (thread);
195 }
196
197 /* These watchpoint related wrapper functions simply pass on the function call
198 if the low target has registered a corresponding function. */
199
200 bool
201 win32_process_target::supports_z_point_type (char z_type)
202 {
203 return (z_type == Z_PACKET_SW_BP
204 || (the_low_target.supports_z_point_type != NULL
205 && the_low_target.supports_z_point_type (z_type)));
206 }
207
208 int
209 win32_process_target::insert_point (enum raw_bkpt_type type, CORE_ADDR addr,
210 int size, raw_breakpoint *bp)
211 {
212 if (type == raw_bkpt_type_sw)
213 return insert_memory_breakpoint (bp);
214 else if (the_low_target.insert_point != NULL)
215 return the_low_target.insert_point (type, addr, size, bp);
216 else
217 /* Unsupported (see target.h). */
218 return 1;
219 }
220
221 int
222 win32_process_target::remove_point (enum raw_bkpt_type type, CORE_ADDR addr,
223 int size, raw_breakpoint *bp)
224 {
225 if (type == raw_bkpt_type_sw)
226 return remove_memory_breakpoint (bp);
227 else if (the_low_target.remove_point != NULL)
228 return the_low_target.remove_point (type, addr, size, bp);
229 else
230 /* Unsupported (see target.h). */
231 return 1;
232 }
233
234 bool
235 win32_process_target::stopped_by_watchpoint ()
236 {
237 if (the_low_target.stopped_by_watchpoint != NULL)
238 return the_low_target.stopped_by_watchpoint ();
239 else
240 return false;
241 }
242
243 CORE_ADDR
244 win32_process_target::stopped_data_address ()
245 {
246 if (the_low_target.stopped_data_address != NULL)
247 return the_low_target.stopped_data_address ();
248 else
249 return 0;
250 }
251
252
253 /* Transfer memory from/to the debugged process. */
254 static int
255 child_xfer_memory (CORE_ADDR memaddr, char *our, int len,
256 int write, process_stratum_target *target)
257 {
258 BOOL success;
259 SIZE_T done = 0;
260 DWORD lasterror = 0;
261 uintptr_t addr = (uintptr_t) memaddr;
262
263 if (write)
264 {
265 success = WriteProcessMemory (windows_process.handle, (LPVOID) addr,
266 (LPCVOID) our, len, &done);
267 if (!success)
268 lasterror = GetLastError ();
269 FlushInstructionCache (windows_process.handle, (LPCVOID) addr, len);
270 }
271 else
272 {
273 success = ReadProcessMemory (windows_process.handle, (LPCVOID) addr,
274 (LPVOID) our, len, &done);
275 if (!success)
276 lasterror = GetLastError ();
277 }
278 if (!success && lasterror == ERROR_PARTIAL_COPY && done > 0)
279 return done;
280 else
281 return success ? done : -1;
282 }
283
284 /* Clear out any old thread list and reinitialize it to a pristine
285 state. */
286 static void
287 child_init_thread_list (void)
288 {
289 for_each_thread (delete_thread_info);
290 }
291
292 static void
293 do_initial_child_stuff (HANDLE proch, DWORD pid, int attached)
294 {
295 struct process_info *proc;
296
297 windows_process.last_sig = GDB_SIGNAL_0;
298 windows_process.handle = proch;
299 windows_process.main_thread_id = 0;
300
301 windows_process.soft_interrupt_requested = 0;
302 windows_process.faked_breakpoint = 0;
303 windows_process.open_process_used = true;
304
305 memset (&windows_process.current_event, 0,
306 sizeof (windows_process.current_event));
307
308 #ifdef __x86_64__
309 BOOL wow64;
310 if (!IsWow64Process (proch, &wow64))
311 {
312 DWORD err = GetLastError ();
313 throw_winerror_with_name ("Check if WOW64 process failed", err);
314 }
315 windows_process.wow64_process = wow64;
316
317 if (windows_process.wow64_process
318 && (Wow64GetThreadContext == nullptr
319 || Wow64SetThreadContext == nullptr))
320 error ("WOW64 debugging is not supported on this system.\n");
321
322 windows_process.ignore_first_breakpoint
323 = !attached && windows_process.wow64_process;
324 #endif
325
326 proc = add_process (pid, attached);
327 #ifdef __x86_64__
328 if (windows_process.wow64_process)
329 proc->tdesc = wow64_win32_tdesc;
330 else
331 #endif
332 proc->tdesc = win32_tdesc;
333 child_init_thread_list ();
334 windows_process.child_initialization_done = 0;
335
336 if (the_low_target.initial_stuff != NULL)
337 (*the_low_target.initial_stuff) ();
338
339 windows_process.cached_status.set_ignore ();
340
341 /* Flush all currently pending debug events (thread and dll list) up
342 to the initial breakpoint. */
343 while (1)
344 {
345 struct target_waitstatus status;
346
347 the_target->wait (minus_one_ptid, &status, 0);
348
349 /* Note win32_wait doesn't return thread events. */
350 if (status.kind () != TARGET_WAITKIND_LOADED)
351 {
352 windows_process.cached_status = status;
353 break;
354 }
355
356 {
357 struct thread_resume resume;
358
359 resume.thread = minus_one_ptid;
360 resume.kind = resume_continue;
361 resume.sig = 0;
362
363 the_target->resume (&resume, 1);
364 }
365 }
366
367 /* Now that the inferior has been started and all DLLs have been mapped,
368 we can iterate over all DLLs and load them in.
369
370 We avoid doing it any earlier because, on certain versions of Windows,
371 LOAD_DLL_DEBUG_EVENTs are sometimes not complete. In particular,
372 we have seen on Windows 8.1 that the ntdll.dll load event does not
373 include the DLL name, preventing us from creating an associated SO.
374 A possible explanation is that ntdll.dll might be mapped before
375 the SO info gets created by the Windows system -- ntdll.dll is
376 the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs
377 do not seem to suffer from that problem.
378
379 Rather than try to work around this sort of issue, it is much
380 simpler to just ignore DLL load/unload events during the startup
381 phase, and then process them all in one batch now. */
382 windows_process.add_all_dlls ();
383
384 windows_process.child_initialization_done = 1;
385 }
386
387 /* Resume all artificially suspended threads if we are continuing
388 execution. */
389 static void
390 continue_one_thread (thread_info *thread, int thread_id)
391 {
392 auto th = static_cast<windows_thread_info *> (thread->target_data ());
393
394 if (thread_id == -1 || thread_id == th->tid)
395 {
396 win32_prepare_to_resume (th);
397
398 if (th->suspended)
399 {
400 DWORD *context_flags = windows_process.context_flags_ptr (th);
401 if (*context_flags)
402 {
403 win32_set_thread_context (th);
404 *context_flags = 0;
405 }
406
407 th->resume ();
408 }
409 }
410 }
411
412 static BOOL
413 child_continue (DWORD continue_status, int thread_id)
414 {
415 windows_process.desired_stop_thread_id = thread_id;
416 if (windows_process.matching_pending_stop (debug_threads))
417 return TRUE;
418
419 /* The inferior will only continue after the ContinueDebugEvent
420 call. */
421 for_each_thread ([&] (thread_info *thread)
422 {
423 continue_one_thread (thread, thread_id);
424 });
425 windows_process.faked_breakpoint = 0;
426
427 return continue_last_debug_event (continue_status, debug_threads);
428 }
429
430 /* Fetch register(s) from the current thread context. */
431 static void
432 child_fetch_inferior_registers (struct regcache *regcache, int r)
433 {
434 int regno;
435 windows_thread_info *th
436 = windows_process.thread_rec (current_thread->id,
437 INVALIDATE_CONTEXT);
438 if (r == -1 || r > NUM_REGS)
439 child_fetch_inferior_registers (regcache, NUM_REGS);
440 else
441 for (regno = 0; regno < r; regno++)
442 (*the_low_target.fetch_inferior_register) (regcache, th, regno);
443 }
444
445 /* Store a new register value into the current thread context. We don't
446 change the program's context until later, when we resume it. */
447 static void
448 child_store_inferior_registers (struct regcache *regcache, int r)
449 {
450 int regno;
451 windows_thread_info *th
452 = windows_process.thread_rec (current_thread->id,
453 INVALIDATE_CONTEXT);
454 if (r == -1 || r == 0 || r > NUM_REGS)
455 child_store_inferior_registers (regcache, NUM_REGS);
456 else
457 for (regno = 0; regno < r; regno++)
458 (*the_low_target.store_inferior_register) (regcache, th, regno);
459 }
460
461 static BOOL
462 create_process (const char *program, char *args,
463 DWORD flags, PROCESS_INFORMATION *pi)
464 {
465 const std::string &inferior_cwd = get_inferior_cwd ();
466 BOOL ret;
467 size_t argslen, proglen;
468
469 proglen = strlen (program) + 1;
470 argslen = strlen (args) + proglen;
471
472 STARTUPINFOA si = { sizeof (STARTUPINFOA) };
473 char *program_and_args = (char *) alloca (argslen + 1);
474
475 strcpy (program_and_args, program);
476 strcat (program_and_args, " ");
477 strcat (program_and_args, args);
478 ret = create_process (program, /* image name */
479 program_and_args, /* command line */
480 flags, /* start flags */
481 NULL, /* environment */
482 /* current directory */
483 (inferior_cwd.empty ()
484 ? NULL
485 : gdb_tilde_expand (inferior_cwd).c_str()),
486 get_client_state ().disable_randomization,
487 &si, /* start info */
488 pi); /* proc info */
489
490 return ret;
491 }
492
493 /* Start a new process.
494 PROGRAM is the program name.
495 PROGRAM_ARGS is the vector containing the inferior's args.
496 Returns the new PID on success, -1 on failure. Registers the new
497 process with the process list. */
498 int
499 win32_process_target::create_inferior (const char *program,
500 const std::vector<char *> &program_args)
501 {
502 client_state &cs = get_client_state ();
503 #ifndef USE_WIN32API
504 char real_path[PATH_MAX];
505 char *orig_path, *new_path, *path_ptr;
506 #endif
507 BOOL ret;
508 DWORD flags;
509 PROCESS_INFORMATION pi;
510 DWORD err;
511 std::string str_program_args = construct_inferior_arguments (program_args);
512 char *args = (char *) str_program_args.c_str ();
513
514 /* win32_wait needs to know we're not attaching. */
515 windows_process.attaching = 0;
516
517 if (!program)
518 error ("No executable specified, specify executable to debug.\n");
519
520 flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS;
521
522 #ifndef USE_WIN32API
523 orig_path = NULL;
524 path_ptr = getenv ("PATH");
525 if (path_ptr)
526 {
527 int size = cygwin_conv_path_list (CCP_POSIX_TO_WIN_A, path_ptr, NULL, 0);
528 orig_path = (char *) alloca (strlen (path_ptr) + 1);
529 new_path = (char *) alloca (size);
530 strcpy (orig_path, path_ptr);
531 cygwin_conv_path_list (CCP_POSIX_TO_WIN_A, path_ptr, new_path, size);
532 setenv ("PATH", new_path, 1);
533 }
534 cygwin_conv_path (CCP_POSIX_TO_WIN_A, program, real_path, PATH_MAX);
535 program = real_path;
536 #endif
537
538 OUTMSG2 (("Command line is \"%s %s\"\n", program, args));
539
540 #ifdef CREATE_NEW_PROCESS_GROUP
541 flags |= CREATE_NEW_PROCESS_GROUP;
542 #endif
543
544 ret = create_process (program, args, flags, &pi);
545 err = GetLastError ();
546 if (!ret && err == ERROR_FILE_NOT_FOUND)
547 {
548 char *exename = (char *) alloca (strlen (program) + 5);
549 strcat (strcpy (exename, program), ".exe");
550 ret = create_process (exename, args, flags, &pi);
551 err = GetLastError ();
552 }
553
554 #ifndef USE_WIN32API
555 if (orig_path)
556 setenv ("PATH", orig_path, 1);
557 #endif
558
559 if (!ret)
560 {
561 std::string msg = string_printf (_("Error creating process \"%s %s\""),
562 program, args);
563 throw_winerror_with_name (msg.c_str (), err);
564 }
565 else
566 {
567 OUTMSG2 (("Process created: %s %s\n", program, (char *) args));
568 }
569
570 CloseHandle (pi.hThread);
571
572 do_initial_child_stuff (pi.hProcess, pi.dwProcessId, 0);
573
574 /* Wait till we are at 1st instruction in program, return new pid
575 (assuming success). */
576 cs.last_ptid = wait (ptid_t (pi.dwProcessId), &cs.last_status, 0);
577
578 /* Necessary for handle_v_kill. */
579 signal_pid = pi.dwProcessId;
580
581 return pi.dwProcessId;
582 }
583
584 /* Attach to a running process.
585 PID is the process ID to attach to, specified by the user
586 or a higher layer. */
587 int
588 win32_process_target::attach (unsigned long pid)
589 {
590 HANDLE h;
591 DWORD err;
592
593 h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
594 if (h != NULL)
595 {
596 if (DebugActiveProcess (pid))
597 {
598 DebugSetProcessKillOnExit (FALSE);
599
600 /* win32_wait needs to know we're attaching. */
601 windows_process.attaching = 1;
602 do_initial_child_stuff (h, pid, 1);
603 return 0;
604 }
605
606 CloseHandle (h);
607 }
608
609 err = GetLastError ();
610 throw_winerror_with_name ("Attach to process failed", err);
611 }
612
613 /* See nat/windows-nat.h. */
614
615 int
616 gdbserver_windows_process::handle_output_debug_string
617 (struct target_waitstatus *ourstatus)
618 {
619 #define READ_BUFFER_LEN 1024
620 CORE_ADDR addr;
621 char s[READ_BUFFER_LEN + 1] = { 0 };
622 DWORD nbytes = current_event.u.DebugString.nDebugStringLength;
623
624 if (nbytes == 0)
625 return 0;
626
627 if (nbytes > READ_BUFFER_LEN)
628 nbytes = READ_BUFFER_LEN;
629
630 addr = (CORE_ADDR) (size_t) current_event.u.DebugString.lpDebugStringData;
631
632 if (current_event.u.DebugString.fUnicode)
633 {
634 /* The event tells us how many bytes, not chars, even
635 in Unicode. */
636 WCHAR buffer[(READ_BUFFER_LEN + 1) / sizeof (WCHAR)] = { 0 };
637 if (read_inferior_memory (addr, (unsigned char *) buffer, nbytes) != 0)
638 return 0;
639 wcstombs (s, buffer, (nbytes + 1) / sizeof (WCHAR));
640 }
641 else
642 {
643 if (read_inferior_memory (addr, (unsigned char *) s, nbytes) != 0)
644 return 0;
645 }
646
647 if (!startswith (s, "cYg"))
648 {
649 if (!server_waiting)
650 {
651 OUTMSG2(("%s", s));
652 return 0;
653 }
654
655 monitor_output (s);
656 }
657 #undef READ_BUFFER_LEN
658
659 return 0;
660 }
661
662 static void
663 win32_clear_process ()
664 {
665 if (windows_process.open_process_used)
666 {
667 CloseHandle (windows_process.handle);
668 windows_process.open_process_used = false;
669 }
670
671 for_each_thread (delete_thread_info);
672 windows_process.siginfo_er.ExceptionCode = 0;
673 }
674
675 /* Implementation of target_ops::kill. */
676
677 int
678 win32_process_target::kill (process_info *process)
679 {
680 TerminateProcess (windows_process.handle, 0);
681 for (;;)
682 {
683 if (!child_continue (DBG_CONTINUE, -1))
684 break;
685 if (!wait_for_debug_event (&windows_process.current_event, INFINITE))
686 break;
687 if (windows_process.current_event.dwDebugEventCode
688 == EXIT_PROCESS_DEBUG_EVENT)
689 break;
690 else if (windows_process.current_event.dwDebugEventCode
691 == OUTPUT_DEBUG_STRING_EVENT)
692 windows_process.handle_output_debug_string (nullptr);
693 }
694
695 win32_clear_process ();
696 remove_process (process);
697
698 return 0;
699 }
700
701 /* Implementation of target_ops::detach. */
702
703 int
704 win32_process_target::detach (process_info *process)
705 {
706 struct thread_resume resume;
707 resume.thread = minus_one_ptid;
708 resume.kind = resume_continue;
709 resume.sig = 0;
710 this->resume (&resume, 1);
711
712 if (!DebugActiveProcessStop (process->pid))
713 return -1;
714
715 DebugSetProcessKillOnExit (FALSE);
716 win32_clear_process ();
717 remove_process (process);
718
719 return 0;
720 }
721
722 void
723 win32_process_target::mourn (struct process_info *process)
724 {
725 remove_process (process);
726 }
727
728 /* Implementation of target_ops::join. */
729
730 void
731 win32_process_target::join (int pid)
732 {
733 HANDLE h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
734 if (h != NULL)
735 {
736 WaitForSingleObject (h, INFINITE);
737 CloseHandle (h);
738 }
739 }
740
741 /* Return true iff the thread with thread ID TID is alive. */
742 bool
743 win32_process_target::thread_alive (ptid_t ptid)
744 {
745 /* Our thread list is reliable; don't bother to poll target
746 threads. */
747 return find_thread_ptid (ptid) != NULL;
748 }
749
750 /* Resume the inferior process. RESUME_INFO describes how we want
751 to resume. */
752 void
753 win32_process_target::resume (thread_resume *resume_info, size_t n)
754 {
755 DWORD tid;
756 enum gdb_signal sig;
757 int step;
758 windows_thread_info *th;
759 DWORD continue_status = DBG_CONTINUE;
760 ptid_t ptid;
761
762 /* This handles the very limited set of resume packets that GDB can
763 currently produce. */
764
765 if (n == 1 && resume_info[0].thread == minus_one_ptid)
766 tid = -1;
767 else if (n > 1)
768 tid = -1;
769 else
770 /* Yes, we're ignoring resume_info[0].thread. It'd be tricky to make
771 the Windows resume code do the right thing for thread switching. */
772 tid = windows_process.current_event.dwThreadId;
773
774 if (resume_info[0].thread != minus_one_ptid)
775 {
776 sig = gdb_signal_from_host (resume_info[0].sig);
777 step = resume_info[0].kind == resume_step;
778 }
779 else
780 {
781 sig = GDB_SIGNAL_0;
782 step = 0;
783 }
784
785 if (sig != GDB_SIGNAL_0)
786 {
787 if (windows_process.current_event.dwDebugEventCode
788 != EXCEPTION_DEBUG_EVENT)
789 {
790 OUTMSG (("Cannot continue with signal %s here.\n",
791 gdb_signal_to_string (sig)));
792 }
793 else if (sig == windows_process.last_sig)
794 continue_status = DBG_EXCEPTION_NOT_HANDLED;
795 else
796 OUTMSG (("Can only continue with received signal %s.\n",
797 gdb_signal_to_string (windows_process.last_sig)));
798 }
799
800 windows_process.last_sig = GDB_SIGNAL_0;
801
802 /* Get context for the currently selected thread. */
803 ptid = debug_event_ptid (&windows_process.current_event);
804 th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
805 if (th)
806 {
807 win32_prepare_to_resume (th);
808
809 DWORD *context_flags = windows_process.context_flags_ptr (th);
810 if (*context_flags)
811 {
812 /* Move register values from the inferior into the thread
813 context structure. */
814 regcache_invalidate ();
815
816 if (step)
817 {
818 if (the_low_target.single_step != NULL)
819 (*the_low_target.single_step) (th);
820 else
821 error ("Single stepping is not supported "
822 "in this configuration.\n");
823 }
824
825 win32_set_thread_context (th);
826 *context_flags = 0;
827 }
828 }
829
830 /* Allow continuing with the same signal that interrupted us.
831 Otherwise complain. */
832
833 child_continue (continue_status, tid);
834 }
835
836 /* See nat/windows-nat.h. */
837
838 void
839 gdbserver_windows_process::handle_load_dll (const char *name, LPVOID base)
840 {
841 CORE_ADDR load_addr = (CORE_ADDR) (uintptr_t) base;
842
843 char buf[MAX_PATH + 1];
844 char buf2[MAX_PATH + 1];
845
846 WIN32_FIND_DATAA w32_fd;
847 HANDLE h = FindFirstFileA (name, &w32_fd);
848
849 /* The symbols in a dll are offset by 0x1000, which is the
850 offset from 0 of the first byte in an image - because
851 of the file header and the section alignment. */
852 load_addr += 0x1000;
853
854 if (h == INVALID_HANDLE_VALUE)
855 strcpy (buf, name);
856 else
857 {
858 FindClose (h);
859 strcpy (buf, name);
860 {
861 char cwd[MAX_PATH + 1];
862 char *p;
863 if (GetCurrentDirectoryA (MAX_PATH + 1, cwd))
864 {
865 p = strrchr (buf, '\\');
866 if (p)
867 p[1] = '\0';
868 SetCurrentDirectoryA (buf);
869 GetFullPathNameA (w32_fd.cFileName, MAX_PATH, buf, &p);
870 SetCurrentDirectoryA (cwd);
871 }
872 }
873 }
874
875 if (strcasecmp (buf, "ntdll.dll") == 0)
876 {
877 GetSystemDirectoryA (buf, sizeof (buf));
878 strcat (buf, "\\ntdll.dll");
879 }
880
881 #ifdef __CYGWIN__
882 cygwin_conv_path (CCP_WIN_A_TO_POSIX, buf, buf2, sizeof (buf2));
883 #else
884 strcpy (buf2, buf);
885 #endif
886
887 loaded_dll (buf2, load_addr);
888 }
889
890 /* See nat/windows-nat.h. */
891
892 void
893 gdbserver_windows_process::handle_unload_dll ()
894 {
895 CORE_ADDR load_addr =
896 (CORE_ADDR) (uintptr_t) current_event.u.UnloadDll.lpBaseOfDll;
897
898 /* The symbols in a dll are offset by 0x1000, which is the
899 offset from 0 of the first byte in an image - because
900 of the file header and the section alignment. */
901 load_addr += 0x1000;
902 unloaded_dll (NULL, load_addr);
903 }
904
905 static void
906 suspend_one_thread (thread_info *thread)
907 {
908 auto th = static_cast<windows_thread_info *> (thread->target_data ());
909
910 th->suspend ();
911 }
912
913 static void
914 fake_breakpoint_event (void)
915 {
916 OUTMSG2(("fake_breakpoint_event\n"));
917
918 windows_process.faked_breakpoint = 1;
919
920 memset (&windows_process.current_event, 0,
921 sizeof (windows_process.current_event));
922 windows_process.current_event.dwThreadId = windows_process.main_thread_id;
923 windows_process.current_event.dwDebugEventCode = EXCEPTION_DEBUG_EVENT;
924 windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
925 = EXCEPTION_BREAKPOINT;
926
927 for_each_thread (suspend_one_thread);
928 }
929
930 /* See nat/windows-nat.h. */
931
932 bool
933 gdbserver_windows_process::handle_access_violation
934 (const EXCEPTION_RECORD *rec)
935 {
936 return false;
937 }
938
939 /* A helper function that will, if needed, set
940 'stopped_at_software_breakpoint' on the thread and adjust the
941 PC. */
942
943 static void
944 maybe_adjust_pc ()
945 {
946 regcache *regcache = get_thread_regcache (current_thread);
947 child_fetch_inferior_registers (regcache, -1);
948
949 windows_thread_info *th
950 = windows_process.thread_rec (current_thread->id,
951 DONT_INVALIDATE_CONTEXT);
952 th->stopped_at_software_breakpoint = false;
953
954 if (windows_process.current_event.dwDebugEventCode == EXCEPTION_DEBUG_EVENT
955 && ((windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
956 == EXCEPTION_BREAKPOINT)
957 || (windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
958 == STATUS_WX86_BREAKPOINT))
959 && windows_process.child_initialization_done)
960 {
961 th->stopped_at_software_breakpoint = true;
962 CORE_ADDR pc = regcache_read_pc (regcache);
963 CORE_ADDR sw_breakpoint_pc = pc - the_low_target.decr_pc_after_break;
964 regcache_write_pc (regcache, sw_breakpoint_pc);
965 }
966 }
967
968 /* Get the next event from the child. */
969
970 static int
971 get_child_debug_event (DWORD *continue_status,
972 struct target_waitstatus *ourstatus)
973 {
974 ptid_t ptid;
975
976 windows_process.last_sig = GDB_SIGNAL_0;
977 ourstatus->set_spurious ();
978 *continue_status = DBG_CONTINUE;
979
980 /* Check if GDB sent us an interrupt request. */
981 check_remote_input_interrupt_request ();
982
983 DEBUG_EVENT *current_event = &windows_process.current_event;
984
985 if (windows_process.soft_interrupt_requested)
986 {
987 windows_process.soft_interrupt_requested = 0;
988 fake_breakpoint_event ();
989 goto gotevent;
990 }
991
992 windows_process.attaching = 0;
993 {
994 std::optional<pending_stop> stop
995 = windows_process.fetch_pending_stop (debug_threads);
996 if (stop.has_value ())
997 {
998 *ourstatus = stop->status;
999 windows_process.current_event = stop->event;
1000 ptid = debug_event_ptid (&windows_process.current_event);
1001 switch_to_thread (find_thread_ptid (ptid));
1002 return 1;
1003 }
1004
1005 /* Keep the wait time low enough for comfortable remote
1006 interruption, but high enough so gdbserver doesn't become a
1007 bottleneck. */
1008 if (!wait_for_debug_event (&windows_process.current_event, 250))
1009 {
1010 DWORD e = GetLastError();
1011
1012 if (e == ERROR_PIPE_NOT_CONNECTED)
1013 {
1014 /* This will happen if the loader fails to successfully
1015 load the application, e.g., if the main executable
1016 tries to pull in a non-existing export from a
1017 DLL. */
1018 ourstatus->set_exited (1);
1019 return 1;
1020 }
1021
1022 return 0;
1023 }
1024 }
1025
1026 gotevent:
1027
1028 switch (current_event->dwDebugEventCode)
1029 {
1030 case CREATE_THREAD_DEBUG_EVENT:
1031 OUTMSG2 (("gdbserver: kernel event CREATE_THREAD_DEBUG_EVENT "
1032 "for pid=%u tid=%x)\n",
1033 (unsigned) current_event->dwProcessId,
1034 (unsigned) current_event->dwThreadId));
1035
1036 /* Record the existence of this thread. */
1037 child_add_thread (current_event->dwProcessId,
1038 current_event->dwThreadId,
1039 current_event->u.CreateThread.hThread,
1040 current_event->u.CreateThread.lpThreadLocalBase);
1041 break;
1042
1043 case EXIT_THREAD_DEBUG_EVENT:
1044 OUTMSG2 (("gdbserver: kernel event EXIT_THREAD_DEBUG_EVENT "
1045 "for pid=%u tid=%x\n",
1046 (unsigned) current_event->dwProcessId,
1047 (unsigned) current_event->dwThreadId));
1048 child_delete_thread (current_event->dwProcessId,
1049 current_event->dwThreadId);
1050
1051 switch_to_thread (get_first_thread ());
1052 return 1;
1053
1054 case CREATE_PROCESS_DEBUG_EVENT:
1055 OUTMSG2 (("gdbserver: kernel event CREATE_PROCESS_DEBUG_EVENT "
1056 "for pid=%u tid=%x\n",
1057 (unsigned) current_event->dwProcessId,
1058 (unsigned) current_event->dwThreadId));
1059 CloseHandle (current_event->u.CreateProcessInfo.hFile);
1060
1061 if (windows_process.open_process_used)
1062 {
1063 CloseHandle (windows_process.handle);
1064 windows_process.open_process_used = false;
1065 }
1066
1067 windows_process.handle = current_event->u.CreateProcessInfo.hProcess;
1068 windows_process.main_thread_id = current_event->dwThreadId;
1069
1070 /* Add the main thread. */
1071 child_add_thread (current_event->dwProcessId,
1072 windows_process.main_thread_id,
1073 current_event->u.CreateProcessInfo.hThread,
1074 current_event->u.CreateProcessInfo.lpThreadLocalBase);
1075 break;
1076
1077 case EXIT_PROCESS_DEBUG_EVENT:
1078 OUTMSG2 (("gdbserver: kernel event EXIT_PROCESS_DEBUG_EVENT "
1079 "for pid=%u tid=%x\n",
1080 (unsigned) current_event->dwProcessId,
1081 (unsigned) current_event->dwThreadId));
1082 {
1083 DWORD exit_status = current_event->u.ExitProcess.dwExitCode;
1084 /* If the exit status looks like a fatal exception, but we
1085 don't recognize the exception's code, make the original
1086 exit status value available, to avoid losing information. */
1087 int exit_signal
1088 = WIFSIGNALED (exit_status) ? WTERMSIG (exit_status) : -1;
1089 if (exit_signal == -1)
1090 ourstatus->set_exited (exit_status);
1091 else
1092 ourstatus->set_signalled (gdb_signal_from_host (exit_signal));
1093 }
1094 child_continue (DBG_CONTINUE, windows_process.desired_stop_thread_id);
1095 break;
1096
1097 case LOAD_DLL_DEBUG_EVENT:
1098 OUTMSG2 (("gdbserver: kernel event LOAD_DLL_DEBUG_EVENT "
1099 "for pid=%u tid=%x\n",
1100 (unsigned) current_event->dwProcessId,
1101 (unsigned) current_event->dwThreadId));
1102 CloseHandle (current_event->u.LoadDll.hFile);
1103 if (! windows_process.child_initialization_done)
1104 break;
1105 windows_process.dll_loaded_event ();
1106
1107 ourstatus->set_loaded ();
1108 break;
1109
1110 case UNLOAD_DLL_DEBUG_EVENT:
1111 OUTMSG2 (("gdbserver: kernel event UNLOAD_DLL_DEBUG_EVENT "
1112 "for pid=%u tid=%x\n",
1113 (unsigned) current_event->dwProcessId,
1114 (unsigned) current_event->dwThreadId));
1115 if (! windows_process.child_initialization_done)
1116 break;
1117 windows_process.handle_unload_dll ();
1118 ourstatus->set_loaded ();
1119 break;
1120
1121 case EXCEPTION_DEBUG_EVENT:
1122 OUTMSG2 (("gdbserver: kernel event EXCEPTION_DEBUG_EVENT "
1123 "for pid=%u tid=%x\n",
1124 (unsigned) current_event->dwProcessId,
1125 (unsigned) current_event->dwThreadId));
1126 if (windows_process.handle_exception (ourstatus, debug_threads)
1127 == HANDLE_EXCEPTION_UNHANDLED)
1128 *continue_status = DBG_EXCEPTION_NOT_HANDLED;
1129 break;
1130
1131 case OUTPUT_DEBUG_STRING_EVENT:
1132 /* A message from the kernel (or Cygwin). */
1133 OUTMSG2 (("gdbserver: kernel event OUTPUT_DEBUG_STRING_EVENT "
1134 "for pid=%u tid=%x\n",
1135 (unsigned) current_event->dwProcessId,
1136 (unsigned) current_event->dwThreadId));
1137 windows_process.handle_output_debug_string (nullptr);
1138 break;
1139
1140 default:
1141 OUTMSG2 (("gdbserver: kernel event unknown "
1142 "for pid=%u tid=%x code=%x\n",
1143 (unsigned) current_event->dwProcessId,
1144 (unsigned) current_event->dwThreadId,
1145 (unsigned) current_event->dwDebugEventCode));
1146 break;
1147 }
1148
1149 ptid = debug_event_ptid (&windows_process.current_event);
1150
1151 if (windows_process.desired_stop_thread_id != -1
1152 && windows_process.desired_stop_thread_id != ptid.lwp ())
1153 {
1154 /* Pending stop. See the comment by the definition of
1155 "pending_stops" for details on why this is needed. */
1156 OUTMSG2 (("get_windows_debug_event - "
1157 "unexpected stop in 0x%lx (expecting 0x%x)\n",
1158 ptid.lwp (), windows_process.desired_stop_thread_id));
1159 maybe_adjust_pc ();
1160 windows_process.pending_stops.push_back
1161 ({(DWORD) ptid.lwp (), *ourstatus, *current_event});
1162 ourstatus->set_spurious ();
1163 }
1164 else
1165 switch_to_thread (find_thread_ptid (ptid));
1166
1167 return 1;
1168 }
1169
1170 /* Wait for the inferior process to change state.
1171 STATUS will be filled in with a response code to send to GDB.
1172 Returns the signal which caused the process to stop. */
1173 ptid_t
1174 win32_process_target::wait (ptid_t ptid, target_waitstatus *ourstatus,
1175 target_wait_flags options)
1176 {
1177 if (windows_process.cached_status.kind () != TARGET_WAITKIND_IGNORE)
1178 {
1179 /* The core always does a wait after creating the inferior, and
1180 do_initial_child_stuff already ran the inferior to the
1181 initial breakpoint (or an exit, if creating the process
1182 fails). Report it now. */
1183 *ourstatus = windows_process.cached_status;
1184 windows_process.cached_status.set_ignore ();
1185 return debug_event_ptid (&windows_process.current_event);
1186 }
1187
1188 while (1)
1189 {
1190 DWORD continue_status;
1191 if (!get_child_debug_event (&continue_status, ourstatus))
1192 continue;
1193
1194 switch (ourstatus->kind ())
1195 {
1196 case TARGET_WAITKIND_EXITED:
1197 OUTMSG2 (("Child exited with retcode = %x\n",
1198 ourstatus->exit_status ()));
1199 win32_clear_process ();
1200 return ptid_t (windows_process.current_event.dwProcessId);
1201 case TARGET_WAITKIND_STOPPED:
1202 case TARGET_WAITKIND_SIGNALLED:
1203 case TARGET_WAITKIND_LOADED:
1204 {
1205 OUTMSG2 (("Child Stopped with signal = %d \n",
1206 ourstatus->sig ()));
1207 maybe_adjust_pc ();
1208 return debug_event_ptid (&windows_process.current_event);
1209 }
1210 default:
1211 OUTMSG (("Ignoring unknown internal event, %d\n",
1212 ourstatus->kind ()));
1213 [[fallthrough]];
1214 case TARGET_WAITKIND_SPURIOUS:
1215 /* do nothing, just continue */
1216 child_continue (continue_status,
1217 windows_process.desired_stop_thread_id);
1218 break;
1219 }
1220 }
1221 }
1222
1223 /* Fetch registers from the inferior process.
1224 If REGNO is -1, fetch all registers; otherwise, fetch at least REGNO. */
1225 void
1226 win32_process_target::fetch_registers (regcache *regcache, int regno)
1227 {
1228 child_fetch_inferior_registers (regcache, regno);
1229 }
1230
1231 /* Store registers to the inferior process.
1232 If REGNO is -1, store all registers; otherwise, store at least REGNO. */
1233 void
1234 win32_process_target::store_registers (regcache *regcache, int regno)
1235 {
1236 child_store_inferior_registers (regcache, regno);
1237 }
1238
1239 /* Read memory from the inferior process. This should generally be
1240 called through read_inferior_memory, which handles breakpoint shadowing.
1241 Read LEN bytes at MEMADDR into a buffer at MYADDR. */
1242 int
1243 win32_process_target::read_memory (CORE_ADDR memaddr, unsigned char *myaddr,
1244 int len)
1245 {
1246 return child_xfer_memory (memaddr, (char *) myaddr, len, 0, 0) != len;
1247 }
1248
1249 /* Write memory to the inferior process. This should generally be
1250 called through write_inferior_memory, which handles breakpoint shadowing.
1251 Write LEN bytes from the buffer at MYADDR to MEMADDR.
1252 Returns 0 on success and errno on failure. */
1253 int
1254 win32_process_target::write_memory (CORE_ADDR memaddr,
1255 const unsigned char *myaddr, int len)
1256 {
1257 return child_xfer_memory (memaddr, (char *) myaddr, len, 1, 0) != len;
1258 }
1259
1260 /* Send an interrupt request to the inferior process. */
1261 void
1262 win32_process_target::request_interrupt ()
1263 {
1264 if (GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, signal_pid))
1265 return;
1266
1267 /* GenerateConsoleCtrlEvent can fail if process id being debugged is
1268 not a process group id.
1269 Fallback to XP/Vista 'DebugBreakProcess', which generates a
1270 breakpoint exception in the interior process. */
1271
1272 if (DebugBreakProcess (windows_process.handle))
1273 return;
1274
1275 /* Last resort, suspend all threads manually. */
1276 windows_process.soft_interrupt_requested = 1;
1277 }
1278
1279 bool
1280 win32_process_target::supports_hardware_single_step ()
1281 {
1282 return true;
1283 }
1284
1285 bool
1286 win32_process_target::supports_qxfer_siginfo ()
1287 {
1288 return true;
1289 }
1290
1291 /* Write Windows signal info. */
1292
1293 int
1294 win32_process_target::qxfer_siginfo (const char *annex,
1295 unsigned char *readbuf,
1296 unsigned const char *writebuf,
1297 CORE_ADDR offset, int len)
1298 {
1299 if (windows_process.siginfo_er.ExceptionCode == 0)
1300 return -1;
1301
1302 if (readbuf == nullptr)
1303 return -1;
1304
1305 char *buf = (char *) &windows_process.siginfo_er;
1306 size_t bufsize = sizeof (windows_process.siginfo_er);
1307
1308 #ifdef __x86_64__
1309 EXCEPTION_RECORD32 er32;
1310 if (windows_process.wow64_process)
1311 {
1312 buf = (char *) &er32;
1313 bufsize = sizeof (er32);
1314
1315 er32.ExceptionCode = windows_process.siginfo_er.ExceptionCode;
1316 er32.ExceptionFlags = windows_process.siginfo_er.ExceptionFlags;
1317 er32.ExceptionRecord
1318 = (uintptr_t) windows_process.siginfo_er.ExceptionRecord;
1319 er32.ExceptionAddress
1320 = (uintptr_t) windows_process.siginfo_er.ExceptionAddress;
1321 er32.NumberParameters = windows_process.siginfo_er.NumberParameters;
1322 int i;
1323 for (i = 0; i < EXCEPTION_MAXIMUM_PARAMETERS; i++)
1324 er32.ExceptionInformation[i]
1325 = windows_process.siginfo_er.ExceptionInformation[i];
1326 }
1327 #endif
1328
1329 if (offset > bufsize)
1330 return -1;
1331
1332 if (offset + len > bufsize)
1333 len = bufsize - offset;
1334
1335 memcpy (readbuf, buf + offset, len);
1336
1337 return len;
1338 }
1339
1340 bool
1341 win32_process_target::supports_get_tib_address ()
1342 {
1343 return true;
1344 }
1345
1346 /* Write Windows OS Thread Information Block address. */
1347
1348 int
1349 win32_process_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
1350 {
1351 windows_thread_info *th;
1352 th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
1353 if (th == NULL)
1354 return 0;
1355 if (addr != NULL)
1356 *addr = th->thread_local_base;
1357 return 1;
1358 }
1359
1360 /* Implementation of the target_ops method "sw_breakpoint_from_kind". */
1361
1362 const gdb_byte *
1363 win32_process_target::sw_breakpoint_from_kind (int kind, int *size)
1364 {
1365 *size = the_low_target.breakpoint_len;
1366 return the_low_target.breakpoint;
1367 }
1368
1369 bool
1370 win32_process_target::stopped_by_sw_breakpoint ()
1371 {
1372 windows_thread_info *th
1373 = windows_process.thread_rec (current_thread->id,
1374 DONT_INVALIDATE_CONTEXT);
1375 return th == nullptr ? false : th->stopped_at_software_breakpoint;
1376 }
1377
1378 bool
1379 win32_process_target::supports_stopped_by_sw_breakpoint ()
1380 {
1381 return true;
1382 }
1383
1384 CORE_ADDR
1385 win32_process_target::read_pc (struct regcache *regcache)
1386 {
1387 return (*the_low_target.get_pc) (regcache);
1388 }
1389
1390 void
1391 win32_process_target::write_pc (struct regcache *regcache, CORE_ADDR pc)
1392 {
1393 return (*the_low_target.set_pc) (regcache, pc);
1394 }
1395
1396 const char *
1397 win32_process_target::thread_name (ptid_t thread)
1398 {
1399 windows_thread_info *th
1400 = windows_process.thread_rec (current_thread->id,
1401 DONT_INVALIDATE_CONTEXT);
1402 return th->thread_name ();
1403 }
1404
1405 const char *
1406 win32_process_target::pid_to_exec_file (int pid)
1407 {
1408 return windows_process.pid_to_exec_file (pid);
1409 }
1410
1411 /* The win32 target ops object. */
1412
1413 static win32_process_target the_win32_target;
1414
1415 /* Initialize the Win32 backend. */
1416 void
1417 initialize_low (void)
1418 {
1419 set_target_ops (&the_win32_target);
1420 the_low_target.arch_setup ();
1421
1422 initialize_loadable ();
1423 }
1424