1 /* Target-vector operations for controlling windows child processes, for GDB.
3 Copyright (C) 1995-2015 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 */
31 #include "completer.h"
35 #include <sys/types.h>
42 #include <sys/cygwin.h>
43 #include <cygwin/version.h>
47 #include "filenames.h"
51 #include "gdb_obstack.h"
52 #include "gdbthread.h"
58 #include "xml-support.h"
60 #include "i386-tdep.h"
61 #include "i387-tdep.h"
63 #include "windows-tdep.h"
64 #include "windows-nat.h"
66 #include "complaints.h"
67 #include "inf-child.h"
69 #define AdjustTokenPrivileges dyn_AdjustTokenPrivileges
70 #define DebugActiveProcessStop dyn_DebugActiveProcessStop
71 #define DebugBreakProcess dyn_DebugBreakProcess
72 #define DebugSetProcessKillOnExit dyn_DebugSetProcessKillOnExit
73 #define EnumProcessModules dyn_EnumProcessModules
74 #define GetModuleInformation dyn_GetModuleInformation
75 #define LookupPrivilegeValueA dyn_LookupPrivilegeValueA
76 #define OpenProcessToken dyn_OpenProcessToken
77 #define GetConsoleFontSize dyn_GetConsoleFontSize
78 #define GetCurrentConsoleFont dyn_GetCurrentConsoleFont
80 static BOOL WINAPI (*AdjustTokenPrivileges)(HANDLE, BOOL, PTOKEN_PRIVILEGES,
81 DWORD, PTOKEN_PRIVILEGES, PDWORD);
82 static BOOL WINAPI (*DebugActiveProcessStop) (DWORD);
83 static BOOL WINAPI (*DebugBreakProcess) (HANDLE);
84 static BOOL WINAPI (*DebugSetProcessKillOnExit) (BOOL);
85 static BOOL WINAPI (*EnumProcessModules) (HANDLE, HMODULE *, DWORD,
87 static BOOL WINAPI (*GetModuleInformation) (HANDLE, HMODULE, LPMODULEINFO,
89 static BOOL WINAPI (*LookupPrivilegeValueA)(LPCSTR, LPCSTR, PLUID);
90 static BOOL WINAPI (*OpenProcessToken)(HANDLE, DWORD, PHANDLE);
91 static BOOL WINAPI (*GetCurrentConsoleFont) (HANDLE, BOOL,
93 static COORD WINAPI (*GetConsoleFontSize) (HANDLE, DWORD);
97 #undef GetModuleFileNameEx
100 # define __PMAX (MAX_PATH + 1)
101 static DWORD WINAPI (*GetModuleFileNameEx) (HANDLE, HMODULE, LPSTR, DWORD);
102 # define STARTUPINFO STARTUPINFOA
103 # define CreateProcess CreateProcessA
104 # define GetModuleFileNameEx_name "GetModuleFileNameExA"
105 # define bad_GetModuleFileNameEx bad_GetModuleFileNameExA
107 # define __PMAX PATH_MAX
108 /* The starting and ending address of the cygwin1.dll text segment. */
109 static CORE_ADDR cygwin_load_start;
110 static CORE_ADDR cygwin_load_end;
112 typedef wchar_t cygwin_buf_t;
113 static DWORD WINAPI (*GetModuleFileNameEx) (HANDLE, HMODULE,
115 # define STARTUPINFO STARTUPINFOW
116 # define CreateProcess CreateProcessW
117 # define GetModuleFileNameEx_name "GetModuleFileNameExW"
118 # define bad_GetModuleFileNameEx bad_GetModuleFileNameExW
121 static int have_saved_context; /* True if we've saved context from a
123 static CONTEXT saved_context; /* Containes the saved context from a
126 /* If we're not using the old Cygwin header file set, define the
127 following which never should have been in the generic Win32 API
128 headers in the first place since they were our own invention... */
129 #ifndef _GNU_H_WINDOWS_H
132 FLAG_TRACE_BIT = 0x100,
136 #ifndef CONTEXT_EXTENDED_REGISTERS
137 /* This macro is only defined on ia32. It only makes sense on this target,
138 so define it as zero if not already defined. */
139 #define CONTEXT_EXTENDED_REGISTERS 0
142 #define CONTEXT_DEBUGGER_DR CONTEXT_FULL | CONTEXT_FLOATING_POINT \
143 | CONTEXT_SEGMENTS | CONTEXT_DEBUG_REGISTERS \
144 | CONTEXT_EXTENDED_REGISTERS
146 static uintptr_t dr[8];
147 static int debug_registers_changed;
148 static int debug_registers_used;
150 static int windows_initialization_done;
151 #define DR6_CLEAR_VALUE 0xffff0ff0
153 /* The string sent by cygwin when it processes a signal.
154 FIXME: This should be in a cygwin include file. */
155 #ifndef _CYGWIN_SIGNAL_STRING
156 #define _CYGWIN_SIGNAL_STRING "cYgSiGw00f"
159 #define CHECK(x) check (x, __FILE__,__LINE__)
160 #define DEBUG_EXEC(x) if (debug_exec) printf_unfiltered x
161 #define DEBUG_EVENTS(x) if (debug_events) printf_unfiltered x
162 #define DEBUG_MEM(x) if (debug_memory) printf_unfiltered x
163 #define DEBUG_EXCEPT(x) if (debug_exceptions) printf_unfiltered x
165 static void windows_interrupt (struct target_ops *self, ptid_t);
166 static int windows_thread_alive (struct target_ops *, ptid_t);
167 static void windows_kill_inferior (struct target_ops *);
169 static void cygwin_set_dr (int i, CORE_ADDR addr);
170 static void cygwin_set_dr7 (unsigned long val);
171 static CORE_ADDR cygwin_get_dr (int i);
172 static unsigned long cygwin_get_dr6 (void);
173 static unsigned long cygwin_get_dr7 (void);
175 static enum gdb_signal last_sig = GDB_SIGNAL_0;
176 /* Set if a signal was received from the debugged process. */
178 /* Thread information structure used to track information that is
179 not available in gdb's thread structure. */
180 typedef struct windows_thread_info_struct
182 struct windows_thread_info_struct *next;
185 CORE_ADDR thread_local_base;
194 static windows_thread_info thread_head;
196 /* The process and thread handles for the above context. */
198 static DEBUG_EVENT current_event; /* The current debug event from
200 static HANDLE current_process_handle; /* Currently executing process */
201 static windows_thread_info *current_thread; /* Info on currently selected thread */
202 static DWORD main_thread_id; /* Thread ID of the main thread */
204 /* Counts of things. */
205 static int exception_count = 0;
206 static int event_count = 0;
207 static int saw_create;
208 static int open_process_used = 0;
211 static int new_console = 0;
213 static int cygwin_exceptions = 0;
215 static int new_group = 1;
216 static int debug_exec = 0; /* show execution */
217 static int debug_events = 0; /* show events from kernel */
218 static int debug_memory = 0; /* show target memory accesses */
219 static int debug_exceptions = 0; /* show target exceptions */
220 static int useshell = 0; /* use shell for subprocesses */
222 /* This vector maps GDB's idea of a register's number into an offset
223 in the windows exception context vector.
225 It also contains the bit mask needed to load the register in question.
227 The contents of this table can only be computed by the units
228 that provide CPU-specific support for Windows native debugging.
229 These units should set the table by calling
230 windows_set_context_register_offsets.
232 One day we could read a reg, we could inspect the context we
233 already have loaded, if it doesn't have the bit set that we need,
234 we read that set of registers in using GetThreadContext. If the
235 context already contains what we need, we just unpack it. Then to
236 write a register, first we have to ensure that the context contains
237 the other regs of the group, and then we copy the info in and set
240 static const int *mappings;
242 /* The function to use in order to determine whether a register is
243 a segment register or not. */
244 static segment_register_p_ftype *segment_register_p;
246 /* This vector maps the target's idea of an exception (extracted
247 from the DEBUG_EVENT structure) to GDB's idea. */
249 struct xlate_exception
255 static const struct xlate_exception
258 {EXCEPTION_ACCESS_VIOLATION, GDB_SIGNAL_SEGV},
259 {STATUS_STACK_OVERFLOW, GDB_SIGNAL_SEGV},
260 {EXCEPTION_BREAKPOINT, GDB_SIGNAL_TRAP},
261 {DBG_CONTROL_C, GDB_SIGNAL_INT},
262 {EXCEPTION_SINGLE_STEP, GDB_SIGNAL_TRAP},
263 {STATUS_FLOAT_DIVIDE_BY_ZERO, GDB_SIGNAL_FPE},
266 /* Set the MAPPINGS static global to OFFSETS.
267 See the description of MAPPINGS for more details. */
270 windows_set_context_register_offsets (const int *offsets)
275 /* See windows-nat.h. */
278 windows_set_segment_register_p (segment_register_p_ftype *fun)
280 segment_register_p = fun;
284 check (BOOL ok, const char *file, int line)
287 printf_filtered ("error return %s:%d was %u\n", file, line,
288 (unsigned) GetLastError ());
291 /* Find a thread record given a thread id. If GET_CONTEXT is not 0,
292 then also retrieve the context for this thread. If GET_CONTEXT is
293 negative, then don't suspend the thread. */
294 static windows_thread_info *
295 thread_rec (DWORD id, int get_context)
297 windows_thread_info *th;
299 for (th = &thread_head; (th = th->next) != NULL;)
302 if (!th->suspended && get_context)
304 if (get_context > 0 && id != current_event.dwThreadId)
306 if (SuspendThread (th->h) == (DWORD) -1)
308 DWORD err = GetLastError ();
310 /* We get Access Denied (5) when trying to suspend
311 threads that Windows started on behalf of the
312 debuggee, usually when those threads are just
314 We can get Invalid Handle (6) if the main thread
316 if (err != ERROR_INVALID_HANDLE
317 && err != ERROR_ACCESS_DENIED)
318 warning (_("SuspendThread (tid=0x%x) failed."
320 (unsigned) id, (unsigned) err);
326 else if (get_context < 0)
328 th->reload_context = 1;
336 /* Add a thread to the thread list. */
337 static windows_thread_info *
338 windows_add_thread (ptid_t ptid, HANDLE h, void *tlb)
340 windows_thread_info *th;
343 gdb_assert (ptid_get_tid (ptid) != 0);
345 id = ptid_get_tid (ptid);
347 if ((th = thread_rec (id, FALSE)))
350 th = XCNEW (windows_thread_info);
353 th->thread_local_base = (CORE_ADDR) (uintptr_t) tlb;
354 th->next = thread_head.next;
355 thread_head.next = th;
357 /* Set the debug registers for the new thread if they are used. */
358 if (debug_registers_used)
360 /* Only change the value of the debug registers. */
361 th->context.ContextFlags = CONTEXT_DEBUG_REGISTERS;
362 CHECK (GetThreadContext (th->h, &th->context));
363 th->context.Dr0 = dr[0];
364 th->context.Dr1 = dr[1];
365 th->context.Dr2 = dr[2];
366 th->context.Dr3 = dr[3];
367 th->context.Dr6 = DR6_CLEAR_VALUE;
368 th->context.Dr7 = dr[7];
369 CHECK (SetThreadContext (th->h, &th->context));
370 th->context.ContextFlags = 0;
375 /* Clear out any old thread list and reintialize it to a
378 windows_init_thread_list (void)
380 windows_thread_info *th = &thread_head;
382 DEBUG_EVENTS (("gdb: windows_init_thread_list\n"));
384 while (th->next != NULL)
386 windows_thread_info *here = th->next;
387 th->next = here->next;
390 thread_head.next = NULL;
393 /* Delete a thread from the list of threads. */
395 windows_delete_thread (ptid_t ptid, DWORD exit_code)
397 windows_thread_info *th;
400 gdb_assert (ptid_get_tid (ptid) != 0);
402 id = ptid_get_tid (ptid);
405 printf_unfiltered ("[Deleting %s]\n", target_pid_to_str (ptid));
406 else if (print_thread_events && id != main_thread_id)
407 printf_unfiltered (_("[%s exited with code %u]\n"),
408 target_pid_to_str (ptid), (unsigned) exit_code);
409 delete_thread (ptid);
411 for (th = &thread_head;
412 th->next != NULL && th->next->id != id;
416 if (th->next != NULL)
418 windows_thread_info *here = th->next;
419 th->next = here->next;
425 do_windows_fetch_inferior_registers (struct regcache *regcache, int r)
427 char *context_offset = ((char *) ¤t_thread->context) + mappings[r];
428 struct gdbarch *gdbarch = get_regcache_arch (regcache);
429 struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
433 return; /* Windows sometimes uses a non-existent thread id in its
436 if (current_thread->reload_context)
439 if (have_saved_context)
441 /* Lie about where the program actually is stopped since
442 cygwin has informed us that we should consider the signal
443 to have occurred at another location which is stored in
445 memcpy (¤t_thread->context, &saved_context,
446 __COPY_CONTEXT_SIZE);
447 have_saved_context = 0;
452 windows_thread_info *th = current_thread;
453 th->context.ContextFlags = CONTEXT_DEBUGGER_DR;
454 CHECK (GetThreadContext (th->h, &th->context));
455 /* Copy dr values from that thread.
456 But only if there were not modified since last stop.
458 if (!debug_registers_changed)
460 dr[0] = th->context.Dr0;
461 dr[1] = th->context.Dr1;
462 dr[2] = th->context.Dr2;
463 dr[3] = th->context.Dr3;
464 dr[6] = th->context.Dr6;
465 dr[7] = th->context.Dr7;
468 current_thread->reload_context = 0;
471 if (r == I387_FISEG_REGNUM (tdep))
473 l = *((long *) context_offset) & 0xffff;
474 regcache_raw_supply (regcache, r, (char *) &l);
476 else if (r == I387_FOP_REGNUM (tdep))
478 l = (*((long *) context_offset) >> 16) & ((1 << 11) - 1);
479 regcache_raw_supply (regcache, r, (char *) &l);
481 else if (segment_register_p (r))
483 /* GDB treats segment registers as 32bit registers, but they are
484 in fact only 16 bits long. Make sure we do not read extra
485 bits from our source buffer. */
486 l = *((long *) context_offset) & 0xffff;
487 regcache_raw_supply (regcache, r, (char *) &l);
490 regcache_raw_supply (regcache, r, context_offset);
493 for (r = 0; r < gdbarch_num_regs (gdbarch); r++)
494 do_windows_fetch_inferior_registers (regcache, r);
499 windows_fetch_inferior_registers (struct target_ops *ops,
500 struct regcache *regcache, int r)
502 current_thread = thread_rec (ptid_get_tid (inferior_ptid), TRUE);
503 /* Check if current_thread exists. Windows sometimes uses a non-existent
504 thread id in its events. */
506 do_windows_fetch_inferior_registers (regcache, r);
510 do_windows_store_inferior_registers (const struct regcache *regcache, int r)
513 /* Windows sometimes uses a non-existent thread id in its events. */;
515 regcache_raw_collect (regcache, r,
516 ((char *) ¤t_thread->context) + mappings[r]);
519 for (r = 0; r < gdbarch_num_regs (get_regcache_arch (regcache)); r++)
520 do_windows_store_inferior_registers (regcache, r);
524 /* Store a new register value into the current thread context. */
526 windows_store_inferior_registers (struct target_ops *ops,
527 struct regcache *regcache, int r)
529 current_thread = thread_rec (ptid_get_tid (inferior_ptid), TRUE);
530 /* Check if current_thread exists. Windows sometimes uses a non-existent
531 thread id in its events. */
533 do_windows_store_inferior_registers (regcache, r);
536 /* Encapsulate the information required in a call to
537 symbol_file_add_args. */
538 struct safe_symbol_file_add_args
542 struct section_addr_info *addrs;
545 struct ui_file *err, *out;
549 /* Maintain a linked list of "so" information. */
555 static struct so_list solib_start, *solib_end;
557 static struct so_list *
558 windows_make_so (const char *name, LPVOID load_addr)
565 WIN32_FIND_DATA w32_fd;
566 HANDLE h = FindFirstFile(name, &w32_fd);
568 if (h == INVALID_HANDLE_VALUE)
574 if (GetCurrentDirectory (MAX_PATH + 1, cwd))
576 p = strrchr (buf, '\\');
579 SetCurrentDirectory (buf);
580 GetFullPathName (w32_fd.cFileName, MAX_PATH, buf, &p);
581 SetCurrentDirectory (cwd);
584 if (strcasecmp (buf, "ntdll.dll") == 0)
586 GetSystemDirectory (buf, sizeof (buf));
587 strcat (buf, "\\ntdll.dll");
590 cygwin_buf_t buf[__PMAX];
593 if (access (name, F_OK) != 0)
595 if (strcasecmp (name, "ntdll.dll") == 0)
598 GetSystemDirectoryW (buf, sizeof (buf) / sizeof (wchar_t));
599 wcscat (buf, L"\\ntdll.dll");
603 GetSystemDirectoryA (buf, sizeof (buf) / sizeof (wchar_t));
604 strcat (buf, "\\ntdll.dll");
609 so = XCNEW (struct so_list);
610 so->lm_info = XNEW (struct lm_info);
611 so->lm_info->load_addr = load_addr;
612 strcpy (so->so_original_name, name);
614 strcpy (so->so_name, buf);
617 cygwin_conv_path (CCP_WIN_W_TO_POSIX, buf, so->so_name,
618 SO_NAME_MAX_PATH_SIZE);
621 char *rname = realpath (name, NULL);
622 if (rname && strlen (rname) < SO_NAME_MAX_PATH_SIZE)
624 strcpy (so->so_name, rname);
628 error (_("dll path too long"));
630 /* Record cygwin1.dll .text start/end. */
631 p = strchr (so->so_name, '\0') - (sizeof ("/cygwin1.dll") - 1);
632 if (p >= so->so_name && strcasecmp (p, "/cygwin1.dll") == 0)
635 asection *text = NULL;
638 abfd = gdb_bfd_open (so->so_name, "pei-i386", -1);
643 if (bfd_check_format (abfd, bfd_object))
644 text = bfd_get_section_by_name (abfd, ".text");
648 gdb_bfd_unref (abfd);
652 /* The symbols in a dll are offset by 0x1000, which is the
653 offset from 0 of the first byte in an image - because of the
654 file header and the section alignment. */
655 cygwin_load_start = (CORE_ADDR) (uintptr_t) ((char *)
657 cygwin_load_end = cygwin_load_start + bfd_section_size (abfd, text);
659 gdb_bfd_unref (abfd);
667 get_image_name (HANDLE h, void *address, int unicode)
670 static char buf[__PMAX];
672 static char buf[(2 * __PMAX) + 1];
674 DWORD size = unicode ? sizeof (WCHAR) : sizeof (char);
680 /* Attempt to read the name of the dll that was detected.
681 This is documented to work only when actively debugging
682 a program. It will not work for attached processes. */
686 /* See if we could read the address of a string, and that the
687 address isn't null. */
688 if (!ReadProcessMemory (h, address, &address_ptr,
689 sizeof (address_ptr), &done)
690 || done != sizeof (address_ptr) || !address_ptr)
693 /* Find the length of the string. */
694 while (ReadProcessMemory (h, address_ptr + len++ * size, &b, size, &done)
695 && (b[0] != 0 || b[size - 1] != 0) && done == size)
699 ReadProcessMemory (h, address_ptr, buf, len, &done);
702 WCHAR *unicode_address = (WCHAR *) alloca (len * sizeof (WCHAR));
703 ReadProcessMemory (h, address_ptr, unicode_address, len * sizeof (WCHAR),
706 wcstombs (buf, unicode_address, __PMAX);
708 WideCharToMultiByte (CP_ACP, 0, unicode_address, len, buf, sizeof buf,
716 /* Handle a DLL load event, and return 1.
718 This function assumes that this event did not occur during inferior
719 initialization, where their event info may be incomplete (see
720 do_initial_windows_stuff and windows_add_all_dlls for more info
721 on how we handle DLL loading during that phase). */
724 handle_load_dll (void *dummy)
726 LOAD_DLL_DEBUG_INFO *event = ¤t_event.u.LoadDll;
729 /* Try getting the DLL name via the lpImageName field of the event.
730 Note that Microsoft documents this fields as strictly optional,
731 in the sense that it might be NULL. And the first DLL event in
732 particular is explicitly documented as "likely not pass[ed]"
733 (source: MSDN LOAD_DLL_DEBUG_INFO structure). */
734 dll_name = get_image_name (current_process_handle,
735 event->lpImageName, event->fUnicode);
739 solib_end->next = windows_make_so (dll_name, event->lpBaseOfDll);
740 solib_end = solib_end->next;
742 DEBUG_EVENTS (("gdb: Loading dll \"%s\" at %s.\n", solib_end->so_name,
743 host_address_to_string (solib_end->lm_info->load_addr)));
749 windows_free_so (struct so_list *so)
756 /* Handle a DLL unload event.
757 Return 1 if successful, or zero otherwise.
759 This function assumes that this event did not occur during inferior
760 initialization, where their event info may be incomplete (see
761 do_initial_windows_stuff and windows_add_all_dlls for more info
762 on how we handle DLL loading during that phase). */
765 handle_unload_dll (void *dummy)
767 LPVOID lpBaseOfDll = current_event.u.UnloadDll.lpBaseOfDll;
770 for (so = &solib_start; so->next != NULL; so = so->next)
771 if (so->next->lm_info->load_addr == lpBaseOfDll)
773 struct so_list *sodel = so->next;
775 so->next = sodel->next;
778 DEBUG_EVENTS (("gdb: Unloading dll \"%s\".\n", sodel->so_name));
780 windows_free_so (sodel);
784 /* We did not find any DLL that was previously loaded at this address,
785 so register a complaint. We do not report an error, because we have
786 observed that this may be happening under some circumstances. For
787 instance, running 32bit applications on x64 Windows causes us to receive
788 4 mysterious UNLOAD_DLL_DEBUG_EVENTs during the startup phase (these
789 events are apparently caused by the WOW layer, the interface between
790 32bit and 64bit worlds). */
791 complaint (&symfile_complaints, _("dll starting at %s not found."),
792 host_address_to_string (lpBaseOfDll));
797 /* Clear list of loaded DLLs. */
799 windows_clear_solib (void)
801 solib_start.next = NULL;
802 solib_end = &solib_start;
805 /* Handle DEBUG_STRING output from child process.
806 Cygwin prepends its messages with a "cygwin:". Interpret this as
807 a Cygwin signal. Otherwise just print the string as a warning. */
809 handle_output_debug_string (struct target_waitstatus *ourstatus)
814 if (!target_read_string
815 ((CORE_ADDR) (uintptr_t) current_event.u.DebugString.lpDebugStringData,
819 else if (!startswith (s, _CYGWIN_SIGNAL_STRING))
822 if (!startswith (s, "cYg"))
825 char *p = strchr (s, '\0');
827 if (p > s && *--p == '\n')
835 /* Got a cygwin signal marker. A cygwin signal is followed by
836 the signal number itself and then optionally followed by the
837 thread id and address to saved context within the DLL. If
838 these are supplied, then the given thread is assumed to have
839 issued the signal and the context from the thread is assumed
840 to be stored at the given address in the inferior. Tell gdb
841 to treat this like a real signal. */
843 int sig = strtol (s + sizeof (_CYGWIN_SIGNAL_STRING) - 1, &p, 0);
844 int gotasig = gdb_signal_from_host (sig);
846 ourstatus->value.sig = gotasig;
852 ourstatus->kind = TARGET_WAITKIND_STOPPED;
853 retval = strtoul (p, &p, 0);
855 retval = main_thread_id;
856 else if ((x = (LPCVOID) (uintptr_t) strtoull (p, NULL, 0))
857 && ReadProcessMemory (current_process_handle, x,
859 __COPY_CONTEXT_SIZE, &n)
860 && n == __COPY_CONTEXT_SIZE)
861 have_saved_context = 1;
872 display_selector (HANDLE thread, DWORD sel)
875 if (GetThreadSelectorEntry (thread, sel, &info))
878 printf_filtered ("0x%03x: ", (unsigned) sel);
879 if (!info.HighWord.Bits.Pres)
881 puts_filtered ("Segment not present\n");
884 base = (info.HighWord.Bits.BaseHi << 24) +
885 (info.HighWord.Bits.BaseMid << 16)
887 limit = (info.HighWord.Bits.LimitHi << 16) + info.LimitLow;
888 if (info.HighWord.Bits.Granularity)
889 limit = (limit << 12) | 0xfff;
890 printf_filtered ("base=0x%08x limit=0x%08x", base, limit);
891 if (info.HighWord.Bits.Default_Big)
892 puts_filtered(" 32-bit ");
894 puts_filtered(" 16-bit ");
895 switch ((info.HighWord.Bits.Type & 0xf) >> 1)
898 puts_filtered ("Data (Read-Only, Exp-up");
901 puts_filtered ("Data (Read/Write, Exp-up");
904 puts_filtered ("Unused segment (");
907 puts_filtered ("Data (Read/Write, Exp-down");
910 puts_filtered ("Code (Exec-Only, N.Conf");
913 puts_filtered ("Code (Exec/Read, N.Conf");
916 puts_filtered ("Code (Exec-Only, Conf");
919 puts_filtered ("Code (Exec/Read, Conf");
922 printf_filtered ("Unknown type 0x%x",info.HighWord.Bits.Type);
924 if ((info.HighWord.Bits.Type & 0x1) == 0)
925 puts_filtered(", N.Acc");
926 puts_filtered (")\n");
927 if ((info.HighWord.Bits.Type & 0x10) == 0)
928 puts_filtered("System selector ");
929 printf_filtered ("Priviledge level = %d. ", info.HighWord.Bits.Dpl);
930 if (info.HighWord.Bits.Granularity)
931 puts_filtered ("Page granular.\n");
933 puts_filtered ("Byte granular.\n");
938 DWORD err = GetLastError ();
939 if (err == ERROR_NOT_SUPPORTED)
940 printf_filtered ("Function not supported\n");
942 printf_filtered ("Invalid selector 0x%x.\n", (unsigned) sel);
948 display_selectors (char * args, int from_tty)
952 puts_filtered ("Impossible to display selectors now.\n");
958 puts_filtered ("Selector $cs\n");
959 display_selector (current_thread->h,
960 current_thread->context.SegCs);
961 puts_filtered ("Selector $ds\n");
962 display_selector (current_thread->h,
963 current_thread->context.SegDs);
964 puts_filtered ("Selector $es\n");
965 display_selector (current_thread->h,
966 current_thread->context.SegEs);
967 puts_filtered ("Selector $ss\n");
968 display_selector (current_thread->h,
969 current_thread->context.SegSs);
970 puts_filtered ("Selector $fs\n");
971 display_selector (current_thread->h,
972 current_thread->context.SegFs);
973 puts_filtered ("Selector $gs\n");
974 display_selector (current_thread->h,
975 current_thread->context.SegGs);
980 sel = parse_and_eval_long (args);
981 printf_filtered ("Selector \"%s\"\n",args);
982 display_selector (current_thread->h, sel);
986 #define DEBUG_EXCEPTION_SIMPLE(x) if (debug_exceptions) \
987 printf_unfiltered ("gdb: Target exception %s at %s\n", x, \
988 host_address_to_string (\
989 current_event.u.Exception.ExceptionRecord.ExceptionAddress))
992 handle_exception (struct target_waitstatus *ourstatus)
994 windows_thread_info *th;
995 DWORD code = current_event.u.Exception.ExceptionRecord.ExceptionCode;
997 ourstatus->kind = TARGET_WAITKIND_STOPPED;
999 /* Record the context of the current thread. */
1000 th = thread_rec (current_event.dwThreadId, -1);
1004 case EXCEPTION_ACCESS_VIOLATION:
1005 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ACCESS_VIOLATION");
1006 ourstatus->value.sig = GDB_SIGNAL_SEGV;
1009 /* See if the access violation happened within the cygwin DLL
1010 itself. Cygwin uses a kind of exception handling to deal
1011 with passed-in invalid addresses. gdb should not treat
1012 these as real SEGVs since they will be silently handled by
1013 cygwin. A real SEGV will (theoretically) be caught by
1014 cygwin later in the process and will be sent as a
1015 cygwin-specific-signal. So, ignore SEGVs if they show up
1016 within the text segment of the DLL itself. */
1018 CORE_ADDR addr = (CORE_ADDR) (uintptr_t)
1019 current_event.u.Exception.ExceptionRecord.ExceptionAddress;
1021 if ((!cygwin_exceptions && (addr >= cygwin_load_start
1022 && addr < cygwin_load_end))
1023 || (find_pc_partial_function (addr, &fn, NULL, NULL)
1024 && startswith (fn, "KERNEL32!IsBad")))
1029 case STATUS_STACK_OVERFLOW:
1030 DEBUG_EXCEPTION_SIMPLE ("STATUS_STACK_OVERFLOW");
1031 ourstatus->value.sig = GDB_SIGNAL_SEGV;
1033 case STATUS_FLOAT_DENORMAL_OPERAND:
1034 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DENORMAL_OPERAND");
1035 ourstatus->value.sig = GDB_SIGNAL_FPE;
1037 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
1038 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ARRAY_BOUNDS_EXCEEDED");
1039 ourstatus->value.sig = GDB_SIGNAL_FPE;
1041 case STATUS_FLOAT_INEXACT_RESULT:
1042 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INEXACT_RESULT");
1043 ourstatus->value.sig = GDB_SIGNAL_FPE;
1045 case STATUS_FLOAT_INVALID_OPERATION:
1046 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INVALID_OPERATION");
1047 ourstatus->value.sig = GDB_SIGNAL_FPE;
1049 case STATUS_FLOAT_OVERFLOW:
1050 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_OVERFLOW");
1051 ourstatus->value.sig = GDB_SIGNAL_FPE;
1053 case STATUS_FLOAT_STACK_CHECK:
1054 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_STACK_CHECK");
1055 ourstatus->value.sig = GDB_SIGNAL_FPE;
1057 case STATUS_FLOAT_UNDERFLOW:
1058 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_UNDERFLOW");
1059 ourstatus->value.sig = GDB_SIGNAL_FPE;
1061 case STATUS_FLOAT_DIVIDE_BY_ZERO:
1062 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DIVIDE_BY_ZERO");
1063 ourstatus->value.sig = GDB_SIGNAL_FPE;
1065 case STATUS_INTEGER_DIVIDE_BY_ZERO:
1066 DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_DIVIDE_BY_ZERO");
1067 ourstatus->value.sig = GDB_SIGNAL_FPE;
1069 case STATUS_INTEGER_OVERFLOW:
1070 DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_OVERFLOW");
1071 ourstatus->value.sig = GDB_SIGNAL_FPE;
1073 case EXCEPTION_BREAKPOINT:
1074 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_BREAKPOINT");
1075 ourstatus->value.sig = GDB_SIGNAL_TRAP;
1078 DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_C");
1079 ourstatus->value.sig = GDB_SIGNAL_INT;
1081 case DBG_CONTROL_BREAK:
1082 DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_BREAK");
1083 ourstatus->value.sig = GDB_SIGNAL_INT;
1085 case EXCEPTION_SINGLE_STEP:
1086 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_SINGLE_STEP");
1087 ourstatus->value.sig = GDB_SIGNAL_TRAP;
1089 case EXCEPTION_ILLEGAL_INSTRUCTION:
1090 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ILLEGAL_INSTRUCTION");
1091 ourstatus->value.sig = GDB_SIGNAL_ILL;
1093 case EXCEPTION_PRIV_INSTRUCTION:
1094 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_PRIV_INSTRUCTION");
1095 ourstatus->value.sig = GDB_SIGNAL_ILL;
1097 case EXCEPTION_NONCONTINUABLE_EXCEPTION:
1098 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_NONCONTINUABLE_EXCEPTION");
1099 ourstatus->value.sig = GDB_SIGNAL_ILL;
1102 /* Treat unhandled first chance exceptions specially. */
1103 if (current_event.u.Exception.dwFirstChance)
1105 printf_unfiltered ("gdb: unknown target exception 0x%08x at %s\n",
1106 (unsigned) current_event.u.Exception.ExceptionRecord.ExceptionCode,
1107 host_address_to_string (
1108 current_event.u.Exception.ExceptionRecord.ExceptionAddress));
1109 ourstatus->value.sig = GDB_SIGNAL_UNKNOWN;
1113 last_sig = ourstatus->value.sig;
1117 /* Resume thread specified by ID, or all artificially suspended
1118 threads, if we are continuing execution. KILLED non-zero means we
1119 have killed the inferior, so we should ignore weird errors due to
1120 threads shutting down. */
1122 windows_continue (DWORD continue_status, int id, int killed)
1125 windows_thread_info *th;
1128 DEBUG_EVENTS (("ContinueDebugEvent (cpid=%d, ctid=0x%x, %s);\n",
1129 (unsigned) current_event.dwProcessId,
1130 (unsigned) current_event.dwThreadId,
1131 continue_status == DBG_CONTINUE ?
1132 "DBG_CONTINUE" : "DBG_EXCEPTION_NOT_HANDLED"));
1134 for (th = &thread_head; (th = th->next) != NULL;)
1135 if ((id == -1 || id == (int) th->id)
1138 if (debug_registers_changed)
1140 th->context.ContextFlags |= CONTEXT_DEBUG_REGISTERS;
1141 th->context.Dr0 = dr[0];
1142 th->context.Dr1 = dr[1];
1143 th->context.Dr2 = dr[2];
1144 th->context.Dr3 = dr[3];
1145 th->context.Dr6 = DR6_CLEAR_VALUE;
1146 th->context.Dr7 = dr[7];
1148 if (th->context.ContextFlags)
1152 if (GetExitCodeThread (th->h, &ec)
1153 && ec == STILL_ACTIVE)
1155 BOOL status = SetThreadContext (th->h, &th->context);
1160 th->context.ContextFlags = 0;
1162 if (th->suspended > 0)
1163 (void) ResumeThread (th->h);
1167 res = ContinueDebugEvent (current_event.dwProcessId,
1168 current_event.dwThreadId,
1172 error (_("Failed to resume program execution"
1173 " (ContinueDebugEvent failed, error %u)"),
1174 (unsigned int) GetLastError ());
1176 debug_registers_changed = 0;
1180 /* Called in pathological case where Windows fails to send a
1181 CREATE_PROCESS_DEBUG_EVENT after an attach. */
1183 fake_create_process (void)
1185 current_process_handle = OpenProcess (PROCESS_ALL_ACCESS, FALSE,
1186 current_event.dwProcessId);
1187 if (current_process_handle != NULL)
1188 open_process_used = 1;
1191 error (_("OpenProcess call failed, GetLastError = %u"),
1192 (unsigned) GetLastError ());
1193 /* We can not debug anything in that case. */
1195 main_thread_id = current_event.dwThreadId;
1196 current_thread = windows_add_thread (
1197 ptid_build (current_event.dwProcessId, 0,
1198 current_event.dwThreadId),
1199 current_event.u.CreateThread.hThread,
1200 current_event.u.CreateThread.lpThreadLocalBase);
1201 return main_thread_id;
1205 windows_resume (struct target_ops *ops,
1206 ptid_t ptid, int step, enum gdb_signal sig)
1208 windows_thread_info *th;
1209 DWORD continue_status = DBG_CONTINUE;
1211 /* A specific PTID means `step only this thread id'. */
1212 int resume_all = ptid_equal (ptid, minus_one_ptid);
1214 /* If we're continuing all threads, it's the current inferior that
1215 should be handled specially. */
1217 ptid = inferior_ptid;
1219 if (sig != GDB_SIGNAL_0)
1221 if (current_event.dwDebugEventCode != EXCEPTION_DEBUG_EVENT)
1223 DEBUG_EXCEPT(("Cannot continue with signal %d here.\n",sig));
1225 else if (sig == last_sig)
1226 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1229 /* This code does not seem to work, because
1230 the kernel does probably not consider changes in the ExceptionRecord
1231 structure when passing the exception to the inferior.
1232 Note that this seems possible in the exception handler itself. */
1235 for (i = 0; xlate[i].them != -1; i++)
1236 if (xlate[i].us == sig)
1238 current_event.u.Exception.ExceptionRecord.ExceptionCode
1240 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1243 if (continue_status == DBG_CONTINUE)
1245 DEBUG_EXCEPT(("Cannot continue with signal %d.\n",sig));
1249 DEBUG_EXCEPT(("Can only continue with received signal %d.\n",
1253 last_sig = GDB_SIGNAL_0;
1255 DEBUG_EXEC (("gdb: windows_resume (pid=%d, tid=%ld, step=%d, sig=%d);\n",
1256 ptid_get_pid (ptid), ptid_get_tid (ptid), step, sig));
1258 /* Get context for currently selected thread. */
1259 th = thread_rec (ptid_get_tid (inferior_ptid), FALSE);
1264 /* Single step by setting t bit. */
1265 struct regcache *regcache = get_current_regcache ();
1266 struct gdbarch *gdbarch = get_regcache_arch (regcache);
1267 windows_fetch_inferior_registers (ops, regcache,
1268 gdbarch_ps_regnum (gdbarch));
1269 th->context.EFlags |= FLAG_TRACE_BIT;
1272 if (th->context.ContextFlags)
1274 if (debug_registers_changed)
1276 th->context.Dr0 = dr[0];
1277 th->context.Dr1 = dr[1];
1278 th->context.Dr2 = dr[2];
1279 th->context.Dr3 = dr[3];
1280 th->context.Dr6 = DR6_CLEAR_VALUE;
1281 th->context.Dr7 = dr[7];
1283 CHECK (SetThreadContext (th->h, &th->context));
1284 th->context.ContextFlags = 0;
1288 /* Allow continuing with the same signal that interrupted us.
1289 Otherwise complain. */
1292 windows_continue (continue_status, -1, 0);
1294 windows_continue (continue_status, ptid_get_tid (ptid), 0);
1297 /* Ctrl-C handler used when the inferior is not run in the same console. The
1298 handler is in charge of interrupting the inferior using DebugBreakProcess.
1299 Note that this function is not available prior to Windows XP. In this case
1300 we emit a warning. */
1302 ctrl_c_handler (DWORD event_type)
1304 const int attach_flag = current_inferior ()->attach_flag;
1306 /* Only handle Ctrl-C and Ctrl-Break events. Ignore others. */
1307 if (event_type != CTRL_C_EVENT && event_type != CTRL_BREAK_EVENT)
1310 /* If the inferior and the debugger share the same console, do nothing as
1311 the inferior has also received the Ctrl-C event. */
1312 if (!new_console && !attach_flag)
1315 if (!DebugBreakProcess (current_process_handle))
1316 warning (_("Could not interrupt program. "
1317 "Press Ctrl-c in the program console."));
1319 /* Return true to tell that Ctrl-C has been handled. */
1323 /* Get the next event from the child. Returns a non-zero thread id if the event
1324 requires handling by WFI (or whatever). */
1326 get_windows_debug_event (struct target_ops *ops,
1327 int pid, struct target_waitstatus *ourstatus)
1330 DWORD continue_status, event_code;
1331 windows_thread_info *th;
1332 static windows_thread_info dummy_thread_info;
1333 DWORD thread_id = 0;
1335 last_sig = GDB_SIGNAL_0;
1337 if (!(debug_event = WaitForDebugEvent (¤t_event, 1000)))
1341 continue_status = DBG_CONTINUE;
1343 event_code = current_event.dwDebugEventCode;
1344 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
1346 have_saved_context = 0;
1350 case CREATE_THREAD_DEBUG_EVENT:
1351 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1352 (unsigned) current_event.dwProcessId,
1353 (unsigned) current_event.dwThreadId,
1354 "CREATE_THREAD_DEBUG_EVENT"));
1355 if (saw_create != 1)
1357 struct inferior *inf;
1358 inf = find_inferior_pid (current_event.dwProcessId);
1359 if (!saw_create && inf->attach_flag)
1361 /* Kludge around a Windows bug where first event is a create
1362 thread event. Caused when attached process does not have
1364 thread_id = fake_create_process ();
1370 /* Record the existence of this thread. */
1371 thread_id = current_event.dwThreadId;
1372 th = windows_add_thread (ptid_build (current_event.dwProcessId, 0,
1373 current_event.dwThreadId),
1374 current_event.u.CreateThread.hThread,
1375 current_event.u.CreateThread.lpThreadLocalBase);
1379 case EXIT_THREAD_DEBUG_EVENT:
1380 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1381 (unsigned) current_event.dwProcessId,
1382 (unsigned) current_event.dwThreadId,
1383 "EXIT_THREAD_DEBUG_EVENT"));
1385 if (current_event.dwThreadId != main_thread_id)
1387 windows_delete_thread (ptid_build (current_event.dwProcessId, 0,
1388 current_event.dwThreadId),
1389 current_event.u.ExitThread.dwExitCode);
1390 th = &dummy_thread_info;
1394 case CREATE_PROCESS_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_PROCESS_DEBUG_EVENT"));
1399 CloseHandle (current_event.u.CreateProcessInfo.hFile);
1400 if (++saw_create != 1)
1403 current_process_handle = current_event.u.CreateProcessInfo.hProcess;
1405 windows_delete_thread (ptid_build (current_event.dwProcessId, 0,
1408 main_thread_id = current_event.dwThreadId;
1409 /* Add the main thread. */
1410 th = windows_add_thread (ptid_build (current_event.dwProcessId, 0,
1411 current_event.dwThreadId),
1412 current_event.u.CreateProcessInfo.hThread,
1413 current_event.u.CreateProcessInfo.lpThreadLocalBase);
1414 thread_id = current_event.dwThreadId;
1417 case EXIT_PROCESS_DEBUG_EVENT:
1418 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1419 (unsigned) current_event.dwProcessId,
1420 (unsigned) current_event.dwThreadId,
1421 "EXIT_PROCESS_DEBUG_EVENT"));
1422 if (!windows_initialization_done)
1424 target_terminal_ours ();
1425 target_mourn_inferior ();
1426 error (_("During startup program exited with code 0x%x."),
1427 (unsigned int) current_event.u.ExitProcess.dwExitCode);
1429 else if (saw_create == 1)
1431 ourstatus->kind = TARGET_WAITKIND_EXITED;
1432 ourstatus->value.integer = current_event.u.ExitProcess.dwExitCode;
1433 thread_id = main_thread_id;
1437 case LOAD_DLL_DEBUG_EVENT:
1438 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1439 (unsigned) current_event.dwProcessId,
1440 (unsigned) current_event.dwThreadId,
1441 "LOAD_DLL_DEBUG_EVENT"));
1442 CloseHandle (current_event.u.LoadDll.hFile);
1443 if (saw_create != 1 || ! windows_initialization_done)
1445 catch_errors (handle_load_dll, NULL, (char *) "", RETURN_MASK_ALL);
1446 ourstatus->kind = TARGET_WAITKIND_LOADED;
1447 ourstatus->value.integer = 0;
1448 thread_id = main_thread_id;
1451 case UNLOAD_DLL_DEBUG_EVENT:
1452 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1453 (unsigned) current_event.dwProcessId,
1454 (unsigned) current_event.dwThreadId,
1455 "UNLOAD_DLL_DEBUG_EVENT"));
1456 if (saw_create != 1 || ! windows_initialization_done)
1458 catch_errors (handle_unload_dll, NULL, (char *) "", RETURN_MASK_ALL);
1459 ourstatus->kind = TARGET_WAITKIND_LOADED;
1460 ourstatus->value.integer = 0;
1461 thread_id = main_thread_id;
1464 case EXCEPTION_DEBUG_EVENT:
1465 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1466 (unsigned) current_event.dwProcessId,
1467 (unsigned) current_event.dwThreadId,
1468 "EXCEPTION_DEBUG_EVENT"));
1469 if (saw_create != 1)
1471 switch (handle_exception (ourstatus))
1474 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1477 thread_id = current_event.dwThreadId;
1481 continue_status = -1;
1486 case OUTPUT_DEBUG_STRING_EVENT: /* Message from the kernel. */
1487 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1488 (unsigned) current_event.dwProcessId,
1489 (unsigned) current_event.dwThreadId,
1490 "OUTPUT_DEBUG_STRING_EVENT"));
1491 if (saw_create != 1)
1493 thread_id = handle_output_debug_string (ourstatus);
1497 if (saw_create != 1)
1499 printf_unfiltered ("gdb: kernel event for pid=%u tid=0x%x\n",
1500 (unsigned) current_event.dwProcessId,
1501 (unsigned) current_event.dwThreadId);
1502 printf_unfiltered (" unknown event code %u\n",
1503 (unsigned) current_event.dwDebugEventCode);
1507 if (!thread_id || saw_create != 1)
1509 if (continue_status == -1)
1510 windows_resume (ops, minus_one_ptid, 0, 1);
1512 CHECK (windows_continue (continue_status, -1, 0));
1516 inferior_ptid = ptid_build (current_event.dwProcessId, 0,
1518 current_thread = th;
1519 if (!current_thread)
1520 current_thread = thread_rec (thread_id, TRUE);
1527 /* Wait for interesting events to occur in the target process. */
1529 windows_wait (struct target_ops *ops,
1530 ptid_t ptid, struct target_waitstatus *ourstatus, int options)
1534 target_terminal_ours ();
1536 /* We loop when we get a non-standard exception rather than return
1537 with a SPURIOUS because resume can try and step or modify things,
1538 which needs a current_thread->h. But some of these exceptions mark
1539 the birth or death of threads, which mean that the current thread
1540 isn't necessarily what you think it is. */
1546 /* If the user presses Ctrl-c while the debugger is waiting
1547 for an event, he expects the debugger to interrupt his program
1548 and to get the prompt back. There are two possible situations:
1550 - The debugger and the program do not share the console, in
1551 which case the Ctrl-c event only reached the debugger.
1552 In that case, the ctrl_c handler will take care of interrupting
1553 the inferior. Note that this case is working starting with
1554 Windows XP. For Windows 2000, Ctrl-C should be pressed in the
1557 - The debugger and the program share the same console, in which
1558 case both debugger and inferior will receive the Ctrl-c event.
1559 In that case the ctrl_c handler will ignore the event, as the
1560 Ctrl-c event generated inside the inferior will trigger the
1561 expected debug event.
1563 FIXME: brobecker/2008-05-20: If the inferior receives the
1564 signal first and the delay until GDB receives that signal
1565 is sufficiently long, GDB can sometimes receive the SIGINT
1566 after we have unblocked the CTRL+C handler. This would
1567 lead to the debugger stopping prematurely while handling
1568 the new-thread event that comes with the handling of the SIGINT
1569 inside the inferior, and then stop again immediately when
1570 the user tries to resume the execution in the inferior.
1571 This is a classic race that we should try to fix one day. */
1572 SetConsoleCtrlHandler (&ctrl_c_handler, TRUE);
1573 retval = get_windows_debug_event (ops, pid, ourstatus);
1574 SetConsoleCtrlHandler (&ctrl_c_handler, FALSE);
1577 return ptid_build (current_event.dwProcessId, 0, retval);
1582 if (deprecated_ui_loop_hook != NULL)
1583 detach = deprecated_ui_loop_hook (0);
1586 windows_kill_inferior (ops);
1591 /* Iterate over all DLLs currently mapped by our inferior, and
1592 add them to our list of solibs. */
1595 windows_add_all_dlls (void)
1598 HMODULE dummy_hmodule;
1603 if (EnumProcessModules (current_process_handle, &dummy_hmodule,
1604 sizeof (HMODULE), &cb_needed) == 0)
1610 hmodules = (HMODULE *) alloca (cb_needed);
1611 if (EnumProcessModules (current_process_handle, hmodules,
1612 cb_needed, &cb_needed) == 0)
1615 for (i = 1; i < (int) (cb_needed / sizeof (HMODULE)); i++)
1619 wchar_t dll_name[__PMAX];
1622 char dll_name[__PMAX];
1625 if (GetModuleInformation (current_process_handle, hmodules[i],
1626 &mi, sizeof (mi)) == 0)
1628 if (GetModuleFileNameEx (current_process_handle, hmodules[i],
1629 dll_name, sizeof (dll_name)) == 0)
1632 wcstombs (name, dll_name, __PMAX);
1637 solib_end->next = windows_make_so (name, mi.lpBaseOfDll);
1638 solib_end = solib_end->next;
1643 do_initial_windows_stuff (struct target_ops *ops, DWORD pid, int attaching)
1646 struct inferior *inf;
1647 struct thread_info *tp;
1649 last_sig = GDB_SIGNAL_0;
1651 exception_count = 0;
1652 open_process_used = 0;
1653 debug_registers_changed = 0;
1654 debug_registers_used = 0;
1655 for (i = 0; i < sizeof (dr) / sizeof (dr[0]); i++)
1658 cygwin_load_start = cygwin_load_end = 0;
1660 current_event.dwProcessId = pid;
1661 memset (¤t_event, 0, sizeof (current_event));
1662 if (!target_is_pushed (ops))
1664 disable_breakpoints_in_shlibs ();
1665 windows_clear_solib ();
1666 clear_proceed_status (0);
1667 init_wait_for_inferior ();
1669 inf = current_inferior ();
1670 inferior_appeared (inf, pid);
1671 inf->attach_flag = attaching;
1673 /* Make the new process the current inferior, so terminal handling
1674 can rely on it. When attaching, we don't know about any thread
1675 id here, but that's OK --- nothing should be referencing the
1676 current thread until we report an event out of windows_wait. */
1677 inferior_ptid = pid_to_ptid (pid);
1679 target_terminal_init ();
1680 target_terminal_inferior ();
1682 windows_initialization_done = 0;
1686 struct target_waitstatus status;
1688 windows_wait (ops, minus_one_ptid, &status, 0);
1690 /* Note windows_wait returns TARGET_WAITKIND_SPURIOUS for thread
1692 if (status.kind != TARGET_WAITKIND_LOADED
1693 && status.kind != TARGET_WAITKIND_SPURIOUS)
1696 windows_resume (ops, minus_one_ptid, 0, GDB_SIGNAL_0);
1699 /* Now that the inferior has been started and all DLLs have been mapped,
1700 we can iterate over all DLLs and load them in.
1702 We avoid doing it any earlier because, on certain versions of Windows,
1703 LOAD_DLL_DEBUG_EVENTs are sometimes not complete. In particular,
1704 we have seen on Windows 8.1 that the ntdll.dll load event does not
1705 include the DLL name, preventing us from creating an associated SO.
1706 A possible explanation is that ntdll.dll might be mapped before
1707 the SO info gets created by the Windows system -- ntdll.dll is
1708 the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs
1709 do not seem to suffer from that problem.
1711 Rather than try to work around this sort of issue, it is much
1712 simpler to just ignore DLL load/unload events during the startup
1713 phase, and then process them all in one batch now. */
1714 windows_add_all_dlls ();
1716 windows_initialization_done = 1;
1720 /* Try to set or remove a user privilege to the current process. Return -1
1721 if that fails, the previous setting of that privilege otherwise.
1723 This code is copied from the Cygwin source code and rearranged to allow
1724 dynamically loading of the needed symbols from advapi32 which is only
1725 available on NT/2K/XP. */
1727 set_process_privilege (const char *privilege, BOOL enable)
1729 HANDLE token_hdl = NULL;
1731 TOKEN_PRIVILEGES new_priv, orig_priv;
1735 if (!OpenProcessToken (GetCurrentProcess (),
1736 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
1740 if (!LookupPrivilegeValueA (NULL, privilege, &restore_priv))
1743 new_priv.PrivilegeCount = 1;
1744 new_priv.Privileges[0].Luid = restore_priv;
1745 new_priv.Privileges[0].Attributes = enable ? SE_PRIVILEGE_ENABLED : 0;
1747 if (!AdjustTokenPrivileges (token_hdl, FALSE, &new_priv,
1748 sizeof orig_priv, &orig_priv, &size))
1751 /* Disabled, otherwise every `attach' in an unprivileged user session
1752 would raise the "Failed to get SE_DEBUG_NAME privilege" warning in
1753 windows_attach(). */
1754 /* AdjustTokenPrivileges returns TRUE even if the privilege could not
1755 be enabled. GetLastError () returns an correct error code, though. */
1756 if (enable && GetLastError () == ERROR_NOT_ALL_ASSIGNED)
1760 ret = orig_priv.Privileges[0].Attributes == SE_PRIVILEGE_ENABLED ? 1 : 0;
1764 CloseHandle (token_hdl);
1769 /* Attach to process PID, then initialize for debugging it. */
1771 windows_attach (struct target_ops *ops, const char *args, int from_tty)
1776 pid = parse_pid_to_attach (args);
1778 if (set_process_privilege (SE_DEBUG_NAME, TRUE) < 0)
1780 printf_unfiltered ("Warning: Failed to get SE_DEBUG_NAME privilege\n");
1781 printf_unfiltered ("This can cause attach to "
1782 "fail on Windows NT/2K/XP\n");
1785 windows_init_thread_list ();
1786 ok = DebugActiveProcess (pid);
1792 /* Try fall back to Cygwin pid. */
1793 pid = cygwin_internal (CW_CYGWIN_PID_TO_WINPID, pid);
1796 ok = DebugActiveProcess (pid);
1801 error (_("Can't attach to process."));
1803 DebugSetProcessKillOnExit (FALSE);
1807 char *exec_file = (char *) get_exec_file (0);
1810 printf_unfiltered ("Attaching to program `%s', %s\n", exec_file,
1811 target_pid_to_str (pid_to_ptid (pid)));
1813 printf_unfiltered ("Attaching to %s\n",
1814 target_pid_to_str (pid_to_ptid (pid)));
1816 gdb_flush (gdb_stdout);
1819 do_initial_windows_stuff (ops, pid, 1);
1820 target_terminal_ours ();
1824 windows_detach (struct target_ops *ops, const char *args, int from_tty)
1829 windows_resume (ops, ptid, 0, GDB_SIGNAL_0);
1831 if (!DebugActiveProcessStop (current_event.dwProcessId))
1833 error (_("Can't detach process %u (error %u)"),
1834 (unsigned) current_event.dwProcessId, (unsigned) GetLastError ());
1837 DebugSetProcessKillOnExit (FALSE);
1839 if (detached && from_tty)
1841 char *exec_file = get_exec_file (0);
1844 printf_unfiltered ("Detaching from program: %s, Pid %u\n", exec_file,
1845 (unsigned) current_event.dwProcessId);
1846 gdb_flush (gdb_stdout);
1849 x86_cleanup_dregs ();
1850 inferior_ptid = null_ptid;
1851 detach_inferior (current_event.dwProcessId);
1853 inf_child_maybe_unpush_target (ops);
1856 /* Try to determine the executable filename.
1858 EXE_NAME_RET is a pointer to a buffer whose size is EXE_NAME_MAX_LEN.
1860 Upon success, the filename is stored inside EXE_NAME_RET, and
1861 this function returns nonzero.
1863 Otherwise, this function returns zero and the contents of
1864 EXE_NAME_RET is undefined. */
1867 windows_get_exec_module_filename (char *exe_name_ret, size_t exe_name_max_len)
1874 if (!EnumProcessModules (current_process_handle, &dh_buf,
1875 sizeof (HMODULE), &cbNeeded) || !cbNeeded)
1878 /* We know the executable is always first in the list of modules,
1879 which we just fetched. So no need to fetch more. */
1883 /* Cygwin prefers that the path be in /x/y/z format, so extract
1884 the filename into a temporary buffer first, and then convert it
1885 to POSIX format into the destination buffer. */
1886 cygwin_buf_t *pathbuf = alloca (exe_name_max_len * sizeof (cygwin_buf_t));
1888 len = GetModuleFileNameEx (current_process_handle,
1889 dh_buf, pathbuf, exe_name_max_len);
1891 error (_("Error getting executable filename: %u."),
1892 (unsigned) GetLastError ());
1893 if (cygwin_conv_path (CCP_WIN_W_TO_POSIX, pathbuf, exe_name_ret,
1894 exe_name_max_len) < 0)
1895 error (_("Error converting executable filename to POSIX: %d."), errno);
1898 len = GetModuleFileNameEx (current_process_handle,
1899 dh_buf, exe_name_ret, exe_name_max_len);
1901 error (_("Error getting executable filename: %u."),
1902 (unsigned) GetLastError ());
1905 return 1; /* success */
1908 /* The pid_to_exec_file target_ops method for this platform. */
1911 windows_pid_to_exec_file (struct target_ops *self, int pid)
1913 static char path[__PMAX];
1915 /* Try to find exe name as symlink target of /proc/<pid>/exe. */
1917 char procexe[sizeof ("/proc/4294967295/exe")];
1919 xsnprintf (procexe, sizeof (procexe), "/proc/%u/exe", pid);
1920 nchars = readlink (procexe, path, sizeof(path));
1921 if (nchars > 0 && nchars < sizeof (path))
1923 path[nchars] = '\0'; /* Got it */
1928 /* If we get here then either Cygwin is hosed, this isn't a Cygwin version
1929 of gdb, or we're trying to debug a non-Cygwin windows executable. */
1930 if (!windows_get_exec_module_filename (path, sizeof (path)))
1936 /* Print status information about what we're accessing. */
1939 windows_files_info (struct target_ops *ignore)
1941 struct inferior *inf = current_inferior ();
1943 printf_unfiltered ("\tUsing the running image of %s %s.\n",
1944 inf->attach_flag ? "attached" : "child",
1945 target_pid_to_str (inferior_ptid));
1948 /* Modify CreateProcess parameters for use of a new separate console.
1950 *FLAGS: DWORD parameter for general process creation flags.
1951 *SI: STARTUPINFO structure, for which the console window size and
1952 console buffer size is filled in if GDB is running in a console.
1953 to create the new console.
1954 The size of the used font is not available on all versions of
1955 Windows OS. Furthermore, the current font might not be the default
1956 font, but this is still better than before.
1957 If the windows and buffer sizes are computed,
1958 SI->DWFLAGS is changed so that this information is used
1959 by CreateProcess function. */
1962 windows_set_console_info (STARTUPINFO *si, DWORD *flags)
1964 HANDLE hconsole = CreateFile ("CONOUT$", GENERIC_READ | GENERIC_WRITE,
1965 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
1967 if (hconsole != INVALID_HANDLE_VALUE)
1969 CONSOLE_SCREEN_BUFFER_INFO sbinfo;
1971 CONSOLE_FONT_INFO cfi;
1973 GetCurrentConsoleFont (hconsole, FALSE, &cfi);
1974 font_size = GetConsoleFontSize (hconsole, cfi.nFont);
1975 GetConsoleScreenBufferInfo(hconsole, &sbinfo);
1976 si->dwXSize = sbinfo.srWindow.Right - sbinfo.srWindow.Left + 1;
1977 si->dwYSize = sbinfo.srWindow.Bottom - sbinfo.srWindow.Top + 1;
1979 si->dwXSize *= font_size.X;
1983 si->dwYSize *= font_size.Y;
1986 si->dwXCountChars = sbinfo.dwSize.X;
1987 si->dwYCountChars = sbinfo.dwSize.Y;
1988 si->dwFlags |= STARTF_USESIZE | STARTF_USECOUNTCHARS;
1990 *flags |= CREATE_NEW_CONSOLE;
1994 /* Function called by qsort to sort environment strings. */
1997 envvar_cmp (const void *a, const void *b)
1999 const char **p = (const char **) a;
2000 const char **q = (const char **) b;
2001 return strcasecmp (*p, *q);
2007 clear_win32_environment (char **env)
2011 wchar_t *copy = NULL, *equalpos;
2013 for (i = 0; env[i] && *env[i]; i++)
2015 len = mbstowcs (NULL, env[i], 0) + 1;
2016 copy = (wchar_t *) xrealloc (copy, len * sizeof (wchar_t));
2017 mbstowcs (copy, env[i], len);
2018 equalpos = wcschr (copy, L'=');
2021 SetEnvironmentVariableW (copy, NULL);
2027 /* Start an inferior windows child process and sets inferior_ptid to its pid.
2028 EXEC_FILE is the file to run.
2029 ALLARGS is a string containing the arguments to the program.
2030 ENV is the environment vector to pass. Errors reported with error(). */
2033 windows_create_inferior (struct target_ops *ops, char *exec_file,
2034 char *allargs, char **in_env, int from_tty)
2038 cygwin_buf_t real_path[__PMAX];
2039 cygwin_buf_t shell[__PMAX]; /* Path to shell */
2041 cygwin_buf_t *toexec;
2042 cygwin_buf_t *cygallargs;
2044 char **old_env = NULL;
2048 int ostdin, ostdout, ostderr;
2050 char real_path[__PMAX];
2051 char shell[__PMAX]; /* Path to shell */
2063 PROCESS_INFORMATION pi;
2066 const char *inferior_io_terminal = get_inferior_io_terminal ();
2069 error (_("No executable specified, use `target exec'."));
2071 memset (&si, 0, sizeof (si));
2072 si.cb = sizeof (si);
2075 flags |= CREATE_NEW_PROCESS_GROUP;
2078 windows_set_console_info (&si, &flags);
2083 flags |= DEBUG_ONLY_THIS_PROCESS;
2084 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, exec_file, real_path,
2085 __PMAX * sizeof (cygwin_buf_t)) < 0)
2086 error (_("Error starting executable: %d"), errno);
2089 len = mbstowcs (NULL, allargs, 0) + 1;
2090 if (len == (size_t) -1)
2091 error (_("Error starting executable: %d"), errno);
2092 cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
2093 mbstowcs (cygallargs, allargs, len);
2095 cygallargs = allargs;
2100 sh = getenv ("SHELL");
2103 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, sh, shell, __PMAX) < 0)
2104 error (_("Error starting executable via shell: %d"), errno);
2106 len = sizeof (L" -c 'exec '") + mbstowcs (NULL, exec_file, 0)
2107 + mbstowcs (NULL, allargs, 0) + 2;
2108 cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
2109 swprintf (cygallargs, len, L" -c 'exec %s %s'", exec_file, allargs);
2111 len = (sizeof (" -c 'exec '") + strlen (exec_file)
2112 + strlen (allargs) + 2);
2113 cygallargs = (char *) alloca (len);
2114 xsnprintf (cygallargs, len, " -c 'exec %s %s'", exec_file, allargs);
2117 flags |= DEBUG_PROCESS;
2121 args = (cygwin_buf_t *) alloca ((wcslen (toexec) + wcslen (cygallargs) + 2)
2122 * sizeof (wchar_t));
2123 wcscpy (args, toexec);
2124 wcscat (args, L" ");
2125 wcscat (args, cygallargs);
2127 args = (cygwin_buf_t *) alloca (strlen (toexec) + strlen (cygallargs) + 2);
2128 strcpy (args, toexec);
2130 strcat (args, cygallargs);
2133 #ifdef CW_CVT_ENV_TO_WINENV
2134 /* First try to create a direct Win32 copy of the POSIX environment. */
2135 w32_env = (PWCHAR) cygwin_internal (CW_CVT_ENV_TO_WINENV, in_env);
2136 if (w32_env != (PWCHAR) -1)
2137 flags |= CREATE_UNICODE_ENVIRONMENT;
2139 /* If that fails, fall back to old method tweaking GDB's environment. */
2142 /* Reset all Win32 environment variables to avoid leftover on next run. */
2143 clear_win32_environment (environ);
2144 /* Prepare the environment vars for CreateProcess. */
2147 cygwin_internal (CW_SYNC_WINENV);
2151 if (!inferior_io_terminal)
2152 tty = ostdin = ostdout = ostderr = -1;
2155 tty = open (inferior_io_terminal, O_RDWR | O_NOCTTY);
2158 print_sys_errmsg (inferior_io_terminal, errno);
2159 ostdin = ostdout = ostderr = -1;
2172 windows_init_thread_list ();
2173 ret = CreateProcess (0,
2174 args, /* command line */
2175 NULL, /* Security */
2177 TRUE, /* inherit handles */
2178 flags, /* start flags */
2179 w32_env, /* environment */
2180 NULL, /* current directory */
2184 /* Just free the Win32 environment, if it could be created. */
2188 /* Reset all environment variables to avoid leftover on next run. */
2189 clear_win32_environment (in_env);
2190 /* Restore normal GDB environment variables. */
2192 cygwin_internal (CW_SYNC_WINENV);
2207 /* Build the command line, a space-separated list of tokens where
2208 the first token is the name of the module to be executed.
2209 To avoid ambiguities introduced by spaces in the module name,
2211 args_len = strlen (toexec) + 2 /* quotes */ + strlen (allargs) + 2;
2212 args = (char *) alloca (args_len);
2213 xsnprintf (args, args_len, "\"%s\" %s", toexec, allargs);
2215 flags |= DEBUG_ONLY_THIS_PROCESS;
2217 if (!inferior_io_terminal)
2218 tty = INVALID_HANDLE_VALUE;
2221 SECURITY_ATTRIBUTES sa;
2222 sa.nLength = sizeof(sa);
2223 sa.lpSecurityDescriptor = 0;
2224 sa.bInheritHandle = TRUE;
2225 tty = CreateFileA (inferior_io_terminal, GENERIC_READ | GENERIC_WRITE,
2226 0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
2227 if (tty == INVALID_HANDLE_VALUE)
2228 warning (_("Warning: Failed to open TTY %s, error %#x."),
2229 inferior_io_terminal, (unsigned) GetLastError ());
2233 si.hStdOutput = tty;
2235 si.dwFlags |= STARTF_USESTDHANDLES;
2239 /* CreateProcess takes the environment list as a null terminated set of
2240 strings (i.e. two nulls terminate the list). */
2242 /* Get total size for env strings. */
2243 for (envlen = 0, i = 0; in_env[i] && *in_env[i]; i++)
2244 envlen += strlen (in_env[i]) + 1;
2246 envsize = sizeof (in_env[0]) * (i + 1);
2247 env = (char **) alloca (envsize);
2248 memcpy (env, in_env, envsize);
2249 /* Windows programs expect the environment block to be sorted. */
2250 qsort (env, i, sizeof (char *), envvar_cmp);
2252 w32env = (char *) alloca (envlen + 1);
2254 /* Copy env strings into new buffer. */
2255 for (temp = w32env, i = 0; env[i] && *env[i]; i++)
2257 strcpy (temp, env[i]);
2258 temp += strlen (temp) + 1;
2261 /* Final nil string to terminate new env. */
2264 windows_init_thread_list ();
2265 ret = CreateProcessA (0,
2266 args, /* command line */
2267 NULL, /* Security */
2269 TRUE, /* inherit handles */
2270 flags, /* start flags */
2271 w32env, /* environment */
2272 NULL, /* current directory */
2275 if (tty != INVALID_HANDLE_VALUE)
2280 error (_("Error creating process %s, (error %u)."),
2281 exec_file, (unsigned) GetLastError ());
2283 CloseHandle (pi.hThread);
2284 CloseHandle (pi.hProcess);
2286 if (useshell && shell[0] != '\0')
2291 do_initial_windows_stuff (ops, pi.dwProcessId, 0);
2293 /* windows_continue (DBG_CONTINUE, -1, 0); */
2297 windows_mourn_inferior (struct target_ops *ops)
2299 (void) windows_continue (DBG_CONTINUE, -1, 0);
2300 x86_cleanup_dregs();
2301 if (open_process_used)
2303 CHECK (CloseHandle (current_process_handle));
2304 open_process_used = 0;
2306 inf_child_mourn_inferior (ops);
2309 /* Send a SIGINT to the process group. This acts just like the user typed a
2310 ^C on the controlling terminal. */
2313 windows_interrupt (struct target_ops *self, ptid_t ptid)
2315 DEBUG_EVENTS (("gdb: GenerateConsoleCtrlEvent (CTRLC_EVENT, 0)\n"));
2316 CHECK (GenerateConsoleCtrlEvent (CTRL_C_EVENT, current_event.dwProcessId));
2317 registers_changed (); /* refresh register state */
2320 /* Helper for windows_xfer_partial that handles memory transfers.
2321 Arguments are like target_xfer_partial. */
2323 static enum target_xfer_status
2324 windows_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
2325 ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
2329 DWORD lasterror = 0;
2331 if (writebuf != NULL)
2333 DEBUG_MEM (("gdb: write target memory, %s bytes at %s\n",
2334 pulongest (len), core_addr_to_string (memaddr)));
2335 success = WriteProcessMemory (current_process_handle,
2336 (LPVOID) (uintptr_t) memaddr, writebuf,
2339 lasterror = GetLastError ();
2340 FlushInstructionCache (current_process_handle,
2341 (LPCVOID) (uintptr_t) memaddr, len);
2345 DEBUG_MEM (("gdb: read target memory, %s bytes at %s\n",
2346 pulongest (len), core_addr_to_string (memaddr)));
2347 success = ReadProcessMemory (current_process_handle,
2348 (LPCVOID) (uintptr_t) memaddr, readbuf,
2351 lasterror = GetLastError ();
2353 *xfered_len = (ULONGEST) done;
2354 if (!success && lasterror == ERROR_PARTIAL_COPY && done > 0)
2355 return TARGET_XFER_OK;
2357 return success ? TARGET_XFER_OK : TARGET_XFER_E_IO;
2361 windows_kill_inferior (struct target_ops *ops)
2363 CHECK (TerminateProcess (current_process_handle, 0));
2367 if (!windows_continue (DBG_CONTINUE, -1, 1))
2369 if (!WaitForDebugEvent (¤t_event, INFINITE))
2371 if (current_event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
2375 target_mourn_inferior (); /* Or just windows_mourn_inferior? */
2379 windows_close (struct target_ops *self)
2381 DEBUG_EVENTS (("gdb: windows_close, inferior_ptid=%d\n",
2382 ptid_get_pid (inferior_ptid)));
2385 /* Convert pid to printable format. */
2387 windows_pid_to_str (struct target_ops *ops, ptid_t ptid)
2389 static char buf[80];
2391 if (ptid_get_tid (ptid) != 0)
2393 snprintf (buf, sizeof (buf), "Thread %d.0x%lx",
2394 ptid_get_pid (ptid), ptid_get_tid (ptid));
2398 return normal_pid_to_str (ptid);
2401 static enum target_xfer_status
2402 windows_xfer_shared_libraries (struct target_ops *ops,
2403 enum target_object object, const char *annex,
2404 gdb_byte *readbuf, const gdb_byte *writebuf,
2405 ULONGEST offset, ULONGEST len,
2406 ULONGEST *xfered_len)
2408 struct obstack obstack;
2414 return TARGET_XFER_E_IO;
2416 obstack_init (&obstack);
2417 obstack_grow_str (&obstack, "<library-list>\n");
2418 for (so = solib_start.next; so; so = so->next)
2419 windows_xfer_shared_library (so->so_name, (CORE_ADDR)
2420 (uintptr_t) so->lm_info->load_addr,
2421 target_gdbarch (), &obstack);
2422 obstack_grow_str0 (&obstack, "</library-list>\n");
2424 buf = (const char *) obstack_finish (&obstack);
2425 len_avail = strlen (buf);
2426 if (offset >= len_avail)
2430 if (len > len_avail - offset)
2431 len = len_avail - offset;
2432 memcpy (readbuf, buf + offset, len);
2435 obstack_free (&obstack, NULL);
2436 *xfered_len = (ULONGEST) len;
2437 return len != 0 ? TARGET_XFER_OK : TARGET_XFER_EOF;
2440 static enum target_xfer_status
2441 windows_xfer_partial (struct target_ops *ops, enum target_object object,
2442 const char *annex, gdb_byte *readbuf,
2443 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
2444 ULONGEST *xfered_len)
2448 case TARGET_OBJECT_MEMORY:
2449 return windows_xfer_memory (readbuf, writebuf, offset, len, xfered_len);
2451 case TARGET_OBJECT_LIBRARIES:
2452 return windows_xfer_shared_libraries (ops, object, annex, readbuf,
2453 writebuf, offset, len, xfered_len);
2456 return ops->beneath->to_xfer_partial (ops->beneath, object, annex,
2457 readbuf, writebuf, offset, len,
2462 /* Provide thread local base, i.e. Thread Information Block address.
2463 Returns 1 if ptid is found and sets *ADDR to thread_local_base. */
2466 windows_get_tib_address (struct target_ops *self,
2467 ptid_t ptid, CORE_ADDR *addr)
2469 windows_thread_info *th;
2471 th = thread_rec (ptid_get_tid (ptid), 0);
2476 *addr = th->thread_local_base;
2482 windows_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
2484 return ptid_build (ptid_get_pid (inferior_ptid), 0, lwp);
2487 static struct target_ops *
2488 windows_target (void)
2490 struct target_ops *t = inf_child_target ();
2492 t->to_close = windows_close;
2493 t->to_attach = windows_attach;
2494 t->to_attach_no_wait = 1;
2495 t->to_detach = windows_detach;
2496 t->to_resume = windows_resume;
2497 t->to_wait = windows_wait;
2498 t->to_fetch_registers = windows_fetch_inferior_registers;
2499 t->to_store_registers = windows_store_inferior_registers;
2500 t->to_xfer_partial = windows_xfer_partial;
2501 t->to_files_info = windows_files_info;
2502 t->to_kill = windows_kill_inferior;
2503 t->to_create_inferior = windows_create_inferior;
2504 t->to_mourn_inferior = windows_mourn_inferior;
2505 t->to_thread_alive = windows_thread_alive;
2506 t->to_pid_to_str = windows_pid_to_str;
2507 t->to_interrupt = windows_interrupt;
2508 t->to_pid_to_exec_file = windows_pid_to_exec_file;
2509 t->to_get_ada_task_ptid = windows_get_ada_task_ptid;
2510 t->to_get_tib_address = windows_get_tib_address;
2515 /* -Wmissing-prototypes */
2516 extern initialize_file_ftype _initialize_windows_nat;
2519 _initialize_windows_nat (void)
2521 struct target_ops *t;
2523 t = windows_target ();
2525 x86_use_watchpoints (t);
2527 x86_dr_low.set_control = cygwin_set_dr7;
2528 x86_dr_low.set_addr = cygwin_set_dr;
2529 x86_dr_low.get_addr = cygwin_get_dr;
2530 x86_dr_low.get_status = cygwin_get_dr6;
2531 x86_dr_low.get_control = cygwin_get_dr7;
2533 /* x86_dr_low.debug_register_length field is set by
2534 calling x86_set_debug_register_length function
2535 in processor windows specific native file. */
2540 cygwin_internal (CW_SET_DOS_FILE_WARNING, 0);
2544 add_setshow_boolean_cmd ("shell", class_support, &useshell, _("\
2545 Set use of shell to start subprocess."), _("\
2546 Show use of shell to start subprocess."), NULL,
2548 NULL, /* FIXME: i18n: */
2549 &setlist, &showlist);
2551 add_setshow_boolean_cmd ("cygwin-exceptions", class_support,
2552 &cygwin_exceptions, _("\
2553 Break when an exception is detected in the Cygwin DLL itself."), _("\
2554 Show whether gdb breaks on exceptions in the Cygwin DLL itself."), NULL,
2556 NULL, /* FIXME: i18n: */
2557 &setlist, &showlist);
2560 add_setshow_boolean_cmd ("new-console", class_support, &new_console, _("\
2561 Set creation of new console when creating child process."), _("\
2562 Show creation of new console when creating child process."), NULL,
2564 NULL, /* FIXME: i18n: */
2565 &setlist, &showlist);
2567 add_setshow_boolean_cmd ("new-group", class_support, &new_group, _("\
2568 Set creation of new group when creating child process."), _("\
2569 Show creation of new group when creating child process."), NULL,
2571 NULL, /* FIXME: i18n: */
2572 &setlist, &showlist);
2574 add_setshow_boolean_cmd ("debugexec", class_support, &debug_exec, _("\
2575 Set whether to display execution in child process."), _("\
2576 Show whether to display execution in child process."), NULL,
2578 NULL, /* FIXME: i18n: */
2579 &setlist, &showlist);
2581 add_setshow_boolean_cmd ("debugevents", class_support, &debug_events, _("\
2582 Set whether to display kernel events in child process."), _("\
2583 Show whether to display kernel events in child process."), NULL,
2585 NULL, /* FIXME: i18n: */
2586 &setlist, &showlist);
2588 add_setshow_boolean_cmd ("debugmemory", class_support, &debug_memory, _("\
2589 Set whether to display memory accesses in child process."), _("\
2590 Show whether to display memory accesses in child process."), NULL,
2592 NULL, /* FIXME: i18n: */
2593 &setlist, &showlist);
2595 add_setshow_boolean_cmd ("debugexceptions", class_support,
2596 &debug_exceptions, _("\
2597 Set whether to display kernel exceptions in child process."), _("\
2598 Show whether to display kernel exceptions in child process."), NULL,
2600 NULL, /* FIXME: i18n: */
2601 &setlist, &showlist);
2603 init_w32_command_list ();
2605 add_cmd ("selector", class_info, display_selectors,
2606 _("Display selectors infos."),
2610 /* Hardware watchpoint support, adapted from go32-nat.c code. */
2612 /* Pass the address ADDR to the inferior in the I'th debug register.
2613 Here we just store the address in dr array, the registers will be
2614 actually set up when windows_continue is called. */
2616 cygwin_set_dr (int i, CORE_ADDR addr)
2619 internal_error (__FILE__, __LINE__,
2620 _("Invalid register %d in cygwin_set_dr.\n"), i);
2622 debug_registers_changed = 1;
2623 debug_registers_used = 1;
2626 /* Pass the value VAL to the inferior in the DR7 debug control
2627 register. Here we just store the address in D_REGS, the watchpoint
2628 will be actually set up in windows_wait. */
2630 cygwin_set_dr7 (unsigned long val)
2632 dr[7] = (CORE_ADDR) val;
2633 debug_registers_changed = 1;
2634 debug_registers_used = 1;
2637 /* Get the value of debug register I from the inferior. */
2640 cygwin_get_dr (int i)
2645 /* Get the value of the DR6 debug status register from the inferior.
2646 Here we just return the value stored in dr[6]
2647 by the last call to thread_rec for current_event.dwThreadId id. */
2648 static unsigned long
2649 cygwin_get_dr6 (void)
2651 return (unsigned long) dr[6];
2654 /* Get the value of the DR7 debug status register from the inferior.
2655 Here we just return the value stored in dr[7] by the last call to
2656 thread_rec for current_event.dwThreadId id. */
2658 static unsigned long
2659 cygwin_get_dr7 (void)
2661 return (unsigned long) dr[7];
2664 /* Determine if the thread referenced by "ptid" is alive
2665 by "polling" it. If WaitForSingleObject returns WAIT_OBJECT_0
2666 it means that the thread has died. Otherwise it is assumed to be alive. */
2668 windows_thread_alive (struct target_ops *ops, ptid_t ptid)
2672 gdb_assert (ptid_get_tid (ptid) != 0);
2673 tid = ptid_get_tid (ptid);
2675 return WaitForSingleObject (thread_rec (tid, FALSE)->h, 0) == WAIT_OBJECT_0
2679 /* -Wmissing-prototypes */
2680 extern initialize_file_ftype _initialize_check_for_gdb_ini;
2683 _initialize_check_for_gdb_ini (void)
2686 if (inhibit_gdbinit)
2689 homedir = getenv ("HOME");
2693 char *oldini = (char *) alloca (strlen (homedir) +
2694 sizeof ("/gdb.ini"));
2695 strcpy (oldini, homedir);
2696 p = strchr (oldini, '\0');
2697 if (p > oldini && !IS_DIR_SEPARATOR (p[-1]))
2699 strcpy (p, "gdb.ini");
2700 if (access (oldini, 0) == 0)
2702 int len = strlen (oldini);
2703 char *newini = (char *) alloca (len + 1);
2705 xsnprintf (newini, len + 1, "%.*s.gdbinit",
2706 (int) (len - (sizeof ("gdb.ini") - 1)), oldini);
2707 warning (_("obsolete '%s' found. Rename to '%s'."), oldini, newini);
2712 /* Define dummy functions which always return error for the rare cases where
2713 these functions could not be found. */
2715 bad_DebugActiveProcessStop (DWORD w)
2720 bad_DebugBreakProcess (HANDLE w)
2725 bad_DebugSetProcessKillOnExit (BOOL w)
2730 bad_EnumProcessModules (HANDLE w, HMODULE *x, DWORD y, LPDWORD z)
2737 bad_GetModuleFileNameExW (HANDLE w, HMODULE x, LPWSTR y, DWORD z)
2743 bad_GetModuleFileNameExA (HANDLE w, HMODULE x, LPSTR y, DWORD z)
2750 bad_GetModuleInformation (HANDLE w, HMODULE x, LPMODULEINFO y, DWORD z)
2756 bad_OpenProcessToken (HANDLE w, DWORD x, PHANDLE y)
2762 bad_GetCurrentConsoleFont (HANDLE w, BOOL bMaxWindow, CONSOLE_FONT_INFO *f)
2768 bad_GetConsoleFontSize (HANDLE w, DWORD nFont)
2776 /* -Wmissing-prototypes */
2777 extern initialize_file_ftype _initialize_loadable;
2779 /* Load any functions which may not be available in ancient versions
2783 _initialize_loadable (void)
2787 hm = LoadLibrary ("kernel32.dll");
2790 DebugActiveProcessStop = (void *)
2791 GetProcAddress (hm, "DebugActiveProcessStop");
2792 DebugBreakProcess = (void *)
2793 GetProcAddress (hm, "DebugBreakProcess");
2794 DebugSetProcessKillOnExit = (void *)
2795 GetProcAddress (hm, "DebugSetProcessKillOnExit");
2796 GetConsoleFontSize = (void *)
2797 GetProcAddress (hm, "GetConsoleFontSize");
2798 GetCurrentConsoleFont = (void *)
2799 GetProcAddress (hm, "GetCurrentConsoleFont");
2802 /* Set variables to dummy versions of these processes if the function
2803 wasn't found in kernel32.dll. */
2804 if (!DebugBreakProcess)
2805 DebugBreakProcess = bad_DebugBreakProcess;
2806 if (!DebugActiveProcessStop || !DebugSetProcessKillOnExit)
2808 DebugActiveProcessStop = bad_DebugActiveProcessStop;
2809 DebugSetProcessKillOnExit = bad_DebugSetProcessKillOnExit;
2811 if (!GetConsoleFontSize)
2812 GetConsoleFontSize = bad_GetConsoleFontSize;
2813 if (!GetCurrentConsoleFont)
2814 GetCurrentConsoleFont = bad_GetCurrentConsoleFont;
2816 /* Load optional functions used for retrieving filename information
2817 associated with the currently debugged process or its dlls. */
2818 hm = LoadLibrary ("psapi.dll");
2821 EnumProcessModules = (void *)
2822 GetProcAddress (hm, "EnumProcessModules");
2823 GetModuleInformation = (void *)
2824 GetProcAddress (hm, "GetModuleInformation");
2825 GetModuleFileNameEx = (void *)
2826 GetProcAddress (hm, GetModuleFileNameEx_name);
2829 if (!EnumProcessModules || !GetModuleInformation || !GetModuleFileNameEx)
2831 /* Set variables to dummy versions of these processes if the function
2832 wasn't found in psapi.dll. */
2833 EnumProcessModules = bad_EnumProcessModules;
2834 GetModuleInformation = bad_GetModuleInformation;
2835 GetModuleFileNameEx = bad_GetModuleFileNameEx;
2836 /* This will probably fail on Windows 9x/Me. Let the user know
2837 that we're missing some functionality. */
2839 cannot automatically find executable file or library to read symbols.\n\
2840 Use \"file\" or \"dll\" command to load executable/libraries directly."));
2843 hm = LoadLibrary ("advapi32.dll");
2846 OpenProcessToken = (void *) GetProcAddress (hm, "OpenProcessToken");
2847 LookupPrivilegeValueA = (void *)
2848 GetProcAddress (hm, "LookupPrivilegeValueA");
2849 AdjustTokenPrivileges = (void *)
2850 GetProcAddress (hm, "AdjustTokenPrivileges");
2851 /* Only need to set one of these since if OpenProcessToken fails nothing
2853 if (!OpenProcessToken || !LookupPrivilegeValueA
2854 || !AdjustTokenPrivileges)
2855 OpenProcessToken = bad_OpenProcessToken;