1 /* Target-vector operations for controlling windows child processes, for GDB. 2 3 Copyright (C) 1995-2016 Free Software Foundation, Inc. 4 5 Contributed by Cygnus Solutions, A Red Hat Company. 6 7 This file is part of GDB. 8 9 This program is free software; you can redistribute it and/or modify 10 it under the terms of the GNU General Public License as published by 11 the Free Software Foundation; either version 3 of the License, or 12 (at your option) any later version. 13 14 This program is distributed in the hope that it will be useful, 15 but WITHOUT ANY WARRANTY; without even the implied warranty of 16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 GNU General Public License for more details. 18 19 You should have received a copy of the GNU General Public License 20 along with this program. If not, see <http://www.gnu.org/licenses/>. */ 21 22 /* Originally by Steve Chamberlain, sac@cygnus.com */ 23 24 #include "defs.h" 25 #include "frame.h" /* required by inferior.h */ 26 #include "inferior.h" 27 #include "infrun.h" 28 #include "target.h" 29 #include "gdbcore.h" 30 #include "command.h" 31 #include "completer.h" 32 #include "regcache.h" 33 #include "top.h" 34 #include <signal.h> 35 #include <sys/types.h> 36 #include <fcntl.h> 37 #include <windows.h> 38 #include <imagehlp.h> 39 #include <psapi.h> 40 #ifdef __CYGWIN__ 41 #include <wchar.h> 42 #include <sys/cygwin.h> 43 #include <cygwin/version.h> 44 #endif 45 46 #include "buildsym.h" 47 #include "filenames.h" 48 #include "symfile.h" 49 #include "objfiles.h" 50 #include "gdb_bfd.h" 51 #include "gdb_obstack.h" 52 #include "gdbthread.h" 53 #include "gdbcmd.h" 54 #include <unistd.h> 55 #include "exec.h" 56 #include "solist.h" 57 #include "solib.h" 58 #include "xml-support.h" 59 #include "inttypes.h" 60 61 #include "i386-tdep.h" 62 #include "i387-tdep.h" 63 64 #include "windows-tdep.h" 65 #include "windows-nat.h" 66 #include "x86-nat.h" 67 #include "complaints.h" 68 #include "inf-child.h" 69 70 #define AdjustTokenPrivileges dyn_AdjustTokenPrivileges 71 #define DebugActiveProcessStop dyn_DebugActiveProcessStop 72 #define DebugBreakProcess dyn_DebugBreakProcess 73 #define DebugSetProcessKillOnExit dyn_DebugSetProcessKillOnExit 74 #define EnumProcessModules dyn_EnumProcessModules 75 #define GetModuleInformation dyn_GetModuleInformation 76 #define LookupPrivilegeValueA dyn_LookupPrivilegeValueA 77 #define OpenProcessToken dyn_OpenProcessToken 78 #define GetConsoleFontSize dyn_GetConsoleFontSize 79 #define GetCurrentConsoleFont dyn_GetCurrentConsoleFont 80 81 typedef BOOL WINAPI (AdjustTokenPrivileges_ftype) (HANDLE, BOOL, 82 PTOKEN_PRIVILEGES, 83 DWORD, PTOKEN_PRIVILEGES, 84 PDWORD); 85 static AdjustTokenPrivileges_ftype *AdjustTokenPrivileges; 86 87 typedef BOOL WINAPI (DebugActiveProcessStop_ftype) (DWORD); 88 static DebugActiveProcessStop_ftype *DebugActiveProcessStop; 89 90 typedef BOOL WINAPI (DebugBreakProcess_ftype) (HANDLE); 91 static DebugBreakProcess_ftype *DebugBreakProcess; 92 93 typedef BOOL WINAPI (DebugSetProcessKillOnExit_ftype) (BOOL); 94 static DebugSetProcessKillOnExit_ftype *DebugSetProcessKillOnExit; 95 96 typedef BOOL WINAPI (EnumProcessModules_ftype) (HANDLE, HMODULE *, DWORD, 97 LPDWORD); 98 static EnumProcessModules_ftype *EnumProcessModules; 99 100 typedef BOOL WINAPI (GetModuleInformation_ftype) (HANDLE, HMODULE, 101 LPMODULEINFO, DWORD); 102 static GetModuleInformation_ftype *GetModuleInformation; 103 104 typedef BOOL WINAPI (LookupPrivilegeValueA_ftype) (LPCSTR, LPCSTR, PLUID); 105 static LookupPrivilegeValueA_ftype *LookupPrivilegeValueA; 106 107 typedef BOOL WINAPI (OpenProcessToken_ftype) (HANDLE, DWORD, PHANDLE); 108 static OpenProcessToken_ftype *OpenProcessToken; 109 110 typedef BOOL WINAPI (GetCurrentConsoleFont_ftype) (HANDLE, BOOL, 111 CONSOLE_FONT_INFO *); 112 static GetCurrentConsoleFont_ftype *GetCurrentConsoleFont; 113 114 typedef COORD WINAPI (GetConsoleFontSize_ftype) (HANDLE, DWORD); 115 static GetConsoleFontSize_ftype *GetConsoleFontSize; 116 117 #undef STARTUPINFO 118 #undef CreateProcess 119 #undef GetModuleFileNameEx 120 121 #ifndef __CYGWIN__ 122 # define __PMAX (MAX_PATH + 1) 123 typedef DWORD WINAPI (GetModuleFileNameEx_ftype) (HANDLE, HMODULE, LPSTR, DWORD); 124 static GetModuleFileNameEx_ftype *GetModuleFileNameEx; 125 # define STARTUPINFO STARTUPINFOA 126 # define CreateProcess CreateProcessA 127 # define GetModuleFileNameEx_name "GetModuleFileNameExA" 128 # define bad_GetModuleFileNameEx bad_GetModuleFileNameExA 129 #else 130 # define __PMAX PATH_MAX 131 /* The starting and ending address of the cygwin1.dll text segment. */ 132 static CORE_ADDR cygwin_load_start; 133 static CORE_ADDR cygwin_load_end; 134 # define __USEWIDE 135 typedef wchar_t cygwin_buf_t; 136 typedef DWORD WINAPI (GetModuleFileNameEx_ftype) (HANDLE, HMODULE, 137 LPWSTR, DWORD); 138 static GetModuleFileNameEx_ftype *GetModuleFileNameEx; 139 # define STARTUPINFO STARTUPINFOW 140 # define CreateProcess CreateProcessW 141 # define GetModuleFileNameEx_name "GetModuleFileNameExW" 142 # define bad_GetModuleFileNameEx bad_GetModuleFileNameExW 143 #endif 144 145 static int have_saved_context; /* True if we've saved context from a 146 cygwin signal. */ 147 static CONTEXT saved_context; /* Containes the saved context from a 148 cygwin signal. */ 149 150 /* If we're not using the old Cygwin header file set, define the 151 following which never should have been in the generic Win32 API 152 headers in the first place since they were our own invention... */ 153 #ifndef _GNU_H_WINDOWS_H 154 enum 155 { 156 FLAG_TRACE_BIT = 0x100, 157 }; 158 #endif 159 160 #ifndef CONTEXT_EXTENDED_REGISTERS 161 /* This macro is only defined on ia32. It only makes sense on this target, 162 so define it as zero if not already defined. */ 163 #define CONTEXT_EXTENDED_REGISTERS 0 164 #endif 165 166 #define CONTEXT_DEBUGGER_DR CONTEXT_FULL | CONTEXT_FLOATING_POINT \ 167 | CONTEXT_SEGMENTS | CONTEXT_DEBUG_REGISTERS \ 168 | CONTEXT_EXTENDED_REGISTERS 169 170 static uintptr_t dr[8]; 171 static int debug_registers_changed; 172 static int debug_registers_used; 173 174 static int windows_initialization_done; 175 #define DR6_CLEAR_VALUE 0xffff0ff0 176 177 /* The string sent by cygwin when it processes a signal. 178 FIXME: This should be in a cygwin include file. */ 179 #ifndef _CYGWIN_SIGNAL_STRING 180 #define _CYGWIN_SIGNAL_STRING "cYgSiGw00f" 181 #endif 182 183 #define CHECK(x) check (x, __FILE__,__LINE__) 184 #define DEBUG_EXEC(x) if (debug_exec) printf_unfiltered x 185 #define DEBUG_EVENTS(x) if (debug_events) printf_unfiltered x 186 #define DEBUG_MEM(x) if (debug_memory) printf_unfiltered x 187 #define DEBUG_EXCEPT(x) if (debug_exceptions) printf_unfiltered x 188 189 static void windows_interrupt (struct target_ops *self, ptid_t); 190 static int windows_thread_alive (struct target_ops *, ptid_t); 191 static void windows_kill_inferior (struct target_ops *); 192 193 static void cygwin_set_dr (int i, CORE_ADDR addr); 194 static void cygwin_set_dr7 (unsigned long val); 195 static CORE_ADDR cygwin_get_dr (int i); 196 static unsigned long cygwin_get_dr6 (void); 197 static unsigned long cygwin_get_dr7 (void); 198 199 static enum gdb_signal last_sig = GDB_SIGNAL_0; 200 /* Set if a signal was received from the debugged process. */ 201 202 /* Thread information structure used to track information that is 203 not available in gdb's thread structure. */ 204 typedef struct windows_thread_info_struct 205 { 206 struct windows_thread_info_struct *next; 207 DWORD id; 208 HANDLE h; 209 CORE_ADDR thread_local_base; 210 char *name; 211 int suspended; 212 int reload_context; 213 CONTEXT context; 214 STACKFRAME sf; 215 } 216 windows_thread_info; 217 218 static windows_thread_info thread_head; 219 220 /* The process and thread handles for the above context. */ 221 222 static DEBUG_EVENT current_event; /* The current debug event from 223 WaitForDebugEvent */ 224 static HANDLE current_process_handle; /* Currently executing process */ 225 static windows_thread_info *current_thread; /* Info on currently selected thread */ 226 static DWORD main_thread_id; /* Thread ID of the main thread */ 227 228 /* Counts of things. */ 229 static int exception_count = 0; 230 static int event_count = 0; 231 static int saw_create; 232 static int open_process_used = 0; 233 234 /* User options. */ 235 static int new_console = 0; 236 #ifdef __CYGWIN__ 237 static int cygwin_exceptions = 0; 238 #endif 239 static int new_group = 1; 240 static int debug_exec = 0; /* show execution */ 241 static int debug_events = 0; /* show events from kernel */ 242 static int debug_memory = 0; /* show target memory accesses */ 243 static int debug_exceptions = 0; /* show target exceptions */ 244 static int useshell = 0; /* use shell for subprocesses */ 245 246 /* This vector maps GDB's idea of a register's number into an offset 247 in the windows exception context vector. 248 249 It also contains the bit mask needed to load the register in question. 250 251 The contents of this table can only be computed by the units 252 that provide CPU-specific support for Windows native debugging. 253 These units should set the table by calling 254 windows_set_context_register_offsets. 255 256 One day we could read a reg, we could inspect the context we 257 already have loaded, if it doesn't have the bit set that we need, 258 we read that set of registers in using GetThreadContext. If the 259 context already contains what we need, we just unpack it. Then to 260 write a register, first we have to ensure that the context contains 261 the other regs of the group, and then we copy the info in and set 262 out bit. */ 263 264 static const int *mappings; 265 266 /* The function to use in order to determine whether a register is 267 a segment register or not. */ 268 static segment_register_p_ftype *segment_register_p; 269 270 /* This vector maps the target's idea of an exception (extracted 271 from the DEBUG_EVENT structure) to GDB's idea. */ 272 273 struct xlate_exception 274 { 275 int them; 276 enum gdb_signal us; 277 }; 278 279 static const struct xlate_exception 280 xlate[] = 281 { 282 {EXCEPTION_ACCESS_VIOLATION, GDB_SIGNAL_SEGV}, 283 {STATUS_STACK_OVERFLOW, GDB_SIGNAL_SEGV}, 284 {EXCEPTION_BREAKPOINT, GDB_SIGNAL_TRAP}, 285 {DBG_CONTROL_C, GDB_SIGNAL_INT}, 286 {EXCEPTION_SINGLE_STEP, GDB_SIGNAL_TRAP}, 287 {STATUS_FLOAT_DIVIDE_BY_ZERO, GDB_SIGNAL_FPE}, 288 {-1, GDB_SIGNAL_UNKNOWN}}; 289 290 /* Set the MAPPINGS static global to OFFSETS. 291 See the description of MAPPINGS for more details. */ 292 293 void 294 windows_set_context_register_offsets (const int *offsets) 295 { 296 mappings = offsets; 297 } 298 299 /* See windows-nat.h. */ 300 301 void 302 windows_set_segment_register_p (segment_register_p_ftype *fun) 303 { 304 segment_register_p = fun; 305 } 306 307 static void 308 check (BOOL ok, const char *file, int line) 309 { 310 if (!ok) 311 printf_filtered ("error return %s:%d was %u\n", file, line, 312 (unsigned) GetLastError ()); 313 } 314 315 /* Find a thread record given a thread id. If GET_CONTEXT is not 0, 316 then also retrieve the context for this thread. If GET_CONTEXT is 317 negative, then don't suspend the thread. */ 318 static windows_thread_info * 319 thread_rec (DWORD id, int get_context) 320 { 321 windows_thread_info *th; 322 323 for (th = &thread_head; (th = th->next) != NULL;) 324 if (th->id == id) 325 { 326 if (!th->suspended && get_context) 327 { 328 if (get_context > 0 && id != current_event.dwThreadId) 329 { 330 if (SuspendThread (th->h) == (DWORD) -1) 331 { 332 DWORD err = GetLastError (); 333 334 /* We get Access Denied (5) when trying to suspend 335 threads that Windows started on behalf of the 336 debuggee, usually when those threads are just 337 about to exit. 338 We can get Invalid Handle (6) if the main thread 339 has exited. */ 340 if (err != ERROR_INVALID_HANDLE 341 && err != ERROR_ACCESS_DENIED) 342 warning (_("SuspendThread (tid=0x%x) failed." 343 " (winerr %u)"), 344 (unsigned) id, (unsigned) err); 345 th->suspended = -1; 346 } 347 else 348 th->suspended = 1; 349 } 350 else if (get_context < 0) 351 th->suspended = -1; 352 th->reload_context = 1; 353 } 354 return th; 355 } 356 357 return NULL; 358 } 359 360 /* Add a thread to the thread list. */ 361 static windows_thread_info * 362 windows_add_thread (ptid_t ptid, HANDLE h, void *tlb) 363 { 364 windows_thread_info *th; 365 DWORD id; 366 367 gdb_assert (ptid_get_tid (ptid) != 0); 368 369 id = ptid_get_tid (ptid); 370 371 if ((th = thread_rec (id, FALSE))) 372 return th; 373 374 th = XCNEW (windows_thread_info); 375 th->id = id; 376 th->h = h; 377 th->thread_local_base = (CORE_ADDR) (uintptr_t) tlb; 378 th->next = thread_head.next; 379 thread_head.next = th; 380 add_thread (ptid); 381 /* Set the debug registers for the new thread if they are used. */ 382 if (debug_registers_used) 383 { 384 /* Only change the value of the debug registers. */ 385 th->context.ContextFlags = CONTEXT_DEBUG_REGISTERS; 386 CHECK (GetThreadContext (th->h, &th->context)); 387 th->context.Dr0 = dr[0]; 388 th->context.Dr1 = dr[1]; 389 th->context.Dr2 = dr[2]; 390 th->context.Dr3 = dr[3]; 391 th->context.Dr6 = DR6_CLEAR_VALUE; 392 th->context.Dr7 = dr[7]; 393 CHECK (SetThreadContext (th->h, &th->context)); 394 th->context.ContextFlags = 0; 395 } 396 return th; 397 } 398 399 /* Clear out any old thread list and reintialize it to a 400 pristine state. */ 401 static void 402 windows_init_thread_list (void) 403 { 404 windows_thread_info *th = &thread_head; 405 406 DEBUG_EVENTS (("gdb: windows_init_thread_list\n")); 407 init_thread_list (); 408 while (th->next != NULL) 409 { 410 windows_thread_info *here = th->next; 411 th->next = here->next; 412 xfree (here); 413 } 414 thread_head.next = NULL; 415 } 416 417 /* Delete a thread from the list of threads. */ 418 static void 419 windows_delete_thread (ptid_t ptid, DWORD exit_code) 420 { 421 windows_thread_info *th; 422 DWORD id; 423 424 gdb_assert (ptid_get_tid (ptid) != 0); 425 426 id = ptid_get_tid (ptid); 427 428 if (info_verbose) 429 printf_unfiltered ("[Deleting %s]\n", target_pid_to_str (ptid)); 430 else if (print_thread_events && id != main_thread_id) 431 printf_unfiltered (_("[%s exited with code %u]\n"), 432 target_pid_to_str (ptid), (unsigned) exit_code); 433 delete_thread (ptid); 434 435 for (th = &thread_head; 436 th->next != NULL && th->next->id != id; 437 th = th->next) 438 continue; 439 440 if (th->next != NULL) 441 { 442 windows_thread_info *here = th->next; 443 th->next = here->next; 444 xfree (here); 445 } 446 } 447 448 static void 449 do_windows_fetch_inferior_registers (struct regcache *regcache, int r) 450 { 451 char *context_offset = ((char *) ¤t_thread->context) + mappings[r]; 452 struct gdbarch *gdbarch = get_regcache_arch (regcache); 453 struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch); 454 long l; 455 456 if (!current_thread) 457 return; /* Windows sometimes uses a non-existent thread id in its 458 events. */ 459 460 if (current_thread->reload_context) 461 { 462 #ifdef __CYGWIN__ 463 if (have_saved_context) 464 { 465 /* Lie about where the program actually is stopped since 466 cygwin has informed us that we should consider the signal 467 to have occurred at another location which is stored in 468 "saved_context. */ 469 memcpy (¤t_thread->context, &saved_context, 470 __COPY_CONTEXT_SIZE); 471 have_saved_context = 0; 472 } 473 else 474 #endif 475 { 476 windows_thread_info *th = current_thread; 477 th->context.ContextFlags = CONTEXT_DEBUGGER_DR; 478 CHECK (GetThreadContext (th->h, &th->context)); 479 /* Copy dr values from that thread. 480 But only if there were not modified since last stop. 481 PR gdb/2388 */ 482 if (!debug_registers_changed) 483 { 484 dr[0] = th->context.Dr0; 485 dr[1] = th->context.Dr1; 486 dr[2] = th->context.Dr2; 487 dr[3] = th->context.Dr3; 488 dr[6] = th->context.Dr6; 489 dr[7] = th->context.Dr7; 490 } 491 } 492 current_thread->reload_context = 0; 493 } 494 495 if (r == I387_FISEG_REGNUM (tdep)) 496 { 497 l = *((long *) context_offset) & 0xffff; 498 regcache_raw_supply (regcache, r, (char *) &l); 499 } 500 else if (r == I387_FOP_REGNUM (tdep)) 501 { 502 l = (*((long *) context_offset) >> 16) & ((1 << 11) - 1); 503 regcache_raw_supply (regcache, r, (char *) &l); 504 } 505 else if (segment_register_p (r)) 506 { 507 /* GDB treats segment registers as 32bit registers, but they are 508 in fact only 16 bits long. Make sure we do not read extra 509 bits from our source buffer. */ 510 l = *((long *) context_offset) & 0xffff; 511 regcache_raw_supply (regcache, r, (char *) &l); 512 } 513 else if (r >= 0) 514 regcache_raw_supply (regcache, r, context_offset); 515 else 516 { 517 for (r = 0; r < gdbarch_num_regs (gdbarch); r++) 518 do_windows_fetch_inferior_registers (regcache, r); 519 } 520 } 521 522 static void 523 windows_fetch_inferior_registers (struct target_ops *ops, 524 struct regcache *regcache, int r) 525 { 526 current_thread = thread_rec (ptid_get_tid (inferior_ptid), TRUE); 527 /* Check if current_thread exists. Windows sometimes uses a non-existent 528 thread id in its events. */ 529 if (current_thread) 530 do_windows_fetch_inferior_registers (regcache, r); 531 } 532 533 static void 534 do_windows_store_inferior_registers (const struct regcache *regcache, int r) 535 { 536 if (!current_thread) 537 /* Windows sometimes uses a non-existent thread id in its events. */; 538 else if (r >= 0) 539 regcache_raw_collect (regcache, r, 540 ((char *) ¤t_thread->context) + mappings[r]); 541 else 542 { 543 for (r = 0; r < gdbarch_num_regs (get_regcache_arch (regcache)); r++) 544 do_windows_store_inferior_registers (regcache, r); 545 } 546 } 547 548 /* Store a new register value into the current thread context. */ 549 static void 550 windows_store_inferior_registers (struct target_ops *ops, 551 struct regcache *regcache, int r) 552 { 553 current_thread = thread_rec (ptid_get_tid (inferior_ptid), TRUE); 554 /* Check if current_thread exists. Windows sometimes uses a non-existent 555 thread id in its events. */ 556 if (current_thread) 557 do_windows_store_inferior_registers (regcache, r); 558 } 559 560 /* Encapsulate the information required in a call to 561 symbol_file_add_args. */ 562 struct safe_symbol_file_add_args 563 { 564 char *name; 565 int from_tty; 566 struct section_addr_info *addrs; 567 int mainline; 568 int flags; 569 struct ui_file *err, *out; 570 struct objfile *ret; 571 }; 572 573 /* Maintain a linked list of "so" information. */ 574 struct lm_info 575 { 576 LPVOID load_addr; 577 }; 578 579 static struct so_list solib_start, *solib_end; 580 581 static struct so_list * 582 windows_make_so (const char *name, LPVOID load_addr) 583 { 584 struct so_list *so; 585 char *p; 586 #ifndef __CYGWIN__ 587 char buf[__PMAX]; 588 char cwd[__PMAX]; 589 WIN32_FIND_DATA w32_fd; 590 HANDLE h = FindFirstFile(name, &w32_fd); 591 592 if (h == INVALID_HANDLE_VALUE) 593 strcpy (buf, name); 594 else 595 { 596 FindClose (h); 597 strcpy (buf, name); 598 if (GetCurrentDirectory (MAX_PATH + 1, cwd)) 599 { 600 p = strrchr (buf, '\\'); 601 if (p) 602 p[1] = '\0'; 603 SetCurrentDirectory (buf); 604 GetFullPathName (w32_fd.cFileName, MAX_PATH, buf, &p); 605 SetCurrentDirectory (cwd); 606 } 607 } 608 if (strcasecmp (buf, "ntdll.dll") == 0) 609 { 610 GetSystemDirectory (buf, sizeof (buf)); 611 strcat (buf, "\\ntdll.dll"); 612 } 613 #else 614 cygwin_buf_t buf[__PMAX]; 615 616 buf[0] = 0; 617 if (access (name, F_OK) != 0) 618 { 619 if (strcasecmp (name, "ntdll.dll") == 0) 620 #ifdef __USEWIDE 621 { 622 GetSystemDirectoryW (buf, sizeof (buf) / sizeof (wchar_t)); 623 wcscat (buf, L"\\ntdll.dll"); 624 } 625 #else 626 { 627 GetSystemDirectoryA (buf, sizeof (buf) / sizeof (wchar_t)); 628 strcat (buf, "\\ntdll.dll"); 629 } 630 #endif 631 } 632 #endif 633 so = XCNEW (struct so_list); 634 so->lm_info = XNEW (struct lm_info); 635 so->lm_info->load_addr = load_addr; 636 strcpy (so->so_original_name, name); 637 #ifndef __CYGWIN__ 638 strcpy (so->so_name, buf); 639 #else 640 if (buf[0]) 641 cygwin_conv_path (CCP_WIN_W_TO_POSIX, buf, so->so_name, 642 SO_NAME_MAX_PATH_SIZE); 643 else 644 { 645 char *rname = realpath (name, NULL); 646 if (rname && strlen (rname) < SO_NAME_MAX_PATH_SIZE) 647 { 648 strcpy (so->so_name, rname); 649 free (rname); 650 } 651 else 652 error (_("dll path too long")); 653 } 654 /* Record cygwin1.dll .text start/end. */ 655 p = strchr (so->so_name, '\0') - (sizeof ("/cygwin1.dll") - 1); 656 if (p >= so->so_name && strcasecmp (p, "/cygwin1.dll") == 0) 657 { 658 bfd *abfd; 659 asection *text = NULL; 660 CORE_ADDR text_vma; 661 662 abfd = gdb_bfd_open (so->so_name, "pei-i386", -1); 663 664 if (!abfd) 665 return so; 666 667 if (bfd_check_format (abfd, bfd_object)) 668 text = bfd_get_section_by_name (abfd, ".text"); 669 670 if (!text) 671 { 672 gdb_bfd_unref (abfd); 673 return so; 674 } 675 676 /* The symbols in a dll are offset by 0x1000, which is the 677 offset from 0 of the first byte in an image - because of the 678 file header and the section alignment. */ 679 cygwin_load_start = (CORE_ADDR) (uintptr_t) ((char *) 680 load_addr + 0x1000); 681 cygwin_load_end = cygwin_load_start + bfd_section_size (abfd, text); 682 683 gdb_bfd_unref (abfd); 684 } 685 #endif 686 687 return so; 688 } 689 690 static char * 691 get_image_name (HANDLE h, void *address, int unicode) 692 { 693 #ifdef __CYGWIN__ 694 static char buf[__PMAX]; 695 #else 696 static char buf[(2 * __PMAX) + 1]; 697 #endif 698 DWORD size = unicode ? sizeof (WCHAR) : sizeof (char); 699 char *address_ptr; 700 int len = 0; 701 char b[2]; 702 SIZE_T done; 703 704 /* Attempt to read the name of the dll that was detected. 705 This is documented to work only when actively debugging 706 a program. It will not work for attached processes. */ 707 if (address == NULL) 708 return NULL; 709 710 /* See if we could read the address of a string, and that the 711 address isn't null. */ 712 if (!ReadProcessMemory (h, address, &address_ptr, 713 sizeof (address_ptr), &done) 714 || done != sizeof (address_ptr) || !address_ptr) 715 return NULL; 716 717 /* Find the length of the string. */ 718 while (ReadProcessMemory (h, address_ptr + len++ * size, &b, size, &done) 719 && (b[0] != 0 || b[size - 1] != 0) && done == size) 720 continue; 721 722 if (!unicode) 723 ReadProcessMemory (h, address_ptr, buf, len, &done); 724 else 725 { 726 WCHAR *unicode_address = (WCHAR *) alloca (len * sizeof (WCHAR)); 727 ReadProcessMemory (h, address_ptr, unicode_address, len * sizeof (WCHAR), 728 &done); 729 #ifdef __CYGWIN__ 730 wcstombs (buf, unicode_address, __PMAX); 731 #else 732 WideCharToMultiByte (CP_ACP, 0, unicode_address, len, buf, sizeof buf, 733 0, 0); 734 #endif 735 } 736 737 return buf; 738 } 739 740 /* Handle a DLL load event, and return 1. 741 742 This function assumes that this event did not occur during inferior 743 initialization, where their event info may be incomplete (see 744 do_initial_windows_stuff and windows_add_all_dlls for more info 745 on how we handle DLL loading during that phase). */ 746 747 static int 748 handle_load_dll (void *dummy) 749 { 750 LOAD_DLL_DEBUG_INFO *event = ¤t_event.u.LoadDll; 751 char *dll_name; 752 753 /* Try getting the DLL name via the lpImageName field of the event. 754 Note that Microsoft documents this fields as strictly optional, 755 in the sense that it might be NULL. And the first DLL event in 756 particular is explicitly documented as "likely not pass[ed]" 757 (source: MSDN LOAD_DLL_DEBUG_INFO structure). */ 758 dll_name = get_image_name (current_process_handle, 759 event->lpImageName, event->fUnicode); 760 if (!dll_name) 761 return 1; 762 763 solib_end->next = windows_make_so (dll_name, event->lpBaseOfDll); 764 solib_end = solib_end->next; 765 766 DEBUG_EVENTS (("gdb: Loading dll \"%s\" at %s.\n", solib_end->so_name, 767 host_address_to_string (solib_end->lm_info->load_addr))); 768 769 return 1; 770 } 771 772 static void 773 windows_free_so (struct so_list *so) 774 { 775 if (so->lm_info) 776 xfree (so->lm_info); 777 xfree (so); 778 } 779 780 /* Handle a DLL unload event. 781 Return 1 if successful, or zero otherwise. 782 783 This function assumes that this event did not occur during inferior 784 initialization, where their event info may be incomplete (see 785 do_initial_windows_stuff and windows_add_all_dlls for more info 786 on how we handle DLL loading during that phase). */ 787 788 static int 789 handle_unload_dll (void *dummy) 790 { 791 LPVOID lpBaseOfDll = current_event.u.UnloadDll.lpBaseOfDll; 792 struct so_list *so; 793 794 for (so = &solib_start; so->next != NULL; so = so->next) 795 if (so->next->lm_info->load_addr == lpBaseOfDll) 796 { 797 struct so_list *sodel = so->next; 798 799 so->next = sodel->next; 800 if (!so->next) 801 solib_end = so; 802 DEBUG_EVENTS (("gdb: Unloading dll \"%s\".\n", sodel->so_name)); 803 804 windows_free_so (sodel); 805 return 1; 806 } 807 808 /* We did not find any DLL that was previously loaded at this address, 809 so register a complaint. We do not report an error, because we have 810 observed that this may be happening under some circumstances. For 811 instance, running 32bit applications on x64 Windows causes us to receive 812 4 mysterious UNLOAD_DLL_DEBUG_EVENTs during the startup phase (these 813 events are apparently caused by the WOW layer, the interface between 814 32bit and 64bit worlds). */ 815 complaint (&symfile_complaints, _("dll starting at %s not found."), 816 host_address_to_string (lpBaseOfDll)); 817 818 return 0; 819 } 820 821 /* Clear list of loaded DLLs. */ 822 static void 823 windows_clear_solib (void) 824 { 825 solib_start.next = NULL; 826 solib_end = &solib_start; 827 } 828 829 static void 830 signal_event_command (char *args, int from_tty) 831 { 832 uintptr_t event_id = 0; 833 char *endargs = NULL; 834 835 if (args == NULL) 836 error (_("signal-event requires an argument (integer event id)")); 837 838 event_id = strtoumax (args, &endargs, 10); 839 840 if ((errno == ERANGE) || (event_id == 0) || (event_id > UINTPTR_MAX) || 841 ((HANDLE) event_id == INVALID_HANDLE_VALUE)) 842 error (_("Failed to convert `%s' to event id"), args); 843 844 SetEvent ((HANDLE) event_id); 845 CloseHandle ((HANDLE) event_id); 846 } 847 848 /* Handle DEBUG_STRING output from child process. 849 Cygwin prepends its messages with a "cygwin:". Interpret this as 850 a Cygwin signal. Otherwise just print the string as a warning. */ 851 static int 852 handle_output_debug_string (struct target_waitstatus *ourstatus) 853 { 854 char *s = NULL; 855 int retval = 0; 856 857 if (!target_read_string 858 ((CORE_ADDR) (uintptr_t) current_event.u.DebugString.lpDebugStringData, 859 &s, 1024, 0) 860 || !s || !*s) 861 /* nothing to do */; 862 else if (!startswith (s, _CYGWIN_SIGNAL_STRING)) 863 { 864 #ifdef __CYGWIN__ 865 if (!startswith (s, "cYg")) 866 #endif 867 { 868 char *p = strchr (s, '\0'); 869 870 if (p > s && *--p == '\n') 871 *p = '\0'; 872 warning (("%s"), s); 873 } 874 } 875 #ifdef __CYGWIN__ 876 else 877 { 878 /* Got a cygwin signal marker. A cygwin signal is followed by 879 the signal number itself and then optionally followed by the 880 thread id and address to saved context within the DLL. If 881 these are supplied, then the given thread is assumed to have 882 issued the signal and the context from the thread is assumed 883 to be stored at the given address in the inferior. Tell gdb 884 to treat this like a real signal. */ 885 char *p; 886 int sig = strtol (s + sizeof (_CYGWIN_SIGNAL_STRING) - 1, &p, 0); 887 gdb_signal gotasig = gdb_signal_from_host (sig); 888 889 ourstatus->value.sig = gotasig; 890 if (gotasig) 891 { 892 LPCVOID x; 893 SIZE_T n; 894 895 ourstatus->kind = TARGET_WAITKIND_STOPPED; 896 retval = strtoul (p, &p, 0); 897 if (!retval) 898 retval = main_thread_id; 899 else if ((x = (LPCVOID) (uintptr_t) strtoull (p, NULL, 0)) 900 && ReadProcessMemory (current_process_handle, x, 901 &saved_context, 902 __COPY_CONTEXT_SIZE, &n) 903 && n == __COPY_CONTEXT_SIZE) 904 have_saved_context = 1; 905 } 906 } 907 #endif 908 909 if (s) 910 xfree (s); 911 return retval; 912 } 913 914 static int 915 display_selector (HANDLE thread, DWORD sel) 916 { 917 LDT_ENTRY info; 918 if (GetThreadSelectorEntry (thread, sel, &info)) 919 { 920 int base, limit; 921 printf_filtered ("0x%03x: ", (unsigned) sel); 922 if (!info.HighWord.Bits.Pres) 923 { 924 puts_filtered ("Segment not present\n"); 925 return 0; 926 } 927 base = (info.HighWord.Bits.BaseHi << 24) + 928 (info.HighWord.Bits.BaseMid << 16) 929 + info.BaseLow; 930 limit = (info.HighWord.Bits.LimitHi << 16) + info.LimitLow; 931 if (info.HighWord.Bits.Granularity) 932 limit = (limit << 12) | 0xfff; 933 printf_filtered ("base=0x%08x limit=0x%08x", base, limit); 934 if (info.HighWord.Bits.Default_Big) 935 puts_filtered(" 32-bit "); 936 else 937 puts_filtered(" 16-bit "); 938 switch ((info.HighWord.Bits.Type & 0xf) >> 1) 939 { 940 case 0: 941 puts_filtered ("Data (Read-Only, Exp-up"); 942 break; 943 case 1: 944 puts_filtered ("Data (Read/Write, Exp-up"); 945 break; 946 case 2: 947 puts_filtered ("Unused segment ("); 948 break; 949 case 3: 950 puts_filtered ("Data (Read/Write, Exp-down"); 951 break; 952 case 4: 953 puts_filtered ("Code (Exec-Only, N.Conf"); 954 break; 955 case 5: 956 puts_filtered ("Code (Exec/Read, N.Conf"); 957 break; 958 case 6: 959 puts_filtered ("Code (Exec-Only, Conf"); 960 break; 961 case 7: 962 puts_filtered ("Code (Exec/Read, Conf"); 963 break; 964 default: 965 printf_filtered ("Unknown type 0x%x",info.HighWord.Bits.Type); 966 } 967 if ((info.HighWord.Bits.Type & 0x1) == 0) 968 puts_filtered(", N.Acc"); 969 puts_filtered (")\n"); 970 if ((info.HighWord.Bits.Type & 0x10) == 0) 971 puts_filtered("System selector "); 972 printf_filtered ("Priviledge level = %d. ", info.HighWord.Bits.Dpl); 973 if (info.HighWord.Bits.Granularity) 974 puts_filtered ("Page granular.\n"); 975 else 976 puts_filtered ("Byte granular.\n"); 977 return 1; 978 } 979 else 980 { 981 DWORD err = GetLastError (); 982 if (err == ERROR_NOT_SUPPORTED) 983 printf_filtered ("Function not supported\n"); 984 else 985 printf_filtered ("Invalid selector 0x%x.\n", (unsigned) sel); 986 return 0; 987 } 988 } 989 990 static void 991 display_selectors (char * args, int from_tty) 992 { 993 if (!current_thread) 994 { 995 puts_filtered ("Impossible to display selectors now.\n"); 996 return; 997 } 998 if (!args) 999 { 1000 1001 puts_filtered ("Selector $cs\n"); 1002 display_selector (current_thread->h, 1003 current_thread->context.SegCs); 1004 puts_filtered ("Selector $ds\n"); 1005 display_selector (current_thread->h, 1006 current_thread->context.SegDs); 1007 puts_filtered ("Selector $es\n"); 1008 display_selector (current_thread->h, 1009 current_thread->context.SegEs); 1010 puts_filtered ("Selector $ss\n"); 1011 display_selector (current_thread->h, 1012 current_thread->context.SegSs); 1013 puts_filtered ("Selector $fs\n"); 1014 display_selector (current_thread->h, 1015 current_thread->context.SegFs); 1016 puts_filtered ("Selector $gs\n"); 1017 display_selector (current_thread->h, 1018 current_thread->context.SegGs); 1019 } 1020 else 1021 { 1022 int sel; 1023 sel = parse_and_eval_long (args); 1024 printf_filtered ("Selector \"%s\"\n",args); 1025 display_selector (current_thread->h, sel); 1026 } 1027 } 1028 1029 #define DEBUG_EXCEPTION_SIMPLE(x) if (debug_exceptions) \ 1030 printf_unfiltered ("gdb: Target exception %s at %s\n", x, \ 1031 host_address_to_string (\ 1032 current_event.u.Exception.ExceptionRecord.ExceptionAddress)) 1033 1034 static int 1035 handle_exception (struct target_waitstatus *ourstatus) 1036 { 1037 DWORD code = current_event.u.Exception.ExceptionRecord.ExceptionCode; 1038 1039 ourstatus->kind = TARGET_WAITKIND_STOPPED; 1040 1041 /* Record the context of the current thread. */ 1042 thread_rec (current_event.dwThreadId, -1); 1043 1044 switch (code) 1045 { 1046 case EXCEPTION_ACCESS_VIOLATION: 1047 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ACCESS_VIOLATION"); 1048 ourstatus->value.sig = GDB_SIGNAL_SEGV; 1049 #ifdef __CYGWIN__ 1050 { 1051 /* See if the access violation happened within the cygwin DLL 1052 itself. Cygwin uses a kind of exception handling to deal 1053 with passed-in invalid addresses. gdb should not treat 1054 these as real SEGVs since they will be silently handled by 1055 cygwin. A real SEGV will (theoretically) be caught by 1056 cygwin later in the process and will be sent as a 1057 cygwin-specific-signal. So, ignore SEGVs if they show up 1058 within the text segment of the DLL itself. */ 1059 const char *fn; 1060 CORE_ADDR addr = (CORE_ADDR) (uintptr_t) 1061 current_event.u.Exception.ExceptionRecord.ExceptionAddress; 1062 1063 if ((!cygwin_exceptions && (addr >= cygwin_load_start 1064 && addr < cygwin_load_end)) 1065 || (find_pc_partial_function (addr, &fn, NULL, NULL) 1066 && startswith (fn, "KERNEL32!IsBad"))) 1067 return 0; 1068 } 1069 #endif 1070 break; 1071 case STATUS_STACK_OVERFLOW: 1072 DEBUG_EXCEPTION_SIMPLE ("STATUS_STACK_OVERFLOW"); 1073 ourstatus->value.sig = GDB_SIGNAL_SEGV; 1074 break; 1075 case STATUS_FLOAT_DENORMAL_OPERAND: 1076 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DENORMAL_OPERAND"); 1077 ourstatus->value.sig = GDB_SIGNAL_FPE; 1078 break; 1079 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: 1080 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ARRAY_BOUNDS_EXCEEDED"); 1081 ourstatus->value.sig = GDB_SIGNAL_FPE; 1082 break; 1083 case STATUS_FLOAT_INEXACT_RESULT: 1084 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INEXACT_RESULT"); 1085 ourstatus->value.sig = GDB_SIGNAL_FPE; 1086 break; 1087 case STATUS_FLOAT_INVALID_OPERATION: 1088 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INVALID_OPERATION"); 1089 ourstatus->value.sig = GDB_SIGNAL_FPE; 1090 break; 1091 case STATUS_FLOAT_OVERFLOW: 1092 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_OVERFLOW"); 1093 ourstatus->value.sig = GDB_SIGNAL_FPE; 1094 break; 1095 case STATUS_FLOAT_STACK_CHECK: 1096 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_STACK_CHECK"); 1097 ourstatus->value.sig = GDB_SIGNAL_FPE; 1098 break; 1099 case STATUS_FLOAT_UNDERFLOW: 1100 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_UNDERFLOW"); 1101 ourstatus->value.sig = GDB_SIGNAL_FPE; 1102 break; 1103 case STATUS_FLOAT_DIVIDE_BY_ZERO: 1104 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DIVIDE_BY_ZERO"); 1105 ourstatus->value.sig = GDB_SIGNAL_FPE; 1106 break; 1107 case STATUS_INTEGER_DIVIDE_BY_ZERO: 1108 DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_DIVIDE_BY_ZERO"); 1109 ourstatus->value.sig = GDB_SIGNAL_FPE; 1110 break; 1111 case STATUS_INTEGER_OVERFLOW: 1112 DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_OVERFLOW"); 1113 ourstatus->value.sig = GDB_SIGNAL_FPE; 1114 break; 1115 case EXCEPTION_BREAKPOINT: 1116 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_BREAKPOINT"); 1117 ourstatus->value.sig = GDB_SIGNAL_TRAP; 1118 break; 1119 case DBG_CONTROL_C: 1120 DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_C"); 1121 ourstatus->value.sig = GDB_SIGNAL_INT; 1122 break; 1123 case DBG_CONTROL_BREAK: 1124 DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_BREAK"); 1125 ourstatus->value.sig = GDB_SIGNAL_INT; 1126 break; 1127 case EXCEPTION_SINGLE_STEP: 1128 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_SINGLE_STEP"); 1129 ourstatus->value.sig = GDB_SIGNAL_TRAP; 1130 break; 1131 case EXCEPTION_ILLEGAL_INSTRUCTION: 1132 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ILLEGAL_INSTRUCTION"); 1133 ourstatus->value.sig = GDB_SIGNAL_ILL; 1134 break; 1135 case EXCEPTION_PRIV_INSTRUCTION: 1136 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_PRIV_INSTRUCTION"); 1137 ourstatus->value.sig = GDB_SIGNAL_ILL; 1138 break; 1139 case EXCEPTION_NONCONTINUABLE_EXCEPTION: 1140 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_NONCONTINUABLE_EXCEPTION"); 1141 ourstatus->value.sig = GDB_SIGNAL_ILL; 1142 break; 1143 default: 1144 /* Treat unhandled first chance exceptions specially. */ 1145 if (current_event.u.Exception.dwFirstChance) 1146 return 0; 1147 printf_unfiltered ("gdb: unknown target exception 0x%08x at %s\n", 1148 (unsigned) current_event.u.Exception.ExceptionRecord.ExceptionCode, 1149 host_address_to_string ( 1150 current_event.u.Exception.ExceptionRecord.ExceptionAddress)); 1151 ourstatus->value.sig = GDB_SIGNAL_UNKNOWN; 1152 break; 1153 } 1154 exception_count++; 1155 last_sig = ourstatus->value.sig; 1156 return 1; 1157 } 1158 1159 /* Resume thread specified by ID, or all artificially suspended 1160 threads, if we are continuing execution. KILLED non-zero means we 1161 have killed the inferior, so we should ignore weird errors due to 1162 threads shutting down. */ 1163 static BOOL 1164 windows_continue (DWORD continue_status, int id, int killed) 1165 { 1166 int i; 1167 windows_thread_info *th; 1168 BOOL res; 1169 1170 DEBUG_EVENTS (("ContinueDebugEvent (cpid=%d, ctid=0x%x, %s);\n", 1171 (unsigned) current_event.dwProcessId, 1172 (unsigned) current_event.dwThreadId, 1173 continue_status == DBG_CONTINUE ? 1174 "DBG_CONTINUE" : "DBG_EXCEPTION_NOT_HANDLED")); 1175 1176 for (th = &thread_head; (th = th->next) != NULL;) 1177 if ((id == -1 || id == (int) th->id) 1178 && th->suspended) 1179 { 1180 if (debug_registers_changed) 1181 { 1182 th->context.ContextFlags |= CONTEXT_DEBUG_REGISTERS; 1183 th->context.Dr0 = dr[0]; 1184 th->context.Dr1 = dr[1]; 1185 th->context.Dr2 = dr[2]; 1186 th->context.Dr3 = dr[3]; 1187 th->context.Dr6 = DR6_CLEAR_VALUE; 1188 th->context.Dr7 = dr[7]; 1189 } 1190 if (th->context.ContextFlags) 1191 { 1192 DWORD ec = 0; 1193 1194 if (GetExitCodeThread (th->h, &ec) 1195 && ec == STILL_ACTIVE) 1196 { 1197 BOOL status = SetThreadContext (th->h, &th->context); 1198 1199 if (!killed) 1200 CHECK (status); 1201 } 1202 th->context.ContextFlags = 0; 1203 } 1204 if (th->suspended > 0) 1205 (void) ResumeThread (th->h); 1206 th->suspended = 0; 1207 } 1208 1209 res = ContinueDebugEvent (current_event.dwProcessId, 1210 current_event.dwThreadId, 1211 continue_status); 1212 1213 if (!res) 1214 error (_("Failed to resume program execution" 1215 " (ContinueDebugEvent failed, error %u)"), 1216 (unsigned int) GetLastError ()); 1217 1218 debug_registers_changed = 0; 1219 return res; 1220 } 1221 1222 /* Called in pathological case where Windows fails to send a 1223 CREATE_PROCESS_DEBUG_EVENT after an attach. */ 1224 static DWORD 1225 fake_create_process (void) 1226 { 1227 current_process_handle = OpenProcess (PROCESS_ALL_ACCESS, FALSE, 1228 current_event.dwProcessId); 1229 if (current_process_handle != NULL) 1230 open_process_used = 1; 1231 else 1232 { 1233 error (_("OpenProcess call failed, GetLastError = %u"), 1234 (unsigned) GetLastError ()); 1235 /* We can not debug anything in that case. */ 1236 } 1237 main_thread_id = current_event.dwThreadId; 1238 current_thread = windows_add_thread ( 1239 ptid_build (current_event.dwProcessId, 0, 1240 current_event.dwThreadId), 1241 current_event.u.CreateThread.hThread, 1242 current_event.u.CreateThread.lpThreadLocalBase); 1243 return main_thread_id; 1244 } 1245 1246 static void 1247 windows_resume (struct target_ops *ops, 1248 ptid_t ptid, int step, enum gdb_signal sig) 1249 { 1250 windows_thread_info *th; 1251 DWORD continue_status = DBG_CONTINUE; 1252 1253 /* A specific PTID means `step only this thread id'. */ 1254 int resume_all = ptid_equal (ptid, minus_one_ptid); 1255 1256 /* If we're continuing all threads, it's the current inferior that 1257 should be handled specially. */ 1258 if (resume_all) 1259 ptid = inferior_ptid; 1260 1261 if (sig != GDB_SIGNAL_0) 1262 { 1263 if (current_event.dwDebugEventCode != EXCEPTION_DEBUG_EVENT) 1264 { 1265 DEBUG_EXCEPT(("Cannot continue with signal %d here.\n",sig)); 1266 } 1267 else if (sig == last_sig) 1268 continue_status = DBG_EXCEPTION_NOT_HANDLED; 1269 else 1270 #if 0 1271 /* This code does not seem to work, because 1272 the kernel does probably not consider changes in the ExceptionRecord 1273 structure when passing the exception to the inferior. 1274 Note that this seems possible in the exception handler itself. */ 1275 { 1276 int i; 1277 for (i = 0; xlate[i].them != -1; i++) 1278 if (xlate[i].us == sig) 1279 { 1280 current_event.u.Exception.ExceptionRecord.ExceptionCode 1281 = xlate[i].them; 1282 continue_status = DBG_EXCEPTION_NOT_HANDLED; 1283 break; 1284 } 1285 if (continue_status == DBG_CONTINUE) 1286 { 1287 DEBUG_EXCEPT(("Cannot continue with signal %d.\n",sig)); 1288 } 1289 } 1290 #endif 1291 DEBUG_EXCEPT(("Can only continue with received signal %d.\n", 1292 last_sig)); 1293 } 1294 1295 last_sig = GDB_SIGNAL_0; 1296 1297 DEBUG_EXEC (("gdb: windows_resume (pid=%d, tid=%ld, step=%d, sig=%d);\n", 1298 ptid_get_pid (ptid), ptid_get_tid (ptid), step, sig)); 1299 1300 /* Get context for currently selected thread. */ 1301 th = thread_rec (ptid_get_tid (inferior_ptid), FALSE); 1302 if (th) 1303 { 1304 if (step) 1305 { 1306 /* Single step by setting t bit. */ 1307 struct regcache *regcache = get_current_regcache (); 1308 struct gdbarch *gdbarch = get_regcache_arch (regcache); 1309 windows_fetch_inferior_registers (ops, regcache, 1310 gdbarch_ps_regnum (gdbarch)); 1311 th->context.EFlags |= FLAG_TRACE_BIT; 1312 } 1313 1314 if (th->context.ContextFlags) 1315 { 1316 if (debug_registers_changed) 1317 { 1318 th->context.Dr0 = dr[0]; 1319 th->context.Dr1 = dr[1]; 1320 th->context.Dr2 = dr[2]; 1321 th->context.Dr3 = dr[3]; 1322 th->context.Dr6 = DR6_CLEAR_VALUE; 1323 th->context.Dr7 = dr[7]; 1324 } 1325 CHECK (SetThreadContext (th->h, &th->context)); 1326 th->context.ContextFlags = 0; 1327 } 1328 } 1329 1330 /* Allow continuing with the same signal that interrupted us. 1331 Otherwise complain. */ 1332 1333 if (resume_all) 1334 windows_continue (continue_status, -1, 0); 1335 else 1336 windows_continue (continue_status, ptid_get_tid (ptid), 0); 1337 } 1338 1339 /* Ctrl-C handler used when the inferior is not run in the same console. The 1340 handler is in charge of interrupting the inferior using DebugBreakProcess. 1341 Note that this function is not available prior to Windows XP. In this case 1342 we emit a warning. */ 1343 static BOOL WINAPI 1344 ctrl_c_handler (DWORD event_type) 1345 { 1346 const int attach_flag = current_inferior ()->attach_flag; 1347 1348 /* Only handle Ctrl-C and Ctrl-Break events. Ignore others. */ 1349 if (event_type != CTRL_C_EVENT && event_type != CTRL_BREAK_EVENT) 1350 return FALSE; 1351 1352 /* If the inferior and the debugger share the same console, do nothing as 1353 the inferior has also received the Ctrl-C event. */ 1354 if (!new_console && !attach_flag) 1355 return TRUE; 1356 1357 if (!DebugBreakProcess (current_process_handle)) 1358 warning (_("Could not interrupt program. " 1359 "Press Ctrl-c in the program console.")); 1360 1361 /* Return true to tell that Ctrl-C has been handled. */ 1362 return TRUE; 1363 } 1364 1365 /* Get the next event from the child. Returns a non-zero thread id if the event 1366 requires handling by WFI (or whatever). */ 1367 static int 1368 get_windows_debug_event (struct target_ops *ops, 1369 int pid, struct target_waitstatus *ourstatus) 1370 { 1371 BOOL debug_event; 1372 DWORD continue_status, event_code; 1373 windows_thread_info *th; 1374 static windows_thread_info dummy_thread_info; 1375 DWORD thread_id = 0; 1376 1377 last_sig = GDB_SIGNAL_0; 1378 1379 if (!(debug_event = WaitForDebugEvent (¤t_event, 1000))) 1380 goto out; 1381 1382 event_count++; 1383 continue_status = DBG_CONTINUE; 1384 1385 event_code = current_event.dwDebugEventCode; 1386 ourstatus->kind = TARGET_WAITKIND_SPURIOUS; 1387 th = NULL; 1388 have_saved_context = 0; 1389 1390 switch (event_code) 1391 { 1392 case CREATE_THREAD_DEBUG_EVENT: 1393 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n", 1394 (unsigned) current_event.dwProcessId, 1395 (unsigned) current_event.dwThreadId, 1396 "CREATE_THREAD_DEBUG_EVENT")); 1397 if (saw_create != 1) 1398 { 1399 struct inferior *inf; 1400 inf = find_inferior_pid (current_event.dwProcessId); 1401 if (!saw_create && inf->attach_flag) 1402 { 1403 /* Kludge around a Windows bug where first event is a create 1404 thread event. Caused when attached process does not have 1405 a main thread. */ 1406 thread_id = fake_create_process (); 1407 if (thread_id) 1408 saw_create++; 1409 } 1410 break; 1411 } 1412 /* Record the existence of this thread. */ 1413 thread_id = current_event.dwThreadId; 1414 th = windows_add_thread (ptid_build (current_event.dwProcessId, 0, 1415 current_event.dwThreadId), 1416 current_event.u.CreateThread.hThread, 1417 current_event.u.CreateThread.lpThreadLocalBase); 1418 1419 break; 1420 1421 case EXIT_THREAD_DEBUG_EVENT: 1422 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n", 1423 (unsigned) current_event.dwProcessId, 1424 (unsigned) current_event.dwThreadId, 1425 "EXIT_THREAD_DEBUG_EVENT")); 1426 1427 if (current_event.dwThreadId != main_thread_id) 1428 { 1429 windows_delete_thread (ptid_build (current_event.dwProcessId, 0, 1430 current_event.dwThreadId), 1431 current_event.u.ExitThread.dwExitCode); 1432 th = &dummy_thread_info; 1433 } 1434 break; 1435 1436 case CREATE_PROCESS_DEBUG_EVENT: 1437 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n", 1438 (unsigned) current_event.dwProcessId, 1439 (unsigned) current_event.dwThreadId, 1440 "CREATE_PROCESS_DEBUG_EVENT")); 1441 CloseHandle (current_event.u.CreateProcessInfo.hFile); 1442 if (++saw_create != 1) 1443 break; 1444 1445 current_process_handle = current_event.u.CreateProcessInfo.hProcess; 1446 if (main_thread_id) 1447 windows_delete_thread (ptid_build (current_event.dwProcessId, 0, 1448 main_thread_id), 1449 0); 1450 main_thread_id = current_event.dwThreadId; 1451 /* Add the main thread. */ 1452 th = windows_add_thread (ptid_build (current_event.dwProcessId, 0, 1453 current_event.dwThreadId), 1454 current_event.u.CreateProcessInfo.hThread, 1455 current_event.u.CreateProcessInfo.lpThreadLocalBase); 1456 thread_id = current_event.dwThreadId; 1457 break; 1458 1459 case EXIT_PROCESS_DEBUG_EVENT: 1460 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n", 1461 (unsigned) current_event.dwProcessId, 1462 (unsigned) current_event.dwThreadId, 1463 "EXIT_PROCESS_DEBUG_EVENT")); 1464 if (!windows_initialization_done) 1465 { 1466 target_terminal_ours (); 1467 target_mourn_inferior (); 1468 error (_("During startup program exited with code 0x%x."), 1469 (unsigned int) current_event.u.ExitProcess.dwExitCode); 1470 } 1471 else if (saw_create == 1) 1472 { 1473 ourstatus->kind = TARGET_WAITKIND_EXITED; 1474 ourstatus->value.integer = current_event.u.ExitProcess.dwExitCode; 1475 thread_id = main_thread_id; 1476 } 1477 break; 1478 1479 case LOAD_DLL_DEBUG_EVENT: 1480 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n", 1481 (unsigned) current_event.dwProcessId, 1482 (unsigned) current_event.dwThreadId, 1483 "LOAD_DLL_DEBUG_EVENT")); 1484 CloseHandle (current_event.u.LoadDll.hFile); 1485 if (saw_create != 1 || ! windows_initialization_done) 1486 break; 1487 catch_errors (handle_load_dll, NULL, (char *) "", RETURN_MASK_ALL); 1488 ourstatus->kind = TARGET_WAITKIND_LOADED; 1489 ourstatus->value.integer = 0; 1490 thread_id = main_thread_id; 1491 break; 1492 1493 case UNLOAD_DLL_DEBUG_EVENT: 1494 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n", 1495 (unsigned) current_event.dwProcessId, 1496 (unsigned) current_event.dwThreadId, 1497 "UNLOAD_DLL_DEBUG_EVENT")); 1498 if (saw_create != 1 || ! windows_initialization_done) 1499 break; 1500 catch_errors (handle_unload_dll, NULL, (char *) "", RETURN_MASK_ALL); 1501 ourstatus->kind = TARGET_WAITKIND_LOADED; 1502 ourstatus->value.integer = 0; 1503 thread_id = main_thread_id; 1504 break; 1505 1506 case EXCEPTION_DEBUG_EVENT: 1507 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n", 1508 (unsigned) current_event.dwProcessId, 1509 (unsigned) current_event.dwThreadId, 1510 "EXCEPTION_DEBUG_EVENT")); 1511 if (saw_create != 1) 1512 break; 1513 if (handle_exception (ourstatus)) 1514 thread_id = current_event.dwThreadId; 1515 else 1516 continue_status = DBG_EXCEPTION_NOT_HANDLED; 1517 break; 1518 1519 case OUTPUT_DEBUG_STRING_EVENT: /* Message from the kernel. */ 1520 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n", 1521 (unsigned) current_event.dwProcessId, 1522 (unsigned) current_event.dwThreadId, 1523 "OUTPUT_DEBUG_STRING_EVENT")); 1524 if (saw_create != 1) 1525 break; 1526 thread_id = handle_output_debug_string (ourstatus); 1527 break; 1528 1529 default: 1530 if (saw_create != 1) 1531 break; 1532 printf_unfiltered ("gdb: kernel event for pid=%u tid=0x%x\n", 1533 (unsigned) current_event.dwProcessId, 1534 (unsigned) current_event.dwThreadId); 1535 printf_unfiltered (" unknown event code %u\n", 1536 (unsigned) current_event.dwDebugEventCode); 1537 break; 1538 } 1539 1540 if (!thread_id || saw_create != 1) 1541 { 1542 CHECK (windows_continue (continue_status, -1, 0)); 1543 } 1544 else 1545 { 1546 inferior_ptid = ptid_build (current_event.dwProcessId, 0, 1547 thread_id); 1548 current_thread = th; 1549 if (!current_thread) 1550 current_thread = thread_rec (thread_id, TRUE); 1551 } 1552 1553 out: 1554 return thread_id; 1555 } 1556 1557 /* Wait for interesting events to occur in the target process. */ 1558 static ptid_t 1559 windows_wait (struct target_ops *ops, 1560 ptid_t ptid, struct target_waitstatus *ourstatus, int options) 1561 { 1562 int pid = -1; 1563 1564 target_terminal_ours (); 1565 1566 /* We loop when we get a non-standard exception rather than return 1567 with a SPURIOUS because resume can try and step or modify things, 1568 which needs a current_thread->h. But some of these exceptions mark 1569 the birth or death of threads, which mean that the current thread 1570 isn't necessarily what you think it is. */ 1571 1572 while (1) 1573 { 1574 int retval; 1575 1576 /* If the user presses Ctrl-c while the debugger is waiting 1577 for an event, he expects the debugger to interrupt his program 1578 and to get the prompt back. There are two possible situations: 1579 1580 - The debugger and the program do not share the console, in 1581 which case the Ctrl-c event only reached the debugger. 1582 In that case, the ctrl_c handler will take care of interrupting 1583 the inferior. Note that this case is working starting with 1584 Windows XP. For Windows 2000, Ctrl-C should be pressed in the 1585 inferior console. 1586 1587 - The debugger and the program share the same console, in which 1588 case both debugger and inferior will receive the Ctrl-c event. 1589 In that case the ctrl_c handler will ignore the event, as the 1590 Ctrl-c event generated inside the inferior will trigger the 1591 expected debug event. 1592 1593 FIXME: brobecker/2008-05-20: If the inferior receives the 1594 signal first and the delay until GDB receives that signal 1595 is sufficiently long, GDB can sometimes receive the SIGINT 1596 after we have unblocked the CTRL+C handler. This would 1597 lead to the debugger stopping prematurely while handling 1598 the new-thread event that comes with the handling of the SIGINT 1599 inside the inferior, and then stop again immediately when 1600 the user tries to resume the execution in the inferior. 1601 This is a classic race that we should try to fix one day. */ 1602 SetConsoleCtrlHandler (&ctrl_c_handler, TRUE); 1603 retval = get_windows_debug_event (ops, pid, ourstatus); 1604 SetConsoleCtrlHandler (&ctrl_c_handler, FALSE); 1605 1606 if (retval) 1607 return ptid_build (current_event.dwProcessId, 0, retval); 1608 else 1609 { 1610 int detach = 0; 1611 1612 if (deprecated_ui_loop_hook != NULL) 1613 detach = deprecated_ui_loop_hook (0); 1614 1615 if (detach) 1616 windows_kill_inferior (ops); 1617 } 1618 } 1619 } 1620 1621 /* Iterate over all DLLs currently mapped by our inferior, and 1622 add them to our list of solibs. */ 1623 1624 static void 1625 windows_add_all_dlls (void) 1626 { 1627 struct so_list *so; 1628 HMODULE dummy_hmodule; 1629 DWORD cb_needed; 1630 HMODULE *hmodules; 1631 int i; 1632 1633 if (EnumProcessModules (current_process_handle, &dummy_hmodule, 1634 sizeof (HMODULE), &cb_needed) == 0) 1635 return; 1636 1637 if (cb_needed < 1) 1638 return; 1639 1640 hmodules = (HMODULE *) alloca (cb_needed); 1641 if (EnumProcessModules (current_process_handle, hmodules, 1642 cb_needed, &cb_needed) == 0) 1643 return; 1644 1645 for (i = 1; i < (int) (cb_needed / sizeof (HMODULE)); i++) 1646 { 1647 MODULEINFO mi; 1648 #ifdef __USEWIDE 1649 wchar_t dll_name[__PMAX]; 1650 char name[__PMAX]; 1651 #else 1652 char dll_name[__PMAX]; 1653 char *name; 1654 #endif 1655 if (GetModuleInformation (current_process_handle, hmodules[i], 1656 &mi, sizeof (mi)) == 0) 1657 continue; 1658 if (GetModuleFileNameEx (current_process_handle, hmodules[i], 1659 dll_name, sizeof (dll_name)) == 0) 1660 continue; 1661 #ifdef __USEWIDE 1662 wcstombs (name, dll_name, __PMAX); 1663 #else 1664 name = dll_name; 1665 #endif 1666 1667 solib_end->next = windows_make_so (name, mi.lpBaseOfDll); 1668 solib_end = solib_end->next; 1669 } 1670 } 1671 1672 static void 1673 do_initial_windows_stuff (struct target_ops *ops, DWORD pid, int attaching) 1674 { 1675 int i; 1676 struct inferior *inf; 1677 struct thread_info *tp; 1678 1679 last_sig = GDB_SIGNAL_0; 1680 event_count = 0; 1681 exception_count = 0; 1682 open_process_used = 0; 1683 debug_registers_changed = 0; 1684 debug_registers_used = 0; 1685 for (i = 0; i < sizeof (dr) / sizeof (dr[0]); i++) 1686 dr[i] = 0; 1687 #ifdef __CYGWIN__ 1688 cygwin_load_start = cygwin_load_end = 0; 1689 #endif 1690 current_event.dwProcessId = pid; 1691 memset (¤t_event, 0, sizeof (current_event)); 1692 if (!target_is_pushed (ops)) 1693 push_target (ops); 1694 disable_breakpoints_in_shlibs (); 1695 windows_clear_solib (); 1696 clear_proceed_status (0); 1697 init_wait_for_inferior (); 1698 1699 inf = current_inferior (); 1700 inferior_appeared (inf, pid); 1701 inf->attach_flag = attaching; 1702 1703 /* Make the new process the current inferior, so terminal handling 1704 can rely on it. When attaching, we don't know about any thread 1705 id here, but that's OK --- nothing should be referencing the 1706 current thread until we report an event out of windows_wait. */ 1707 inferior_ptid = pid_to_ptid (pid); 1708 1709 target_terminal_init (); 1710 target_terminal_inferior (); 1711 1712 windows_initialization_done = 0; 1713 1714 while (1) 1715 { 1716 struct target_waitstatus status; 1717 1718 windows_wait (ops, minus_one_ptid, &status, 0); 1719 1720 /* Note windows_wait returns TARGET_WAITKIND_SPURIOUS for thread 1721 events. */ 1722 if (status.kind != TARGET_WAITKIND_LOADED 1723 && status.kind != TARGET_WAITKIND_SPURIOUS) 1724 break; 1725 1726 windows_resume (ops, minus_one_ptid, 0, GDB_SIGNAL_0); 1727 } 1728 1729 /* Now that the inferior has been started and all DLLs have been mapped, 1730 we can iterate over all DLLs and load them in. 1731 1732 We avoid doing it any earlier because, on certain versions of Windows, 1733 LOAD_DLL_DEBUG_EVENTs are sometimes not complete. In particular, 1734 we have seen on Windows 8.1 that the ntdll.dll load event does not 1735 include the DLL name, preventing us from creating an associated SO. 1736 A possible explanation is that ntdll.dll might be mapped before 1737 the SO info gets created by the Windows system -- ntdll.dll is 1738 the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs 1739 do not seem to suffer from that problem. 1740 1741 Rather than try to work around this sort of issue, it is much 1742 simpler to just ignore DLL load/unload events during the startup 1743 phase, and then process them all in one batch now. */ 1744 windows_add_all_dlls (); 1745 1746 windows_initialization_done = 1; 1747 return; 1748 } 1749 1750 /* Try to set or remove a user privilege to the current process. Return -1 1751 if that fails, the previous setting of that privilege otherwise. 1752 1753 This code is copied from the Cygwin source code and rearranged to allow 1754 dynamically loading of the needed symbols from advapi32 which is only 1755 available on NT/2K/XP. */ 1756 static int 1757 set_process_privilege (const char *privilege, BOOL enable) 1758 { 1759 HANDLE token_hdl = NULL; 1760 LUID restore_priv; 1761 TOKEN_PRIVILEGES new_priv, orig_priv; 1762 int ret = -1; 1763 DWORD size; 1764 1765 if (!OpenProcessToken (GetCurrentProcess (), 1766 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES, 1767 &token_hdl)) 1768 goto out; 1769 1770 if (!LookupPrivilegeValueA (NULL, privilege, &restore_priv)) 1771 goto out; 1772 1773 new_priv.PrivilegeCount = 1; 1774 new_priv.Privileges[0].Luid = restore_priv; 1775 new_priv.Privileges[0].Attributes = enable ? SE_PRIVILEGE_ENABLED : 0; 1776 1777 if (!AdjustTokenPrivileges (token_hdl, FALSE, &new_priv, 1778 sizeof orig_priv, &orig_priv, &size)) 1779 goto out; 1780 #if 0 1781 /* Disabled, otherwise every `attach' in an unprivileged user session 1782 would raise the "Failed to get SE_DEBUG_NAME privilege" warning in 1783 windows_attach(). */ 1784 /* AdjustTokenPrivileges returns TRUE even if the privilege could not 1785 be enabled. GetLastError () returns an correct error code, though. */ 1786 if (enable && GetLastError () == ERROR_NOT_ALL_ASSIGNED) 1787 goto out; 1788 #endif 1789 1790 ret = orig_priv.Privileges[0].Attributes == SE_PRIVILEGE_ENABLED ? 1 : 0; 1791 1792 out: 1793 if (token_hdl) 1794 CloseHandle (token_hdl); 1795 1796 return ret; 1797 } 1798 1799 /* Attach to process PID, then initialize for debugging it. */ 1800 static void 1801 windows_attach (struct target_ops *ops, const char *args, int from_tty) 1802 { 1803 BOOL ok; 1804 DWORD pid; 1805 1806 pid = parse_pid_to_attach (args); 1807 1808 if (set_process_privilege (SE_DEBUG_NAME, TRUE) < 0) 1809 { 1810 printf_unfiltered ("Warning: Failed to get SE_DEBUG_NAME privilege\n"); 1811 printf_unfiltered ("This can cause attach to " 1812 "fail on Windows NT/2K/XP\n"); 1813 } 1814 1815 windows_init_thread_list (); 1816 ok = DebugActiveProcess (pid); 1817 saw_create = 0; 1818 1819 #ifdef __CYGWIN__ 1820 if (!ok) 1821 { 1822 /* Try fall back to Cygwin pid. */ 1823 pid = cygwin_internal (CW_CYGWIN_PID_TO_WINPID, pid); 1824 1825 if (pid > 0) 1826 ok = DebugActiveProcess (pid); 1827 } 1828 #endif 1829 1830 if (!ok) 1831 error (_("Can't attach to process.")); 1832 1833 DebugSetProcessKillOnExit (FALSE); 1834 1835 if (from_tty) 1836 { 1837 char *exec_file = (char *) get_exec_file (0); 1838 1839 if (exec_file) 1840 printf_unfiltered ("Attaching to program `%s', %s\n", exec_file, 1841 target_pid_to_str (pid_to_ptid (pid))); 1842 else 1843 printf_unfiltered ("Attaching to %s\n", 1844 target_pid_to_str (pid_to_ptid (pid))); 1845 1846 gdb_flush (gdb_stdout); 1847 } 1848 1849 do_initial_windows_stuff (ops, pid, 1); 1850 target_terminal_ours (); 1851 } 1852 1853 static void 1854 windows_detach (struct target_ops *ops, const char *args, int from_tty) 1855 { 1856 int detached = 1; 1857 1858 ptid_t ptid = {-1}; 1859 windows_resume (ops, ptid, 0, GDB_SIGNAL_0); 1860 1861 if (!DebugActiveProcessStop (current_event.dwProcessId)) 1862 { 1863 error (_("Can't detach process %u (error %u)"), 1864 (unsigned) current_event.dwProcessId, (unsigned) GetLastError ()); 1865 detached = 0; 1866 } 1867 DebugSetProcessKillOnExit (FALSE); 1868 1869 if (detached && from_tty) 1870 { 1871 char *exec_file = get_exec_file (0); 1872 if (exec_file == 0) 1873 exec_file = ""; 1874 printf_unfiltered ("Detaching from program: %s, Pid %u\n", exec_file, 1875 (unsigned) current_event.dwProcessId); 1876 gdb_flush (gdb_stdout); 1877 } 1878 1879 x86_cleanup_dregs (); 1880 inferior_ptid = null_ptid; 1881 detach_inferior (current_event.dwProcessId); 1882 1883 inf_child_maybe_unpush_target (ops); 1884 } 1885 1886 /* Try to determine the executable filename. 1887 1888 EXE_NAME_RET is a pointer to a buffer whose size is EXE_NAME_MAX_LEN. 1889 1890 Upon success, the filename is stored inside EXE_NAME_RET, and 1891 this function returns nonzero. 1892 1893 Otherwise, this function returns zero and the contents of 1894 EXE_NAME_RET is undefined. */ 1895 1896 static int 1897 windows_get_exec_module_filename (char *exe_name_ret, size_t exe_name_max_len) 1898 { 1899 DWORD len; 1900 HMODULE dh_buf; 1901 DWORD cbNeeded; 1902 1903 cbNeeded = 0; 1904 if (!EnumProcessModules (current_process_handle, &dh_buf, 1905 sizeof (HMODULE), &cbNeeded) || !cbNeeded) 1906 return 0; 1907 1908 /* We know the executable is always first in the list of modules, 1909 which we just fetched. So no need to fetch more. */ 1910 1911 #ifdef __CYGWIN__ 1912 { 1913 /* Cygwin prefers that the path be in /x/y/z format, so extract 1914 the filename into a temporary buffer first, and then convert it 1915 to POSIX format into the destination buffer. */ 1916 cygwin_buf_t *pathbuf = (cygwin_buf_t *) alloca (exe_name_max_len * sizeof (cygwin_buf_t)); 1917 1918 len = GetModuleFileNameEx (current_process_handle, 1919 dh_buf, pathbuf, exe_name_max_len); 1920 if (len == 0) 1921 error (_("Error getting executable filename: %u."), 1922 (unsigned) GetLastError ()); 1923 if (cygwin_conv_path (CCP_WIN_W_TO_POSIX, pathbuf, exe_name_ret, 1924 exe_name_max_len) < 0) 1925 error (_("Error converting executable filename to POSIX: %d."), errno); 1926 } 1927 #else 1928 len = GetModuleFileNameEx (current_process_handle, 1929 dh_buf, exe_name_ret, exe_name_max_len); 1930 if (len == 0) 1931 error (_("Error getting executable filename: %u."), 1932 (unsigned) GetLastError ()); 1933 #endif 1934 1935 return 1; /* success */ 1936 } 1937 1938 /* The pid_to_exec_file target_ops method for this platform. */ 1939 1940 static char * 1941 windows_pid_to_exec_file (struct target_ops *self, int pid) 1942 { 1943 static char path[__PMAX]; 1944 #ifdef __CYGWIN__ 1945 /* Try to find exe name as symlink target of /proc/<pid>/exe. */ 1946 int nchars; 1947 char procexe[sizeof ("/proc/4294967295/exe")]; 1948 1949 xsnprintf (procexe, sizeof (procexe), "/proc/%u/exe", pid); 1950 nchars = readlink (procexe, path, sizeof(path)); 1951 if (nchars > 0 && nchars < sizeof (path)) 1952 { 1953 path[nchars] = '\0'; /* Got it */ 1954 return path; 1955 } 1956 #endif 1957 1958 /* If we get here then either Cygwin is hosed, this isn't a Cygwin version 1959 of gdb, or we're trying to debug a non-Cygwin windows executable. */ 1960 if (!windows_get_exec_module_filename (path, sizeof (path))) 1961 path[0] = '\0'; 1962 1963 return path; 1964 } 1965 1966 /* Print status information about what we're accessing. */ 1967 1968 static void 1969 windows_files_info (struct target_ops *ignore) 1970 { 1971 struct inferior *inf = current_inferior (); 1972 1973 printf_unfiltered ("\tUsing the running image of %s %s.\n", 1974 inf->attach_flag ? "attached" : "child", 1975 target_pid_to_str (inferior_ptid)); 1976 } 1977 1978 /* Modify CreateProcess parameters for use of a new separate console. 1979 Parameters are: 1980 *FLAGS: DWORD parameter for general process creation flags. 1981 *SI: STARTUPINFO structure, for which the console window size and 1982 console buffer size is filled in if GDB is running in a console. 1983 to create the new console. 1984 The size of the used font is not available on all versions of 1985 Windows OS. Furthermore, the current font might not be the default 1986 font, but this is still better than before. 1987 If the windows and buffer sizes are computed, 1988 SI->DWFLAGS is changed so that this information is used 1989 by CreateProcess function. */ 1990 1991 static void 1992 windows_set_console_info (STARTUPINFO *si, DWORD *flags) 1993 { 1994 HANDLE hconsole = CreateFile ("CONOUT$", GENERIC_READ | GENERIC_WRITE, 1995 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0); 1996 1997 if (hconsole != INVALID_HANDLE_VALUE) 1998 { 1999 CONSOLE_SCREEN_BUFFER_INFO sbinfo; 2000 COORD font_size; 2001 CONSOLE_FONT_INFO cfi; 2002 2003 GetCurrentConsoleFont (hconsole, FALSE, &cfi); 2004 font_size = GetConsoleFontSize (hconsole, cfi.nFont); 2005 GetConsoleScreenBufferInfo(hconsole, &sbinfo); 2006 si->dwXSize = sbinfo.srWindow.Right - sbinfo.srWindow.Left + 1; 2007 si->dwYSize = sbinfo.srWindow.Bottom - sbinfo.srWindow.Top + 1; 2008 if (font_size.X) 2009 si->dwXSize *= font_size.X; 2010 else 2011 si->dwXSize *= 8; 2012 if (font_size.Y) 2013 si->dwYSize *= font_size.Y; 2014 else 2015 si->dwYSize *= 12; 2016 si->dwXCountChars = sbinfo.dwSize.X; 2017 si->dwYCountChars = sbinfo.dwSize.Y; 2018 si->dwFlags |= STARTF_USESIZE | STARTF_USECOUNTCHARS; 2019 } 2020 *flags |= CREATE_NEW_CONSOLE; 2021 } 2022 2023 #ifndef __CYGWIN__ 2024 /* Function called by qsort to sort environment strings. */ 2025 2026 static int 2027 envvar_cmp (const void *a, const void *b) 2028 { 2029 const char **p = (const char **) a; 2030 const char **q = (const char **) b; 2031 return strcasecmp (*p, *q); 2032 } 2033 #endif 2034 2035 #ifdef __CYGWIN__ 2036 static void 2037 clear_win32_environment (char **env) 2038 { 2039 int i; 2040 size_t len; 2041 wchar_t *copy = NULL, *equalpos; 2042 2043 for (i = 0; env[i] && *env[i]; i++) 2044 { 2045 len = mbstowcs (NULL, env[i], 0) + 1; 2046 copy = (wchar_t *) xrealloc (copy, len * sizeof (wchar_t)); 2047 mbstowcs (copy, env[i], len); 2048 equalpos = wcschr (copy, L'='); 2049 if (equalpos) 2050 *equalpos = L'\0'; 2051 SetEnvironmentVariableW (copy, NULL); 2052 } 2053 xfree (copy); 2054 } 2055 #endif 2056 2057 /* Start an inferior windows child process and sets inferior_ptid to its pid. 2058 EXEC_FILE is the file to run. 2059 ALLARGS is a string containing the arguments to the program. 2060 ENV is the environment vector to pass. Errors reported with error(). */ 2061 2062 static void 2063 windows_create_inferior (struct target_ops *ops, char *exec_file, 2064 char *allargs, char **in_env, int from_tty) 2065 { 2066 STARTUPINFO si; 2067 #ifdef __CYGWIN__ 2068 cygwin_buf_t real_path[__PMAX]; 2069 cygwin_buf_t shell[__PMAX]; /* Path to shell */ 2070 const char *sh; 2071 cygwin_buf_t *toexec; 2072 cygwin_buf_t *cygallargs; 2073 cygwin_buf_t *args; 2074 char **old_env = NULL; 2075 PWCHAR w32_env; 2076 size_t len; 2077 int tty; 2078 int ostdin, ostdout, ostderr; 2079 #else 2080 char real_path[__PMAX]; 2081 char shell[__PMAX]; /* Path to shell */ 2082 char *toexec; 2083 char *args; 2084 size_t args_len; 2085 HANDLE tty; 2086 char *w32env; 2087 char *temp; 2088 size_t envlen; 2089 int i; 2090 size_t envsize; 2091 char **env; 2092 #endif 2093 PROCESS_INFORMATION pi; 2094 BOOL ret; 2095 DWORD flags = 0; 2096 const char *inferior_io_terminal = get_inferior_io_terminal (); 2097 2098 if (!exec_file) 2099 error (_("No executable specified, use `target exec'.")); 2100 2101 memset (&si, 0, sizeof (si)); 2102 si.cb = sizeof (si); 2103 2104 if (new_group) 2105 flags |= CREATE_NEW_PROCESS_GROUP; 2106 2107 if (new_console) 2108 windows_set_console_info (&si, &flags); 2109 2110 #ifdef __CYGWIN__ 2111 if (!useshell) 2112 { 2113 flags |= DEBUG_ONLY_THIS_PROCESS; 2114 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, exec_file, real_path, 2115 __PMAX * sizeof (cygwin_buf_t)) < 0) 2116 error (_("Error starting executable: %d"), errno); 2117 toexec = real_path; 2118 #ifdef __USEWIDE 2119 len = mbstowcs (NULL, allargs, 0) + 1; 2120 if (len == (size_t) -1) 2121 error (_("Error starting executable: %d"), errno); 2122 cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t)); 2123 mbstowcs (cygallargs, allargs, len); 2124 #else 2125 cygallargs = allargs; 2126 #endif 2127 } 2128 else 2129 { 2130 sh = getenv ("SHELL"); 2131 if (!sh) 2132 sh = "/bin/sh"; 2133 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, sh, shell, __PMAX) < 0) 2134 error (_("Error starting executable via shell: %d"), errno); 2135 #ifdef __USEWIDE 2136 len = sizeof (L" -c 'exec '") + mbstowcs (NULL, exec_file, 0) 2137 + mbstowcs (NULL, allargs, 0) + 2; 2138 cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t)); 2139 swprintf (cygallargs, len, L" -c 'exec %s %s'", exec_file, allargs); 2140 #else 2141 len = (sizeof (" -c 'exec '") + strlen (exec_file) 2142 + strlen (allargs) + 2); 2143 cygallargs = (char *) alloca (len); 2144 xsnprintf (cygallargs, len, " -c 'exec %s %s'", exec_file, allargs); 2145 #endif 2146 toexec = shell; 2147 flags |= DEBUG_PROCESS; 2148 } 2149 2150 #ifdef __USEWIDE 2151 args = (cygwin_buf_t *) alloca ((wcslen (toexec) + wcslen (cygallargs) + 2) 2152 * sizeof (wchar_t)); 2153 wcscpy (args, toexec); 2154 wcscat (args, L" "); 2155 wcscat (args, cygallargs); 2156 #else 2157 args = (cygwin_buf_t *) alloca (strlen (toexec) + strlen (cygallargs) + 2); 2158 strcpy (args, toexec); 2159 strcat (args, " "); 2160 strcat (args, cygallargs); 2161 #endif 2162 2163 #ifdef CW_CVT_ENV_TO_WINENV 2164 /* First try to create a direct Win32 copy of the POSIX environment. */ 2165 w32_env = (PWCHAR) cygwin_internal (CW_CVT_ENV_TO_WINENV, in_env); 2166 if (w32_env != (PWCHAR) -1) 2167 flags |= CREATE_UNICODE_ENVIRONMENT; 2168 else 2169 /* If that fails, fall back to old method tweaking GDB's environment. */ 2170 #endif 2171 { 2172 /* Reset all Win32 environment variables to avoid leftover on next run. */ 2173 clear_win32_environment (environ); 2174 /* Prepare the environment vars for CreateProcess. */ 2175 old_env = environ; 2176 environ = in_env; 2177 cygwin_internal (CW_SYNC_WINENV); 2178 w32_env = NULL; 2179 } 2180 2181 if (!inferior_io_terminal) 2182 tty = ostdin = ostdout = ostderr = -1; 2183 else 2184 { 2185 tty = open (inferior_io_terminal, O_RDWR | O_NOCTTY); 2186 if (tty < 0) 2187 { 2188 print_sys_errmsg (inferior_io_terminal, errno); 2189 ostdin = ostdout = ostderr = -1; 2190 } 2191 else 2192 { 2193 ostdin = dup (0); 2194 ostdout = dup (1); 2195 ostderr = dup (2); 2196 dup2 (tty, 0); 2197 dup2 (tty, 1); 2198 dup2 (tty, 2); 2199 } 2200 } 2201 2202 windows_init_thread_list (); 2203 ret = CreateProcess (0, 2204 args, /* command line */ 2205 NULL, /* Security */ 2206 NULL, /* thread */ 2207 TRUE, /* inherit handles */ 2208 flags, /* start flags */ 2209 w32_env, /* environment */ 2210 NULL, /* current directory */ 2211 &si, 2212 &pi); 2213 if (w32_env) 2214 /* Just free the Win32 environment, if it could be created. */ 2215 free (w32_env); 2216 else 2217 { 2218 /* Reset all environment variables to avoid leftover on next run. */ 2219 clear_win32_environment (in_env); 2220 /* Restore normal GDB environment variables. */ 2221 environ = old_env; 2222 cygwin_internal (CW_SYNC_WINENV); 2223 } 2224 2225 if (tty >= 0) 2226 { 2227 close (tty); 2228 dup2 (ostdin, 0); 2229 dup2 (ostdout, 1); 2230 dup2 (ostderr, 2); 2231 close (ostdin); 2232 close (ostdout); 2233 close (ostderr); 2234 } 2235 #else 2236 toexec = exec_file; 2237 /* Build the command line, a space-separated list of tokens where 2238 the first token is the name of the module to be executed. 2239 To avoid ambiguities introduced by spaces in the module name, 2240 we quote it. */ 2241 args_len = strlen (toexec) + 2 /* quotes */ + strlen (allargs) + 2; 2242 args = (char *) alloca (args_len); 2243 xsnprintf (args, args_len, "\"%s\" %s", toexec, allargs); 2244 2245 flags |= DEBUG_ONLY_THIS_PROCESS; 2246 2247 if (!inferior_io_terminal) 2248 tty = INVALID_HANDLE_VALUE; 2249 else 2250 { 2251 SECURITY_ATTRIBUTES sa; 2252 sa.nLength = sizeof(sa); 2253 sa.lpSecurityDescriptor = 0; 2254 sa.bInheritHandle = TRUE; 2255 tty = CreateFileA (inferior_io_terminal, GENERIC_READ | GENERIC_WRITE, 2256 0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); 2257 if (tty == INVALID_HANDLE_VALUE) 2258 warning (_("Warning: Failed to open TTY %s, error %#x."), 2259 inferior_io_terminal, (unsigned) GetLastError ()); 2260 else 2261 { 2262 si.hStdInput = tty; 2263 si.hStdOutput = tty; 2264 si.hStdError = tty; 2265 si.dwFlags |= STARTF_USESTDHANDLES; 2266 } 2267 } 2268 2269 /* CreateProcess takes the environment list as a null terminated set of 2270 strings (i.e. two nulls terminate the list). */ 2271 2272 /* Get total size for env strings. */ 2273 for (envlen = 0, i = 0; in_env[i] && *in_env[i]; i++) 2274 envlen += strlen (in_env[i]) + 1; 2275 2276 envsize = sizeof (in_env[0]) * (i + 1); 2277 env = (char **) alloca (envsize); 2278 memcpy (env, in_env, envsize); 2279 /* Windows programs expect the environment block to be sorted. */ 2280 qsort (env, i, sizeof (char *), envvar_cmp); 2281 2282 w32env = (char *) alloca (envlen + 1); 2283 2284 /* Copy env strings into new buffer. */ 2285 for (temp = w32env, i = 0; env[i] && *env[i]; i++) 2286 { 2287 strcpy (temp, env[i]); 2288 temp += strlen (temp) + 1; 2289 } 2290 2291 /* Final nil string to terminate new env. */ 2292 *temp = 0; 2293 2294 windows_init_thread_list (); 2295 ret = CreateProcessA (0, 2296 args, /* command line */ 2297 NULL, /* Security */ 2298 NULL, /* thread */ 2299 TRUE, /* inherit handles */ 2300 flags, /* start flags */ 2301 w32env, /* environment */ 2302 NULL, /* current directory */ 2303 &si, 2304 &pi); 2305 if (tty != INVALID_HANDLE_VALUE) 2306 CloseHandle (tty); 2307 #endif 2308 2309 if (!ret) 2310 error (_("Error creating process %s, (error %u)."), 2311 exec_file, (unsigned) GetLastError ()); 2312 2313 CloseHandle (pi.hThread); 2314 CloseHandle (pi.hProcess); 2315 2316 if (useshell && shell[0] != '\0') 2317 saw_create = -1; 2318 else 2319 saw_create = 0; 2320 2321 do_initial_windows_stuff (ops, pi.dwProcessId, 0); 2322 2323 /* windows_continue (DBG_CONTINUE, -1, 0); */ 2324 } 2325 2326 static void 2327 windows_mourn_inferior (struct target_ops *ops) 2328 { 2329 (void) windows_continue (DBG_CONTINUE, -1, 0); 2330 x86_cleanup_dregs(); 2331 if (open_process_used) 2332 { 2333 CHECK (CloseHandle (current_process_handle)); 2334 open_process_used = 0; 2335 } 2336 inf_child_mourn_inferior (ops); 2337 } 2338 2339 /* Send a SIGINT to the process group. This acts just like the user typed a 2340 ^C on the controlling terminal. */ 2341 2342 static void 2343 windows_interrupt (struct target_ops *self, ptid_t ptid) 2344 { 2345 DEBUG_EVENTS (("gdb: GenerateConsoleCtrlEvent (CTRLC_EVENT, 0)\n")); 2346 CHECK (GenerateConsoleCtrlEvent (CTRL_C_EVENT, current_event.dwProcessId)); 2347 registers_changed (); /* refresh register state */ 2348 } 2349 2350 /* Helper for windows_xfer_partial that handles memory transfers. 2351 Arguments are like target_xfer_partial. */ 2352 2353 static enum target_xfer_status 2354 windows_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf, 2355 ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len) 2356 { 2357 SIZE_T done = 0; 2358 BOOL success; 2359 DWORD lasterror = 0; 2360 2361 if (writebuf != NULL) 2362 { 2363 DEBUG_MEM (("gdb: write target memory, %s bytes at %s\n", 2364 pulongest (len), core_addr_to_string (memaddr))); 2365 success = WriteProcessMemory (current_process_handle, 2366 (LPVOID) (uintptr_t) memaddr, writebuf, 2367 len, &done); 2368 if (!success) 2369 lasterror = GetLastError (); 2370 FlushInstructionCache (current_process_handle, 2371 (LPCVOID) (uintptr_t) memaddr, len); 2372 } 2373 else 2374 { 2375 DEBUG_MEM (("gdb: read target memory, %s bytes at %s\n", 2376 pulongest (len), core_addr_to_string (memaddr))); 2377 success = ReadProcessMemory (current_process_handle, 2378 (LPCVOID) (uintptr_t) memaddr, readbuf, 2379 len, &done); 2380 if (!success) 2381 lasterror = GetLastError (); 2382 } 2383 *xfered_len = (ULONGEST) done; 2384 if (!success && lasterror == ERROR_PARTIAL_COPY && done > 0) 2385 return TARGET_XFER_OK; 2386 else 2387 return success ? TARGET_XFER_OK : TARGET_XFER_E_IO; 2388 } 2389 2390 static void 2391 windows_kill_inferior (struct target_ops *ops) 2392 { 2393 CHECK (TerminateProcess (current_process_handle, 0)); 2394 2395 for (;;) 2396 { 2397 if (!windows_continue (DBG_CONTINUE, -1, 1)) 2398 break; 2399 if (!WaitForDebugEvent (¤t_event, INFINITE)) 2400 break; 2401 if (current_event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT) 2402 break; 2403 } 2404 2405 target_mourn_inferior (); /* Or just windows_mourn_inferior? */ 2406 } 2407 2408 static void 2409 windows_close (struct target_ops *self) 2410 { 2411 DEBUG_EVENTS (("gdb: windows_close, inferior_ptid=%d\n", 2412 ptid_get_pid (inferior_ptid))); 2413 } 2414 2415 /* Convert pid to printable format. */ 2416 static char * 2417 windows_pid_to_str (struct target_ops *ops, ptid_t ptid) 2418 { 2419 static char buf[80]; 2420 2421 if (ptid_get_tid (ptid) != 0) 2422 { 2423 snprintf (buf, sizeof (buf), "Thread %d.0x%lx", 2424 ptid_get_pid (ptid), ptid_get_tid (ptid)); 2425 return buf; 2426 } 2427 2428 return normal_pid_to_str (ptid); 2429 } 2430 2431 static enum target_xfer_status 2432 windows_xfer_shared_libraries (struct target_ops *ops, 2433 enum target_object object, const char *annex, 2434 gdb_byte *readbuf, const gdb_byte *writebuf, 2435 ULONGEST offset, ULONGEST len, 2436 ULONGEST *xfered_len) 2437 { 2438 struct obstack obstack; 2439 const char *buf; 2440 LONGEST len_avail; 2441 struct so_list *so; 2442 2443 if (writebuf) 2444 return TARGET_XFER_E_IO; 2445 2446 obstack_init (&obstack); 2447 obstack_grow_str (&obstack, "<library-list>\n"); 2448 for (so = solib_start.next; so; so = so->next) 2449 windows_xfer_shared_library (so->so_name, (CORE_ADDR) 2450 (uintptr_t) so->lm_info->load_addr, 2451 target_gdbarch (), &obstack); 2452 obstack_grow_str0 (&obstack, "</library-list>\n"); 2453 2454 buf = (const char *) obstack_finish (&obstack); 2455 len_avail = strlen (buf); 2456 if (offset >= len_avail) 2457 len= 0; 2458 else 2459 { 2460 if (len > len_avail - offset) 2461 len = len_avail - offset; 2462 memcpy (readbuf, buf + offset, len); 2463 } 2464 2465 obstack_free (&obstack, NULL); 2466 *xfered_len = (ULONGEST) len; 2467 return len != 0 ? TARGET_XFER_OK : TARGET_XFER_EOF; 2468 } 2469 2470 static enum target_xfer_status 2471 windows_xfer_partial (struct target_ops *ops, enum target_object object, 2472 const char *annex, gdb_byte *readbuf, 2473 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len, 2474 ULONGEST *xfered_len) 2475 { 2476 switch (object) 2477 { 2478 case TARGET_OBJECT_MEMORY: 2479 return windows_xfer_memory (readbuf, writebuf, offset, len, xfered_len); 2480 2481 case TARGET_OBJECT_LIBRARIES: 2482 return windows_xfer_shared_libraries (ops, object, annex, readbuf, 2483 writebuf, offset, len, xfered_len); 2484 2485 default: 2486 return ops->beneath->to_xfer_partial (ops->beneath, object, annex, 2487 readbuf, writebuf, offset, len, 2488 xfered_len); 2489 } 2490 } 2491 2492 /* Provide thread local base, i.e. Thread Information Block address. 2493 Returns 1 if ptid is found and sets *ADDR to thread_local_base. */ 2494 2495 static int 2496 windows_get_tib_address (struct target_ops *self, 2497 ptid_t ptid, CORE_ADDR *addr) 2498 { 2499 windows_thread_info *th; 2500 2501 th = thread_rec (ptid_get_tid (ptid), 0); 2502 if (th == NULL) 2503 return 0; 2504 2505 if (addr != NULL) 2506 *addr = th->thread_local_base; 2507 2508 return 1; 2509 } 2510 2511 static ptid_t 2512 windows_get_ada_task_ptid (struct target_ops *self, long lwp, long thread) 2513 { 2514 return ptid_build (ptid_get_pid (inferior_ptid), 0, lwp); 2515 } 2516 2517 static struct target_ops * 2518 windows_target (void) 2519 { 2520 struct target_ops *t = inf_child_target (); 2521 2522 t->to_close = windows_close; 2523 t->to_attach = windows_attach; 2524 t->to_attach_no_wait = 1; 2525 t->to_detach = windows_detach; 2526 t->to_resume = windows_resume; 2527 t->to_wait = windows_wait; 2528 t->to_fetch_registers = windows_fetch_inferior_registers; 2529 t->to_store_registers = windows_store_inferior_registers; 2530 t->to_xfer_partial = windows_xfer_partial; 2531 t->to_files_info = windows_files_info; 2532 t->to_kill = windows_kill_inferior; 2533 t->to_create_inferior = windows_create_inferior; 2534 t->to_mourn_inferior = windows_mourn_inferior; 2535 t->to_thread_alive = windows_thread_alive; 2536 t->to_pid_to_str = windows_pid_to_str; 2537 t->to_interrupt = windows_interrupt; 2538 t->to_pid_to_exec_file = windows_pid_to_exec_file; 2539 t->to_get_ada_task_ptid = windows_get_ada_task_ptid; 2540 t->to_get_tib_address = windows_get_tib_address; 2541 2542 return t; 2543 } 2544 2545 /* -Wmissing-prototypes */ 2546 extern initialize_file_ftype _initialize_windows_nat; 2547 2548 void 2549 _initialize_windows_nat (void) 2550 { 2551 struct target_ops *t; 2552 2553 t = windows_target (); 2554 2555 x86_use_watchpoints (t); 2556 2557 x86_dr_low.set_control = cygwin_set_dr7; 2558 x86_dr_low.set_addr = cygwin_set_dr; 2559 x86_dr_low.get_addr = cygwin_get_dr; 2560 x86_dr_low.get_status = cygwin_get_dr6; 2561 x86_dr_low.get_control = cygwin_get_dr7; 2562 2563 /* x86_dr_low.debug_register_length field is set by 2564 calling x86_set_debug_register_length function 2565 in processor windows specific native file. */ 2566 2567 add_target (t); 2568 2569 #ifdef __CYGWIN__ 2570 cygwin_internal (CW_SET_DOS_FILE_WARNING, 0); 2571 #endif 2572 2573 add_com ("signal-event", class_run, signal_event_command, _("\ 2574 Signal a crashed process with event ID, to allow its debugging.\n\ 2575 This command is needed in support of setting up GDB as JIT debugger on \ 2576 MS-Windows. The command should be invoked from the GDB command line using \ 2577 the '-ex' command-line option. The ID of the event that blocks the \ 2578 crashed process will be supplied by the Windows JIT debugging mechanism.")); 2579 2580 #ifdef __CYGWIN__ 2581 add_setshow_boolean_cmd ("shell", class_support, &useshell, _("\ 2582 Set use of shell to start subprocess."), _("\ 2583 Show use of shell to start subprocess."), NULL, 2584 NULL, 2585 NULL, /* FIXME: i18n: */ 2586 &setlist, &showlist); 2587 2588 add_setshow_boolean_cmd ("cygwin-exceptions", class_support, 2589 &cygwin_exceptions, _("\ 2590 Break when an exception is detected in the Cygwin DLL itself."), _("\ 2591 Show whether gdb breaks on exceptions in the Cygwin DLL itself."), NULL, 2592 NULL, 2593 NULL, /* FIXME: i18n: */ 2594 &setlist, &showlist); 2595 #endif 2596 2597 add_setshow_boolean_cmd ("new-console", class_support, &new_console, _("\ 2598 Set creation of new console when creating child process."), _("\ 2599 Show creation of new console when creating child process."), NULL, 2600 NULL, 2601 NULL, /* FIXME: i18n: */ 2602 &setlist, &showlist); 2603 2604 add_setshow_boolean_cmd ("new-group", class_support, &new_group, _("\ 2605 Set creation of new group when creating child process."), _("\ 2606 Show creation of new group when creating child process."), NULL, 2607 NULL, 2608 NULL, /* FIXME: i18n: */ 2609 &setlist, &showlist); 2610 2611 add_setshow_boolean_cmd ("debugexec", class_support, &debug_exec, _("\ 2612 Set whether to display execution in child process."), _("\ 2613 Show whether to display execution in child process."), NULL, 2614 NULL, 2615 NULL, /* FIXME: i18n: */ 2616 &setlist, &showlist); 2617 2618 add_setshow_boolean_cmd ("debugevents", class_support, &debug_events, _("\ 2619 Set whether to display kernel events in child process."), _("\ 2620 Show whether to display kernel events in child process."), NULL, 2621 NULL, 2622 NULL, /* FIXME: i18n: */ 2623 &setlist, &showlist); 2624 2625 add_setshow_boolean_cmd ("debugmemory", class_support, &debug_memory, _("\ 2626 Set whether to display memory accesses in child process."), _("\ 2627 Show whether to display memory accesses in child process."), NULL, 2628 NULL, 2629 NULL, /* FIXME: i18n: */ 2630 &setlist, &showlist); 2631 2632 add_setshow_boolean_cmd ("debugexceptions", class_support, 2633 &debug_exceptions, _("\ 2634 Set whether to display kernel exceptions in child process."), _("\ 2635 Show whether to display kernel exceptions in child process."), NULL, 2636 NULL, 2637 NULL, /* FIXME: i18n: */ 2638 &setlist, &showlist); 2639 2640 init_w32_command_list (); 2641 2642 add_cmd ("selector", class_info, display_selectors, 2643 _("Display selectors infos."), 2644 &info_w32_cmdlist); 2645 } 2646 2647 /* Hardware watchpoint support, adapted from go32-nat.c code. */ 2648 2649 /* Pass the address ADDR to the inferior in the I'th debug register. 2650 Here we just store the address in dr array, the registers will be 2651 actually set up when windows_continue is called. */ 2652 static void 2653 cygwin_set_dr (int i, CORE_ADDR addr) 2654 { 2655 if (i < 0 || i > 3) 2656 internal_error (__FILE__, __LINE__, 2657 _("Invalid register %d in cygwin_set_dr.\n"), i); 2658 dr[i] = addr; 2659 debug_registers_changed = 1; 2660 debug_registers_used = 1; 2661 } 2662 2663 /* Pass the value VAL to the inferior in the DR7 debug control 2664 register. Here we just store the address in D_REGS, the watchpoint 2665 will be actually set up in windows_wait. */ 2666 static void 2667 cygwin_set_dr7 (unsigned long val) 2668 { 2669 dr[7] = (CORE_ADDR) val; 2670 debug_registers_changed = 1; 2671 debug_registers_used = 1; 2672 } 2673 2674 /* Get the value of debug register I from the inferior. */ 2675 2676 static CORE_ADDR 2677 cygwin_get_dr (int i) 2678 { 2679 return dr[i]; 2680 } 2681 2682 /* Get the value of the DR6 debug status register from the inferior. 2683 Here we just return the value stored in dr[6] 2684 by the last call to thread_rec for current_event.dwThreadId id. */ 2685 static unsigned long 2686 cygwin_get_dr6 (void) 2687 { 2688 return (unsigned long) dr[6]; 2689 } 2690 2691 /* Get the value of the DR7 debug status register from the inferior. 2692 Here we just return the value stored in dr[7] by the last call to 2693 thread_rec for current_event.dwThreadId id. */ 2694 2695 static unsigned long 2696 cygwin_get_dr7 (void) 2697 { 2698 return (unsigned long) dr[7]; 2699 } 2700 2701 /* Determine if the thread referenced by "ptid" is alive 2702 by "polling" it. If WaitForSingleObject returns WAIT_OBJECT_0 2703 it means that the thread has died. Otherwise it is assumed to be alive. */ 2704 static int 2705 windows_thread_alive (struct target_ops *ops, ptid_t ptid) 2706 { 2707 int tid; 2708 2709 gdb_assert (ptid_get_tid (ptid) != 0); 2710 tid = ptid_get_tid (ptid); 2711 2712 return WaitForSingleObject (thread_rec (tid, FALSE)->h, 0) == WAIT_OBJECT_0 2713 ? FALSE : TRUE; 2714 } 2715 2716 /* -Wmissing-prototypes */ 2717 extern initialize_file_ftype _initialize_check_for_gdb_ini; 2718 2719 void 2720 _initialize_check_for_gdb_ini (void) 2721 { 2722 char *homedir; 2723 if (inhibit_gdbinit) 2724 return; 2725 2726 homedir = getenv ("HOME"); 2727 if (homedir) 2728 { 2729 char *p; 2730 char *oldini = (char *) alloca (strlen (homedir) + 2731 sizeof ("gdb.ini") + 1); 2732 strcpy (oldini, homedir); 2733 p = strchr (oldini, '\0'); 2734 if (p > oldini && !IS_DIR_SEPARATOR (p[-1])) 2735 *p++ = '/'; 2736 strcpy (p, "gdb.ini"); 2737 if (access (oldini, 0) == 0) 2738 { 2739 int len = strlen (oldini); 2740 char *newini = (char *) alloca (len + 2); 2741 2742 xsnprintf (newini, len + 2, "%.*s.gdbinit", 2743 (int) (len - (sizeof ("gdb.ini") - 1)), oldini); 2744 warning (_("obsolete '%s' found. Rename to '%s'."), oldini, newini); 2745 } 2746 } 2747 } 2748 2749 /* Define dummy functions which always return error for the rare cases where 2750 these functions could not be found. */ 2751 static BOOL WINAPI 2752 bad_DebugActiveProcessStop (DWORD w) 2753 { 2754 return FALSE; 2755 } 2756 static BOOL WINAPI 2757 bad_DebugBreakProcess (HANDLE w) 2758 { 2759 return FALSE; 2760 } 2761 static BOOL WINAPI 2762 bad_DebugSetProcessKillOnExit (BOOL w) 2763 { 2764 return FALSE; 2765 } 2766 static BOOL WINAPI 2767 bad_EnumProcessModules (HANDLE w, HMODULE *x, DWORD y, LPDWORD z) 2768 { 2769 return FALSE; 2770 } 2771 2772 #ifdef __USEWIDE 2773 static DWORD WINAPI 2774 bad_GetModuleFileNameExW (HANDLE w, HMODULE x, LPWSTR y, DWORD z) 2775 { 2776 return 0; 2777 } 2778 #else 2779 static DWORD WINAPI 2780 bad_GetModuleFileNameExA (HANDLE w, HMODULE x, LPSTR y, DWORD z) 2781 { 2782 return 0; 2783 } 2784 #endif 2785 2786 static BOOL WINAPI 2787 bad_GetModuleInformation (HANDLE w, HMODULE x, LPMODULEINFO y, DWORD z) 2788 { 2789 return FALSE; 2790 } 2791 2792 static BOOL WINAPI 2793 bad_OpenProcessToken (HANDLE w, DWORD x, PHANDLE y) 2794 { 2795 return FALSE; 2796 } 2797 2798 static BOOL WINAPI 2799 bad_GetCurrentConsoleFont (HANDLE w, BOOL bMaxWindow, CONSOLE_FONT_INFO *f) 2800 { 2801 f->nFont = 0; 2802 return 1; 2803 } 2804 static COORD WINAPI 2805 bad_GetConsoleFontSize (HANDLE w, DWORD nFont) 2806 { 2807 COORD size; 2808 size.X = 8; 2809 size.Y = 12; 2810 return size; 2811 } 2812 2813 /* -Wmissing-prototypes */ 2814 extern initialize_file_ftype _initialize_loadable; 2815 2816 /* Load any functions which may not be available in ancient versions 2817 of Windows. */ 2818 2819 void 2820 _initialize_loadable (void) 2821 { 2822 HMODULE hm = NULL; 2823 2824 #define GPA(m, func) \ 2825 func = (func ## _ftype *) GetProcAddress (m, #func) 2826 2827 hm = LoadLibrary ("kernel32.dll"); 2828 if (hm) 2829 { 2830 GPA (hm, DebugActiveProcessStop); 2831 GPA (hm, DebugBreakProcess); 2832 GPA (hm, DebugSetProcessKillOnExit); 2833 GPA (hm, GetConsoleFontSize); 2834 GPA (hm, DebugActiveProcessStop); 2835 GPA (hm, GetCurrentConsoleFont); 2836 } 2837 2838 /* Set variables to dummy versions of these processes if the function 2839 wasn't found in kernel32.dll. */ 2840 if (!DebugBreakProcess) 2841 DebugBreakProcess = bad_DebugBreakProcess; 2842 if (!DebugActiveProcessStop || !DebugSetProcessKillOnExit) 2843 { 2844 DebugActiveProcessStop = bad_DebugActiveProcessStop; 2845 DebugSetProcessKillOnExit = bad_DebugSetProcessKillOnExit; 2846 } 2847 if (!GetConsoleFontSize) 2848 GetConsoleFontSize = bad_GetConsoleFontSize; 2849 if (!GetCurrentConsoleFont) 2850 GetCurrentConsoleFont = bad_GetCurrentConsoleFont; 2851 2852 /* Load optional functions used for retrieving filename information 2853 associated with the currently debugged process or its dlls. */ 2854 hm = LoadLibrary ("psapi.dll"); 2855 if (hm) 2856 { 2857 GPA (hm, EnumProcessModules); 2858 GPA (hm, GetModuleInformation); 2859 GetModuleFileNameEx = (GetModuleFileNameEx_ftype *) 2860 GetProcAddress (hm, GetModuleFileNameEx_name); 2861 } 2862 2863 if (!EnumProcessModules || !GetModuleInformation || !GetModuleFileNameEx) 2864 { 2865 /* Set variables to dummy versions of these processes if the function 2866 wasn't found in psapi.dll. */ 2867 EnumProcessModules = bad_EnumProcessModules; 2868 GetModuleInformation = bad_GetModuleInformation; 2869 GetModuleFileNameEx = bad_GetModuleFileNameEx; 2870 /* This will probably fail on Windows 9x/Me. Let the user know 2871 that we're missing some functionality. */ 2872 warning(_("\ 2873 cannot automatically find executable file or library to read symbols.\n\ 2874 Use \"file\" or \"dll\" command to load executable/libraries directly.")); 2875 } 2876 2877 hm = LoadLibrary ("advapi32.dll"); 2878 if (hm) 2879 { 2880 GPA (hm, OpenProcessToken); 2881 GPA (hm, LookupPrivilegeValueA); 2882 GPA (hm, AdjustTokenPrivileges); 2883 /* Only need to set one of these since if OpenProcessToken fails nothing 2884 else is needed. */ 2885 if (!OpenProcessToken || !LookupPrivilegeValueA 2886 || !AdjustTokenPrivileges) 2887 OpenProcessToken = bad_OpenProcessToken; 2888 } 2889 2890 #undef GPA 2891 } 2892