Automatic date update in version.in
[binutils-gdb.git] / gdbserver / win32-low.cc
blob27224077cea4591115da35a5a87a461e76a3be01
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 "gdb/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 #ifndef COUNTOF
65 #define COUNTOF(STR) (sizeof (STR) / sizeof ((STR)[0]))
66 #endif
68 int using_threads = 1;
70 const struct target_desc *win32_tdesc;
71 #ifdef __x86_64__
72 const struct target_desc *wow64_win32_tdesc;
73 #endif
75 #define NUM_REGS (the_low_target.num_regs ())
77 /* Get the thread ID from the current selected inferior (the current
78 thread). */
79 static ptid_t
80 current_thread_ptid (void)
82 return current_ptid;
85 /* The current debug event from WaitForDebugEvent. */
86 static ptid_t
87 debug_event_ptid (DEBUG_EVENT *event)
89 return ptid_t (event->dwProcessId, event->dwThreadId, 0);
92 /* Get the thread context of the thread associated with TH. */
94 static void
95 win32_get_thread_context (windows_thread_info *th)
97 #ifdef __x86_64__
98 if (windows_process.wow64_process)
99 memset (&th->wow64_context, 0, sizeof (WOW64_CONTEXT));
100 else
101 #endif
102 memset (&th->context, 0, sizeof (CONTEXT));
103 (*the_low_target.get_thread_context) (th);
106 /* Set the thread context of the thread associated with TH. */
108 static void
109 win32_set_thread_context (windows_thread_info *th)
111 #ifdef __x86_64__
112 if (windows_process.wow64_process)
113 Wow64SetThreadContext (th->h, &th->wow64_context);
114 else
115 #endif
116 SetThreadContext (th->h, &th->context);
119 /* Set the thread context of the thread associated with TH. */
121 static void
122 win32_prepare_to_resume (windows_thread_info *th)
124 if (the_low_target.prepare_to_resume != NULL)
125 (*the_low_target.prepare_to_resume) (th);
128 /* See win32-low.h. */
130 void
131 win32_require_context (windows_thread_info *th)
133 DWORD context_flags;
134 #ifdef __x86_64__
135 if (windows_process.wow64_process)
136 context_flags = th->wow64_context.ContextFlags;
137 else
138 #endif
139 context_flags = th->context.ContextFlags;
140 if (context_flags == 0)
142 th->suspend ();
143 win32_get_thread_context (th);
147 /* See nat/windows-nat.h. */
149 windows_thread_info *
150 gdbserver_windows_process::thread_rec
151 (ptid_t ptid, thread_disposition_type disposition)
153 thread_info *thread = find_thread_ptid (ptid);
154 if (thread == NULL)
155 return NULL;
157 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread);
158 if (disposition != DONT_INVALIDATE_CONTEXT)
159 win32_require_context (th);
160 return th;
163 /* Add a thread to the thread list. */
164 static windows_thread_info *
165 child_add_thread (DWORD pid, DWORD tid, HANDLE h, void *tlb)
167 windows_thread_info *th;
168 ptid_t ptid = ptid_t (pid, tid, 0);
170 if ((th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT)))
171 return th;
173 CORE_ADDR base = (CORE_ADDR) (uintptr_t) tlb;
174 #ifdef __x86_64__
175 /* For WOW64 processes, this is actually the pointer to the 64bit TIB,
176 and the 32bit TIB is exactly 2 pages after it. */
177 if (windows_process.wow64_process)
178 base += 2 * 4096; /* page size = 4096 */
179 #endif
180 th = new windows_thread_info (tid, h, base);
182 add_thread (ptid, th);
184 if (the_low_target.thread_added != NULL)
185 (*the_low_target.thread_added) (th);
187 return th;
190 /* Delete a thread from the list of threads. */
191 static void
192 delete_thread_info (thread_info *thread)
194 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread);
196 remove_thread (thread);
197 delete th;
200 /* Delete a thread from the list of threads. */
201 static void
202 child_delete_thread (DWORD pid, DWORD tid)
204 /* If the last thread is exiting, just return. */
205 if (all_threads.size () == 1)
206 return;
208 thread_info *thread = find_thread_ptid (ptid_t (pid, tid));
209 if (thread == NULL)
210 return;
212 delete_thread_info (thread);
215 /* These watchpoint related wrapper functions simply pass on the function call
216 if the low target has registered a corresponding function. */
218 bool
219 win32_process_target::supports_z_point_type (char z_type)
221 return (z_type == Z_PACKET_SW_BP
222 || (the_low_target.supports_z_point_type != NULL
223 && the_low_target.supports_z_point_type (z_type)));
227 win32_process_target::insert_point (enum raw_bkpt_type type, CORE_ADDR addr,
228 int size, raw_breakpoint *bp)
230 if (type == raw_bkpt_type_sw)
231 return insert_memory_breakpoint (bp);
232 else if (the_low_target.insert_point != NULL)
233 return the_low_target.insert_point (type, addr, size, bp);
234 else
235 /* Unsupported (see target.h). */
236 return 1;
240 win32_process_target::remove_point (enum raw_bkpt_type type, CORE_ADDR addr,
241 int size, raw_breakpoint *bp)
243 if (type == raw_bkpt_type_sw)
244 return remove_memory_breakpoint (bp);
245 else if (the_low_target.remove_point != NULL)
246 return the_low_target.remove_point (type, addr, size, bp);
247 else
248 /* Unsupported (see target.h). */
249 return 1;
252 bool
253 win32_process_target::stopped_by_watchpoint ()
255 if (the_low_target.stopped_by_watchpoint != NULL)
256 return the_low_target.stopped_by_watchpoint ();
257 else
258 return false;
261 CORE_ADDR
262 win32_process_target::stopped_data_address ()
264 if (the_low_target.stopped_data_address != NULL)
265 return the_low_target.stopped_data_address ();
266 else
267 return 0;
271 /* Transfer memory from/to the debugged process. */
272 static int
273 child_xfer_memory (CORE_ADDR memaddr, char *our, int len,
274 int write, process_stratum_target *target)
276 BOOL success;
277 SIZE_T done = 0;
278 DWORD lasterror = 0;
279 uintptr_t addr = (uintptr_t) memaddr;
281 if (write)
283 success = WriteProcessMemory (windows_process.handle, (LPVOID) addr,
284 (LPCVOID) our, len, &done);
285 if (!success)
286 lasterror = GetLastError ();
287 FlushInstructionCache (windows_process.handle, (LPCVOID) addr, len);
289 else
291 success = ReadProcessMemory (windows_process.handle, (LPCVOID) addr,
292 (LPVOID) our, len, &done);
293 if (!success)
294 lasterror = GetLastError ();
296 if (!success && lasterror == ERROR_PARTIAL_COPY && done > 0)
297 return done;
298 else
299 return success ? done : -1;
302 /* Clear out any old thread list and reinitialize it to a pristine
303 state. */
304 static void
305 child_init_thread_list (void)
307 for_each_thread (delete_thread_info);
310 static void
311 do_initial_child_stuff (HANDLE proch, DWORD pid, int attached)
313 struct process_info *proc;
315 windows_process.last_sig = GDB_SIGNAL_0;
316 windows_process.handle = proch;
317 windows_process.main_thread_id = 0;
319 windows_process.soft_interrupt_requested = 0;
320 windows_process.faked_breakpoint = 0;
321 windows_process.open_process_used = true;
323 memset (&windows_process.current_event, 0,
324 sizeof (windows_process.current_event));
326 #ifdef __x86_64__
327 BOOL wow64;
328 if (!IsWow64Process (proch, &wow64))
330 DWORD err = GetLastError ();
331 error ("Check if WOW64 process failed (error %d): %s\n",
332 (int) err, strwinerror (err));
334 windows_process.wow64_process = wow64;
336 if (windows_process.wow64_process
337 && (Wow64GetThreadContext == nullptr
338 || Wow64SetThreadContext == nullptr))
339 error ("WOW64 debugging is not supported on this system.\n");
341 windows_process.ignore_first_breakpoint
342 = !attached && windows_process.wow64_process;
343 #endif
345 proc = add_process (pid, attached);
346 #ifdef __x86_64__
347 if (windows_process.wow64_process)
348 proc->tdesc = wow64_win32_tdesc;
349 else
350 #endif
351 proc->tdesc = win32_tdesc;
352 child_init_thread_list ();
353 windows_process.child_initialization_done = 0;
355 if (the_low_target.initial_stuff != NULL)
356 (*the_low_target.initial_stuff) ();
358 windows_process.cached_status.set_ignore ();
360 /* Flush all currently pending debug events (thread and dll list) up
361 to the initial breakpoint. */
362 while (1)
364 struct target_waitstatus status;
366 the_target->wait (minus_one_ptid, &status, 0);
368 /* Note win32_wait doesn't return thread events. */
369 if (status.kind () != TARGET_WAITKIND_LOADED)
371 windows_process.cached_status = status;
372 break;
376 struct thread_resume resume;
378 resume.thread = minus_one_ptid;
379 resume.kind = resume_continue;
380 resume.sig = 0;
382 the_target->resume (&resume, 1);
386 /* Now that the inferior has been started and all DLLs have been mapped,
387 we can iterate over all DLLs and load them in.
389 We avoid doing it any earlier because, on certain versions of Windows,
390 LOAD_DLL_DEBUG_EVENTs are sometimes not complete. In particular,
391 we have seen on Windows 8.1 that the ntdll.dll load event does not
392 include the DLL name, preventing us from creating an associated SO.
393 A possible explanation is that ntdll.dll might be mapped before
394 the SO info gets created by the Windows system -- ntdll.dll is
395 the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs
396 do not seem to suffer from that problem.
398 Rather than try to work around this sort of issue, it is much
399 simpler to just ignore DLL load/unload events during the startup
400 phase, and then process them all in one batch now. */
401 windows_process.add_all_dlls ();
403 windows_process.child_initialization_done = 1;
406 /* Resume all artificially suspended threads if we are continuing
407 execution. */
408 static void
409 continue_one_thread (thread_info *thread, int thread_id)
411 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread);
413 if (thread_id == -1 || thread_id == th->tid)
415 win32_prepare_to_resume (th);
417 if (th->suspended)
419 DWORD *context_flags;
420 #ifdef __x86_64__
421 if (windows_process.wow64_process)
422 context_flags = &th->wow64_context.ContextFlags;
423 else
424 #endif
425 context_flags = &th->context.ContextFlags;
426 if (*context_flags)
428 win32_set_thread_context (th);
429 *context_flags = 0;
432 th->resume ();
437 static BOOL
438 child_continue (DWORD continue_status, int thread_id)
440 windows_process.desired_stop_thread_id = thread_id;
441 if (windows_process.matching_pending_stop (debug_threads))
442 return TRUE;
444 /* The inferior will only continue after the ContinueDebugEvent
445 call. */
446 for_each_thread ([&] (thread_info *thread)
448 continue_one_thread (thread, thread_id);
450 windows_process.faked_breakpoint = 0;
452 return continue_last_debug_event (continue_status, debug_threads);
455 /* Fetch register(s) from the current thread context. */
456 static void
457 child_fetch_inferior_registers (struct regcache *regcache, int r)
459 int regno;
460 windows_thread_info *th
461 = windows_process.thread_rec (current_thread_ptid (),
462 INVALIDATE_CONTEXT);
463 if (r == -1 || r > NUM_REGS)
464 child_fetch_inferior_registers (regcache, NUM_REGS);
465 else
466 for (regno = 0; regno < r; regno++)
467 (*the_low_target.fetch_inferior_register) (regcache, th, regno);
470 /* Store a new register value into the current thread context. We don't
471 change the program's context until later, when we resume it. */
472 static void
473 child_store_inferior_registers (struct regcache *regcache, int r)
475 int regno;
476 windows_thread_info *th
477 = windows_process.thread_rec (current_thread_ptid (),
478 INVALIDATE_CONTEXT);
479 if (r == -1 || r == 0 || r > NUM_REGS)
480 child_store_inferior_registers (regcache, NUM_REGS);
481 else
482 for (regno = 0; regno < r; regno++)
483 (*the_low_target.store_inferior_register) (regcache, th, regno);
486 /* Map the Windows error number in ERROR to a locale-dependent error
487 message string and return a pointer to it. Typically, the values
488 for ERROR come from GetLastError.
490 The string pointed to shall not be modified by the application,
491 but may be overwritten by a subsequent call to strwinerror
493 The strwinerror function does not change the current setting
494 of GetLastError. */
496 char *
497 strwinerror (DWORD error)
499 static char buf[1024];
500 TCHAR *msgbuf;
501 DWORD lasterr = GetLastError ();
502 DWORD chars = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
503 | FORMAT_MESSAGE_ALLOCATE_BUFFER,
504 NULL,
505 error,
506 0, /* Default language */
507 (LPTSTR) &msgbuf,
509 NULL);
510 if (chars != 0)
512 /* If there is an \r\n appended, zap it. */
513 if (chars >= 2
514 && msgbuf[chars - 2] == '\r'
515 && msgbuf[chars - 1] == '\n')
517 chars -= 2;
518 msgbuf[chars] = 0;
521 if (chars > ((COUNTOF (buf)) - 1))
523 chars = COUNTOF (buf) - 1;
524 msgbuf [chars] = 0;
527 #ifdef UNICODE
528 wcstombs (buf, msgbuf, chars + 1);
529 #else
530 strncpy (buf, msgbuf, chars + 1);
531 #endif
532 LocalFree (msgbuf);
534 else
535 sprintf (buf, "unknown win32 error (%u)", (unsigned) error);
537 SetLastError (lasterr);
538 return buf;
541 static BOOL
542 create_process (const char *program, char *args,
543 DWORD flags, PROCESS_INFORMATION *pi)
545 const std::string &inferior_cwd = get_inferior_cwd ();
546 BOOL ret;
547 size_t argslen, proglen;
549 proglen = strlen (program) + 1;
550 argslen = strlen (args) + proglen;
552 STARTUPINFOA si = { sizeof (STARTUPINFOA) };
553 char *program_and_args = (char *) alloca (argslen + 1);
555 strcpy (program_and_args, program);
556 strcat (program_and_args, " ");
557 strcat (program_and_args, args);
558 ret = create_process (program, /* image name */
559 program_and_args, /* command line */
560 flags, /* start flags */
561 NULL, /* environment */
562 /* current directory */
563 (inferior_cwd.empty ()
564 ? NULL
565 : gdb_tilde_expand (inferior_cwd.c_str ()).c_str()),
566 get_client_state ().disable_randomization,
567 &si, /* start info */
568 pi); /* proc info */
570 return ret;
573 /* Start a new process.
574 PROGRAM is the program name.
575 PROGRAM_ARGS is the vector containing the inferior's args.
576 Returns the new PID on success, -1 on failure. Registers the new
577 process with the process list. */
579 win32_process_target::create_inferior (const char *program,
580 const std::vector<char *> &program_args)
582 client_state &cs = get_client_state ();
583 #ifndef USE_WIN32API
584 char real_path[PATH_MAX];
585 char *orig_path, *new_path, *path_ptr;
586 #endif
587 BOOL ret;
588 DWORD flags;
589 PROCESS_INFORMATION pi;
590 DWORD err;
591 std::string str_program_args = construct_inferior_arguments (program_args);
592 char *args = (char *) str_program_args.c_str ();
594 /* win32_wait needs to know we're not attaching. */
595 windows_process.attaching = 0;
597 if (!program)
598 error ("No executable specified, specify executable to debug.\n");
600 flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS;
602 #ifndef USE_WIN32API
603 orig_path = NULL;
604 path_ptr = getenv ("PATH");
605 if (path_ptr)
607 int size = cygwin_conv_path_list (CCP_POSIX_TO_WIN_A, path_ptr, NULL, 0);
608 orig_path = (char *) alloca (strlen (path_ptr) + 1);
609 new_path = (char *) alloca (size);
610 strcpy (orig_path, path_ptr);
611 cygwin_conv_path_list (CCP_POSIX_TO_WIN_A, path_ptr, new_path, size);
612 setenv ("PATH", new_path, 1);
614 cygwin_conv_path (CCP_POSIX_TO_WIN_A, program, real_path, PATH_MAX);
615 program = real_path;
616 #endif
618 OUTMSG2 (("Command line is \"%s %s\"\n", program, args));
620 #ifdef CREATE_NEW_PROCESS_GROUP
621 flags |= CREATE_NEW_PROCESS_GROUP;
622 #endif
624 ret = create_process (program, args, flags, &pi);
625 err = GetLastError ();
626 if (!ret && err == ERROR_FILE_NOT_FOUND)
628 char *exename = (char *) alloca (strlen (program) + 5);
629 strcat (strcpy (exename, program), ".exe");
630 ret = create_process (exename, args, flags, &pi);
631 err = GetLastError ();
634 #ifndef USE_WIN32API
635 if (orig_path)
636 setenv ("PATH", orig_path, 1);
637 #endif
639 if (!ret)
641 error ("Error creating process \"%s %s\", (error %d): %s\n",
642 program, args, (int) err, strwinerror (err));
644 else
646 OUTMSG2 (("Process created: %s %s\n", program, (char *) args));
649 CloseHandle (pi.hThread);
651 do_initial_child_stuff (pi.hProcess, pi.dwProcessId, 0);
653 /* Wait till we are at 1st instruction in program, return new pid
654 (assuming success). */
655 cs.last_ptid = wait (ptid_t (pi.dwProcessId), &cs.last_status, 0);
657 /* Necessary for handle_v_kill. */
658 signal_pid = pi.dwProcessId;
660 return pi.dwProcessId;
663 /* Attach to a running process.
664 PID is the process ID to attach to, specified by the user
665 or a higher layer. */
667 win32_process_target::attach (unsigned long pid)
669 HANDLE h;
670 DWORD err;
672 h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
673 if (h != NULL)
675 if (DebugActiveProcess (pid))
677 DebugSetProcessKillOnExit (FALSE);
679 /* win32_wait needs to know we're attaching. */
680 windows_process.attaching = 1;
681 do_initial_child_stuff (h, pid, 1);
682 return 0;
685 CloseHandle (h);
688 err = GetLastError ();
689 error ("Attach to process failed (error %d): %s\n",
690 (int) err, strwinerror (err));
693 /* See nat/windows-nat.h. */
696 gdbserver_windows_process::handle_output_debug_string
697 (struct target_waitstatus *ourstatus)
699 #define READ_BUFFER_LEN 1024
700 CORE_ADDR addr;
701 char s[READ_BUFFER_LEN + 1] = { 0 };
702 DWORD nbytes = current_event.u.DebugString.nDebugStringLength;
704 if (nbytes == 0)
705 return 0;
707 if (nbytes > READ_BUFFER_LEN)
708 nbytes = READ_BUFFER_LEN;
710 addr = (CORE_ADDR) (size_t) current_event.u.DebugString.lpDebugStringData;
712 if (current_event.u.DebugString.fUnicode)
714 /* The event tells us how many bytes, not chars, even
715 in Unicode. */
716 WCHAR buffer[(READ_BUFFER_LEN + 1) / sizeof (WCHAR)] = { 0 };
717 if (read_inferior_memory (addr, (unsigned char *) buffer, nbytes) != 0)
718 return 0;
719 wcstombs (s, buffer, (nbytes + 1) / sizeof (WCHAR));
721 else
723 if (read_inferior_memory (addr, (unsigned char *) s, nbytes) != 0)
724 return 0;
727 if (!startswith (s, "cYg"))
729 if (!server_waiting)
731 OUTMSG2(("%s", s));
732 return 0;
735 monitor_output (s);
737 #undef READ_BUFFER_LEN
739 return 0;
742 static void
743 win32_clear_inferiors (void)
745 if (windows_process.open_process_used)
747 CloseHandle (windows_process.handle);
748 windows_process.open_process_used = false;
751 for_each_thread (delete_thread_info);
752 windows_process.siginfo_er.ExceptionCode = 0;
753 clear_inferiors ();
756 /* Implementation of target_ops::kill. */
759 win32_process_target::kill (process_info *process)
761 TerminateProcess (windows_process.handle, 0);
762 for (;;)
764 if (!child_continue (DBG_CONTINUE, -1))
765 break;
766 if (!wait_for_debug_event (&windows_process.current_event, INFINITE))
767 break;
768 if (windows_process.current_event.dwDebugEventCode
769 == EXIT_PROCESS_DEBUG_EVENT)
770 break;
771 else if (windows_process.current_event.dwDebugEventCode
772 == OUTPUT_DEBUG_STRING_EVENT)
773 windows_process.handle_output_debug_string (nullptr);
776 win32_clear_inferiors ();
778 remove_process (process);
779 return 0;
782 /* Implementation of target_ops::detach. */
785 win32_process_target::detach (process_info *process)
787 struct thread_resume resume;
788 resume.thread = minus_one_ptid;
789 resume.kind = resume_continue;
790 resume.sig = 0;
791 this->resume (&resume, 1);
793 if (!DebugActiveProcessStop (process->pid))
794 return -1;
796 DebugSetProcessKillOnExit (FALSE);
797 remove_process (process);
799 win32_clear_inferiors ();
800 return 0;
803 void
804 win32_process_target::mourn (struct process_info *process)
806 remove_process (process);
809 /* Implementation of target_ops::join. */
811 void
812 win32_process_target::join (int pid)
814 HANDLE h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
815 if (h != NULL)
817 WaitForSingleObject (h, INFINITE);
818 CloseHandle (h);
822 /* Return true iff the thread with thread ID TID is alive. */
823 bool
824 win32_process_target::thread_alive (ptid_t ptid)
826 /* Our thread list is reliable; don't bother to poll target
827 threads. */
828 return find_thread_ptid (ptid) != NULL;
831 /* Resume the inferior process. RESUME_INFO describes how we want
832 to resume. */
833 void
834 win32_process_target::resume (thread_resume *resume_info, size_t n)
836 DWORD tid;
837 enum gdb_signal sig;
838 int step;
839 windows_thread_info *th;
840 DWORD continue_status = DBG_CONTINUE;
841 ptid_t ptid;
843 /* This handles the very limited set of resume packets that GDB can
844 currently produce. */
846 if (n == 1 && resume_info[0].thread == minus_one_ptid)
847 tid = -1;
848 else if (n > 1)
849 tid = -1;
850 else
851 /* Yes, we're ignoring resume_info[0].thread. It'd be tricky to make
852 the Windows resume code do the right thing for thread switching. */
853 tid = windows_process.current_event.dwThreadId;
855 if (resume_info[0].thread != minus_one_ptid)
857 sig = gdb_signal_from_host (resume_info[0].sig);
858 step = resume_info[0].kind == resume_step;
860 else
862 sig = GDB_SIGNAL_0;
863 step = 0;
866 if (sig != GDB_SIGNAL_0)
868 if (windows_process.current_event.dwDebugEventCode
869 != EXCEPTION_DEBUG_EVENT)
871 OUTMSG (("Cannot continue with signal %s here.\n",
872 gdb_signal_to_string (sig)));
874 else if (sig == windows_process.last_sig)
875 continue_status = DBG_EXCEPTION_NOT_HANDLED;
876 else
877 OUTMSG (("Can only continue with received signal %s.\n",
878 gdb_signal_to_string (windows_process.last_sig)));
881 windows_process.last_sig = GDB_SIGNAL_0;
883 /* Get context for the currently selected thread. */
884 ptid = debug_event_ptid (&windows_process.current_event);
885 th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
886 if (th)
888 win32_prepare_to_resume (th);
890 DWORD *context_flags;
891 #ifdef __x86_64__
892 if (windows_process.wow64_process)
893 context_flags = &th->wow64_context.ContextFlags;
894 else
895 #endif
896 context_flags = &th->context.ContextFlags;
897 if (*context_flags)
899 /* Move register values from the inferior into the thread
900 context structure. */
901 regcache_invalidate ();
903 if (step)
905 if (the_low_target.single_step != NULL)
906 (*the_low_target.single_step) (th);
907 else
908 error ("Single stepping is not supported "
909 "in this configuration.\n");
912 win32_set_thread_context (th);
913 *context_flags = 0;
917 /* Allow continuing with the same signal that interrupted us.
918 Otherwise complain. */
920 child_continue (continue_status, tid);
923 /* See nat/windows-nat.h. */
925 void
926 gdbserver_windows_process::handle_load_dll (const char *name, LPVOID base)
928 CORE_ADDR load_addr = (CORE_ADDR) (uintptr_t) base;
930 char buf[MAX_PATH + 1];
931 char buf2[MAX_PATH + 1];
933 WIN32_FIND_DATAA w32_fd;
934 HANDLE h = FindFirstFileA (name, &w32_fd);
936 /* The symbols in a dll are offset by 0x1000, which is the
937 offset from 0 of the first byte in an image - because
938 of the file header and the section alignment. */
939 load_addr += 0x1000;
941 if (h == INVALID_HANDLE_VALUE)
942 strcpy (buf, name);
943 else
945 FindClose (h);
946 strcpy (buf, name);
948 char cwd[MAX_PATH + 1];
949 char *p;
950 if (GetCurrentDirectoryA (MAX_PATH + 1, cwd))
952 p = strrchr (buf, '\\');
953 if (p)
954 p[1] = '\0';
955 SetCurrentDirectoryA (buf);
956 GetFullPathNameA (w32_fd.cFileName, MAX_PATH, buf, &p);
957 SetCurrentDirectoryA (cwd);
962 if (strcasecmp (buf, "ntdll.dll") == 0)
964 GetSystemDirectoryA (buf, sizeof (buf));
965 strcat (buf, "\\ntdll.dll");
968 #ifdef __CYGWIN__
969 cygwin_conv_path (CCP_WIN_A_TO_POSIX, buf, buf2, sizeof (buf2));
970 #else
971 strcpy (buf2, buf);
972 #endif
974 loaded_dll (buf2, load_addr);
977 /* See nat/windows-nat.h. */
979 void
980 gdbserver_windows_process::handle_unload_dll ()
982 CORE_ADDR load_addr =
983 (CORE_ADDR) (uintptr_t) current_event.u.UnloadDll.lpBaseOfDll;
985 /* The symbols in a dll are offset by 0x1000, which is the
986 offset from 0 of the first byte in an image - because
987 of the file header and the section alignment. */
988 load_addr += 0x1000;
989 unloaded_dll (NULL, load_addr);
992 static void
993 suspend_one_thread (thread_info *thread)
995 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread);
997 th->suspend ();
1000 static void
1001 fake_breakpoint_event (void)
1003 OUTMSG2(("fake_breakpoint_event\n"));
1005 windows_process.faked_breakpoint = 1;
1007 memset (&windows_process.current_event, 0,
1008 sizeof (windows_process.current_event));
1009 windows_process.current_event.dwThreadId = windows_process.main_thread_id;
1010 windows_process.current_event.dwDebugEventCode = EXCEPTION_DEBUG_EVENT;
1011 windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
1012 = EXCEPTION_BREAKPOINT;
1014 for_each_thread (suspend_one_thread);
1017 /* See nat/windows-nat.h. */
1019 bool
1020 gdbserver_windows_process::handle_access_violation
1021 (const EXCEPTION_RECORD *rec)
1023 return false;
1026 /* A helper function that will, if needed, set
1027 'stopped_at_software_breakpoint' on the thread and adjust the
1028 PC. */
1030 static void
1031 maybe_adjust_pc ()
1033 struct regcache *regcache = get_thread_regcache (current_thread, 1);
1034 child_fetch_inferior_registers (regcache, -1);
1036 windows_thread_info *th
1037 = windows_process.thread_rec (current_thread_ptid (),
1038 DONT_INVALIDATE_CONTEXT);
1039 th->stopped_at_software_breakpoint = false;
1041 if (windows_process.current_event.dwDebugEventCode == EXCEPTION_DEBUG_EVENT
1042 && ((windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
1043 == EXCEPTION_BREAKPOINT)
1044 || (windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
1045 == STATUS_WX86_BREAKPOINT))
1046 && windows_process.child_initialization_done)
1048 th->stopped_at_software_breakpoint = true;
1049 CORE_ADDR pc = regcache_read_pc (regcache);
1050 CORE_ADDR sw_breakpoint_pc = pc - the_low_target.decr_pc_after_break;
1051 regcache_write_pc (regcache, sw_breakpoint_pc);
1055 /* Get the next event from the child. */
1057 static int
1058 get_child_debug_event (DWORD *continue_status,
1059 struct target_waitstatus *ourstatus)
1061 ptid_t ptid;
1063 windows_process.last_sig = GDB_SIGNAL_0;
1064 ourstatus->set_spurious ();
1065 *continue_status = DBG_CONTINUE;
1067 /* Check if GDB sent us an interrupt request. */
1068 check_remote_input_interrupt_request ();
1070 DEBUG_EVENT *current_event = &windows_process.current_event;
1072 if (windows_process.soft_interrupt_requested)
1074 windows_process.soft_interrupt_requested = 0;
1075 fake_breakpoint_event ();
1076 goto gotevent;
1079 windows_process.attaching = 0;
1081 gdb::optional<pending_stop> stop
1082 = windows_process.fetch_pending_stop (debug_threads);
1083 if (stop.has_value ())
1085 *ourstatus = stop->status;
1086 windows_process.current_event = stop->event;
1087 ptid = debug_event_ptid (&windows_process.current_event);
1088 switch_to_thread (find_thread_ptid (ptid));
1089 return 1;
1092 /* Keep the wait time low enough for comfortable remote
1093 interruption, but high enough so gdbserver doesn't become a
1094 bottleneck. */
1095 if (!wait_for_debug_event (&windows_process.current_event, 250))
1097 DWORD e = GetLastError();
1099 if (e == ERROR_PIPE_NOT_CONNECTED)
1101 /* This will happen if the loader fails to succesfully
1102 load the application, e.g., if the main executable
1103 tries to pull in a non-existing export from a
1104 DLL. */
1105 ourstatus->set_exited (1);
1106 return 1;
1109 return 0;
1113 gotevent:
1115 switch (current_event->dwDebugEventCode)
1117 case CREATE_THREAD_DEBUG_EVENT:
1118 OUTMSG2 (("gdbserver: kernel event CREATE_THREAD_DEBUG_EVENT "
1119 "for pid=%u tid=%x)\n",
1120 (unsigned) current_event->dwProcessId,
1121 (unsigned) current_event->dwThreadId));
1123 /* Record the existence of this thread. */
1124 child_add_thread (current_event->dwProcessId,
1125 current_event->dwThreadId,
1126 current_event->u.CreateThread.hThread,
1127 current_event->u.CreateThread.lpThreadLocalBase);
1128 break;
1130 case EXIT_THREAD_DEBUG_EVENT:
1131 OUTMSG2 (("gdbserver: kernel event EXIT_THREAD_DEBUG_EVENT "
1132 "for pid=%u tid=%x\n",
1133 (unsigned) current_event->dwProcessId,
1134 (unsigned) current_event->dwThreadId));
1135 child_delete_thread (current_event->dwProcessId,
1136 current_event->dwThreadId);
1138 switch_to_thread (get_first_thread ());
1139 return 1;
1141 case CREATE_PROCESS_DEBUG_EVENT:
1142 OUTMSG2 (("gdbserver: kernel event CREATE_PROCESS_DEBUG_EVENT "
1143 "for pid=%u tid=%x\n",
1144 (unsigned) current_event->dwProcessId,
1145 (unsigned) current_event->dwThreadId));
1146 CloseHandle (current_event->u.CreateProcessInfo.hFile);
1148 if (windows_process.open_process_used)
1150 CloseHandle (windows_process.handle);
1151 windows_process.open_process_used = false;
1154 windows_process.handle = current_event->u.CreateProcessInfo.hProcess;
1155 windows_process.main_thread_id = current_event->dwThreadId;
1157 /* Add the main thread. */
1158 child_add_thread (current_event->dwProcessId,
1159 windows_process.main_thread_id,
1160 current_event->u.CreateProcessInfo.hThread,
1161 current_event->u.CreateProcessInfo.lpThreadLocalBase);
1162 break;
1164 case EXIT_PROCESS_DEBUG_EVENT:
1165 OUTMSG2 (("gdbserver: kernel event EXIT_PROCESS_DEBUG_EVENT "
1166 "for pid=%u tid=%x\n",
1167 (unsigned) current_event->dwProcessId,
1168 (unsigned) current_event->dwThreadId));
1170 DWORD exit_status = current_event->u.ExitProcess.dwExitCode;
1171 /* If the exit status looks like a fatal exception, but we
1172 don't recognize the exception's code, make the original
1173 exit status value available, to avoid losing information. */
1174 int exit_signal
1175 = WIFSIGNALED (exit_status) ? WTERMSIG (exit_status) : -1;
1176 if (exit_signal == -1)
1177 ourstatus->set_exited (exit_status);
1178 else
1179 ourstatus->set_signalled (gdb_signal_from_host (exit_signal));
1181 child_continue (DBG_CONTINUE, windows_process.desired_stop_thread_id);
1182 break;
1184 case LOAD_DLL_DEBUG_EVENT:
1185 OUTMSG2 (("gdbserver: kernel event LOAD_DLL_DEBUG_EVENT "
1186 "for pid=%u tid=%x\n",
1187 (unsigned) current_event->dwProcessId,
1188 (unsigned) current_event->dwThreadId));
1189 CloseHandle (current_event->u.LoadDll.hFile);
1190 if (! windows_process.child_initialization_done)
1191 break;
1192 windows_process.dll_loaded_event ();
1194 ourstatus->set_loaded ();
1195 break;
1197 case UNLOAD_DLL_DEBUG_EVENT:
1198 OUTMSG2 (("gdbserver: kernel event UNLOAD_DLL_DEBUG_EVENT "
1199 "for pid=%u tid=%x\n",
1200 (unsigned) current_event->dwProcessId,
1201 (unsigned) current_event->dwThreadId));
1202 if (! windows_process.child_initialization_done)
1203 break;
1204 windows_process.handle_unload_dll ();
1205 ourstatus->set_loaded ();
1206 break;
1208 case EXCEPTION_DEBUG_EVENT:
1209 OUTMSG2 (("gdbserver: kernel event EXCEPTION_DEBUG_EVENT "
1210 "for pid=%u tid=%x\n",
1211 (unsigned) current_event->dwProcessId,
1212 (unsigned) current_event->dwThreadId));
1213 if (windows_process.handle_exception (ourstatus, debug_threads)
1214 == HANDLE_EXCEPTION_UNHANDLED)
1215 *continue_status = DBG_EXCEPTION_NOT_HANDLED;
1216 break;
1218 case OUTPUT_DEBUG_STRING_EVENT:
1219 /* A message from the kernel (or Cygwin). */
1220 OUTMSG2 (("gdbserver: kernel event OUTPUT_DEBUG_STRING_EVENT "
1221 "for pid=%u tid=%x\n",
1222 (unsigned) current_event->dwProcessId,
1223 (unsigned) current_event->dwThreadId));
1224 windows_process.handle_output_debug_string (nullptr);
1225 break;
1227 default:
1228 OUTMSG2 (("gdbserver: kernel event unknown "
1229 "for pid=%u tid=%x code=%x\n",
1230 (unsigned) current_event->dwProcessId,
1231 (unsigned) current_event->dwThreadId,
1232 (unsigned) current_event->dwDebugEventCode));
1233 break;
1236 ptid = debug_event_ptid (&windows_process.current_event);
1238 if (windows_process.desired_stop_thread_id != -1
1239 && windows_process.desired_stop_thread_id != ptid.lwp ())
1241 /* Pending stop. See the comment by the definition of
1242 "pending_stops" for details on why this is needed. */
1243 OUTMSG2 (("get_windows_debug_event - "
1244 "unexpected stop in 0x%lx (expecting 0x%x)\n",
1245 ptid.lwp (), windows_process.desired_stop_thread_id));
1246 maybe_adjust_pc ();
1247 windows_process.pending_stops.push_back
1248 ({(DWORD) ptid.lwp (), *ourstatus, *current_event});
1249 ourstatus->set_spurious ();
1251 else
1252 switch_to_thread (find_thread_ptid (ptid));
1254 return 1;
1257 /* Wait for the inferior process to change state.
1258 STATUS will be filled in with a response code to send to GDB.
1259 Returns the signal which caused the process to stop. */
1260 ptid_t
1261 win32_process_target::wait (ptid_t ptid, target_waitstatus *ourstatus,
1262 target_wait_flags options)
1264 if (windows_process.cached_status.kind () != TARGET_WAITKIND_IGNORE)
1266 /* The core always does a wait after creating the inferior, and
1267 do_initial_child_stuff already ran the inferior to the
1268 initial breakpoint (or an exit, if creating the process
1269 fails). Report it now. */
1270 *ourstatus = windows_process.cached_status;
1271 windows_process.cached_status.set_ignore ();
1272 return debug_event_ptid (&windows_process.current_event);
1275 while (1)
1277 DWORD continue_status;
1278 if (!get_child_debug_event (&continue_status, ourstatus))
1279 continue;
1281 switch (ourstatus->kind ())
1283 case TARGET_WAITKIND_EXITED:
1284 OUTMSG2 (("Child exited with retcode = %x\n",
1285 ourstatus->exit_status ()));
1286 win32_clear_inferiors ();
1287 return ptid_t (windows_process.current_event.dwProcessId);
1288 case TARGET_WAITKIND_STOPPED:
1289 case TARGET_WAITKIND_SIGNALLED:
1290 case TARGET_WAITKIND_LOADED:
1292 OUTMSG2 (("Child Stopped with signal = %d \n",
1293 ourstatus->sig ()));
1294 maybe_adjust_pc ();
1295 return debug_event_ptid (&windows_process.current_event);
1297 default:
1298 OUTMSG (("Ignoring unknown internal event, %d\n",
1299 ourstatus->kind ()));
1300 /* fall-through */
1301 case TARGET_WAITKIND_SPURIOUS:
1302 /* do nothing, just continue */
1303 child_continue (continue_status,
1304 windows_process.desired_stop_thread_id);
1305 break;
1310 /* Fetch registers from the inferior process.
1311 If REGNO is -1, fetch all registers; otherwise, fetch at least REGNO. */
1312 void
1313 win32_process_target::fetch_registers (regcache *regcache, int regno)
1315 child_fetch_inferior_registers (regcache, regno);
1318 /* Store registers to the inferior process.
1319 If REGNO is -1, store all registers; otherwise, store at least REGNO. */
1320 void
1321 win32_process_target::store_registers (regcache *regcache, int regno)
1323 child_store_inferior_registers (regcache, regno);
1326 /* Read memory from the inferior process. This should generally be
1327 called through read_inferior_memory, which handles breakpoint shadowing.
1328 Read LEN bytes at MEMADDR into a buffer at MYADDR. */
1330 win32_process_target::read_memory (CORE_ADDR memaddr, unsigned char *myaddr,
1331 int len)
1333 return child_xfer_memory (memaddr, (char *) myaddr, len, 0, 0) != len;
1336 /* Write memory to the inferior process. This should generally be
1337 called through write_inferior_memory, which handles breakpoint shadowing.
1338 Write LEN bytes from the buffer at MYADDR to MEMADDR.
1339 Returns 0 on success and errno on failure. */
1341 win32_process_target::write_memory (CORE_ADDR memaddr,
1342 const unsigned char *myaddr, int len)
1344 return child_xfer_memory (memaddr, (char *) myaddr, len, 1, 0) != len;
1347 /* Send an interrupt request to the inferior process. */
1348 void
1349 win32_process_target::request_interrupt ()
1351 if (GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, signal_pid))
1352 return;
1354 /* GenerateConsoleCtrlEvent can fail if process id being debugged is
1355 not a process group id.
1356 Fallback to XP/Vista 'DebugBreakProcess', which generates a
1357 breakpoint exception in the interior process. */
1359 if (DebugBreakProcess (windows_process.handle))
1360 return;
1362 /* Last resort, suspend all threads manually. */
1363 windows_process.soft_interrupt_requested = 1;
1366 bool
1367 win32_process_target::supports_hardware_single_step ()
1369 return true;
1372 bool
1373 win32_process_target::supports_qxfer_siginfo ()
1375 return true;
1378 /* Write Windows signal info. */
1381 win32_process_target::qxfer_siginfo (const char *annex,
1382 unsigned char *readbuf,
1383 unsigned const char *writebuf,
1384 CORE_ADDR offset, int len)
1386 if (windows_process.siginfo_er.ExceptionCode == 0)
1387 return -1;
1389 if (readbuf == nullptr)
1390 return -1;
1392 char *buf = (char *) &windows_process.siginfo_er;
1393 size_t bufsize = sizeof (windows_process.siginfo_er);
1395 #ifdef __x86_64__
1396 EXCEPTION_RECORD32 er32;
1397 if (windows_process.wow64_process)
1399 buf = (char *) &er32;
1400 bufsize = sizeof (er32);
1402 er32.ExceptionCode = windows_process.siginfo_er.ExceptionCode;
1403 er32.ExceptionFlags = windows_process.siginfo_er.ExceptionFlags;
1404 er32.ExceptionRecord
1405 = (uintptr_t) windows_process.siginfo_er.ExceptionRecord;
1406 er32.ExceptionAddress
1407 = (uintptr_t) windows_process.siginfo_er.ExceptionAddress;
1408 er32.NumberParameters = windows_process.siginfo_er.NumberParameters;
1409 int i;
1410 for (i = 0; i < EXCEPTION_MAXIMUM_PARAMETERS; i++)
1411 er32.ExceptionInformation[i]
1412 = windows_process.siginfo_er.ExceptionInformation[i];
1414 #endif
1416 if (offset > bufsize)
1417 return -1;
1419 if (offset + len > bufsize)
1420 len = bufsize - offset;
1422 memcpy (readbuf, buf + offset, len);
1424 return len;
1427 bool
1428 win32_process_target::supports_get_tib_address ()
1430 return true;
1433 /* Write Windows OS Thread Information Block address. */
1436 win32_process_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
1438 windows_thread_info *th;
1439 th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
1440 if (th == NULL)
1441 return 0;
1442 if (addr != NULL)
1443 *addr = th->thread_local_base;
1444 return 1;
1447 /* Implementation of the target_ops method "sw_breakpoint_from_kind". */
1449 const gdb_byte *
1450 win32_process_target::sw_breakpoint_from_kind (int kind, int *size)
1452 *size = the_low_target.breakpoint_len;
1453 return the_low_target.breakpoint;
1456 bool
1457 win32_process_target::stopped_by_sw_breakpoint ()
1459 windows_thread_info *th
1460 = windows_process.thread_rec (current_thread_ptid (),
1461 DONT_INVALIDATE_CONTEXT);
1462 return th == nullptr ? false : th->stopped_at_software_breakpoint;
1465 bool
1466 win32_process_target::supports_stopped_by_sw_breakpoint ()
1468 return true;
1471 CORE_ADDR
1472 win32_process_target::read_pc (struct regcache *regcache)
1474 return (*the_low_target.get_pc) (regcache);
1477 void
1478 win32_process_target::write_pc (struct regcache *regcache, CORE_ADDR pc)
1480 return (*the_low_target.set_pc) (regcache, pc);
1483 const char *
1484 win32_process_target::thread_name (ptid_t thread)
1486 windows_thread_info *th
1487 = windows_process.thread_rec (current_thread_ptid (),
1488 DONT_INVALIDATE_CONTEXT);
1489 return th->thread_name ();
1492 const char *
1493 win32_process_target::pid_to_exec_file (int pid)
1495 return windows_process.pid_to_exec_file (pid);
1498 /* The win32 target ops object. */
1500 static win32_process_target the_win32_target;
1502 /* Initialize the Win32 backend. */
1503 void
1504 initialize_low (void)
1506 set_target_ops (&the_win32_target);
1507 the_low_target.arch_setup ();
1509 initialize_loadable ();