1 /* Target-vector operations for controlling windows child processes, for GDB.
3 Copyright (C) 1995-2014 Free Software Foundation, Inc.
5 Contributed by Cygnus Solutions, A Red Hat Company.
7 This file is part of GDB.
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.
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.
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/>. */
22 /* Originally by Steve Chamberlain, sac@cygnus.com */
25 #include "frame.h" /* required by inferior.h */
28 #include "exceptions.h"
31 #include "completer.h"
35 #include <sys/types.h>
43 #include <sys/cygwin.h>
44 #include <cygwin/version.h>
48 #include "filenames.h"
52 #include "gdb_obstack.h"
54 #include "gdbthread.h"
60 #include "xml-support.h"
62 #include "i386-tdep.h"
63 #include "i387-tdep.h"
65 #include "windows-tdep.h"
66 #include "windows-nat.h"
68 #include "complaints.h"
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
81 static BOOL WINAPI (*AdjustTokenPrivileges)(HANDLE, BOOL, PTOKEN_PRIVILEGES,
82 DWORD, PTOKEN_PRIVILEGES, PDWORD);
83 static BOOL WINAPI (*DebugActiveProcessStop) (DWORD);
84 static BOOL WINAPI (*DebugBreakProcess) (HANDLE);
85 static BOOL WINAPI (*DebugSetProcessKillOnExit) (BOOL);
86 static BOOL WINAPI (*EnumProcessModules) (HANDLE, HMODULE *, DWORD,
88 static BOOL WINAPI (*GetModuleInformation) (HANDLE, HMODULE, LPMODULEINFO,
90 static BOOL WINAPI (*LookupPrivilegeValueA)(LPCSTR, LPCSTR, PLUID);
91 static BOOL WINAPI (*OpenProcessToken)(HANDLE, DWORD, PHANDLE);
92 static BOOL WINAPI (*GetCurrentConsoleFont) (HANDLE, BOOL,
94 static COORD WINAPI (*GetConsoleFontSize) (HANDLE, DWORD);
96 static struct target_ops windows_ops;
100 #undef GetModuleFileNameEx
103 # define __PMAX (MAX_PATH + 1)
104 static DWORD WINAPI (*GetModuleFileNameEx) (HANDLE, HMODULE, LPSTR, DWORD);
105 # define STARTUPINFO STARTUPINFOA
106 # define CreateProcess CreateProcessA
107 # define GetModuleFileNameEx_name "GetModuleFileNameExA"
108 # define bad_GetModuleFileNameEx bad_GetModuleFileNameExA
110 # define __PMAX PATH_MAX
111 /* The starting and ending address of the cygwin1.dll text segment. */
112 static CORE_ADDR cygwin_load_start;
113 static CORE_ADDR cygwin_load_end;
115 typedef wchar_t cygwin_buf_t;
116 static DWORD WINAPI (*GetModuleFileNameEx) (HANDLE, HMODULE,
118 # define STARTUPINFO STARTUPINFOW
119 # define CreateProcess CreateProcessW
120 # define GetModuleFileNameEx_name "GetModuleFileNameExW"
121 # define bad_GetModuleFileNameEx bad_GetModuleFileNameExW
124 static int have_saved_context; /* True if we've saved context from a
126 static CONTEXT saved_context; /* Containes the saved context from a
129 /* If we're not using the old Cygwin header file set, define the
130 following which never should have been in the generic Win32 API
131 headers in the first place since they were our own invention... */
132 #ifndef _GNU_H_WINDOWS_H
135 FLAG_TRACE_BIT = 0x100,
136 CONTEXT_DEBUGGER = (CONTEXT_FULL | CONTEXT_FLOATING_POINT)
140 #ifndef CONTEXT_EXTENDED_REGISTERS
141 /* This macro is only defined on ia32. It only makes sense on this target,
142 so define it as zero if not already defined. */
143 #define CONTEXT_EXTENDED_REGISTERS 0
146 #define CONTEXT_DEBUGGER_DR CONTEXT_DEBUGGER | CONTEXT_DEBUG_REGISTERS \
147 | CONTEXT_EXTENDED_REGISTERS
149 static uintptr_t dr[8];
150 static int debug_registers_changed;
151 static int debug_registers_used;
153 static int windows_initialization_done;
154 #define DR6_CLEAR_VALUE 0xffff0ff0
156 /* The string sent by cygwin when it processes a signal.
157 FIXME: This should be in a cygwin include file. */
158 #ifndef _CYGWIN_SIGNAL_STRING
159 #define _CYGWIN_SIGNAL_STRING "cYgSiGw00f"
162 #define CHECK(x) check (x, __FILE__,__LINE__)
163 #define DEBUG_EXEC(x) if (debug_exec) printf_unfiltered x
164 #define DEBUG_EVENTS(x) if (debug_events) printf_unfiltered x
165 #define DEBUG_MEM(x) if (debug_memory) printf_unfiltered x
166 #define DEBUG_EXCEPT(x) if (debug_exceptions) printf_unfiltered x
168 static void windows_stop (struct target_ops *self, ptid_t);
169 static int windows_thread_alive (struct target_ops *, ptid_t);
170 static void windows_kill_inferior (struct target_ops *);
172 static void cygwin_set_dr (int i, CORE_ADDR addr);
173 static void cygwin_set_dr7 (unsigned long val);
174 static CORE_ADDR cygwin_get_dr (int i);
175 static unsigned long cygwin_get_dr6 (void);
176 static unsigned long cygwin_get_dr7 (void);
178 static enum gdb_signal last_sig = GDB_SIGNAL_0;
179 /* Set if a signal was received from the debugged process. */
181 /* Thread information structure used to track information that is
182 not available in gdb's thread structure. */
183 typedef struct thread_info_struct
185 struct thread_info_struct *next;
188 CORE_ADDR thread_local_base;
197 static thread_info thread_head;
199 /* The process and thread handles for the above context. */
201 static DEBUG_EVENT current_event; /* The current debug event from
203 static HANDLE current_process_handle; /* Currently executing process */
204 static thread_info *current_thread; /* Info on currently selected thread */
205 static DWORD main_thread_id; /* Thread ID of the main thread */
207 /* Counts of things. */
208 static int exception_count = 0;
209 static int event_count = 0;
210 static int saw_create;
211 static int open_process_used = 0;
214 static int new_console = 0;
216 static int cygwin_exceptions = 0;
218 static int new_group = 1;
219 static int debug_exec = 0; /* show execution */
220 static int debug_events = 0; /* show events from kernel */
221 static int debug_memory = 0; /* show target memory accesses */
222 static int debug_exceptions = 0; /* show target exceptions */
223 static int useshell = 0; /* use shell for subprocesses */
225 /* This vector maps GDB's idea of a register's number into an offset
226 in the windows exception context vector.
228 It also contains the bit mask needed to load the register in question.
230 The contents of this table can only be computed by the units
231 that provide CPU-specific support for Windows native debugging.
232 These units should set the table by calling
233 windows_set_context_register_offsets.
235 One day we could read a reg, we could inspect the context we
236 already have loaded, if it doesn't have the bit set that we need,
237 we read that set of registers in using GetThreadContext. If the
238 context already contains what we need, we just unpack it. Then to
239 write a register, first we have to ensure that the context contains
240 the other regs of the group, and then we copy the info in and set
243 static const int *mappings;
245 /* The function to use in order to determine whether a register is
246 a segment register or not. */
247 static segment_register_p_ftype *segment_register_p;
249 /* This vector maps the target's idea of an exception (extracted
250 from the DEBUG_EVENT structure) to GDB's idea. */
252 struct xlate_exception
258 static const struct xlate_exception
261 {EXCEPTION_ACCESS_VIOLATION, GDB_SIGNAL_SEGV},
262 {STATUS_STACK_OVERFLOW, GDB_SIGNAL_SEGV},
263 {EXCEPTION_BREAKPOINT, GDB_SIGNAL_TRAP},
264 {DBG_CONTROL_C, GDB_SIGNAL_INT},
265 {EXCEPTION_SINGLE_STEP, GDB_SIGNAL_TRAP},
266 {STATUS_FLOAT_DIVIDE_BY_ZERO, GDB_SIGNAL_FPE},
269 /* Set the MAPPINGS static global to OFFSETS.
270 See the description of MAPPINGS for more details. */
273 windows_set_context_register_offsets (const int *offsets)
278 /* See windows-nat.h. */
281 windows_set_segment_register_p (segment_register_p_ftype *fun)
283 segment_register_p = fun;
287 check (BOOL ok, const char *file, int line)
290 printf_filtered ("error return %s:%d was %u\n", file, line,
291 (unsigned) GetLastError ());
294 /* Find a thread record given a thread id. If GET_CONTEXT is not 0,
295 then also retrieve the context for this thread. If GET_CONTEXT is
296 negative, then don't suspend the thread. */
298 thread_rec (DWORD id, int get_context)
302 for (th = &thread_head; (th = th->next) != NULL;)
305 if (!th->suspended && get_context)
307 if (get_context > 0 && id != current_event.dwThreadId)
309 if (SuspendThread (th->h) == (DWORD) -1)
311 DWORD err = GetLastError ();
313 warning (_("SuspendThread (tid=0x%x) failed."
315 (unsigned) id, (unsigned) err);
320 else if (get_context < 0)
322 th->reload_context = 1;
330 /* Add a thread to the thread list. */
332 windows_add_thread (ptid_t ptid, HANDLE h, void *tlb)
337 gdb_assert (ptid_get_tid (ptid) != 0);
339 id = ptid_get_tid (ptid);
341 if ((th = thread_rec (id, FALSE)))
344 th = XCNEW (thread_info);
347 th->thread_local_base = (CORE_ADDR) (uintptr_t) tlb;
348 th->next = thread_head.next;
349 thread_head.next = th;
351 /* Set the debug registers for the new thread if they are used. */
352 if (debug_registers_used)
354 /* Only change the value of the debug registers. */
355 th->context.ContextFlags = CONTEXT_DEBUG_REGISTERS;
356 CHECK (GetThreadContext (th->h, &th->context));
357 th->context.Dr0 = dr[0];
358 th->context.Dr1 = dr[1];
359 th->context.Dr2 = dr[2];
360 th->context.Dr3 = dr[3];
361 th->context.Dr6 = DR6_CLEAR_VALUE;
362 th->context.Dr7 = dr[7];
363 CHECK (SetThreadContext (th->h, &th->context));
364 th->context.ContextFlags = 0;
369 /* Clear out any old thread list and reintialize it to a
372 windows_init_thread_list (void)
374 thread_info *th = &thread_head;
376 DEBUG_EVENTS (("gdb: windows_init_thread_list\n"));
378 while (th->next != NULL)
380 thread_info *here = th->next;
381 th->next = here->next;
384 thread_head.next = NULL;
387 /* Delete a thread from the list of threads. */
389 windows_delete_thread (ptid_t ptid, DWORD exit_code)
394 gdb_assert (ptid_get_tid (ptid) != 0);
396 id = ptid_get_tid (ptid);
399 printf_unfiltered ("[Deleting %s]\n", target_pid_to_str (ptid));
400 else if (print_thread_events && id != main_thread_id)
401 printf_unfiltered (_("[%s exited with code %u]\n"),
402 target_pid_to_str (ptid), (unsigned) exit_code);
403 delete_thread (ptid);
405 for (th = &thread_head;
406 th->next != NULL && th->next->id != id;
410 if (th->next != NULL)
412 thread_info *here = th->next;
413 th->next = here->next;
419 do_windows_fetch_inferior_registers (struct regcache *regcache, int r)
421 char *context_offset = ((char *) ¤t_thread->context) + mappings[r];
422 struct gdbarch *gdbarch = get_regcache_arch (regcache);
423 struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
427 return; /* Windows sometimes uses a non-existent thread id in its
430 if (current_thread->reload_context)
432 #ifdef __COPY_CONTEXT_SIZE
433 if (have_saved_context)
435 /* Lie about where the program actually is stopped since
436 cygwin has informed us that we should consider the signal
437 to have occurred at another location which is stored in
439 memcpy (¤t_thread->context, &saved_context,
440 __COPY_CONTEXT_SIZE);
441 have_saved_context = 0;
446 thread_info *th = current_thread;
447 th->context.ContextFlags = CONTEXT_DEBUGGER_DR;
448 GetThreadContext (th->h, &th->context);
449 /* Copy dr values from that thread.
450 But only if there were not modified since last stop.
452 if (!debug_registers_changed)
454 dr[0] = th->context.Dr0;
455 dr[1] = th->context.Dr1;
456 dr[2] = th->context.Dr2;
457 dr[3] = th->context.Dr3;
458 dr[6] = th->context.Dr6;
459 dr[7] = th->context.Dr7;
462 current_thread->reload_context = 0;
465 if (r == I387_FISEG_REGNUM (tdep))
467 l = *((long *) context_offset) & 0xffff;
468 regcache_raw_supply (regcache, r, (char *) &l);
470 else if (r == I387_FOP_REGNUM (tdep))
472 l = (*((long *) context_offset) >> 16) & ((1 << 11) - 1);
473 regcache_raw_supply (regcache, r, (char *) &l);
475 else if (segment_register_p (r))
477 /* GDB treats segment registers as 32bit registers, but they are
478 in fact only 16 bits long. Make sure we do not read extra
479 bits from our source buffer. */
480 l = *((long *) context_offset) & 0xffff;
481 regcache_raw_supply (regcache, r, (char *) &l);
484 regcache_raw_supply (regcache, r, context_offset);
487 for (r = 0; r < gdbarch_num_regs (gdbarch); r++)
488 do_windows_fetch_inferior_registers (regcache, r);
493 windows_fetch_inferior_registers (struct target_ops *ops,
494 struct regcache *regcache, int r)
496 current_thread = thread_rec (ptid_get_tid (inferior_ptid), TRUE);
497 /* Check if current_thread exists. Windows sometimes uses a non-existent
498 thread id in its events. */
500 do_windows_fetch_inferior_registers (regcache, r);
504 do_windows_store_inferior_registers (const struct regcache *regcache, int r)
507 /* Windows sometimes uses a non-existent thread id in its events. */;
509 regcache_raw_collect (regcache, r,
510 ((char *) ¤t_thread->context) + mappings[r]);
513 for (r = 0; r < gdbarch_num_regs (get_regcache_arch (regcache)); r++)
514 do_windows_store_inferior_registers (regcache, r);
518 /* Store a new register value into the current thread context. */
520 windows_store_inferior_registers (struct target_ops *ops,
521 struct regcache *regcache, int r)
523 current_thread = thread_rec (ptid_get_tid (inferior_ptid), TRUE);
524 /* Check if current_thread exists. Windows sometimes uses a non-existent
525 thread id in its events. */
527 do_windows_store_inferior_registers (regcache, r);
530 /* Encapsulate the information required in a call to
531 symbol_file_add_args. */
532 struct safe_symbol_file_add_args
536 struct section_addr_info *addrs;
539 struct ui_file *err, *out;
543 /* Maintain a linked list of "so" information. */
549 static struct so_list solib_start, *solib_end;
551 /* Call symbol_file_add with stderr redirected. We don't care if there
554 safe_symbol_file_add_stub (void *argv)
556 #define p ((struct safe_symbol_file_add_args *) argv)
557 const int add_flags = ((p->from_tty ? SYMFILE_VERBOSE : 0)
558 | (p->mainline ? SYMFILE_MAINLINE : 0));
559 p->ret = symbol_file_add (p->name, add_flags, p->addrs, p->flags);
564 /* Restore gdb's stderr after calling symbol_file_add. */
566 safe_symbol_file_add_cleanup (void *p)
568 #define sp ((struct safe_symbol_file_add_args *)p)
569 gdb_flush (gdb_stderr);
570 gdb_flush (gdb_stdout);
571 ui_file_delete (gdb_stderr);
572 ui_file_delete (gdb_stdout);
573 gdb_stderr = sp->err;
574 gdb_stdout = sp->out;
578 /* symbol_file_add wrapper that prevents errors from being displayed. */
579 static struct objfile *
580 safe_symbol_file_add (char *name, int from_tty,
581 struct section_addr_info *addrs,
582 int mainline, int flags)
584 struct safe_symbol_file_add_args p;
585 struct cleanup *cleanup;
587 cleanup = make_cleanup (safe_symbol_file_add_cleanup, &p);
591 gdb_flush (gdb_stderr);
592 gdb_flush (gdb_stdout);
593 gdb_stderr = ui_file_new ();
594 gdb_stdout = ui_file_new ();
596 p.from_tty = from_tty;
598 p.mainline = mainline;
600 catch_errors (safe_symbol_file_add_stub, &p, "", RETURN_MASK_ERROR);
602 do_cleanups (cleanup);
606 static struct so_list *
607 windows_make_so (const char *name, LPVOID load_addr)
614 WIN32_FIND_DATA w32_fd;
615 HANDLE h = FindFirstFile(name, &w32_fd);
617 if (h == INVALID_HANDLE_VALUE)
623 if (GetCurrentDirectory (MAX_PATH + 1, cwd))
625 p = strrchr (buf, '\\');
628 SetCurrentDirectory (buf);
629 GetFullPathName (w32_fd.cFileName, MAX_PATH, buf, &p);
630 SetCurrentDirectory (cwd);
633 if (strcasecmp (buf, "ntdll.dll") == 0)
635 GetSystemDirectory (buf, sizeof (buf));
636 strcat (buf, "\\ntdll.dll");
639 cygwin_buf_t buf[__PMAX];
642 if (access (name, F_OK) != 0)
644 if (strcasecmp (name, "ntdll.dll") == 0)
647 GetSystemDirectoryW (buf, sizeof (buf) / sizeof (wchar_t));
648 wcscat (buf, L"\\ntdll.dll");
652 GetSystemDirectoryA (buf, sizeof (buf) / sizeof (wchar_t));
653 strcat (buf, "\\ntdll.dll");
658 so = XCNEW (struct so_list);
659 so->lm_info = (struct lm_info *) xmalloc (sizeof (struct lm_info));
660 so->lm_info->load_addr = load_addr;
661 strcpy (so->so_original_name, name);
663 strcpy (so->so_name, buf);
666 cygwin_conv_path (CCP_WIN_W_TO_POSIX, buf, so->so_name,
667 SO_NAME_MAX_PATH_SIZE);
670 char *rname = realpath (name, NULL);
671 if (rname && strlen (rname) < SO_NAME_MAX_PATH_SIZE)
673 strcpy (so->so_name, rname);
677 error (_("dll path too long"));
679 /* Record cygwin1.dll .text start/end. */
680 p = strchr (so->so_name, '\0') - (sizeof ("/cygwin1.dll") - 1);
681 if (p >= so->so_name && strcasecmp (p, "/cygwin1.dll") == 0)
684 asection *text = NULL;
687 abfd = gdb_bfd_open (so->so_name, "pei-i386", -1);
692 if (bfd_check_format (abfd, bfd_object))
693 text = bfd_get_section_by_name (abfd, ".text");
697 gdb_bfd_unref (abfd);
701 /* The symbols in a dll are offset by 0x1000, which is the
702 offset from 0 of the first byte in an image - because of the
703 file header and the section alignment. */
704 cygwin_load_start = (CORE_ADDR) (uintptr_t) ((char *)
706 cygwin_load_end = cygwin_load_start + bfd_section_size (abfd, text);
708 gdb_bfd_unref (abfd);
716 get_image_name (HANDLE h, void *address, int unicode)
719 static char buf[__PMAX];
721 static char buf[(2 * __PMAX) + 1];
723 DWORD size = unicode ? sizeof (WCHAR) : sizeof (char);
729 /* Attempt to read the name of the dll that was detected.
730 This is documented to work only when actively debugging
731 a program. It will not work for attached processes. */
735 /* See if we could read the address of a string, and that the
736 address isn't null. */
737 if (!ReadProcessMemory (h, address, &address_ptr,
738 sizeof (address_ptr), &done)
739 || done != sizeof (address_ptr) || !address_ptr)
742 /* Find the length of the string. */
743 while (ReadProcessMemory (h, address_ptr + len++ * size, &b, size, &done)
744 && (b[0] != 0 || b[size - 1] != 0) && done == size)
748 ReadProcessMemory (h, address_ptr, buf, len, &done);
751 WCHAR *unicode_address = (WCHAR *) alloca (len * sizeof (WCHAR));
752 ReadProcessMemory (h, address_ptr, unicode_address, len * sizeof (WCHAR),
755 wcstombs (buf, unicode_address, __PMAX);
757 WideCharToMultiByte (CP_ACP, 0, unicode_address, len, buf, sizeof buf,
765 /* Handle a DLL load event, and return 1.
767 This function assumes that this event did not occur during inferior
768 initialization, where their event info may be incomplete (see
769 do_initial_windows_stuff and windows_add_all_dlls for more info
770 on how we handle DLL loading during that phase). */
773 handle_load_dll (void *dummy)
775 LOAD_DLL_DEBUG_INFO *event = ¤t_event.u.LoadDll;
778 /* Try getting the DLL name via the lpImageName field of the event.
779 Note that Microsoft documents this fields as strictly optional,
780 in the sense that it might be NULL. And the first DLL event in
781 particular is explicitly documented as "likely not pass[ed]"
782 (source: MSDN LOAD_DLL_DEBUG_INFO structure). */
783 dll_name = get_image_name (current_process_handle,
784 event->lpImageName, event->fUnicode);
788 solib_end->next = windows_make_so (dll_name, event->lpBaseOfDll);
789 solib_end = solib_end->next;
791 DEBUG_EVENTS (("gdb: Loading dll \"%s\" at %s.\n", solib_end->so_name,
792 host_address_to_string (solib_end->lm_info->load_addr)));
798 windows_free_so (struct so_list *so)
806 handle_unload_dll (void *dummy)
808 LPVOID lpBaseOfDll = current_event.u.UnloadDll.lpBaseOfDll;
811 for (so = &solib_start; so->next != NULL; so = so->next)
812 if (so->next->lm_info->load_addr == lpBaseOfDll)
814 struct so_list *sodel = so->next;
816 so->next = sodel->next;
819 DEBUG_EVENTS (("gdb: Unloading dll \"%s\".\n", sodel->so_name));
821 windows_free_so (sodel);
825 /* We did not find any DLL that was previously loaded at this address,
826 so register a complaint. We do not report an error, because we have
827 observed that this may be happening under some circumstances. For
828 instance, running 32bit applications on x64 Windows causes us to receive
829 4 mysterious UNLOAD_DLL_DEBUG_EVENTs during the startup phase (these
830 events are apparently caused by the WOW layer, the interface between
831 32bit and 64bit worlds). */
832 complaint (&symfile_complaints, _("dll starting at %s not found."),
833 host_address_to_string (lpBaseOfDll));
838 /* Clear list of loaded DLLs. */
840 windows_clear_solib (void)
842 solib_start.next = NULL;
843 solib_end = &solib_start;
846 /* Load DLL symbol info. */
848 dll_symbol_command (char *args, int from_tty)
854 error (_("dll-symbols requires a file name"));
857 if (n > 4 && strcasecmp (args + n - 4, ".dll") != 0)
859 char *newargs = (char *) alloca (n + 4 + 1);
860 strcpy (newargs, args);
861 strcat (newargs, ".dll");
865 safe_symbol_file_add (args, from_tty, NULL, 0, OBJF_SHARED | OBJF_USERLOADED);
868 /* Handle DEBUG_STRING output from child process.
869 Cygwin prepends its messages with a "cygwin:". Interpret this as
870 a Cygwin signal. Otherwise just print the string as a warning. */
872 handle_output_debug_string (struct target_waitstatus *ourstatus)
877 if (!target_read_string
878 ((CORE_ADDR) (uintptr_t) current_event.u.DebugString.lpDebugStringData,
882 else if (strncmp (s, _CYGWIN_SIGNAL_STRING,
883 sizeof (_CYGWIN_SIGNAL_STRING) - 1) != 0)
886 if (strncmp (s, "cYg", 3) != 0)
890 #ifdef __COPY_CONTEXT_SIZE
893 /* Got a cygwin signal marker. A cygwin signal is followed by
894 the signal number itself and then optionally followed by the
895 thread id and address to saved context within the DLL. If
896 these are supplied, then the given thread is assumed to have
897 issued the signal and the context from the thread is assumed
898 to be stored at the given address in the inferior. Tell gdb
899 to treat this like a real signal. */
901 int sig = strtol (s + sizeof (_CYGWIN_SIGNAL_STRING) - 1, &p, 0);
902 int gotasig = gdb_signal_from_host (sig);
904 ourstatus->value.sig = gotasig;
910 ourstatus->kind = TARGET_WAITKIND_STOPPED;
911 retval = strtoul (p, &p, 0);
913 retval = main_thread_id;
914 else if ((x = (LPCVOID) (uintptr_t) strtoull (p, NULL, 0))
915 && ReadProcessMemory (current_process_handle, x,
917 __COPY_CONTEXT_SIZE, &n)
918 && n == __COPY_CONTEXT_SIZE)
919 have_saved_context = 1;
920 current_event.dwThreadId = retval;
931 display_selector (HANDLE thread, DWORD sel)
934 if (GetThreadSelectorEntry (thread, sel, &info))
937 printf_filtered ("0x%03x: ", (unsigned) sel);
938 if (!info.HighWord.Bits.Pres)
940 puts_filtered ("Segment not present\n");
943 base = (info.HighWord.Bits.BaseHi << 24) +
944 (info.HighWord.Bits.BaseMid << 16)
946 limit = (info.HighWord.Bits.LimitHi << 16) + info.LimitLow;
947 if (info.HighWord.Bits.Granularity)
948 limit = (limit << 12) | 0xfff;
949 printf_filtered ("base=0x%08x limit=0x%08x", base, limit);
950 if (info.HighWord.Bits.Default_Big)
951 puts_filtered(" 32-bit ");
953 puts_filtered(" 16-bit ");
954 switch ((info.HighWord.Bits.Type & 0xf) >> 1)
957 puts_filtered ("Data (Read-Only, Exp-up");
960 puts_filtered ("Data (Read/Write, Exp-up");
963 puts_filtered ("Unused segment (");
966 puts_filtered ("Data (Read/Write, Exp-down");
969 puts_filtered ("Code (Exec-Only, N.Conf");
972 puts_filtered ("Code (Exec/Read, N.Conf");
975 puts_filtered ("Code (Exec-Only, Conf");
978 puts_filtered ("Code (Exec/Read, Conf");
981 printf_filtered ("Unknown type 0x%x",info.HighWord.Bits.Type);
983 if ((info.HighWord.Bits.Type & 0x1) == 0)
984 puts_filtered(", N.Acc");
985 puts_filtered (")\n");
986 if ((info.HighWord.Bits.Type & 0x10) == 0)
987 puts_filtered("System selector ");
988 printf_filtered ("Priviledge level = %d. ", info.HighWord.Bits.Dpl);
989 if (info.HighWord.Bits.Granularity)
990 puts_filtered ("Page granular.\n");
992 puts_filtered ("Byte granular.\n");
997 DWORD err = GetLastError ();
998 if (err == ERROR_NOT_SUPPORTED)
999 printf_filtered ("Function not supported\n");
1001 printf_filtered ("Invalid selector 0x%x.\n", (unsigned) sel);
1007 display_selectors (char * args, int from_tty)
1009 if (!current_thread)
1011 puts_filtered ("Impossible to display selectors now.\n");
1017 puts_filtered ("Selector $cs\n");
1018 display_selector (current_thread->h,
1019 current_thread->context.SegCs);
1020 puts_filtered ("Selector $ds\n");
1021 display_selector (current_thread->h,
1022 current_thread->context.SegDs);
1023 puts_filtered ("Selector $es\n");
1024 display_selector (current_thread->h,
1025 current_thread->context.SegEs);
1026 puts_filtered ("Selector $ss\n");
1027 display_selector (current_thread->h,
1028 current_thread->context.SegSs);
1029 puts_filtered ("Selector $fs\n");
1030 display_selector (current_thread->h,
1031 current_thread->context.SegFs);
1032 puts_filtered ("Selector $gs\n");
1033 display_selector (current_thread->h,
1034 current_thread->context.SegGs);
1039 sel = parse_and_eval_long (args);
1040 printf_filtered ("Selector \"%s\"\n",args);
1041 display_selector (current_thread->h, sel);
1045 #define DEBUG_EXCEPTION_SIMPLE(x) if (debug_exceptions) \
1046 printf_unfiltered ("gdb: Target exception %s at %s\n", x, \
1047 host_address_to_string (\
1048 current_event.u.Exception.ExceptionRecord.ExceptionAddress))
1051 handle_exception (struct target_waitstatus *ourstatus)
1054 DWORD code = current_event.u.Exception.ExceptionRecord.ExceptionCode;
1056 ourstatus->kind = TARGET_WAITKIND_STOPPED;
1058 /* Record the context of the current thread. */
1059 th = thread_rec (current_event.dwThreadId, -1);
1063 case EXCEPTION_ACCESS_VIOLATION:
1064 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ACCESS_VIOLATION");
1065 ourstatus->value.sig = GDB_SIGNAL_SEGV;
1068 /* See if the access violation happened within the cygwin DLL
1069 itself. Cygwin uses a kind of exception handling to deal
1070 with passed-in invalid addresses. gdb should not treat
1071 these as real SEGVs since they will be silently handled by
1072 cygwin. A real SEGV will (theoretically) be caught by
1073 cygwin later in the process and will be sent as a
1074 cygwin-specific-signal. So, ignore SEGVs if they show up
1075 within the text segment of the DLL itself. */
1077 CORE_ADDR addr = (CORE_ADDR) (uintptr_t)
1078 current_event.u.Exception.ExceptionRecord.ExceptionAddress;
1080 if ((!cygwin_exceptions && (addr >= cygwin_load_start
1081 && addr < cygwin_load_end))
1082 || (find_pc_partial_function (addr, &fn, NULL, NULL)
1083 && strncmp (fn, "KERNEL32!IsBad",
1084 strlen ("KERNEL32!IsBad")) == 0))
1089 case STATUS_STACK_OVERFLOW:
1090 DEBUG_EXCEPTION_SIMPLE ("STATUS_STACK_OVERFLOW");
1091 ourstatus->value.sig = GDB_SIGNAL_SEGV;
1093 case STATUS_FLOAT_DENORMAL_OPERAND:
1094 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DENORMAL_OPERAND");
1095 ourstatus->value.sig = GDB_SIGNAL_FPE;
1097 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
1098 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ARRAY_BOUNDS_EXCEEDED");
1099 ourstatus->value.sig = GDB_SIGNAL_FPE;
1101 case STATUS_FLOAT_INEXACT_RESULT:
1102 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INEXACT_RESULT");
1103 ourstatus->value.sig = GDB_SIGNAL_FPE;
1105 case STATUS_FLOAT_INVALID_OPERATION:
1106 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INVALID_OPERATION");
1107 ourstatus->value.sig = GDB_SIGNAL_FPE;
1109 case STATUS_FLOAT_OVERFLOW:
1110 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_OVERFLOW");
1111 ourstatus->value.sig = GDB_SIGNAL_FPE;
1113 case STATUS_FLOAT_STACK_CHECK:
1114 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_STACK_CHECK");
1115 ourstatus->value.sig = GDB_SIGNAL_FPE;
1117 case STATUS_FLOAT_UNDERFLOW:
1118 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_UNDERFLOW");
1119 ourstatus->value.sig = GDB_SIGNAL_FPE;
1121 case STATUS_FLOAT_DIVIDE_BY_ZERO:
1122 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DIVIDE_BY_ZERO");
1123 ourstatus->value.sig = GDB_SIGNAL_FPE;
1125 case STATUS_INTEGER_DIVIDE_BY_ZERO:
1126 DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_DIVIDE_BY_ZERO");
1127 ourstatus->value.sig = GDB_SIGNAL_FPE;
1129 case STATUS_INTEGER_OVERFLOW:
1130 DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_OVERFLOW");
1131 ourstatus->value.sig = GDB_SIGNAL_FPE;
1133 case EXCEPTION_BREAKPOINT:
1134 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_BREAKPOINT");
1135 ourstatus->value.sig = GDB_SIGNAL_TRAP;
1138 DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_C");
1139 ourstatus->value.sig = GDB_SIGNAL_INT;
1141 case DBG_CONTROL_BREAK:
1142 DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_BREAK");
1143 ourstatus->value.sig = GDB_SIGNAL_INT;
1145 case EXCEPTION_SINGLE_STEP:
1146 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_SINGLE_STEP");
1147 ourstatus->value.sig = GDB_SIGNAL_TRAP;
1149 case EXCEPTION_ILLEGAL_INSTRUCTION:
1150 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ILLEGAL_INSTRUCTION");
1151 ourstatus->value.sig = GDB_SIGNAL_ILL;
1153 case EXCEPTION_PRIV_INSTRUCTION:
1154 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_PRIV_INSTRUCTION");
1155 ourstatus->value.sig = GDB_SIGNAL_ILL;
1157 case EXCEPTION_NONCONTINUABLE_EXCEPTION:
1158 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_NONCONTINUABLE_EXCEPTION");
1159 ourstatus->value.sig = GDB_SIGNAL_ILL;
1162 /* Treat unhandled first chance exceptions specially. */
1163 if (current_event.u.Exception.dwFirstChance)
1165 printf_unfiltered ("gdb: unknown target exception 0x%08x at %s\n",
1166 (unsigned) current_event.u.Exception.ExceptionRecord.ExceptionCode,
1167 host_address_to_string (
1168 current_event.u.Exception.ExceptionRecord.ExceptionAddress));
1169 ourstatus->value.sig = GDB_SIGNAL_UNKNOWN;
1173 last_sig = ourstatus->value.sig;
1177 /* Resume all artificially suspended threads if we are continuing
1180 windows_continue (DWORD continue_status, int id)
1186 DEBUG_EVENTS (("ContinueDebugEvent (cpid=%d, ctid=0x%x, %s);\n",
1187 (unsigned) current_event.dwProcessId,
1188 (unsigned) current_event.dwThreadId,
1189 continue_status == DBG_CONTINUE ?
1190 "DBG_CONTINUE" : "DBG_EXCEPTION_NOT_HANDLED"));
1192 for (th = &thread_head; (th = th->next) != NULL;)
1193 if ((id == -1 || id == (int) th->id)
1196 if (debug_registers_changed)
1198 th->context.ContextFlags |= CONTEXT_DEBUG_REGISTERS;
1199 th->context.Dr0 = dr[0];
1200 th->context.Dr1 = dr[1];
1201 th->context.Dr2 = dr[2];
1202 th->context.Dr3 = dr[3];
1203 th->context.Dr6 = DR6_CLEAR_VALUE;
1204 th->context.Dr7 = dr[7];
1206 if (th->context.ContextFlags)
1208 CHECK (SetThreadContext (th->h, &th->context));
1209 th->context.ContextFlags = 0;
1211 if (th->suspended > 0)
1212 (void) ResumeThread (th->h);
1216 res = ContinueDebugEvent (current_event.dwProcessId,
1217 current_event.dwThreadId,
1220 debug_registers_changed = 0;
1224 /* Called in pathological case where Windows fails to send a
1225 CREATE_PROCESS_DEBUG_EVENT after an attach. */
1227 fake_create_process (void)
1229 current_process_handle = OpenProcess (PROCESS_ALL_ACCESS, FALSE,
1230 current_event.dwProcessId);
1231 if (current_process_handle != NULL)
1232 open_process_used = 1;
1235 error (_("OpenProcess call failed, GetLastError = %u"),
1236 (unsigned) GetLastError ());
1237 /* We can not debug anything in that case. */
1239 main_thread_id = current_event.dwThreadId;
1240 current_thread = windows_add_thread (
1241 ptid_build (current_event.dwProcessId, 0,
1242 current_event.dwThreadId),
1243 current_event.u.CreateThread.hThread,
1244 current_event.u.CreateThread.lpThreadLocalBase);
1245 return main_thread_id;
1249 windows_resume (struct target_ops *ops,
1250 ptid_t ptid, int step, enum gdb_signal sig)
1253 DWORD continue_status = DBG_CONTINUE;
1255 /* A specific PTID means `step only this thread id'. */
1256 int resume_all = ptid_equal (ptid, minus_one_ptid);
1258 /* If we're continuing all threads, it's the current inferior that
1259 should be handled specially. */
1261 ptid = inferior_ptid;
1263 if (sig != GDB_SIGNAL_0)
1265 if (current_event.dwDebugEventCode != EXCEPTION_DEBUG_EVENT)
1267 DEBUG_EXCEPT(("Cannot continue with signal %d here.\n",sig));
1269 else if (sig == last_sig)
1270 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1273 /* This code does not seem to work, because
1274 the kernel does probably not consider changes in the ExceptionRecord
1275 structure when passing the exception to the inferior.
1276 Note that this seems possible in the exception handler itself. */
1279 for (i = 0; xlate[i].them != -1; i++)
1280 if (xlate[i].us == sig)
1282 current_event.u.Exception.ExceptionRecord.ExceptionCode
1284 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1287 if (continue_status == DBG_CONTINUE)
1289 DEBUG_EXCEPT(("Cannot continue with signal %d.\n",sig));
1293 DEBUG_EXCEPT(("Can only continue with recieved signal %d.\n",
1297 last_sig = GDB_SIGNAL_0;
1299 DEBUG_EXEC (("gdb: windows_resume (pid=%d, tid=%ld, step=%d, sig=%d);\n",
1300 ptid_get_pid (ptid), ptid_get_tid (ptid), step, sig));
1302 /* Get context for currently selected thread. */
1303 th = thread_rec (ptid_get_tid (inferior_ptid), FALSE);
1308 /* Single step by setting t bit. */
1309 struct regcache *regcache = get_current_regcache ();
1310 struct gdbarch *gdbarch = get_regcache_arch (regcache);
1311 windows_fetch_inferior_registers (ops, regcache,
1312 gdbarch_ps_regnum (gdbarch));
1313 th->context.EFlags |= FLAG_TRACE_BIT;
1316 if (th->context.ContextFlags)
1318 if (debug_registers_changed)
1320 th->context.Dr0 = dr[0];
1321 th->context.Dr1 = dr[1];
1322 th->context.Dr2 = dr[2];
1323 th->context.Dr3 = dr[3];
1324 th->context.Dr6 = DR6_CLEAR_VALUE;
1325 th->context.Dr7 = dr[7];
1327 CHECK (SetThreadContext (th->h, &th->context));
1328 th->context.ContextFlags = 0;
1332 /* Allow continuing with the same signal that interrupted us.
1333 Otherwise complain. */
1336 windows_continue (continue_status, -1);
1338 windows_continue (continue_status, ptid_get_tid (ptid));
1341 /* Ctrl-C handler used when the inferior is not run in the same console. The
1342 handler is in charge of interrupting the inferior using DebugBreakProcess.
1343 Note that this function is not available prior to Windows XP. In this case
1344 we emit a warning. */
1346 ctrl_c_handler (DWORD event_type)
1348 const int attach_flag = current_inferior ()->attach_flag;
1350 /* Only handle Ctrl-C and Ctrl-Break events. Ignore others. */
1351 if (event_type != CTRL_C_EVENT && event_type != CTRL_BREAK_EVENT)
1354 /* If the inferior and the debugger share the same console, do nothing as
1355 the inferior has also received the Ctrl-C event. */
1356 if (!new_console && !attach_flag)
1359 if (!DebugBreakProcess (current_process_handle))
1360 warning (_("Could not interrupt program. "
1361 "Press Ctrl-c in the program console."));
1363 /* Return true to tell that Ctrl-C has been handled. */
1367 /* Get the next event from the child. Return 1 if the event requires
1368 handling by WFI (or whatever). */
1370 get_windows_debug_event (struct target_ops *ops,
1371 int pid, struct target_waitstatus *ourstatus)
1374 DWORD continue_status, event_code;
1376 static thread_info dummy_thread_info;
1379 last_sig = GDB_SIGNAL_0;
1381 if (!(debug_event = WaitForDebugEvent (¤t_event, 1000)))
1385 continue_status = DBG_CONTINUE;
1387 event_code = current_event.dwDebugEventCode;
1388 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
1390 have_saved_context = 0;
1394 case CREATE_THREAD_DEBUG_EVENT:
1395 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1396 (unsigned) current_event.dwProcessId,
1397 (unsigned) current_event.dwThreadId,
1398 "CREATE_THREAD_DEBUG_EVENT"));
1399 if (saw_create != 1)
1401 struct inferior *inf;
1402 inf = find_inferior_pid (current_event.dwProcessId);
1403 if (!saw_create && inf->attach_flag)
1405 /* Kludge around a Windows bug where first event is a create
1406 thread event. Caused when attached process does not have
1408 retval = fake_create_process ();
1414 /* Record the existence of this thread. */
1415 retval = current_event.dwThreadId;
1416 th = windows_add_thread (ptid_build (current_event.dwProcessId, 0,
1417 current_event.dwThreadId),
1418 current_event.u.CreateThread.hThread,
1419 current_event.u.CreateThread.lpThreadLocalBase);
1423 case EXIT_THREAD_DEBUG_EVENT:
1424 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1425 (unsigned) current_event.dwProcessId,
1426 (unsigned) current_event.dwThreadId,
1427 "EXIT_THREAD_DEBUG_EVENT"));
1429 if (current_event.dwThreadId != main_thread_id)
1431 windows_delete_thread (ptid_build (current_event.dwProcessId, 0,
1432 current_event.dwThreadId),
1433 current_event.u.ExitThread.dwExitCode);
1434 th = &dummy_thread_info;
1438 case CREATE_PROCESS_DEBUG_EVENT:
1439 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1440 (unsigned) current_event.dwProcessId,
1441 (unsigned) current_event.dwThreadId,
1442 "CREATE_PROCESS_DEBUG_EVENT"));
1443 CloseHandle (current_event.u.CreateProcessInfo.hFile);
1444 if (++saw_create != 1)
1447 current_process_handle = current_event.u.CreateProcessInfo.hProcess;
1449 windows_delete_thread (ptid_build (current_event.dwProcessId, 0,
1452 main_thread_id = current_event.dwThreadId;
1453 /* Add the main thread. */
1454 th = windows_add_thread (ptid_build (current_event.dwProcessId, 0,
1455 current_event.dwThreadId),
1456 current_event.u.CreateProcessInfo.hThread,
1457 current_event.u.CreateProcessInfo.lpThreadLocalBase);
1458 retval = current_event.dwThreadId;
1461 case EXIT_PROCESS_DEBUG_EVENT:
1462 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1463 (unsigned) current_event.dwProcessId,
1464 (unsigned) current_event.dwThreadId,
1465 "EXIT_PROCESS_DEBUG_EVENT"));
1466 if (!windows_initialization_done)
1468 target_terminal_ours ();
1469 target_mourn_inferior ();
1470 error (_("During startup program exited with code 0x%x."),
1471 (unsigned int) current_event.u.ExitProcess.dwExitCode);
1473 else if (saw_create == 1)
1475 ourstatus->kind = TARGET_WAITKIND_EXITED;
1476 ourstatus->value.integer = current_event.u.ExitProcess.dwExitCode;
1477 retval = main_thread_id;
1481 case LOAD_DLL_DEBUG_EVENT:
1482 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1483 (unsigned) current_event.dwProcessId,
1484 (unsigned) current_event.dwThreadId,
1485 "LOAD_DLL_DEBUG_EVENT"));
1486 CloseHandle (current_event.u.LoadDll.hFile);
1487 if (saw_create != 1 || ! windows_initialization_done)
1489 catch_errors (handle_load_dll, NULL, (char *) "", RETURN_MASK_ALL);
1490 ourstatus->kind = TARGET_WAITKIND_LOADED;
1491 ourstatus->value.integer = 0;
1492 retval = main_thread_id;
1495 case UNLOAD_DLL_DEBUG_EVENT:
1496 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1497 (unsigned) current_event.dwProcessId,
1498 (unsigned) current_event.dwThreadId,
1499 "UNLOAD_DLL_DEBUG_EVENT"));
1500 if (saw_create != 1 || ! windows_initialization_done)
1502 catch_errors (handle_unload_dll, NULL, (char *) "", RETURN_MASK_ALL);
1503 ourstatus->kind = TARGET_WAITKIND_LOADED;
1504 ourstatus->value.integer = 0;
1505 retval = main_thread_id;
1508 case EXCEPTION_DEBUG_EVENT:
1509 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1510 (unsigned) current_event.dwProcessId,
1511 (unsigned) current_event.dwThreadId,
1512 "EXCEPTION_DEBUG_EVENT"));
1513 if (saw_create != 1)
1515 switch (handle_exception (ourstatus))
1518 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1521 retval = current_event.dwThreadId;
1525 continue_status = -1;
1530 case OUTPUT_DEBUG_STRING_EVENT: /* Message from the kernel. */
1531 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1532 (unsigned) current_event.dwProcessId,
1533 (unsigned) current_event.dwThreadId,
1534 "OUTPUT_DEBUG_STRING_EVENT"));
1535 if (saw_create != 1)
1537 retval = handle_output_debug_string (ourstatus);
1541 if (saw_create != 1)
1543 printf_unfiltered ("gdb: kernel event for pid=%u tid=0x%x\n",
1544 (unsigned) current_event.dwProcessId,
1545 (unsigned) current_event.dwThreadId);
1546 printf_unfiltered (" unknown event code %u\n",
1547 (unsigned) current_event.dwDebugEventCode);
1551 if (!retval || saw_create != 1)
1553 if (continue_status == -1)
1554 windows_resume (ops, minus_one_ptid, 0, 1);
1556 CHECK (windows_continue (continue_status, -1));
1560 inferior_ptid = ptid_build (current_event.dwProcessId, 0,
1562 current_thread = th ?: thread_rec (current_event.dwThreadId, TRUE);
1569 /* Wait for interesting events to occur in the target process. */
1571 windows_wait (struct target_ops *ops,
1572 ptid_t ptid, struct target_waitstatus *ourstatus, int options)
1576 target_terminal_ours ();
1578 /* We loop when we get a non-standard exception rather than return
1579 with a SPURIOUS because resume can try and step or modify things,
1580 which needs a current_thread->h. But some of these exceptions mark
1581 the birth or death of threads, which mean that the current thread
1582 isn't necessarily what you think it is. */
1588 /* If the user presses Ctrl-c while the debugger is waiting
1589 for an event, he expects the debugger to interrupt his program
1590 and to get the prompt back. There are two possible situations:
1592 - The debugger and the program do not share the console, in
1593 which case the Ctrl-c event only reached the debugger.
1594 In that case, the ctrl_c handler will take care of interrupting
1595 the inferior. Note that this case is working starting with
1596 Windows XP. For Windows 2000, Ctrl-C should be pressed in the
1599 - The debugger and the program share the same console, in which
1600 case both debugger and inferior will receive the Ctrl-c event.
1601 In that case the ctrl_c handler will ignore the event, as the
1602 Ctrl-c event generated inside the inferior will trigger the
1603 expected debug event.
1605 FIXME: brobecker/2008-05-20: If the inferior receives the
1606 signal first and the delay until GDB receives that signal
1607 is sufficiently long, GDB can sometimes receive the SIGINT
1608 after we have unblocked the CTRL+C handler. This would
1609 lead to the debugger stopping prematurely while handling
1610 the new-thread event that comes with the handling of the SIGINT
1611 inside the inferior, and then stop again immediately when
1612 the user tries to resume the execution in the inferior.
1613 This is a classic race that we should try to fix one day. */
1614 SetConsoleCtrlHandler (&ctrl_c_handler, TRUE);
1615 retval = get_windows_debug_event (ops, pid, ourstatus);
1616 SetConsoleCtrlHandler (&ctrl_c_handler, FALSE);
1619 return ptid_build (current_event.dwProcessId, 0, retval);
1624 if (deprecated_ui_loop_hook != NULL)
1625 detach = deprecated_ui_loop_hook (0);
1628 windows_kill_inferior (ops);
1633 /* Iterate over all DLLs currently mapped by our inferior, and
1634 add them to our list of solibs. */
1637 windows_add_all_dlls (void)
1640 HMODULE dummy_hmodule;
1645 if (EnumProcessModules (current_process_handle, &dummy_hmodule,
1646 sizeof (HMODULE), &cb_needed) == 0)
1652 hmodules = (HMODULE *) alloca (cb_needed);
1653 if (EnumProcessModules (current_process_handle, hmodules,
1654 cb_needed, &cb_needed) == 0)
1657 for (i = 1; i < (int) (cb_needed / sizeof (HMODULE)); i++)
1661 wchar_t dll_name[__PMAX];
1664 char dll_name[__PMAX];
1667 if (GetModuleInformation (current_process_handle, hmodules[i],
1668 &mi, sizeof (mi)) == 0)
1670 if (GetModuleFileNameEx (current_process_handle, hmodules[i],
1671 dll_name, sizeof (dll_name)) == 0)
1674 wcstombs (name, dll_name, __PMAX);
1679 solib_end->next = windows_make_so (name, mi.lpBaseOfDll);
1680 solib_end = solib_end->next;
1685 do_initial_windows_stuff (struct target_ops *ops, DWORD pid, int attaching)
1687 extern int stop_after_trap;
1689 struct inferior *inf;
1690 struct thread_info *tp;
1692 last_sig = GDB_SIGNAL_0;
1694 exception_count = 0;
1695 open_process_used = 0;
1696 debug_registers_changed = 0;
1697 debug_registers_used = 0;
1698 for (i = 0; i < sizeof (dr) / sizeof (dr[0]); i++)
1701 cygwin_load_start = cygwin_load_end = 0;
1703 current_event.dwProcessId = pid;
1704 memset (¤t_event, 0, sizeof (current_event));
1706 disable_breakpoints_in_shlibs ();
1707 windows_clear_solib ();
1708 clear_proceed_status ();
1709 init_wait_for_inferior ();
1711 inf = current_inferior ();
1712 inferior_appeared (inf, pid);
1713 inf->attach_flag = attaching;
1715 /* Make the new process the current inferior, so terminal handling
1716 can rely on it. When attaching, we don't know about any thread
1717 id here, but that's OK --- nothing should be referencing the
1718 current thread until we report an event out of windows_wait. */
1719 inferior_ptid = pid_to_ptid (pid);
1721 terminal_init_inferior_with_pgrp (pid);
1722 target_terminal_inferior ();
1724 windows_initialization_done = 0;
1725 inf->control.stop_soon = STOP_QUIETLY;
1728 stop_after_trap = 1;
1729 wait_for_inferior ();
1730 tp = inferior_thread ();
1731 if (tp->suspend.stop_signal != GDB_SIGNAL_TRAP)
1732 resume (0, tp->suspend.stop_signal);
1737 /* Now that the inferior has been started and all DLLs have been mapped,
1738 we can iterate over all DLLs and load them in. */
1739 windows_add_all_dlls ();
1741 windows_initialization_done = 1;
1742 inf->control.stop_soon = NO_STOP_QUIETLY;
1743 stop_after_trap = 0;
1747 /* Try to set or remove a user privilege to the current process. Return -1
1748 if that fails, the previous setting of that privilege otherwise.
1750 This code is copied from the Cygwin source code and rearranged to allow
1751 dynamically loading of the needed symbols from advapi32 which is only
1752 available on NT/2K/XP. */
1754 set_process_privilege (const char *privilege, BOOL enable)
1756 HANDLE token_hdl = NULL;
1758 TOKEN_PRIVILEGES new_priv, orig_priv;
1762 if (!OpenProcessToken (GetCurrentProcess (),
1763 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
1767 if (!LookupPrivilegeValueA (NULL, privilege, &restore_priv))
1770 new_priv.PrivilegeCount = 1;
1771 new_priv.Privileges[0].Luid = restore_priv;
1772 new_priv.Privileges[0].Attributes = enable ? SE_PRIVILEGE_ENABLED : 0;
1774 if (!AdjustTokenPrivileges (token_hdl, FALSE, &new_priv,
1775 sizeof orig_priv, &orig_priv, &size))
1778 /* Disabled, otherwise every `attach' in an unprivileged user session
1779 would raise the "Failed to get SE_DEBUG_NAME privilege" warning in
1780 windows_attach(). */
1781 /* AdjustTokenPrivileges returns TRUE even if the privilege could not
1782 be enabled. GetLastError () returns an correct error code, though. */
1783 if (enable && GetLastError () == ERROR_NOT_ALL_ASSIGNED)
1787 ret = orig_priv.Privileges[0].Attributes == SE_PRIVILEGE_ENABLED ? 1 : 0;
1791 CloseHandle (token_hdl);
1796 /* Attach to process PID, then initialize for debugging it. */
1798 windows_attach (struct target_ops *ops, char *args, int from_tty)
1803 pid = parse_pid_to_attach (args);
1805 if (set_process_privilege (SE_DEBUG_NAME, TRUE) < 0)
1807 printf_unfiltered ("Warning: Failed to get SE_DEBUG_NAME privilege\n");
1808 printf_unfiltered ("This can cause attach to "
1809 "fail on Windows NT/2K/XP\n");
1812 windows_init_thread_list ();
1813 ok = DebugActiveProcess (pid);
1819 /* Try fall back to Cygwin pid. */
1820 pid = cygwin_internal (CW_CYGWIN_PID_TO_WINPID, pid);
1823 ok = DebugActiveProcess (pid);
1828 error (_("Can't attach to process."));
1830 DebugSetProcessKillOnExit (FALSE);
1834 char *exec_file = (char *) get_exec_file (0);
1837 printf_unfiltered ("Attaching to program `%s', %s\n", exec_file,
1838 target_pid_to_str (pid_to_ptid (pid)));
1840 printf_unfiltered ("Attaching to %s\n",
1841 target_pid_to_str (pid_to_ptid (pid)));
1843 gdb_flush (gdb_stdout);
1846 do_initial_windows_stuff (ops, pid, 1);
1847 target_terminal_ours ();
1851 windows_detach (struct target_ops *ops, const char *args, int from_tty)
1856 windows_resume (ops, ptid, 0, GDB_SIGNAL_0);
1858 if (!DebugActiveProcessStop (current_event.dwProcessId))
1860 error (_("Can't detach process %u (error %u)"),
1861 (unsigned) current_event.dwProcessId, (unsigned) GetLastError ());
1864 DebugSetProcessKillOnExit (FALSE);
1866 if (detached && from_tty)
1868 char *exec_file = get_exec_file (0);
1871 printf_unfiltered ("Detaching from program: %s, Pid %u\n", exec_file,
1872 (unsigned) current_event.dwProcessId);
1873 gdb_flush (gdb_stdout);
1876 i386_cleanup_dregs ();
1877 inferior_ptid = null_ptid;
1878 detach_inferior (current_event.dwProcessId);
1880 unpush_target (ops);
1883 /* Try to determine the executable filename.
1885 EXE_NAME_RET is a pointer to a buffer whose size is EXE_NAME_MAX_LEN.
1887 Upon success, the filename is stored inside EXE_NAME_RET, and
1888 this function returns nonzero.
1890 Otherwise, this function returns zero and the contents of
1891 EXE_NAME_RET is undefined. */
1894 windows_get_exec_module_filename (char *exe_name_ret, size_t exe_name_max_len)
1901 if (!EnumProcessModules (current_process_handle, &dh_buf,
1902 sizeof (HMODULE), &cbNeeded) || !cbNeeded)
1905 /* We know the executable is always first in the list of modules,
1906 which we just fetched. So no need to fetch more. */
1910 /* Cygwin prefers that the path be in /x/y/z format, so extract
1911 the filename into a temporary buffer first, and then convert it
1912 to POSIX format into the destination buffer. */
1913 cygwin_buf_t *pathbuf = alloca (exe_name_max_len * sizeof (cygwin_buf_t));
1915 len = GetModuleFileNameEx (current_process_handle,
1916 dh_buf, pathbuf, exe_name_max_len);
1918 error (_("Error getting executable filename: %u."),
1919 (unsigned) GetLastError ());
1920 if (cygwin_conv_path (CCP_WIN_W_TO_POSIX, pathbuf, exe_name_ret,
1921 exe_name_max_len) < 0)
1922 error (_("Error converting executable filename to POSIX: %d."), errno);
1925 len = GetModuleFileNameEx (current_process_handle,
1926 dh_buf, exe_name_ret, exe_name_max_len);
1928 error (_("Error getting executable filename: %u."),
1929 (unsigned) GetLastError ());
1932 return 1; /* success */
1935 /* The pid_to_exec_file target_ops method for this platform. */
1938 windows_pid_to_exec_file (struct target_ops *self, int pid)
1940 static char path[__PMAX];
1942 /* Try to find exe name as symlink target of /proc/<pid>/exe. */
1944 char procexe[sizeof ("/proc/4294967295/exe")];
1946 xsnprintf (procexe, sizeof (procexe), "/proc/%u/exe", pid);
1947 nchars = readlink (procexe, path, sizeof(path));
1948 if (nchars > 0 && nchars < sizeof (path))
1950 path[nchars] = '\0'; /* Got it */
1955 /* If we get here then either Cygwin is hosed, this isn't a Cygwin version
1956 of gdb, or we're trying to debug a non-Cygwin windows executable. */
1957 if (!windows_get_exec_module_filename (path, sizeof (path)))
1963 /* Print status information about what we're accessing. */
1966 windows_files_info (struct target_ops *ignore)
1968 struct inferior *inf = current_inferior ();
1970 printf_unfiltered ("\tUsing the running image of %s %s.\n",
1971 inf->attach_flag ? "attached" : "child",
1972 target_pid_to_str (inferior_ptid));
1976 windows_open (char *arg, int from_tty)
1978 error (_("Use the \"run\" command to start a Unix child process."));
1981 /* Modify CreateProcess parameters for use of a new separate console.
1983 *FLAGS: DWORD parameter for general process creation flags.
1984 *SI: STARTUPINFO structure, for which the console window size and
1985 console buffer size is filled in if GDB is running in a console.
1986 to create the new console.
1987 The size of the used font is not available on all versions of
1988 Windows OS. Furthermore, the current font might not be the default
1989 font, but this is still better than before.
1990 If the windows and buffer sizes are computed,
1991 SI->DWFLAGS is changed so that this information is used
1992 by CreateProcess function. */
1995 windows_set_console_info (STARTUPINFO *si, DWORD *flags)
1997 HANDLE hconsole = CreateFile ("CONOUT$", GENERIC_READ | GENERIC_WRITE,
1998 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
2000 if (hconsole != INVALID_HANDLE_VALUE)
2002 CONSOLE_SCREEN_BUFFER_INFO sbinfo;
2004 CONSOLE_FONT_INFO cfi;
2006 GetCurrentConsoleFont (hconsole, FALSE, &cfi);
2007 font_size = GetConsoleFontSize (hconsole, cfi.nFont);
2008 GetConsoleScreenBufferInfo(hconsole, &sbinfo);
2009 si->dwXSize = sbinfo.srWindow.Right - sbinfo.srWindow.Left + 1;
2010 si->dwYSize = sbinfo.srWindow.Bottom - sbinfo.srWindow.Top + 1;
2012 si->dwXSize *= font_size.X;
2016 si->dwYSize *= font_size.Y;
2019 si->dwXCountChars = sbinfo.dwSize.X;
2020 si->dwYCountChars = sbinfo.dwSize.Y;
2021 si->dwFlags |= STARTF_USESIZE | STARTF_USECOUNTCHARS;
2023 *flags |= CREATE_NEW_CONSOLE;
2027 /* Function called by qsort to sort environment strings. */
2030 envvar_cmp (const void *a, const void *b)
2032 const char **p = (const char **) a;
2033 const char **q = (const char **) b;
2034 return strcasecmp (*p, *q);
2040 clear_win32_environment (char **env)
2044 wchar_t *copy = NULL, *equalpos;
2046 for (i = 0; env[i] && *env[i]; i++)
2048 len = mbstowcs (NULL, env[i], 0) + 1;
2049 copy = (wchar_t *) xrealloc (copy, len * sizeof (wchar_t));
2050 mbstowcs (copy, env[i], len);
2051 equalpos = wcschr (copy, L'=');
2054 SetEnvironmentVariableW (copy, NULL);
2060 /* Start an inferior windows child process and sets inferior_ptid to its pid.
2061 EXEC_FILE is the file to run.
2062 ALLARGS is a string containing the arguments to the program.
2063 ENV is the environment vector to pass. Errors reported with error(). */
2066 windows_create_inferior (struct target_ops *ops, char *exec_file,
2067 char *allargs, char **in_env, int from_tty)
2071 cygwin_buf_t real_path[__PMAX];
2072 cygwin_buf_t shell[__PMAX]; /* Path to shell */
2074 cygwin_buf_t *toexec;
2075 cygwin_buf_t *cygallargs;
2077 char **old_env = NULL;
2081 int ostdin, ostdout, ostderr;
2083 char real_path[__PMAX];
2084 char shell[__PMAX]; /* Path to shell */
2096 PROCESS_INFORMATION pi;
2099 const char *inferior_io_terminal = get_inferior_io_terminal ();
2102 error (_("No executable specified, use `target exec'."));
2104 memset (&si, 0, sizeof (si));
2105 si.cb = sizeof (si);
2108 flags |= CREATE_NEW_PROCESS_GROUP;
2111 windows_set_console_info (&si, &flags);
2116 flags |= DEBUG_ONLY_THIS_PROCESS;
2117 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, exec_file, real_path,
2118 __PMAX * sizeof (cygwin_buf_t)) < 0)
2119 error (_("Error starting executable: %d"), errno);
2122 len = mbstowcs (NULL, allargs, 0) + 1;
2123 if (len == (size_t) -1)
2124 error (_("Error starting executable: %d"), errno);
2125 cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
2126 mbstowcs (cygallargs, allargs, len);
2128 cygallargs = allargs;
2133 sh = getenv ("SHELL");
2136 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, sh, shell, __PMAX) < 0)
2137 error (_("Error starting executable via shell: %d"), errno);
2139 len = sizeof (L" -c 'exec '") + mbstowcs (NULL, exec_file, 0)
2140 + mbstowcs (NULL, allargs, 0) + 2;
2141 cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
2142 swprintf (cygallargs, len, L" -c 'exec %s %s'", exec_file, allargs);
2144 len = (sizeof (" -c 'exec '") + strlen (exec_file)
2145 + strlen (allargs) + 2);
2146 cygallargs = (char *) alloca (len);
2147 xsnprintf (cygallargs, len, " -c 'exec %s %s'", exec_file, allargs);
2150 flags |= DEBUG_PROCESS;
2154 args = (cygwin_buf_t *) alloca ((wcslen (toexec) + wcslen (cygallargs) + 2)
2155 * sizeof (wchar_t));
2156 wcscpy (args, toexec);
2157 wcscat (args, L" ");
2158 wcscat (args, cygallargs);
2160 args = (cygwin_buf_t *) alloca (strlen (toexec) + strlen (cygallargs) + 2);
2161 strcpy (args, toexec);
2163 strcat (args, cygallargs);
2166 #ifdef CW_CVT_ENV_TO_WINENV
2167 /* First try to create a direct Win32 copy of the POSIX environment. */
2168 w32_env = (PWCHAR) cygwin_internal (CW_CVT_ENV_TO_WINENV, in_env);
2169 if (w32_env != (PWCHAR) -1)
2170 flags |= CREATE_UNICODE_ENVIRONMENT;
2172 /* If that fails, fall back to old method tweaking GDB's environment. */
2175 /* Reset all Win32 environment variables to avoid leftover on next run. */
2176 clear_win32_environment (environ);
2177 /* Prepare the environment vars for CreateProcess. */
2180 cygwin_internal (CW_SYNC_WINENV);
2184 if (!inferior_io_terminal)
2185 tty = ostdin = ostdout = ostderr = -1;
2188 tty = open (inferior_io_terminal, O_RDWR | O_NOCTTY);
2191 print_sys_errmsg (inferior_io_terminal, errno);
2192 ostdin = ostdout = ostderr = -1;
2205 windows_init_thread_list ();
2206 ret = CreateProcess (0,
2207 args, /* command line */
2208 NULL, /* Security */
2210 TRUE, /* inherit handles */
2211 flags, /* start flags */
2212 w32_env, /* environment */
2213 NULL, /* current directory */
2217 /* Just free the Win32 environment, if it could be created. */
2221 /* Reset all environment variables to avoid leftover on next run. */
2222 clear_win32_environment (in_env);
2223 /* Restore normal GDB environment variables. */
2225 cygwin_internal (CW_SYNC_WINENV);
2240 /* Build the command line, a space-separated list of tokens where
2241 the first token is the name of the module to be executed.
2242 To avoid ambiguities introduced by spaces in the module name,
2244 args_len = strlen (toexec) + 2 /* quotes */ + strlen (allargs) + 2;
2245 args = alloca (args_len);
2246 xsnprintf (args, args_len, "\"%s\" %s", toexec, allargs);
2248 flags |= DEBUG_ONLY_THIS_PROCESS;
2250 if (!inferior_io_terminal)
2251 tty = INVALID_HANDLE_VALUE;
2254 SECURITY_ATTRIBUTES sa;
2255 sa.nLength = sizeof(sa);
2256 sa.lpSecurityDescriptor = 0;
2257 sa.bInheritHandle = TRUE;
2258 tty = CreateFileA (inferior_io_terminal, GENERIC_READ | GENERIC_WRITE,
2259 0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
2260 if (tty == INVALID_HANDLE_VALUE)
2261 warning (_("Warning: Failed to open TTY %s, error %#x."),
2262 inferior_io_terminal, (unsigned) GetLastError ());
2266 si.hStdOutput = tty;
2268 si.dwFlags |= STARTF_USESTDHANDLES;
2272 /* CreateProcess takes the environment list as a null terminated set of
2273 strings (i.e. two nulls terminate the list). */
2275 /* Get total size for env strings. */
2276 for (envlen = 0, i = 0; in_env[i] && *in_env[i]; i++)
2277 envlen += strlen (in_env[i]) + 1;
2279 envsize = sizeof (in_env[0]) * (i + 1);
2280 env = (char **) alloca (envsize);
2281 memcpy (env, in_env, envsize);
2282 /* Windows programs expect the environment block to be sorted. */
2283 qsort (env, i, sizeof (char *), envvar_cmp);
2285 w32env = alloca (envlen + 1);
2287 /* Copy env strings into new buffer. */
2288 for (temp = w32env, i = 0; env[i] && *env[i]; i++)
2290 strcpy (temp, env[i]);
2291 temp += strlen (temp) + 1;
2294 /* Final nil string to terminate new env. */
2297 windows_init_thread_list ();
2298 ret = CreateProcessA (0,
2299 args, /* command line */
2300 NULL, /* Security */
2302 TRUE, /* inherit handles */
2303 flags, /* start flags */
2304 w32env, /* environment */
2305 NULL, /* current directory */
2308 if (tty != INVALID_HANDLE_VALUE)
2313 error (_("Error creating process %s, (error %u)."),
2314 exec_file, (unsigned) GetLastError ());
2316 CloseHandle (pi.hThread);
2317 CloseHandle (pi.hProcess);
2319 if (useshell && shell[0] != '\0')
2324 do_initial_windows_stuff (ops, pi.dwProcessId, 0);
2326 /* windows_continue (DBG_CONTINUE, -1); */
2330 windows_mourn_inferior (struct target_ops *ops)
2332 (void) windows_continue (DBG_CONTINUE, -1);
2333 i386_cleanup_dregs();
2334 if (open_process_used)
2336 CHECK (CloseHandle (current_process_handle));
2337 open_process_used = 0;
2339 unpush_target (ops);
2340 generic_mourn_inferior ();
2343 /* Send a SIGINT to the process group. This acts just like the user typed a
2344 ^C on the controlling terminal. */
2347 windows_stop (struct target_ops *self, ptid_t ptid)
2349 DEBUG_EVENTS (("gdb: GenerateConsoleCtrlEvent (CTRLC_EVENT, 0)\n"));
2350 CHECK (GenerateConsoleCtrlEvent (CTRL_C_EVENT, current_event.dwProcessId));
2351 registers_changed (); /* refresh register state */
2354 /* Helper for windows_xfer_partial that handles memory transfers.
2355 Arguments are like target_xfer_partial. */
2357 static enum target_xfer_status
2358 windows_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
2359 ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
2363 DWORD lasterror = 0;
2365 if (writebuf != NULL)
2367 DEBUG_MEM (("gdb: write target memory, %s bytes at %s\n",
2368 pulongest (len), core_addr_to_string (memaddr)));
2369 success = WriteProcessMemory (current_process_handle,
2370 (LPVOID) (uintptr_t) memaddr, writebuf,
2373 lasterror = GetLastError ();
2374 FlushInstructionCache (current_process_handle,
2375 (LPCVOID) (uintptr_t) memaddr, len);
2379 DEBUG_MEM (("gdb: read target memory, %s bytes at %s\n",
2380 pulongest (len), core_addr_to_string (memaddr)));
2381 success = ReadProcessMemory (current_process_handle,
2382 (LPCVOID) (uintptr_t) memaddr, readbuf,
2385 lasterror = GetLastError ();
2387 *xfered_len = (ULONGEST) done;
2388 if (!success && lasterror == ERROR_PARTIAL_COPY && done > 0)
2389 return TARGET_XFER_OK;
2391 return success ? TARGET_XFER_OK : TARGET_XFER_E_IO;
2395 windows_kill_inferior (struct target_ops *ops)
2397 CHECK (TerminateProcess (current_process_handle, 0));
2401 if (!windows_continue (DBG_CONTINUE, -1))
2403 if (!WaitForDebugEvent (¤t_event, INFINITE))
2405 if (current_event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
2409 target_mourn_inferior (); /* Or just windows_mourn_inferior? */
2413 windows_prepare_to_store (struct target_ops *self, struct regcache *regcache)
2415 /* Do nothing, since we can store individual regs. */
2419 windows_can_run (struct target_ops *self)
2425 windows_close (struct target_ops *self)
2427 DEBUG_EVENTS (("gdb: windows_close, inferior_ptid=%d\n",
2428 ptid_get_pid (inferior_ptid)));
2431 /* Convert pid to printable format. */
2433 windows_pid_to_str (struct target_ops *ops, ptid_t ptid)
2435 static char buf[80];
2437 if (ptid_get_tid (ptid) != 0)
2439 snprintf (buf, sizeof (buf), "Thread %d.0x%lx",
2440 ptid_get_pid (ptid), ptid_get_tid (ptid));
2444 return normal_pid_to_str (ptid);
2447 static enum target_xfer_status
2448 windows_xfer_shared_libraries (struct target_ops *ops,
2449 enum target_object object, const char *annex,
2450 gdb_byte *readbuf, const gdb_byte *writebuf,
2451 ULONGEST offset, ULONGEST len,
2452 ULONGEST *xfered_len)
2454 struct obstack obstack;
2460 return TARGET_XFER_E_IO;
2462 obstack_init (&obstack);
2463 obstack_grow_str (&obstack, "<library-list>\n");
2464 for (so = solib_start.next; so; so = so->next)
2465 windows_xfer_shared_library (so->so_name, (CORE_ADDR)
2466 (uintptr_t) so->lm_info->load_addr,
2467 target_gdbarch (), &obstack);
2468 obstack_grow_str0 (&obstack, "</library-list>\n");
2470 buf = obstack_finish (&obstack);
2471 len_avail = strlen (buf);
2472 if (offset >= len_avail)
2476 if (len > len_avail - offset)
2477 len = len_avail - offset;
2478 memcpy (readbuf, buf + offset, len);
2481 obstack_free (&obstack, NULL);
2482 *xfered_len = (ULONGEST) len;
2483 return TARGET_XFER_OK;
2486 static enum target_xfer_status
2487 windows_xfer_partial (struct target_ops *ops, enum target_object object,
2488 const char *annex, gdb_byte *readbuf,
2489 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
2490 ULONGEST *xfered_len)
2494 case TARGET_OBJECT_MEMORY:
2495 return windows_xfer_memory (readbuf, writebuf, offset, len, xfered_len);
2497 case TARGET_OBJECT_LIBRARIES:
2498 return windows_xfer_shared_libraries (ops, object, annex, readbuf,
2499 writebuf, offset, len, xfered_len);
2502 if (ops->beneath != NULL)
2503 return ops->beneath->to_xfer_partial (ops->beneath, object, annex,
2504 readbuf, writebuf, offset, len,
2506 return TARGET_XFER_E_IO;
2510 /* Provide thread local base, i.e. Thread Information Block address.
2511 Returns 1 if ptid is found and sets *ADDR to thread_local_base. */
2514 windows_get_tib_address (struct target_ops *self,
2515 ptid_t ptid, CORE_ADDR *addr)
2519 th = thread_rec (ptid_get_tid (ptid), 0);
2524 *addr = th->thread_local_base;
2530 windows_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
2532 return ptid_build (ptid_get_pid (inferior_ptid), 0, lwp);
2536 init_windows_ops (void)
2538 windows_ops.to_shortname = "child";
2539 windows_ops.to_longname = "Win32 child process";
2540 windows_ops.to_doc = "Win32 child process (started by the \"run\" command).";
2541 windows_ops.to_open = windows_open;
2542 windows_ops.to_close = windows_close;
2543 windows_ops.to_attach = windows_attach;
2544 windows_ops.to_attach_no_wait = 1;
2545 windows_ops.to_detach = windows_detach;
2546 windows_ops.to_resume = windows_resume;
2547 windows_ops.to_wait = windows_wait;
2548 windows_ops.to_fetch_registers = windows_fetch_inferior_registers;
2549 windows_ops.to_store_registers = windows_store_inferior_registers;
2550 windows_ops.to_prepare_to_store = windows_prepare_to_store;
2551 windows_ops.to_xfer_partial = windows_xfer_partial;
2552 windows_ops.to_files_info = windows_files_info;
2553 windows_ops.to_insert_breakpoint = memory_insert_breakpoint;
2554 windows_ops.to_remove_breakpoint = memory_remove_breakpoint;
2555 windows_ops.to_terminal_init = terminal_init_inferior;
2556 windows_ops.to_terminal_inferior = terminal_inferior;
2557 windows_ops.to_terminal_ours_for_output = terminal_ours_for_output;
2558 windows_ops.to_terminal_ours = terminal_ours;
2559 windows_ops.to_terminal_save_ours = terminal_save_ours;
2560 windows_ops.to_terminal_info = child_terminal_info;
2561 windows_ops.to_kill = windows_kill_inferior;
2562 windows_ops.to_create_inferior = windows_create_inferior;
2563 windows_ops.to_mourn_inferior = windows_mourn_inferior;
2564 windows_ops.to_can_run = windows_can_run;
2565 windows_ops.to_thread_alive = windows_thread_alive;
2566 windows_ops.to_pid_to_str = windows_pid_to_str;
2567 windows_ops.to_stop = windows_stop;
2568 windows_ops.to_stratum = process_stratum;
2569 windows_ops.to_has_all_memory = default_child_has_all_memory;
2570 windows_ops.to_has_memory = default_child_has_memory;
2571 windows_ops.to_has_stack = default_child_has_stack;
2572 windows_ops.to_has_registers = default_child_has_registers;
2573 windows_ops.to_has_execution = default_child_has_execution;
2574 windows_ops.to_pid_to_exec_file = windows_pid_to_exec_file;
2575 windows_ops.to_get_ada_task_ptid = windows_get_ada_task_ptid;
2576 windows_ops.to_get_tib_address = windows_get_tib_address;
2578 i386_use_watchpoints (&windows_ops);
2580 i386_dr_low.set_control = cygwin_set_dr7;
2581 i386_dr_low.set_addr = cygwin_set_dr;
2582 i386_dr_low.get_addr = cygwin_get_dr;
2583 i386_dr_low.get_status = cygwin_get_dr6;
2584 i386_dr_low.get_control = cygwin_get_dr7;
2586 /* i386_dr_low.debug_register_length field is set by
2587 calling i386_set_debug_register_length function
2588 in processor windows specific native file. */
2590 windows_ops.to_magic = OPS_MAGIC;
2594 set_windows_aliases (char *argv0)
2596 add_info_alias ("dll", "sharedlibrary", 1);
2599 /* -Wmissing-prototypes */
2600 extern initialize_file_ftype _initialize_windows_nat;
2603 _initialize_windows_nat (void)
2605 struct cmd_list_element *c;
2607 init_windows_ops ();
2610 cygwin_internal (CW_SET_DOS_FILE_WARNING, 0);
2613 c = add_com ("dll-symbols", class_files, dll_symbol_command,
2614 _("Load dll library symbols from FILE."));
2615 set_cmd_completer (c, filename_completer);
2616 deprecate_cmd (c, "sharedlibrary");
2618 c = add_com ("add-shared-symbol-files", class_files, dll_symbol_command,
2619 _("Load dll library symbols from FILE."));
2620 set_cmd_completer (c, filename_completer);
2621 deprecate_cmd (c, "sharedlibrary");
2623 c = add_com ("assf", class_files, dll_symbol_command,
2624 _("Load dll library symbols from FILE."));
2625 set_cmd_completer (c, filename_completer);
2626 deprecate_cmd (c, "sharedlibrary");
2629 add_setshow_boolean_cmd ("shell", class_support, &useshell, _("\
2630 Set use of shell to start subprocess."), _("\
2631 Show use of shell to start subprocess."), NULL,
2633 NULL, /* FIXME: i18n: */
2634 &setlist, &showlist);
2636 add_setshow_boolean_cmd ("cygwin-exceptions", class_support,
2637 &cygwin_exceptions, _("\
2638 Break when an exception is detected in the Cygwin DLL itself."), _("\
2639 Show whether gdb breaks on exceptions in the Cygwin DLL itself."), NULL,
2641 NULL, /* FIXME: i18n: */
2642 &setlist, &showlist);
2645 add_setshow_boolean_cmd ("new-console", class_support, &new_console, _("\
2646 Set creation of new console when creating child process."), _("\
2647 Show creation of new console when creating child process."), NULL,
2649 NULL, /* FIXME: i18n: */
2650 &setlist, &showlist);
2652 add_setshow_boolean_cmd ("new-group", class_support, &new_group, _("\
2653 Set creation of new group when creating child process."), _("\
2654 Show creation of new group when creating child process."), NULL,
2656 NULL, /* FIXME: i18n: */
2657 &setlist, &showlist);
2659 add_setshow_boolean_cmd ("debugexec", class_support, &debug_exec, _("\
2660 Set whether to display execution in child process."), _("\
2661 Show whether to display execution in child process."), NULL,
2663 NULL, /* FIXME: i18n: */
2664 &setlist, &showlist);
2666 add_setshow_boolean_cmd ("debugevents", class_support, &debug_events, _("\
2667 Set whether to display kernel events in child process."), _("\
2668 Show whether to display kernel events in child process."), NULL,
2670 NULL, /* FIXME: i18n: */
2671 &setlist, &showlist);
2673 add_setshow_boolean_cmd ("debugmemory", class_support, &debug_memory, _("\
2674 Set whether to display memory accesses in child process."), _("\
2675 Show whether to display memory accesses in child process."), NULL,
2677 NULL, /* FIXME: i18n: */
2678 &setlist, &showlist);
2680 add_setshow_boolean_cmd ("debugexceptions", class_support,
2681 &debug_exceptions, _("\
2682 Set whether to display kernel exceptions in child process."), _("\
2683 Show whether to display kernel exceptions in child process."), NULL,
2685 NULL, /* FIXME: i18n: */
2686 &setlist, &showlist);
2688 init_w32_command_list ();
2690 add_cmd ("selector", class_info, display_selectors,
2691 _("Display selectors infos."),
2693 add_target (&windows_ops);
2694 deprecated_init_ui_hook = set_windows_aliases;
2697 /* Hardware watchpoint support, adapted from go32-nat.c code. */
2699 /* Pass the address ADDR to the inferior in the I'th debug register.
2700 Here we just store the address in dr array, the registers will be
2701 actually set up when windows_continue is called. */
2703 cygwin_set_dr (int i, CORE_ADDR addr)
2706 internal_error (__FILE__, __LINE__,
2707 _("Invalid register %d in cygwin_set_dr.\n"), i);
2709 debug_registers_changed = 1;
2710 debug_registers_used = 1;
2713 /* Pass the value VAL to the inferior in the DR7 debug control
2714 register. Here we just store the address in D_REGS, the watchpoint
2715 will be actually set up in windows_wait. */
2717 cygwin_set_dr7 (unsigned long val)
2719 dr[7] = (CORE_ADDR) val;
2720 debug_registers_changed = 1;
2721 debug_registers_used = 1;
2724 /* Get the value of debug register I from the inferior. */
2727 cygwin_get_dr (int i)
2732 /* Get the value of the DR6 debug status register from the inferior.
2733 Here we just return the value stored in dr[6]
2734 by the last call to thread_rec for current_event.dwThreadId id. */
2735 static unsigned long
2736 cygwin_get_dr6 (void)
2738 return (unsigned long) dr[6];
2741 /* Get the value of the DR7 debug status register from the inferior.
2742 Here we just return the value stored in dr[7] by the last call to
2743 thread_rec for current_event.dwThreadId id. */
2745 static unsigned long
2746 cygwin_get_dr7 (void)
2748 return (unsigned long) dr[7];
2751 /* Determine if the thread referenced by "ptid" is alive
2752 by "polling" it. If WaitForSingleObject returns WAIT_OBJECT_0
2753 it means that the thread has died. Otherwise it is assumed to be alive. */
2755 windows_thread_alive (struct target_ops *ops, ptid_t ptid)
2759 gdb_assert (ptid_get_tid (ptid) != 0);
2760 tid = ptid_get_tid (ptid);
2762 return WaitForSingleObject (thread_rec (tid, FALSE)->h, 0) == WAIT_OBJECT_0
2766 /* -Wmissing-prototypes */
2767 extern initialize_file_ftype _initialize_check_for_gdb_ini;
2770 _initialize_check_for_gdb_ini (void)
2773 if (inhibit_gdbinit)
2776 homedir = getenv ("HOME");
2780 char *oldini = (char *) alloca (strlen (homedir) +
2781 sizeof ("/gdb.ini"));
2782 strcpy (oldini, homedir);
2783 p = strchr (oldini, '\0');
2784 if (p > oldini && !IS_DIR_SEPARATOR (p[-1]))
2786 strcpy (p, "gdb.ini");
2787 if (access (oldini, 0) == 0)
2789 int len = strlen (oldini);
2790 char *newini = alloca (len + 1);
2792 xsnprintf (newini, len + 1, "%.*s.gdbinit",
2793 (int) (len - (sizeof ("gdb.ini") - 1)), oldini);
2794 warning (_("obsolete '%s' found. Rename to '%s'."), oldini, newini);
2799 /* Define dummy functions which always return error for the rare cases where
2800 these functions could not be found. */
2802 bad_DebugActiveProcessStop (DWORD w)
2807 bad_DebugBreakProcess (HANDLE w)
2812 bad_DebugSetProcessKillOnExit (BOOL w)
2817 bad_EnumProcessModules (HANDLE w, HMODULE *x, DWORD y, LPDWORD z)
2824 bad_GetModuleFileNameExW (HANDLE w, HMODULE x, LPWSTR y, DWORD z)
2830 bad_GetModuleFileNameExA (HANDLE w, HMODULE x, LPSTR y, DWORD z)
2837 bad_GetModuleInformation (HANDLE w, HMODULE x, LPMODULEINFO y, DWORD z)
2843 bad_OpenProcessToken (HANDLE w, DWORD x, PHANDLE y)
2849 bad_GetCurrentConsoleFont (HANDLE w, BOOL bMaxWindow, CONSOLE_FONT_INFO *f)
2855 bad_GetConsoleFontSize (HANDLE w, DWORD nFont)
2863 /* -Wmissing-prototypes */
2864 extern initialize_file_ftype _initialize_loadable;
2866 /* Load any functions which may not be available in ancient versions
2870 _initialize_loadable (void)
2874 hm = LoadLibrary ("kernel32.dll");
2877 DebugActiveProcessStop = (void *)
2878 GetProcAddress (hm, "DebugActiveProcessStop");
2879 DebugBreakProcess = (void *)
2880 GetProcAddress (hm, "DebugBreakProcess");
2881 DebugSetProcessKillOnExit = (void *)
2882 GetProcAddress (hm, "DebugSetProcessKillOnExit");
2883 GetConsoleFontSize = (void *)
2884 GetProcAddress (hm, "GetConsoleFontSize");
2885 GetCurrentConsoleFont = (void *)
2886 GetProcAddress (hm, "GetCurrentConsoleFont");
2889 /* Set variables to dummy versions of these processes if the function
2890 wasn't found in kernel32.dll. */
2891 if (!DebugBreakProcess)
2892 DebugBreakProcess = bad_DebugBreakProcess;
2893 if (!DebugActiveProcessStop || !DebugSetProcessKillOnExit)
2895 DebugActiveProcessStop = bad_DebugActiveProcessStop;
2896 DebugSetProcessKillOnExit = bad_DebugSetProcessKillOnExit;
2898 if (!GetConsoleFontSize)
2899 GetConsoleFontSize = bad_GetConsoleFontSize;
2900 if (!GetCurrentConsoleFont)
2901 GetCurrentConsoleFont = bad_GetCurrentConsoleFont;
2903 /* Load optional functions used for retrieving filename information
2904 associated with the currently debugged process or its dlls. */
2905 hm = LoadLibrary ("psapi.dll");
2908 EnumProcessModules = (void *)
2909 GetProcAddress (hm, "EnumProcessModules");
2910 GetModuleInformation = (void *)
2911 GetProcAddress (hm, "GetModuleInformation");
2912 GetModuleFileNameEx = (void *)
2913 GetProcAddress (hm, GetModuleFileNameEx_name);
2916 if (!EnumProcessModules || !GetModuleInformation || !GetModuleFileNameEx)
2918 /* Set variables to dummy versions of these processes if the function
2919 wasn't found in psapi.dll. */
2920 EnumProcessModules = bad_EnumProcessModules;
2921 GetModuleInformation = bad_GetModuleInformation;
2922 GetModuleFileNameEx = bad_GetModuleFileNameEx;
2923 /* This will probably fail on Windows 9x/Me. Let the user know
2924 that we're missing some functionality. */
2926 cannot automatically find executable file or library to read symbols.\n\
2927 Use \"file\" or \"dll\" command to load executable/libraries directly."));
2930 hm = LoadLibrary ("advapi32.dll");
2933 OpenProcessToken = (void *) GetProcAddress (hm, "OpenProcessToken");
2934 LookupPrivilegeValueA = (void *)
2935 GetProcAddress (hm, "LookupPrivilegeValueA");
2936 AdjustTokenPrivileges = (void *)
2937 GetProcAddress (hm, "AdjustTokenPrivileges");
2938 /* Only need to set one of these since if OpenProcessToken fails nothing
2940 if (!OpenProcessToken || !LookupPrivilegeValueA
2941 || !AdjustTokenPrivileges)
2942 OpenProcessToken = bad_OpenProcessToken;