Automatic date update in version.in
[binutils-gdb.git] / gdbserver / win32-low.cc
blob192ea465e69c0bbf46375d715c88f639e84671df
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 windows_process_info 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 /* Globals. */
71 static int attaching = 0;
73 /* A status that hasn't been reported to the core yet, and so
74 win32_wait should return it next, instead of fetching the next
75 debug event off the win32 API. */
76 static struct target_waitstatus cached_status;
78 /* Non zero if an interrupt request is to be satisfied by suspending
79 all threads. */
80 static int soft_interrupt_requested = 0;
82 /* Non zero if the inferior is stopped in a simulated breakpoint done
83 by suspending all the threads. */
84 static int faked_breakpoint = 0;
86 /* True if current_process_handle needs to be closed. */
87 static bool open_process_used = false;
89 const struct target_desc *win32_tdesc;
90 #ifdef __x86_64__
91 const struct target_desc *wow64_win32_tdesc;
92 #endif
94 #define NUM_REGS (the_low_target.num_regs ())
96 /* Get the thread ID from the current selected inferior (the current
97 thread). */
98 static ptid_t
99 current_thread_ptid (void)
101 return current_ptid;
104 /* The current debug event from WaitForDebugEvent. */
105 static ptid_t
106 debug_event_ptid (DEBUG_EVENT *event)
108 return ptid_t (event->dwProcessId, event->dwThreadId, 0);
111 /* Get the thread context of the thread associated with TH. */
113 static void
114 win32_get_thread_context (windows_thread_info *th)
116 #ifdef __x86_64__
117 if (windows_process.wow64_process)
118 memset (&th->wow64_context, 0, sizeof (WOW64_CONTEXT));
119 else
120 #endif
121 memset (&th->context, 0, sizeof (CONTEXT));
122 (*the_low_target.get_thread_context) (th);
125 /* Set the thread context of the thread associated with TH. */
127 static void
128 win32_set_thread_context (windows_thread_info *th)
130 #ifdef __x86_64__
131 if (windows_process.wow64_process)
132 Wow64SetThreadContext (th->h, &th->wow64_context);
133 else
134 #endif
135 SetThreadContext (th->h, &th->context);
138 /* Set the thread context of the thread associated with TH. */
140 static void
141 win32_prepare_to_resume (windows_thread_info *th)
143 if (the_low_target.prepare_to_resume != NULL)
144 (*the_low_target.prepare_to_resume) (th);
147 /* See win32-low.h. */
149 void
150 win32_require_context (windows_thread_info *th)
152 DWORD context_flags;
153 #ifdef __x86_64__
154 if (windows_process.wow64_process)
155 context_flags = th->wow64_context.ContextFlags;
156 else
157 #endif
158 context_flags = th->context.ContextFlags;
159 if (context_flags == 0)
161 th->suspend ();
162 win32_get_thread_context (th);
166 /* See nat/windows-nat.h. */
168 windows_thread_info *
169 windows_nat::windows_process_info::thread_rec
170 (ptid_t ptid, thread_disposition_type disposition)
172 thread_info *thread = find_thread_ptid (ptid);
173 if (thread == NULL)
174 return NULL;
176 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread);
177 if (disposition != DONT_INVALIDATE_CONTEXT)
178 win32_require_context (th);
179 return th;
182 /* Add a thread to the thread list. */
183 static windows_thread_info *
184 child_add_thread (DWORD pid, DWORD tid, HANDLE h, void *tlb)
186 windows_thread_info *th;
187 ptid_t ptid = ptid_t (pid, tid, 0);
189 if ((th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT)))
190 return th;
192 CORE_ADDR base = (CORE_ADDR) (uintptr_t) tlb;
193 #ifdef __x86_64__
194 /* For WOW64 processes, this is actually the pointer to the 64bit TIB,
195 and the 32bit TIB is exactly 2 pages after it. */
196 if (windows_process.wow64_process)
197 base += 2 * 4096; /* page size = 4096 */
198 #endif
199 th = new windows_thread_info (tid, h, base);
201 add_thread (ptid, th);
203 if (the_low_target.thread_added != NULL)
204 (*the_low_target.thread_added) (th);
206 return th;
209 /* Delete a thread from the list of threads. */
210 static void
211 delete_thread_info (thread_info *thread)
213 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread);
215 remove_thread (thread);
216 delete th;
219 /* Delete a thread from the list of threads. */
220 static void
221 child_delete_thread (DWORD pid, DWORD tid)
223 /* If the last thread is exiting, just return. */
224 if (all_threads.size () == 1)
225 return;
227 thread_info *thread = find_thread_ptid (ptid_t (pid, tid));
228 if (thread == NULL)
229 return;
231 delete_thread_info (thread);
234 /* These watchpoint related wrapper functions simply pass on the function call
235 if the low target has registered a corresponding function. */
237 bool
238 win32_process_target::supports_z_point_type (char z_type)
240 return (z_type == Z_PACKET_SW_BP
241 || (the_low_target.supports_z_point_type != NULL
242 && the_low_target.supports_z_point_type (z_type)));
246 win32_process_target::insert_point (enum raw_bkpt_type type, CORE_ADDR addr,
247 int size, raw_breakpoint *bp)
249 if (type == raw_bkpt_type_sw)
250 return insert_memory_breakpoint (bp);
251 else if (the_low_target.insert_point != NULL)
252 return the_low_target.insert_point (type, addr, size, bp);
253 else
254 /* Unsupported (see target.h). */
255 return 1;
259 win32_process_target::remove_point (enum raw_bkpt_type type, CORE_ADDR addr,
260 int size, raw_breakpoint *bp)
262 if (type == raw_bkpt_type_sw)
263 return remove_memory_breakpoint (bp);
264 else if (the_low_target.remove_point != NULL)
265 return the_low_target.remove_point (type, addr, size, bp);
266 else
267 /* Unsupported (see target.h). */
268 return 1;
271 bool
272 win32_process_target::stopped_by_watchpoint ()
274 if (the_low_target.stopped_by_watchpoint != NULL)
275 return the_low_target.stopped_by_watchpoint ();
276 else
277 return false;
280 CORE_ADDR
281 win32_process_target::stopped_data_address ()
283 if (the_low_target.stopped_data_address != NULL)
284 return the_low_target.stopped_data_address ();
285 else
286 return 0;
290 /* Transfer memory from/to the debugged process. */
291 static int
292 child_xfer_memory (CORE_ADDR memaddr, char *our, int len,
293 int write, process_stratum_target *target)
295 BOOL success;
296 SIZE_T done = 0;
297 DWORD lasterror = 0;
298 uintptr_t addr = (uintptr_t) memaddr;
300 if (write)
302 success = WriteProcessMemory (windows_process.handle, (LPVOID) addr,
303 (LPCVOID) our, len, &done);
304 if (!success)
305 lasterror = GetLastError ();
306 FlushInstructionCache (windows_process.handle, (LPCVOID) addr, len);
308 else
310 success = ReadProcessMemory (windows_process.handle, (LPCVOID) addr,
311 (LPVOID) our, len, &done);
312 if (!success)
313 lasterror = GetLastError ();
315 if (!success && lasterror == ERROR_PARTIAL_COPY && done > 0)
316 return done;
317 else
318 return success ? done : -1;
321 /* Clear out any old thread list and reinitialize it to a pristine
322 state. */
323 static void
324 child_init_thread_list (void)
326 for_each_thread (delete_thread_info);
329 /* Zero during the child initialization phase, and nonzero otherwise. */
331 static int child_initialization_done = 0;
333 static void
334 do_initial_child_stuff (HANDLE proch, DWORD pid, int attached)
336 struct process_info *proc;
338 windows_process.last_sig = GDB_SIGNAL_0;
339 windows_process.handle = proch;
340 windows_process.id = pid;
341 windows_process.main_thread_id = 0;
343 soft_interrupt_requested = 0;
344 faked_breakpoint = 0;
345 open_process_used = true;
347 memset (&windows_process.current_event, 0,
348 sizeof (windows_process.current_event));
350 #ifdef __x86_64__
351 BOOL wow64;
352 if (!IsWow64Process (proch, &wow64))
354 DWORD err = GetLastError ();
355 error ("Check if WOW64 process failed (error %d): %s\n",
356 (int) err, strwinerror (err));
358 windows_process.wow64_process = wow64;
360 if (windows_process.wow64_process
361 && (Wow64GetThreadContext == nullptr
362 || Wow64SetThreadContext == nullptr))
363 error ("WOW64 debugging is not supported on this system.\n");
365 windows_process.ignore_first_breakpoint
366 = !attached && windows_process.wow64_process;
367 #endif
369 proc = add_process (pid, attached);
370 #ifdef __x86_64__
371 if (windows_process.wow64_process)
372 proc->tdesc = wow64_win32_tdesc;
373 else
374 #endif
375 proc->tdesc = win32_tdesc;
376 child_init_thread_list ();
377 child_initialization_done = 0;
379 if (the_low_target.initial_stuff != NULL)
380 (*the_low_target.initial_stuff) ();
382 cached_status.set_ignore ();
384 /* Flush all currently pending debug events (thread and dll list) up
385 to the initial breakpoint. */
386 while (1)
388 struct target_waitstatus status;
390 the_target->wait (minus_one_ptid, &status, 0);
392 /* Note win32_wait doesn't return thread events. */
393 if (status.kind () != TARGET_WAITKIND_LOADED)
395 cached_status = status;
396 break;
400 struct thread_resume resume;
402 resume.thread = minus_one_ptid;
403 resume.kind = resume_continue;
404 resume.sig = 0;
406 the_target->resume (&resume, 1);
410 /* Now that the inferior has been started and all DLLs have been mapped,
411 we can iterate over all DLLs and load them in.
413 We avoid doing it any earlier because, on certain versions of Windows,
414 LOAD_DLL_DEBUG_EVENTs are sometimes not complete. In particular,
415 we have seen on Windows 8.1 that the ntdll.dll load event does not
416 include the DLL name, preventing us from creating an associated SO.
417 A possible explanation is that ntdll.dll might be mapped before
418 the SO info gets created by the Windows system -- ntdll.dll is
419 the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs
420 do not seem to suffer from that problem.
422 Rather than try to work around this sort of issue, it is much
423 simpler to just ignore DLL load/unload events during the startup
424 phase, and then process them all in one batch now. */
425 windows_process.add_all_dlls ();
427 child_initialization_done = 1;
430 /* Resume all artificially suspended threads if we are continuing
431 execution. */
432 static void
433 continue_one_thread (thread_info *thread, int thread_id)
435 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread);
437 if (thread_id == -1 || thread_id == th->tid)
439 win32_prepare_to_resume (th);
441 if (th->suspended)
443 DWORD *context_flags;
444 #ifdef __x86_64__
445 if (windows_process.wow64_process)
446 context_flags = &th->wow64_context.ContextFlags;
447 else
448 #endif
449 context_flags = &th->context.ContextFlags;
450 if (*context_flags)
452 win32_set_thread_context (th);
453 *context_flags = 0;
456 th->resume ();
461 static BOOL
462 child_continue (DWORD continue_status, int thread_id)
464 windows_process.desired_stop_thread_id = thread_id;
465 if (windows_process.matching_pending_stop (debug_threads))
466 return TRUE;
468 /* The inferior will only continue after the ContinueDebugEvent
469 call. */
470 for_each_thread ([&] (thread_info *thread)
472 continue_one_thread (thread, thread_id);
474 faked_breakpoint = 0;
476 return continue_last_debug_event (continue_status, debug_threads);
479 /* Fetch register(s) from the current thread context. */
480 static void
481 child_fetch_inferior_registers (struct regcache *regcache, int r)
483 int regno;
484 windows_thread_info *th
485 = windows_process.thread_rec (current_thread_ptid (),
486 INVALIDATE_CONTEXT);
487 if (r == -1 || r > NUM_REGS)
488 child_fetch_inferior_registers (regcache, NUM_REGS);
489 else
490 for (regno = 0; regno < r; regno++)
491 (*the_low_target.fetch_inferior_register) (regcache, th, regno);
494 /* Store a new register value into the current thread context. We don't
495 change the program's context until later, when we resume it. */
496 static void
497 child_store_inferior_registers (struct regcache *regcache, int r)
499 int regno;
500 windows_thread_info *th
501 = windows_process.thread_rec (current_thread_ptid (),
502 INVALIDATE_CONTEXT);
503 if (r == -1 || r == 0 || r > NUM_REGS)
504 child_store_inferior_registers (regcache, NUM_REGS);
505 else
506 for (regno = 0; regno < r; regno++)
507 (*the_low_target.store_inferior_register) (regcache, th, regno);
510 /* Map the Windows error number in ERROR to a locale-dependent error
511 message string and return a pointer to it. Typically, the values
512 for ERROR come from GetLastError.
514 The string pointed to shall not be modified by the application,
515 but may be overwritten by a subsequent call to strwinerror
517 The strwinerror function does not change the current setting
518 of GetLastError. */
520 char *
521 strwinerror (DWORD error)
523 static char buf[1024];
524 TCHAR *msgbuf;
525 DWORD lasterr = GetLastError ();
526 DWORD chars = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
527 | FORMAT_MESSAGE_ALLOCATE_BUFFER,
528 NULL,
529 error,
530 0, /* Default language */
531 (LPTSTR) &msgbuf,
533 NULL);
534 if (chars != 0)
536 /* If there is an \r\n appended, zap it. */
537 if (chars >= 2
538 && msgbuf[chars - 2] == '\r'
539 && msgbuf[chars - 1] == '\n')
541 chars -= 2;
542 msgbuf[chars] = 0;
545 if (chars > ((COUNTOF (buf)) - 1))
547 chars = COUNTOF (buf) - 1;
548 msgbuf [chars] = 0;
551 #ifdef UNICODE
552 wcstombs (buf, msgbuf, chars + 1);
553 #else
554 strncpy (buf, msgbuf, chars + 1);
555 #endif
556 LocalFree (msgbuf);
558 else
559 sprintf (buf, "unknown win32 error (%u)", (unsigned) error);
561 SetLastError (lasterr);
562 return buf;
565 static BOOL
566 create_process (const char *program, char *args,
567 DWORD flags, PROCESS_INFORMATION *pi)
569 const std::string &inferior_cwd = get_inferior_cwd ();
570 BOOL ret;
571 size_t argslen, proglen;
573 proglen = strlen (program) + 1;
574 argslen = strlen (args) + proglen;
576 STARTUPINFOA si = { sizeof (STARTUPINFOA) };
577 char *program_and_args = (char *) alloca (argslen + 1);
579 strcpy (program_and_args, program);
580 strcat (program_and_args, " ");
581 strcat (program_and_args, args);
582 ret = CreateProcessA (program, /* image name */
583 program_and_args, /* command line */
584 NULL, /* security */
585 NULL, /* thread */
586 TRUE, /* inherit handles */
587 flags, /* start flags */
588 NULL, /* environment */
589 /* current directory */
590 (inferior_cwd.empty ()
591 ? NULL
592 : gdb_tilde_expand (inferior_cwd.c_str ()).c_str()),
593 &si, /* start info */
594 pi); /* proc info */
596 return ret;
599 /* Start a new process.
600 PROGRAM is the program name.
601 PROGRAM_ARGS is the vector containing the inferior's args.
602 Returns the new PID on success, -1 on failure. Registers the new
603 process with the process list. */
605 win32_process_target::create_inferior (const char *program,
606 const std::vector<char *> &program_args)
608 client_state &cs = get_client_state ();
609 #ifndef USE_WIN32API
610 char real_path[PATH_MAX];
611 char *orig_path, *new_path, *path_ptr;
612 #endif
613 BOOL ret;
614 DWORD flags;
615 PROCESS_INFORMATION pi;
616 DWORD err;
617 std::string str_program_args = construct_inferior_arguments (program_args);
618 char *args = (char *) str_program_args.c_str ();
620 /* win32_wait needs to know we're not attaching. */
621 attaching = 0;
623 if (!program)
624 error ("No executable specified, specify executable to debug.\n");
626 flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS;
628 #ifndef USE_WIN32API
629 orig_path = NULL;
630 path_ptr = getenv ("PATH");
631 if (path_ptr)
633 int size = cygwin_conv_path_list (CCP_POSIX_TO_WIN_A, path_ptr, NULL, 0);
634 orig_path = (char *) alloca (strlen (path_ptr) + 1);
635 new_path = (char *) alloca (size);
636 strcpy (orig_path, path_ptr);
637 cygwin_conv_path_list (CCP_POSIX_TO_WIN_A, path_ptr, new_path, size);
638 setenv ("PATH", new_path, 1);
640 cygwin_conv_path (CCP_POSIX_TO_WIN_A, program, real_path, PATH_MAX);
641 program = real_path;
642 #endif
644 OUTMSG2 (("Command line is \"%s %s\"\n", program, args));
646 #ifdef CREATE_NEW_PROCESS_GROUP
647 flags |= CREATE_NEW_PROCESS_GROUP;
648 #endif
650 ret = create_process (program, args, flags, &pi);
651 err = GetLastError ();
652 if (!ret && err == ERROR_FILE_NOT_FOUND)
654 char *exename = (char *) alloca (strlen (program) + 5);
655 strcat (strcpy (exename, program), ".exe");
656 ret = create_process (exename, args, flags, &pi);
657 err = GetLastError ();
660 #ifndef USE_WIN32API
661 if (orig_path)
662 setenv ("PATH", orig_path, 1);
663 #endif
665 if (!ret)
667 error ("Error creating process \"%s %s\", (error %d): %s\n",
668 program, args, (int) err, strwinerror (err));
670 else
672 OUTMSG2 (("Process created: %s %s\n", program, (char *) args));
675 CloseHandle (pi.hThread);
677 do_initial_child_stuff (pi.hProcess, pi.dwProcessId, 0);
679 /* Wait till we are at 1st instruction in program, return new pid
680 (assuming success). */
681 cs.last_ptid = wait (ptid_t (windows_process.id), &cs.last_status, 0);
683 /* Necessary for handle_v_kill. */
684 signal_pid = windows_process.id;
686 return windows_process.id;
689 /* Attach to a running process.
690 PID is the process ID to attach to, specified by the user
691 or a higher layer. */
693 win32_process_target::attach (unsigned long pid)
695 HANDLE h;
696 DWORD err;
698 h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
699 if (h != NULL)
701 if (DebugActiveProcess (pid))
703 DebugSetProcessKillOnExit (FALSE);
705 /* win32_wait needs to know we're attaching. */
706 attaching = 1;
707 do_initial_child_stuff (h, pid, 1);
708 return 0;
711 CloseHandle (h);
714 err = GetLastError ();
715 error ("Attach to process failed (error %d): %s\n",
716 (int) err, strwinerror (err));
719 /* See nat/windows-nat.h. */
722 windows_nat::windows_process_info::handle_output_debug_string
723 (struct target_waitstatus *ourstatus)
725 #define READ_BUFFER_LEN 1024
726 CORE_ADDR addr;
727 char s[READ_BUFFER_LEN + 1] = { 0 };
728 DWORD nbytes = current_event.u.DebugString.nDebugStringLength;
730 if (nbytes == 0)
731 return 0;
733 if (nbytes > READ_BUFFER_LEN)
734 nbytes = READ_BUFFER_LEN;
736 addr = (CORE_ADDR) (size_t) current_event.u.DebugString.lpDebugStringData;
738 if (current_event.u.DebugString.fUnicode)
740 /* The event tells us how many bytes, not chars, even
741 in Unicode. */
742 WCHAR buffer[(READ_BUFFER_LEN + 1) / sizeof (WCHAR)] = { 0 };
743 if (read_inferior_memory (addr, (unsigned char *) buffer, nbytes) != 0)
744 return 0;
745 wcstombs (s, buffer, (nbytes + 1) / sizeof (WCHAR));
747 else
749 if (read_inferior_memory (addr, (unsigned char *) s, nbytes) != 0)
750 return 0;
753 if (!startswith (s, "cYg"))
755 if (!server_waiting)
757 OUTMSG2(("%s", s));
758 return 0;
761 monitor_output (s);
763 #undef READ_BUFFER_LEN
765 return 0;
768 static void
769 win32_clear_inferiors (void)
771 if (open_process_used)
773 CloseHandle (windows_process.handle);
774 open_process_used = false;
777 for_each_thread (delete_thread_info);
778 windows_process.siginfo_er.ExceptionCode = 0;
779 clear_inferiors ();
782 /* Implementation of target_ops::kill. */
785 win32_process_target::kill (process_info *process)
787 TerminateProcess (windows_process.handle, 0);
788 for (;;)
790 if (!child_continue (DBG_CONTINUE, -1))
791 break;
792 if (!wait_for_debug_event (&windows_process.current_event, INFINITE))
793 break;
794 if (windows_process.current_event.dwDebugEventCode
795 == EXIT_PROCESS_DEBUG_EVENT)
796 break;
797 else if (windows_process.current_event.dwDebugEventCode
798 == OUTPUT_DEBUG_STRING_EVENT)
799 windows_process.handle_output_debug_string (nullptr);
802 win32_clear_inferiors ();
804 remove_process (process);
805 return 0;
808 /* Implementation of target_ops::detach. */
811 win32_process_target::detach (process_info *process)
813 struct thread_resume resume;
814 resume.thread = minus_one_ptid;
815 resume.kind = resume_continue;
816 resume.sig = 0;
817 this->resume (&resume, 1);
819 if (!DebugActiveProcessStop (windows_process.id))
820 return -1;
822 DebugSetProcessKillOnExit (FALSE);
823 remove_process (process);
825 win32_clear_inferiors ();
826 return 0;
829 void
830 win32_process_target::mourn (struct process_info *process)
832 remove_process (process);
835 /* Implementation of target_ops::join. */
837 void
838 win32_process_target::join (int pid)
840 HANDLE h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
841 if (h != NULL)
843 WaitForSingleObject (h, INFINITE);
844 CloseHandle (h);
848 /* Return true iff the thread with thread ID TID is alive. */
849 bool
850 win32_process_target::thread_alive (ptid_t ptid)
852 /* Our thread list is reliable; don't bother to poll target
853 threads. */
854 return find_thread_ptid (ptid) != NULL;
857 /* Resume the inferior process. RESUME_INFO describes how we want
858 to resume. */
859 void
860 win32_process_target::resume (thread_resume *resume_info, size_t n)
862 DWORD tid;
863 enum gdb_signal sig;
864 int step;
865 windows_thread_info *th;
866 DWORD continue_status = DBG_CONTINUE;
867 ptid_t ptid;
869 /* This handles the very limited set of resume packets that GDB can
870 currently produce. */
872 if (n == 1 && resume_info[0].thread == minus_one_ptid)
873 tid = -1;
874 else if (n > 1)
875 tid = -1;
876 else
877 /* Yes, we're ignoring resume_info[0].thread. It'd be tricky to make
878 the Windows resume code do the right thing for thread switching. */
879 tid = windows_process.current_event.dwThreadId;
881 if (resume_info[0].thread != minus_one_ptid)
883 sig = gdb_signal_from_host (resume_info[0].sig);
884 step = resume_info[0].kind == resume_step;
886 else
888 sig = GDB_SIGNAL_0;
889 step = 0;
892 if (sig != GDB_SIGNAL_0)
894 if (windows_process.current_event.dwDebugEventCode
895 != EXCEPTION_DEBUG_EVENT)
897 OUTMSG (("Cannot continue with signal %s here.\n",
898 gdb_signal_to_string (sig)));
900 else if (sig == windows_process.last_sig)
901 continue_status = DBG_EXCEPTION_NOT_HANDLED;
902 else
903 OUTMSG (("Can only continue with received signal %s.\n",
904 gdb_signal_to_string (windows_process.last_sig)));
907 windows_process.last_sig = GDB_SIGNAL_0;
909 /* Get context for the currently selected thread. */
910 ptid = debug_event_ptid (&windows_process.current_event);
911 th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
912 if (th)
914 win32_prepare_to_resume (th);
916 DWORD *context_flags;
917 #ifdef __x86_64__
918 if (windows_process.wow64_process)
919 context_flags = &th->wow64_context.ContextFlags;
920 else
921 #endif
922 context_flags = &th->context.ContextFlags;
923 if (*context_flags)
925 /* Move register values from the inferior into the thread
926 context structure. */
927 regcache_invalidate ();
929 if (step)
931 if (the_low_target.single_step != NULL)
932 (*the_low_target.single_step) (th);
933 else
934 error ("Single stepping is not supported "
935 "in this configuration.\n");
938 win32_set_thread_context (th);
939 *context_flags = 0;
943 /* Allow continuing with the same signal that interrupted us.
944 Otherwise complain. */
946 child_continue (continue_status, tid);
949 /* See nat/windows-nat.h. */
951 void
952 windows_nat::windows_process_info::handle_load_dll (const char *name,
953 LPVOID base)
955 CORE_ADDR load_addr = (CORE_ADDR) (uintptr_t) base;
957 char buf[MAX_PATH + 1];
958 char buf2[MAX_PATH + 1];
960 WIN32_FIND_DATAA w32_fd;
961 HANDLE h = FindFirstFileA (name, &w32_fd);
963 /* The symbols in a dll are offset by 0x1000, which is the
964 offset from 0 of the first byte in an image - because
965 of the file header and the section alignment. */
966 load_addr += 0x1000;
968 if (h == INVALID_HANDLE_VALUE)
969 strcpy (buf, name);
970 else
972 FindClose (h);
973 strcpy (buf, name);
975 char cwd[MAX_PATH + 1];
976 char *p;
977 if (GetCurrentDirectoryA (MAX_PATH + 1, cwd))
979 p = strrchr (buf, '\\');
980 if (p)
981 p[1] = '\0';
982 SetCurrentDirectoryA (buf);
983 GetFullPathNameA (w32_fd.cFileName, MAX_PATH, buf, &p);
984 SetCurrentDirectoryA (cwd);
989 if (strcasecmp (buf, "ntdll.dll") == 0)
991 GetSystemDirectoryA (buf, sizeof (buf));
992 strcat (buf, "\\ntdll.dll");
995 #ifdef __CYGWIN__
996 cygwin_conv_path (CCP_WIN_A_TO_POSIX, buf, buf2, sizeof (buf2));
997 #else
998 strcpy (buf2, buf);
999 #endif
1001 loaded_dll (buf2, load_addr);
1004 /* See nat/windows-nat.h. */
1006 void
1007 windows_nat::windows_process_info::handle_unload_dll ()
1009 CORE_ADDR load_addr =
1010 (CORE_ADDR) (uintptr_t) current_event.u.UnloadDll.lpBaseOfDll;
1012 /* The symbols in a dll are offset by 0x1000, which is the
1013 offset from 0 of the first byte in an image - because
1014 of the file header and the section alignment. */
1015 load_addr += 0x1000;
1016 unloaded_dll (NULL, load_addr);
1019 static void
1020 suspend_one_thread (thread_info *thread)
1022 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread);
1024 th->suspend ();
1027 static void
1028 fake_breakpoint_event (void)
1030 OUTMSG2(("fake_breakpoint_event\n"));
1032 faked_breakpoint = 1;
1034 memset (&windows_process.current_event, 0,
1035 sizeof (windows_process.current_event));
1036 windows_process.current_event.dwThreadId = windows_process.main_thread_id;
1037 windows_process.current_event.dwDebugEventCode = EXCEPTION_DEBUG_EVENT;
1038 windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
1039 = EXCEPTION_BREAKPOINT;
1041 for_each_thread (suspend_one_thread);
1044 /* See nat/windows-nat.h. */
1046 bool
1047 windows_nat::windows_process_info::handle_access_violation
1048 (const EXCEPTION_RECORD *rec)
1050 return false;
1053 /* A helper function that will, if needed, set
1054 'stopped_at_software_breakpoint' on the thread and adjust the
1055 PC. */
1057 static void
1058 maybe_adjust_pc ()
1060 struct regcache *regcache = get_thread_regcache (current_thread, 1);
1061 child_fetch_inferior_registers (regcache, -1);
1063 windows_thread_info *th
1064 = windows_process.thread_rec (current_thread_ptid (),
1065 DONT_INVALIDATE_CONTEXT);
1066 th->stopped_at_software_breakpoint = false;
1068 if (windows_process.current_event.dwDebugEventCode == EXCEPTION_DEBUG_EVENT
1069 && ((windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
1070 == EXCEPTION_BREAKPOINT)
1071 || (windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
1072 == STATUS_WX86_BREAKPOINT))
1073 && child_initialization_done)
1075 th->stopped_at_software_breakpoint = true;
1076 CORE_ADDR pc = regcache_read_pc (regcache);
1077 CORE_ADDR sw_breakpoint_pc = pc - the_low_target.decr_pc_after_break;
1078 regcache_write_pc (regcache, sw_breakpoint_pc);
1082 /* Get the next event from the child. */
1084 static int
1085 get_child_debug_event (DWORD *continue_status,
1086 struct target_waitstatus *ourstatus)
1088 ptid_t ptid;
1090 windows_process.last_sig = GDB_SIGNAL_0;
1091 ourstatus->set_spurious ();
1092 *continue_status = DBG_CONTINUE;
1094 /* Check if GDB sent us an interrupt request. */
1095 check_remote_input_interrupt_request ();
1097 DEBUG_EVENT *current_event = &windows_process.current_event;
1099 if (soft_interrupt_requested)
1101 soft_interrupt_requested = 0;
1102 fake_breakpoint_event ();
1103 goto gotevent;
1106 attaching = 0;
1108 gdb::optional<pending_stop> stop
1109 = windows_process.fetch_pending_stop (debug_threads);
1110 if (stop.has_value ())
1112 *ourstatus = stop->status;
1113 windows_process.current_event = stop->event;
1114 ptid = debug_event_ptid (&windows_process.current_event);
1115 switch_to_thread (find_thread_ptid (ptid));
1116 return 1;
1119 /* Keep the wait time low enough for comfortable remote
1120 interruption, but high enough so gdbserver doesn't become a
1121 bottleneck. */
1122 if (!wait_for_debug_event (&windows_process.current_event, 250))
1124 DWORD e = GetLastError();
1126 if (e == ERROR_PIPE_NOT_CONNECTED)
1128 /* This will happen if the loader fails to succesfully
1129 load the application, e.g., if the main executable
1130 tries to pull in a non-existing export from a
1131 DLL. */
1132 ourstatus->set_exited (1);
1133 return 1;
1136 return 0;
1140 gotevent:
1142 switch (current_event->dwDebugEventCode)
1144 case CREATE_THREAD_DEBUG_EVENT:
1145 OUTMSG2 (("gdbserver: kernel event CREATE_THREAD_DEBUG_EVENT "
1146 "for pid=%u tid=%x)\n",
1147 (unsigned) current_event->dwProcessId,
1148 (unsigned) current_event->dwThreadId));
1150 /* Record the existence of this thread. */
1151 child_add_thread (current_event->dwProcessId,
1152 current_event->dwThreadId,
1153 current_event->u.CreateThread.hThread,
1154 current_event->u.CreateThread.lpThreadLocalBase);
1155 break;
1157 case EXIT_THREAD_DEBUG_EVENT:
1158 OUTMSG2 (("gdbserver: kernel event EXIT_THREAD_DEBUG_EVENT "
1159 "for pid=%u tid=%x\n",
1160 (unsigned) current_event->dwProcessId,
1161 (unsigned) current_event->dwThreadId));
1162 child_delete_thread (current_event->dwProcessId,
1163 current_event->dwThreadId);
1165 switch_to_thread (get_first_thread ());
1166 return 1;
1168 case CREATE_PROCESS_DEBUG_EVENT:
1169 OUTMSG2 (("gdbserver: kernel event CREATE_PROCESS_DEBUG_EVENT "
1170 "for pid=%u tid=%x\n",
1171 (unsigned) current_event->dwProcessId,
1172 (unsigned) current_event->dwThreadId));
1173 CloseHandle (current_event->u.CreateProcessInfo.hFile);
1175 if (open_process_used)
1177 CloseHandle (windows_process.handle);
1178 open_process_used = false;
1181 windows_process.handle = current_event->u.CreateProcessInfo.hProcess;
1182 windows_process.main_thread_id = current_event->dwThreadId;
1184 /* Add the main thread. */
1185 child_add_thread (current_event->dwProcessId,
1186 windows_process.main_thread_id,
1187 current_event->u.CreateProcessInfo.hThread,
1188 current_event->u.CreateProcessInfo.lpThreadLocalBase);
1189 break;
1191 case EXIT_PROCESS_DEBUG_EVENT:
1192 OUTMSG2 (("gdbserver: kernel event EXIT_PROCESS_DEBUG_EVENT "
1193 "for pid=%u tid=%x\n",
1194 (unsigned) current_event->dwProcessId,
1195 (unsigned) current_event->dwThreadId));
1197 DWORD exit_status = current_event->u.ExitProcess.dwExitCode;
1198 /* If the exit status looks like a fatal exception, but we
1199 don't recognize the exception's code, make the original
1200 exit status value available, to avoid losing information. */
1201 int exit_signal
1202 = WIFSIGNALED (exit_status) ? WTERMSIG (exit_status) : -1;
1203 if (exit_signal == -1)
1204 ourstatus->set_exited (exit_status);
1205 else
1206 ourstatus->set_signalled (gdb_signal_from_host (exit_signal));
1208 child_continue (DBG_CONTINUE, windows_process.desired_stop_thread_id);
1209 break;
1211 case LOAD_DLL_DEBUG_EVENT:
1212 OUTMSG2 (("gdbserver: kernel event LOAD_DLL_DEBUG_EVENT "
1213 "for pid=%u tid=%x\n",
1214 (unsigned) current_event->dwProcessId,
1215 (unsigned) current_event->dwThreadId));
1216 CloseHandle (current_event->u.LoadDll.hFile);
1217 if (! child_initialization_done)
1218 break;
1219 windows_process.dll_loaded_event ();
1221 ourstatus->set_loaded ();
1222 break;
1224 case UNLOAD_DLL_DEBUG_EVENT:
1225 OUTMSG2 (("gdbserver: kernel event UNLOAD_DLL_DEBUG_EVENT "
1226 "for pid=%u tid=%x\n",
1227 (unsigned) current_event->dwProcessId,
1228 (unsigned) current_event->dwThreadId));
1229 if (! child_initialization_done)
1230 break;
1231 windows_process.handle_unload_dll ();
1232 ourstatus->set_loaded ();
1233 break;
1235 case EXCEPTION_DEBUG_EVENT:
1236 OUTMSG2 (("gdbserver: kernel event EXCEPTION_DEBUG_EVENT "
1237 "for pid=%u tid=%x\n",
1238 (unsigned) current_event->dwProcessId,
1239 (unsigned) current_event->dwThreadId));
1240 if (windows_process.handle_exception (ourstatus, debug_threads)
1241 == HANDLE_EXCEPTION_UNHANDLED)
1242 *continue_status = DBG_EXCEPTION_NOT_HANDLED;
1243 break;
1245 case OUTPUT_DEBUG_STRING_EVENT:
1246 /* A message from the kernel (or Cygwin). */
1247 OUTMSG2 (("gdbserver: kernel event OUTPUT_DEBUG_STRING_EVENT "
1248 "for pid=%u tid=%x\n",
1249 (unsigned) current_event->dwProcessId,
1250 (unsigned) current_event->dwThreadId));
1251 windows_process.handle_output_debug_string (nullptr);
1252 break;
1254 default:
1255 OUTMSG2 (("gdbserver: kernel event unknown "
1256 "for pid=%u tid=%x code=%x\n",
1257 (unsigned) current_event->dwProcessId,
1258 (unsigned) current_event->dwThreadId,
1259 (unsigned) current_event->dwDebugEventCode));
1260 break;
1263 ptid = debug_event_ptid (&windows_process.current_event);
1265 if (windows_process.desired_stop_thread_id != -1
1266 && windows_process.desired_stop_thread_id != ptid.lwp ())
1268 /* Pending stop. See the comment by the definition of
1269 "pending_stops" for details on why this is needed. */
1270 OUTMSG2 (("get_windows_debug_event - "
1271 "unexpected stop in 0x%lx (expecting 0x%x)\n",
1272 ptid.lwp (), windows_process.desired_stop_thread_id));
1273 maybe_adjust_pc ();
1274 windows_process.pending_stops.push_back
1275 ({(DWORD) ptid.lwp (), *ourstatus, *current_event});
1276 ourstatus->set_spurious ();
1278 else
1279 switch_to_thread (find_thread_ptid (ptid));
1281 return 1;
1284 /* Wait for the inferior process to change state.
1285 STATUS will be filled in with a response code to send to GDB.
1286 Returns the signal which caused the process to stop. */
1287 ptid_t
1288 win32_process_target::wait (ptid_t ptid, target_waitstatus *ourstatus,
1289 target_wait_flags options)
1291 if (cached_status.kind () != TARGET_WAITKIND_IGNORE)
1293 /* The core always does a wait after creating the inferior, and
1294 do_initial_child_stuff already ran the inferior to the
1295 initial breakpoint (or an exit, if creating the process
1296 fails). Report it now. */
1297 *ourstatus = cached_status;
1298 cached_status.set_ignore ();
1299 return debug_event_ptid (&windows_process.current_event);
1302 while (1)
1304 DWORD continue_status;
1305 if (!get_child_debug_event (&continue_status, ourstatus))
1306 continue;
1308 switch (ourstatus->kind ())
1310 case TARGET_WAITKIND_EXITED:
1311 OUTMSG2 (("Child exited with retcode = %x\n",
1312 ourstatus->exit_status ()));
1313 win32_clear_inferiors ();
1314 return ptid_t (windows_process.current_event.dwProcessId);
1315 case TARGET_WAITKIND_STOPPED:
1316 case TARGET_WAITKIND_SIGNALLED:
1317 case TARGET_WAITKIND_LOADED:
1319 OUTMSG2 (("Child Stopped with signal = %d \n",
1320 ourstatus->sig ()));
1321 maybe_adjust_pc ();
1322 return debug_event_ptid (&windows_process.current_event);
1324 default:
1325 OUTMSG (("Ignoring unknown internal event, %d\n",
1326 ourstatus->kind ()));
1327 /* fall-through */
1328 case TARGET_WAITKIND_SPURIOUS:
1329 /* do nothing, just continue */
1330 child_continue (continue_status,
1331 windows_process.desired_stop_thread_id);
1332 break;
1337 /* Fetch registers from the inferior process.
1338 If REGNO is -1, fetch all registers; otherwise, fetch at least REGNO. */
1339 void
1340 win32_process_target::fetch_registers (regcache *regcache, int regno)
1342 child_fetch_inferior_registers (regcache, regno);
1345 /* Store registers to the inferior process.
1346 If REGNO is -1, store all registers; otherwise, store at least REGNO. */
1347 void
1348 win32_process_target::store_registers (regcache *regcache, int regno)
1350 child_store_inferior_registers (regcache, regno);
1353 /* Read memory from the inferior process. This should generally be
1354 called through read_inferior_memory, which handles breakpoint shadowing.
1355 Read LEN bytes at MEMADDR into a buffer at MYADDR. */
1357 win32_process_target::read_memory (CORE_ADDR memaddr, unsigned char *myaddr,
1358 int len)
1360 return child_xfer_memory (memaddr, (char *) myaddr, len, 0, 0) != len;
1363 /* Write memory to the inferior process. This should generally be
1364 called through write_inferior_memory, which handles breakpoint shadowing.
1365 Write LEN bytes from the buffer at MYADDR to MEMADDR.
1366 Returns 0 on success and errno on failure. */
1368 win32_process_target::write_memory (CORE_ADDR memaddr,
1369 const unsigned char *myaddr, int len)
1371 return child_xfer_memory (memaddr, (char *) myaddr, len, 1, 0) != len;
1374 /* Send an interrupt request to the inferior process. */
1375 void
1376 win32_process_target::request_interrupt ()
1378 if (GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, windows_process.id))
1379 return;
1381 /* GenerateConsoleCtrlEvent can fail if process id being debugged is
1382 not a process group id.
1383 Fallback to XP/Vista 'DebugBreakProcess', which generates a
1384 breakpoint exception in the interior process. */
1386 if (DebugBreakProcess (windows_process.handle))
1387 return;
1389 /* Last resort, suspend all threads manually. */
1390 soft_interrupt_requested = 1;
1393 bool
1394 win32_process_target::supports_hardware_single_step ()
1396 return true;
1399 bool
1400 win32_process_target::supports_qxfer_siginfo ()
1402 return true;
1405 /* Write Windows signal info. */
1408 win32_process_target::qxfer_siginfo (const char *annex,
1409 unsigned char *readbuf,
1410 unsigned const char *writebuf,
1411 CORE_ADDR offset, int len)
1413 if (windows_process.siginfo_er.ExceptionCode == 0)
1414 return -1;
1416 if (readbuf == nullptr)
1417 return -1;
1419 char *buf = (char *) &windows_process.siginfo_er;
1420 size_t bufsize = sizeof (windows_process.siginfo_er);
1422 #ifdef __x86_64__
1423 EXCEPTION_RECORD32 er32;
1424 if (windows_process.wow64_process)
1426 buf = (char *) &er32;
1427 bufsize = sizeof (er32);
1429 er32.ExceptionCode = windows_process.siginfo_er.ExceptionCode;
1430 er32.ExceptionFlags = windows_process.siginfo_er.ExceptionFlags;
1431 er32.ExceptionRecord
1432 = (uintptr_t) windows_process.siginfo_er.ExceptionRecord;
1433 er32.ExceptionAddress
1434 = (uintptr_t) windows_process.siginfo_er.ExceptionAddress;
1435 er32.NumberParameters = windows_process.siginfo_er.NumberParameters;
1436 int i;
1437 for (i = 0; i < EXCEPTION_MAXIMUM_PARAMETERS; i++)
1438 er32.ExceptionInformation[i]
1439 = windows_process.siginfo_er.ExceptionInformation[i];
1441 #endif
1443 if (offset > bufsize)
1444 return -1;
1446 if (offset + len > bufsize)
1447 len = bufsize - offset;
1449 memcpy (readbuf, buf + offset, len);
1451 return len;
1454 bool
1455 win32_process_target::supports_get_tib_address ()
1457 return true;
1460 /* Write Windows OS Thread Information Block address. */
1463 win32_process_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
1465 windows_thread_info *th;
1466 th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
1467 if (th == NULL)
1468 return 0;
1469 if (addr != NULL)
1470 *addr = th->thread_local_base;
1471 return 1;
1474 /* Implementation of the target_ops method "sw_breakpoint_from_kind". */
1476 const gdb_byte *
1477 win32_process_target::sw_breakpoint_from_kind (int kind, int *size)
1479 *size = the_low_target.breakpoint_len;
1480 return the_low_target.breakpoint;
1483 bool
1484 win32_process_target::stopped_by_sw_breakpoint ()
1486 windows_thread_info *th
1487 = windows_process.thread_rec (current_thread_ptid (),
1488 DONT_INVALIDATE_CONTEXT);
1489 return th == nullptr ? false : th->stopped_at_software_breakpoint;
1492 bool
1493 win32_process_target::supports_stopped_by_sw_breakpoint ()
1495 return true;
1498 CORE_ADDR
1499 win32_process_target::read_pc (struct regcache *regcache)
1501 return (*the_low_target.get_pc) (regcache);
1504 void
1505 win32_process_target::write_pc (struct regcache *regcache, CORE_ADDR pc)
1507 return (*the_low_target.set_pc) (regcache, pc);
1510 const char *
1511 win32_process_target::thread_name (ptid_t thread)
1513 windows_thread_info *th
1514 = windows_process.thread_rec (current_thread_ptid (),
1515 DONT_INVALIDATE_CONTEXT);
1516 return th->thread_name ();
1519 /* The win32 target ops object. */
1521 static win32_process_target the_win32_target;
1523 /* Initialize the Win32 backend. */
1524 void
1525 initialize_low (void)
1527 set_target_ops (&the_win32_target);
1528 the_low_target.arch_setup ();
1530 initialize_loadable ();