1 /* Low level interface to Windows debugging, for gdbserver. 2 Copyright (C) 2006-2024 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 "regcache.h" 22 #include "gdbsupport/fileio.h" 23 #include "mem-break.h" 24 #include "win32-low.h" 25 #include "gdbthread.h" 26 #include "dll.h" 27 #include "hostio.h" 28 #include <windows.h> 29 #include <winnt.h> 30 #include <imagehlp.h> 31 #include <tlhelp32.h> 32 #include <psapi.h> 33 #include <process.h> 34 #include "gdbsupport/gdb_tilde_expand.h" 35 #include "gdbsupport/common-inferior.h" 36 #include "gdbsupport/gdb_wait.h" 37 38 using namespace windows_nat; 39 40 /* See win32-low.h. */ 41 gdbserver_windows_process windows_process; 42 43 #ifndef USE_WIN32API 44 #include <sys/cygwin.h> 45 #endif 46 47 #define OUTMSG(X) do { printf X; fflush (stderr); } while (0) 48 49 #define OUTMSG2(X) \ 50 do \ 51 { \ 52 if (debug_threads) \ 53 { \ 54 printf X; \ 55 fflush (stderr); \ 56 } \ 57 } while (0) 58 59 #ifndef _T 60 #define _T(x) TEXT (x) 61 #endif 62 63 int using_threads = 1; 64 65 const struct target_desc *win32_tdesc; 66 #ifdef __x86_64__ 67 const struct target_desc *wow64_win32_tdesc; 68 #endif 69 70 #define NUM_REGS (the_low_target.num_regs ()) 71 72 /* Get the thread ID from the current selected inferior (the current 73 thread). */ 74 static ptid_t 75 current_thread_ptid (void) 76 { 77 return current_ptid; 78 } 79 80 /* The current debug event from WaitForDebugEvent. */ 81 static ptid_t 82 debug_event_ptid (DEBUG_EVENT *event) 83 { 84 return ptid_t (event->dwProcessId, event->dwThreadId, 0); 85 } 86 87 /* Get the thread context of the thread associated with TH. */ 88 89 static void 90 win32_get_thread_context (windows_thread_info *th) 91 { 92 #ifdef __x86_64__ 93 if (windows_process.wow64_process) 94 memset (&th->wow64_context, 0, sizeof (WOW64_CONTEXT)); 95 else 96 #endif 97 memset (&th->context, 0, sizeof (CONTEXT)); 98 (*the_low_target.get_thread_context) (th); 99 } 100 101 /* Set the thread context of the thread associated with TH. */ 102 103 static void 104 win32_set_thread_context (windows_thread_info *th) 105 { 106 #ifdef __x86_64__ 107 if (windows_process.wow64_process) 108 Wow64SetThreadContext (th->h, &th->wow64_context); 109 else 110 #endif 111 SetThreadContext (th->h, &th->context); 112 } 113 114 /* Set the thread context of the thread associated with TH. */ 115 116 static void 117 win32_prepare_to_resume (windows_thread_info *th) 118 { 119 if (the_low_target.prepare_to_resume != NULL) 120 (*the_low_target.prepare_to_resume) (th); 121 } 122 123 /* See win32-low.h. */ 124 125 void 126 win32_require_context (windows_thread_info *th) 127 { 128 DWORD context_flags; 129 #ifdef __x86_64__ 130 if (windows_process.wow64_process) 131 context_flags = th->wow64_context.ContextFlags; 132 else 133 #endif 134 context_flags = th->context.ContextFlags; 135 if (context_flags == 0) 136 { 137 th->suspend (); 138 win32_get_thread_context (th); 139 } 140 } 141 142 /* See nat/windows-nat.h. */ 143 144 windows_thread_info * 145 gdbserver_windows_process::thread_rec 146 (ptid_t ptid, thread_disposition_type disposition) 147 { 148 thread_info *thread = find_thread_ptid (ptid); 149 if (thread == NULL) 150 return NULL; 151 152 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread); 153 if (disposition != DONT_INVALIDATE_CONTEXT) 154 win32_require_context (th); 155 return th; 156 } 157 158 /* Add a thread to the thread list. */ 159 static windows_thread_info * 160 child_add_thread (DWORD pid, DWORD tid, HANDLE h, void *tlb) 161 { 162 windows_thread_info *th; 163 ptid_t ptid = ptid_t (pid, tid, 0); 164 165 if ((th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT))) 166 return th; 167 168 CORE_ADDR base = (CORE_ADDR) (uintptr_t) tlb; 169 #ifdef __x86_64__ 170 /* For WOW64 processes, this is actually the pointer to the 64bit TIB, 171 and the 32bit TIB is exactly 2 pages after it. */ 172 if (windows_process.wow64_process) 173 base += 2 * 4096; /* page size = 4096 */ 174 #endif 175 th = new windows_thread_info (tid, h, base); 176 177 add_thread (ptid, th); 178 179 if (the_low_target.thread_added != NULL) 180 (*the_low_target.thread_added) (th); 181 182 return th; 183 } 184 185 /* Delete a thread from the list of threads. */ 186 static void 187 delete_thread_info (thread_info *thread) 188 { 189 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread); 190 191 remove_thread (thread); 192 delete th; 193 } 194 195 /* Delete a thread from the list of threads. */ 196 static void 197 child_delete_thread (DWORD pid, DWORD tid) 198 { 199 /* If the last thread is exiting, just return. */ 200 if (all_threads.size () == 1) 201 return; 202 203 thread_info *thread = find_thread_ptid (ptid_t (pid, tid)); 204 if (thread == NULL) 205 return; 206 207 delete_thread_info (thread); 208 } 209 210 /* These watchpoint related wrapper functions simply pass on the function call 211 if the low target has registered a corresponding function. */ 212 213 bool 214 win32_process_target::supports_z_point_type (char z_type) 215 { 216 return (z_type == Z_PACKET_SW_BP 217 || (the_low_target.supports_z_point_type != NULL 218 && the_low_target.supports_z_point_type (z_type))); 219 } 220 221 int 222 win32_process_target::insert_point (enum raw_bkpt_type type, CORE_ADDR addr, 223 int size, raw_breakpoint *bp) 224 { 225 if (type == raw_bkpt_type_sw) 226 return insert_memory_breakpoint (bp); 227 else if (the_low_target.insert_point != NULL) 228 return the_low_target.insert_point (type, addr, size, bp); 229 else 230 /* Unsupported (see target.h). */ 231 return 1; 232 } 233 234 int 235 win32_process_target::remove_point (enum raw_bkpt_type type, CORE_ADDR addr, 236 int size, raw_breakpoint *bp) 237 { 238 if (type == raw_bkpt_type_sw) 239 return remove_memory_breakpoint (bp); 240 else if (the_low_target.remove_point != NULL) 241 return the_low_target.remove_point (type, addr, size, bp); 242 else 243 /* Unsupported (see target.h). */ 244 return 1; 245 } 246 247 bool 248 win32_process_target::stopped_by_watchpoint () 249 { 250 if (the_low_target.stopped_by_watchpoint != NULL) 251 return the_low_target.stopped_by_watchpoint (); 252 else 253 return false; 254 } 255 256 CORE_ADDR 257 win32_process_target::stopped_data_address () 258 { 259 if (the_low_target.stopped_data_address != NULL) 260 return the_low_target.stopped_data_address (); 261 else 262 return 0; 263 } 264 265 266 /* Transfer memory from/to the debugged process. */ 267 static int 268 child_xfer_memory (CORE_ADDR memaddr, char *our, int len, 269 int write, process_stratum_target *target) 270 { 271 BOOL success; 272 SIZE_T done = 0; 273 DWORD lasterror = 0; 274 uintptr_t addr = (uintptr_t) memaddr; 275 276 if (write) 277 { 278 success = WriteProcessMemory (windows_process.handle, (LPVOID) addr, 279 (LPCVOID) our, len, &done); 280 if (!success) 281 lasterror = GetLastError (); 282 FlushInstructionCache (windows_process.handle, (LPCVOID) addr, len); 283 } 284 else 285 { 286 success = ReadProcessMemory (windows_process.handle, (LPCVOID) addr, 287 (LPVOID) our, len, &done); 288 if (!success) 289 lasterror = GetLastError (); 290 } 291 if (!success && lasterror == ERROR_PARTIAL_COPY && done > 0) 292 return done; 293 else 294 return success ? done : -1; 295 } 296 297 /* Clear out any old thread list and reinitialize it to a pristine 298 state. */ 299 static void 300 child_init_thread_list (void) 301 { 302 for_each_thread (delete_thread_info); 303 } 304 305 static void 306 do_initial_child_stuff (HANDLE proch, DWORD pid, int attached) 307 { 308 struct process_info *proc; 309 310 windows_process.last_sig = GDB_SIGNAL_0; 311 windows_process.handle = proch; 312 windows_process.main_thread_id = 0; 313 314 windows_process.soft_interrupt_requested = 0; 315 windows_process.faked_breakpoint = 0; 316 windows_process.open_process_used = true; 317 318 memset (&windows_process.current_event, 0, 319 sizeof (windows_process.current_event)); 320 321 #ifdef __x86_64__ 322 BOOL wow64; 323 if (!IsWow64Process (proch, &wow64)) 324 { 325 DWORD err = GetLastError (); 326 throw_winerror_with_name ("Check if WOW64 process failed", err); 327 } 328 windows_process.wow64_process = wow64; 329 330 if (windows_process.wow64_process 331 && (Wow64GetThreadContext == nullptr 332 || Wow64SetThreadContext == nullptr)) 333 error ("WOW64 debugging is not supported on this system.\n"); 334 335 windows_process.ignore_first_breakpoint 336 = !attached && windows_process.wow64_process; 337 #endif 338 339 proc = add_process (pid, attached); 340 #ifdef __x86_64__ 341 if (windows_process.wow64_process) 342 proc->tdesc = wow64_win32_tdesc; 343 else 344 #endif 345 proc->tdesc = win32_tdesc; 346 child_init_thread_list (); 347 windows_process.child_initialization_done = 0; 348 349 if (the_low_target.initial_stuff != NULL) 350 (*the_low_target.initial_stuff) (); 351 352 windows_process.cached_status.set_ignore (); 353 354 /* Flush all currently pending debug events (thread and dll list) up 355 to the initial breakpoint. */ 356 while (1) 357 { 358 struct target_waitstatus status; 359 360 the_target->wait (minus_one_ptid, &status, 0); 361 362 /* Note win32_wait doesn't return thread events. */ 363 if (status.kind () != TARGET_WAITKIND_LOADED) 364 { 365 windows_process.cached_status = status; 366 break; 367 } 368 369 { 370 struct thread_resume resume; 371 372 resume.thread = minus_one_ptid; 373 resume.kind = resume_continue; 374 resume.sig = 0; 375 376 the_target->resume (&resume, 1); 377 } 378 } 379 380 /* Now that the inferior has been started and all DLLs have been mapped, 381 we can iterate over all DLLs and load them in. 382 383 We avoid doing it any earlier because, on certain versions of Windows, 384 LOAD_DLL_DEBUG_EVENTs are sometimes not complete. In particular, 385 we have seen on Windows 8.1 that the ntdll.dll load event does not 386 include the DLL name, preventing us from creating an associated SO. 387 A possible explanation is that ntdll.dll might be mapped before 388 the SO info gets created by the Windows system -- ntdll.dll is 389 the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs 390 do not seem to suffer from that problem. 391 392 Rather than try to work around this sort of issue, it is much 393 simpler to just ignore DLL load/unload events during the startup 394 phase, and then process them all in one batch now. */ 395 windows_process.add_all_dlls (); 396 397 windows_process.child_initialization_done = 1; 398 } 399 400 /* Resume all artificially suspended threads if we are continuing 401 execution. */ 402 static void 403 continue_one_thread (thread_info *thread, int thread_id) 404 { 405 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread); 406 407 if (thread_id == -1 || thread_id == th->tid) 408 { 409 win32_prepare_to_resume (th); 410 411 if (th->suspended) 412 { 413 DWORD *context_flags; 414 #ifdef __x86_64__ 415 if (windows_process.wow64_process) 416 context_flags = &th->wow64_context.ContextFlags; 417 else 418 #endif 419 context_flags = &th->context.ContextFlags; 420 if (*context_flags) 421 { 422 win32_set_thread_context (th); 423 *context_flags = 0; 424 } 425 426 th->resume (); 427 } 428 } 429 } 430 431 static BOOL 432 child_continue (DWORD continue_status, int thread_id) 433 { 434 windows_process.desired_stop_thread_id = thread_id; 435 if (windows_process.matching_pending_stop (debug_threads)) 436 return TRUE; 437 438 /* The inferior will only continue after the ContinueDebugEvent 439 call. */ 440 for_each_thread ([&] (thread_info *thread) 441 { 442 continue_one_thread (thread, thread_id); 443 }); 444 windows_process.faked_breakpoint = 0; 445 446 return continue_last_debug_event (continue_status, debug_threads); 447 } 448 449 /* Fetch register(s) from the current thread context. */ 450 static void 451 child_fetch_inferior_registers (struct regcache *regcache, int r) 452 { 453 int regno; 454 windows_thread_info *th 455 = windows_process.thread_rec (current_thread_ptid (), 456 INVALIDATE_CONTEXT); 457 if (r == -1 || r > NUM_REGS) 458 child_fetch_inferior_registers (regcache, NUM_REGS); 459 else 460 for (regno = 0; regno < r; regno++) 461 (*the_low_target.fetch_inferior_register) (regcache, th, regno); 462 } 463 464 /* Store a new register value into the current thread context. We don't 465 change the program's context until later, when we resume it. */ 466 static void 467 child_store_inferior_registers (struct regcache *regcache, int r) 468 { 469 int regno; 470 windows_thread_info *th 471 = windows_process.thread_rec (current_thread_ptid (), 472 INVALIDATE_CONTEXT); 473 if (r == -1 || r == 0 || r > NUM_REGS) 474 child_store_inferior_registers (regcache, NUM_REGS); 475 else 476 for (regno = 0; regno < r; regno++) 477 (*the_low_target.store_inferior_register) (regcache, th, regno); 478 } 479 480 static BOOL 481 create_process (const char *program, char *args, 482 DWORD flags, PROCESS_INFORMATION *pi) 483 { 484 const std::string &inferior_cwd = get_inferior_cwd (); 485 BOOL ret; 486 size_t argslen, proglen; 487 488 proglen = strlen (program) + 1; 489 argslen = strlen (args) + proglen; 490 491 STARTUPINFOA si = { sizeof (STARTUPINFOA) }; 492 char *program_and_args = (char *) alloca (argslen + 1); 493 494 strcpy (program_and_args, program); 495 strcat (program_and_args, " "); 496 strcat (program_and_args, args); 497 ret = create_process (program, /* image name */ 498 program_and_args, /* command line */ 499 flags, /* start flags */ 500 NULL, /* environment */ 501 /* current directory */ 502 (inferior_cwd.empty () 503 ? NULL 504 : gdb_tilde_expand (inferior_cwd.c_str ()).c_str()), 505 get_client_state ().disable_randomization, 506 &si, /* start info */ 507 pi); /* proc info */ 508 509 return ret; 510 } 511 512 /* Start a new process. 513 PROGRAM is the program name. 514 PROGRAM_ARGS is the vector containing the inferior's args. 515 Returns the new PID on success, -1 on failure. Registers the new 516 process with the process list. */ 517 int 518 win32_process_target::create_inferior (const char *program, 519 const std::vector<char *> &program_args) 520 { 521 client_state &cs = get_client_state (); 522 #ifndef USE_WIN32API 523 char real_path[PATH_MAX]; 524 char *orig_path, *new_path, *path_ptr; 525 #endif 526 BOOL ret; 527 DWORD flags; 528 PROCESS_INFORMATION pi; 529 DWORD err; 530 std::string str_program_args = construct_inferior_arguments (program_args); 531 char *args = (char *) str_program_args.c_str (); 532 533 /* win32_wait needs to know we're not attaching. */ 534 windows_process.attaching = 0; 535 536 if (!program) 537 error ("No executable specified, specify executable to debug.\n"); 538 539 flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS; 540 541 #ifndef USE_WIN32API 542 orig_path = NULL; 543 path_ptr = getenv ("PATH"); 544 if (path_ptr) 545 { 546 int size = cygwin_conv_path_list (CCP_POSIX_TO_WIN_A, path_ptr, NULL, 0); 547 orig_path = (char *) alloca (strlen (path_ptr) + 1); 548 new_path = (char *) alloca (size); 549 strcpy (orig_path, path_ptr); 550 cygwin_conv_path_list (CCP_POSIX_TO_WIN_A, path_ptr, new_path, size); 551 setenv ("PATH", new_path, 1); 552 } 553 cygwin_conv_path (CCP_POSIX_TO_WIN_A, program, real_path, PATH_MAX); 554 program = real_path; 555 #endif 556 557 OUTMSG2 (("Command line is \"%s %s\"\n", program, args)); 558 559 #ifdef CREATE_NEW_PROCESS_GROUP 560 flags |= CREATE_NEW_PROCESS_GROUP; 561 #endif 562 563 ret = create_process (program, args, flags, &pi); 564 err = GetLastError (); 565 if (!ret && err == ERROR_FILE_NOT_FOUND) 566 { 567 char *exename = (char *) alloca (strlen (program) + 5); 568 strcat (strcpy (exename, program), ".exe"); 569 ret = create_process (exename, args, flags, &pi); 570 err = GetLastError (); 571 } 572 573 #ifndef USE_WIN32API 574 if (orig_path) 575 setenv ("PATH", orig_path, 1); 576 #endif 577 578 if (!ret) 579 { 580 std::string msg = string_printf (_("Error creating process \"%s %s\""), 581 program, args); 582 throw_winerror_with_name (msg.c_str (), err); 583 } 584 else 585 { 586 OUTMSG2 (("Process created: %s %s\n", program, (char *) args)); 587 } 588 589 CloseHandle (pi.hThread); 590 591 do_initial_child_stuff (pi.hProcess, pi.dwProcessId, 0); 592 593 /* Wait till we are at 1st instruction in program, return new pid 594 (assuming success). */ 595 cs.last_ptid = wait (ptid_t (pi.dwProcessId), &cs.last_status, 0); 596 597 /* Necessary for handle_v_kill. */ 598 signal_pid = pi.dwProcessId; 599 600 return pi.dwProcessId; 601 } 602 603 /* Attach to a running process. 604 PID is the process ID to attach to, specified by the user 605 or a higher layer. */ 606 int 607 win32_process_target::attach (unsigned long pid) 608 { 609 HANDLE h; 610 DWORD err; 611 612 h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid); 613 if (h != NULL) 614 { 615 if (DebugActiveProcess (pid)) 616 { 617 DebugSetProcessKillOnExit (FALSE); 618 619 /* win32_wait needs to know we're attaching. */ 620 windows_process.attaching = 1; 621 do_initial_child_stuff (h, pid, 1); 622 return 0; 623 } 624 625 CloseHandle (h); 626 } 627 628 err = GetLastError (); 629 throw_winerror_with_name ("Attach to process failed", err); 630 } 631 632 /* See nat/windows-nat.h. */ 633 634 int 635 gdbserver_windows_process::handle_output_debug_string 636 (struct target_waitstatus *ourstatus) 637 { 638 #define READ_BUFFER_LEN 1024 639 CORE_ADDR addr; 640 char s[READ_BUFFER_LEN + 1] = { 0 }; 641 DWORD nbytes = current_event.u.DebugString.nDebugStringLength; 642 643 if (nbytes == 0) 644 return 0; 645 646 if (nbytes > READ_BUFFER_LEN) 647 nbytes = READ_BUFFER_LEN; 648 649 addr = (CORE_ADDR) (size_t) current_event.u.DebugString.lpDebugStringData; 650 651 if (current_event.u.DebugString.fUnicode) 652 { 653 /* The event tells us how many bytes, not chars, even 654 in Unicode. */ 655 WCHAR buffer[(READ_BUFFER_LEN + 1) / sizeof (WCHAR)] = { 0 }; 656 if (read_inferior_memory (addr, (unsigned char *) buffer, nbytes) != 0) 657 return 0; 658 wcstombs (s, buffer, (nbytes + 1) / sizeof (WCHAR)); 659 } 660 else 661 { 662 if (read_inferior_memory (addr, (unsigned char *) s, nbytes) != 0) 663 return 0; 664 } 665 666 if (!startswith (s, "cYg")) 667 { 668 if (!server_waiting) 669 { 670 OUTMSG2(("%s", s)); 671 return 0; 672 } 673 674 monitor_output (s); 675 } 676 #undef READ_BUFFER_LEN 677 678 return 0; 679 } 680 681 static void 682 win32_clear_inferiors (void) 683 { 684 if (windows_process.open_process_used) 685 { 686 CloseHandle (windows_process.handle); 687 windows_process.open_process_used = false; 688 } 689 690 for_each_thread (delete_thread_info); 691 windows_process.siginfo_er.ExceptionCode = 0; 692 clear_inferiors (); 693 } 694 695 /* Implementation of target_ops::kill. */ 696 697 int 698 win32_process_target::kill (process_info *process) 699 { 700 TerminateProcess (windows_process.handle, 0); 701 for (;;) 702 { 703 if (!child_continue (DBG_CONTINUE, -1)) 704 break; 705 if (!wait_for_debug_event (&windows_process.current_event, INFINITE)) 706 break; 707 if (windows_process.current_event.dwDebugEventCode 708 == EXIT_PROCESS_DEBUG_EVENT) 709 break; 710 else if (windows_process.current_event.dwDebugEventCode 711 == OUTPUT_DEBUG_STRING_EVENT) 712 windows_process.handle_output_debug_string (nullptr); 713 } 714 715 win32_clear_inferiors (); 716 717 remove_process (process); 718 return 0; 719 } 720 721 /* Implementation of target_ops::detach. */ 722 723 int 724 win32_process_target::detach (process_info *process) 725 { 726 struct thread_resume resume; 727 resume.thread = minus_one_ptid; 728 resume.kind = resume_continue; 729 resume.sig = 0; 730 this->resume (&resume, 1); 731 732 if (!DebugActiveProcessStop (process->pid)) 733 return -1; 734 735 DebugSetProcessKillOnExit (FALSE); 736 win32_clear_inferiors (); 737 remove_process (process); 738 739 return 0; 740 } 741 742 void 743 win32_process_target::mourn (struct process_info *process) 744 { 745 remove_process (process); 746 } 747 748 /* Implementation of target_ops::join. */ 749 750 void 751 win32_process_target::join (int pid) 752 { 753 HANDLE h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid); 754 if (h != NULL) 755 { 756 WaitForSingleObject (h, INFINITE); 757 CloseHandle (h); 758 } 759 } 760 761 /* Return true iff the thread with thread ID TID is alive. */ 762 bool 763 win32_process_target::thread_alive (ptid_t ptid) 764 { 765 /* Our thread list is reliable; don't bother to poll target 766 threads. */ 767 return find_thread_ptid (ptid) != NULL; 768 } 769 770 /* Resume the inferior process. RESUME_INFO describes how we want 771 to resume. */ 772 void 773 win32_process_target::resume (thread_resume *resume_info, size_t n) 774 { 775 DWORD tid; 776 enum gdb_signal sig; 777 int step; 778 windows_thread_info *th; 779 DWORD continue_status = DBG_CONTINUE; 780 ptid_t ptid; 781 782 /* This handles the very limited set of resume packets that GDB can 783 currently produce. */ 784 785 if (n == 1 && resume_info[0].thread == minus_one_ptid) 786 tid = -1; 787 else if (n > 1) 788 tid = -1; 789 else 790 /* Yes, we're ignoring resume_info[0].thread. It'd be tricky to make 791 the Windows resume code do the right thing for thread switching. */ 792 tid = windows_process.current_event.dwThreadId; 793 794 if (resume_info[0].thread != minus_one_ptid) 795 { 796 sig = gdb_signal_from_host (resume_info[0].sig); 797 step = resume_info[0].kind == resume_step; 798 } 799 else 800 { 801 sig = GDB_SIGNAL_0; 802 step = 0; 803 } 804 805 if (sig != GDB_SIGNAL_0) 806 { 807 if (windows_process.current_event.dwDebugEventCode 808 != EXCEPTION_DEBUG_EVENT) 809 { 810 OUTMSG (("Cannot continue with signal %s here.\n", 811 gdb_signal_to_string (sig))); 812 } 813 else if (sig == windows_process.last_sig) 814 continue_status = DBG_EXCEPTION_NOT_HANDLED; 815 else 816 OUTMSG (("Can only continue with received signal %s.\n", 817 gdb_signal_to_string (windows_process.last_sig))); 818 } 819 820 windows_process.last_sig = GDB_SIGNAL_0; 821 822 /* Get context for the currently selected thread. */ 823 ptid = debug_event_ptid (&windows_process.current_event); 824 th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT); 825 if (th) 826 { 827 win32_prepare_to_resume (th); 828 829 DWORD *context_flags; 830 #ifdef __x86_64__ 831 if (windows_process.wow64_process) 832 context_flags = &th->wow64_context.ContextFlags; 833 else 834 #endif 835 context_flags = &th->context.ContextFlags; 836 if (*context_flags) 837 { 838 /* Move register values from the inferior into the thread 839 context structure. */ 840 regcache_invalidate (); 841 842 if (step) 843 { 844 if (the_low_target.single_step != NULL) 845 (*the_low_target.single_step) (th); 846 else 847 error ("Single stepping is not supported " 848 "in this configuration.\n"); 849 } 850 851 win32_set_thread_context (th); 852 *context_flags = 0; 853 } 854 } 855 856 /* Allow continuing with the same signal that interrupted us. 857 Otherwise complain. */ 858 859 child_continue (continue_status, tid); 860 } 861 862 /* See nat/windows-nat.h. */ 863 864 void 865 gdbserver_windows_process::handle_load_dll (const char *name, LPVOID base) 866 { 867 CORE_ADDR load_addr = (CORE_ADDR) (uintptr_t) base; 868 869 char buf[MAX_PATH + 1]; 870 char buf2[MAX_PATH + 1]; 871 872 WIN32_FIND_DATAA w32_fd; 873 HANDLE h = FindFirstFileA (name, &w32_fd); 874 875 /* The symbols in a dll are offset by 0x1000, which is the 876 offset from 0 of the first byte in an image - because 877 of the file header and the section alignment. */ 878 load_addr += 0x1000; 879 880 if (h == INVALID_HANDLE_VALUE) 881 strcpy (buf, name); 882 else 883 { 884 FindClose (h); 885 strcpy (buf, name); 886 { 887 char cwd[MAX_PATH + 1]; 888 char *p; 889 if (GetCurrentDirectoryA (MAX_PATH + 1, cwd)) 890 { 891 p = strrchr (buf, '\\'); 892 if (p) 893 p[1] = '\0'; 894 SetCurrentDirectoryA (buf); 895 GetFullPathNameA (w32_fd.cFileName, MAX_PATH, buf, &p); 896 SetCurrentDirectoryA (cwd); 897 } 898 } 899 } 900 901 if (strcasecmp (buf, "ntdll.dll") == 0) 902 { 903 GetSystemDirectoryA (buf, sizeof (buf)); 904 strcat (buf, "\\ntdll.dll"); 905 } 906 907 #ifdef __CYGWIN__ 908 cygwin_conv_path (CCP_WIN_A_TO_POSIX, buf, buf2, sizeof (buf2)); 909 #else 910 strcpy (buf2, buf); 911 #endif 912 913 loaded_dll (buf2, load_addr); 914 } 915 916 /* See nat/windows-nat.h. */ 917 918 void 919 gdbserver_windows_process::handle_unload_dll () 920 { 921 CORE_ADDR load_addr = 922 (CORE_ADDR) (uintptr_t) current_event.u.UnloadDll.lpBaseOfDll; 923 924 /* The symbols in a dll are offset by 0x1000, which is the 925 offset from 0 of the first byte in an image - because 926 of the file header and the section alignment. */ 927 load_addr += 0x1000; 928 unloaded_dll (NULL, load_addr); 929 } 930 931 static void 932 suspend_one_thread (thread_info *thread) 933 { 934 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread); 935 936 th->suspend (); 937 } 938 939 static void 940 fake_breakpoint_event (void) 941 { 942 OUTMSG2(("fake_breakpoint_event\n")); 943 944 windows_process.faked_breakpoint = 1; 945 946 memset (&windows_process.current_event, 0, 947 sizeof (windows_process.current_event)); 948 windows_process.current_event.dwThreadId = windows_process.main_thread_id; 949 windows_process.current_event.dwDebugEventCode = EXCEPTION_DEBUG_EVENT; 950 windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode 951 = EXCEPTION_BREAKPOINT; 952 953 for_each_thread (suspend_one_thread); 954 } 955 956 /* See nat/windows-nat.h. */ 957 958 bool 959 gdbserver_windows_process::handle_access_violation 960 (const EXCEPTION_RECORD *rec) 961 { 962 return false; 963 } 964 965 /* A helper function that will, if needed, set 966 'stopped_at_software_breakpoint' on the thread and adjust the 967 PC. */ 968 969 static void 970 maybe_adjust_pc () 971 { 972 struct regcache *regcache = get_thread_regcache (current_thread, 1); 973 child_fetch_inferior_registers (regcache, -1); 974 975 windows_thread_info *th 976 = windows_process.thread_rec (current_thread_ptid (), 977 DONT_INVALIDATE_CONTEXT); 978 th->stopped_at_software_breakpoint = false; 979 980 if (windows_process.current_event.dwDebugEventCode == EXCEPTION_DEBUG_EVENT 981 && ((windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode 982 == EXCEPTION_BREAKPOINT) 983 || (windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode 984 == STATUS_WX86_BREAKPOINT)) 985 && windows_process.child_initialization_done) 986 { 987 th->stopped_at_software_breakpoint = true; 988 CORE_ADDR pc = regcache_read_pc (regcache); 989 CORE_ADDR sw_breakpoint_pc = pc - the_low_target.decr_pc_after_break; 990 regcache_write_pc (regcache, sw_breakpoint_pc); 991 } 992 } 993 994 /* Get the next event from the child. */ 995 996 static int 997 get_child_debug_event (DWORD *continue_status, 998 struct target_waitstatus *ourstatus) 999 { 1000 ptid_t ptid; 1001 1002 windows_process.last_sig = GDB_SIGNAL_0; 1003 ourstatus->set_spurious (); 1004 *continue_status = DBG_CONTINUE; 1005 1006 /* Check if GDB sent us an interrupt request. */ 1007 check_remote_input_interrupt_request (); 1008 1009 DEBUG_EVENT *current_event = &windows_process.current_event; 1010 1011 if (windows_process.soft_interrupt_requested) 1012 { 1013 windows_process.soft_interrupt_requested = 0; 1014 fake_breakpoint_event (); 1015 goto gotevent; 1016 } 1017 1018 windows_process.attaching = 0; 1019 { 1020 std::optional<pending_stop> stop 1021 = windows_process.fetch_pending_stop (debug_threads); 1022 if (stop.has_value ()) 1023 { 1024 *ourstatus = stop->status; 1025 windows_process.current_event = stop->event; 1026 ptid = debug_event_ptid (&windows_process.current_event); 1027 switch_to_thread (find_thread_ptid (ptid)); 1028 return 1; 1029 } 1030 1031 /* Keep the wait time low enough for comfortable remote 1032 interruption, but high enough so gdbserver doesn't become a 1033 bottleneck. */ 1034 if (!wait_for_debug_event (&windows_process.current_event, 250)) 1035 { 1036 DWORD e = GetLastError(); 1037 1038 if (e == ERROR_PIPE_NOT_CONNECTED) 1039 { 1040 /* This will happen if the loader fails to successfully 1041 load the application, e.g., if the main executable 1042 tries to pull in a non-existing export from a 1043 DLL. */ 1044 ourstatus->set_exited (1); 1045 return 1; 1046 } 1047 1048 return 0; 1049 } 1050 } 1051 1052 gotevent: 1053 1054 switch (current_event->dwDebugEventCode) 1055 { 1056 case CREATE_THREAD_DEBUG_EVENT: 1057 OUTMSG2 (("gdbserver: kernel event CREATE_THREAD_DEBUG_EVENT " 1058 "for pid=%u tid=%x)\n", 1059 (unsigned) current_event->dwProcessId, 1060 (unsigned) current_event->dwThreadId)); 1061 1062 /* Record the existence of this thread. */ 1063 child_add_thread (current_event->dwProcessId, 1064 current_event->dwThreadId, 1065 current_event->u.CreateThread.hThread, 1066 current_event->u.CreateThread.lpThreadLocalBase); 1067 break; 1068 1069 case EXIT_THREAD_DEBUG_EVENT: 1070 OUTMSG2 (("gdbserver: kernel event EXIT_THREAD_DEBUG_EVENT " 1071 "for pid=%u tid=%x\n", 1072 (unsigned) current_event->dwProcessId, 1073 (unsigned) current_event->dwThreadId)); 1074 child_delete_thread (current_event->dwProcessId, 1075 current_event->dwThreadId); 1076 1077 switch_to_thread (get_first_thread ()); 1078 return 1; 1079 1080 case CREATE_PROCESS_DEBUG_EVENT: 1081 OUTMSG2 (("gdbserver: kernel event CREATE_PROCESS_DEBUG_EVENT " 1082 "for pid=%u tid=%x\n", 1083 (unsigned) current_event->dwProcessId, 1084 (unsigned) current_event->dwThreadId)); 1085 CloseHandle (current_event->u.CreateProcessInfo.hFile); 1086 1087 if (windows_process.open_process_used) 1088 { 1089 CloseHandle (windows_process.handle); 1090 windows_process.open_process_used = false; 1091 } 1092 1093 windows_process.handle = current_event->u.CreateProcessInfo.hProcess; 1094 windows_process.main_thread_id = current_event->dwThreadId; 1095 1096 /* Add the main thread. */ 1097 child_add_thread (current_event->dwProcessId, 1098 windows_process.main_thread_id, 1099 current_event->u.CreateProcessInfo.hThread, 1100 current_event->u.CreateProcessInfo.lpThreadLocalBase); 1101 break; 1102 1103 case EXIT_PROCESS_DEBUG_EVENT: 1104 OUTMSG2 (("gdbserver: kernel event EXIT_PROCESS_DEBUG_EVENT " 1105 "for pid=%u tid=%x\n", 1106 (unsigned) current_event->dwProcessId, 1107 (unsigned) current_event->dwThreadId)); 1108 { 1109 DWORD exit_status = current_event->u.ExitProcess.dwExitCode; 1110 /* If the exit status looks like a fatal exception, but we 1111 don't recognize the exception's code, make the original 1112 exit status value available, to avoid losing information. */ 1113 int exit_signal 1114 = WIFSIGNALED (exit_status) ? WTERMSIG (exit_status) : -1; 1115 if (exit_signal == -1) 1116 ourstatus->set_exited (exit_status); 1117 else 1118 ourstatus->set_signalled (gdb_signal_from_host (exit_signal)); 1119 } 1120 child_continue (DBG_CONTINUE, windows_process.desired_stop_thread_id); 1121 break; 1122 1123 case LOAD_DLL_DEBUG_EVENT: 1124 OUTMSG2 (("gdbserver: kernel event LOAD_DLL_DEBUG_EVENT " 1125 "for pid=%u tid=%x\n", 1126 (unsigned) current_event->dwProcessId, 1127 (unsigned) current_event->dwThreadId)); 1128 CloseHandle (current_event->u.LoadDll.hFile); 1129 if (! windows_process.child_initialization_done) 1130 break; 1131 windows_process.dll_loaded_event (); 1132 1133 ourstatus->set_loaded (); 1134 break; 1135 1136 case UNLOAD_DLL_DEBUG_EVENT: 1137 OUTMSG2 (("gdbserver: kernel event UNLOAD_DLL_DEBUG_EVENT " 1138 "for pid=%u tid=%x\n", 1139 (unsigned) current_event->dwProcessId, 1140 (unsigned) current_event->dwThreadId)); 1141 if (! windows_process.child_initialization_done) 1142 break; 1143 windows_process.handle_unload_dll (); 1144 ourstatus->set_loaded (); 1145 break; 1146 1147 case EXCEPTION_DEBUG_EVENT: 1148 OUTMSG2 (("gdbserver: kernel event EXCEPTION_DEBUG_EVENT " 1149 "for pid=%u tid=%x\n", 1150 (unsigned) current_event->dwProcessId, 1151 (unsigned) current_event->dwThreadId)); 1152 if (windows_process.handle_exception (ourstatus, debug_threads) 1153 == HANDLE_EXCEPTION_UNHANDLED) 1154 *continue_status = DBG_EXCEPTION_NOT_HANDLED; 1155 break; 1156 1157 case OUTPUT_DEBUG_STRING_EVENT: 1158 /* A message from the kernel (or Cygwin). */ 1159 OUTMSG2 (("gdbserver: kernel event OUTPUT_DEBUG_STRING_EVENT " 1160 "for pid=%u tid=%x\n", 1161 (unsigned) current_event->dwProcessId, 1162 (unsigned) current_event->dwThreadId)); 1163 windows_process.handle_output_debug_string (nullptr); 1164 break; 1165 1166 default: 1167 OUTMSG2 (("gdbserver: kernel event unknown " 1168 "for pid=%u tid=%x code=%x\n", 1169 (unsigned) current_event->dwProcessId, 1170 (unsigned) current_event->dwThreadId, 1171 (unsigned) current_event->dwDebugEventCode)); 1172 break; 1173 } 1174 1175 ptid = debug_event_ptid (&windows_process.current_event); 1176 1177 if (windows_process.desired_stop_thread_id != -1 1178 && windows_process.desired_stop_thread_id != ptid.lwp ()) 1179 { 1180 /* Pending stop. See the comment by the definition of 1181 "pending_stops" for details on why this is needed. */ 1182 OUTMSG2 (("get_windows_debug_event - " 1183 "unexpected stop in 0x%lx (expecting 0x%x)\n", 1184 ptid.lwp (), windows_process.desired_stop_thread_id)); 1185 maybe_adjust_pc (); 1186 windows_process.pending_stops.push_back 1187 ({(DWORD) ptid.lwp (), *ourstatus, *current_event}); 1188 ourstatus->set_spurious (); 1189 } 1190 else 1191 switch_to_thread (find_thread_ptid (ptid)); 1192 1193 return 1; 1194 } 1195 1196 /* Wait for the inferior process to change state. 1197 STATUS will be filled in with a response code to send to GDB. 1198 Returns the signal which caused the process to stop. */ 1199 ptid_t 1200 win32_process_target::wait (ptid_t ptid, target_waitstatus *ourstatus, 1201 target_wait_flags options) 1202 { 1203 if (windows_process.cached_status.kind () != TARGET_WAITKIND_IGNORE) 1204 { 1205 /* The core always does a wait after creating the inferior, and 1206 do_initial_child_stuff already ran the inferior to the 1207 initial breakpoint (or an exit, if creating the process 1208 fails). Report it now. */ 1209 *ourstatus = windows_process.cached_status; 1210 windows_process.cached_status.set_ignore (); 1211 return debug_event_ptid (&windows_process.current_event); 1212 } 1213 1214 while (1) 1215 { 1216 DWORD continue_status; 1217 if (!get_child_debug_event (&continue_status, ourstatus)) 1218 continue; 1219 1220 switch (ourstatus->kind ()) 1221 { 1222 case TARGET_WAITKIND_EXITED: 1223 OUTMSG2 (("Child exited with retcode = %x\n", 1224 ourstatus->exit_status ())); 1225 win32_clear_inferiors (); 1226 return ptid_t (windows_process.current_event.dwProcessId); 1227 case TARGET_WAITKIND_STOPPED: 1228 case TARGET_WAITKIND_SIGNALLED: 1229 case TARGET_WAITKIND_LOADED: 1230 { 1231 OUTMSG2 (("Child Stopped with signal = %d \n", 1232 ourstatus->sig ())); 1233 maybe_adjust_pc (); 1234 return debug_event_ptid (&windows_process.current_event); 1235 } 1236 default: 1237 OUTMSG (("Ignoring unknown internal event, %d\n", 1238 ourstatus->kind ())); 1239 [[fallthrough]]; 1240 case TARGET_WAITKIND_SPURIOUS: 1241 /* do nothing, just continue */ 1242 child_continue (continue_status, 1243 windows_process.desired_stop_thread_id); 1244 break; 1245 } 1246 } 1247 } 1248 1249 /* Fetch registers from the inferior process. 1250 If REGNO is -1, fetch all registers; otherwise, fetch at least REGNO. */ 1251 void 1252 win32_process_target::fetch_registers (regcache *regcache, int regno) 1253 { 1254 child_fetch_inferior_registers (regcache, regno); 1255 } 1256 1257 /* Store registers to the inferior process. 1258 If REGNO is -1, store all registers; otherwise, store at least REGNO. */ 1259 void 1260 win32_process_target::store_registers (regcache *regcache, int regno) 1261 { 1262 child_store_inferior_registers (regcache, regno); 1263 } 1264 1265 /* Read memory from the inferior process. This should generally be 1266 called through read_inferior_memory, which handles breakpoint shadowing. 1267 Read LEN bytes at MEMADDR into a buffer at MYADDR. */ 1268 int 1269 win32_process_target::read_memory (CORE_ADDR memaddr, unsigned char *myaddr, 1270 int len) 1271 { 1272 return child_xfer_memory (memaddr, (char *) myaddr, len, 0, 0) != len; 1273 } 1274 1275 /* Write memory to the inferior process. This should generally be 1276 called through write_inferior_memory, which handles breakpoint shadowing. 1277 Write LEN bytes from the buffer at MYADDR to MEMADDR. 1278 Returns 0 on success and errno on failure. */ 1279 int 1280 win32_process_target::write_memory (CORE_ADDR memaddr, 1281 const unsigned char *myaddr, int len) 1282 { 1283 return child_xfer_memory (memaddr, (char *) myaddr, len, 1, 0) != len; 1284 } 1285 1286 /* Send an interrupt request to the inferior process. */ 1287 void 1288 win32_process_target::request_interrupt () 1289 { 1290 if (GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, signal_pid)) 1291 return; 1292 1293 /* GenerateConsoleCtrlEvent can fail if process id being debugged is 1294 not a process group id. 1295 Fallback to XP/Vista 'DebugBreakProcess', which generates a 1296 breakpoint exception in the interior process. */ 1297 1298 if (DebugBreakProcess (windows_process.handle)) 1299 return; 1300 1301 /* Last resort, suspend all threads manually. */ 1302 windows_process.soft_interrupt_requested = 1; 1303 } 1304 1305 bool 1306 win32_process_target::supports_hardware_single_step () 1307 { 1308 return true; 1309 } 1310 1311 bool 1312 win32_process_target::supports_qxfer_siginfo () 1313 { 1314 return true; 1315 } 1316 1317 /* Write Windows signal info. */ 1318 1319 int 1320 win32_process_target::qxfer_siginfo (const char *annex, 1321 unsigned char *readbuf, 1322 unsigned const char *writebuf, 1323 CORE_ADDR offset, int len) 1324 { 1325 if (windows_process.siginfo_er.ExceptionCode == 0) 1326 return -1; 1327 1328 if (readbuf == nullptr) 1329 return -1; 1330 1331 char *buf = (char *) &windows_process.siginfo_er; 1332 size_t bufsize = sizeof (windows_process.siginfo_er); 1333 1334 #ifdef __x86_64__ 1335 EXCEPTION_RECORD32 er32; 1336 if (windows_process.wow64_process) 1337 { 1338 buf = (char *) &er32; 1339 bufsize = sizeof (er32); 1340 1341 er32.ExceptionCode = windows_process.siginfo_er.ExceptionCode; 1342 er32.ExceptionFlags = windows_process.siginfo_er.ExceptionFlags; 1343 er32.ExceptionRecord 1344 = (uintptr_t) windows_process.siginfo_er.ExceptionRecord; 1345 er32.ExceptionAddress 1346 = (uintptr_t) windows_process.siginfo_er.ExceptionAddress; 1347 er32.NumberParameters = windows_process.siginfo_er.NumberParameters; 1348 int i; 1349 for (i = 0; i < EXCEPTION_MAXIMUM_PARAMETERS; i++) 1350 er32.ExceptionInformation[i] 1351 = windows_process.siginfo_er.ExceptionInformation[i]; 1352 } 1353 #endif 1354 1355 if (offset > bufsize) 1356 return -1; 1357 1358 if (offset + len > bufsize) 1359 len = bufsize - offset; 1360 1361 memcpy (readbuf, buf + offset, len); 1362 1363 return len; 1364 } 1365 1366 bool 1367 win32_process_target::supports_get_tib_address () 1368 { 1369 return true; 1370 } 1371 1372 /* Write Windows OS Thread Information Block address. */ 1373 1374 int 1375 win32_process_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr) 1376 { 1377 windows_thread_info *th; 1378 th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT); 1379 if (th == NULL) 1380 return 0; 1381 if (addr != NULL) 1382 *addr = th->thread_local_base; 1383 return 1; 1384 } 1385 1386 /* Implementation of the target_ops method "sw_breakpoint_from_kind". */ 1387 1388 const gdb_byte * 1389 win32_process_target::sw_breakpoint_from_kind (int kind, int *size) 1390 { 1391 *size = the_low_target.breakpoint_len; 1392 return the_low_target.breakpoint; 1393 } 1394 1395 bool 1396 win32_process_target::stopped_by_sw_breakpoint () 1397 { 1398 windows_thread_info *th 1399 = windows_process.thread_rec (current_thread_ptid (), 1400 DONT_INVALIDATE_CONTEXT); 1401 return th == nullptr ? false : th->stopped_at_software_breakpoint; 1402 } 1403 1404 bool 1405 win32_process_target::supports_stopped_by_sw_breakpoint () 1406 { 1407 return true; 1408 } 1409 1410 CORE_ADDR 1411 win32_process_target::read_pc (struct regcache *regcache) 1412 { 1413 return (*the_low_target.get_pc) (regcache); 1414 } 1415 1416 void 1417 win32_process_target::write_pc (struct regcache *regcache, CORE_ADDR pc) 1418 { 1419 return (*the_low_target.set_pc) (regcache, pc); 1420 } 1421 1422 const char * 1423 win32_process_target::thread_name (ptid_t thread) 1424 { 1425 windows_thread_info *th 1426 = windows_process.thread_rec (current_thread_ptid (), 1427 DONT_INVALIDATE_CONTEXT); 1428 return th->thread_name (); 1429 } 1430 1431 const char * 1432 win32_process_target::pid_to_exec_file (int pid) 1433 { 1434 return windows_process.pid_to_exec_file (pid); 1435 } 1436 1437 /* The win32 target ops object. */ 1438 1439 static win32_process_target the_win32_target; 1440 1441 /* Initialize the Win32 backend. */ 1442 void 1443 initialize_low (void) 1444 { 1445 set_target_ops (&the_win32_target); 1446 the_low_target.arch_setup (); 1447 1448 initialize_loadable (); 1449 } 1450