arm: Support pac_key_* register operand for MRS/MSR in Armv8.1-M Mainline
[binutils-gdb.git] / gdbserver / win32-low.cc
blob0174a32e5d1917454371318158476468b4918276
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 "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"
38 using namespace windows_nat;
40 /* See win32-low.h. */
41 gdbserver_windows_process windows_process;
43 #ifndef USE_WIN32API
44 #include <sys/cygwin.h>
45 #endif
47 #define OUTMSG(X) do { printf X; fflush (stderr); } while (0)
49 #define OUTMSG2(X) \
50 do \
51 { \
52 if (debug_threads) \
53 { \
54 printf X; \
55 fflush (stderr); \
56 } \
57 } while (0)
59 #ifndef _T
60 #define _T(x) TEXT (x)
61 #endif
63 int using_threads = 1;
65 const struct target_desc *win32_tdesc;
66 #ifdef __x86_64__
67 const struct target_desc *wow64_win32_tdesc;
68 #endif
70 #define NUM_REGS (the_low_target.num_regs ())
72 /* The current debug event from WaitForDebugEvent. */
73 static ptid_t
74 debug_event_ptid (DEBUG_EVENT *event)
76 return ptid_t (event->dwProcessId, event->dwThreadId, 0);
79 /* Get the thread context of the thread associated with TH. */
81 static void
82 win32_get_thread_context (windows_thread_info *th)
84 #ifdef __x86_64__
85 if (windows_process.wow64_process)
86 memset (&th->wow64_context, 0, sizeof (WOW64_CONTEXT));
87 else
88 #endif
89 memset (&th->context, 0, sizeof (CONTEXT));
90 (*the_low_target.get_thread_context) (th);
93 /* Set the thread context of the thread associated with TH. */
95 static void
96 win32_set_thread_context (windows_thread_info *th)
98 #ifdef __x86_64__
99 if (windows_process.wow64_process)
100 Wow64SetThreadContext (th->h, &th->wow64_context);
101 else
102 #endif
103 SetThreadContext (th->h, &th->context);
106 /* Set the thread context of the thread associated with TH. */
108 static void
109 win32_prepare_to_resume (windows_thread_info *th)
111 if (the_low_target.prepare_to_resume != NULL)
112 (*the_low_target.prepare_to_resume) (th);
115 /* See win32-low.h. */
117 void
118 win32_require_context (windows_thread_info *th)
120 DWORD context_flags;
121 #ifdef __x86_64__
122 if (windows_process.wow64_process)
123 context_flags = th->wow64_context.ContextFlags;
124 else
125 #endif
126 context_flags = th->context.ContextFlags;
127 if (context_flags == 0)
129 th->suspend ();
130 win32_get_thread_context (th);
134 /* See nat/windows-nat.h. */
136 windows_thread_info *
137 gdbserver_windows_process::thread_rec
138 (ptid_t ptid, thread_disposition_type disposition)
140 thread_info *thread = find_thread_ptid (ptid);
141 if (thread == NULL)
142 return NULL;
144 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread);
145 if (disposition != DONT_INVALIDATE_CONTEXT)
146 win32_require_context (th);
147 return th;
150 /* Add a thread to the thread list. */
151 static windows_thread_info *
152 child_add_thread (DWORD pid, DWORD tid, HANDLE h, void *tlb)
154 windows_thread_info *th;
155 ptid_t ptid = ptid_t (pid, tid, 0);
157 if ((th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT)))
158 return th;
160 CORE_ADDR base = (CORE_ADDR) (uintptr_t) tlb;
161 #ifdef __x86_64__
162 /* For WOW64 processes, this is actually the pointer to the 64bit TIB,
163 and the 32bit TIB is exactly 2 pages after it. */
164 if (windows_process.wow64_process)
165 base += 2 * 4096; /* page size = 4096 */
166 #endif
167 th = new windows_thread_info (tid, h, base);
169 find_process_pid (pid)->add_thread (ptid, th);
171 if (the_low_target.thread_added != NULL)
172 (*the_low_target.thread_added) (th);
174 return th;
177 /* Delete a thread from the list of threads. */
178 static void
179 delete_thread_info (thread_info *thread)
181 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread);
183 thread->process ()->remove_thread (thread);
184 delete th;
187 /* Delete a thread from the list of threads. */
188 static void
189 child_delete_thread (DWORD pid, DWORD tid)
191 /* If the last thread is exiting, just return. */
192 if (all_threads.size () == 1)
193 return;
195 thread_info *thread = find_thread_ptid (ptid_t (pid, tid));
196 if (thread == NULL)
197 return;
199 delete_thread_info (thread);
202 /* These watchpoint related wrapper functions simply pass on the function call
203 if the low target has registered a corresponding function. */
205 bool
206 win32_process_target::supports_z_point_type (char z_type)
208 return (z_type == Z_PACKET_SW_BP
209 || (the_low_target.supports_z_point_type != NULL
210 && the_low_target.supports_z_point_type (z_type)));
214 win32_process_target::insert_point (enum raw_bkpt_type type, CORE_ADDR addr,
215 int size, raw_breakpoint *bp)
217 if (type == raw_bkpt_type_sw)
218 return insert_memory_breakpoint (bp);
219 else if (the_low_target.insert_point != NULL)
220 return the_low_target.insert_point (type, addr, size, bp);
221 else
222 /* Unsupported (see target.h). */
223 return 1;
227 win32_process_target::remove_point (enum raw_bkpt_type type, CORE_ADDR addr,
228 int size, raw_breakpoint *bp)
230 if (type == raw_bkpt_type_sw)
231 return remove_memory_breakpoint (bp);
232 else if (the_low_target.remove_point != NULL)
233 return the_low_target.remove_point (type, addr, size, bp);
234 else
235 /* Unsupported (see target.h). */
236 return 1;
239 bool
240 win32_process_target::stopped_by_watchpoint ()
242 if (the_low_target.stopped_by_watchpoint != NULL)
243 return the_low_target.stopped_by_watchpoint ();
244 else
245 return false;
248 CORE_ADDR
249 win32_process_target::stopped_data_address ()
251 if (the_low_target.stopped_data_address != NULL)
252 return the_low_target.stopped_data_address ();
253 else
254 return 0;
258 /* Transfer memory from/to the debugged process. */
259 static int
260 child_xfer_memory (CORE_ADDR memaddr, char *our, int len,
261 int write, process_stratum_target *target)
263 BOOL success;
264 SIZE_T done = 0;
265 DWORD lasterror = 0;
266 uintptr_t addr = (uintptr_t) memaddr;
268 if (write)
270 success = WriteProcessMemory (windows_process.handle, (LPVOID) addr,
271 (LPCVOID) our, len, &done);
272 if (!success)
273 lasterror = GetLastError ();
274 FlushInstructionCache (windows_process.handle, (LPCVOID) addr, len);
276 else
278 success = ReadProcessMemory (windows_process.handle, (LPCVOID) addr,
279 (LPVOID) our, len, &done);
280 if (!success)
281 lasterror = GetLastError ();
283 if (!success && lasterror == ERROR_PARTIAL_COPY && done > 0)
284 return done;
285 else
286 return success ? done : -1;
289 /* Clear out any old thread list and reinitialize it to a pristine
290 state. */
291 static void
292 child_init_thread_list (void)
294 for_each_thread (delete_thread_info);
297 static void
298 do_initial_child_stuff (HANDLE proch, DWORD pid, int attached)
300 struct process_info *proc;
302 windows_process.last_sig = GDB_SIGNAL_0;
303 windows_process.handle = proch;
304 windows_process.main_thread_id = 0;
306 windows_process.soft_interrupt_requested = 0;
307 windows_process.faked_breakpoint = 0;
308 windows_process.open_process_used = true;
310 memset (&windows_process.current_event, 0,
311 sizeof (windows_process.current_event));
313 #ifdef __x86_64__
314 BOOL wow64;
315 if (!IsWow64Process (proch, &wow64))
317 DWORD err = GetLastError ();
318 throw_winerror_with_name ("Check if WOW64 process failed", err);
320 windows_process.wow64_process = wow64;
322 if (windows_process.wow64_process
323 && (Wow64GetThreadContext == nullptr
324 || Wow64SetThreadContext == nullptr))
325 error ("WOW64 debugging is not supported on this system.\n");
327 windows_process.ignore_first_breakpoint
328 = !attached && windows_process.wow64_process;
329 #endif
331 proc = add_process (pid, attached);
332 #ifdef __x86_64__
333 if (windows_process.wow64_process)
334 proc->tdesc = wow64_win32_tdesc;
335 else
336 #endif
337 proc->tdesc = win32_tdesc;
338 child_init_thread_list ();
339 windows_process.child_initialization_done = 0;
341 if (the_low_target.initial_stuff != NULL)
342 (*the_low_target.initial_stuff) ();
344 windows_process.cached_status.set_ignore ();
346 /* Flush all currently pending debug events (thread and dll list) up
347 to the initial breakpoint. */
348 while (1)
350 struct target_waitstatus status;
352 the_target->wait (minus_one_ptid, &status, 0);
354 /* Note win32_wait doesn't return thread events. */
355 if (status.kind () != TARGET_WAITKIND_LOADED)
357 windows_process.cached_status = status;
358 break;
362 struct thread_resume resume;
364 resume.thread = minus_one_ptid;
365 resume.kind = resume_continue;
366 resume.sig = 0;
368 the_target->resume (&resume, 1);
372 /* Now that the inferior has been started and all DLLs have been mapped,
373 we can iterate over all DLLs and load them in.
375 We avoid doing it any earlier because, on certain versions of Windows,
376 LOAD_DLL_DEBUG_EVENTs are sometimes not complete. In particular,
377 we have seen on Windows 8.1 that the ntdll.dll load event does not
378 include the DLL name, preventing us from creating an associated SO.
379 A possible explanation is that ntdll.dll might be mapped before
380 the SO info gets created by the Windows system -- ntdll.dll is
381 the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs
382 do not seem to suffer from that problem.
384 Rather than try to work around this sort of issue, it is much
385 simpler to just ignore DLL load/unload events during the startup
386 phase, and then process them all in one batch now. */
387 windows_process.add_all_dlls ();
389 windows_process.child_initialization_done = 1;
392 /* Resume all artificially suspended threads if we are continuing
393 execution. */
394 static void
395 continue_one_thread (thread_info *thread, int thread_id)
397 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread);
399 if (thread_id == -1 || thread_id == th->tid)
401 win32_prepare_to_resume (th);
403 if (th->suspended)
405 DWORD *context_flags;
406 #ifdef __x86_64__
407 if (windows_process.wow64_process)
408 context_flags = &th->wow64_context.ContextFlags;
409 else
410 #endif
411 context_flags = &th->context.ContextFlags;
412 if (*context_flags)
414 win32_set_thread_context (th);
415 *context_flags = 0;
418 th->resume ();
423 static BOOL
424 child_continue (DWORD continue_status, int thread_id)
426 windows_process.desired_stop_thread_id = thread_id;
427 if (windows_process.matching_pending_stop (debug_threads))
428 return TRUE;
430 /* The inferior will only continue after the ContinueDebugEvent
431 call. */
432 for_each_thread ([&] (thread_info *thread)
434 continue_one_thread (thread, thread_id);
436 windows_process.faked_breakpoint = 0;
438 return continue_last_debug_event (continue_status, debug_threads);
441 /* Fetch register(s) from the current thread context. */
442 static void
443 child_fetch_inferior_registers (struct regcache *regcache, int r)
445 int regno;
446 windows_thread_info *th
447 = windows_process.thread_rec (current_thread->id,
448 INVALIDATE_CONTEXT);
449 if (r == -1 || r > NUM_REGS)
450 child_fetch_inferior_registers (regcache, NUM_REGS);
451 else
452 for (regno = 0; regno < r; regno++)
453 (*the_low_target.fetch_inferior_register) (regcache, th, regno);
456 /* Store a new register value into the current thread context. We don't
457 change the program's context until later, when we resume it. */
458 static void
459 child_store_inferior_registers (struct regcache *regcache, int r)
461 int regno;
462 windows_thread_info *th
463 = windows_process.thread_rec (current_thread->id,
464 INVALIDATE_CONTEXT);
465 if (r == -1 || r == 0 || r > NUM_REGS)
466 child_store_inferior_registers (regcache, NUM_REGS);
467 else
468 for (regno = 0; regno < r; regno++)
469 (*the_low_target.store_inferior_register) (regcache, th, regno);
472 static BOOL
473 create_process (const char *program, char *args,
474 DWORD flags, PROCESS_INFORMATION *pi)
476 const std::string &inferior_cwd = get_inferior_cwd ();
477 BOOL ret;
478 size_t argslen, proglen;
480 proglen = strlen (program) + 1;
481 argslen = strlen (args) + proglen;
483 STARTUPINFOA si = { sizeof (STARTUPINFOA) };
484 char *program_and_args = (char *) alloca (argslen + 1);
486 strcpy (program_and_args, program);
487 strcat (program_and_args, " ");
488 strcat (program_and_args, args);
489 ret = create_process (program, /* image name */
490 program_and_args, /* command line */
491 flags, /* start flags */
492 NULL, /* environment */
493 /* current directory */
494 (inferior_cwd.empty ()
495 ? NULL
496 : gdb_tilde_expand (inferior_cwd).c_str()),
497 get_client_state ().disable_randomization,
498 &si, /* start info */
499 pi); /* proc info */
501 return ret;
504 /* Start a new process.
505 PROGRAM is the program name.
506 PROGRAM_ARGS is the vector containing the inferior's args.
507 Returns the new PID on success, -1 on failure. Registers the new
508 process with the process list. */
510 win32_process_target::create_inferior (const char *program,
511 const std::vector<char *> &program_args)
513 client_state &cs = get_client_state ();
514 #ifndef USE_WIN32API
515 char real_path[PATH_MAX];
516 char *orig_path, *new_path, *path_ptr;
517 #endif
518 BOOL ret;
519 DWORD flags;
520 PROCESS_INFORMATION pi;
521 DWORD err;
522 std::string str_program_args = construct_inferior_arguments (program_args);
523 char *args = (char *) str_program_args.c_str ();
525 /* win32_wait needs to know we're not attaching. */
526 windows_process.attaching = 0;
528 if (!program)
529 error ("No executable specified, specify executable to debug.\n");
531 flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS;
533 #ifndef USE_WIN32API
534 orig_path = NULL;
535 path_ptr = getenv ("PATH");
536 if (path_ptr)
538 int size = cygwin_conv_path_list (CCP_POSIX_TO_WIN_A, path_ptr, NULL, 0);
539 orig_path = (char *) alloca (strlen (path_ptr) + 1);
540 new_path = (char *) alloca (size);
541 strcpy (orig_path, path_ptr);
542 cygwin_conv_path_list (CCP_POSIX_TO_WIN_A, path_ptr, new_path, size);
543 setenv ("PATH", new_path, 1);
545 cygwin_conv_path (CCP_POSIX_TO_WIN_A, program, real_path, PATH_MAX);
546 program = real_path;
547 #endif
549 OUTMSG2 (("Command line is \"%s %s\"\n", program, args));
551 #ifdef CREATE_NEW_PROCESS_GROUP
552 flags |= CREATE_NEW_PROCESS_GROUP;
553 #endif
555 ret = create_process (program, args, flags, &pi);
556 err = GetLastError ();
557 if (!ret && err == ERROR_FILE_NOT_FOUND)
559 char *exename = (char *) alloca (strlen (program) + 5);
560 strcat (strcpy (exename, program), ".exe");
561 ret = create_process (exename, args, flags, &pi);
562 err = GetLastError ();
565 #ifndef USE_WIN32API
566 if (orig_path)
567 setenv ("PATH", orig_path, 1);
568 #endif
570 if (!ret)
572 std::string msg = string_printf (_("Error creating process \"%s %s\""),
573 program, args);
574 throw_winerror_with_name (msg.c_str (), err);
576 else
578 OUTMSG2 (("Process created: %s %s\n", program, (char *) args));
581 CloseHandle (pi.hThread);
583 do_initial_child_stuff (pi.hProcess, pi.dwProcessId, 0);
585 /* Wait till we are at 1st instruction in program, return new pid
586 (assuming success). */
587 cs.last_ptid = wait (ptid_t (pi.dwProcessId), &cs.last_status, 0);
589 /* Necessary for handle_v_kill. */
590 signal_pid = pi.dwProcessId;
592 return pi.dwProcessId;
595 /* Attach to a running process.
596 PID is the process ID to attach to, specified by the user
597 or a higher layer. */
599 win32_process_target::attach (unsigned long pid)
601 HANDLE h;
602 DWORD err;
604 h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
605 if (h != NULL)
607 if (DebugActiveProcess (pid))
609 DebugSetProcessKillOnExit (FALSE);
611 /* win32_wait needs to know we're attaching. */
612 windows_process.attaching = 1;
613 do_initial_child_stuff (h, pid, 1);
614 return 0;
617 CloseHandle (h);
620 err = GetLastError ();
621 throw_winerror_with_name ("Attach to process failed", err);
624 /* See nat/windows-nat.h. */
627 gdbserver_windows_process::handle_output_debug_string
628 (struct target_waitstatus *ourstatus)
630 #define READ_BUFFER_LEN 1024
631 CORE_ADDR addr;
632 char s[READ_BUFFER_LEN + 1] = { 0 };
633 DWORD nbytes = current_event.u.DebugString.nDebugStringLength;
635 if (nbytes == 0)
636 return 0;
638 if (nbytes > READ_BUFFER_LEN)
639 nbytes = READ_BUFFER_LEN;
641 addr = (CORE_ADDR) (size_t) current_event.u.DebugString.lpDebugStringData;
643 if (current_event.u.DebugString.fUnicode)
645 /* The event tells us how many bytes, not chars, even
646 in Unicode. */
647 WCHAR buffer[(READ_BUFFER_LEN + 1) / sizeof (WCHAR)] = { 0 };
648 if (read_inferior_memory (addr, (unsigned char *) buffer, nbytes) != 0)
649 return 0;
650 wcstombs (s, buffer, (nbytes + 1) / sizeof (WCHAR));
652 else
654 if (read_inferior_memory (addr, (unsigned char *) s, nbytes) != 0)
655 return 0;
658 if (!startswith (s, "cYg"))
660 if (!server_waiting)
662 OUTMSG2(("%s", s));
663 return 0;
666 monitor_output (s);
668 #undef READ_BUFFER_LEN
670 return 0;
673 static void
674 win32_clear_inferiors (void)
676 if (windows_process.open_process_used)
678 CloseHandle (windows_process.handle);
679 windows_process.open_process_used = false;
682 for_each_thread (delete_thread_info);
683 windows_process.siginfo_er.ExceptionCode = 0;
684 clear_inferiors ();
687 /* Implementation of target_ops::kill. */
690 win32_process_target::kill (process_info *process)
692 TerminateProcess (windows_process.handle, 0);
693 for (;;)
695 if (!child_continue (DBG_CONTINUE, -1))
696 break;
697 if (!wait_for_debug_event (&windows_process.current_event, INFINITE))
698 break;
699 if (windows_process.current_event.dwDebugEventCode
700 == EXIT_PROCESS_DEBUG_EVENT)
701 break;
702 else if (windows_process.current_event.dwDebugEventCode
703 == OUTPUT_DEBUG_STRING_EVENT)
704 windows_process.handle_output_debug_string (nullptr);
707 win32_clear_inferiors ();
709 remove_process (process);
710 return 0;
713 /* Implementation of target_ops::detach. */
716 win32_process_target::detach (process_info *process)
718 struct thread_resume resume;
719 resume.thread = minus_one_ptid;
720 resume.kind = resume_continue;
721 resume.sig = 0;
722 this->resume (&resume, 1);
724 if (!DebugActiveProcessStop (process->pid))
725 return -1;
727 DebugSetProcessKillOnExit (FALSE);
728 win32_clear_inferiors ();
729 remove_process (process);
731 return 0;
734 void
735 win32_process_target::mourn (struct process_info *process)
737 remove_process (process);
740 /* Implementation of target_ops::join. */
742 void
743 win32_process_target::join (int pid)
745 HANDLE h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
746 if (h != NULL)
748 WaitForSingleObject (h, INFINITE);
749 CloseHandle (h);
753 /* Return true iff the thread with thread ID TID is alive. */
754 bool
755 win32_process_target::thread_alive (ptid_t ptid)
757 /* Our thread list is reliable; don't bother to poll target
758 threads. */
759 return find_thread_ptid (ptid) != NULL;
762 /* Resume the inferior process. RESUME_INFO describes how we want
763 to resume. */
764 void
765 win32_process_target::resume (thread_resume *resume_info, size_t n)
767 DWORD tid;
768 enum gdb_signal sig;
769 int step;
770 windows_thread_info *th;
771 DWORD continue_status = DBG_CONTINUE;
772 ptid_t ptid;
774 /* This handles the very limited set of resume packets that GDB can
775 currently produce. */
777 if (n == 1 && resume_info[0].thread == minus_one_ptid)
778 tid = -1;
779 else if (n > 1)
780 tid = -1;
781 else
782 /* Yes, we're ignoring resume_info[0].thread. It'd be tricky to make
783 the Windows resume code do the right thing for thread switching. */
784 tid = windows_process.current_event.dwThreadId;
786 if (resume_info[0].thread != minus_one_ptid)
788 sig = gdb_signal_from_host (resume_info[0].sig);
789 step = resume_info[0].kind == resume_step;
791 else
793 sig = GDB_SIGNAL_0;
794 step = 0;
797 if (sig != GDB_SIGNAL_0)
799 if (windows_process.current_event.dwDebugEventCode
800 != EXCEPTION_DEBUG_EVENT)
802 OUTMSG (("Cannot continue with signal %s here.\n",
803 gdb_signal_to_string (sig)));
805 else if (sig == windows_process.last_sig)
806 continue_status = DBG_EXCEPTION_NOT_HANDLED;
807 else
808 OUTMSG (("Can only continue with received signal %s.\n",
809 gdb_signal_to_string (windows_process.last_sig)));
812 windows_process.last_sig = GDB_SIGNAL_0;
814 /* Get context for the currently selected thread. */
815 ptid = debug_event_ptid (&windows_process.current_event);
816 th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
817 if (th)
819 win32_prepare_to_resume (th);
821 DWORD *context_flags;
822 #ifdef __x86_64__
823 if (windows_process.wow64_process)
824 context_flags = &th->wow64_context.ContextFlags;
825 else
826 #endif
827 context_flags = &th->context.ContextFlags;
828 if (*context_flags)
830 /* Move register values from the inferior into the thread
831 context structure. */
832 regcache_invalidate ();
834 if (step)
836 if (the_low_target.single_step != NULL)
837 (*the_low_target.single_step) (th);
838 else
839 error ("Single stepping is not supported "
840 "in this configuration.\n");
843 win32_set_thread_context (th);
844 *context_flags = 0;
848 /* Allow continuing with the same signal that interrupted us.
849 Otherwise complain. */
851 child_continue (continue_status, tid);
854 /* See nat/windows-nat.h. */
856 void
857 gdbserver_windows_process::handle_load_dll (const char *name, LPVOID base)
859 CORE_ADDR load_addr = (CORE_ADDR) (uintptr_t) base;
861 char buf[MAX_PATH + 1];
862 char buf2[MAX_PATH + 1];
864 WIN32_FIND_DATAA w32_fd;
865 HANDLE h = FindFirstFileA (name, &w32_fd);
867 /* The symbols in a dll are offset by 0x1000, which is the
868 offset from 0 of the first byte in an image - because
869 of the file header and the section alignment. */
870 load_addr += 0x1000;
872 if (h == INVALID_HANDLE_VALUE)
873 strcpy (buf, name);
874 else
876 FindClose (h);
877 strcpy (buf, name);
879 char cwd[MAX_PATH + 1];
880 char *p;
881 if (GetCurrentDirectoryA (MAX_PATH + 1, cwd))
883 p = strrchr (buf, '\\');
884 if (p)
885 p[1] = '\0';
886 SetCurrentDirectoryA (buf);
887 GetFullPathNameA (w32_fd.cFileName, MAX_PATH, buf, &p);
888 SetCurrentDirectoryA (cwd);
893 if (strcasecmp (buf, "ntdll.dll") == 0)
895 GetSystemDirectoryA (buf, sizeof (buf));
896 strcat (buf, "\\ntdll.dll");
899 #ifdef __CYGWIN__
900 cygwin_conv_path (CCP_WIN_A_TO_POSIX, buf, buf2, sizeof (buf2));
901 #else
902 strcpy (buf2, buf);
903 #endif
905 loaded_dll (buf2, load_addr);
908 /* See nat/windows-nat.h. */
910 void
911 gdbserver_windows_process::handle_unload_dll ()
913 CORE_ADDR load_addr =
914 (CORE_ADDR) (uintptr_t) current_event.u.UnloadDll.lpBaseOfDll;
916 /* The symbols in a dll are offset by 0x1000, which is the
917 offset from 0 of the first byte in an image - because
918 of the file header and the section alignment. */
919 load_addr += 0x1000;
920 unloaded_dll (NULL, load_addr);
923 static void
924 suspend_one_thread (thread_info *thread)
926 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread);
928 th->suspend ();
931 static void
932 fake_breakpoint_event (void)
934 OUTMSG2(("fake_breakpoint_event\n"));
936 windows_process.faked_breakpoint = 1;
938 memset (&windows_process.current_event, 0,
939 sizeof (windows_process.current_event));
940 windows_process.current_event.dwThreadId = windows_process.main_thread_id;
941 windows_process.current_event.dwDebugEventCode = EXCEPTION_DEBUG_EVENT;
942 windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
943 = EXCEPTION_BREAKPOINT;
945 for_each_thread (suspend_one_thread);
948 /* See nat/windows-nat.h. */
950 bool
951 gdbserver_windows_process::handle_access_violation
952 (const EXCEPTION_RECORD *rec)
954 return false;
957 /* A helper function that will, if needed, set
958 'stopped_at_software_breakpoint' on the thread and adjust the
959 PC. */
961 static void
962 maybe_adjust_pc ()
964 struct regcache *regcache = get_thread_regcache (current_thread, 1);
965 child_fetch_inferior_registers (regcache, -1);
967 windows_thread_info *th
968 = windows_process.thread_rec (current_thread->id,
969 DONT_INVALIDATE_CONTEXT);
970 th->stopped_at_software_breakpoint = false;
972 if (windows_process.current_event.dwDebugEventCode == EXCEPTION_DEBUG_EVENT
973 && ((windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
974 == EXCEPTION_BREAKPOINT)
975 || (windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
976 == STATUS_WX86_BREAKPOINT))
977 && windows_process.child_initialization_done)
979 th->stopped_at_software_breakpoint = true;
980 CORE_ADDR pc = regcache_read_pc (regcache);
981 CORE_ADDR sw_breakpoint_pc = pc - the_low_target.decr_pc_after_break;
982 regcache_write_pc (regcache, sw_breakpoint_pc);
986 /* Get the next event from the child. */
988 static int
989 get_child_debug_event (DWORD *continue_status,
990 struct target_waitstatus *ourstatus)
992 ptid_t ptid;
994 windows_process.last_sig = GDB_SIGNAL_0;
995 ourstatus->set_spurious ();
996 *continue_status = DBG_CONTINUE;
998 /* Check if GDB sent us an interrupt request. */
999 check_remote_input_interrupt_request ();
1001 DEBUG_EVENT *current_event = &windows_process.current_event;
1003 if (windows_process.soft_interrupt_requested)
1005 windows_process.soft_interrupt_requested = 0;
1006 fake_breakpoint_event ();
1007 goto gotevent;
1010 windows_process.attaching = 0;
1012 std::optional<pending_stop> stop
1013 = windows_process.fetch_pending_stop (debug_threads);
1014 if (stop.has_value ())
1016 *ourstatus = stop->status;
1017 windows_process.current_event = stop->event;
1018 ptid = debug_event_ptid (&windows_process.current_event);
1019 switch_to_thread (find_thread_ptid (ptid));
1020 return 1;
1023 /* Keep the wait time low enough for comfortable remote
1024 interruption, but high enough so gdbserver doesn't become a
1025 bottleneck. */
1026 if (!wait_for_debug_event (&windows_process.current_event, 250))
1028 DWORD e = GetLastError();
1030 if (e == ERROR_PIPE_NOT_CONNECTED)
1032 /* This will happen if the loader fails to successfully
1033 load the application, e.g., if the main executable
1034 tries to pull in a non-existing export from a
1035 DLL. */
1036 ourstatus->set_exited (1);
1037 return 1;
1040 return 0;
1044 gotevent:
1046 switch (current_event->dwDebugEventCode)
1048 case CREATE_THREAD_DEBUG_EVENT:
1049 OUTMSG2 (("gdbserver: kernel event CREATE_THREAD_DEBUG_EVENT "
1050 "for pid=%u tid=%x)\n",
1051 (unsigned) current_event->dwProcessId,
1052 (unsigned) current_event->dwThreadId));
1054 /* Record the existence of this thread. */
1055 child_add_thread (current_event->dwProcessId,
1056 current_event->dwThreadId,
1057 current_event->u.CreateThread.hThread,
1058 current_event->u.CreateThread.lpThreadLocalBase);
1059 break;
1061 case EXIT_THREAD_DEBUG_EVENT:
1062 OUTMSG2 (("gdbserver: kernel event EXIT_THREAD_DEBUG_EVENT "
1063 "for pid=%u tid=%x\n",
1064 (unsigned) current_event->dwProcessId,
1065 (unsigned) current_event->dwThreadId));
1066 child_delete_thread (current_event->dwProcessId,
1067 current_event->dwThreadId);
1069 switch_to_thread (get_first_thread ());
1070 return 1;
1072 case CREATE_PROCESS_DEBUG_EVENT:
1073 OUTMSG2 (("gdbserver: kernel event CREATE_PROCESS_DEBUG_EVENT "
1074 "for pid=%u tid=%x\n",
1075 (unsigned) current_event->dwProcessId,
1076 (unsigned) current_event->dwThreadId));
1077 CloseHandle (current_event->u.CreateProcessInfo.hFile);
1079 if (windows_process.open_process_used)
1081 CloseHandle (windows_process.handle);
1082 windows_process.open_process_used = false;
1085 windows_process.handle = current_event->u.CreateProcessInfo.hProcess;
1086 windows_process.main_thread_id = current_event->dwThreadId;
1088 /* Add the main thread. */
1089 child_add_thread (current_event->dwProcessId,
1090 windows_process.main_thread_id,
1091 current_event->u.CreateProcessInfo.hThread,
1092 current_event->u.CreateProcessInfo.lpThreadLocalBase);
1093 break;
1095 case EXIT_PROCESS_DEBUG_EVENT:
1096 OUTMSG2 (("gdbserver: kernel event EXIT_PROCESS_DEBUG_EVENT "
1097 "for pid=%u tid=%x\n",
1098 (unsigned) current_event->dwProcessId,
1099 (unsigned) current_event->dwThreadId));
1101 DWORD exit_status = current_event->u.ExitProcess.dwExitCode;
1102 /* If the exit status looks like a fatal exception, but we
1103 don't recognize the exception's code, make the original
1104 exit status value available, to avoid losing information. */
1105 int exit_signal
1106 = WIFSIGNALED (exit_status) ? WTERMSIG (exit_status) : -1;
1107 if (exit_signal == -1)
1108 ourstatus->set_exited (exit_status);
1109 else
1110 ourstatus->set_signalled (gdb_signal_from_host (exit_signal));
1112 child_continue (DBG_CONTINUE, windows_process.desired_stop_thread_id);
1113 break;
1115 case LOAD_DLL_DEBUG_EVENT:
1116 OUTMSG2 (("gdbserver: kernel event LOAD_DLL_DEBUG_EVENT "
1117 "for pid=%u tid=%x\n",
1118 (unsigned) current_event->dwProcessId,
1119 (unsigned) current_event->dwThreadId));
1120 CloseHandle (current_event->u.LoadDll.hFile);
1121 if (! windows_process.child_initialization_done)
1122 break;
1123 windows_process.dll_loaded_event ();
1125 ourstatus->set_loaded ();
1126 break;
1128 case UNLOAD_DLL_DEBUG_EVENT:
1129 OUTMSG2 (("gdbserver: kernel event UNLOAD_DLL_DEBUG_EVENT "
1130 "for pid=%u tid=%x\n",
1131 (unsigned) current_event->dwProcessId,
1132 (unsigned) current_event->dwThreadId));
1133 if (! windows_process.child_initialization_done)
1134 break;
1135 windows_process.handle_unload_dll ();
1136 ourstatus->set_loaded ();
1137 break;
1139 case EXCEPTION_DEBUG_EVENT:
1140 OUTMSG2 (("gdbserver: kernel event EXCEPTION_DEBUG_EVENT "
1141 "for pid=%u tid=%x\n",
1142 (unsigned) current_event->dwProcessId,
1143 (unsigned) current_event->dwThreadId));
1144 if (windows_process.handle_exception (ourstatus, debug_threads)
1145 == HANDLE_EXCEPTION_UNHANDLED)
1146 *continue_status = DBG_EXCEPTION_NOT_HANDLED;
1147 break;
1149 case OUTPUT_DEBUG_STRING_EVENT:
1150 /* A message from the kernel (or Cygwin). */
1151 OUTMSG2 (("gdbserver: kernel event OUTPUT_DEBUG_STRING_EVENT "
1152 "for pid=%u tid=%x\n",
1153 (unsigned) current_event->dwProcessId,
1154 (unsigned) current_event->dwThreadId));
1155 windows_process.handle_output_debug_string (nullptr);
1156 break;
1158 default:
1159 OUTMSG2 (("gdbserver: kernel event unknown "
1160 "for pid=%u tid=%x code=%x\n",
1161 (unsigned) current_event->dwProcessId,
1162 (unsigned) current_event->dwThreadId,
1163 (unsigned) current_event->dwDebugEventCode));
1164 break;
1167 ptid = debug_event_ptid (&windows_process.current_event);
1169 if (windows_process.desired_stop_thread_id != -1
1170 && windows_process.desired_stop_thread_id != ptid.lwp ())
1172 /* Pending stop. See the comment by the definition of
1173 "pending_stops" for details on why this is needed. */
1174 OUTMSG2 (("get_windows_debug_event - "
1175 "unexpected stop in 0x%lx (expecting 0x%x)\n",
1176 ptid.lwp (), windows_process.desired_stop_thread_id));
1177 maybe_adjust_pc ();
1178 windows_process.pending_stops.push_back
1179 ({(DWORD) ptid.lwp (), *ourstatus, *current_event});
1180 ourstatus->set_spurious ();
1182 else
1183 switch_to_thread (find_thread_ptid (ptid));
1185 return 1;
1188 /* Wait for the inferior process to change state.
1189 STATUS will be filled in with a response code to send to GDB.
1190 Returns the signal which caused the process to stop. */
1191 ptid_t
1192 win32_process_target::wait (ptid_t ptid, target_waitstatus *ourstatus,
1193 target_wait_flags options)
1195 if (windows_process.cached_status.kind () != TARGET_WAITKIND_IGNORE)
1197 /* The core always does a wait after creating the inferior, and
1198 do_initial_child_stuff already ran the inferior to the
1199 initial breakpoint (or an exit, if creating the process
1200 fails). Report it now. */
1201 *ourstatus = windows_process.cached_status;
1202 windows_process.cached_status.set_ignore ();
1203 return debug_event_ptid (&windows_process.current_event);
1206 while (1)
1208 DWORD continue_status;
1209 if (!get_child_debug_event (&continue_status, ourstatus))
1210 continue;
1212 switch (ourstatus->kind ())
1214 case TARGET_WAITKIND_EXITED:
1215 OUTMSG2 (("Child exited with retcode = %x\n",
1216 ourstatus->exit_status ()));
1217 win32_clear_inferiors ();
1218 return ptid_t (windows_process.current_event.dwProcessId);
1219 case TARGET_WAITKIND_STOPPED:
1220 case TARGET_WAITKIND_SIGNALLED:
1221 case TARGET_WAITKIND_LOADED:
1223 OUTMSG2 (("Child Stopped with signal = %d \n",
1224 ourstatus->sig ()));
1225 maybe_adjust_pc ();
1226 return debug_event_ptid (&windows_process.current_event);
1228 default:
1229 OUTMSG (("Ignoring unknown internal event, %d\n",
1230 ourstatus->kind ()));
1231 [[fallthrough]];
1232 case TARGET_WAITKIND_SPURIOUS:
1233 /* do nothing, just continue */
1234 child_continue (continue_status,
1235 windows_process.desired_stop_thread_id);
1236 break;
1241 /* Fetch registers from the inferior process.
1242 If REGNO is -1, fetch all registers; otherwise, fetch at least REGNO. */
1243 void
1244 win32_process_target::fetch_registers (regcache *regcache, int regno)
1246 child_fetch_inferior_registers (regcache, regno);
1249 /* Store registers to the inferior process.
1250 If REGNO is -1, store all registers; otherwise, store at least REGNO. */
1251 void
1252 win32_process_target::store_registers (regcache *regcache, int regno)
1254 child_store_inferior_registers (regcache, regno);
1257 /* Read memory from the inferior process. This should generally be
1258 called through read_inferior_memory, which handles breakpoint shadowing.
1259 Read LEN bytes at MEMADDR into a buffer at MYADDR. */
1261 win32_process_target::read_memory (CORE_ADDR memaddr, unsigned char *myaddr,
1262 int len)
1264 return child_xfer_memory (memaddr, (char *) myaddr, len, 0, 0) != len;
1267 /* Write memory to the inferior process. This should generally be
1268 called through write_inferior_memory, which handles breakpoint shadowing.
1269 Write LEN bytes from the buffer at MYADDR to MEMADDR.
1270 Returns 0 on success and errno on failure. */
1272 win32_process_target::write_memory (CORE_ADDR memaddr,
1273 const unsigned char *myaddr, int len)
1275 return child_xfer_memory (memaddr, (char *) myaddr, len, 1, 0) != len;
1278 /* Send an interrupt request to the inferior process. */
1279 void
1280 win32_process_target::request_interrupt ()
1282 if (GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, signal_pid))
1283 return;
1285 /* GenerateConsoleCtrlEvent can fail if process id being debugged is
1286 not a process group id.
1287 Fallback to XP/Vista 'DebugBreakProcess', which generates a
1288 breakpoint exception in the interior process. */
1290 if (DebugBreakProcess (windows_process.handle))
1291 return;
1293 /* Last resort, suspend all threads manually. */
1294 windows_process.soft_interrupt_requested = 1;
1297 bool
1298 win32_process_target::supports_hardware_single_step ()
1300 return true;
1303 bool
1304 win32_process_target::supports_qxfer_siginfo ()
1306 return true;
1309 /* Write Windows signal info. */
1312 win32_process_target::qxfer_siginfo (const char *annex,
1313 unsigned char *readbuf,
1314 unsigned const char *writebuf,
1315 CORE_ADDR offset, int len)
1317 if (windows_process.siginfo_er.ExceptionCode == 0)
1318 return -1;
1320 if (readbuf == nullptr)
1321 return -1;
1323 char *buf = (char *) &windows_process.siginfo_er;
1324 size_t bufsize = sizeof (windows_process.siginfo_er);
1326 #ifdef __x86_64__
1327 EXCEPTION_RECORD32 er32;
1328 if (windows_process.wow64_process)
1330 buf = (char *) &er32;
1331 bufsize = sizeof (er32);
1333 er32.ExceptionCode = windows_process.siginfo_er.ExceptionCode;
1334 er32.ExceptionFlags = windows_process.siginfo_er.ExceptionFlags;
1335 er32.ExceptionRecord
1336 = (uintptr_t) windows_process.siginfo_er.ExceptionRecord;
1337 er32.ExceptionAddress
1338 = (uintptr_t) windows_process.siginfo_er.ExceptionAddress;
1339 er32.NumberParameters = windows_process.siginfo_er.NumberParameters;
1340 int i;
1341 for (i = 0; i < EXCEPTION_MAXIMUM_PARAMETERS; i++)
1342 er32.ExceptionInformation[i]
1343 = windows_process.siginfo_er.ExceptionInformation[i];
1345 #endif
1347 if (offset > bufsize)
1348 return -1;
1350 if (offset + len > bufsize)
1351 len = bufsize - offset;
1353 memcpy (readbuf, buf + offset, len);
1355 return len;
1358 bool
1359 win32_process_target::supports_get_tib_address ()
1361 return true;
1364 /* Write Windows OS Thread Information Block address. */
1367 win32_process_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
1369 windows_thread_info *th;
1370 th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
1371 if (th == NULL)
1372 return 0;
1373 if (addr != NULL)
1374 *addr = th->thread_local_base;
1375 return 1;
1378 /* Implementation of the target_ops method "sw_breakpoint_from_kind". */
1380 const gdb_byte *
1381 win32_process_target::sw_breakpoint_from_kind (int kind, int *size)
1383 *size = the_low_target.breakpoint_len;
1384 return the_low_target.breakpoint;
1387 bool
1388 win32_process_target::stopped_by_sw_breakpoint ()
1390 windows_thread_info *th
1391 = windows_process.thread_rec (current_thread->id,
1392 DONT_INVALIDATE_CONTEXT);
1393 return th == nullptr ? false : th->stopped_at_software_breakpoint;
1396 bool
1397 win32_process_target::supports_stopped_by_sw_breakpoint ()
1399 return true;
1402 CORE_ADDR
1403 win32_process_target::read_pc (struct regcache *regcache)
1405 return (*the_low_target.get_pc) (regcache);
1408 void
1409 win32_process_target::write_pc (struct regcache *regcache, CORE_ADDR pc)
1411 return (*the_low_target.set_pc) (regcache, pc);
1414 const char *
1415 win32_process_target::thread_name (ptid_t thread)
1417 windows_thread_info *th
1418 = windows_process.thread_rec (current_thread->id,
1419 DONT_INVALIDATE_CONTEXT);
1420 return th->thread_name ();
1423 const char *
1424 win32_process_target::pid_to_exec_file (int pid)
1426 return windows_process.pid_to_exec_file (pid);
1429 /* The win32 target ops object. */
1431 static win32_process_target the_win32_target;
1433 /* Initialize the Win32 backend. */
1434 void
1435 initialize_low (void)
1437 set_target_ops (&the_win32_target);
1438 the_low_target.arch_setup ();
1440 initialize_loadable ();