GDB/testsuite: Fix PARAM_ZUINTEGER reported for PARAM_ZUINTEGER_UNLIMITED
[binutils-gdb.git] / gdbserver / win32-low.cc
1 /* Low level interface to Windows debugging, for gdbserver.
2 Copyright (C) 2006-2022 Free Software Foundation, Inc.
3
4 Contributed by Leo Zayas. Based on "win32-nat.c" from GDB.
5
6 This file is part of GDB.
7
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.
12
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.
17
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/>. */
20
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"
38
39 using namespace windows_nat;
40
41 /* See win32-low.h. */
42 gdbserver_windows_process windows_process;
43
44 #ifndef USE_WIN32API
45 #include <sys/cygwin.h>
46 #endif
47
48 #define OUTMSG(X) do { printf X; fflush (stderr); } while (0)
49
50 #define OUTMSG2(X) \
51 do \
52 { \
53 if (debug_threads) \
54 { \
55 printf X; \
56 fflush (stderr); \
57 } \
58 } while (0)
59
60 #ifndef _T
61 #define _T(x) TEXT (x)
62 #endif
63
64 int using_threads = 1;
65
66 const struct target_desc *win32_tdesc;
67 #ifdef __x86_64__
68 const struct target_desc *wow64_win32_tdesc;
69 #endif
70
71 #define NUM_REGS (the_low_target.num_regs ())
72
73 /* Get the thread ID from the current selected inferior (the current
74 thread). */
75 static ptid_t
76 current_thread_ptid (void)
77 {
78 return current_ptid;
79 }
80
81 /* The current debug event from WaitForDebugEvent. */
82 static ptid_t
83 debug_event_ptid (DEBUG_EVENT *event)
84 {
85 return ptid_t (event->dwProcessId, event->dwThreadId, 0);
86 }
87
88 /* Get the thread context of the thread associated with TH. */
89
90 static void
91 win32_get_thread_context (windows_thread_info *th)
92 {
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);
100 }
101
102 /* Set the thread context of the thread associated with TH. */
103
104 static void
105 win32_set_thread_context (windows_thread_info *th)
106 {
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);
113 }
114
115 /* Set the thread context of the thread associated with TH. */
116
117 static void
118 win32_prepare_to_resume (windows_thread_info *th)
119 {
120 if (the_low_target.prepare_to_resume != NULL)
121 (*the_low_target.prepare_to_resume) (th);
122 }
123
124 /* See win32-low.h. */
125
126 void
127 win32_require_context (windows_thread_info *th)
128 {
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)
137 {
138 th->suspend ();
139 win32_get_thread_context (th);
140 }
141 }
142
143 /* See nat/windows-nat.h. */
144
145 windows_thread_info *
146 gdbserver_windows_process::thread_rec
147 (ptid_t ptid, thread_disposition_type disposition)
148 {
149 thread_info *thread = find_thread_ptid (ptid);
150 if (thread == NULL)
151 return NULL;
152
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;
157 }
158
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)
162 {
163 windows_thread_info *th;
164 ptid_t ptid = ptid_t (pid, tid, 0);
165
166 if ((th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT)))
167 return th;
168
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);
177
178 add_thread (ptid, th);
179
180 if (the_low_target.thread_added != NULL)
181 (*the_low_target.thread_added) (th);
182
183 return th;
184 }
185
186 /* Delete a thread from the list of threads. */
187 static void
188 delete_thread_info (thread_info *thread)
189 {
190 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread);
191
192 remove_thread (thread);
193 delete th;
194 }
195
196 /* Delete a thread from the list of threads. */
197 static void
198 child_delete_thread (DWORD pid, DWORD tid)
199 {
200 /* If the last thread is exiting, just return. */
201 if (all_threads.size () == 1)
202 return;
203
204 thread_info *thread = find_thread_ptid (ptid_t (pid, tid));
205 if (thread == NULL)
206 return;
207
208 delete_thread_info (thread);
209 }
210
211 /* These watchpoint related wrapper functions simply pass on the function call
212 if the low target has registered a corresponding function. */
213
214 bool
215 win32_process_target::supports_z_point_type (char z_type)
216 {
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)));
220 }
221
222 int
223 win32_process_target::insert_point (enum raw_bkpt_type type, CORE_ADDR addr,
224 int size, raw_breakpoint *bp)
225 {
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;
233 }
234
235 int
236 win32_process_target::remove_point (enum raw_bkpt_type type, CORE_ADDR addr,
237 int size, raw_breakpoint *bp)
238 {
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;
246 }
247
248 bool
249 win32_process_target::stopped_by_watchpoint ()
250 {
251 if (the_low_target.stopped_by_watchpoint != NULL)
252 return the_low_target.stopped_by_watchpoint ();
253 else
254 return false;
255 }
256
257 CORE_ADDR
258 win32_process_target::stopped_data_address ()
259 {
260 if (the_low_target.stopped_data_address != NULL)
261 return the_low_target.stopped_data_address ();
262 else
263 return 0;
264 }
265
266
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)
271 {
272 BOOL success;
273 SIZE_T done = 0;
274 DWORD lasterror = 0;
275 uintptr_t addr = (uintptr_t) memaddr;
276
277 if (write)
278 {
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);
284 }
285 else
286 {
287 success = ReadProcessMemory (windows_process.handle, (LPCVOID) addr,
288 (LPVOID) our, len, &done);
289 if (!success)
290 lasterror = GetLastError ();
291 }
292 if (!success && lasterror == ERROR_PARTIAL_COPY && done > 0)
293 return done;
294 else
295 return success ? done : -1;
296 }
297
298 /* Clear out any old thread list and reinitialize it to a pristine
299 state. */
300 static void
301 child_init_thread_list (void)
302 {
303 for_each_thread (delete_thread_info);
304 }
305
306 static void
307 do_initial_child_stuff (HANDLE proch, DWORD pid, int attached)
308 {
309 struct process_info *proc;
310
311 windows_process.last_sig = GDB_SIGNAL_0;
312 windows_process.handle = proch;
313 windows_process.main_thread_id = 0;
314
315 windows_process.soft_interrupt_requested = 0;
316 windows_process.faked_breakpoint = 0;
317 windows_process.open_process_used = true;
318
319 memset (&windows_process.current_event, 0,
320 sizeof (windows_process.current_event));
321
322 #ifdef __x86_64__
323 BOOL wow64;
324 if (!IsWow64Process (proch, &wow64))
325 {
326 DWORD err = GetLastError ();
327 error ("Check if WOW64 process failed (error %d): %s\n",
328 (int) err, strwinerror (err));
329 }
330 windows_process.wow64_process = wow64;
331
332 if (windows_process.wow64_process
333 && (Wow64GetThreadContext == nullptr
334 || Wow64SetThreadContext == nullptr))
335 error ("WOW64 debugging is not supported on this system.\n");
336
337 windows_process.ignore_first_breakpoint
338 = !attached && windows_process.wow64_process;
339 #endif
340
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;
350
351 if (the_low_target.initial_stuff != NULL)
352 (*the_low_target.initial_stuff) ();
353
354 windows_process.cached_status.set_ignore ();
355
356 /* Flush all currently pending debug events (thread and dll list) up
357 to the initial breakpoint. */
358 while (1)
359 {
360 struct target_waitstatus status;
361
362 the_target->wait (minus_one_ptid, &status, 0);
363
364 /* Note win32_wait doesn't return thread events. */
365 if (status.kind () != TARGET_WAITKIND_LOADED)
366 {
367 windows_process.cached_status = status;
368 break;
369 }
370
371 {
372 struct thread_resume resume;
373
374 resume.thread = minus_one_ptid;
375 resume.kind = resume_continue;
376 resume.sig = 0;
377
378 the_target->resume (&resume, 1);
379 }
380 }
381
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.
384
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.
393
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 ();
398
399 windows_process.child_initialization_done = 1;
400 }
401
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)
406 {
407 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread);
408
409 if (thread_id == -1 || thread_id == th->tid)
410 {
411 win32_prepare_to_resume (th);
412
413 if (th->suspended)
414 {
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)
423 {
424 win32_set_thread_context (th);
425 *context_flags = 0;
426 }
427
428 th->resume ();
429 }
430 }
431 }
432
433 static BOOL
434 child_continue (DWORD continue_status, int thread_id)
435 {
436 windows_process.desired_stop_thread_id = thread_id;
437 if (windows_process.matching_pending_stop (debug_threads))
438 return TRUE;
439
440 /* The inferior will only continue after the ContinueDebugEvent
441 call. */
442 for_each_thread ([&] (thread_info *thread)
443 {
444 continue_one_thread (thread, thread_id);
445 });
446 windows_process.faked_breakpoint = 0;
447
448 return continue_last_debug_event (continue_status, debug_threads);
449 }
450
451 /* Fetch register(s) from the current thread context. */
452 static void
453 child_fetch_inferior_registers (struct regcache *regcache, int r)
454 {
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);
464 }
465
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)
470 {
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);
480 }
481
482 static BOOL
483 create_process (const char *program, char *args,
484 DWORD flags, PROCESS_INFORMATION *pi)
485 {
486 const std::string &inferior_cwd = get_inferior_cwd ();
487 BOOL ret;
488 size_t argslen, proglen;
489
490 proglen = strlen (program) + 1;
491 argslen = strlen (args) + proglen;
492
493 STARTUPINFOA si = { sizeof (STARTUPINFOA) };
494 char *program_and_args = (char *) alloca (argslen + 1);
495
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 */
510
511 return ret;
512 }
513
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. */
519 int
520 win32_process_target::create_inferior (const char *program,
521 const std::vector<char *> &program_args)
522 {
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 ();
534
535 /* win32_wait needs to know we're not attaching. */
536 windows_process.attaching = 0;
537
538 if (!program)
539 error ("No executable specified, specify executable to debug.\n");
540
541 flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS;
542
543 #ifndef USE_WIN32API
544 orig_path = NULL;
545 path_ptr = getenv ("PATH");
546 if (path_ptr)
547 {
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);
554 }
555 cygwin_conv_path (CCP_POSIX_TO_WIN_A, program, real_path, PATH_MAX);
556 program = real_path;
557 #endif
558
559 OUTMSG2 (("Command line is \"%s %s\"\n", program, args));
560
561 #ifdef CREATE_NEW_PROCESS_GROUP
562 flags |= CREATE_NEW_PROCESS_GROUP;
563 #endif
564
565 ret = create_process (program, args, flags, &pi);
566 err = GetLastError ();
567 if (!ret && err == ERROR_FILE_NOT_FOUND)
568 {
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 ();
573 }
574
575 #ifndef USE_WIN32API
576 if (orig_path)
577 setenv ("PATH", orig_path, 1);
578 #endif
579
580 if (!ret)
581 {
582 error ("Error creating process \"%s %s\", (error %d): %s\n",
583 program, args, (int) err, strwinerror (err));
584 }
585 else
586 {
587 OUTMSG2 (("Process created: %s %s\n", program, (char *) args));
588 }
589
590 CloseHandle (pi.hThread);
591
592 do_initial_child_stuff (pi.hProcess, pi.dwProcessId, 0);
593
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);
597
598 /* Necessary for handle_v_kill. */
599 signal_pid = pi.dwProcessId;
600
601 return pi.dwProcessId;
602 }
603
604 /* Attach to a running process.
605 PID is the process ID to attach to, specified by the user
606 or a higher layer. */
607 int
608 win32_process_target::attach (unsigned long pid)
609 {
610 HANDLE h;
611 DWORD err;
612
613 h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
614 if (h != NULL)
615 {
616 if (DebugActiveProcess (pid))
617 {
618 DebugSetProcessKillOnExit (FALSE);
619
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;
624 }
625
626 CloseHandle (h);
627 }
628
629 err = GetLastError ();
630 error ("Attach to process failed (error %d): %s\n",
631 (int) err, strwinerror (err));
632 }
633
634 /* See nat/windows-nat.h. */
635
636 int
637 gdbserver_windows_process::handle_output_debug_string
638 (struct target_waitstatus *ourstatus)
639 {
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;
644
645 if (nbytes == 0)
646 return 0;
647
648 if (nbytes > READ_BUFFER_LEN)
649 nbytes = READ_BUFFER_LEN;
650
651 addr = (CORE_ADDR) (size_t) current_event.u.DebugString.lpDebugStringData;
652
653 if (current_event.u.DebugString.fUnicode)
654 {
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));
661 }
662 else
663 {
664 if (read_inferior_memory (addr, (unsigned char *) s, nbytes) != 0)
665 return 0;
666 }
667
668 if (!startswith (s, "cYg"))
669 {
670 if (!server_waiting)
671 {
672 OUTMSG2(("%s", s));
673 return 0;
674 }
675
676 monitor_output (s);
677 }
678 #undef READ_BUFFER_LEN
679
680 return 0;
681 }
682
683 static void
684 win32_clear_inferiors (void)
685 {
686 if (windows_process.open_process_used)
687 {
688 CloseHandle (windows_process.handle);
689 windows_process.open_process_used = false;
690 }
691
692 for_each_thread (delete_thread_info);
693 windows_process.siginfo_er.ExceptionCode = 0;
694 clear_inferiors ();
695 }
696
697 /* Implementation of target_ops::kill. */
698
699 int
700 win32_process_target::kill (process_info *process)
701 {
702 TerminateProcess (windows_process.handle, 0);
703 for (;;)
704 {
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);
715 }
716
717 win32_clear_inferiors ();
718
719 remove_process (process);
720 return 0;
721 }
722
723 /* Implementation of target_ops::detach. */
724
725 int
726 win32_process_target::detach (process_info *process)
727 {
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);
733
734 if (!DebugActiveProcessStop (process->pid))
735 return -1;
736
737 DebugSetProcessKillOnExit (FALSE);
738 remove_process (process);
739
740 win32_clear_inferiors ();
741 return 0;
742 }
743
744 void
745 win32_process_target::mourn (struct process_info *process)
746 {
747 remove_process (process);
748 }
749
750 /* Implementation of target_ops::join. */
751
752 void
753 win32_process_target::join (int pid)
754 {
755 HANDLE h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
756 if (h != NULL)
757 {
758 WaitForSingleObject (h, INFINITE);
759 CloseHandle (h);
760 }
761 }
762
763 /* Return true iff the thread with thread ID TID is alive. */
764 bool
765 win32_process_target::thread_alive (ptid_t ptid)
766 {
767 /* Our thread list is reliable; don't bother to poll target
768 threads. */
769 return find_thread_ptid (ptid) != NULL;
770 }
771
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)
776 {
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;
783
784 /* This handles the very limited set of resume packets that GDB can
785 currently produce. */
786
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;
795
796 if (resume_info[0].thread != minus_one_ptid)
797 {
798 sig = gdb_signal_from_host (resume_info[0].sig);
799 step = resume_info[0].kind == resume_step;
800 }
801 else
802 {
803 sig = GDB_SIGNAL_0;
804 step = 0;
805 }
806
807 if (sig != GDB_SIGNAL_0)
808 {
809 if (windows_process.current_event.dwDebugEventCode
810 != EXCEPTION_DEBUG_EVENT)
811 {
812 OUTMSG (("Cannot continue with signal %s here.\n",
813 gdb_signal_to_string (sig)));
814 }
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)));
820 }
821
822 windows_process.last_sig = GDB_SIGNAL_0;
823
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)
828 {
829 win32_prepare_to_resume (th);
830
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)
839 {
840 /* Move register values from the inferior into the thread
841 context structure. */
842 regcache_invalidate ();
843
844 if (step)
845 {
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");
851 }
852
853 win32_set_thread_context (th);
854 *context_flags = 0;
855 }
856 }
857
858 /* Allow continuing with the same signal that interrupted us.
859 Otherwise complain. */
860
861 child_continue (continue_status, tid);
862 }
863
864 /* See nat/windows-nat.h. */
865
866 void
867 gdbserver_windows_process::handle_load_dll (const char *name, LPVOID base)
868 {
869 CORE_ADDR load_addr = (CORE_ADDR) (uintptr_t) base;
870
871 char buf[MAX_PATH + 1];
872 char buf2[MAX_PATH + 1];
873
874 WIN32_FIND_DATAA w32_fd;
875 HANDLE h = FindFirstFileA (name, &w32_fd);
876
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;
881
882 if (h == INVALID_HANDLE_VALUE)
883 strcpy (buf, name);
884 else
885 {
886 FindClose (h);
887 strcpy (buf, name);
888 {
889 char cwd[MAX_PATH + 1];
890 char *p;
891 if (GetCurrentDirectoryA (MAX_PATH + 1, cwd))
892 {
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);
899 }
900 }
901 }
902
903 if (strcasecmp (buf, "ntdll.dll") == 0)
904 {
905 GetSystemDirectoryA (buf, sizeof (buf));
906 strcat (buf, "\\ntdll.dll");
907 }
908
909 #ifdef __CYGWIN__
910 cygwin_conv_path (CCP_WIN_A_TO_POSIX, buf, buf2, sizeof (buf2));
911 #else
912 strcpy (buf2, buf);
913 #endif
914
915 loaded_dll (buf2, load_addr);
916 }
917
918 /* See nat/windows-nat.h. */
919
920 void
921 gdbserver_windows_process::handle_unload_dll ()
922 {
923 CORE_ADDR load_addr =
924 (CORE_ADDR) (uintptr_t) current_event.u.UnloadDll.lpBaseOfDll;
925
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);
931 }
932
933 static void
934 suspend_one_thread (thread_info *thread)
935 {
936 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread);
937
938 th->suspend ();
939 }
940
941 static void
942 fake_breakpoint_event (void)
943 {
944 OUTMSG2(("fake_breakpoint_event\n"));
945
946 windows_process.faked_breakpoint = 1;
947
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;
954
955 for_each_thread (suspend_one_thread);
956 }
957
958 /* See nat/windows-nat.h. */
959
960 bool
961 gdbserver_windows_process::handle_access_violation
962 (const EXCEPTION_RECORD *rec)
963 {
964 return false;
965 }
966
967 /* A helper function that will, if needed, set
968 'stopped_at_software_breakpoint' on the thread and adjust the
969 PC. */
970
971 static void
972 maybe_adjust_pc ()
973 {
974 struct regcache *regcache = get_thread_regcache (current_thread, 1);
975 child_fetch_inferior_registers (regcache, -1);
976
977 windows_thread_info *th
978 = windows_process.thread_rec (current_thread_ptid (),
979 DONT_INVALIDATE_CONTEXT);
980 th->stopped_at_software_breakpoint = false;
981
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)
988 {
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);
993 }
994 }
995
996 /* Get the next event from the child. */
997
998 static int
999 get_child_debug_event (DWORD *continue_status,
1000 struct target_waitstatus *ourstatus)
1001 {
1002 ptid_t ptid;
1003
1004 windows_process.last_sig = GDB_SIGNAL_0;
1005 ourstatus->set_spurious ();
1006 *continue_status = DBG_CONTINUE;
1007
1008 /* Check if GDB sent us an interrupt request. */
1009 check_remote_input_interrupt_request ();
1010
1011 DEBUG_EVENT *current_event = &windows_process.current_event;
1012
1013 if (windows_process.soft_interrupt_requested)
1014 {
1015 windows_process.soft_interrupt_requested = 0;
1016 fake_breakpoint_event ();
1017 goto gotevent;
1018 }
1019
1020 windows_process.attaching = 0;
1021 {
1022 gdb::optional<pending_stop> stop
1023 = windows_process.fetch_pending_stop (debug_threads);
1024 if (stop.has_value ())
1025 {
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;
1031 }
1032
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))
1037 {
1038 DWORD e = GetLastError();
1039
1040 if (e == ERROR_PIPE_NOT_CONNECTED)
1041 {
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;
1048 }
1049
1050 return 0;
1051 }
1052 }
1053
1054 gotevent:
1055
1056 switch (current_event->dwDebugEventCode)
1057 {
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));
1063
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;
1070
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);
1078
1079 switch_to_thread (get_first_thread ());
1080 return 1;
1081
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);
1088
1089 if (windows_process.open_process_used)
1090 {
1091 CloseHandle (windows_process.handle);
1092 windows_process.open_process_used = false;
1093 }
1094
1095 windows_process.handle = current_event->u.CreateProcessInfo.hProcess;
1096 windows_process.main_thread_id = current_event->dwThreadId;
1097
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;
1104
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));
1110 {
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));
1121 }
1122 child_continue (DBG_CONTINUE, windows_process.desired_stop_thread_id);
1123 break;
1124
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 ();
1134
1135 ourstatus->set_loaded ();
1136 break;
1137
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;
1148
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;
1158
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;
1167
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;
1175 }
1176
1177 ptid = debug_event_ptid (&windows_process.current_event);
1178
1179 if (windows_process.desired_stop_thread_id != -1
1180 && windows_process.desired_stop_thread_id != ptid.lwp ())
1181 {
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 ();
1191 }
1192 else
1193 switch_to_thread (find_thread_ptid (ptid));
1194
1195 return 1;
1196 }
1197
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)
1204 {
1205 if (windows_process.cached_status.kind () != TARGET_WAITKIND_IGNORE)
1206 {
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);
1214 }
1215
1216 while (1)
1217 {
1218 DWORD continue_status;
1219 if (!get_child_debug_event (&continue_status, ourstatus))
1220 continue;
1221
1222 switch (ourstatus->kind ())
1223 {
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:
1232 {
1233 OUTMSG2 (("Child Stopped with signal = %d \n",
1234 ourstatus->sig ()));
1235 maybe_adjust_pc ();
1236 return debug_event_ptid (&windows_process.current_event);
1237 }
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;
1247 }
1248 }
1249 }
1250
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)
1255 {
1256 child_fetch_inferior_registers (regcache, regno);
1257 }
1258
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)
1263 {
1264 child_store_inferior_registers (regcache, regno);
1265 }
1266
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. */
1270 int
1271 win32_process_target::read_memory (CORE_ADDR memaddr, unsigned char *myaddr,
1272 int len)
1273 {
1274 return child_xfer_memory (memaddr, (char *) myaddr, len, 0, 0) != len;
1275 }
1276
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. */
1281 int
1282 win32_process_target::write_memory (CORE_ADDR memaddr,
1283 const unsigned char *myaddr, int len)
1284 {
1285 return child_xfer_memory (memaddr, (char *) myaddr, len, 1, 0) != len;
1286 }
1287
1288 /* Send an interrupt request to the inferior process. */
1289 void
1290 win32_process_target::request_interrupt ()
1291 {
1292 if (GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, signal_pid))
1293 return;
1294
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. */
1299
1300 if (DebugBreakProcess (windows_process.handle))
1301 return;
1302
1303 /* Last resort, suspend all threads manually. */
1304 windows_process.soft_interrupt_requested = 1;
1305 }
1306
1307 bool
1308 win32_process_target::supports_hardware_single_step ()
1309 {
1310 return true;
1311 }
1312
1313 bool
1314 win32_process_target::supports_qxfer_siginfo ()
1315 {
1316 return true;
1317 }
1318
1319 /* Write Windows signal info. */
1320
1321 int
1322 win32_process_target::qxfer_siginfo (const char *annex,
1323 unsigned char *readbuf,
1324 unsigned const char *writebuf,
1325 CORE_ADDR offset, int len)
1326 {
1327 if (windows_process.siginfo_er.ExceptionCode == 0)
1328 return -1;
1329
1330 if (readbuf == nullptr)
1331 return -1;
1332
1333 char *buf = (char *) &windows_process.siginfo_er;
1334 size_t bufsize = sizeof (windows_process.siginfo_er);
1335
1336 #ifdef __x86_64__
1337 EXCEPTION_RECORD32 er32;
1338 if (windows_process.wow64_process)
1339 {
1340 buf = (char *) &er32;
1341 bufsize = sizeof (er32);
1342
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];
1354 }
1355 #endif
1356
1357 if (offset > bufsize)
1358 return -1;
1359
1360 if (offset + len > bufsize)
1361 len = bufsize - offset;
1362
1363 memcpy (readbuf, buf + offset, len);
1364
1365 return len;
1366 }
1367
1368 bool
1369 win32_process_target::supports_get_tib_address ()
1370 {
1371 return true;
1372 }
1373
1374 /* Write Windows OS Thread Information Block address. */
1375
1376 int
1377 win32_process_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
1378 {
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;
1386 }
1387
1388 /* Implementation of the target_ops method "sw_breakpoint_from_kind". */
1389
1390 const gdb_byte *
1391 win32_process_target::sw_breakpoint_from_kind (int kind, int *size)
1392 {
1393 *size = the_low_target.breakpoint_len;
1394 return the_low_target.breakpoint;
1395 }
1396
1397 bool
1398 win32_process_target::stopped_by_sw_breakpoint ()
1399 {
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;
1404 }
1405
1406 bool
1407 win32_process_target::supports_stopped_by_sw_breakpoint ()
1408 {
1409 return true;
1410 }
1411
1412 CORE_ADDR
1413 win32_process_target::read_pc (struct regcache *regcache)
1414 {
1415 return (*the_low_target.get_pc) (regcache);
1416 }
1417
1418 void
1419 win32_process_target::write_pc (struct regcache *regcache, CORE_ADDR pc)
1420 {
1421 return (*the_low_target.set_pc) (regcache, pc);
1422 }
1423
1424 const char *
1425 win32_process_target::thread_name (ptid_t thread)
1426 {
1427 windows_thread_info *th
1428 = windows_process.thread_rec (current_thread_ptid (),
1429 DONT_INVALIDATE_CONTEXT);
1430 return th->thread_name ();
1431 }
1432
1433 const char *
1434 win32_process_target::pid_to_exec_file (int pid)
1435 {
1436 return windows_process.pid_to_exec_file (pid);
1437 }
1438
1439 /* The win32 target ops object. */
1440
1441 static win32_process_target the_win32_target;
1442
1443 /* Initialize the Win32 backend. */
1444 void
1445 initialize_low (void)
1446 {
1447 set_target_ops (&the_win32_target);
1448 the_low_target.arch_setup ();
1449
1450 initialize_loadable ();
1451 }