Automatic date update in version.in
[binutils-gdb.git] / gdbserver / win32-low.cc
blobaf132f60215d14e61a512719faedc36384694952
1 /* Low level interface to Windows debugging, for gdbserver.
2 Copyright (C) 2006-2022 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 error ("Check if WOW64 process failed (error %d): %s\n",
328 (int) err, strwinerror (err));
330 windows_process.wow64_process = wow64;
332 if (windows_process.wow64_process
333 && (Wow64GetThreadContext == nullptr
334 || Wow64SetThreadContext == nullptr))
335 error ("WOW64 debugging is not supported on this system.\n");
337 windows_process.ignore_first_breakpoint
338 = !attached && windows_process.wow64_process;
339 #endif
341 proc = add_process (pid, attached);
342 #ifdef __x86_64__
343 if (windows_process.wow64_process)
344 proc->tdesc = wow64_win32_tdesc;
345 else
346 #endif
347 proc->tdesc = win32_tdesc;
348 child_init_thread_list ();
349 windows_process.child_initialization_done = 0;
351 if (the_low_target.initial_stuff != NULL)
352 (*the_low_target.initial_stuff) ();
354 windows_process.cached_status.set_ignore ();
356 /* Flush all currently pending debug events (thread and dll list) up
357 to the initial breakpoint. */
358 while (1)
360 struct target_waitstatus status;
362 the_target->wait (minus_one_ptid, &status, 0);
364 /* Note win32_wait doesn't return thread events. */
365 if (status.kind () != TARGET_WAITKIND_LOADED)
367 windows_process.cached_status = status;
368 break;
372 struct thread_resume resume;
374 resume.thread = minus_one_ptid;
375 resume.kind = resume_continue;
376 resume.sig = 0;
378 the_target->resume (&resume, 1);
382 /* Now that the inferior has been started and all DLLs have been mapped,
383 we can iterate over all DLLs and load them in.
385 We avoid doing it any earlier because, on certain versions of Windows,
386 LOAD_DLL_DEBUG_EVENTs are sometimes not complete. In particular,
387 we have seen on Windows 8.1 that the ntdll.dll load event does not
388 include the DLL name, preventing us from creating an associated SO.
389 A possible explanation is that ntdll.dll might be mapped before
390 the SO info gets created by the Windows system -- ntdll.dll is
391 the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs
392 do not seem to suffer from that problem.
394 Rather than try to work around this sort of issue, it is much
395 simpler to just ignore DLL load/unload events during the startup
396 phase, and then process them all in one batch now. */
397 windows_process.add_all_dlls ();
399 windows_process.child_initialization_done = 1;
402 /* Resume all artificially suspended threads if we are continuing
403 execution. */
404 static void
405 continue_one_thread (thread_info *thread, int thread_id)
407 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread);
409 if (thread_id == -1 || thread_id == th->tid)
411 win32_prepare_to_resume (th);
413 if (th->suspended)
415 DWORD *context_flags;
416 #ifdef __x86_64__
417 if (windows_process.wow64_process)
418 context_flags = &th->wow64_context.ContextFlags;
419 else
420 #endif
421 context_flags = &th->context.ContextFlags;
422 if (*context_flags)
424 win32_set_thread_context (th);
425 *context_flags = 0;
428 th->resume ();
433 static BOOL
434 child_continue (DWORD continue_status, int thread_id)
436 windows_process.desired_stop_thread_id = thread_id;
437 if (windows_process.matching_pending_stop (debug_threads))
438 return TRUE;
440 /* The inferior will only continue after the ContinueDebugEvent
441 call. */
442 for_each_thread ([&] (thread_info *thread)
444 continue_one_thread (thread, thread_id);
446 windows_process.faked_breakpoint = 0;
448 return continue_last_debug_event (continue_status, debug_threads);
451 /* Fetch register(s) from the current thread context. */
452 static void
453 child_fetch_inferior_registers (struct regcache *regcache, int r)
455 int regno;
456 windows_thread_info *th
457 = windows_process.thread_rec (current_thread_ptid (),
458 INVALIDATE_CONTEXT);
459 if (r == -1 || r > NUM_REGS)
460 child_fetch_inferior_registers (regcache, NUM_REGS);
461 else
462 for (regno = 0; regno < r; regno++)
463 (*the_low_target.fetch_inferior_register) (regcache, th, regno);
466 /* Store a new register value into the current thread context. We don't
467 change the program's context until later, when we resume it. */
468 static void
469 child_store_inferior_registers (struct regcache *regcache, int r)
471 int regno;
472 windows_thread_info *th
473 = windows_process.thread_rec (current_thread_ptid (),
474 INVALIDATE_CONTEXT);
475 if (r == -1 || r == 0 || r > NUM_REGS)
476 child_store_inferior_registers (regcache, NUM_REGS);
477 else
478 for (regno = 0; regno < r; regno++)
479 (*the_low_target.store_inferior_register) (regcache, th, regno);
482 static BOOL
483 create_process (const char *program, char *args,
484 DWORD flags, PROCESS_INFORMATION *pi)
486 const std::string &inferior_cwd = get_inferior_cwd ();
487 BOOL ret;
488 size_t argslen, proglen;
490 proglen = strlen (program) + 1;
491 argslen = strlen (args) + proglen;
493 STARTUPINFOA si = { sizeof (STARTUPINFOA) };
494 char *program_and_args = (char *) alloca (argslen + 1);
496 strcpy (program_and_args, program);
497 strcat (program_and_args, " ");
498 strcat (program_and_args, args);
499 ret = create_process (program, /* image name */
500 program_and_args, /* command line */
501 flags, /* start flags */
502 NULL, /* environment */
503 /* current directory */
504 (inferior_cwd.empty ()
505 ? NULL
506 : gdb_tilde_expand (inferior_cwd.c_str ()).c_str()),
507 get_client_state ().disable_randomization,
508 &si, /* start info */
509 pi); /* proc info */
511 return ret;
514 /* Start a new process.
515 PROGRAM is the program name.
516 PROGRAM_ARGS is the vector containing the inferior's args.
517 Returns the new PID on success, -1 on failure. Registers the new
518 process with the process list. */
520 win32_process_target::create_inferior (const char *program,
521 const std::vector<char *> &program_args)
523 client_state &cs = get_client_state ();
524 #ifndef USE_WIN32API
525 char real_path[PATH_MAX];
526 char *orig_path, *new_path, *path_ptr;
527 #endif
528 BOOL ret;
529 DWORD flags;
530 PROCESS_INFORMATION pi;
531 DWORD err;
532 std::string str_program_args = construct_inferior_arguments (program_args);
533 char *args = (char *) str_program_args.c_str ();
535 /* win32_wait needs to know we're not attaching. */
536 windows_process.attaching = 0;
538 if (!program)
539 error ("No executable specified, specify executable to debug.\n");
541 flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS;
543 #ifndef USE_WIN32API
544 orig_path = NULL;
545 path_ptr = getenv ("PATH");
546 if (path_ptr)
548 int size = cygwin_conv_path_list (CCP_POSIX_TO_WIN_A, path_ptr, NULL, 0);
549 orig_path = (char *) alloca (strlen (path_ptr) + 1);
550 new_path = (char *) alloca (size);
551 strcpy (orig_path, path_ptr);
552 cygwin_conv_path_list (CCP_POSIX_TO_WIN_A, path_ptr, new_path, size);
553 setenv ("PATH", new_path, 1);
555 cygwin_conv_path (CCP_POSIX_TO_WIN_A, program, real_path, PATH_MAX);
556 program = real_path;
557 #endif
559 OUTMSG2 (("Command line is \"%s %s\"\n", program, args));
561 #ifdef CREATE_NEW_PROCESS_GROUP
562 flags |= CREATE_NEW_PROCESS_GROUP;
563 #endif
565 ret = create_process (program, args, flags, &pi);
566 err = GetLastError ();
567 if (!ret && err == ERROR_FILE_NOT_FOUND)
569 char *exename = (char *) alloca (strlen (program) + 5);
570 strcat (strcpy (exename, program), ".exe");
571 ret = create_process (exename, args, flags, &pi);
572 err = GetLastError ();
575 #ifndef USE_WIN32API
576 if (orig_path)
577 setenv ("PATH", orig_path, 1);
578 #endif
580 if (!ret)
582 error ("Error creating process \"%s %s\", (error %d): %s\n",
583 program, args, (int) err, strwinerror (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 error ("Attach to process failed (error %d): %s\n",
631 (int) err, strwinerror (err));
634 /* See nat/windows-nat.h. */
637 gdbserver_windows_process::handle_output_debug_string
638 (struct target_waitstatus *ourstatus)
640 #define READ_BUFFER_LEN 1024
641 CORE_ADDR addr;
642 char s[READ_BUFFER_LEN + 1] = { 0 };
643 DWORD nbytes = current_event.u.DebugString.nDebugStringLength;
645 if (nbytes == 0)
646 return 0;
648 if (nbytes > READ_BUFFER_LEN)
649 nbytes = READ_BUFFER_LEN;
651 addr = (CORE_ADDR) (size_t) current_event.u.DebugString.lpDebugStringData;
653 if (current_event.u.DebugString.fUnicode)
655 /* The event tells us how many bytes, not chars, even
656 in Unicode. */
657 WCHAR buffer[(READ_BUFFER_LEN + 1) / sizeof (WCHAR)] = { 0 };
658 if (read_inferior_memory (addr, (unsigned char *) buffer, nbytes) != 0)
659 return 0;
660 wcstombs (s, buffer, (nbytes + 1) / sizeof (WCHAR));
662 else
664 if (read_inferior_memory (addr, (unsigned char *) s, nbytes) != 0)
665 return 0;
668 if (!startswith (s, "cYg"))
670 if (!server_waiting)
672 OUTMSG2(("%s", s));
673 return 0;
676 monitor_output (s);
678 #undef READ_BUFFER_LEN
680 return 0;
683 static void
684 win32_clear_inferiors (void)
686 if (windows_process.open_process_used)
688 CloseHandle (windows_process.handle);
689 windows_process.open_process_used = false;
692 for_each_thread (delete_thread_info);
693 windows_process.siginfo_er.ExceptionCode = 0;
694 clear_inferiors ();
697 /* Implementation of target_ops::kill. */
700 win32_process_target::kill (process_info *process)
702 TerminateProcess (windows_process.handle, 0);
703 for (;;)
705 if (!child_continue (DBG_CONTINUE, -1))
706 break;
707 if (!wait_for_debug_event (&windows_process.current_event, INFINITE))
708 break;
709 if (windows_process.current_event.dwDebugEventCode
710 == EXIT_PROCESS_DEBUG_EVENT)
711 break;
712 else if (windows_process.current_event.dwDebugEventCode
713 == OUTPUT_DEBUG_STRING_EVENT)
714 windows_process.handle_output_debug_string (nullptr);
717 win32_clear_inferiors ();
719 remove_process (process);
720 return 0;
723 /* Implementation of target_ops::detach. */
726 win32_process_target::detach (process_info *process)
728 struct thread_resume resume;
729 resume.thread = minus_one_ptid;
730 resume.kind = resume_continue;
731 resume.sig = 0;
732 this->resume (&resume, 1);
734 if (!DebugActiveProcessStop (process->pid))
735 return -1;
737 DebugSetProcessKillOnExit (FALSE);
738 remove_process (process);
740 win32_clear_inferiors ();
741 return 0;
744 void
745 win32_process_target::mourn (struct process_info *process)
747 remove_process (process);
750 /* Implementation of target_ops::join. */
752 void
753 win32_process_target::join (int pid)
755 HANDLE h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
756 if (h != NULL)
758 WaitForSingleObject (h, INFINITE);
759 CloseHandle (h);
763 /* Return true iff the thread with thread ID TID is alive. */
764 bool
765 win32_process_target::thread_alive (ptid_t ptid)
767 /* Our thread list is reliable; don't bother to poll target
768 threads. */
769 return find_thread_ptid (ptid) != NULL;
772 /* Resume the inferior process. RESUME_INFO describes how we want
773 to resume. */
774 void
775 win32_process_target::resume (thread_resume *resume_info, size_t n)
777 DWORD tid;
778 enum gdb_signal sig;
779 int step;
780 windows_thread_info *th;
781 DWORD continue_status = DBG_CONTINUE;
782 ptid_t ptid;
784 /* This handles the very limited set of resume packets that GDB can
785 currently produce. */
787 if (n == 1 && resume_info[0].thread == minus_one_ptid)
788 tid = -1;
789 else if (n > 1)
790 tid = -1;
791 else
792 /* Yes, we're ignoring resume_info[0].thread. It'd be tricky to make
793 the Windows resume code do the right thing for thread switching. */
794 tid = windows_process.current_event.dwThreadId;
796 if (resume_info[0].thread != minus_one_ptid)
798 sig = gdb_signal_from_host (resume_info[0].sig);
799 step = resume_info[0].kind == resume_step;
801 else
803 sig = GDB_SIGNAL_0;
804 step = 0;
807 if (sig != GDB_SIGNAL_0)
809 if (windows_process.current_event.dwDebugEventCode
810 != EXCEPTION_DEBUG_EVENT)
812 OUTMSG (("Cannot continue with signal %s here.\n",
813 gdb_signal_to_string (sig)));
815 else if (sig == windows_process.last_sig)
816 continue_status = DBG_EXCEPTION_NOT_HANDLED;
817 else
818 OUTMSG (("Can only continue with received signal %s.\n",
819 gdb_signal_to_string (windows_process.last_sig)));
822 windows_process.last_sig = GDB_SIGNAL_0;
824 /* Get context for the currently selected thread. */
825 ptid = debug_event_ptid (&windows_process.current_event);
826 th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
827 if (th)
829 win32_prepare_to_resume (th);
831 DWORD *context_flags;
832 #ifdef __x86_64__
833 if (windows_process.wow64_process)
834 context_flags = &th->wow64_context.ContextFlags;
835 else
836 #endif
837 context_flags = &th->context.ContextFlags;
838 if (*context_flags)
840 /* Move register values from the inferior into the thread
841 context structure. */
842 regcache_invalidate ();
844 if (step)
846 if (the_low_target.single_step != NULL)
847 (*the_low_target.single_step) (th);
848 else
849 error ("Single stepping is not supported "
850 "in this configuration.\n");
853 win32_set_thread_context (th);
854 *context_flags = 0;
858 /* Allow continuing with the same signal that interrupted us.
859 Otherwise complain. */
861 child_continue (continue_status, tid);
864 /* See nat/windows-nat.h. */
866 void
867 gdbserver_windows_process::handle_load_dll (const char *name, LPVOID base)
869 CORE_ADDR load_addr = (CORE_ADDR) (uintptr_t) base;
871 char buf[MAX_PATH + 1];
872 char buf2[MAX_PATH + 1];
874 WIN32_FIND_DATAA w32_fd;
875 HANDLE h = FindFirstFileA (name, &w32_fd);
877 /* The symbols in a dll are offset by 0x1000, which is the
878 offset from 0 of the first byte in an image - because
879 of the file header and the section alignment. */
880 load_addr += 0x1000;
882 if (h == INVALID_HANDLE_VALUE)
883 strcpy (buf, name);
884 else
886 FindClose (h);
887 strcpy (buf, name);
889 char cwd[MAX_PATH + 1];
890 char *p;
891 if (GetCurrentDirectoryA (MAX_PATH + 1, cwd))
893 p = strrchr (buf, '\\');
894 if (p)
895 p[1] = '\0';
896 SetCurrentDirectoryA (buf);
897 GetFullPathNameA (w32_fd.cFileName, MAX_PATH, buf, &p);
898 SetCurrentDirectoryA (cwd);
903 if (strcasecmp (buf, "ntdll.dll") == 0)
905 GetSystemDirectoryA (buf, sizeof (buf));
906 strcat (buf, "\\ntdll.dll");
909 #ifdef __CYGWIN__
910 cygwin_conv_path (CCP_WIN_A_TO_POSIX, buf, buf2, sizeof (buf2));
911 #else
912 strcpy (buf2, buf);
913 #endif
915 loaded_dll (buf2, load_addr);
918 /* See nat/windows-nat.h. */
920 void
921 gdbserver_windows_process::handle_unload_dll ()
923 CORE_ADDR load_addr =
924 (CORE_ADDR) (uintptr_t) current_event.u.UnloadDll.lpBaseOfDll;
926 /* The symbols in a dll are offset by 0x1000, which is the
927 offset from 0 of the first byte in an image - because
928 of the file header and the section alignment. */
929 load_addr += 0x1000;
930 unloaded_dll (NULL, load_addr);
933 static void
934 suspend_one_thread (thread_info *thread)
936 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread);
938 th->suspend ();
941 static void
942 fake_breakpoint_event (void)
944 OUTMSG2(("fake_breakpoint_event\n"));
946 windows_process.faked_breakpoint = 1;
948 memset (&windows_process.current_event, 0,
949 sizeof (windows_process.current_event));
950 windows_process.current_event.dwThreadId = windows_process.main_thread_id;
951 windows_process.current_event.dwDebugEventCode = EXCEPTION_DEBUG_EVENT;
952 windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
953 = EXCEPTION_BREAKPOINT;
955 for_each_thread (suspend_one_thread);
958 /* See nat/windows-nat.h. */
960 bool
961 gdbserver_windows_process::handle_access_violation
962 (const EXCEPTION_RECORD *rec)
964 return false;
967 /* A helper function that will, if needed, set
968 'stopped_at_software_breakpoint' on the thread and adjust the
969 PC. */
971 static void
972 maybe_adjust_pc ()
974 struct regcache *regcache = get_thread_regcache (current_thread, 1);
975 child_fetch_inferior_registers (regcache, -1);
977 windows_thread_info *th
978 = windows_process.thread_rec (current_thread_ptid (),
979 DONT_INVALIDATE_CONTEXT);
980 th->stopped_at_software_breakpoint = false;
982 if (windows_process.current_event.dwDebugEventCode == EXCEPTION_DEBUG_EVENT
983 && ((windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
984 == EXCEPTION_BREAKPOINT)
985 || (windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
986 == STATUS_WX86_BREAKPOINT))
987 && windows_process.child_initialization_done)
989 th->stopped_at_software_breakpoint = true;
990 CORE_ADDR pc = regcache_read_pc (regcache);
991 CORE_ADDR sw_breakpoint_pc = pc - the_low_target.decr_pc_after_break;
992 regcache_write_pc (regcache, sw_breakpoint_pc);
996 /* Get the next event from the child. */
998 static int
999 get_child_debug_event (DWORD *continue_status,
1000 struct target_waitstatus *ourstatus)
1002 ptid_t ptid;
1004 windows_process.last_sig = GDB_SIGNAL_0;
1005 ourstatus->set_spurious ();
1006 *continue_status = DBG_CONTINUE;
1008 /* Check if GDB sent us an interrupt request. */
1009 check_remote_input_interrupt_request ();
1011 DEBUG_EVENT *current_event = &windows_process.current_event;
1013 if (windows_process.soft_interrupt_requested)
1015 windows_process.soft_interrupt_requested = 0;
1016 fake_breakpoint_event ();
1017 goto gotevent;
1020 windows_process.attaching = 0;
1022 gdb::optional<pending_stop> stop
1023 = windows_process.fetch_pending_stop (debug_threads);
1024 if (stop.has_value ())
1026 *ourstatus = stop->status;
1027 windows_process.current_event = stop->event;
1028 ptid = debug_event_ptid (&windows_process.current_event);
1029 switch_to_thread (find_thread_ptid (ptid));
1030 return 1;
1033 /* Keep the wait time low enough for comfortable remote
1034 interruption, but high enough so gdbserver doesn't become a
1035 bottleneck. */
1036 if (!wait_for_debug_event (&windows_process.current_event, 250))
1038 DWORD e = GetLastError();
1040 if (e == ERROR_PIPE_NOT_CONNECTED)
1042 /* This will happen if the loader fails to succesfully
1043 load the application, e.g., if the main executable
1044 tries to pull in a non-existing export from a
1045 DLL. */
1046 ourstatus->set_exited (1);
1047 return 1;
1050 return 0;
1054 gotevent:
1056 switch (current_event->dwDebugEventCode)
1058 case CREATE_THREAD_DEBUG_EVENT:
1059 OUTMSG2 (("gdbserver: kernel event CREATE_THREAD_DEBUG_EVENT "
1060 "for pid=%u tid=%x)\n",
1061 (unsigned) current_event->dwProcessId,
1062 (unsigned) current_event->dwThreadId));
1064 /* Record the existence of this thread. */
1065 child_add_thread (current_event->dwProcessId,
1066 current_event->dwThreadId,
1067 current_event->u.CreateThread.hThread,
1068 current_event->u.CreateThread.lpThreadLocalBase);
1069 break;
1071 case EXIT_THREAD_DEBUG_EVENT:
1072 OUTMSG2 (("gdbserver: kernel event EXIT_THREAD_DEBUG_EVENT "
1073 "for pid=%u tid=%x\n",
1074 (unsigned) current_event->dwProcessId,
1075 (unsigned) current_event->dwThreadId));
1076 child_delete_thread (current_event->dwProcessId,
1077 current_event->dwThreadId);
1079 switch_to_thread (get_first_thread ());
1080 return 1;
1082 case CREATE_PROCESS_DEBUG_EVENT:
1083 OUTMSG2 (("gdbserver: kernel event CREATE_PROCESS_DEBUG_EVENT "
1084 "for pid=%u tid=%x\n",
1085 (unsigned) current_event->dwProcessId,
1086 (unsigned) current_event->dwThreadId));
1087 CloseHandle (current_event->u.CreateProcessInfo.hFile);
1089 if (windows_process.open_process_used)
1091 CloseHandle (windows_process.handle);
1092 windows_process.open_process_used = false;
1095 windows_process.handle = current_event->u.CreateProcessInfo.hProcess;
1096 windows_process.main_thread_id = current_event->dwThreadId;
1098 /* Add the main thread. */
1099 child_add_thread (current_event->dwProcessId,
1100 windows_process.main_thread_id,
1101 current_event->u.CreateProcessInfo.hThread,
1102 current_event->u.CreateProcessInfo.lpThreadLocalBase);
1103 break;
1105 case EXIT_PROCESS_DEBUG_EVENT:
1106 OUTMSG2 (("gdbserver: kernel event EXIT_PROCESS_DEBUG_EVENT "
1107 "for pid=%u tid=%x\n",
1108 (unsigned) current_event->dwProcessId,
1109 (unsigned) current_event->dwThreadId));
1111 DWORD exit_status = current_event->u.ExitProcess.dwExitCode;
1112 /* If the exit status looks like a fatal exception, but we
1113 don't recognize the exception's code, make the original
1114 exit status value available, to avoid losing information. */
1115 int exit_signal
1116 = WIFSIGNALED (exit_status) ? WTERMSIG (exit_status) : -1;
1117 if (exit_signal == -1)
1118 ourstatus->set_exited (exit_status);
1119 else
1120 ourstatus->set_signalled (gdb_signal_from_host (exit_signal));
1122 child_continue (DBG_CONTINUE, windows_process.desired_stop_thread_id);
1123 break;
1125 case LOAD_DLL_DEBUG_EVENT:
1126 OUTMSG2 (("gdbserver: kernel event LOAD_DLL_DEBUG_EVENT "
1127 "for pid=%u tid=%x\n",
1128 (unsigned) current_event->dwProcessId,
1129 (unsigned) current_event->dwThreadId));
1130 CloseHandle (current_event->u.LoadDll.hFile);
1131 if (! windows_process.child_initialization_done)
1132 break;
1133 windows_process.dll_loaded_event ();
1135 ourstatus->set_loaded ();
1136 break;
1138 case UNLOAD_DLL_DEBUG_EVENT:
1139 OUTMSG2 (("gdbserver: kernel event UNLOAD_DLL_DEBUG_EVENT "
1140 "for pid=%u tid=%x\n",
1141 (unsigned) current_event->dwProcessId,
1142 (unsigned) current_event->dwThreadId));
1143 if (! windows_process.child_initialization_done)
1144 break;
1145 windows_process.handle_unload_dll ();
1146 ourstatus->set_loaded ();
1147 break;
1149 case EXCEPTION_DEBUG_EVENT:
1150 OUTMSG2 (("gdbserver: kernel event EXCEPTION_DEBUG_EVENT "
1151 "for pid=%u tid=%x\n",
1152 (unsigned) current_event->dwProcessId,
1153 (unsigned) current_event->dwThreadId));
1154 if (windows_process.handle_exception (ourstatus, debug_threads)
1155 == HANDLE_EXCEPTION_UNHANDLED)
1156 *continue_status = DBG_EXCEPTION_NOT_HANDLED;
1157 break;
1159 case OUTPUT_DEBUG_STRING_EVENT:
1160 /* A message from the kernel (or Cygwin). */
1161 OUTMSG2 (("gdbserver: kernel event OUTPUT_DEBUG_STRING_EVENT "
1162 "for pid=%u tid=%x\n",
1163 (unsigned) current_event->dwProcessId,
1164 (unsigned) current_event->dwThreadId));
1165 windows_process.handle_output_debug_string (nullptr);
1166 break;
1168 default:
1169 OUTMSG2 (("gdbserver: kernel event unknown "
1170 "for pid=%u tid=%x code=%x\n",
1171 (unsigned) current_event->dwProcessId,
1172 (unsigned) current_event->dwThreadId,
1173 (unsigned) current_event->dwDebugEventCode));
1174 break;
1177 ptid = debug_event_ptid (&windows_process.current_event);
1179 if (windows_process.desired_stop_thread_id != -1
1180 && windows_process.desired_stop_thread_id != ptid.lwp ())
1182 /* Pending stop. See the comment by the definition of
1183 "pending_stops" for details on why this is needed. */
1184 OUTMSG2 (("get_windows_debug_event - "
1185 "unexpected stop in 0x%lx (expecting 0x%x)\n",
1186 ptid.lwp (), windows_process.desired_stop_thread_id));
1187 maybe_adjust_pc ();
1188 windows_process.pending_stops.push_back
1189 ({(DWORD) ptid.lwp (), *ourstatus, *current_event});
1190 ourstatus->set_spurious ();
1192 else
1193 switch_to_thread (find_thread_ptid (ptid));
1195 return 1;
1198 /* Wait for the inferior process to change state.
1199 STATUS will be filled in with a response code to send to GDB.
1200 Returns the signal which caused the process to stop. */
1201 ptid_t
1202 win32_process_target::wait (ptid_t ptid, target_waitstatus *ourstatus,
1203 target_wait_flags options)
1205 if (windows_process.cached_status.kind () != TARGET_WAITKIND_IGNORE)
1207 /* The core always does a wait after creating the inferior, and
1208 do_initial_child_stuff already ran the inferior to the
1209 initial breakpoint (or an exit, if creating the process
1210 fails). Report it now. */
1211 *ourstatus = windows_process.cached_status;
1212 windows_process.cached_status.set_ignore ();
1213 return debug_event_ptid (&windows_process.current_event);
1216 while (1)
1218 DWORD continue_status;
1219 if (!get_child_debug_event (&continue_status, ourstatus))
1220 continue;
1222 switch (ourstatus->kind ())
1224 case TARGET_WAITKIND_EXITED:
1225 OUTMSG2 (("Child exited with retcode = %x\n",
1226 ourstatus->exit_status ()));
1227 win32_clear_inferiors ();
1228 return ptid_t (windows_process.current_event.dwProcessId);
1229 case TARGET_WAITKIND_STOPPED:
1230 case TARGET_WAITKIND_SIGNALLED:
1231 case TARGET_WAITKIND_LOADED:
1233 OUTMSG2 (("Child Stopped with signal = %d \n",
1234 ourstatus->sig ()));
1235 maybe_adjust_pc ();
1236 return debug_event_ptid (&windows_process.current_event);
1238 default:
1239 OUTMSG (("Ignoring unknown internal event, %d\n",
1240 ourstatus->kind ()));
1241 /* fall-through */
1242 case TARGET_WAITKIND_SPURIOUS:
1243 /* do nothing, just continue */
1244 child_continue (continue_status,
1245 windows_process.desired_stop_thread_id);
1246 break;
1251 /* Fetch registers from the inferior process.
1252 If REGNO is -1, fetch all registers; otherwise, fetch at least REGNO. */
1253 void
1254 win32_process_target::fetch_registers (regcache *regcache, int regno)
1256 child_fetch_inferior_registers (regcache, regno);
1259 /* Store registers to the inferior process.
1260 If REGNO is -1, store all registers; otherwise, store at least REGNO. */
1261 void
1262 win32_process_target::store_registers (regcache *regcache, int regno)
1264 child_store_inferior_registers (regcache, regno);
1267 /* Read memory from the inferior process. This should generally be
1268 called through read_inferior_memory, which handles breakpoint shadowing.
1269 Read LEN bytes at MEMADDR into a buffer at MYADDR. */
1271 win32_process_target::read_memory (CORE_ADDR memaddr, unsigned char *myaddr,
1272 int len)
1274 return child_xfer_memory (memaddr, (char *) myaddr, len, 0, 0) != len;
1277 /* Write memory to the inferior process. This should generally be
1278 called through write_inferior_memory, which handles breakpoint shadowing.
1279 Write LEN bytes from the buffer at MYADDR to MEMADDR.
1280 Returns 0 on success and errno on failure. */
1282 win32_process_target::write_memory (CORE_ADDR memaddr,
1283 const unsigned char *myaddr, int len)
1285 return child_xfer_memory (memaddr, (char *) myaddr, len, 1, 0) != len;
1288 /* Send an interrupt request to the inferior process. */
1289 void
1290 win32_process_target::request_interrupt ()
1292 if (GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, signal_pid))
1293 return;
1295 /* GenerateConsoleCtrlEvent can fail if process id being debugged is
1296 not a process group id.
1297 Fallback to XP/Vista 'DebugBreakProcess', which generates a
1298 breakpoint exception in the interior process. */
1300 if (DebugBreakProcess (windows_process.handle))
1301 return;
1303 /* Last resort, suspend all threads manually. */
1304 windows_process.soft_interrupt_requested = 1;
1307 bool
1308 win32_process_target::supports_hardware_single_step ()
1310 return true;
1313 bool
1314 win32_process_target::supports_qxfer_siginfo ()
1316 return true;
1319 /* Write Windows signal info. */
1322 win32_process_target::qxfer_siginfo (const char *annex,
1323 unsigned char *readbuf,
1324 unsigned const char *writebuf,
1325 CORE_ADDR offset, int len)
1327 if (windows_process.siginfo_er.ExceptionCode == 0)
1328 return -1;
1330 if (readbuf == nullptr)
1331 return -1;
1333 char *buf = (char *) &windows_process.siginfo_er;
1334 size_t bufsize = sizeof (windows_process.siginfo_er);
1336 #ifdef __x86_64__
1337 EXCEPTION_RECORD32 er32;
1338 if (windows_process.wow64_process)
1340 buf = (char *) &er32;
1341 bufsize = sizeof (er32);
1343 er32.ExceptionCode = windows_process.siginfo_er.ExceptionCode;
1344 er32.ExceptionFlags = windows_process.siginfo_er.ExceptionFlags;
1345 er32.ExceptionRecord
1346 = (uintptr_t) windows_process.siginfo_er.ExceptionRecord;
1347 er32.ExceptionAddress
1348 = (uintptr_t) windows_process.siginfo_er.ExceptionAddress;
1349 er32.NumberParameters = windows_process.siginfo_er.NumberParameters;
1350 int i;
1351 for (i = 0; i < EXCEPTION_MAXIMUM_PARAMETERS; i++)
1352 er32.ExceptionInformation[i]
1353 = windows_process.siginfo_er.ExceptionInformation[i];
1355 #endif
1357 if (offset > bufsize)
1358 return -1;
1360 if (offset + len > bufsize)
1361 len = bufsize - offset;
1363 memcpy (readbuf, buf + offset, len);
1365 return len;
1368 bool
1369 win32_process_target::supports_get_tib_address ()
1371 return true;
1374 /* Write Windows OS Thread Information Block address. */
1377 win32_process_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
1379 windows_thread_info *th;
1380 th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
1381 if (th == NULL)
1382 return 0;
1383 if (addr != NULL)
1384 *addr = th->thread_local_base;
1385 return 1;
1388 /* Implementation of the target_ops method "sw_breakpoint_from_kind". */
1390 const gdb_byte *
1391 win32_process_target::sw_breakpoint_from_kind (int kind, int *size)
1393 *size = the_low_target.breakpoint_len;
1394 return the_low_target.breakpoint;
1397 bool
1398 win32_process_target::stopped_by_sw_breakpoint ()
1400 windows_thread_info *th
1401 = windows_process.thread_rec (current_thread_ptid (),
1402 DONT_INVALIDATE_CONTEXT);
1403 return th == nullptr ? false : th->stopped_at_software_breakpoint;
1406 bool
1407 win32_process_target::supports_stopped_by_sw_breakpoint ()
1409 return true;
1412 CORE_ADDR
1413 win32_process_target::read_pc (struct regcache *regcache)
1415 return (*the_low_target.get_pc) (regcache);
1418 void
1419 win32_process_target::write_pc (struct regcache *regcache, CORE_ADDR pc)
1421 return (*the_low_target.set_pc) (regcache, pc);
1424 const char *
1425 win32_process_target::thread_name (ptid_t thread)
1427 windows_thread_info *th
1428 = windows_process.thread_rec (current_thread_ptid (),
1429 DONT_INVALIDATE_CONTEXT);
1430 return th->thread_name ();
1433 const char *
1434 win32_process_target::pid_to_exec_file (int pid)
1436 return windows_process.pid_to_exec_file (pid);
1439 /* The win32 target ops object. */
1441 static win32_process_target the_win32_target;
1443 /* Initialize the Win32 backend. */
1444 void
1445 initialize_low (void)
1447 set_target_ops (&the_win32_target);
1448 the_low_target.arch_setup ();
1450 initialize_loadable ();