1 /* Target-vector operations for controlling windows child processes, for GDB.
3 Copyright (C) 1995-2017 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"
61 #include "i386-tdep.h"
62 #include "i387-tdep.h"
64 #include "windows-tdep.h"
65 #include "windows-nat.h"
67 #include "complaints.h"
68 #include "inf-child.h"
69 #include "gdb_tilde_expand.h"
71 #define AdjustTokenPrivileges dyn_AdjustTokenPrivileges
72 #define DebugActiveProcessStop dyn_DebugActiveProcessStop
73 #define DebugBreakProcess dyn_DebugBreakProcess
74 #define DebugSetProcessKillOnExit dyn_DebugSetProcessKillOnExit
75 #define EnumProcessModules dyn_EnumProcessModules
76 #define GetModuleInformation dyn_GetModuleInformation
77 #define LookupPrivilegeValueA dyn_LookupPrivilegeValueA
78 #define OpenProcessToken dyn_OpenProcessToken
79 #define GetConsoleFontSize dyn_GetConsoleFontSize
80 #define GetCurrentConsoleFont dyn_GetCurrentConsoleFont
82 typedef BOOL WINAPI (AdjustTokenPrivileges_ftype) (HANDLE, BOOL,
84 DWORD, PTOKEN_PRIVILEGES,
86 static AdjustTokenPrivileges_ftype *AdjustTokenPrivileges;
88 typedef BOOL WINAPI (DebugActiveProcessStop_ftype) (DWORD);
89 static DebugActiveProcessStop_ftype *DebugActiveProcessStop;
91 typedef BOOL WINAPI (DebugBreakProcess_ftype) (HANDLE);
92 static DebugBreakProcess_ftype *DebugBreakProcess;
94 typedef BOOL WINAPI (DebugSetProcessKillOnExit_ftype) (BOOL);
95 static DebugSetProcessKillOnExit_ftype *DebugSetProcessKillOnExit;
97 typedef BOOL WINAPI (EnumProcessModules_ftype) (HANDLE, HMODULE *, DWORD,
99 static EnumProcessModules_ftype *EnumProcessModules;
101 typedef BOOL WINAPI (GetModuleInformation_ftype) (HANDLE, HMODULE,
102 LPMODULEINFO, DWORD);
103 static GetModuleInformation_ftype *GetModuleInformation;
105 typedef BOOL WINAPI (LookupPrivilegeValueA_ftype) (LPCSTR, LPCSTR, PLUID);
106 static LookupPrivilegeValueA_ftype *LookupPrivilegeValueA;
108 typedef BOOL WINAPI (OpenProcessToken_ftype) (HANDLE, DWORD, PHANDLE);
109 static OpenProcessToken_ftype *OpenProcessToken;
111 typedef BOOL WINAPI (GetCurrentConsoleFont_ftype) (HANDLE, BOOL,
112 CONSOLE_FONT_INFO *);
113 static GetCurrentConsoleFont_ftype *GetCurrentConsoleFont;
115 typedef COORD WINAPI (GetConsoleFontSize_ftype) (HANDLE, DWORD);
116 static GetConsoleFontSize_ftype *GetConsoleFontSize;
120 #undef GetModuleFileNameEx
123 # define __PMAX (MAX_PATH + 1)
124 typedef DWORD WINAPI (GetModuleFileNameEx_ftype) (HANDLE, HMODULE, LPSTR, DWORD);
125 static GetModuleFileNameEx_ftype *GetModuleFileNameEx;
126 # define STARTUPINFO STARTUPINFOA
127 # define CreateProcess CreateProcessA
128 # define GetModuleFileNameEx_name "GetModuleFileNameExA"
129 # define bad_GetModuleFileNameEx bad_GetModuleFileNameExA
131 # define __PMAX PATH_MAX
132 /* The starting and ending address of the cygwin1.dll text segment. */
133 static CORE_ADDR cygwin_load_start;
134 static CORE_ADDR cygwin_load_end;
136 typedef wchar_t cygwin_buf_t;
137 typedef DWORD WINAPI (GetModuleFileNameEx_ftype) (HANDLE, HMODULE,
139 static GetModuleFileNameEx_ftype *GetModuleFileNameEx;
140 # define STARTUPINFO STARTUPINFOW
141 # define CreateProcess CreateProcessW
142 # define GetModuleFileNameEx_name "GetModuleFileNameExW"
143 # define bad_GetModuleFileNameEx bad_GetModuleFileNameExW
146 static int have_saved_context; /* True if we've saved context from a
148 static CONTEXT saved_context; /* Containes the saved context from a
151 /* If we're not using the old Cygwin header file set, define the
152 following which never should have been in the generic Win32 API
153 headers in the first place since they were our own invention... */
154 #ifndef _GNU_H_WINDOWS_H
157 FLAG_TRACE_BIT = 0x100,
161 #ifndef CONTEXT_EXTENDED_REGISTERS
162 /* This macro is only defined on ia32. It only makes sense on this target,
163 so define it as zero if not already defined. */
164 #define CONTEXT_EXTENDED_REGISTERS 0
167 #define CONTEXT_DEBUGGER_DR CONTEXT_FULL | CONTEXT_FLOATING_POINT \
168 | CONTEXT_SEGMENTS | CONTEXT_DEBUG_REGISTERS \
169 | CONTEXT_EXTENDED_REGISTERS
171 static uintptr_t dr[8];
172 static int debug_registers_changed;
173 static int debug_registers_used;
175 static int windows_initialization_done;
176 #define DR6_CLEAR_VALUE 0xffff0ff0
178 /* The exception thrown by a program to tell the debugger the name of
179 a thread. The exception record contains an ID of a thread and a
180 name to give it. This exception has no documented name, but MSDN
181 dubs it "MS_VC_EXCEPTION" in one code example. */
182 #define MS_VC_EXCEPTION 0x406d1388
186 HANDLE_EXCEPTION_UNHANDLED = 0,
187 HANDLE_EXCEPTION_HANDLED,
188 HANDLE_EXCEPTION_IGNORED
189 } handle_exception_result;
191 /* The string sent by cygwin when it processes a signal.
192 FIXME: This should be in a cygwin include file. */
193 #ifndef _CYGWIN_SIGNAL_STRING
194 #define _CYGWIN_SIGNAL_STRING "cYgSiGw00f"
197 #define CHECK(x) check (x, __FILE__,__LINE__)
198 #define DEBUG_EXEC(x) if (debug_exec) printf_unfiltered x
199 #define DEBUG_EVENTS(x) if (debug_events) printf_unfiltered x
200 #define DEBUG_MEM(x) if (debug_memory) printf_unfiltered x
201 #define DEBUG_EXCEPT(x) if (debug_exceptions) printf_unfiltered x
203 static void windows_interrupt (struct target_ops *self, ptid_t);
204 static int windows_thread_alive (struct target_ops *, ptid_t);
205 static void windows_kill_inferior (struct target_ops *);
207 static void cygwin_set_dr (int i, CORE_ADDR addr);
208 static void cygwin_set_dr7 (unsigned long val);
209 static CORE_ADDR cygwin_get_dr (int i);
210 static unsigned long cygwin_get_dr6 (void);
211 static unsigned long cygwin_get_dr7 (void);
213 static enum gdb_signal last_sig = GDB_SIGNAL_0;
214 /* Set if a signal was received from the debugged process. */
216 /* Thread information structure used to track information that is
217 not available in gdb's thread structure. */
218 typedef struct windows_thread_info_struct
220 struct windows_thread_info_struct *next;
223 CORE_ADDR thread_local_base;
232 static windows_thread_info thread_head;
234 /* The process and thread handles for the above context. */
236 static DEBUG_EVENT current_event; /* The current debug event from
238 static HANDLE current_process_handle; /* Currently executing process */
239 static windows_thread_info *current_thread; /* Info on currently selected thread */
240 static DWORD main_thread_id; /* Thread ID of the main thread */
242 /* Counts of things. */
243 static int exception_count = 0;
244 static int event_count = 0;
245 static int saw_create;
246 static int open_process_used = 0;
249 static int new_console = 0;
251 static int cygwin_exceptions = 0;
253 static int new_group = 1;
254 static int debug_exec = 0; /* show execution */
255 static int debug_events = 0; /* show events from kernel */
256 static int debug_memory = 0; /* show target memory accesses */
257 static int debug_exceptions = 0; /* show target exceptions */
258 static int useshell = 0; /* use shell for subprocesses */
260 /* This vector maps GDB's idea of a register's number into an offset
261 in the windows exception context vector.
263 It also contains the bit mask needed to load the register in question.
265 The contents of this table can only be computed by the units
266 that provide CPU-specific support for Windows native debugging.
267 These units should set the table by calling
268 windows_set_context_register_offsets.
270 One day we could read a reg, we could inspect the context we
271 already have loaded, if it doesn't have the bit set that we need,
272 we read that set of registers in using GetThreadContext. If the
273 context already contains what we need, we just unpack it. Then to
274 write a register, first we have to ensure that the context contains
275 the other regs of the group, and then we copy the info in and set
278 static const int *mappings;
280 /* The function to use in order to determine whether a register is
281 a segment register or not. */
282 static segment_register_p_ftype *segment_register_p;
284 /* This vector maps the target's idea of an exception (extracted
285 from the DEBUG_EVENT structure) to GDB's idea. */
287 struct xlate_exception
293 static const struct xlate_exception
296 {EXCEPTION_ACCESS_VIOLATION, GDB_SIGNAL_SEGV},
297 {STATUS_STACK_OVERFLOW, GDB_SIGNAL_SEGV},
298 {EXCEPTION_BREAKPOINT, GDB_SIGNAL_TRAP},
299 {DBG_CONTROL_C, GDB_SIGNAL_INT},
300 {EXCEPTION_SINGLE_STEP, GDB_SIGNAL_TRAP},
301 {STATUS_FLOAT_DIVIDE_BY_ZERO, GDB_SIGNAL_FPE},
302 {-1, GDB_SIGNAL_UNKNOWN}};
304 /* Set the MAPPINGS static global to OFFSETS.
305 See the description of MAPPINGS for more details. */
308 windows_set_context_register_offsets (const int *offsets)
313 /* See windows-nat.h. */
316 windows_set_segment_register_p (segment_register_p_ftype *fun)
318 segment_register_p = fun;
322 check (BOOL ok, const char *file, int line)
325 printf_filtered ("error return %s:%d was %u\n", file, line,
326 (unsigned) GetLastError ());
329 /* Find a thread record given a thread id. If GET_CONTEXT is not 0,
330 then also retrieve the context for this thread. If GET_CONTEXT is
331 negative, then don't suspend the thread. */
332 static windows_thread_info *
333 thread_rec (DWORD id, int get_context)
335 windows_thread_info *th;
337 for (th = &thread_head; (th = th->next) != NULL;)
340 if (!th->suspended && get_context)
342 if (get_context > 0 && id != current_event.dwThreadId)
344 if (SuspendThread (th->h) == (DWORD) -1)
346 DWORD err = GetLastError ();
348 /* We get Access Denied (5) when trying to suspend
349 threads that Windows started on behalf of the
350 debuggee, usually when those threads are just
352 We can get Invalid Handle (6) if the main thread
354 if (err != ERROR_INVALID_HANDLE
355 && err != ERROR_ACCESS_DENIED)
356 warning (_("SuspendThread (tid=0x%x) failed."
358 (unsigned) id, (unsigned) err);
364 else if (get_context < 0)
366 th->reload_context = 1;
374 /* Add a thread to the thread list. */
375 static windows_thread_info *
376 windows_add_thread (ptid_t ptid, HANDLE h, void *tlb)
378 windows_thread_info *th;
381 gdb_assert (ptid_get_tid (ptid) != 0);
383 id = ptid_get_tid (ptid);
385 if ((th = thread_rec (id, FALSE)))
388 th = XCNEW (windows_thread_info);
391 th->thread_local_base = (CORE_ADDR) (uintptr_t) tlb;
392 th->next = thread_head.next;
393 thread_head.next = th;
395 /* Set the debug registers for the new thread if they are used. */
396 if (debug_registers_used)
398 /* Only change the value of the debug registers. */
399 th->context.ContextFlags = CONTEXT_DEBUG_REGISTERS;
400 CHECK (GetThreadContext (th->h, &th->context));
401 th->context.Dr0 = dr[0];
402 th->context.Dr1 = dr[1];
403 th->context.Dr2 = dr[2];
404 th->context.Dr3 = dr[3];
405 th->context.Dr6 = DR6_CLEAR_VALUE;
406 th->context.Dr7 = dr[7];
407 CHECK (SetThreadContext (th->h, &th->context));
408 th->context.ContextFlags = 0;
413 /* Clear out any old thread list and reinitialize it to a
416 windows_init_thread_list (void)
418 windows_thread_info *th = &thread_head;
420 DEBUG_EVENTS (("gdb: windows_init_thread_list\n"));
422 while (th->next != NULL)
424 windows_thread_info *here = th->next;
425 th->next = here->next;
428 thread_head.next = NULL;
431 /* Delete a thread from the list of threads. */
433 windows_delete_thread (ptid_t ptid, DWORD exit_code)
435 windows_thread_info *th;
438 gdb_assert (ptid_get_tid (ptid) != 0);
440 id = ptid_get_tid (ptid);
443 printf_unfiltered ("[Deleting %s]\n", target_pid_to_str (ptid));
444 else if (print_thread_events && id != main_thread_id)
445 printf_unfiltered (_("[%s exited with code %u]\n"),
446 target_pid_to_str (ptid), (unsigned) exit_code);
447 delete_thread (ptid);
449 for (th = &thread_head;
450 th->next != NULL && th->next->id != id;
454 if (th->next != NULL)
456 windows_thread_info *here = th->next;
457 th->next = here->next;
464 do_windows_fetch_inferior_registers (struct regcache *regcache,
465 windows_thread_info *th, int r)
467 char *context_offset = ((char *) &th->context) + mappings[r];
468 struct gdbarch *gdbarch = get_regcache_arch (regcache);
469 struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
472 if (th->reload_context)
475 if (have_saved_context)
477 /* Lie about where the program actually is stopped since
478 cygwin has informed us that we should consider the signal
479 to have occurred at another location which is stored in
481 memcpy (&th->context, &saved_context,
482 __COPY_CONTEXT_SIZE);
483 have_saved_context = 0;
488 th->context.ContextFlags = CONTEXT_DEBUGGER_DR;
489 CHECK (GetThreadContext (th->h, &th->context));
490 /* Copy dr values from that thread.
491 But only if there were not modified since last stop.
493 if (!debug_registers_changed)
495 dr[0] = th->context.Dr0;
496 dr[1] = th->context.Dr1;
497 dr[2] = th->context.Dr2;
498 dr[3] = th->context.Dr3;
499 dr[6] = th->context.Dr6;
500 dr[7] = th->context.Dr7;
503 th->reload_context = 0;
506 if (r == I387_FISEG_REGNUM (tdep))
508 l = *((long *) context_offset) & 0xffff;
509 regcache_raw_supply (regcache, r, (char *) &l);
511 else if (r == I387_FOP_REGNUM (tdep))
513 l = (*((long *) context_offset) >> 16) & ((1 << 11) - 1);
514 regcache_raw_supply (regcache, r, (char *) &l);
516 else if (segment_register_p (r))
518 /* GDB treats segment registers as 32bit registers, but they are
519 in fact only 16 bits long. Make sure we do not read extra
520 bits from our source buffer. */
521 l = *((long *) context_offset) & 0xffff;
522 regcache_raw_supply (regcache, r, (char *) &l);
525 regcache_raw_supply (regcache, r, context_offset);
528 for (r = 0; r < gdbarch_num_regs (gdbarch); r++)
529 do_windows_fetch_inferior_registers (regcache, th, r);
534 windows_fetch_inferior_registers (struct target_ops *ops,
535 struct regcache *regcache, int r)
537 DWORD pid = ptid_get_tid (regcache_get_ptid (regcache));
538 windows_thread_info *th = thread_rec (pid, TRUE);
540 /* Check if TH exists. Windows sometimes uses a non-existent
541 thread id in its events. */
543 do_windows_fetch_inferior_registers (regcache, th, r);
547 do_windows_store_inferior_registers (const struct regcache *regcache,
548 windows_thread_info *th, int r)
551 regcache_raw_collect (regcache, r,
552 ((char *) &th->context) + mappings[r]);
555 for (r = 0; r < gdbarch_num_regs (get_regcache_arch (regcache)); r++)
556 do_windows_store_inferior_registers (regcache, th, r);
560 /* Store a new register value into the context of the thread tied to
563 windows_store_inferior_registers (struct target_ops *ops,
564 struct regcache *regcache, int r)
566 DWORD pid = ptid_get_tid (regcache_get_ptid (regcache));
567 windows_thread_info *th = thread_rec (pid, TRUE);
569 /* Check if TH exists. Windows sometimes uses a non-existent
570 thread id in its events. */
572 do_windows_store_inferior_registers (regcache, th, r);
575 /* Encapsulate the information required in a call to
576 symbol_file_add_args. */
577 struct safe_symbol_file_add_args
581 struct section_addr_info *addrs;
584 struct ui_file *err, *out;
588 /* Maintain a linked list of "so" information. */
589 struct lm_info_windows : public lm_info_base
591 LPVOID load_addr = 0;
594 static struct so_list solib_start, *solib_end;
596 static struct so_list *
597 windows_make_so (const char *name, LPVOID load_addr)
604 WIN32_FIND_DATA w32_fd;
605 HANDLE h = FindFirstFile(name, &w32_fd);
607 if (h == INVALID_HANDLE_VALUE)
613 if (GetCurrentDirectory (MAX_PATH + 1, cwd))
615 p = strrchr (buf, '\\');
618 SetCurrentDirectory (buf);
619 GetFullPathName (w32_fd.cFileName, MAX_PATH, buf, &p);
620 SetCurrentDirectory (cwd);
623 if (strcasecmp (buf, "ntdll.dll") == 0)
625 GetSystemDirectory (buf, sizeof (buf));
626 strcat (buf, "\\ntdll.dll");
629 cygwin_buf_t buf[__PMAX];
632 if (access (name, F_OK) != 0)
634 if (strcasecmp (name, "ntdll.dll") == 0)
637 GetSystemDirectoryW (buf, sizeof (buf) / sizeof (wchar_t));
638 wcscat (buf, L"\\ntdll.dll");
642 GetSystemDirectoryA (buf, sizeof (buf) / sizeof (wchar_t));
643 strcat (buf, "\\ntdll.dll");
648 so = XCNEW (struct so_list);
649 lm_info_windows *li = new lm_info_windows;
651 li->load_addr = load_addr;
652 strcpy (so->so_original_name, name);
654 strcpy (so->so_name, buf);
657 cygwin_conv_path (CCP_WIN_W_TO_POSIX, buf, so->so_name,
658 SO_NAME_MAX_PATH_SIZE);
661 char *rname = realpath (name, NULL);
662 if (rname && strlen (rname) < SO_NAME_MAX_PATH_SIZE)
664 strcpy (so->so_name, rname);
668 error (_("dll path too long"));
670 /* Record cygwin1.dll .text start/end. */
671 p = strchr (so->so_name, '\0') - (sizeof ("/cygwin1.dll") - 1);
672 if (p >= so->so_name && strcasecmp (p, "/cygwin1.dll") == 0)
674 asection *text = NULL;
677 gdb_bfd_ref_ptr abfd (gdb_bfd_open (so->so_name, "pei-i386", -1));
682 if (bfd_check_format (abfd.get (), bfd_object))
683 text = bfd_get_section_by_name (abfd.get (), ".text");
688 /* The symbols in a dll are offset by 0x1000, which is the
689 offset from 0 of the first byte in an image - because of the
690 file header and the section alignment. */
691 cygwin_load_start = (CORE_ADDR) (uintptr_t) ((char *)
693 cygwin_load_end = cygwin_load_start + bfd_section_size (abfd.get (),
702 get_image_name (HANDLE h, void *address, int unicode)
705 static char buf[__PMAX];
707 static char buf[(2 * __PMAX) + 1];
709 DWORD size = unicode ? sizeof (WCHAR) : sizeof (char);
715 /* Attempt to read the name of the dll that was detected.
716 This is documented to work only when actively debugging
717 a program. It will not work for attached processes. */
721 /* See if we could read the address of a string, and that the
722 address isn't null. */
723 if (!ReadProcessMemory (h, address, &address_ptr,
724 sizeof (address_ptr), &done)
725 || done != sizeof (address_ptr) || !address_ptr)
728 /* Find the length of the string. */
729 while (ReadProcessMemory (h, address_ptr + len++ * size, &b, size, &done)
730 && (b[0] != 0 || b[size - 1] != 0) && done == size)
734 ReadProcessMemory (h, address_ptr, buf, len, &done);
737 WCHAR *unicode_address = (WCHAR *) alloca (len * sizeof (WCHAR));
738 ReadProcessMemory (h, address_ptr, unicode_address, len * sizeof (WCHAR),
741 wcstombs (buf, unicode_address, __PMAX);
743 WideCharToMultiByte (CP_ACP, 0, unicode_address, len, buf, sizeof buf,
751 /* Handle a DLL load event, and return 1.
753 This function assumes that this event did not occur during inferior
754 initialization, where their event info may be incomplete (see
755 do_initial_windows_stuff and windows_add_all_dlls for more info
756 on how we handle DLL loading during that phase). */
759 handle_load_dll (void *dummy)
761 LOAD_DLL_DEBUG_INFO *event = ¤t_event.u.LoadDll;
764 /* Try getting the DLL name via the lpImageName field of the event.
765 Note that Microsoft documents this fields as strictly optional,
766 in the sense that it might be NULL. And the first DLL event in
767 particular is explicitly documented as "likely not pass[ed]"
768 (source: MSDN LOAD_DLL_DEBUG_INFO structure). */
769 dll_name = get_image_name (current_process_handle,
770 event->lpImageName, event->fUnicode);
774 solib_end->next = windows_make_so (dll_name, event->lpBaseOfDll);
775 solib_end = solib_end->next;
777 lm_info_windows *li = (lm_info_windows *) solib_end->lm_info;
779 DEBUG_EVENTS (("gdb: Loading dll \"%s\" at %s.\n", solib_end->so_name,
780 host_address_to_string (li->load_addr)));
786 windows_free_so (struct so_list *so)
788 lm_info_windows *li = (lm_info_windows *) so->lm_info;
794 /* Handle a DLL unload event.
795 Return 1 if successful, or zero otherwise.
797 This function assumes that this event did not occur during inferior
798 initialization, where their event info may be incomplete (see
799 do_initial_windows_stuff and windows_add_all_dlls for more info
800 on how we handle DLL loading during that phase). */
803 handle_unload_dll (void *dummy)
805 LPVOID lpBaseOfDll = current_event.u.UnloadDll.lpBaseOfDll;
808 for (so = &solib_start; so->next != NULL; so = so->next)
810 lm_info_windows *li_next = (lm_info_windows *) so->next->lm_info;
812 if (li_next->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);
826 /* We did not find any DLL that was previously loaded at this address,
827 so register a complaint. We do not report an error, because we have
828 observed that this may be happening under some circumstances. For
829 instance, running 32bit applications on x64 Windows causes us to receive
830 4 mysterious UNLOAD_DLL_DEBUG_EVENTs during the startup phase (these
831 events are apparently caused by the WOW layer, the interface between
832 32bit and 64bit worlds). */
833 complaint (&symfile_complaints, _("dll starting at %s not found."),
834 host_address_to_string (lpBaseOfDll));
839 /* Clear list of loaded DLLs. */
841 windows_clear_solib (void)
843 solib_start.next = NULL;
844 solib_end = &solib_start;
848 signal_event_command (char *args, int from_tty)
850 uintptr_t event_id = 0;
851 char *endargs = NULL;
854 error (_("signal-event requires an argument (integer event id)"));
856 event_id = strtoumax (args, &endargs, 10);
858 if ((errno == ERANGE) || (event_id == 0) || (event_id > UINTPTR_MAX) ||
859 ((HANDLE) event_id == INVALID_HANDLE_VALUE))
860 error (_("Failed to convert `%s' to event id"), args);
862 SetEvent ((HANDLE) event_id);
863 CloseHandle ((HANDLE) event_id);
866 /* Handle DEBUG_STRING output from child process.
867 Cygwin prepends its messages with a "cygwin:". Interpret this as
868 a Cygwin signal. Otherwise just print the string as a warning. */
870 handle_output_debug_string (struct target_waitstatus *ourstatus)
875 if (!target_read_string
876 ((CORE_ADDR) (uintptr_t) current_event.u.DebugString.lpDebugStringData,
880 else if (!startswith (s, _CYGWIN_SIGNAL_STRING))
883 if (!startswith (s, "cYg"))
886 char *p = strchr (s, '\0');
888 if (p > s && *--p == '\n')
896 /* Got a cygwin signal marker. A cygwin signal is followed by
897 the signal number itself and then optionally followed by the
898 thread id and address to saved context within the DLL. If
899 these are supplied, then the given thread is assumed to have
900 issued the signal and the context from the thread is assumed
901 to be stored at the given address in the inferior. Tell gdb
902 to treat this like a real signal. */
904 int sig = strtol (s + sizeof (_CYGWIN_SIGNAL_STRING) - 1, &p, 0);
905 gdb_signal gotasig = gdb_signal_from_host (sig);
907 ourstatus->value.sig = gotasig;
913 ourstatus->kind = TARGET_WAITKIND_STOPPED;
914 retval = strtoul (p, &p, 0);
916 retval = main_thread_id;
917 else if ((x = (LPCVOID) (uintptr_t) strtoull (p, NULL, 0))
918 && ReadProcessMemory (current_process_handle, x,
920 __COPY_CONTEXT_SIZE, &n)
921 && n == __COPY_CONTEXT_SIZE)
922 have_saved_context = 1;
933 display_selector (HANDLE thread, DWORD sel)
936 if (GetThreadSelectorEntry (thread, sel, &info))
939 printf_filtered ("0x%03x: ", (unsigned) sel);
940 if (!info.HighWord.Bits.Pres)
942 puts_filtered ("Segment not present\n");
945 base = (info.HighWord.Bits.BaseHi << 24) +
946 (info.HighWord.Bits.BaseMid << 16)
948 limit = (info.HighWord.Bits.LimitHi << 16) + info.LimitLow;
949 if (info.HighWord.Bits.Granularity)
950 limit = (limit << 12) | 0xfff;
951 printf_filtered ("base=0x%08x limit=0x%08x", base, limit);
952 if (info.HighWord.Bits.Default_Big)
953 puts_filtered(" 32-bit ");
955 puts_filtered(" 16-bit ");
956 switch ((info.HighWord.Bits.Type & 0xf) >> 1)
959 puts_filtered ("Data (Read-Only, Exp-up");
962 puts_filtered ("Data (Read/Write, Exp-up");
965 puts_filtered ("Unused segment (");
968 puts_filtered ("Data (Read/Write, Exp-down");
971 puts_filtered ("Code (Exec-Only, N.Conf");
974 puts_filtered ("Code (Exec/Read, N.Conf");
977 puts_filtered ("Code (Exec-Only, Conf");
980 puts_filtered ("Code (Exec/Read, Conf");
983 printf_filtered ("Unknown type 0x%x",info.HighWord.Bits.Type);
985 if ((info.HighWord.Bits.Type & 0x1) == 0)
986 puts_filtered(", N.Acc");
987 puts_filtered (")\n");
988 if ((info.HighWord.Bits.Type & 0x10) == 0)
989 puts_filtered("System selector ");
990 printf_filtered ("Priviledge level = %d. ", info.HighWord.Bits.Dpl);
991 if (info.HighWord.Bits.Granularity)
992 puts_filtered ("Page granular.\n");
994 puts_filtered ("Byte granular.\n");
999 DWORD err = GetLastError ();
1000 if (err == ERROR_NOT_SUPPORTED)
1001 printf_filtered ("Function not supported\n");
1003 printf_filtered ("Invalid selector 0x%x.\n", (unsigned) sel);
1009 display_selectors (char * args, int from_tty)
1011 if (!current_thread)
1013 puts_filtered ("Impossible to display selectors now.\n");
1019 puts_filtered ("Selector $cs\n");
1020 display_selector (current_thread->h,
1021 current_thread->context.SegCs);
1022 puts_filtered ("Selector $ds\n");
1023 display_selector (current_thread->h,
1024 current_thread->context.SegDs);
1025 puts_filtered ("Selector $es\n");
1026 display_selector (current_thread->h,
1027 current_thread->context.SegEs);
1028 puts_filtered ("Selector $ss\n");
1029 display_selector (current_thread->h,
1030 current_thread->context.SegSs);
1031 puts_filtered ("Selector $fs\n");
1032 display_selector (current_thread->h,
1033 current_thread->context.SegFs);
1034 puts_filtered ("Selector $gs\n");
1035 display_selector (current_thread->h,
1036 current_thread->context.SegGs);
1041 sel = parse_and_eval_long (args);
1042 printf_filtered ("Selector \"%s\"\n",args);
1043 display_selector (current_thread->h, sel);
1047 #define DEBUG_EXCEPTION_SIMPLE(x) if (debug_exceptions) \
1048 printf_unfiltered ("gdb: Target exception %s at %s\n", x, \
1049 host_address_to_string (\
1050 current_event.u.Exception.ExceptionRecord.ExceptionAddress))
1052 static handle_exception_result
1053 handle_exception (struct target_waitstatus *ourstatus)
1055 EXCEPTION_RECORD *rec = ¤t_event.u.Exception.ExceptionRecord;
1056 DWORD code = rec->ExceptionCode;
1057 handle_exception_result result = HANDLE_EXCEPTION_HANDLED;
1059 ourstatus->kind = TARGET_WAITKIND_STOPPED;
1061 /* Record the context of the current thread. */
1062 thread_rec (current_event.dwThreadId, -1);
1066 case EXCEPTION_ACCESS_VIOLATION:
1067 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ACCESS_VIOLATION");
1068 ourstatus->value.sig = GDB_SIGNAL_SEGV;
1071 /* See if the access violation happened within the cygwin DLL
1072 itself. Cygwin uses a kind of exception handling to deal
1073 with passed-in invalid addresses. gdb should not treat
1074 these as real SEGVs since they will be silently handled by
1075 cygwin. A real SEGV will (theoretically) be caught by
1076 cygwin later in the process and will be sent as a
1077 cygwin-specific-signal. So, ignore SEGVs if they show up
1078 within the text segment of the DLL itself. */
1080 CORE_ADDR addr = (CORE_ADDR) (uintptr_t) rec->ExceptionAddress;
1082 if ((!cygwin_exceptions && (addr >= cygwin_load_start
1083 && addr < cygwin_load_end))
1084 || (find_pc_partial_function (addr, &fn, NULL, NULL)
1085 && startswith (fn, "KERNEL32!IsBad")))
1086 return HANDLE_EXCEPTION_UNHANDLED;
1090 case STATUS_STACK_OVERFLOW:
1091 DEBUG_EXCEPTION_SIMPLE ("STATUS_STACK_OVERFLOW");
1092 ourstatus->value.sig = GDB_SIGNAL_SEGV;
1094 case STATUS_FLOAT_DENORMAL_OPERAND:
1095 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DENORMAL_OPERAND");
1096 ourstatus->value.sig = GDB_SIGNAL_FPE;
1098 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
1099 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ARRAY_BOUNDS_EXCEEDED");
1100 ourstatus->value.sig = GDB_SIGNAL_FPE;
1102 case STATUS_FLOAT_INEXACT_RESULT:
1103 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INEXACT_RESULT");
1104 ourstatus->value.sig = GDB_SIGNAL_FPE;
1106 case STATUS_FLOAT_INVALID_OPERATION:
1107 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INVALID_OPERATION");
1108 ourstatus->value.sig = GDB_SIGNAL_FPE;
1110 case STATUS_FLOAT_OVERFLOW:
1111 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_OVERFLOW");
1112 ourstatus->value.sig = GDB_SIGNAL_FPE;
1114 case STATUS_FLOAT_STACK_CHECK:
1115 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_STACK_CHECK");
1116 ourstatus->value.sig = GDB_SIGNAL_FPE;
1118 case STATUS_FLOAT_UNDERFLOW:
1119 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_UNDERFLOW");
1120 ourstatus->value.sig = GDB_SIGNAL_FPE;
1122 case STATUS_FLOAT_DIVIDE_BY_ZERO:
1123 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DIVIDE_BY_ZERO");
1124 ourstatus->value.sig = GDB_SIGNAL_FPE;
1126 case STATUS_INTEGER_DIVIDE_BY_ZERO:
1127 DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_DIVIDE_BY_ZERO");
1128 ourstatus->value.sig = GDB_SIGNAL_FPE;
1130 case STATUS_INTEGER_OVERFLOW:
1131 DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_OVERFLOW");
1132 ourstatus->value.sig = GDB_SIGNAL_FPE;
1134 case EXCEPTION_BREAKPOINT:
1135 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_BREAKPOINT");
1136 ourstatus->value.sig = GDB_SIGNAL_TRAP;
1139 DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_C");
1140 ourstatus->value.sig = GDB_SIGNAL_INT;
1142 case DBG_CONTROL_BREAK:
1143 DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_BREAK");
1144 ourstatus->value.sig = GDB_SIGNAL_INT;
1146 case EXCEPTION_SINGLE_STEP:
1147 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_SINGLE_STEP");
1148 ourstatus->value.sig = GDB_SIGNAL_TRAP;
1150 case EXCEPTION_ILLEGAL_INSTRUCTION:
1151 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ILLEGAL_INSTRUCTION");
1152 ourstatus->value.sig = GDB_SIGNAL_ILL;
1154 case EXCEPTION_PRIV_INSTRUCTION:
1155 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_PRIV_INSTRUCTION");
1156 ourstatus->value.sig = GDB_SIGNAL_ILL;
1158 case EXCEPTION_NONCONTINUABLE_EXCEPTION:
1159 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_NONCONTINUABLE_EXCEPTION");
1160 ourstatus->value.sig = GDB_SIGNAL_ILL;
1162 case MS_VC_EXCEPTION:
1163 if (rec->NumberParameters >= 3
1164 && (rec->ExceptionInformation[0] & 0xffffffff) == 0x1000)
1166 DWORD named_thread_id;
1167 windows_thread_info *named_thread;
1168 CORE_ADDR thread_name_target;
1170 DEBUG_EXCEPTION_SIMPLE ("MS_VC_EXCEPTION");
1172 thread_name_target = rec->ExceptionInformation[1];
1173 named_thread_id = (DWORD) (0xffffffff & rec->ExceptionInformation[2]);
1175 if (named_thread_id == (DWORD) -1)
1176 named_thread_id = current_event.dwThreadId;
1178 named_thread = thread_rec (named_thread_id, 0);
1179 if (named_thread != NULL)
1181 int thread_name_len;
1184 thread_name_len = target_read_string (thread_name_target,
1185 &thread_name, 1025, NULL);
1186 if (thread_name_len > 0)
1188 thread_name[thread_name_len - 1] = '\0';
1189 xfree (named_thread->name);
1190 named_thread->name = thread_name;
1193 xfree (thread_name);
1195 ourstatus->value.sig = GDB_SIGNAL_TRAP;
1196 result = HANDLE_EXCEPTION_IGNORED;
1199 /* treat improperly formed exception as unknown, fallthrough */
1201 /* Treat unhandled first chance exceptions specially. */
1202 if (current_event.u.Exception.dwFirstChance)
1203 return HANDLE_EXCEPTION_UNHANDLED;
1204 printf_unfiltered ("gdb: unknown target exception 0x%08x at %s\n",
1205 (unsigned) current_event.u.Exception.ExceptionRecord.ExceptionCode,
1206 host_address_to_string (
1207 current_event.u.Exception.ExceptionRecord.ExceptionAddress));
1208 ourstatus->value.sig = GDB_SIGNAL_UNKNOWN;
1212 last_sig = ourstatus->value.sig;
1216 /* Resume thread specified by ID, or all artificially suspended
1217 threads, if we are continuing execution. KILLED non-zero means we
1218 have killed the inferior, so we should ignore weird errors due to
1219 threads shutting down. */
1221 windows_continue (DWORD continue_status, int id, int killed)
1224 windows_thread_info *th;
1227 DEBUG_EVENTS (("ContinueDebugEvent (cpid=%d, ctid=0x%x, %s);\n",
1228 (unsigned) current_event.dwProcessId,
1229 (unsigned) current_event.dwThreadId,
1230 continue_status == DBG_CONTINUE ?
1231 "DBG_CONTINUE" : "DBG_EXCEPTION_NOT_HANDLED"));
1233 for (th = &thread_head; (th = th->next) != NULL;)
1234 if ((id == -1 || id == (int) th->id)
1237 if (debug_registers_changed)
1239 th->context.ContextFlags |= CONTEXT_DEBUG_REGISTERS;
1240 th->context.Dr0 = dr[0];
1241 th->context.Dr1 = dr[1];
1242 th->context.Dr2 = dr[2];
1243 th->context.Dr3 = dr[3];
1244 th->context.Dr6 = DR6_CLEAR_VALUE;
1245 th->context.Dr7 = dr[7];
1247 if (th->context.ContextFlags)
1251 if (GetExitCodeThread (th->h, &ec)
1252 && ec == STILL_ACTIVE)
1254 BOOL status = SetThreadContext (th->h, &th->context);
1259 th->context.ContextFlags = 0;
1261 if (th->suspended > 0)
1262 (void) ResumeThread (th->h);
1266 res = ContinueDebugEvent (current_event.dwProcessId,
1267 current_event.dwThreadId,
1271 error (_("Failed to resume program execution"
1272 " (ContinueDebugEvent failed, error %u)"),
1273 (unsigned int) GetLastError ());
1275 debug_registers_changed = 0;
1279 /* Called in pathological case where Windows fails to send a
1280 CREATE_PROCESS_DEBUG_EVENT after an attach. */
1282 fake_create_process (void)
1284 current_process_handle = OpenProcess (PROCESS_ALL_ACCESS, FALSE,
1285 current_event.dwProcessId);
1286 if (current_process_handle != NULL)
1287 open_process_used = 1;
1290 error (_("OpenProcess call failed, GetLastError = %u"),
1291 (unsigned) GetLastError ());
1292 /* We can not debug anything in that case. */
1294 main_thread_id = current_event.dwThreadId;
1295 current_thread = windows_add_thread (
1296 ptid_build (current_event.dwProcessId, 0,
1297 current_event.dwThreadId),
1298 current_event.u.CreateThread.hThread,
1299 current_event.u.CreateThread.lpThreadLocalBase);
1300 return main_thread_id;
1304 windows_resume (struct target_ops *ops,
1305 ptid_t ptid, int step, enum gdb_signal sig)
1307 windows_thread_info *th;
1308 DWORD continue_status = DBG_CONTINUE;
1310 /* A specific PTID means `step only this thread id'. */
1311 int resume_all = ptid_equal (ptid, minus_one_ptid);
1313 /* If we're continuing all threads, it's the current inferior that
1314 should be handled specially. */
1316 ptid = inferior_ptid;
1318 if (sig != GDB_SIGNAL_0)
1320 if (current_event.dwDebugEventCode != EXCEPTION_DEBUG_EVENT)
1322 DEBUG_EXCEPT(("Cannot continue with signal %d here.\n",sig));
1324 else if (sig == last_sig)
1325 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1328 /* This code does not seem to work, because
1329 the kernel does probably not consider changes in the ExceptionRecord
1330 structure when passing the exception to the inferior.
1331 Note that this seems possible in the exception handler itself. */
1334 for (i = 0; xlate[i].them != -1; i++)
1335 if (xlate[i].us == sig)
1337 current_event.u.Exception.ExceptionRecord.ExceptionCode
1339 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1342 if (continue_status == DBG_CONTINUE)
1344 DEBUG_EXCEPT(("Cannot continue with signal %d.\n",sig));
1348 DEBUG_EXCEPT(("Can only continue with received signal %d.\n",
1352 last_sig = GDB_SIGNAL_0;
1354 DEBUG_EXEC (("gdb: windows_resume (pid=%d, tid=%ld, step=%d, sig=%d);\n",
1355 ptid_get_pid (ptid), ptid_get_tid (ptid), step, sig));
1357 /* Get context for currently selected thread. */
1358 th = thread_rec (ptid_get_tid (inferior_ptid), FALSE);
1363 /* Single step by setting t bit. */
1364 struct regcache *regcache = get_current_regcache ();
1365 struct gdbarch *gdbarch = get_regcache_arch (regcache);
1366 windows_fetch_inferior_registers (ops, regcache,
1367 gdbarch_ps_regnum (gdbarch));
1368 th->context.EFlags |= FLAG_TRACE_BIT;
1371 if (th->context.ContextFlags)
1373 if (debug_registers_changed)
1375 th->context.Dr0 = dr[0];
1376 th->context.Dr1 = dr[1];
1377 th->context.Dr2 = dr[2];
1378 th->context.Dr3 = dr[3];
1379 th->context.Dr6 = DR6_CLEAR_VALUE;
1380 th->context.Dr7 = dr[7];
1382 CHECK (SetThreadContext (th->h, &th->context));
1383 th->context.ContextFlags = 0;
1387 /* Allow continuing with the same signal that interrupted us.
1388 Otherwise complain. */
1391 windows_continue (continue_status, -1, 0);
1393 windows_continue (continue_status, ptid_get_tid (ptid), 0);
1396 /* Ctrl-C handler used when the inferior is not run in the same console. The
1397 handler is in charge of interrupting the inferior using DebugBreakProcess.
1398 Note that this function is not available prior to Windows XP. In this case
1399 we emit a warning. */
1401 ctrl_c_handler (DWORD event_type)
1403 const int attach_flag = current_inferior ()->attach_flag;
1405 /* Only handle Ctrl-C and Ctrl-Break events. Ignore others. */
1406 if (event_type != CTRL_C_EVENT && event_type != CTRL_BREAK_EVENT)
1409 /* If the inferior and the debugger share the same console, do nothing as
1410 the inferior has also received the Ctrl-C event. */
1411 if (!new_console && !attach_flag)
1414 if (!DebugBreakProcess (current_process_handle))
1415 warning (_("Could not interrupt program. "
1416 "Press Ctrl-c in the program console."));
1418 /* Return true to tell that Ctrl-C has been handled. */
1422 /* Get the next event from the child. Returns a non-zero thread id if the event
1423 requires handling by WFI (or whatever). */
1425 get_windows_debug_event (struct target_ops *ops,
1426 int pid, struct target_waitstatus *ourstatus)
1429 DWORD continue_status, event_code;
1430 windows_thread_info *th;
1431 static windows_thread_info dummy_thread_info;
1432 DWORD thread_id = 0;
1434 last_sig = GDB_SIGNAL_0;
1436 if (!(debug_event = WaitForDebugEvent (¤t_event, 1000)))
1440 continue_status = DBG_CONTINUE;
1442 event_code = current_event.dwDebugEventCode;
1443 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
1445 have_saved_context = 0;
1449 case CREATE_THREAD_DEBUG_EVENT:
1450 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1451 (unsigned) current_event.dwProcessId,
1452 (unsigned) current_event.dwThreadId,
1453 "CREATE_THREAD_DEBUG_EVENT"));
1454 if (saw_create != 1)
1456 struct inferior *inf;
1457 inf = find_inferior_pid (current_event.dwProcessId);
1458 if (!saw_create && inf->attach_flag)
1460 /* Kludge around a Windows bug where first event is a create
1461 thread event. Caused when attached process does not have
1463 thread_id = fake_create_process ();
1469 /* Record the existence of this thread. */
1470 thread_id = current_event.dwThreadId;
1471 th = windows_add_thread (ptid_build (current_event.dwProcessId, 0,
1472 current_event.dwThreadId),
1473 current_event.u.CreateThread.hThread,
1474 current_event.u.CreateThread.lpThreadLocalBase);
1478 case EXIT_THREAD_DEBUG_EVENT:
1479 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1480 (unsigned) current_event.dwProcessId,
1481 (unsigned) current_event.dwThreadId,
1482 "EXIT_THREAD_DEBUG_EVENT"));
1484 if (current_event.dwThreadId != main_thread_id)
1486 windows_delete_thread (ptid_build (current_event.dwProcessId, 0,
1487 current_event.dwThreadId),
1488 current_event.u.ExitThread.dwExitCode);
1489 th = &dummy_thread_info;
1493 case CREATE_PROCESS_DEBUG_EVENT:
1494 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1495 (unsigned) current_event.dwProcessId,
1496 (unsigned) current_event.dwThreadId,
1497 "CREATE_PROCESS_DEBUG_EVENT"));
1498 CloseHandle (current_event.u.CreateProcessInfo.hFile);
1499 if (++saw_create != 1)
1502 current_process_handle = current_event.u.CreateProcessInfo.hProcess;
1504 windows_delete_thread (ptid_build (current_event.dwProcessId, 0,
1507 main_thread_id = current_event.dwThreadId;
1508 /* Add the main thread. */
1509 th = windows_add_thread (ptid_build (current_event.dwProcessId, 0,
1510 current_event.dwThreadId),
1511 current_event.u.CreateProcessInfo.hThread,
1512 current_event.u.CreateProcessInfo.lpThreadLocalBase);
1513 thread_id = current_event.dwThreadId;
1516 case EXIT_PROCESS_DEBUG_EVENT:
1517 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1518 (unsigned) current_event.dwProcessId,
1519 (unsigned) current_event.dwThreadId,
1520 "EXIT_PROCESS_DEBUG_EVENT"));
1521 if (!windows_initialization_done)
1523 target_terminal::ours ();
1524 target_mourn_inferior (inferior_ptid);
1525 error (_("During startup program exited with code 0x%x."),
1526 (unsigned int) current_event.u.ExitProcess.dwExitCode);
1528 else if (saw_create == 1)
1530 ourstatus->kind = TARGET_WAITKIND_EXITED;
1531 ourstatus->value.integer = current_event.u.ExitProcess.dwExitCode;
1532 thread_id = main_thread_id;
1536 case LOAD_DLL_DEBUG_EVENT:
1537 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1538 (unsigned) current_event.dwProcessId,
1539 (unsigned) current_event.dwThreadId,
1540 "LOAD_DLL_DEBUG_EVENT"));
1541 CloseHandle (current_event.u.LoadDll.hFile);
1542 if (saw_create != 1 || ! windows_initialization_done)
1544 catch_errors (handle_load_dll, NULL, (char *) "", RETURN_MASK_ALL);
1545 ourstatus->kind = TARGET_WAITKIND_LOADED;
1546 ourstatus->value.integer = 0;
1547 thread_id = main_thread_id;
1550 case UNLOAD_DLL_DEBUG_EVENT:
1551 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1552 (unsigned) current_event.dwProcessId,
1553 (unsigned) current_event.dwThreadId,
1554 "UNLOAD_DLL_DEBUG_EVENT"));
1555 if (saw_create != 1 || ! windows_initialization_done)
1557 catch_errors (handle_unload_dll, NULL, (char *) "", RETURN_MASK_ALL);
1558 ourstatus->kind = TARGET_WAITKIND_LOADED;
1559 ourstatus->value.integer = 0;
1560 thread_id = main_thread_id;
1563 case EXCEPTION_DEBUG_EVENT:
1564 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1565 (unsigned) current_event.dwProcessId,
1566 (unsigned) current_event.dwThreadId,
1567 "EXCEPTION_DEBUG_EVENT"));
1568 if (saw_create != 1)
1570 switch (handle_exception (ourstatus))
1572 case HANDLE_EXCEPTION_UNHANDLED:
1574 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1576 case HANDLE_EXCEPTION_HANDLED:
1577 thread_id = current_event.dwThreadId;
1579 case HANDLE_EXCEPTION_IGNORED:
1580 continue_status = DBG_CONTINUE;
1585 case OUTPUT_DEBUG_STRING_EVENT: /* Message from the kernel. */
1586 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1587 (unsigned) current_event.dwProcessId,
1588 (unsigned) current_event.dwThreadId,
1589 "OUTPUT_DEBUG_STRING_EVENT"));
1590 if (saw_create != 1)
1592 thread_id = handle_output_debug_string (ourstatus);
1596 if (saw_create != 1)
1598 printf_unfiltered ("gdb: kernel event for pid=%u tid=0x%x\n",
1599 (unsigned) current_event.dwProcessId,
1600 (unsigned) current_event.dwThreadId);
1601 printf_unfiltered (" unknown event code %u\n",
1602 (unsigned) current_event.dwDebugEventCode);
1606 if (!thread_id || saw_create != 1)
1608 CHECK (windows_continue (continue_status, -1, 0));
1612 inferior_ptid = ptid_build (current_event.dwProcessId, 0,
1614 current_thread = th;
1615 if (!current_thread)
1616 current_thread = thread_rec (thread_id, TRUE);
1623 /* Wait for interesting events to occur in the target process. */
1625 windows_wait (struct target_ops *ops,
1626 ptid_t ptid, struct target_waitstatus *ourstatus, int options)
1630 target_terminal::ours ();
1632 /* We loop when we get a non-standard exception rather than return
1633 with a SPURIOUS because resume can try and step or modify things,
1634 which needs a current_thread->h. But some of these exceptions mark
1635 the birth or death of threads, which mean that the current thread
1636 isn't necessarily what you think it is. */
1642 /* If the user presses Ctrl-c while the debugger is waiting
1643 for an event, he expects the debugger to interrupt his program
1644 and to get the prompt back. There are two possible situations:
1646 - The debugger and the program do not share the console, in
1647 which case the Ctrl-c event only reached the debugger.
1648 In that case, the ctrl_c handler will take care of interrupting
1649 the inferior. Note that this case is working starting with
1650 Windows XP. For Windows 2000, Ctrl-C should be pressed in the
1653 - The debugger and the program share the same console, in which
1654 case both debugger and inferior will receive the Ctrl-c event.
1655 In that case the ctrl_c handler will ignore the event, as the
1656 Ctrl-c event generated inside the inferior will trigger the
1657 expected debug event.
1659 FIXME: brobecker/2008-05-20: If the inferior receives the
1660 signal first and the delay until GDB receives that signal
1661 is sufficiently long, GDB can sometimes receive the SIGINT
1662 after we have unblocked the CTRL+C handler. This would
1663 lead to the debugger stopping prematurely while handling
1664 the new-thread event that comes with the handling of the SIGINT
1665 inside the inferior, and then stop again immediately when
1666 the user tries to resume the execution in the inferior.
1667 This is a classic race that we should try to fix one day. */
1668 SetConsoleCtrlHandler (&ctrl_c_handler, TRUE);
1669 retval = get_windows_debug_event (ops, pid, ourstatus);
1670 SetConsoleCtrlHandler (&ctrl_c_handler, FALSE);
1673 return ptid_build (current_event.dwProcessId, 0, retval);
1678 if (deprecated_ui_loop_hook != NULL)
1679 detach = deprecated_ui_loop_hook (0);
1682 windows_kill_inferior (ops);
1687 /* Iterate over all DLLs currently mapped by our inferior, and
1688 add them to our list of solibs. */
1691 windows_add_all_dlls (void)
1694 HMODULE dummy_hmodule;
1699 if (EnumProcessModules (current_process_handle, &dummy_hmodule,
1700 sizeof (HMODULE), &cb_needed) == 0)
1706 hmodules = (HMODULE *) alloca (cb_needed);
1707 if (EnumProcessModules (current_process_handle, hmodules,
1708 cb_needed, &cb_needed) == 0)
1711 for (i = 1; i < (int) (cb_needed / sizeof (HMODULE)); i++)
1715 wchar_t dll_name[__PMAX];
1718 char dll_name[__PMAX];
1721 if (GetModuleInformation (current_process_handle, hmodules[i],
1722 &mi, sizeof (mi)) == 0)
1724 if (GetModuleFileNameEx (current_process_handle, hmodules[i],
1725 dll_name, sizeof (dll_name)) == 0)
1728 wcstombs (name, dll_name, __PMAX);
1733 solib_end->next = windows_make_so (name, mi.lpBaseOfDll);
1734 solib_end = solib_end->next;
1739 do_initial_windows_stuff (struct target_ops *ops, DWORD pid, int attaching)
1742 struct inferior *inf;
1743 struct thread_info *tp;
1745 last_sig = GDB_SIGNAL_0;
1747 exception_count = 0;
1748 open_process_used = 0;
1749 debug_registers_changed = 0;
1750 debug_registers_used = 0;
1751 for (i = 0; i < sizeof (dr) / sizeof (dr[0]); i++)
1754 cygwin_load_start = cygwin_load_end = 0;
1756 current_event.dwProcessId = pid;
1757 memset (¤t_event, 0, sizeof (current_event));
1758 if (!target_is_pushed (ops))
1760 disable_breakpoints_in_shlibs ();
1761 windows_clear_solib ();
1762 clear_proceed_status (0);
1763 init_wait_for_inferior ();
1765 inf = current_inferior ();
1766 inferior_appeared (inf, pid);
1767 inf->attach_flag = attaching;
1769 /* Make the new process the current inferior, so terminal handling
1770 can rely on it. When attaching, we don't know about any thread
1771 id here, but that's OK --- nothing should be referencing the
1772 current thread until we report an event out of windows_wait. */
1773 inferior_ptid = pid_to_ptid (pid);
1775 target_terminal::init ();
1776 target_terminal::inferior ();
1778 windows_initialization_done = 0;
1782 struct target_waitstatus status;
1784 windows_wait (ops, minus_one_ptid, &status, 0);
1786 /* Note windows_wait returns TARGET_WAITKIND_SPURIOUS for thread
1788 if (status.kind != TARGET_WAITKIND_LOADED
1789 && status.kind != TARGET_WAITKIND_SPURIOUS)
1792 windows_resume (ops, minus_one_ptid, 0, GDB_SIGNAL_0);
1795 /* Now that the inferior has been started and all DLLs have been mapped,
1796 we can iterate over all DLLs and load them in.
1798 We avoid doing it any earlier because, on certain versions of Windows,
1799 LOAD_DLL_DEBUG_EVENTs are sometimes not complete. In particular,
1800 we have seen on Windows 8.1 that the ntdll.dll load event does not
1801 include the DLL name, preventing us from creating an associated SO.
1802 A possible explanation is that ntdll.dll might be mapped before
1803 the SO info gets created by the Windows system -- ntdll.dll is
1804 the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs
1805 do not seem to suffer from that problem.
1807 Rather than try to work around this sort of issue, it is much
1808 simpler to just ignore DLL load/unload events during the startup
1809 phase, and then process them all in one batch now. */
1810 windows_add_all_dlls ();
1812 windows_initialization_done = 1;
1816 /* Try to set or remove a user privilege to the current process. Return -1
1817 if that fails, the previous setting of that privilege otherwise.
1819 This code is copied from the Cygwin source code and rearranged to allow
1820 dynamically loading of the needed symbols from advapi32 which is only
1821 available on NT/2K/XP. */
1823 set_process_privilege (const char *privilege, BOOL enable)
1825 HANDLE token_hdl = NULL;
1827 TOKEN_PRIVILEGES new_priv, orig_priv;
1831 if (!OpenProcessToken (GetCurrentProcess (),
1832 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
1836 if (!LookupPrivilegeValueA (NULL, privilege, &restore_priv))
1839 new_priv.PrivilegeCount = 1;
1840 new_priv.Privileges[0].Luid = restore_priv;
1841 new_priv.Privileges[0].Attributes = enable ? SE_PRIVILEGE_ENABLED : 0;
1843 if (!AdjustTokenPrivileges (token_hdl, FALSE, &new_priv,
1844 sizeof orig_priv, &orig_priv, &size))
1847 /* Disabled, otherwise every `attach' in an unprivileged user session
1848 would raise the "Failed to get SE_DEBUG_NAME privilege" warning in
1849 windows_attach(). */
1850 /* AdjustTokenPrivileges returns TRUE even if the privilege could not
1851 be enabled. GetLastError () returns an correct error code, though. */
1852 if (enable && GetLastError () == ERROR_NOT_ALL_ASSIGNED)
1856 ret = orig_priv.Privileges[0].Attributes == SE_PRIVILEGE_ENABLED ? 1 : 0;
1860 CloseHandle (token_hdl);
1865 /* Attach to process PID, then initialize for debugging it. */
1867 windows_attach (struct target_ops *ops, const char *args, int from_tty)
1872 pid = parse_pid_to_attach (args);
1874 if (set_process_privilege (SE_DEBUG_NAME, TRUE) < 0)
1876 printf_unfiltered ("Warning: Failed to get SE_DEBUG_NAME privilege\n");
1877 printf_unfiltered ("This can cause attach to "
1878 "fail on Windows NT/2K/XP\n");
1881 windows_init_thread_list ();
1882 ok = DebugActiveProcess (pid);
1888 /* Try fall back to Cygwin pid. */
1889 pid = cygwin_internal (CW_CYGWIN_PID_TO_WINPID, pid);
1892 ok = DebugActiveProcess (pid);
1897 error (_("Can't attach to process."));
1899 DebugSetProcessKillOnExit (FALSE);
1903 char *exec_file = (char *) get_exec_file (0);
1906 printf_unfiltered ("Attaching to program `%s', %s\n", exec_file,
1907 target_pid_to_str (pid_to_ptid (pid)));
1909 printf_unfiltered ("Attaching to %s\n",
1910 target_pid_to_str (pid_to_ptid (pid)));
1912 gdb_flush (gdb_stdout);
1915 do_initial_windows_stuff (ops, pid, 1);
1916 target_terminal::ours ();
1920 windows_detach (struct target_ops *ops, const char *args, int from_tty)
1924 ptid_t ptid = minus_one_ptid;
1925 windows_resume (ops, ptid, 0, GDB_SIGNAL_0);
1927 if (!DebugActiveProcessStop (current_event.dwProcessId))
1929 error (_("Can't detach process %u (error %u)"),
1930 (unsigned) current_event.dwProcessId, (unsigned) GetLastError ());
1933 DebugSetProcessKillOnExit (FALSE);
1935 if (detached && from_tty)
1937 const char *exec_file = get_exec_file (0);
1940 printf_unfiltered ("Detaching from program: %s, Pid %u\n", exec_file,
1941 (unsigned) current_event.dwProcessId);
1942 gdb_flush (gdb_stdout);
1945 x86_cleanup_dregs ();
1946 inferior_ptid = null_ptid;
1947 detach_inferior (current_event.dwProcessId);
1949 inf_child_maybe_unpush_target (ops);
1952 /* Try to determine the executable filename.
1954 EXE_NAME_RET is a pointer to a buffer whose size is EXE_NAME_MAX_LEN.
1956 Upon success, the filename is stored inside EXE_NAME_RET, and
1957 this function returns nonzero.
1959 Otherwise, this function returns zero and the contents of
1960 EXE_NAME_RET is undefined. */
1963 windows_get_exec_module_filename (char *exe_name_ret, size_t exe_name_max_len)
1970 if (!EnumProcessModules (current_process_handle, &dh_buf,
1971 sizeof (HMODULE), &cbNeeded) || !cbNeeded)
1974 /* We know the executable is always first in the list of modules,
1975 which we just fetched. So no need to fetch more. */
1979 /* Cygwin prefers that the path be in /x/y/z format, so extract
1980 the filename into a temporary buffer first, and then convert it
1981 to POSIX format into the destination buffer. */
1982 cygwin_buf_t *pathbuf = (cygwin_buf_t *) alloca (exe_name_max_len * sizeof (cygwin_buf_t));
1984 len = GetModuleFileNameEx (current_process_handle,
1985 dh_buf, pathbuf, exe_name_max_len);
1987 error (_("Error getting executable filename: %u."),
1988 (unsigned) GetLastError ());
1989 if (cygwin_conv_path (CCP_WIN_W_TO_POSIX, pathbuf, exe_name_ret,
1990 exe_name_max_len) < 0)
1991 error (_("Error converting executable filename to POSIX: %d."), errno);
1994 len = GetModuleFileNameEx (current_process_handle,
1995 dh_buf, exe_name_ret, exe_name_max_len);
1997 error (_("Error getting executable filename: %u."),
1998 (unsigned) GetLastError ());
2001 return 1; /* success */
2004 /* The pid_to_exec_file target_ops method for this platform. */
2007 windows_pid_to_exec_file (struct target_ops *self, int pid)
2009 static char path[__PMAX];
2011 /* Try to find exe name as symlink target of /proc/<pid>/exe. */
2013 char procexe[sizeof ("/proc/4294967295/exe")];
2015 xsnprintf (procexe, sizeof (procexe), "/proc/%u/exe", pid);
2016 nchars = readlink (procexe, path, sizeof(path));
2017 if (nchars > 0 && nchars < sizeof (path))
2019 path[nchars] = '\0'; /* Got it */
2024 /* If we get here then either Cygwin is hosed, this isn't a Cygwin version
2025 of gdb, or we're trying to debug a non-Cygwin windows executable. */
2026 if (!windows_get_exec_module_filename (path, sizeof (path)))
2032 /* Print status information about what we're accessing. */
2035 windows_files_info (struct target_ops *ignore)
2037 struct inferior *inf = current_inferior ();
2039 printf_unfiltered ("\tUsing the running image of %s %s.\n",
2040 inf->attach_flag ? "attached" : "child",
2041 target_pid_to_str (inferior_ptid));
2044 /* Modify CreateProcess parameters for use of a new separate console.
2046 *FLAGS: DWORD parameter for general process creation flags.
2047 *SI: STARTUPINFO structure, for which the console window size and
2048 console buffer size is filled in if GDB is running in a console.
2049 to create the new console.
2050 The size of the used font is not available on all versions of
2051 Windows OS. Furthermore, the current font might not be the default
2052 font, but this is still better than before.
2053 If the windows and buffer sizes are computed,
2054 SI->DWFLAGS is changed so that this information is used
2055 by CreateProcess function. */
2058 windows_set_console_info (STARTUPINFO *si, DWORD *flags)
2060 HANDLE hconsole = CreateFile ("CONOUT$", GENERIC_READ | GENERIC_WRITE,
2061 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
2063 if (hconsole != INVALID_HANDLE_VALUE)
2065 CONSOLE_SCREEN_BUFFER_INFO sbinfo;
2067 CONSOLE_FONT_INFO cfi;
2069 GetCurrentConsoleFont (hconsole, FALSE, &cfi);
2070 font_size = GetConsoleFontSize (hconsole, cfi.nFont);
2071 GetConsoleScreenBufferInfo(hconsole, &sbinfo);
2072 si->dwXSize = sbinfo.srWindow.Right - sbinfo.srWindow.Left + 1;
2073 si->dwYSize = sbinfo.srWindow.Bottom - sbinfo.srWindow.Top + 1;
2075 si->dwXSize *= font_size.X;
2079 si->dwYSize *= font_size.Y;
2082 si->dwXCountChars = sbinfo.dwSize.X;
2083 si->dwYCountChars = sbinfo.dwSize.Y;
2084 si->dwFlags |= STARTF_USESIZE | STARTF_USECOUNTCHARS;
2086 *flags |= CREATE_NEW_CONSOLE;
2090 /* Function called by qsort to sort environment strings. */
2093 envvar_cmp (const void *a, const void *b)
2095 const char **p = (const char **) a;
2096 const char **q = (const char **) b;
2097 return strcasecmp (*p, *q);
2103 clear_win32_environment (char **env)
2107 wchar_t *copy = NULL, *equalpos;
2109 for (i = 0; env[i] && *env[i]; i++)
2111 len = mbstowcs (NULL, env[i], 0) + 1;
2112 copy = (wchar_t *) xrealloc (copy, len * sizeof (wchar_t));
2113 mbstowcs (copy, env[i], len);
2114 equalpos = wcschr (copy, L'=');
2117 SetEnvironmentVariableW (copy, NULL);
2125 /* Redirection of inferior I/O streams for native MS-Windows programs.
2126 Unlike on Unix, where this is handled by invoking the inferior via
2127 the shell, on MS-Windows we need to emulate the cmd.exe shell.
2129 The official documentation of the cmd.exe redirection features is here:
2131 http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx
2133 (That page talks about Windows XP, but there's no newer
2134 documentation, so we assume later versions of cmd.exe didn't change
2137 Caveat: the documentation on that page seems to include a few lies.
2138 For example, it describes strange constructs 1<&2 and 2<&1, which
2139 seem to work only when 1>&2 resp. 2>&1 would make sense, and so I
2140 think the cmd.exe parser of the redirection symbols simply doesn't
2141 care about the < vs > distinction in these cases. Therefore, the
2142 supported features are explicitly documented below.
2144 The emulation below aims at supporting all the valid use cases
2145 supported by cmd.exe, which include:
2147 < FILE redirect standard input from FILE
2148 0< FILE redirect standard input from FILE
2149 <&N redirect standard input from file descriptor N
2150 0<&N redirect standard input from file descriptor N
2151 > FILE redirect standard output to FILE
2152 >> FILE append standard output to FILE
2153 1>> FILE append standard output to FILE
2154 >&N redirect standard output to file descriptor N
2155 1>&N redirect standard output to file descriptor N
2156 >>&N append standard output to file descriptor N
2157 1>>&N append standard output to file descriptor N
2158 2> FILE redirect standard error to FILE
2159 2>> FILE append standard error to FILE
2160 2>&N redirect standard error to file descriptor N
2161 2>>&N append standard error to file descriptor N
2163 Note that using N > 2 in the above construct is supported, but
2164 requires that the corresponding file descriptor be open by some
2165 means elsewhere or outside GDB. Also note that using ">&0" or
2166 "<&2" will generally fail, because the file descriptor redirected
2167 from is normally open in an incompatible mode (e.g., FD 0 is open
2168 for reading only). IOW, use of such tricks is not recommended;
2169 you are on your own.
2171 We do NOT support redirection of file descriptors above 2, as in
2172 "3>SOME-FILE", because MinGW compiled programs don't (supporting
2173 that needs special handling in the startup code that MinGW
2174 doesn't have). Pipes are also not supported.
2176 As for invalid use cases, where the redirection contains some
2177 error, the emulation below will detect that and produce some
2178 error and/or failure. But the behavior in those cases is not
2179 bug-for-bug compatible with what cmd.exe does in those cases.
2180 That's because what cmd.exe does then is not well defined, and
2181 seems to be a side effect of the cmd.exe parsing of the command
2182 line more than anything else. For example, try redirecting to an
2183 invalid file name, as in "> foo:bar".
2185 There are also minor syntactic deviations from what cmd.exe does
2186 in some corner cases. For example, it doesn't support the likes
2187 of "> &foo" to mean redirect to file named literally "&foo"; we
2188 do support that here, because that, too, sounds like some issue
2189 with the cmd.exe parser. Another nicety is that we support
2190 redirection targets that use file names with forward slashes,
2191 something cmd.exe doesn't -- this comes in handy since GDB
2192 file-name completion can be used when typing the command line for
2195 /* Support routines for redirecting standard handles of the inferior. */
2197 /* Parse a single redirection spec, open/duplicate the specified
2198 file/fd, and assign the appropriate value to one of the 3 standard
2199 file descriptors. */
2201 redir_open (const char *redir_string, int *inp, int *out, int *err)
2203 int *fd, ref_fd = -2;
2205 const char *fname = redir_string + 1;
2206 int rc = *redir_string;
2221 fd = (rc == '2') ? err : out;
2222 mode = O_WRONLY | O_CREAT;
2235 if (*fname == '&' && '0' <= fname[1] && fname[1] <= '9')
2237 /* A reference to a file descriptor. */
2239 ref_fd = (int) strtol (fname + 1, &fdtail, 10);
2240 if (fdtail > fname + 1 && *fdtail == '\0')
2242 /* Don't allow redirection when open modes are incompatible. */
2243 if ((ref_fd == 0 && (fd == out || fd == err))
2244 || ((ref_fd == 1 || ref_fd == 2) && fd == inp))
2251 else if (ref_fd == 1)
2253 else if (ref_fd == 2)
2263 fname++; /* skip the separator space */
2264 /* If the descriptor is already open, close it. This allows
2265 multiple specs of redirections for the same stream, which is
2266 somewhat nonsensical, but still valid and supported by cmd.exe.
2267 (But cmd.exe only opens a single file in this case, the one
2268 specified by the last redirection spec on the command line.) */
2273 *fd = _open (fname, mode, _S_IREAD | _S_IWRITE);
2277 else if (ref_fd == -1)
2278 *fd = -1; /* reset to default destination */
2281 *fd = _dup (ref_fd);
2285 /* _open just sets a flag for O_APPEND, which won't be passed to the
2286 inferior, so we need to actually move the file pointer. */
2287 if ((mode & O_APPEND) != 0)
2288 _lseek (*fd, 0L, SEEK_END);
2292 /* Canonicalize a single redirection spec and set up the corresponding
2293 file descriptor as specified. */
2295 redir_set_redirection (const char *s, int *inp, int *out, int *err)
2297 char buf[__PMAX + 2 + 5]; /* extra space for quotes & redirection string */
2299 const char *start = s;
2302 *d++ = *s++; /* copy the 1st character, < or > or a digit */
2303 if ((*start == '>' || *start == '1' || *start == '2')
2307 if (*s == '>' && *start != '>')
2310 else if (*start == '0' && *s == '<')
2312 /* cmd.exe recognizes "&N" only immediately after the redirection symbol. */
2315 while (isspace (*s)) /* skip whitespace before file name */
2317 *d++ = ' '; /* separate file name with a single space */
2320 /* Copy the file name. */
2323 /* Remove quoting characters from the file name in buf[]. */
2324 if (*s == '"') /* could support '..' quoting here */
2328 else if (*s == quote)
2336 else if (*s == '\\')
2338 if (s[1] == '"') /* could support '..' here */
2342 else if (isspace (*s) && !quote)
2346 if (d - buf >= sizeof (buf) - 1)
2348 errno = ENAMETOOLONG;
2354 /* Windows doesn't allow redirection characters in file names, so we
2355 can bail out early if they use them, or if there's no target file
2356 name after the redirection symbol. */
2357 if (d[-1] == '>' || d[-1] == '<')
2362 if (redir_open (buf, inp, out, err) == 0)
2367 /* Parse the command line for redirection specs and prepare the file
2368 descriptors for the 3 standard streams accordingly. */
2370 redirect_inferior_handles (const char *cmd_orig, char *cmd,
2371 int *inp, int *out, int *err)
2373 const char *s = cmd_orig;
2376 bool retval = false;
2378 while (isspace (*s))
2383 if (*s == '"') /* could also support '..' quoting here */
2387 else if (*s == quote)
2390 else if (*s == '\\')
2392 if (s[1] == '"') /* escaped quote char */
2397 /* Process a single redirection candidate. */
2398 if (*s == '<' || *s == '>'
2399 || ((*s == '1' || *s == '2') && s[1] == '>')
2400 || (*s == '0' && s[1] == '<'))
2402 int skip = redir_set_redirection (s, inp, out, err);
2416 #endif /* !__CYGWIN__ */
2418 /* Start an inferior windows child process and sets inferior_ptid to its pid.
2419 EXEC_FILE is the file to run.
2420 ALLARGS is a string containing the arguments to the program.
2421 ENV is the environment vector to pass. Errors reported with error(). */
2424 windows_create_inferior (struct target_ops *ops, const char *exec_file,
2425 const std::string &origallargs, char **in_env,
2430 cygwin_buf_t real_path[__PMAX];
2431 cygwin_buf_t shell[__PMAX]; /* Path to shell */
2432 cygwin_buf_t infcwd[__PMAX];
2434 cygwin_buf_t *toexec;
2435 cygwin_buf_t *cygallargs;
2437 char **old_env = NULL;
2441 int ostdin, ostdout, ostderr;
2442 #else /* !__CYGWIN__ */
2443 char real_path[__PMAX];
2444 char shell[__PMAX]; /* Path to shell */
2446 char *args, *allargs_copy;
2447 size_t args_len, allargs_len;
2448 int fd_inp = -1, fd_out = -1, fd_err = -1;
2449 HANDLE tty = INVALID_HANDLE_VALUE;
2450 HANDLE inf_stdin = INVALID_HANDLE_VALUE;
2451 HANDLE inf_stdout = INVALID_HANDLE_VALUE;
2452 HANDLE inf_stderr = INVALID_HANDLE_VALUE;
2453 bool redirected = false;
2460 #endif /* !__CYGWIN__ */
2461 const char *allargs = origallargs.c_str ();
2462 PROCESS_INFORMATION pi;
2465 const char *inferior_io_terminal = get_inferior_io_terminal ();
2468 error (_("No executable specified, use `target exec'."));
2470 const char *inferior_cwd = get_inferior_cwd ();
2471 std::string expanded_infcwd;
2472 if (inferior_cwd != NULL)
2474 expanded_infcwd = gdb_tilde_expand (inferior_cwd);
2475 /* Mirror slashes on inferior's cwd. */
2476 std::replace (expanded_infcwd.begin (), expanded_infcwd.end (),
2478 inferior_cwd = expanded_infcwd.c_str ();
2481 memset (&si, 0, sizeof (si));
2482 si.cb = sizeof (si);
2485 flags |= CREATE_NEW_PROCESS_GROUP;
2488 windows_set_console_info (&si, &flags);
2493 flags |= DEBUG_ONLY_THIS_PROCESS;
2494 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, exec_file, real_path,
2495 __PMAX * sizeof (cygwin_buf_t)) < 0)
2496 error (_("Error starting executable: %d"), errno);
2499 len = mbstowcs (NULL, allargs, 0) + 1;
2500 if (len == (size_t) -1)
2501 error (_("Error starting executable: %d"), errno);
2502 cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
2503 mbstowcs (cygallargs, allargs, len);
2504 #else /* !__USEWIDE */
2505 cygallargs = allargs;
2510 sh = getenv ("SHELL");
2513 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, sh, shell, __PMAX) < 0)
2514 error (_("Error starting executable via shell: %d"), errno);
2516 len = sizeof (L" -c 'exec '") + mbstowcs (NULL, exec_file, 0)
2517 + mbstowcs (NULL, allargs, 0) + 2;
2518 cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
2519 swprintf (cygallargs, len, L" -c 'exec %s %s'", exec_file, allargs);
2520 #else /* !__USEWIDE */
2521 len = (sizeof (" -c 'exec '") + strlen (exec_file)
2522 + strlen (allargs) + 2);
2523 cygallargs = (char *) alloca (len);
2524 xsnprintf (cygallargs, len, " -c 'exec %s %s'", exec_file, allargs);
2525 #endif /* __USEWIDE */
2527 flags |= DEBUG_PROCESS;
2530 if (inferior_cwd != NULL
2531 && cygwin_conv_path (CCP_POSIX_TO_WIN_W, inferior_cwd,
2532 infcwd, strlen (inferior_cwd)) < 0)
2533 error (_("Error converting inferior cwd: %d"), errno);
2536 args = (cygwin_buf_t *) alloca ((wcslen (toexec) + wcslen (cygallargs) + 2)
2537 * sizeof (wchar_t));
2538 wcscpy (args, toexec);
2539 wcscat (args, L" ");
2540 wcscat (args, cygallargs);
2541 #else /* !__USEWIDE */
2542 args = (cygwin_buf_t *) alloca (strlen (toexec) + strlen (cygallargs) + 2);
2543 strcpy (args, toexec);
2545 strcat (args, cygallargs);
2546 #endif /* !__USEWIDE */
2548 #ifdef CW_CVT_ENV_TO_WINENV
2549 /* First try to create a direct Win32 copy of the POSIX environment. */
2550 w32_env = (PWCHAR) cygwin_internal (CW_CVT_ENV_TO_WINENV, in_env);
2551 if (w32_env != (PWCHAR) -1)
2552 flags |= CREATE_UNICODE_ENVIRONMENT;
2554 /* If that fails, fall back to old method tweaking GDB's environment. */
2555 #endif /* CW_CVT_ENV_TO_WINENV */
2557 /* Reset all Win32 environment variables to avoid leftover on next run. */
2558 clear_win32_environment (environ);
2559 /* Prepare the environment vars for CreateProcess. */
2562 cygwin_internal (CW_SYNC_WINENV);
2566 if (!inferior_io_terminal)
2567 tty = ostdin = ostdout = ostderr = -1;
2570 tty = open (inferior_io_terminal, O_RDWR | O_NOCTTY);
2573 print_sys_errmsg (inferior_io_terminal, errno);
2574 ostdin = ostdout = ostderr = -1;
2587 windows_init_thread_list ();
2588 ret = CreateProcess (0,
2589 args, /* command line */
2590 NULL, /* Security */
2592 TRUE, /* inherit handles */
2593 flags, /* start flags */
2594 w32_env, /* environment */
2595 inferior_cwd != NULL ? infcwd : NULL, /* current
2600 /* Just free the Win32 environment, if it could be created. */
2604 /* Reset all environment variables to avoid leftover on next run. */
2605 clear_win32_environment (in_env);
2606 /* Restore normal GDB environment variables. */
2608 cygwin_internal (CW_SYNC_WINENV);
2621 #else /* !__CYGWIN__ */
2622 allargs_len = strlen (allargs);
2623 allargs_copy = strcpy ((char *) alloca (allargs_len + 1), allargs);
2624 if (strpbrk (allargs_copy, "<>") != NULL)
2629 redirect_inferior_handles (allargs, allargs_copy,
2630 &fd_inp, &fd_out, &fd_err);
2632 warning (_("Error in redirection: %s."), strerror (errno));
2635 allargs_len = strlen (allargs_copy);
2637 /* If not all the standard streams are redirected by the command
2638 line, use inferior_io_terminal for those which aren't. */
2639 if (inferior_io_terminal
2640 && !(fd_inp >= 0 && fd_out >= 0 && fd_err >= 0))
2642 SECURITY_ATTRIBUTES sa;
2643 sa.nLength = sizeof(sa);
2644 sa.lpSecurityDescriptor = 0;
2645 sa.bInheritHandle = TRUE;
2646 tty = CreateFileA (inferior_io_terminal, GENERIC_READ | GENERIC_WRITE,
2647 0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
2648 if (tty == INVALID_HANDLE_VALUE)
2649 warning (_("Warning: Failed to open TTY %s, error %#x."),
2650 inferior_io_terminal, (unsigned) GetLastError ());
2652 if (redirected || tty != INVALID_HANDLE_VALUE)
2655 si.hStdInput = (HANDLE) _get_osfhandle (fd_inp);
2656 else if (tty != INVALID_HANDLE_VALUE)
2659 si.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
2661 si.hStdOutput = (HANDLE) _get_osfhandle (fd_out);
2662 else if (tty != INVALID_HANDLE_VALUE)
2663 si.hStdOutput = tty;
2665 si.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
2667 si.hStdError = (HANDLE) _get_osfhandle (fd_err);
2668 else if (tty != INVALID_HANDLE_VALUE)
2671 si.hStdError = GetStdHandle (STD_ERROR_HANDLE);
2672 si.dwFlags |= STARTF_USESTDHANDLES;
2676 /* Build the command line, a space-separated list of tokens where
2677 the first token is the name of the module to be executed.
2678 To avoid ambiguities introduced by spaces in the module name,
2680 args_len = strlen (toexec) + 2 /* quotes */ + allargs_len + 2;
2681 args = (char *) alloca (args_len);
2682 xsnprintf (args, args_len, "\"%s\" %s", toexec, allargs_copy);
2684 flags |= DEBUG_ONLY_THIS_PROCESS;
2686 /* CreateProcess takes the environment list as a null terminated set of
2687 strings (i.e. two nulls terminate the list). */
2689 /* Get total size for env strings. */
2690 for (envlen = 0, i = 0; in_env[i] && *in_env[i]; i++)
2691 envlen += strlen (in_env[i]) + 1;
2693 envsize = sizeof (in_env[0]) * (i + 1);
2694 env = (char **) alloca (envsize);
2695 memcpy (env, in_env, envsize);
2696 /* Windows programs expect the environment block to be sorted. */
2697 qsort (env, i, sizeof (char *), envvar_cmp);
2699 w32env = (char *) alloca (envlen + 1);
2701 /* Copy env strings into new buffer. */
2702 for (temp = w32env, i = 0; env[i] && *env[i]; i++)
2704 strcpy (temp, env[i]);
2705 temp += strlen (temp) + 1;
2708 /* Final nil string to terminate new env. */
2711 windows_init_thread_list ();
2712 ret = CreateProcessA (0,
2713 args, /* command line */
2714 NULL, /* Security */
2716 TRUE, /* inherit handles */
2717 flags, /* start flags */
2718 w32env, /* environment */
2719 inferior_cwd, /* current directory */
2722 if (tty != INVALID_HANDLE_VALUE)
2730 #endif /* !__CYGWIN__ */
2733 error (_("Error creating process %s, (error %u)."),
2734 exec_file, (unsigned) GetLastError ());
2736 CloseHandle (pi.hThread);
2737 CloseHandle (pi.hProcess);
2739 if (useshell && shell[0] != '\0')
2744 do_initial_windows_stuff (ops, pi.dwProcessId, 0);
2746 /* windows_continue (DBG_CONTINUE, -1, 0); */
2750 windows_mourn_inferior (struct target_ops *ops)
2752 (void) windows_continue (DBG_CONTINUE, -1, 0);
2753 x86_cleanup_dregs();
2754 if (open_process_used)
2756 CHECK (CloseHandle (current_process_handle));
2757 open_process_used = 0;
2759 inf_child_mourn_inferior (ops);
2762 /* Send a SIGINT to the process group. This acts just like the user typed a
2763 ^C on the controlling terminal. */
2766 windows_interrupt (struct target_ops *self, ptid_t ptid)
2768 DEBUG_EVENTS (("gdb: GenerateConsoleCtrlEvent (CTRLC_EVENT, 0)\n"));
2769 CHECK (GenerateConsoleCtrlEvent (CTRL_C_EVENT, current_event.dwProcessId));
2770 registers_changed (); /* refresh register state */
2773 /* Helper for windows_xfer_partial that handles memory transfers.
2774 Arguments are like target_xfer_partial. */
2776 static enum target_xfer_status
2777 windows_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
2778 ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
2782 DWORD lasterror = 0;
2784 if (writebuf != NULL)
2786 DEBUG_MEM (("gdb: write target memory, %s bytes at %s\n",
2787 pulongest (len), core_addr_to_string (memaddr)));
2788 success = WriteProcessMemory (current_process_handle,
2789 (LPVOID) (uintptr_t) memaddr, writebuf,
2792 lasterror = GetLastError ();
2793 FlushInstructionCache (current_process_handle,
2794 (LPCVOID) (uintptr_t) memaddr, len);
2798 DEBUG_MEM (("gdb: read target memory, %s bytes at %s\n",
2799 pulongest (len), core_addr_to_string (memaddr)));
2800 success = ReadProcessMemory (current_process_handle,
2801 (LPCVOID) (uintptr_t) memaddr, readbuf,
2804 lasterror = GetLastError ();
2806 *xfered_len = (ULONGEST) done;
2807 if (!success && lasterror == ERROR_PARTIAL_COPY && done > 0)
2808 return TARGET_XFER_OK;
2810 return success ? TARGET_XFER_OK : TARGET_XFER_E_IO;
2814 windows_kill_inferior (struct target_ops *ops)
2816 CHECK (TerminateProcess (current_process_handle, 0));
2820 if (!windows_continue (DBG_CONTINUE, -1, 1))
2822 if (!WaitForDebugEvent (¤t_event, INFINITE))
2824 if (current_event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
2828 target_mourn_inferior (inferior_ptid); /* Or just windows_mourn_inferior? */
2832 windows_close (struct target_ops *self)
2834 DEBUG_EVENTS (("gdb: windows_close, inferior_ptid=%d\n",
2835 ptid_get_pid (inferior_ptid)));
2838 /* Convert pid to printable format. */
2840 windows_pid_to_str (struct target_ops *ops, ptid_t ptid)
2842 static char buf[80];
2844 if (ptid_get_tid (ptid) != 0)
2846 snprintf (buf, sizeof (buf), "Thread %d.0x%lx",
2847 ptid_get_pid (ptid), ptid_get_tid (ptid));
2851 return normal_pid_to_str (ptid);
2854 static enum target_xfer_status
2855 windows_xfer_shared_libraries (struct target_ops *ops,
2856 enum target_object object, const char *annex,
2857 gdb_byte *readbuf, const gdb_byte *writebuf,
2858 ULONGEST offset, ULONGEST len,
2859 ULONGEST *xfered_len)
2861 struct obstack obstack;
2867 return TARGET_XFER_E_IO;
2869 obstack_init (&obstack);
2870 obstack_grow_str (&obstack, "<library-list>\n");
2871 for (so = solib_start.next; so; so = so->next)
2873 lm_info_windows *li = (lm_info_windows *) so->lm_info;
2875 windows_xfer_shared_library (so->so_name, (CORE_ADDR)
2876 (uintptr_t) li->load_addr,
2877 target_gdbarch (), &obstack);
2879 obstack_grow_str0 (&obstack, "</library-list>\n");
2881 buf = (const char *) obstack_finish (&obstack);
2882 len_avail = strlen (buf);
2883 if (offset >= len_avail)
2887 if (len > len_avail - offset)
2888 len = len_avail - offset;
2889 memcpy (readbuf, buf + offset, len);
2892 obstack_free (&obstack, NULL);
2893 *xfered_len = (ULONGEST) len;
2894 return len != 0 ? TARGET_XFER_OK : TARGET_XFER_EOF;
2897 static enum target_xfer_status
2898 windows_xfer_partial (struct target_ops *ops, enum target_object object,
2899 const char *annex, gdb_byte *readbuf,
2900 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
2901 ULONGEST *xfered_len)
2905 case TARGET_OBJECT_MEMORY:
2906 return windows_xfer_memory (readbuf, writebuf, offset, len, xfered_len);
2908 case TARGET_OBJECT_LIBRARIES:
2909 return windows_xfer_shared_libraries (ops, object, annex, readbuf,
2910 writebuf, offset, len, xfered_len);
2913 return ops->beneath->to_xfer_partial (ops->beneath, object, annex,
2914 readbuf, writebuf, offset, len,
2919 /* Provide thread local base, i.e. Thread Information Block address.
2920 Returns 1 if ptid is found and sets *ADDR to thread_local_base. */
2923 windows_get_tib_address (struct target_ops *self,
2924 ptid_t ptid, CORE_ADDR *addr)
2926 windows_thread_info *th;
2928 th = thread_rec (ptid_get_tid (ptid), 0);
2933 *addr = th->thread_local_base;
2939 windows_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
2941 return ptid_build (ptid_get_pid (inferior_ptid), 0, lwp);
2944 /* Implementation of the to_thread_name method. */
2947 windows_thread_name (struct target_ops *self, struct thread_info *thr)
2949 return thread_rec (ptid_get_tid (thr->ptid), 0)->name;
2952 static struct target_ops *
2953 windows_target (void)
2955 struct target_ops *t = inf_child_target ();
2957 t->to_close = windows_close;
2958 t->to_attach = windows_attach;
2959 t->to_attach_no_wait = 1;
2960 t->to_detach = windows_detach;
2961 t->to_resume = windows_resume;
2962 t->to_wait = windows_wait;
2963 t->to_fetch_registers = windows_fetch_inferior_registers;
2964 t->to_store_registers = windows_store_inferior_registers;
2965 t->to_xfer_partial = windows_xfer_partial;
2966 t->to_files_info = windows_files_info;
2967 t->to_kill = windows_kill_inferior;
2968 t->to_create_inferior = windows_create_inferior;
2969 t->to_mourn_inferior = windows_mourn_inferior;
2970 t->to_thread_alive = windows_thread_alive;
2971 t->to_pid_to_str = windows_pid_to_str;
2972 t->to_interrupt = windows_interrupt;
2973 t->to_pid_to_exec_file = windows_pid_to_exec_file;
2974 t->to_get_ada_task_ptid = windows_get_ada_task_ptid;
2975 t->to_get_tib_address = windows_get_tib_address;
2976 t->to_thread_name = windows_thread_name;
2982 _initialize_windows_nat (void)
2984 struct target_ops *t;
2986 t = windows_target ();
2988 x86_use_watchpoints (t);
2990 x86_dr_low.set_control = cygwin_set_dr7;
2991 x86_dr_low.set_addr = cygwin_set_dr;
2992 x86_dr_low.get_addr = cygwin_get_dr;
2993 x86_dr_low.get_status = cygwin_get_dr6;
2994 x86_dr_low.get_control = cygwin_get_dr7;
2996 /* x86_dr_low.debug_register_length field is set by
2997 calling x86_set_debug_register_length function
2998 in processor windows specific native file. */
3003 cygwin_internal (CW_SET_DOS_FILE_WARNING, 0);
3006 add_com ("signal-event", class_run, signal_event_command, _("\
3007 Signal a crashed process with event ID, to allow its debugging.\n\
3008 This command is needed in support of setting up GDB as JIT debugger on \
3009 MS-Windows. The command should be invoked from the GDB command line using \
3010 the '-ex' command-line option. The ID of the event that blocks the \
3011 crashed process will be supplied by the Windows JIT debugging mechanism."));
3014 add_setshow_boolean_cmd ("shell", class_support, &useshell, _("\
3015 Set use of shell to start subprocess."), _("\
3016 Show use of shell to start subprocess."), NULL,
3018 NULL, /* FIXME: i18n: */
3019 &setlist, &showlist);
3021 add_setshow_boolean_cmd ("cygwin-exceptions", class_support,
3022 &cygwin_exceptions, _("\
3023 Break when an exception is detected in the Cygwin DLL itself."), _("\
3024 Show whether gdb breaks on exceptions in the Cygwin DLL itself."), NULL,
3026 NULL, /* FIXME: i18n: */
3027 &setlist, &showlist);
3030 add_setshow_boolean_cmd ("new-console", class_support, &new_console, _("\
3031 Set creation of new console when creating child process."), _("\
3032 Show creation of new console when creating child process."), NULL,
3034 NULL, /* FIXME: i18n: */
3035 &setlist, &showlist);
3037 add_setshow_boolean_cmd ("new-group", class_support, &new_group, _("\
3038 Set creation of new group when creating child process."), _("\
3039 Show creation of new group when creating child process."), NULL,
3041 NULL, /* FIXME: i18n: */
3042 &setlist, &showlist);
3044 add_setshow_boolean_cmd ("debugexec", class_support, &debug_exec, _("\
3045 Set whether to display execution in child process."), _("\
3046 Show whether to display execution in child process."), NULL,
3048 NULL, /* FIXME: i18n: */
3049 &setlist, &showlist);
3051 add_setshow_boolean_cmd ("debugevents", class_support, &debug_events, _("\
3052 Set whether to display kernel events in child process."), _("\
3053 Show whether to display kernel events in child process."), NULL,
3055 NULL, /* FIXME: i18n: */
3056 &setlist, &showlist);
3058 add_setshow_boolean_cmd ("debugmemory", class_support, &debug_memory, _("\
3059 Set whether to display memory accesses in child process."), _("\
3060 Show whether to display memory accesses in child process."), NULL,
3062 NULL, /* FIXME: i18n: */
3063 &setlist, &showlist);
3065 add_setshow_boolean_cmd ("debugexceptions", class_support,
3066 &debug_exceptions, _("\
3067 Set whether to display kernel exceptions in child process."), _("\
3068 Show whether to display kernel exceptions in child process."), NULL,
3070 NULL, /* FIXME: i18n: */
3071 &setlist, &showlist);
3073 init_w32_command_list ();
3075 add_cmd ("selector", class_info, display_selectors,
3076 _("Display selectors infos."),
3080 /* Hardware watchpoint support, adapted from go32-nat.c code. */
3082 /* Pass the address ADDR to the inferior in the I'th debug register.
3083 Here we just store the address in dr array, the registers will be
3084 actually set up when windows_continue is called. */
3086 cygwin_set_dr (int i, CORE_ADDR addr)
3089 internal_error (__FILE__, __LINE__,
3090 _("Invalid register %d in cygwin_set_dr.\n"), i);
3092 debug_registers_changed = 1;
3093 debug_registers_used = 1;
3096 /* Pass the value VAL to the inferior in the DR7 debug control
3097 register. Here we just store the address in D_REGS, the watchpoint
3098 will be actually set up in windows_wait. */
3100 cygwin_set_dr7 (unsigned long val)
3102 dr[7] = (CORE_ADDR) val;
3103 debug_registers_changed = 1;
3104 debug_registers_used = 1;
3107 /* Get the value of debug register I from the inferior. */
3110 cygwin_get_dr (int i)
3115 /* Get the value of the DR6 debug status register from the inferior.
3116 Here we just return the value stored in dr[6]
3117 by the last call to thread_rec for current_event.dwThreadId id. */
3118 static unsigned long
3119 cygwin_get_dr6 (void)
3121 return (unsigned long) dr[6];
3124 /* Get the value of the DR7 debug status register from the inferior.
3125 Here we just return the value stored in dr[7] by the last call to
3126 thread_rec for current_event.dwThreadId id. */
3128 static unsigned long
3129 cygwin_get_dr7 (void)
3131 return (unsigned long) dr[7];
3134 /* Determine if the thread referenced by "ptid" is alive
3135 by "polling" it. If WaitForSingleObject returns WAIT_OBJECT_0
3136 it means that the thread has died. Otherwise it is assumed to be alive. */
3138 windows_thread_alive (struct target_ops *ops, ptid_t ptid)
3142 gdb_assert (ptid_get_tid (ptid) != 0);
3143 tid = ptid_get_tid (ptid);
3145 return WaitForSingleObject (thread_rec (tid, FALSE)->h, 0) == WAIT_OBJECT_0
3150 _initialize_check_for_gdb_ini (void)
3153 if (inhibit_gdbinit)
3156 homedir = getenv ("HOME");
3160 char *oldini = (char *) alloca (strlen (homedir) +
3161 sizeof ("gdb.ini") + 1);
3162 strcpy (oldini, homedir);
3163 p = strchr (oldini, '\0');
3164 if (p > oldini && !IS_DIR_SEPARATOR (p[-1]))
3166 strcpy (p, "gdb.ini");
3167 if (access (oldini, 0) == 0)
3169 int len = strlen (oldini);
3170 char *newini = (char *) alloca (len + 2);
3172 xsnprintf (newini, len + 2, "%.*s.gdbinit",
3173 (int) (len - (sizeof ("gdb.ini") - 1)), oldini);
3174 warning (_("obsolete '%s' found. Rename to '%s'."), oldini, newini);
3179 /* Define dummy functions which always return error for the rare cases where
3180 these functions could not be found. */
3182 bad_DebugActiveProcessStop (DWORD w)
3187 bad_DebugBreakProcess (HANDLE w)
3192 bad_DebugSetProcessKillOnExit (BOOL w)
3197 bad_EnumProcessModules (HANDLE w, HMODULE *x, DWORD y, LPDWORD z)
3204 bad_GetModuleFileNameExW (HANDLE w, HMODULE x, LPWSTR y, DWORD z)
3210 bad_GetModuleFileNameExA (HANDLE w, HMODULE x, LPSTR y, DWORD z)
3217 bad_GetModuleInformation (HANDLE w, HMODULE x, LPMODULEINFO y, DWORD z)
3223 bad_OpenProcessToken (HANDLE w, DWORD x, PHANDLE y)
3229 bad_GetCurrentConsoleFont (HANDLE w, BOOL bMaxWindow, CONSOLE_FONT_INFO *f)
3235 bad_GetConsoleFontSize (HANDLE w, DWORD nFont)
3243 /* Load any functions which may not be available in ancient versions
3247 _initialize_loadable (void)
3251 #define GPA(m, func) \
3252 func = (func ## _ftype *) GetProcAddress (m, #func)
3254 hm = LoadLibrary ("kernel32.dll");
3257 GPA (hm, DebugActiveProcessStop);
3258 GPA (hm, DebugBreakProcess);
3259 GPA (hm, DebugSetProcessKillOnExit);
3260 GPA (hm, GetConsoleFontSize);
3261 GPA (hm, DebugActiveProcessStop);
3262 GPA (hm, GetCurrentConsoleFont);
3265 /* Set variables to dummy versions of these processes if the function
3266 wasn't found in kernel32.dll. */
3267 if (!DebugBreakProcess)
3268 DebugBreakProcess = bad_DebugBreakProcess;
3269 if (!DebugActiveProcessStop || !DebugSetProcessKillOnExit)
3271 DebugActiveProcessStop = bad_DebugActiveProcessStop;
3272 DebugSetProcessKillOnExit = bad_DebugSetProcessKillOnExit;
3274 if (!GetConsoleFontSize)
3275 GetConsoleFontSize = bad_GetConsoleFontSize;
3276 if (!GetCurrentConsoleFont)
3277 GetCurrentConsoleFont = bad_GetCurrentConsoleFont;
3279 /* Load optional functions used for retrieving filename information
3280 associated with the currently debugged process or its dlls. */
3281 hm = LoadLibrary ("psapi.dll");
3284 GPA (hm, EnumProcessModules);
3285 GPA (hm, GetModuleInformation);
3286 GetModuleFileNameEx = (GetModuleFileNameEx_ftype *)
3287 GetProcAddress (hm, GetModuleFileNameEx_name);
3290 if (!EnumProcessModules || !GetModuleInformation || !GetModuleFileNameEx)
3292 /* Set variables to dummy versions of these processes if the function
3293 wasn't found in psapi.dll. */
3294 EnumProcessModules = bad_EnumProcessModules;
3295 GetModuleInformation = bad_GetModuleInformation;
3296 GetModuleFileNameEx = bad_GetModuleFileNameEx;
3297 /* This will probably fail on Windows 9x/Me. Let the user know
3298 that we're missing some functionality. */
3300 cannot automatically find executable file or library to read symbols.\n\
3301 Use \"file\" or \"dll\" command to load executable/libraries directly."));
3304 hm = LoadLibrary ("advapi32.dll");
3307 GPA (hm, OpenProcessToken);
3308 GPA (hm, LookupPrivilegeValueA);
3309 GPA (hm, AdjustTokenPrivileges);
3310 /* Only need to set one of these since if OpenProcessToken fails nothing
3312 if (!OpenProcessToken || !LookupPrivilegeValueA
3313 || !AdjustTokenPrivileges)
3314 OpenProcessToken = bad_OpenProcessToken;