gdb/testsuite: Reduce gdb.threads/threadcrash.exp reliance on libc symbols
[binutils-gdb.git] / gdbserver / win32-low.cc
blob58e8b089f2e46bbe803ac241deb4587428616299
1 /* Low level interface to Windows debugging, for gdbserver.
2 Copyright (C) 2006-2024 Free Software Foundation, Inc.
4 Contributed by Leo Zayas. Based on "win32-nat.c" from GDB.
6 This file is part of GDB.
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.
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.
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/>. */
21 #include "server.h"
22 #include "regcache.h"
23 #include "gdbsupport/fileio.h"
24 #include "mem-break.h"
25 #include "win32-low.h"
26 #include "gdbthread.h"
27 #include "dll.h"
28 #include "hostio.h"
29 #include <windows.h>
30 #include <winnt.h>
31 #include <imagehlp.h>
32 #include <tlhelp32.h>
33 #include <psapi.h>
34 #include <process.h>
35 #include "gdbsupport/gdb_tilde_expand.h"
36 #include "gdbsupport/common-inferior.h"
37 #include "gdbsupport/gdb_wait.h"
39 using namespace windows_nat;
41 /* See win32-low.h. */
42 gdbserver_windows_process windows_process;
44 #ifndef USE_WIN32API
45 #include <sys/cygwin.h>
46 #endif
48 #define OUTMSG(X) do { printf X; fflush (stderr); } while (0)
50 #define OUTMSG2(X) \
51 do \
52 { \
53 if (debug_threads) \
54 { \
55 printf X; \
56 fflush (stderr); \
57 } \
58 } while (0)
60 #ifndef _T
61 #define _T(x) TEXT (x)
62 #endif
64 int using_threads = 1;
66 const struct target_desc *win32_tdesc;
67 #ifdef __x86_64__
68 const struct target_desc *wow64_win32_tdesc;
69 #endif
71 #define NUM_REGS (the_low_target.num_regs ())
73 /* Get the thread ID from the current selected inferior (the current
74 thread). */
75 static ptid_t
76 current_thread_ptid (void)
78 return current_ptid;
81 /* The current debug event from WaitForDebugEvent. */
82 static ptid_t
83 debug_event_ptid (DEBUG_EVENT *event)
85 return ptid_t (event->dwProcessId, event->dwThreadId, 0);
88 /* Get the thread context of the thread associated with TH. */
90 static void
91 win32_get_thread_context (windows_thread_info *th)
93 #ifdef __x86_64__
94 if (windows_process.wow64_process)
95 memset (&th->wow64_context, 0, sizeof (WOW64_CONTEXT));
96 else
97 #endif
98 memset (&th->context, 0, sizeof (CONTEXT));
99 (*the_low_target.get_thread_context) (th);
102 /* Set the thread context of the thread associated with TH. */
104 static void
105 win32_set_thread_context (windows_thread_info *th)
107 #ifdef __x86_64__
108 if (windows_process.wow64_process)
109 Wow64SetThreadContext (th->h, &th->wow64_context);
110 else
111 #endif
112 SetThreadContext (th->h, &th->context);
115 /* Set the thread context of the thread associated with TH. */
117 static void
118 win32_prepare_to_resume (windows_thread_info *th)
120 if (the_low_target.prepare_to_resume != NULL)
121 (*the_low_target.prepare_to_resume) (th);
124 /* See win32-low.h. */
126 void
127 win32_require_context (windows_thread_info *th)
129 DWORD context_flags;
130 #ifdef __x86_64__
131 if (windows_process.wow64_process)
132 context_flags = th->wow64_context.ContextFlags;
133 else
134 #endif
135 context_flags = th->context.ContextFlags;
136 if (context_flags == 0)
138 th->suspend ();
139 win32_get_thread_context (th);
143 /* See nat/windows-nat.h. */
145 windows_thread_info *
146 gdbserver_windows_process::thread_rec
147 (ptid_t ptid, thread_disposition_type disposition)
149 thread_info *thread = find_thread_ptid (ptid);
150 if (thread == NULL)
151 return NULL;
153 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread);
154 if (disposition != DONT_INVALIDATE_CONTEXT)
155 win32_require_context (th);
156 return th;
159 /* Add a thread to the thread list. */
160 static windows_thread_info *
161 child_add_thread (DWORD pid, DWORD tid, HANDLE h, void *tlb)
163 windows_thread_info *th;
164 ptid_t ptid = ptid_t (pid, tid, 0);
166 if ((th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT)))
167 return th;
169 CORE_ADDR base = (CORE_ADDR) (uintptr_t) tlb;
170 #ifdef __x86_64__
171 /* For WOW64 processes, this is actually the pointer to the 64bit TIB,
172 and the 32bit TIB is exactly 2 pages after it. */
173 if (windows_process.wow64_process)
174 base += 2 * 4096; /* page size = 4096 */
175 #endif
176 th = new windows_thread_info (tid, h, base);
178 add_thread (ptid, th);
180 if (the_low_target.thread_added != NULL)
181 (*the_low_target.thread_added) (th);
183 return th;
186 /* Delete a thread from the list of threads. */
187 static void
188 delete_thread_info (thread_info *thread)
190 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread);
192 remove_thread (thread);
193 delete th;
196 /* Delete a thread from the list of threads. */
197 static void
198 child_delete_thread (DWORD pid, DWORD tid)
200 /* If the last thread is exiting, just return. */
201 if (all_threads.size () == 1)
202 return;
204 thread_info *thread = find_thread_ptid (ptid_t (pid, tid));
205 if (thread == NULL)
206 return;
208 delete_thread_info (thread);
211 /* These watchpoint related wrapper functions simply pass on the function call
212 if the low target has registered a corresponding function. */
214 bool
215 win32_process_target::supports_z_point_type (char z_type)
217 return (z_type == Z_PACKET_SW_BP
218 || (the_low_target.supports_z_point_type != NULL
219 && the_low_target.supports_z_point_type (z_type)));
223 win32_process_target::insert_point (enum raw_bkpt_type type, CORE_ADDR addr,
224 int size, raw_breakpoint *bp)
226 if (type == raw_bkpt_type_sw)
227 return insert_memory_breakpoint (bp);
228 else if (the_low_target.insert_point != NULL)
229 return the_low_target.insert_point (type, addr, size, bp);
230 else
231 /* Unsupported (see target.h). */
232 return 1;
236 win32_process_target::remove_point (enum raw_bkpt_type type, CORE_ADDR addr,
237 int size, raw_breakpoint *bp)
239 if (type == raw_bkpt_type_sw)
240 return remove_memory_breakpoint (bp);
241 else if (the_low_target.remove_point != NULL)
242 return the_low_target.remove_point (type, addr, size, bp);
243 else
244 /* Unsupported (see target.h). */
245 return 1;
248 bool
249 win32_process_target::stopped_by_watchpoint ()
251 if (the_low_target.stopped_by_watchpoint != NULL)
252 return the_low_target.stopped_by_watchpoint ();
253 else
254 return false;
257 CORE_ADDR
258 win32_process_target::stopped_data_address ()
260 if (the_low_target.stopped_data_address != NULL)
261 return the_low_target.stopped_data_address ();
262 else
263 return 0;
267 /* Transfer memory from/to the debugged process. */
268 static int
269 child_xfer_memory (CORE_ADDR memaddr, char *our, int len,
270 int write, process_stratum_target *target)
272 BOOL success;
273 SIZE_T done = 0;
274 DWORD lasterror = 0;
275 uintptr_t addr = (uintptr_t) memaddr;
277 if (write)
279 success = WriteProcessMemory (windows_process.handle, (LPVOID) addr,
280 (LPCVOID) our, len, &done);
281 if (!success)
282 lasterror = GetLastError ();
283 FlushInstructionCache (windows_process.handle, (LPCVOID) addr, len);
285 else
287 success = ReadProcessMemory (windows_process.handle, (LPCVOID) addr,
288 (LPVOID) our, len, &done);
289 if (!success)
290 lasterror = GetLastError ();
292 if (!success && lasterror == ERROR_PARTIAL_COPY && done > 0)
293 return done;
294 else
295 return success ? done : -1;
298 /* Clear out any old thread list and reinitialize it to a pristine
299 state. */
300 static void
301 child_init_thread_list (void)
303 for_each_thread (delete_thread_info);
306 static void
307 do_initial_child_stuff (HANDLE proch, DWORD pid, int attached)
309 struct process_info *proc;
311 windows_process.last_sig = GDB_SIGNAL_0;
312 windows_process.handle = proch;
313 windows_process.main_thread_id = 0;
315 windows_process.soft_interrupt_requested = 0;
316 windows_process.faked_breakpoint = 0;
317 windows_process.open_process_used = true;
319 memset (&windows_process.current_event, 0,
320 sizeof (windows_process.current_event));
322 #ifdef __x86_64__
323 BOOL wow64;
324 if (!IsWow64Process (proch, &wow64))
326 DWORD err = GetLastError ();
327 throw_winerror_with_name ("Check if WOW64 process failed", err);
329 windows_process.wow64_process = wow64;
331 if (windows_process.wow64_process
332 && (Wow64GetThreadContext == nullptr
333 || Wow64SetThreadContext == nullptr))
334 error ("WOW64 debugging is not supported on this system.\n");
336 windows_process.ignore_first_breakpoint
337 = !attached && windows_process.wow64_process;
338 #endif
340 proc = add_process (pid, attached);
341 #ifdef __x86_64__
342 if (windows_process.wow64_process)
343 proc->tdesc = wow64_win32_tdesc;
344 else
345 #endif
346 proc->tdesc = win32_tdesc;
347 child_init_thread_list ();
348 windows_process.child_initialization_done = 0;
350 if (the_low_target.initial_stuff != NULL)
351 (*the_low_target.initial_stuff) ();
353 windows_process.cached_status.set_ignore ();
355 /* Flush all currently pending debug events (thread and dll list) up
356 to the initial breakpoint. */
357 while (1)
359 struct target_waitstatus status;
361 the_target->wait (minus_one_ptid, &status, 0);
363 /* Note win32_wait doesn't return thread events. */
364 if (status.kind () != TARGET_WAITKIND_LOADED)
366 windows_process.cached_status = status;
367 break;
371 struct thread_resume resume;
373 resume.thread = minus_one_ptid;
374 resume.kind = resume_continue;
375 resume.sig = 0;
377 the_target->resume (&resume, 1);
381 /* Now that the inferior has been started and all DLLs have been mapped,
382 we can iterate over all DLLs and load them in.
384 We avoid doing it any earlier because, on certain versions of Windows,
385 LOAD_DLL_DEBUG_EVENTs are sometimes not complete. In particular,
386 we have seen on Windows 8.1 that the ntdll.dll load event does not
387 include the DLL name, preventing us from creating an associated SO.
388 A possible explanation is that ntdll.dll might be mapped before
389 the SO info gets created by the Windows system -- ntdll.dll is
390 the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs
391 do not seem to suffer from that problem.
393 Rather than try to work around this sort of issue, it is much
394 simpler to just ignore DLL load/unload events during the startup
395 phase, and then process them all in one batch now. */
396 windows_process.add_all_dlls ();
398 windows_process.child_initialization_done = 1;
401 /* Resume all artificially suspended threads if we are continuing
402 execution. */
403 static void
404 continue_one_thread (thread_info *thread, int thread_id)
406 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread);
408 if (thread_id == -1 || thread_id == th->tid)
410 win32_prepare_to_resume (th);
412 if (th->suspended)
414 DWORD *context_flags;
415 #ifdef __x86_64__
416 if (windows_process.wow64_process)
417 context_flags = &th->wow64_context.ContextFlags;
418 else
419 #endif
420 context_flags = &th->context.ContextFlags;
421 if (*context_flags)
423 win32_set_thread_context (th);
424 *context_flags = 0;
427 th->resume ();
432 static BOOL
433 child_continue (DWORD continue_status, int thread_id)
435 windows_process.desired_stop_thread_id = thread_id;
436 if (windows_process.matching_pending_stop (debug_threads))
437 return TRUE;
439 /* The inferior will only continue after the ContinueDebugEvent
440 call. */
441 for_each_thread ([&] (thread_info *thread)
443 continue_one_thread (thread, thread_id);
445 windows_process.faked_breakpoint = 0;
447 return continue_last_debug_event (continue_status, debug_threads);
450 /* Fetch register(s) from the current thread context. */
451 static void
452 child_fetch_inferior_registers (struct regcache *regcache, int r)
454 int regno;
455 windows_thread_info *th
456 = windows_process.thread_rec (current_thread_ptid (),
457 INVALIDATE_CONTEXT);
458 if (r == -1 || r > NUM_REGS)
459 child_fetch_inferior_registers (regcache, NUM_REGS);
460 else
461 for (regno = 0; regno < r; regno++)
462 (*the_low_target.fetch_inferior_register) (regcache, th, regno);
465 /* Store a new register value into the current thread context. We don't
466 change the program's context until later, when we resume it. */
467 static void
468 child_store_inferior_registers (struct regcache *regcache, int r)
470 int regno;
471 windows_thread_info *th
472 = windows_process.thread_rec (current_thread_ptid (),
473 INVALIDATE_CONTEXT);
474 if (r == -1 || r == 0 || r > NUM_REGS)
475 child_store_inferior_registers (regcache, NUM_REGS);
476 else
477 for (regno = 0; regno < r; regno++)
478 (*the_low_target.store_inferior_register) (regcache, th, regno);
481 static BOOL
482 create_process (const char *program, char *args,
483 DWORD flags, PROCESS_INFORMATION *pi)
485 const std::string &inferior_cwd = get_inferior_cwd ();
486 BOOL ret;
487 size_t argslen, proglen;
489 proglen = strlen (program) + 1;
490 argslen = strlen (args) + proglen;
492 STARTUPINFOA si = { sizeof (STARTUPINFOA) };
493 char *program_and_args = (char *) alloca (argslen + 1);
495 strcpy (program_and_args, program);
496 strcat (program_and_args, " ");
497 strcat (program_and_args, args);
498 ret = create_process (program, /* image name */
499 program_and_args, /* command line */
500 flags, /* start flags */
501 NULL, /* environment */
502 /* current directory */
503 (inferior_cwd.empty ()
504 ? NULL
505 : gdb_tilde_expand (inferior_cwd.c_str ()).c_str()),
506 get_client_state ().disable_randomization,
507 &si, /* start info */
508 pi); /* proc info */
510 return ret;
513 /* Start a new process.
514 PROGRAM is the program name.
515 PROGRAM_ARGS is the vector containing the inferior's args.
516 Returns the new PID on success, -1 on failure. Registers the new
517 process with the process list. */
519 win32_process_target::create_inferior (const char *program,
520 const std::vector<char *> &program_args)
522 client_state &cs = get_client_state ();
523 #ifndef USE_WIN32API
524 char real_path[PATH_MAX];
525 char *orig_path, *new_path, *path_ptr;
526 #endif
527 BOOL ret;
528 DWORD flags;
529 PROCESS_INFORMATION pi;
530 DWORD err;
531 std::string str_program_args = construct_inferior_arguments (program_args);
532 char *args = (char *) str_program_args.c_str ();
534 /* win32_wait needs to know we're not attaching. */
535 windows_process.attaching = 0;
537 if (!program)
538 error ("No executable specified, specify executable to debug.\n");
540 flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS;
542 #ifndef USE_WIN32API
543 orig_path = NULL;
544 path_ptr = getenv ("PATH");
545 if (path_ptr)
547 int size = cygwin_conv_path_list (CCP_POSIX_TO_WIN_A, path_ptr, NULL, 0);
548 orig_path = (char *) alloca (strlen (path_ptr) + 1);
549 new_path = (char *) alloca (size);
550 strcpy (orig_path, path_ptr);
551 cygwin_conv_path_list (CCP_POSIX_TO_WIN_A, path_ptr, new_path, size);
552 setenv ("PATH", new_path, 1);
554 cygwin_conv_path (CCP_POSIX_TO_WIN_A, program, real_path, PATH_MAX);
555 program = real_path;
556 #endif
558 OUTMSG2 (("Command line is \"%s %s\"\n", program, args));
560 #ifdef CREATE_NEW_PROCESS_GROUP
561 flags |= CREATE_NEW_PROCESS_GROUP;
562 #endif
564 ret = create_process (program, args, flags, &pi);
565 err = GetLastError ();
566 if (!ret && err == ERROR_FILE_NOT_FOUND)
568 char *exename = (char *) alloca (strlen (program) + 5);
569 strcat (strcpy (exename, program), ".exe");
570 ret = create_process (exename, args, flags, &pi);
571 err = GetLastError ();
574 #ifndef USE_WIN32API
575 if (orig_path)
576 setenv ("PATH", orig_path, 1);
577 #endif
579 if (!ret)
581 std::string msg = string_printf (_("Error creating process \"%s %s\""),
582 program, args);
583 throw_winerror_with_name (msg.c_str (), err);
585 else
587 OUTMSG2 (("Process created: %s %s\n", program, (char *) args));
590 CloseHandle (pi.hThread);
592 do_initial_child_stuff (pi.hProcess, pi.dwProcessId, 0);
594 /* Wait till we are at 1st instruction in program, return new pid
595 (assuming success). */
596 cs.last_ptid = wait (ptid_t (pi.dwProcessId), &cs.last_status, 0);
598 /* Necessary for handle_v_kill. */
599 signal_pid = pi.dwProcessId;
601 return pi.dwProcessId;
604 /* Attach to a running process.
605 PID is the process ID to attach to, specified by the user
606 or a higher layer. */
608 win32_process_target::attach (unsigned long pid)
610 HANDLE h;
611 DWORD err;
613 h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
614 if (h != NULL)
616 if (DebugActiveProcess (pid))
618 DebugSetProcessKillOnExit (FALSE);
620 /* win32_wait needs to know we're attaching. */
621 windows_process.attaching = 1;
622 do_initial_child_stuff (h, pid, 1);
623 return 0;
626 CloseHandle (h);
629 err = GetLastError ();
630 throw_winerror_with_name ("Attach to process failed", err);
633 /* See nat/windows-nat.h. */
636 gdbserver_windows_process::handle_output_debug_string
637 (struct target_waitstatus *ourstatus)
639 #define READ_BUFFER_LEN 1024
640 CORE_ADDR addr;
641 char s[READ_BUFFER_LEN + 1] = { 0 };
642 DWORD nbytes = current_event.u.DebugString.nDebugStringLength;
644 if (nbytes == 0)
645 return 0;
647 if (nbytes > READ_BUFFER_LEN)
648 nbytes = READ_BUFFER_LEN;
650 addr = (CORE_ADDR) (size_t) current_event.u.DebugString.lpDebugStringData;
652 if (current_event.u.DebugString.fUnicode)
654 /* The event tells us how many bytes, not chars, even
655 in Unicode. */
656 WCHAR buffer[(READ_BUFFER_LEN + 1) / sizeof (WCHAR)] = { 0 };
657 if (read_inferior_memory (addr, (unsigned char *) buffer, nbytes) != 0)
658 return 0;
659 wcstombs (s, buffer, (nbytes + 1) / sizeof (WCHAR));
661 else
663 if (read_inferior_memory (addr, (unsigned char *) s, nbytes) != 0)
664 return 0;
667 if (!startswith (s, "cYg"))
669 if (!server_waiting)
671 OUTMSG2(("%s", s));
672 return 0;
675 monitor_output (s);
677 #undef READ_BUFFER_LEN
679 return 0;
682 static void
683 win32_clear_inferiors (void)
685 if (windows_process.open_process_used)
687 CloseHandle (windows_process.handle);
688 windows_process.open_process_used = false;
691 for_each_thread (delete_thread_info);
692 windows_process.siginfo_er.ExceptionCode = 0;
693 clear_inferiors ();
696 /* Implementation of target_ops::kill. */
699 win32_process_target::kill (process_info *process)
701 TerminateProcess (windows_process.handle, 0);
702 for (;;)
704 if (!child_continue (DBG_CONTINUE, -1))
705 break;
706 if (!wait_for_debug_event (&windows_process.current_event, INFINITE))
707 break;
708 if (windows_process.current_event.dwDebugEventCode
709 == EXIT_PROCESS_DEBUG_EVENT)
710 break;
711 else if (windows_process.current_event.dwDebugEventCode
712 == OUTPUT_DEBUG_STRING_EVENT)
713 windows_process.handle_output_debug_string (nullptr);
716 win32_clear_inferiors ();
718 remove_process (process);
719 return 0;
722 /* Implementation of target_ops::detach. */
725 win32_process_target::detach (process_info *process)
727 struct thread_resume resume;
728 resume.thread = minus_one_ptid;
729 resume.kind = resume_continue;
730 resume.sig = 0;
731 this->resume (&resume, 1);
733 if (!DebugActiveProcessStop (process->pid))
734 return -1;
736 DebugSetProcessKillOnExit (FALSE);
737 win32_clear_inferiors ();
738 remove_process (process);
740 return 0;
743 void
744 win32_process_target::mourn (struct process_info *process)
746 remove_process (process);
749 /* Implementation of target_ops::join. */
751 void
752 win32_process_target::join (int pid)
754 HANDLE h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
755 if (h != NULL)
757 WaitForSingleObject (h, INFINITE);
758 CloseHandle (h);
762 /* Return true iff the thread with thread ID TID is alive. */
763 bool
764 win32_process_target::thread_alive (ptid_t ptid)
766 /* Our thread list is reliable; don't bother to poll target
767 threads. */
768 return find_thread_ptid (ptid) != NULL;
771 /* Resume the inferior process. RESUME_INFO describes how we want
772 to resume. */
773 void
774 win32_process_target::resume (thread_resume *resume_info, size_t n)
776 DWORD tid;
777 enum gdb_signal sig;
778 int step;
779 windows_thread_info *th;
780 DWORD continue_status = DBG_CONTINUE;
781 ptid_t ptid;
783 /* This handles the very limited set of resume packets that GDB can
784 currently produce. */
786 if (n == 1 && resume_info[0].thread == minus_one_ptid)
787 tid = -1;
788 else if (n > 1)
789 tid = -1;
790 else
791 /* Yes, we're ignoring resume_info[0].thread. It'd be tricky to make
792 the Windows resume code do the right thing for thread switching. */
793 tid = windows_process.current_event.dwThreadId;
795 if (resume_info[0].thread != minus_one_ptid)
797 sig = gdb_signal_from_host (resume_info[0].sig);
798 step = resume_info[0].kind == resume_step;
800 else
802 sig = GDB_SIGNAL_0;
803 step = 0;
806 if (sig != GDB_SIGNAL_0)
808 if (windows_process.current_event.dwDebugEventCode
809 != EXCEPTION_DEBUG_EVENT)
811 OUTMSG (("Cannot continue with signal %s here.\n",
812 gdb_signal_to_string (sig)));
814 else if (sig == windows_process.last_sig)
815 continue_status = DBG_EXCEPTION_NOT_HANDLED;
816 else
817 OUTMSG (("Can only continue with received signal %s.\n",
818 gdb_signal_to_string (windows_process.last_sig)));
821 windows_process.last_sig = GDB_SIGNAL_0;
823 /* Get context for the currently selected thread. */
824 ptid = debug_event_ptid (&windows_process.current_event);
825 th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
826 if (th)
828 win32_prepare_to_resume (th);
830 DWORD *context_flags;
831 #ifdef __x86_64__
832 if (windows_process.wow64_process)
833 context_flags = &th->wow64_context.ContextFlags;
834 else
835 #endif
836 context_flags = &th->context.ContextFlags;
837 if (*context_flags)
839 /* Move register values from the inferior into the thread
840 context structure. */
841 regcache_invalidate ();
843 if (step)
845 if (the_low_target.single_step != NULL)
846 (*the_low_target.single_step) (th);
847 else
848 error ("Single stepping is not supported "
849 "in this configuration.\n");
852 win32_set_thread_context (th);
853 *context_flags = 0;
857 /* Allow continuing with the same signal that interrupted us.
858 Otherwise complain. */
860 child_continue (continue_status, tid);
863 /* See nat/windows-nat.h. */
865 void
866 gdbserver_windows_process::handle_load_dll (const char *name, LPVOID base)
868 CORE_ADDR load_addr = (CORE_ADDR) (uintptr_t) base;
870 char buf[MAX_PATH + 1];
871 char buf2[MAX_PATH + 1];
873 WIN32_FIND_DATAA w32_fd;
874 HANDLE h = FindFirstFileA (name, &w32_fd);
876 /* The symbols in a dll are offset by 0x1000, which is the
877 offset from 0 of the first byte in an image - because
878 of the file header and the section alignment. */
879 load_addr += 0x1000;
881 if (h == INVALID_HANDLE_VALUE)
882 strcpy (buf, name);
883 else
885 FindClose (h);
886 strcpy (buf, name);
888 char cwd[MAX_PATH + 1];
889 char *p;
890 if (GetCurrentDirectoryA (MAX_PATH + 1, cwd))
892 p = strrchr (buf, '\\');
893 if (p)
894 p[1] = '\0';
895 SetCurrentDirectoryA (buf);
896 GetFullPathNameA (w32_fd.cFileName, MAX_PATH, buf, &p);
897 SetCurrentDirectoryA (cwd);
902 if (strcasecmp (buf, "ntdll.dll") == 0)
904 GetSystemDirectoryA (buf, sizeof (buf));
905 strcat (buf, "\\ntdll.dll");
908 #ifdef __CYGWIN__
909 cygwin_conv_path (CCP_WIN_A_TO_POSIX, buf, buf2, sizeof (buf2));
910 #else
911 strcpy (buf2, buf);
912 #endif
914 loaded_dll (buf2, load_addr);
917 /* See nat/windows-nat.h. */
919 void
920 gdbserver_windows_process::handle_unload_dll ()
922 CORE_ADDR load_addr =
923 (CORE_ADDR) (uintptr_t) current_event.u.UnloadDll.lpBaseOfDll;
925 /* The symbols in a dll are offset by 0x1000, which is the
926 offset from 0 of the first byte in an image - because
927 of the file header and the section alignment. */
928 load_addr += 0x1000;
929 unloaded_dll (NULL, load_addr);
932 static void
933 suspend_one_thread (thread_info *thread)
935 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread);
937 th->suspend ();
940 static void
941 fake_breakpoint_event (void)
943 OUTMSG2(("fake_breakpoint_event\n"));
945 windows_process.faked_breakpoint = 1;
947 memset (&windows_process.current_event, 0,
948 sizeof (windows_process.current_event));
949 windows_process.current_event.dwThreadId = windows_process.main_thread_id;
950 windows_process.current_event.dwDebugEventCode = EXCEPTION_DEBUG_EVENT;
951 windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
952 = EXCEPTION_BREAKPOINT;
954 for_each_thread (suspend_one_thread);
957 /* See nat/windows-nat.h. */
959 bool
960 gdbserver_windows_process::handle_access_violation
961 (const EXCEPTION_RECORD *rec)
963 return false;
966 /* A helper function that will, if needed, set
967 'stopped_at_software_breakpoint' on the thread and adjust the
968 PC. */
970 static void
971 maybe_adjust_pc ()
973 struct regcache *regcache = get_thread_regcache (current_thread, 1);
974 child_fetch_inferior_registers (regcache, -1);
976 windows_thread_info *th
977 = windows_process.thread_rec (current_thread_ptid (),
978 DONT_INVALIDATE_CONTEXT);
979 th->stopped_at_software_breakpoint = false;
981 if (windows_process.current_event.dwDebugEventCode == EXCEPTION_DEBUG_EVENT
982 && ((windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
983 == EXCEPTION_BREAKPOINT)
984 || (windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
985 == STATUS_WX86_BREAKPOINT))
986 && windows_process.child_initialization_done)
988 th->stopped_at_software_breakpoint = true;
989 CORE_ADDR pc = regcache_read_pc (regcache);
990 CORE_ADDR sw_breakpoint_pc = pc - the_low_target.decr_pc_after_break;
991 regcache_write_pc (regcache, sw_breakpoint_pc);
995 /* Get the next event from the child. */
997 static int
998 get_child_debug_event (DWORD *continue_status,
999 struct target_waitstatus *ourstatus)
1001 ptid_t ptid;
1003 windows_process.last_sig = GDB_SIGNAL_0;
1004 ourstatus->set_spurious ();
1005 *continue_status = DBG_CONTINUE;
1007 /* Check if GDB sent us an interrupt request. */
1008 check_remote_input_interrupt_request ();
1010 DEBUG_EVENT *current_event = &windows_process.current_event;
1012 if (windows_process.soft_interrupt_requested)
1014 windows_process.soft_interrupt_requested = 0;
1015 fake_breakpoint_event ();
1016 goto gotevent;
1019 windows_process.attaching = 0;
1021 std::optional<pending_stop> stop
1022 = windows_process.fetch_pending_stop (debug_threads);
1023 if (stop.has_value ())
1025 *ourstatus = stop->status;
1026 windows_process.current_event = stop->event;
1027 ptid = debug_event_ptid (&windows_process.current_event);
1028 switch_to_thread (find_thread_ptid (ptid));
1029 return 1;
1032 /* Keep the wait time low enough for comfortable remote
1033 interruption, but high enough so gdbserver doesn't become a
1034 bottleneck. */
1035 if (!wait_for_debug_event (&windows_process.current_event, 250))
1037 DWORD e = GetLastError();
1039 if (e == ERROR_PIPE_NOT_CONNECTED)
1041 /* This will happen if the loader fails to successfully
1042 load the application, e.g., if the main executable
1043 tries to pull in a non-existing export from a
1044 DLL. */
1045 ourstatus->set_exited (1);
1046 return 1;
1049 return 0;
1053 gotevent:
1055 switch (current_event->dwDebugEventCode)
1057 case CREATE_THREAD_DEBUG_EVENT:
1058 OUTMSG2 (("gdbserver: kernel event CREATE_THREAD_DEBUG_EVENT "
1059 "for pid=%u tid=%x)\n",
1060 (unsigned) current_event->dwProcessId,
1061 (unsigned) current_event->dwThreadId));
1063 /* Record the existence of this thread. */
1064 child_add_thread (current_event->dwProcessId,
1065 current_event->dwThreadId,
1066 current_event->u.CreateThread.hThread,
1067 current_event->u.CreateThread.lpThreadLocalBase);
1068 break;
1070 case EXIT_THREAD_DEBUG_EVENT:
1071 OUTMSG2 (("gdbserver: kernel event EXIT_THREAD_DEBUG_EVENT "
1072 "for pid=%u tid=%x\n",
1073 (unsigned) current_event->dwProcessId,
1074 (unsigned) current_event->dwThreadId));
1075 child_delete_thread (current_event->dwProcessId,
1076 current_event->dwThreadId);
1078 switch_to_thread (get_first_thread ());
1079 return 1;
1081 case CREATE_PROCESS_DEBUG_EVENT:
1082 OUTMSG2 (("gdbserver: kernel event CREATE_PROCESS_DEBUG_EVENT "
1083 "for pid=%u tid=%x\n",
1084 (unsigned) current_event->dwProcessId,
1085 (unsigned) current_event->dwThreadId));
1086 CloseHandle (current_event->u.CreateProcessInfo.hFile);
1088 if (windows_process.open_process_used)
1090 CloseHandle (windows_process.handle);
1091 windows_process.open_process_used = false;
1094 windows_process.handle = current_event->u.CreateProcessInfo.hProcess;
1095 windows_process.main_thread_id = current_event->dwThreadId;
1097 /* Add the main thread. */
1098 child_add_thread (current_event->dwProcessId,
1099 windows_process.main_thread_id,
1100 current_event->u.CreateProcessInfo.hThread,
1101 current_event->u.CreateProcessInfo.lpThreadLocalBase);
1102 break;
1104 case EXIT_PROCESS_DEBUG_EVENT:
1105 OUTMSG2 (("gdbserver: kernel event EXIT_PROCESS_DEBUG_EVENT "
1106 "for pid=%u tid=%x\n",
1107 (unsigned) current_event->dwProcessId,
1108 (unsigned) current_event->dwThreadId));
1110 DWORD exit_status = current_event->u.ExitProcess.dwExitCode;
1111 /* If the exit status looks like a fatal exception, but we
1112 don't recognize the exception's code, make the original
1113 exit status value available, to avoid losing information. */
1114 int exit_signal
1115 = WIFSIGNALED (exit_status) ? WTERMSIG (exit_status) : -1;
1116 if (exit_signal == -1)
1117 ourstatus->set_exited (exit_status);
1118 else
1119 ourstatus->set_signalled (gdb_signal_from_host (exit_signal));
1121 child_continue (DBG_CONTINUE, windows_process.desired_stop_thread_id);
1122 break;
1124 case LOAD_DLL_DEBUG_EVENT:
1125 OUTMSG2 (("gdbserver: kernel event LOAD_DLL_DEBUG_EVENT "
1126 "for pid=%u tid=%x\n",
1127 (unsigned) current_event->dwProcessId,
1128 (unsigned) current_event->dwThreadId));
1129 CloseHandle (current_event->u.LoadDll.hFile);
1130 if (! windows_process.child_initialization_done)
1131 break;
1132 windows_process.dll_loaded_event ();
1134 ourstatus->set_loaded ();
1135 break;
1137 case UNLOAD_DLL_DEBUG_EVENT:
1138 OUTMSG2 (("gdbserver: kernel event UNLOAD_DLL_DEBUG_EVENT "
1139 "for pid=%u tid=%x\n",
1140 (unsigned) current_event->dwProcessId,
1141 (unsigned) current_event->dwThreadId));
1142 if (! windows_process.child_initialization_done)
1143 break;
1144 windows_process.handle_unload_dll ();
1145 ourstatus->set_loaded ();
1146 break;
1148 case EXCEPTION_DEBUG_EVENT:
1149 OUTMSG2 (("gdbserver: kernel event EXCEPTION_DEBUG_EVENT "
1150 "for pid=%u tid=%x\n",
1151 (unsigned) current_event->dwProcessId,
1152 (unsigned) current_event->dwThreadId));
1153 if (windows_process.handle_exception (ourstatus, debug_threads)
1154 == HANDLE_EXCEPTION_UNHANDLED)
1155 *continue_status = DBG_EXCEPTION_NOT_HANDLED;
1156 break;
1158 case OUTPUT_DEBUG_STRING_EVENT:
1159 /* A message from the kernel (or Cygwin). */
1160 OUTMSG2 (("gdbserver: kernel event OUTPUT_DEBUG_STRING_EVENT "
1161 "for pid=%u tid=%x\n",
1162 (unsigned) current_event->dwProcessId,
1163 (unsigned) current_event->dwThreadId));
1164 windows_process.handle_output_debug_string (nullptr);
1165 break;
1167 default:
1168 OUTMSG2 (("gdbserver: kernel event unknown "
1169 "for pid=%u tid=%x code=%x\n",
1170 (unsigned) current_event->dwProcessId,
1171 (unsigned) current_event->dwThreadId,
1172 (unsigned) current_event->dwDebugEventCode));
1173 break;
1176 ptid = debug_event_ptid (&windows_process.current_event);
1178 if (windows_process.desired_stop_thread_id != -1
1179 && windows_process.desired_stop_thread_id != ptid.lwp ())
1181 /* Pending stop. See the comment by the definition of
1182 "pending_stops" for details on why this is needed. */
1183 OUTMSG2 (("get_windows_debug_event - "
1184 "unexpected stop in 0x%lx (expecting 0x%x)\n",
1185 ptid.lwp (), windows_process.desired_stop_thread_id));
1186 maybe_adjust_pc ();
1187 windows_process.pending_stops.push_back
1188 ({(DWORD) ptid.lwp (), *ourstatus, *current_event});
1189 ourstatus->set_spurious ();
1191 else
1192 switch_to_thread (find_thread_ptid (ptid));
1194 return 1;
1197 /* Wait for the inferior process to change state.
1198 STATUS will be filled in with a response code to send to GDB.
1199 Returns the signal which caused the process to stop. */
1200 ptid_t
1201 win32_process_target::wait (ptid_t ptid, target_waitstatus *ourstatus,
1202 target_wait_flags options)
1204 if (windows_process.cached_status.kind () != TARGET_WAITKIND_IGNORE)
1206 /* The core always does a wait after creating the inferior, and
1207 do_initial_child_stuff already ran the inferior to the
1208 initial breakpoint (or an exit, if creating the process
1209 fails). Report it now. */
1210 *ourstatus = windows_process.cached_status;
1211 windows_process.cached_status.set_ignore ();
1212 return debug_event_ptid (&windows_process.current_event);
1215 while (1)
1217 DWORD continue_status;
1218 if (!get_child_debug_event (&continue_status, ourstatus))
1219 continue;
1221 switch (ourstatus->kind ())
1223 case TARGET_WAITKIND_EXITED:
1224 OUTMSG2 (("Child exited with retcode = %x\n",
1225 ourstatus->exit_status ()));
1226 win32_clear_inferiors ();
1227 return ptid_t (windows_process.current_event.dwProcessId);
1228 case TARGET_WAITKIND_STOPPED:
1229 case TARGET_WAITKIND_SIGNALLED:
1230 case TARGET_WAITKIND_LOADED:
1232 OUTMSG2 (("Child Stopped with signal = %d \n",
1233 ourstatus->sig ()));
1234 maybe_adjust_pc ();
1235 return debug_event_ptid (&windows_process.current_event);
1237 default:
1238 OUTMSG (("Ignoring unknown internal event, %d\n",
1239 ourstatus->kind ()));
1240 [[fallthrough]];
1241 case TARGET_WAITKIND_SPURIOUS:
1242 /* do nothing, just continue */
1243 child_continue (continue_status,
1244 windows_process.desired_stop_thread_id);
1245 break;
1250 /* Fetch registers from the inferior process.
1251 If REGNO is -1, fetch all registers; otherwise, fetch at least REGNO. */
1252 void
1253 win32_process_target::fetch_registers (regcache *regcache, int regno)
1255 child_fetch_inferior_registers (regcache, regno);
1258 /* Store registers to the inferior process.
1259 If REGNO is -1, store all registers; otherwise, store at least REGNO. */
1260 void
1261 win32_process_target::store_registers (regcache *regcache, int regno)
1263 child_store_inferior_registers (regcache, regno);
1266 /* Read memory from the inferior process. This should generally be
1267 called through read_inferior_memory, which handles breakpoint shadowing.
1268 Read LEN bytes at MEMADDR into a buffer at MYADDR. */
1270 win32_process_target::read_memory (CORE_ADDR memaddr, unsigned char *myaddr,
1271 int len)
1273 return child_xfer_memory (memaddr, (char *) myaddr, len, 0, 0) != len;
1276 /* Write memory to the inferior process. This should generally be
1277 called through write_inferior_memory, which handles breakpoint shadowing.
1278 Write LEN bytes from the buffer at MYADDR to MEMADDR.
1279 Returns 0 on success and errno on failure. */
1281 win32_process_target::write_memory (CORE_ADDR memaddr,
1282 const unsigned char *myaddr, int len)
1284 return child_xfer_memory (memaddr, (char *) myaddr, len, 1, 0) != len;
1287 /* Send an interrupt request to the inferior process. */
1288 void
1289 win32_process_target::request_interrupt ()
1291 if (GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, signal_pid))
1292 return;
1294 /* GenerateConsoleCtrlEvent can fail if process id being debugged is
1295 not a process group id.
1296 Fallback to XP/Vista 'DebugBreakProcess', which generates a
1297 breakpoint exception in the interior process. */
1299 if (DebugBreakProcess (windows_process.handle))
1300 return;
1302 /* Last resort, suspend all threads manually. */
1303 windows_process.soft_interrupt_requested = 1;
1306 bool
1307 win32_process_target::supports_hardware_single_step ()
1309 return true;
1312 bool
1313 win32_process_target::supports_qxfer_siginfo ()
1315 return true;
1318 /* Write Windows signal info. */
1321 win32_process_target::qxfer_siginfo (const char *annex,
1322 unsigned char *readbuf,
1323 unsigned const char *writebuf,
1324 CORE_ADDR offset, int len)
1326 if (windows_process.siginfo_er.ExceptionCode == 0)
1327 return -1;
1329 if (readbuf == nullptr)
1330 return -1;
1332 char *buf = (char *) &windows_process.siginfo_er;
1333 size_t bufsize = sizeof (windows_process.siginfo_er);
1335 #ifdef __x86_64__
1336 EXCEPTION_RECORD32 er32;
1337 if (windows_process.wow64_process)
1339 buf = (char *) &er32;
1340 bufsize = sizeof (er32);
1342 er32.ExceptionCode = windows_process.siginfo_er.ExceptionCode;
1343 er32.ExceptionFlags = windows_process.siginfo_er.ExceptionFlags;
1344 er32.ExceptionRecord
1345 = (uintptr_t) windows_process.siginfo_er.ExceptionRecord;
1346 er32.ExceptionAddress
1347 = (uintptr_t) windows_process.siginfo_er.ExceptionAddress;
1348 er32.NumberParameters = windows_process.siginfo_er.NumberParameters;
1349 int i;
1350 for (i = 0; i < EXCEPTION_MAXIMUM_PARAMETERS; i++)
1351 er32.ExceptionInformation[i]
1352 = windows_process.siginfo_er.ExceptionInformation[i];
1354 #endif
1356 if (offset > bufsize)
1357 return -1;
1359 if (offset + len > bufsize)
1360 len = bufsize - offset;
1362 memcpy (readbuf, buf + offset, len);
1364 return len;
1367 bool
1368 win32_process_target::supports_get_tib_address ()
1370 return true;
1373 /* Write Windows OS Thread Information Block address. */
1376 win32_process_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
1378 windows_thread_info *th;
1379 th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
1380 if (th == NULL)
1381 return 0;
1382 if (addr != NULL)
1383 *addr = th->thread_local_base;
1384 return 1;
1387 /* Implementation of the target_ops method "sw_breakpoint_from_kind". */
1389 const gdb_byte *
1390 win32_process_target::sw_breakpoint_from_kind (int kind, int *size)
1392 *size = the_low_target.breakpoint_len;
1393 return the_low_target.breakpoint;
1396 bool
1397 win32_process_target::stopped_by_sw_breakpoint ()
1399 windows_thread_info *th
1400 = windows_process.thread_rec (current_thread_ptid (),
1401 DONT_INVALIDATE_CONTEXT);
1402 return th == nullptr ? false : th->stopped_at_software_breakpoint;
1405 bool
1406 win32_process_target::supports_stopped_by_sw_breakpoint ()
1408 return true;
1411 CORE_ADDR
1412 win32_process_target::read_pc (struct regcache *regcache)
1414 return (*the_low_target.get_pc) (regcache);
1417 void
1418 win32_process_target::write_pc (struct regcache *regcache, CORE_ADDR pc)
1420 return (*the_low_target.set_pc) (regcache, pc);
1423 const char *
1424 win32_process_target::thread_name (ptid_t thread)
1426 windows_thread_info *th
1427 = windows_process.thread_rec (current_thread_ptid (),
1428 DONT_INVALIDATE_CONTEXT);
1429 return th->thread_name ();
1432 const char *
1433 win32_process_target::pid_to_exec_file (int pid)
1435 return windows_process.pid_to_exec_file (pid);
1438 /* The win32 target ops object. */
1440 static win32_process_target the_win32_target;
1442 /* Initialize the Win32 backend. */
1443 void
1444 initialize_low (void)
1446 set_target_ops (&the_win32_target);
1447 the_low_target.arch_setup ();
1449 initialize_loadable ();