1 /* Target-vector operations for controlling windows child processes, for GDB.
3 Copyright (C) 1995-2016 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"
70 #define AdjustTokenPrivileges dyn_AdjustTokenPrivileges
71 #define DebugActiveProcessStop dyn_DebugActiveProcessStop
72 #define DebugBreakProcess dyn_DebugBreakProcess
73 #define DebugSetProcessKillOnExit dyn_DebugSetProcessKillOnExit
74 #define EnumProcessModules dyn_EnumProcessModules
75 #define GetModuleInformation dyn_GetModuleInformation
76 #define LookupPrivilegeValueA dyn_LookupPrivilegeValueA
77 #define OpenProcessToken dyn_OpenProcessToken
78 #define GetConsoleFontSize dyn_GetConsoleFontSize
79 #define GetCurrentConsoleFont dyn_GetCurrentConsoleFont
81 typedef BOOL
WINAPI (AdjustTokenPrivileges_ftype
) (HANDLE
, BOOL
,
83 DWORD
, PTOKEN_PRIVILEGES
,
85 static AdjustTokenPrivileges_ftype
*AdjustTokenPrivileges
;
87 typedef BOOL
WINAPI (DebugActiveProcessStop_ftype
) (DWORD
);
88 static DebugActiveProcessStop_ftype
*DebugActiveProcessStop
;
90 typedef BOOL
WINAPI (DebugBreakProcess_ftype
) (HANDLE
);
91 static DebugBreakProcess_ftype
*DebugBreakProcess
;
93 typedef BOOL
WINAPI (DebugSetProcessKillOnExit_ftype
) (BOOL
);
94 static DebugSetProcessKillOnExit_ftype
*DebugSetProcessKillOnExit
;
96 typedef BOOL
WINAPI (EnumProcessModules_ftype
) (HANDLE
, HMODULE
*, DWORD
,
98 static EnumProcessModules_ftype
*EnumProcessModules
;
100 typedef BOOL
WINAPI (GetModuleInformation_ftype
) (HANDLE
, HMODULE
,
101 LPMODULEINFO
, DWORD
);
102 static GetModuleInformation_ftype
*GetModuleInformation
;
104 typedef BOOL
WINAPI (LookupPrivilegeValueA_ftype
) (LPCSTR
, LPCSTR
, PLUID
);
105 static LookupPrivilegeValueA_ftype
*LookupPrivilegeValueA
;
107 typedef BOOL
WINAPI (OpenProcessToken_ftype
) (HANDLE
, DWORD
, PHANDLE
);
108 static OpenProcessToken_ftype
*OpenProcessToken
;
110 typedef BOOL
WINAPI (GetCurrentConsoleFont_ftype
) (HANDLE
, BOOL
,
111 CONSOLE_FONT_INFO
*);
112 static GetCurrentConsoleFont_ftype
*GetCurrentConsoleFont
;
114 typedef COORD
WINAPI (GetConsoleFontSize_ftype
) (HANDLE
, DWORD
);
115 static GetConsoleFontSize_ftype
*GetConsoleFontSize
;
119 #undef GetModuleFileNameEx
122 # define __PMAX (MAX_PATH + 1)
123 typedef DWORD
WINAPI (GetModuleFileNameEx_ftype
) (HANDLE
, HMODULE
, LPSTR
, DWORD
);
124 static GetModuleFileNameEx_ftype
*GetModuleFileNameEx
;
125 # define STARTUPINFO STARTUPINFOA
126 # define CreateProcess CreateProcessA
127 # define GetModuleFileNameEx_name "GetModuleFileNameExA"
128 # define bad_GetModuleFileNameEx bad_GetModuleFileNameExA
130 # define __PMAX PATH_MAX
131 /* The starting and ending address of the cygwin1.dll text segment. */
132 static CORE_ADDR cygwin_load_start
;
133 static CORE_ADDR cygwin_load_end
;
135 typedef wchar_t cygwin_buf_t
;
136 typedef DWORD
WINAPI (GetModuleFileNameEx_ftype
) (HANDLE
, HMODULE
,
138 static GetModuleFileNameEx_ftype
*GetModuleFileNameEx
;
139 # define STARTUPINFO STARTUPINFOW
140 # define CreateProcess CreateProcessW
141 # define GetModuleFileNameEx_name "GetModuleFileNameExW"
142 # define bad_GetModuleFileNameEx bad_GetModuleFileNameExW
145 static int have_saved_context
; /* True if we've saved context from a
147 static CONTEXT saved_context
; /* Containes the saved context from a
150 /* If we're not using the old Cygwin header file set, define the
151 following which never should have been in the generic Win32 API
152 headers in the first place since they were our own invention... */
153 #ifndef _GNU_H_WINDOWS_H
156 FLAG_TRACE_BIT
= 0x100,
160 #ifndef CONTEXT_EXTENDED_REGISTERS
161 /* This macro is only defined on ia32. It only makes sense on this target,
162 so define it as zero if not already defined. */
163 #define CONTEXT_EXTENDED_REGISTERS 0
166 #define CONTEXT_DEBUGGER_DR CONTEXT_FULL | CONTEXT_FLOATING_POINT \
167 | CONTEXT_SEGMENTS | CONTEXT_DEBUG_REGISTERS \
168 | CONTEXT_EXTENDED_REGISTERS
170 static uintptr_t dr
[8];
171 static int debug_registers_changed
;
172 static int debug_registers_used
;
174 static int windows_initialization_done
;
175 #define DR6_CLEAR_VALUE 0xffff0ff0
177 /* The string sent by cygwin when it processes a signal.
178 FIXME: This should be in a cygwin include file. */
179 #ifndef _CYGWIN_SIGNAL_STRING
180 #define _CYGWIN_SIGNAL_STRING "cYgSiGw00f"
183 #define CHECK(x) check (x, __FILE__,__LINE__)
184 #define DEBUG_EXEC(x) if (debug_exec) printf_unfiltered x
185 #define DEBUG_EVENTS(x) if (debug_events) printf_unfiltered x
186 #define DEBUG_MEM(x) if (debug_memory) printf_unfiltered x
187 #define DEBUG_EXCEPT(x) if (debug_exceptions) printf_unfiltered x
189 static void windows_interrupt (struct target_ops
*self
, ptid_t
);
190 static int windows_thread_alive (struct target_ops
*, ptid_t
);
191 static void windows_kill_inferior (struct target_ops
*);
193 static void cygwin_set_dr (int i
, CORE_ADDR addr
);
194 static void cygwin_set_dr7 (unsigned long val
);
195 static CORE_ADDR
cygwin_get_dr (int i
);
196 static unsigned long cygwin_get_dr6 (void);
197 static unsigned long cygwin_get_dr7 (void);
199 static enum gdb_signal last_sig
= GDB_SIGNAL_0
;
200 /* Set if a signal was received from the debugged process. */
202 /* Thread information structure used to track information that is
203 not available in gdb's thread structure. */
204 typedef struct windows_thread_info_struct
206 struct windows_thread_info_struct
*next
;
209 CORE_ADDR thread_local_base
;
218 static windows_thread_info thread_head
;
220 /* The process and thread handles for the above context. */
222 static DEBUG_EVENT current_event
; /* The current debug event from
224 static HANDLE current_process_handle
; /* Currently executing process */
225 static windows_thread_info
*current_thread
; /* Info on currently selected thread */
226 static DWORD main_thread_id
; /* Thread ID of the main thread */
228 /* Counts of things. */
229 static int exception_count
= 0;
230 static int event_count
= 0;
231 static int saw_create
;
232 static int open_process_used
= 0;
235 static int new_console
= 0;
237 static int cygwin_exceptions
= 0;
239 static int new_group
= 1;
240 static int debug_exec
= 0; /* show execution */
241 static int debug_events
= 0; /* show events from kernel */
242 static int debug_memory
= 0; /* show target memory accesses */
243 static int debug_exceptions
= 0; /* show target exceptions */
244 static int useshell
= 0; /* use shell for subprocesses */
246 /* This vector maps GDB's idea of a register's number into an offset
247 in the windows exception context vector.
249 It also contains the bit mask needed to load the register in question.
251 The contents of this table can only be computed by the units
252 that provide CPU-specific support for Windows native debugging.
253 These units should set the table by calling
254 windows_set_context_register_offsets.
256 One day we could read a reg, we could inspect the context we
257 already have loaded, if it doesn't have the bit set that we need,
258 we read that set of registers in using GetThreadContext. If the
259 context already contains what we need, we just unpack it. Then to
260 write a register, first we have to ensure that the context contains
261 the other regs of the group, and then we copy the info in and set
264 static const int *mappings
;
266 /* The function to use in order to determine whether a register is
267 a segment register or not. */
268 static segment_register_p_ftype
*segment_register_p
;
270 /* This vector maps the target's idea of an exception (extracted
271 from the DEBUG_EVENT structure) to GDB's idea. */
273 struct xlate_exception
279 static const struct xlate_exception
282 {EXCEPTION_ACCESS_VIOLATION
, GDB_SIGNAL_SEGV
},
283 {STATUS_STACK_OVERFLOW
, GDB_SIGNAL_SEGV
},
284 {EXCEPTION_BREAKPOINT
, GDB_SIGNAL_TRAP
},
285 {DBG_CONTROL_C
, GDB_SIGNAL_INT
},
286 {EXCEPTION_SINGLE_STEP
, GDB_SIGNAL_TRAP
},
287 {STATUS_FLOAT_DIVIDE_BY_ZERO
, GDB_SIGNAL_FPE
},
288 {-1, GDB_SIGNAL_UNKNOWN
}};
290 /* Set the MAPPINGS static global to OFFSETS.
291 See the description of MAPPINGS for more details. */
294 windows_set_context_register_offsets (const int *offsets
)
299 /* See windows-nat.h. */
302 windows_set_segment_register_p (segment_register_p_ftype
*fun
)
304 segment_register_p
= fun
;
308 check (BOOL ok
, const char *file
, int line
)
311 printf_filtered ("error return %s:%d was %u\n", file
, line
,
312 (unsigned) GetLastError ());
315 /* Find a thread record given a thread id. If GET_CONTEXT is not 0,
316 then also retrieve the context for this thread. If GET_CONTEXT is
317 negative, then don't suspend the thread. */
318 static windows_thread_info
*
319 thread_rec (DWORD id
, int get_context
)
321 windows_thread_info
*th
;
323 for (th
= &thread_head
; (th
= th
->next
) != NULL
;)
326 if (!th
->suspended
&& get_context
)
328 if (get_context
> 0 && id
!= current_event
.dwThreadId
)
330 if (SuspendThread (th
->h
) == (DWORD
) -1)
332 DWORD err
= GetLastError ();
334 /* We get Access Denied (5) when trying to suspend
335 threads that Windows started on behalf of the
336 debuggee, usually when those threads are just
338 We can get Invalid Handle (6) if the main thread
340 if (err
!= ERROR_INVALID_HANDLE
341 && err
!= ERROR_ACCESS_DENIED
)
342 warning (_("SuspendThread (tid=0x%x) failed."
344 (unsigned) id
, (unsigned) err
);
350 else if (get_context
< 0)
352 th
->reload_context
= 1;
360 /* Add a thread to the thread list. */
361 static windows_thread_info
*
362 windows_add_thread (ptid_t ptid
, HANDLE h
, void *tlb
)
364 windows_thread_info
*th
;
367 gdb_assert (ptid_get_tid (ptid
) != 0);
369 id
= ptid_get_tid (ptid
);
371 if ((th
= thread_rec (id
, FALSE
)))
374 th
= XCNEW (windows_thread_info
);
377 th
->thread_local_base
= (CORE_ADDR
) (uintptr_t) tlb
;
378 th
->next
= thread_head
.next
;
379 thread_head
.next
= th
;
381 /* Set the debug registers for the new thread if they are used. */
382 if (debug_registers_used
)
384 /* Only change the value of the debug registers. */
385 th
->context
.ContextFlags
= CONTEXT_DEBUG_REGISTERS
;
386 CHECK (GetThreadContext (th
->h
, &th
->context
));
387 th
->context
.Dr0
= dr
[0];
388 th
->context
.Dr1
= dr
[1];
389 th
->context
.Dr2
= dr
[2];
390 th
->context
.Dr3
= dr
[3];
391 th
->context
.Dr6
= DR6_CLEAR_VALUE
;
392 th
->context
.Dr7
= dr
[7];
393 CHECK (SetThreadContext (th
->h
, &th
->context
));
394 th
->context
.ContextFlags
= 0;
399 /* Clear out any old thread list and reintialize it to a
402 windows_init_thread_list (void)
404 windows_thread_info
*th
= &thread_head
;
406 DEBUG_EVENTS (("gdb: windows_init_thread_list\n"));
408 while (th
->next
!= NULL
)
410 windows_thread_info
*here
= th
->next
;
411 th
->next
= here
->next
;
414 thread_head
.next
= NULL
;
417 /* Delete a thread from the list of threads. */
419 windows_delete_thread (ptid_t ptid
, DWORD exit_code
)
421 windows_thread_info
*th
;
424 gdb_assert (ptid_get_tid (ptid
) != 0);
426 id
= ptid_get_tid (ptid
);
429 printf_unfiltered ("[Deleting %s]\n", target_pid_to_str (ptid
));
430 else if (print_thread_events
&& id
!= main_thread_id
)
431 printf_unfiltered (_("[%s exited with code %u]\n"),
432 target_pid_to_str (ptid
), (unsigned) exit_code
);
433 delete_thread (ptid
);
435 for (th
= &thread_head
;
436 th
->next
!= NULL
&& th
->next
->id
!= id
;
440 if (th
->next
!= NULL
)
442 windows_thread_info
*here
= th
->next
;
443 th
->next
= here
->next
;
449 do_windows_fetch_inferior_registers (struct regcache
*regcache
, int r
)
451 char *context_offset
= ((char *) ¤t_thread
->context
) + mappings
[r
];
452 struct gdbarch
*gdbarch
= get_regcache_arch (regcache
);
453 struct gdbarch_tdep
*tdep
= gdbarch_tdep (gdbarch
);
457 return; /* Windows sometimes uses a non-existent thread id in its
460 if (current_thread
->reload_context
)
463 if (have_saved_context
)
465 /* Lie about where the program actually is stopped since
466 cygwin has informed us that we should consider the signal
467 to have occurred at another location which is stored in
469 memcpy (¤t_thread
->context
, &saved_context
,
470 __COPY_CONTEXT_SIZE
);
471 have_saved_context
= 0;
476 windows_thread_info
*th
= current_thread
;
477 th
->context
.ContextFlags
= CONTEXT_DEBUGGER_DR
;
478 CHECK (GetThreadContext (th
->h
, &th
->context
));
479 /* Copy dr values from that thread.
480 But only if there were not modified since last stop.
482 if (!debug_registers_changed
)
484 dr
[0] = th
->context
.Dr0
;
485 dr
[1] = th
->context
.Dr1
;
486 dr
[2] = th
->context
.Dr2
;
487 dr
[3] = th
->context
.Dr3
;
488 dr
[6] = th
->context
.Dr6
;
489 dr
[7] = th
->context
.Dr7
;
492 current_thread
->reload_context
= 0;
495 if (r
== I387_FISEG_REGNUM (tdep
))
497 l
= *((long *) context_offset
) & 0xffff;
498 regcache_raw_supply (regcache
, r
, (char *) &l
);
500 else if (r
== I387_FOP_REGNUM (tdep
))
502 l
= (*((long *) context_offset
) >> 16) & ((1 << 11) - 1);
503 regcache_raw_supply (regcache
, r
, (char *) &l
);
505 else if (segment_register_p (r
))
507 /* GDB treats segment registers as 32bit registers, but they are
508 in fact only 16 bits long. Make sure we do not read extra
509 bits from our source buffer. */
510 l
= *((long *) context_offset
) & 0xffff;
511 regcache_raw_supply (regcache
, r
, (char *) &l
);
514 regcache_raw_supply (regcache
, r
, context_offset
);
517 for (r
= 0; r
< gdbarch_num_regs (gdbarch
); r
++)
518 do_windows_fetch_inferior_registers (regcache
, r
);
523 windows_fetch_inferior_registers (struct target_ops
*ops
,
524 struct regcache
*regcache
, int r
)
526 current_thread
= thread_rec (ptid_get_tid (inferior_ptid
), TRUE
);
527 /* Check if current_thread exists. Windows sometimes uses a non-existent
528 thread id in its events. */
530 do_windows_fetch_inferior_registers (regcache
, r
);
534 do_windows_store_inferior_registers (const struct regcache
*regcache
, int r
)
537 /* Windows sometimes uses a non-existent thread id in its events. */;
539 regcache_raw_collect (regcache
, r
,
540 ((char *) ¤t_thread
->context
) + mappings
[r
]);
543 for (r
= 0; r
< gdbarch_num_regs (get_regcache_arch (regcache
)); r
++)
544 do_windows_store_inferior_registers (regcache
, r
);
548 /* Store a new register value into the current thread context. */
550 windows_store_inferior_registers (struct target_ops
*ops
,
551 struct regcache
*regcache
, int r
)
553 current_thread
= thread_rec (ptid_get_tid (inferior_ptid
), TRUE
);
554 /* Check if current_thread exists. Windows sometimes uses a non-existent
555 thread id in its events. */
557 do_windows_store_inferior_registers (regcache
, r
);
560 /* Encapsulate the information required in a call to
561 symbol_file_add_args. */
562 struct safe_symbol_file_add_args
566 struct section_addr_info
*addrs
;
569 struct ui_file
*err
, *out
;
573 /* Maintain a linked list of "so" information. */
579 static struct so_list solib_start
, *solib_end
;
581 static struct so_list
*
582 windows_make_so (const char *name
, LPVOID load_addr
)
589 WIN32_FIND_DATA w32_fd
;
590 HANDLE h
= FindFirstFile(name
, &w32_fd
);
592 if (h
== INVALID_HANDLE_VALUE
)
598 if (GetCurrentDirectory (MAX_PATH
+ 1, cwd
))
600 p
= strrchr (buf
, '\\');
603 SetCurrentDirectory (buf
);
604 GetFullPathName (w32_fd
.cFileName
, MAX_PATH
, buf
, &p
);
605 SetCurrentDirectory (cwd
);
608 if (strcasecmp (buf
, "ntdll.dll") == 0)
610 GetSystemDirectory (buf
, sizeof (buf
));
611 strcat (buf
, "\\ntdll.dll");
614 cygwin_buf_t buf
[__PMAX
];
617 if (access (name
, F_OK
) != 0)
619 if (strcasecmp (name
, "ntdll.dll") == 0)
622 GetSystemDirectoryW (buf
, sizeof (buf
) / sizeof (wchar_t));
623 wcscat (buf
, L
"\\ntdll.dll");
627 GetSystemDirectoryA (buf
, sizeof (buf
) / sizeof (wchar_t));
628 strcat (buf
, "\\ntdll.dll");
633 so
= XCNEW (struct so_list
);
634 so
->lm_info
= XNEW (struct lm_info
);
635 so
->lm_info
->load_addr
= load_addr
;
636 strcpy (so
->so_original_name
, name
);
638 strcpy (so
->so_name
, buf
);
641 cygwin_conv_path (CCP_WIN_W_TO_POSIX
, buf
, so
->so_name
,
642 SO_NAME_MAX_PATH_SIZE
);
645 char *rname
= realpath (name
, NULL
);
646 if (rname
&& strlen (rname
) < SO_NAME_MAX_PATH_SIZE
)
648 strcpy (so
->so_name
, rname
);
652 error (_("dll path too long"));
654 /* Record cygwin1.dll .text start/end. */
655 p
= strchr (so
->so_name
, '\0') - (sizeof ("/cygwin1.dll") - 1);
656 if (p
>= so
->so_name
&& strcasecmp (p
, "/cygwin1.dll") == 0)
659 asection
*text
= NULL
;
662 abfd
= gdb_bfd_open (so
->so_name
, "pei-i386", -1);
667 if (bfd_check_format (abfd
, bfd_object
))
668 text
= bfd_get_section_by_name (abfd
, ".text");
672 gdb_bfd_unref (abfd
);
676 /* The symbols in a dll are offset by 0x1000, which is the
677 offset from 0 of the first byte in an image - because of the
678 file header and the section alignment. */
679 cygwin_load_start
= (CORE_ADDR
) (uintptr_t) ((char *)
681 cygwin_load_end
= cygwin_load_start
+ bfd_section_size (abfd
, text
);
683 gdb_bfd_unref (abfd
);
691 get_image_name (HANDLE h
, void *address
, int unicode
)
694 static char buf
[__PMAX
];
696 static char buf
[(2 * __PMAX
) + 1];
698 DWORD size
= unicode
? sizeof (WCHAR
) : sizeof (char);
704 /* Attempt to read the name of the dll that was detected.
705 This is documented to work only when actively debugging
706 a program. It will not work for attached processes. */
710 /* See if we could read the address of a string, and that the
711 address isn't null. */
712 if (!ReadProcessMemory (h
, address
, &address_ptr
,
713 sizeof (address_ptr
), &done
)
714 || done
!= sizeof (address_ptr
) || !address_ptr
)
717 /* Find the length of the string. */
718 while (ReadProcessMemory (h
, address_ptr
+ len
++ * size
, &b
, size
, &done
)
719 && (b
[0] != 0 || b
[size
- 1] != 0) && done
== size
)
723 ReadProcessMemory (h
, address_ptr
, buf
, len
, &done
);
726 WCHAR
*unicode_address
= (WCHAR
*) alloca (len
* sizeof (WCHAR
));
727 ReadProcessMemory (h
, address_ptr
, unicode_address
, len
* sizeof (WCHAR
),
730 wcstombs (buf
, unicode_address
, __PMAX
);
732 WideCharToMultiByte (CP_ACP
, 0, unicode_address
, len
, buf
, sizeof buf
,
740 /* Handle a DLL load event, and return 1.
742 This function assumes that this event did not occur during inferior
743 initialization, where their event info may be incomplete (see
744 do_initial_windows_stuff and windows_add_all_dlls for more info
745 on how we handle DLL loading during that phase). */
748 handle_load_dll (void *dummy
)
750 LOAD_DLL_DEBUG_INFO
*event
= ¤t_event
.u
.LoadDll
;
753 /* Try getting the DLL name via the lpImageName field of the event.
754 Note that Microsoft documents this fields as strictly optional,
755 in the sense that it might be NULL. And the first DLL event in
756 particular is explicitly documented as "likely not pass[ed]"
757 (source: MSDN LOAD_DLL_DEBUG_INFO structure). */
758 dll_name
= get_image_name (current_process_handle
,
759 event
->lpImageName
, event
->fUnicode
);
763 solib_end
->next
= windows_make_so (dll_name
, event
->lpBaseOfDll
);
764 solib_end
= solib_end
->next
;
766 DEBUG_EVENTS (("gdb: Loading dll \"%s\" at %s.\n", solib_end
->so_name
,
767 host_address_to_string (solib_end
->lm_info
->load_addr
)));
773 windows_free_so (struct so_list
*so
)
780 /* Handle a DLL unload event.
781 Return 1 if successful, or zero otherwise.
783 This function assumes that this event did not occur during inferior
784 initialization, where their event info may be incomplete (see
785 do_initial_windows_stuff and windows_add_all_dlls for more info
786 on how we handle DLL loading during that phase). */
789 handle_unload_dll (void *dummy
)
791 LPVOID lpBaseOfDll
= current_event
.u
.UnloadDll
.lpBaseOfDll
;
794 for (so
= &solib_start
; so
->next
!= NULL
; so
= so
->next
)
795 if (so
->next
->lm_info
->load_addr
== lpBaseOfDll
)
797 struct so_list
*sodel
= so
->next
;
799 so
->next
= sodel
->next
;
802 DEBUG_EVENTS (("gdb: Unloading dll \"%s\".\n", sodel
->so_name
));
804 windows_free_so (sodel
);
808 /* We did not find any DLL that was previously loaded at this address,
809 so register a complaint. We do not report an error, because we have
810 observed that this may be happening under some circumstances. For
811 instance, running 32bit applications on x64 Windows causes us to receive
812 4 mysterious UNLOAD_DLL_DEBUG_EVENTs during the startup phase (these
813 events are apparently caused by the WOW layer, the interface between
814 32bit and 64bit worlds). */
815 complaint (&symfile_complaints
, _("dll starting at %s not found."),
816 host_address_to_string (lpBaseOfDll
));
821 /* Clear list of loaded DLLs. */
823 windows_clear_solib (void)
825 solib_start
.next
= NULL
;
826 solib_end
= &solib_start
;
830 signal_event_command (char *args
, int from_tty
)
832 uintptr_t event_id
= 0;
833 char *endargs
= NULL
;
836 error (_("signal-event requires an argument (integer event id)"));
838 event_id
= strtoumax (args
, &endargs
, 10);
840 if ((errno
== ERANGE
) || (event_id
== 0) || (event_id
> UINTPTR_MAX
) ||
841 ((HANDLE
) event_id
== INVALID_HANDLE_VALUE
))
842 error (_("Failed to convert `%s' to event id"), args
);
844 SetEvent ((HANDLE
) event_id
);
845 CloseHandle ((HANDLE
) event_id
);
848 /* Handle DEBUG_STRING output from child process.
849 Cygwin prepends its messages with a "cygwin:". Interpret this as
850 a Cygwin signal. Otherwise just print the string as a warning. */
852 handle_output_debug_string (struct target_waitstatus
*ourstatus
)
857 if (!target_read_string
858 ((CORE_ADDR
) (uintptr_t) current_event
.u
.DebugString
.lpDebugStringData
,
862 else if (!startswith (s
, _CYGWIN_SIGNAL_STRING
))
865 if (!startswith (s
, "cYg"))
868 char *p
= strchr (s
, '\0');
870 if (p
> s
&& *--p
== '\n')
878 /* Got a cygwin signal marker. A cygwin signal is followed by
879 the signal number itself and then optionally followed by the
880 thread id and address to saved context within the DLL. If
881 these are supplied, then the given thread is assumed to have
882 issued the signal and the context from the thread is assumed
883 to be stored at the given address in the inferior. Tell gdb
884 to treat this like a real signal. */
886 int sig
= strtol (s
+ sizeof (_CYGWIN_SIGNAL_STRING
) - 1, &p
, 0);
887 gdb_signal gotasig
= gdb_signal_from_host (sig
);
889 ourstatus
->value
.sig
= gotasig
;
895 ourstatus
->kind
= TARGET_WAITKIND_STOPPED
;
896 retval
= strtoul (p
, &p
, 0);
898 retval
= main_thread_id
;
899 else if ((x
= (LPCVOID
) (uintptr_t) strtoull (p
, NULL
, 0))
900 && ReadProcessMemory (current_process_handle
, x
,
902 __COPY_CONTEXT_SIZE
, &n
)
903 && n
== __COPY_CONTEXT_SIZE
)
904 have_saved_context
= 1;
915 display_selector (HANDLE thread
, DWORD sel
)
918 if (GetThreadSelectorEntry (thread
, sel
, &info
))
921 printf_filtered ("0x%03x: ", (unsigned) sel
);
922 if (!info
.HighWord
.Bits
.Pres
)
924 puts_filtered ("Segment not present\n");
927 base
= (info
.HighWord
.Bits
.BaseHi
<< 24) +
928 (info
.HighWord
.Bits
.BaseMid
<< 16)
930 limit
= (info
.HighWord
.Bits
.LimitHi
<< 16) + info
.LimitLow
;
931 if (info
.HighWord
.Bits
.Granularity
)
932 limit
= (limit
<< 12) | 0xfff;
933 printf_filtered ("base=0x%08x limit=0x%08x", base
, limit
);
934 if (info
.HighWord
.Bits
.Default_Big
)
935 puts_filtered(" 32-bit ");
937 puts_filtered(" 16-bit ");
938 switch ((info
.HighWord
.Bits
.Type
& 0xf) >> 1)
941 puts_filtered ("Data (Read-Only, Exp-up");
944 puts_filtered ("Data (Read/Write, Exp-up");
947 puts_filtered ("Unused segment (");
950 puts_filtered ("Data (Read/Write, Exp-down");
953 puts_filtered ("Code (Exec-Only, N.Conf");
956 puts_filtered ("Code (Exec/Read, N.Conf");
959 puts_filtered ("Code (Exec-Only, Conf");
962 puts_filtered ("Code (Exec/Read, Conf");
965 printf_filtered ("Unknown type 0x%x",info
.HighWord
.Bits
.Type
);
967 if ((info
.HighWord
.Bits
.Type
& 0x1) == 0)
968 puts_filtered(", N.Acc");
969 puts_filtered (")\n");
970 if ((info
.HighWord
.Bits
.Type
& 0x10) == 0)
971 puts_filtered("System selector ");
972 printf_filtered ("Priviledge level = %d. ", info
.HighWord
.Bits
.Dpl
);
973 if (info
.HighWord
.Bits
.Granularity
)
974 puts_filtered ("Page granular.\n");
976 puts_filtered ("Byte granular.\n");
981 DWORD err
= GetLastError ();
982 if (err
== ERROR_NOT_SUPPORTED
)
983 printf_filtered ("Function not supported\n");
985 printf_filtered ("Invalid selector 0x%x.\n", (unsigned) sel
);
991 display_selectors (char * args
, int from_tty
)
995 puts_filtered ("Impossible to display selectors now.\n");
1001 puts_filtered ("Selector $cs\n");
1002 display_selector (current_thread
->h
,
1003 current_thread
->context
.SegCs
);
1004 puts_filtered ("Selector $ds\n");
1005 display_selector (current_thread
->h
,
1006 current_thread
->context
.SegDs
);
1007 puts_filtered ("Selector $es\n");
1008 display_selector (current_thread
->h
,
1009 current_thread
->context
.SegEs
);
1010 puts_filtered ("Selector $ss\n");
1011 display_selector (current_thread
->h
,
1012 current_thread
->context
.SegSs
);
1013 puts_filtered ("Selector $fs\n");
1014 display_selector (current_thread
->h
,
1015 current_thread
->context
.SegFs
);
1016 puts_filtered ("Selector $gs\n");
1017 display_selector (current_thread
->h
,
1018 current_thread
->context
.SegGs
);
1023 sel
= parse_and_eval_long (args
);
1024 printf_filtered ("Selector \"%s\"\n",args
);
1025 display_selector (current_thread
->h
, sel
);
1029 #define DEBUG_EXCEPTION_SIMPLE(x) if (debug_exceptions) \
1030 printf_unfiltered ("gdb: Target exception %s at %s\n", x, \
1031 host_address_to_string (\
1032 current_event.u.Exception.ExceptionRecord.ExceptionAddress))
1035 handle_exception (struct target_waitstatus
*ourstatus
)
1037 DWORD code
= current_event
.u
.Exception
.ExceptionRecord
.ExceptionCode
;
1039 ourstatus
->kind
= TARGET_WAITKIND_STOPPED
;
1041 /* Record the context of the current thread. */
1042 thread_rec (current_event
.dwThreadId
, -1);
1046 case EXCEPTION_ACCESS_VIOLATION
:
1047 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ACCESS_VIOLATION");
1048 ourstatus
->value
.sig
= GDB_SIGNAL_SEGV
;
1051 /* See if the access violation happened within the cygwin DLL
1052 itself. Cygwin uses a kind of exception handling to deal
1053 with passed-in invalid addresses. gdb should not treat
1054 these as real SEGVs since they will be silently handled by
1055 cygwin. A real SEGV will (theoretically) be caught by
1056 cygwin later in the process and will be sent as a
1057 cygwin-specific-signal. So, ignore SEGVs if they show up
1058 within the text segment of the DLL itself. */
1060 CORE_ADDR addr
= (CORE_ADDR
) (uintptr_t)
1061 current_event
.u
.Exception
.ExceptionRecord
.ExceptionAddress
;
1063 if ((!cygwin_exceptions
&& (addr
>= cygwin_load_start
1064 && addr
< cygwin_load_end
))
1065 || (find_pc_partial_function (addr
, &fn
, NULL
, NULL
)
1066 && startswith (fn
, "KERNEL32!IsBad")))
1071 case STATUS_STACK_OVERFLOW
:
1072 DEBUG_EXCEPTION_SIMPLE ("STATUS_STACK_OVERFLOW");
1073 ourstatus
->value
.sig
= GDB_SIGNAL_SEGV
;
1075 case STATUS_FLOAT_DENORMAL_OPERAND
:
1076 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DENORMAL_OPERAND");
1077 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1079 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED
:
1080 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ARRAY_BOUNDS_EXCEEDED");
1081 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1083 case STATUS_FLOAT_INEXACT_RESULT
:
1084 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INEXACT_RESULT");
1085 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1087 case STATUS_FLOAT_INVALID_OPERATION
:
1088 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INVALID_OPERATION");
1089 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1091 case STATUS_FLOAT_OVERFLOW
:
1092 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_OVERFLOW");
1093 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1095 case STATUS_FLOAT_STACK_CHECK
:
1096 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_STACK_CHECK");
1097 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1099 case STATUS_FLOAT_UNDERFLOW
:
1100 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_UNDERFLOW");
1101 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1103 case STATUS_FLOAT_DIVIDE_BY_ZERO
:
1104 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DIVIDE_BY_ZERO");
1105 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1107 case STATUS_INTEGER_DIVIDE_BY_ZERO
:
1108 DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_DIVIDE_BY_ZERO");
1109 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1111 case STATUS_INTEGER_OVERFLOW
:
1112 DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_OVERFLOW");
1113 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1115 case EXCEPTION_BREAKPOINT
:
1116 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_BREAKPOINT");
1117 ourstatus
->value
.sig
= GDB_SIGNAL_TRAP
;
1120 DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_C");
1121 ourstatus
->value
.sig
= GDB_SIGNAL_INT
;
1123 case DBG_CONTROL_BREAK
:
1124 DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_BREAK");
1125 ourstatus
->value
.sig
= GDB_SIGNAL_INT
;
1127 case EXCEPTION_SINGLE_STEP
:
1128 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_SINGLE_STEP");
1129 ourstatus
->value
.sig
= GDB_SIGNAL_TRAP
;
1131 case EXCEPTION_ILLEGAL_INSTRUCTION
:
1132 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ILLEGAL_INSTRUCTION");
1133 ourstatus
->value
.sig
= GDB_SIGNAL_ILL
;
1135 case EXCEPTION_PRIV_INSTRUCTION
:
1136 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_PRIV_INSTRUCTION");
1137 ourstatus
->value
.sig
= GDB_SIGNAL_ILL
;
1139 case EXCEPTION_NONCONTINUABLE_EXCEPTION
:
1140 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_NONCONTINUABLE_EXCEPTION");
1141 ourstatus
->value
.sig
= GDB_SIGNAL_ILL
;
1144 /* Treat unhandled first chance exceptions specially. */
1145 if (current_event
.u
.Exception
.dwFirstChance
)
1147 printf_unfiltered ("gdb: unknown target exception 0x%08x at %s\n",
1148 (unsigned) current_event
.u
.Exception
.ExceptionRecord
.ExceptionCode
,
1149 host_address_to_string (
1150 current_event
.u
.Exception
.ExceptionRecord
.ExceptionAddress
));
1151 ourstatus
->value
.sig
= GDB_SIGNAL_UNKNOWN
;
1155 last_sig
= ourstatus
->value
.sig
;
1159 /* Resume thread specified by ID, or all artificially suspended
1160 threads, if we are continuing execution. KILLED non-zero means we
1161 have killed the inferior, so we should ignore weird errors due to
1162 threads shutting down. */
1164 windows_continue (DWORD continue_status
, int id
, int killed
)
1167 windows_thread_info
*th
;
1170 DEBUG_EVENTS (("ContinueDebugEvent (cpid=%d, ctid=0x%x, %s);\n",
1171 (unsigned) current_event
.dwProcessId
,
1172 (unsigned) current_event
.dwThreadId
,
1173 continue_status
== DBG_CONTINUE
?
1174 "DBG_CONTINUE" : "DBG_EXCEPTION_NOT_HANDLED"));
1176 for (th
= &thread_head
; (th
= th
->next
) != NULL
;)
1177 if ((id
== -1 || id
== (int) th
->id
)
1180 if (debug_registers_changed
)
1182 th
->context
.ContextFlags
|= CONTEXT_DEBUG_REGISTERS
;
1183 th
->context
.Dr0
= dr
[0];
1184 th
->context
.Dr1
= dr
[1];
1185 th
->context
.Dr2
= dr
[2];
1186 th
->context
.Dr3
= dr
[3];
1187 th
->context
.Dr6
= DR6_CLEAR_VALUE
;
1188 th
->context
.Dr7
= dr
[7];
1190 if (th
->context
.ContextFlags
)
1194 if (GetExitCodeThread (th
->h
, &ec
)
1195 && ec
== STILL_ACTIVE
)
1197 BOOL status
= SetThreadContext (th
->h
, &th
->context
);
1202 th
->context
.ContextFlags
= 0;
1204 if (th
->suspended
> 0)
1205 (void) ResumeThread (th
->h
);
1209 res
= ContinueDebugEvent (current_event
.dwProcessId
,
1210 current_event
.dwThreadId
,
1214 error (_("Failed to resume program execution"
1215 " (ContinueDebugEvent failed, error %u)"),
1216 (unsigned int) GetLastError ());
1218 debug_registers_changed
= 0;
1222 /* Called in pathological case where Windows fails to send a
1223 CREATE_PROCESS_DEBUG_EVENT after an attach. */
1225 fake_create_process (void)
1227 current_process_handle
= OpenProcess (PROCESS_ALL_ACCESS
, FALSE
,
1228 current_event
.dwProcessId
);
1229 if (current_process_handle
!= NULL
)
1230 open_process_used
= 1;
1233 error (_("OpenProcess call failed, GetLastError = %u"),
1234 (unsigned) GetLastError ());
1235 /* We can not debug anything in that case. */
1237 main_thread_id
= current_event
.dwThreadId
;
1238 current_thread
= windows_add_thread (
1239 ptid_build (current_event
.dwProcessId
, 0,
1240 current_event
.dwThreadId
),
1241 current_event
.u
.CreateThread
.hThread
,
1242 current_event
.u
.CreateThread
.lpThreadLocalBase
);
1243 return main_thread_id
;
1247 windows_resume (struct target_ops
*ops
,
1248 ptid_t ptid
, int step
, enum gdb_signal sig
)
1250 windows_thread_info
*th
;
1251 DWORD continue_status
= DBG_CONTINUE
;
1253 /* A specific PTID means `step only this thread id'. */
1254 int resume_all
= ptid_equal (ptid
, minus_one_ptid
);
1256 /* If we're continuing all threads, it's the current inferior that
1257 should be handled specially. */
1259 ptid
= inferior_ptid
;
1261 if (sig
!= GDB_SIGNAL_0
)
1263 if (current_event
.dwDebugEventCode
!= EXCEPTION_DEBUG_EVENT
)
1265 DEBUG_EXCEPT(("Cannot continue with signal %d here.\n",sig
));
1267 else if (sig
== last_sig
)
1268 continue_status
= DBG_EXCEPTION_NOT_HANDLED
;
1271 /* This code does not seem to work, because
1272 the kernel does probably not consider changes in the ExceptionRecord
1273 structure when passing the exception to the inferior.
1274 Note that this seems possible in the exception handler itself. */
1277 for (i
= 0; xlate
[i
].them
!= -1; i
++)
1278 if (xlate
[i
].us
== sig
)
1280 current_event
.u
.Exception
.ExceptionRecord
.ExceptionCode
1282 continue_status
= DBG_EXCEPTION_NOT_HANDLED
;
1285 if (continue_status
== DBG_CONTINUE
)
1287 DEBUG_EXCEPT(("Cannot continue with signal %d.\n",sig
));
1291 DEBUG_EXCEPT(("Can only continue with received signal %d.\n",
1295 last_sig
= GDB_SIGNAL_0
;
1297 DEBUG_EXEC (("gdb: windows_resume (pid=%d, tid=%ld, step=%d, sig=%d);\n",
1298 ptid_get_pid (ptid
), ptid_get_tid (ptid
), step
, sig
));
1300 /* Get context for currently selected thread. */
1301 th
= thread_rec (ptid_get_tid (inferior_ptid
), FALSE
);
1306 /* Single step by setting t bit. */
1307 struct regcache
*regcache
= get_current_regcache ();
1308 struct gdbarch
*gdbarch
= get_regcache_arch (regcache
);
1309 windows_fetch_inferior_registers (ops
, regcache
,
1310 gdbarch_ps_regnum (gdbarch
));
1311 th
->context
.EFlags
|= FLAG_TRACE_BIT
;
1314 if (th
->context
.ContextFlags
)
1316 if (debug_registers_changed
)
1318 th
->context
.Dr0
= dr
[0];
1319 th
->context
.Dr1
= dr
[1];
1320 th
->context
.Dr2
= dr
[2];
1321 th
->context
.Dr3
= dr
[3];
1322 th
->context
.Dr6
= DR6_CLEAR_VALUE
;
1323 th
->context
.Dr7
= dr
[7];
1325 CHECK (SetThreadContext (th
->h
, &th
->context
));
1326 th
->context
.ContextFlags
= 0;
1330 /* Allow continuing with the same signal that interrupted us.
1331 Otherwise complain. */
1334 windows_continue (continue_status
, -1, 0);
1336 windows_continue (continue_status
, ptid_get_tid (ptid
), 0);
1339 /* Ctrl-C handler used when the inferior is not run in the same console. The
1340 handler is in charge of interrupting the inferior using DebugBreakProcess.
1341 Note that this function is not available prior to Windows XP. In this case
1342 we emit a warning. */
1344 ctrl_c_handler (DWORD event_type
)
1346 const int attach_flag
= current_inferior ()->attach_flag
;
1348 /* Only handle Ctrl-C and Ctrl-Break events. Ignore others. */
1349 if (event_type
!= CTRL_C_EVENT
&& event_type
!= CTRL_BREAK_EVENT
)
1352 /* If the inferior and the debugger share the same console, do nothing as
1353 the inferior has also received the Ctrl-C event. */
1354 if (!new_console
&& !attach_flag
)
1357 if (!DebugBreakProcess (current_process_handle
))
1358 warning (_("Could not interrupt program. "
1359 "Press Ctrl-c in the program console."));
1361 /* Return true to tell that Ctrl-C has been handled. */
1365 /* Get the next event from the child. Returns a non-zero thread id if the event
1366 requires handling by WFI (or whatever). */
1368 get_windows_debug_event (struct target_ops
*ops
,
1369 int pid
, struct target_waitstatus
*ourstatus
)
1372 DWORD continue_status
, event_code
;
1373 windows_thread_info
*th
;
1374 static windows_thread_info dummy_thread_info
;
1375 DWORD thread_id
= 0;
1377 last_sig
= GDB_SIGNAL_0
;
1379 if (!(debug_event
= WaitForDebugEvent (¤t_event
, 1000)))
1383 continue_status
= DBG_CONTINUE
;
1385 event_code
= current_event
.dwDebugEventCode
;
1386 ourstatus
->kind
= TARGET_WAITKIND_SPURIOUS
;
1388 have_saved_context
= 0;
1392 case CREATE_THREAD_DEBUG_EVENT
:
1393 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1394 (unsigned) current_event
.dwProcessId
,
1395 (unsigned) current_event
.dwThreadId
,
1396 "CREATE_THREAD_DEBUG_EVENT"));
1397 if (saw_create
!= 1)
1399 struct inferior
*inf
;
1400 inf
= find_inferior_pid (current_event
.dwProcessId
);
1401 if (!saw_create
&& inf
->attach_flag
)
1403 /* Kludge around a Windows bug where first event is a create
1404 thread event. Caused when attached process does not have
1406 thread_id
= fake_create_process ();
1412 /* Record the existence of this thread. */
1413 thread_id
= current_event
.dwThreadId
;
1414 th
= windows_add_thread (ptid_build (current_event
.dwProcessId
, 0,
1415 current_event
.dwThreadId
),
1416 current_event
.u
.CreateThread
.hThread
,
1417 current_event
.u
.CreateThread
.lpThreadLocalBase
);
1421 case EXIT_THREAD_DEBUG_EVENT
:
1422 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1423 (unsigned) current_event
.dwProcessId
,
1424 (unsigned) current_event
.dwThreadId
,
1425 "EXIT_THREAD_DEBUG_EVENT"));
1427 if (current_event
.dwThreadId
!= main_thread_id
)
1429 windows_delete_thread (ptid_build (current_event
.dwProcessId
, 0,
1430 current_event
.dwThreadId
),
1431 current_event
.u
.ExitThread
.dwExitCode
);
1432 th
= &dummy_thread_info
;
1436 case CREATE_PROCESS_DEBUG_EVENT
:
1437 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1438 (unsigned) current_event
.dwProcessId
,
1439 (unsigned) current_event
.dwThreadId
,
1440 "CREATE_PROCESS_DEBUG_EVENT"));
1441 CloseHandle (current_event
.u
.CreateProcessInfo
.hFile
);
1442 if (++saw_create
!= 1)
1445 current_process_handle
= current_event
.u
.CreateProcessInfo
.hProcess
;
1447 windows_delete_thread (ptid_build (current_event
.dwProcessId
, 0,
1450 main_thread_id
= current_event
.dwThreadId
;
1451 /* Add the main thread. */
1452 th
= windows_add_thread (ptid_build (current_event
.dwProcessId
, 0,
1453 current_event
.dwThreadId
),
1454 current_event
.u
.CreateProcessInfo
.hThread
,
1455 current_event
.u
.CreateProcessInfo
.lpThreadLocalBase
);
1456 thread_id
= current_event
.dwThreadId
;
1459 case EXIT_PROCESS_DEBUG_EVENT
:
1460 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1461 (unsigned) current_event
.dwProcessId
,
1462 (unsigned) current_event
.dwThreadId
,
1463 "EXIT_PROCESS_DEBUG_EVENT"));
1464 if (!windows_initialization_done
)
1466 target_terminal_ours ();
1467 target_mourn_inferior ();
1468 error (_("During startup program exited with code 0x%x."),
1469 (unsigned int) current_event
.u
.ExitProcess
.dwExitCode
);
1471 else if (saw_create
== 1)
1473 ourstatus
->kind
= TARGET_WAITKIND_EXITED
;
1474 ourstatus
->value
.integer
= current_event
.u
.ExitProcess
.dwExitCode
;
1475 thread_id
= main_thread_id
;
1479 case LOAD_DLL_DEBUG_EVENT
:
1480 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1481 (unsigned) current_event
.dwProcessId
,
1482 (unsigned) current_event
.dwThreadId
,
1483 "LOAD_DLL_DEBUG_EVENT"));
1484 CloseHandle (current_event
.u
.LoadDll
.hFile
);
1485 if (saw_create
!= 1 || ! windows_initialization_done
)
1487 catch_errors (handle_load_dll
, NULL
, (char *) "", RETURN_MASK_ALL
);
1488 ourstatus
->kind
= TARGET_WAITKIND_LOADED
;
1489 ourstatus
->value
.integer
= 0;
1490 thread_id
= main_thread_id
;
1493 case UNLOAD_DLL_DEBUG_EVENT
:
1494 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1495 (unsigned) current_event
.dwProcessId
,
1496 (unsigned) current_event
.dwThreadId
,
1497 "UNLOAD_DLL_DEBUG_EVENT"));
1498 if (saw_create
!= 1 || ! windows_initialization_done
)
1500 catch_errors (handle_unload_dll
, NULL
, (char *) "", RETURN_MASK_ALL
);
1501 ourstatus
->kind
= TARGET_WAITKIND_LOADED
;
1502 ourstatus
->value
.integer
= 0;
1503 thread_id
= main_thread_id
;
1506 case EXCEPTION_DEBUG_EVENT
:
1507 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1508 (unsigned) current_event
.dwProcessId
,
1509 (unsigned) current_event
.dwThreadId
,
1510 "EXCEPTION_DEBUG_EVENT"));
1511 if (saw_create
!= 1)
1513 if (handle_exception (ourstatus
))
1514 thread_id
= current_event
.dwThreadId
;
1516 continue_status
= DBG_EXCEPTION_NOT_HANDLED
;
1519 case OUTPUT_DEBUG_STRING_EVENT
: /* Message from the kernel. */
1520 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1521 (unsigned) current_event
.dwProcessId
,
1522 (unsigned) current_event
.dwThreadId
,
1523 "OUTPUT_DEBUG_STRING_EVENT"));
1524 if (saw_create
!= 1)
1526 thread_id
= handle_output_debug_string (ourstatus
);
1530 if (saw_create
!= 1)
1532 printf_unfiltered ("gdb: kernel event for pid=%u tid=0x%x\n",
1533 (unsigned) current_event
.dwProcessId
,
1534 (unsigned) current_event
.dwThreadId
);
1535 printf_unfiltered (" unknown event code %u\n",
1536 (unsigned) current_event
.dwDebugEventCode
);
1540 if (!thread_id
|| saw_create
!= 1)
1542 CHECK (windows_continue (continue_status
, -1, 0));
1546 inferior_ptid
= ptid_build (current_event
.dwProcessId
, 0,
1548 current_thread
= th
;
1549 if (!current_thread
)
1550 current_thread
= thread_rec (thread_id
, TRUE
);
1557 /* Wait for interesting events to occur in the target process. */
1559 windows_wait (struct target_ops
*ops
,
1560 ptid_t ptid
, struct target_waitstatus
*ourstatus
, int options
)
1564 target_terminal_ours ();
1566 /* We loop when we get a non-standard exception rather than return
1567 with a SPURIOUS because resume can try and step or modify things,
1568 which needs a current_thread->h. But some of these exceptions mark
1569 the birth or death of threads, which mean that the current thread
1570 isn't necessarily what you think it is. */
1576 /* If the user presses Ctrl-c while the debugger is waiting
1577 for an event, he expects the debugger to interrupt his program
1578 and to get the prompt back. There are two possible situations:
1580 - The debugger and the program do not share the console, in
1581 which case the Ctrl-c event only reached the debugger.
1582 In that case, the ctrl_c handler will take care of interrupting
1583 the inferior. Note that this case is working starting with
1584 Windows XP. For Windows 2000, Ctrl-C should be pressed in the
1587 - The debugger and the program share the same console, in which
1588 case both debugger and inferior will receive the Ctrl-c event.
1589 In that case the ctrl_c handler will ignore the event, as the
1590 Ctrl-c event generated inside the inferior will trigger the
1591 expected debug event.
1593 FIXME: brobecker/2008-05-20: If the inferior receives the
1594 signal first and the delay until GDB receives that signal
1595 is sufficiently long, GDB can sometimes receive the SIGINT
1596 after we have unblocked the CTRL+C handler. This would
1597 lead to the debugger stopping prematurely while handling
1598 the new-thread event that comes with the handling of the SIGINT
1599 inside the inferior, and then stop again immediately when
1600 the user tries to resume the execution in the inferior.
1601 This is a classic race that we should try to fix one day. */
1602 SetConsoleCtrlHandler (&ctrl_c_handler
, TRUE
);
1603 retval
= get_windows_debug_event (ops
, pid
, ourstatus
);
1604 SetConsoleCtrlHandler (&ctrl_c_handler
, FALSE
);
1607 return ptid_build (current_event
.dwProcessId
, 0, retval
);
1612 if (deprecated_ui_loop_hook
!= NULL
)
1613 detach
= deprecated_ui_loop_hook (0);
1616 windows_kill_inferior (ops
);
1621 /* Iterate over all DLLs currently mapped by our inferior, and
1622 add them to our list of solibs. */
1625 windows_add_all_dlls (void)
1628 HMODULE dummy_hmodule
;
1633 if (EnumProcessModules (current_process_handle
, &dummy_hmodule
,
1634 sizeof (HMODULE
), &cb_needed
) == 0)
1640 hmodules
= (HMODULE
*) alloca (cb_needed
);
1641 if (EnumProcessModules (current_process_handle
, hmodules
,
1642 cb_needed
, &cb_needed
) == 0)
1645 for (i
= 1; i
< (int) (cb_needed
/ sizeof (HMODULE
)); i
++)
1649 wchar_t dll_name
[__PMAX
];
1652 char dll_name
[__PMAX
];
1655 if (GetModuleInformation (current_process_handle
, hmodules
[i
],
1656 &mi
, sizeof (mi
)) == 0)
1658 if (GetModuleFileNameEx (current_process_handle
, hmodules
[i
],
1659 dll_name
, sizeof (dll_name
)) == 0)
1662 wcstombs (name
, dll_name
, __PMAX
);
1667 solib_end
->next
= windows_make_so (name
, mi
.lpBaseOfDll
);
1668 solib_end
= solib_end
->next
;
1673 do_initial_windows_stuff (struct target_ops
*ops
, DWORD pid
, int attaching
)
1676 struct inferior
*inf
;
1677 struct thread_info
*tp
;
1679 last_sig
= GDB_SIGNAL_0
;
1681 exception_count
= 0;
1682 open_process_used
= 0;
1683 debug_registers_changed
= 0;
1684 debug_registers_used
= 0;
1685 for (i
= 0; i
< sizeof (dr
) / sizeof (dr
[0]); i
++)
1688 cygwin_load_start
= cygwin_load_end
= 0;
1690 current_event
.dwProcessId
= pid
;
1691 memset (¤t_event
, 0, sizeof (current_event
));
1692 if (!target_is_pushed (ops
))
1694 disable_breakpoints_in_shlibs ();
1695 windows_clear_solib ();
1696 clear_proceed_status (0);
1697 init_wait_for_inferior ();
1699 inf
= current_inferior ();
1700 inferior_appeared (inf
, pid
);
1701 inf
->attach_flag
= attaching
;
1703 /* Make the new process the current inferior, so terminal handling
1704 can rely on it. When attaching, we don't know about any thread
1705 id here, but that's OK --- nothing should be referencing the
1706 current thread until we report an event out of windows_wait. */
1707 inferior_ptid
= pid_to_ptid (pid
);
1709 target_terminal_init ();
1710 target_terminal_inferior ();
1712 windows_initialization_done
= 0;
1716 struct target_waitstatus status
;
1718 windows_wait (ops
, minus_one_ptid
, &status
, 0);
1720 /* Note windows_wait returns TARGET_WAITKIND_SPURIOUS for thread
1722 if (status
.kind
!= TARGET_WAITKIND_LOADED
1723 && status
.kind
!= TARGET_WAITKIND_SPURIOUS
)
1726 windows_resume (ops
, minus_one_ptid
, 0, GDB_SIGNAL_0
);
1729 /* Now that the inferior has been started and all DLLs have been mapped,
1730 we can iterate over all DLLs and load them in.
1732 We avoid doing it any earlier because, on certain versions of Windows,
1733 LOAD_DLL_DEBUG_EVENTs are sometimes not complete. In particular,
1734 we have seen on Windows 8.1 that the ntdll.dll load event does not
1735 include the DLL name, preventing us from creating an associated SO.
1736 A possible explanation is that ntdll.dll might be mapped before
1737 the SO info gets created by the Windows system -- ntdll.dll is
1738 the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs
1739 do not seem to suffer from that problem.
1741 Rather than try to work around this sort of issue, it is much
1742 simpler to just ignore DLL load/unload events during the startup
1743 phase, and then process them all in one batch now. */
1744 windows_add_all_dlls ();
1746 windows_initialization_done
= 1;
1750 /* Try to set or remove a user privilege to the current process. Return -1
1751 if that fails, the previous setting of that privilege otherwise.
1753 This code is copied from the Cygwin source code and rearranged to allow
1754 dynamically loading of the needed symbols from advapi32 which is only
1755 available on NT/2K/XP. */
1757 set_process_privilege (const char *privilege
, BOOL enable
)
1759 HANDLE token_hdl
= NULL
;
1761 TOKEN_PRIVILEGES new_priv
, orig_priv
;
1765 if (!OpenProcessToken (GetCurrentProcess (),
1766 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
1770 if (!LookupPrivilegeValueA (NULL
, privilege
, &restore_priv
))
1773 new_priv
.PrivilegeCount
= 1;
1774 new_priv
.Privileges
[0].Luid
= restore_priv
;
1775 new_priv
.Privileges
[0].Attributes
= enable
? SE_PRIVILEGE_ENABLED
: 0;
1777 if (!AdjustTokenPrivileges (token_hdl
, FALSE
, &new_priv
,
1778 sizeof orig_priv
, &orig_priv
, &size
))
1781 /* Disabled, otherwise every `attach' in an unprivileged user session
1782 would raise the "Failed to get SE_DEBUG_NAME privilege" warning in
1783 windows_attach(). */
1784 /* AdjustTokenPrivileges returns TRUE even if the privilege could not
1785 be enabled. GetLastError () returns an correct error code, though. */
1786 if (enable
&& GetLastError () == ERROR_NOT_ALL_ASSIGNED
)
1790 ret
= orig_priv
.Privileges
[0].Attributes
== SE_PRIVILEGE_ENABLED
? 1 : 0;
1794 CloseHandle (token_hdl
);
1799 /* Attach to process PID, then initialize for debugging it. */
1801 windows_attach (struct target_ops
*ops
, const char *args
, int from_tty
)
1806 pid
= parse_pid_to_attach (args
);
1808 if (set_process_privilege (SE_DEBUG_NAME
, TRUE
) < 0)
1810 printf_unfiltered ("Warning: Failed to get SE_DEBUG_NAME privilege\n");
1811 printf_unfiltered ("This can cause attach to "
1812 "fail on Windows NT/2K/XP\n");
1815 windows_init_thread_list ();
1816 ok
= DebugActiveProcess (pid
);
1822 /* Try fall back to Cygwin pid. */
1823 pid
= cygwin_internal (CW_CYGWIN_PID_TO_WINPID
, pid
);
1826 ok
= DebugActiveProcess (pid
);
1831 error (_("Can't attach to process."));
1833 DebugSetProcessKillOnExit (FALSE
);
1837 char *exec_file
= (char *) get_exec_file (0);
1840 printf_unfiltered ("Attaching to program `%s', %s\n", exec_file
,
1841 target_pid_to_str (pid_to_ptid (pid
)));
1843 printf_unfiltered ("Attaching to %s\n",
1844 target_pid_to_str (pid_to_ptid (pid
)));
1846 gdb_flush (gdb_stdout
);
1849 do_initial_windows_stuff (ops
, pid
, 1);
1850 target_terminal_ours ();
1854 windows_detach (struct target_ops
*ops
, const char *args
, int from_tty
)
1859 windows_resume (ops
, ptid
, 0, GDB_SIGNAL_0
);
1861 if (!DebugActiveProcessStop (current_event
.dwProcessId
))
1863 error (_("Can't detach process %u (error %u)"),
1864 (unsigned) current_event
.dwProcessId
, (unsigned) GetLastError ());
1867 DebugSetProcessKillOnExit (FALSE
);
1869 if (detached
&& from_tty
)
1871 char *exec_file
= get_exec_file (0);
1874 printf_unfiltered ("Detaching from program: %s, Pid %u\n", exec_file
,
1875 (unsigned) current_event
.dwProcessId
);
1876 gdb_flush (gdb_stdout
);
1879 x86_cleanup_dregs ();
1880 inferior_ptid
= null_ptid
;
1881 detach_inferior (current_event
.dwProcessId
);
1883 inf_child_maybe_unpush_target (ops
);
1886 /* Try to determine the executable filename.
1888 EXE_NAME_RET is a pointer to a buffer whose size is EXE_NAME_MAX_LEN.
1890 Upon success, the filename is stored inside EXE_NAME_RET, and
1891 this function returns nonzero.
1893 Otherwise, this function returns zero and the contents of
1894 EXE_NAME_RET is undefined. */
1897 windows_get_exec_module_filename (char *exe_name_ret
, size_t exe_name_max_len
)
1904 if (!EnumProcessModules (current_process_handle
, &dh_buf
,
1905 sizeof (HMODULE
), &cbNeeded
) || !cbNeeded
)
1908 /* We know the executable is always first in the list of modules,
1909 which we just fetched. So no need to fetch more. */
1913 /* Cygwin prefers that the path be in /x/y/z format, so extract
1914 the filename into a temporary buffer first, and then convert it
1915 to POSIX format into the destination buffer. */
1916 cygwin_buf_t
*pathbuf
= (cygwin_buf_t
*) alloca (exe_name_max_len
* sizeof (cygwin_buf_t
));
1918 len
= GetModuleFileNameEx (current_process_handle
,
1919 dh_buf
, pathbuf
, exe_name_max_len
);
1921 error (_("Error getting executable filename: %u."),
1922 (unsigned) GetLastError ());
1923 if (cygwin_conv_path (CCP_WIN_W_TO_POSIX
, pathbuf
, exe_name_ret
,
1924 exe_name_max_len
) < 0)
1925 error (_("Error converting executable filename to POSIX: %d."), errno
);
1928 len
= GetModuleFileNameEx (current_process_handle
,
1929 dh_buf
, exe_name_ret
, exe_name_max_len
);
1931 error (_("Error getting executable filename: %u."),
1932 (unsigned) GetLastError ());
1935 return 1; /* success */
1938 /* The pid_to_exec_file target_ops method for this platform. */
1941 windows_pid_to_exec_file (struct target_ops
*self
, int pid
)
1943 static char path
[__PMAX
];
1945 /* Try to find exe name as symlink target of /proc/<pid>/exe. */
1947 char procexe
[sizeof ("/proc/4294967295/exe")];
1949 xsnprintf (procexe
, sizeof (procexe
), "/proc/%u/exe", pid
);
1950 nchars
= readlink (procexe
, path
, sizeof(path
));
1951 if (nchars
> 0 && nchars
< sizeof (path
))
1953 path
[nchars
] = '\0'; /* Got it */
1958 /* If we get here then either Cygwin is hosed, this isn't a Cygwin version
1959 of gdb, or we're trying to debug a non-Cygwin windows executable. */
1960 if (!windows_get_exec_module_filename (path
, sizeof (path
)))
1966 /* Print status information about what we're accessing. */
1969 windows_files_info (struct target_ops
*ignore
)
1971 struct inferior
*inf
= current_inferior ();
1973 printf_unfiltered ("\tUsing the running image of %s %s.\n",
1974 inf
->attach_flag
? "attached" : "child",
1975 target_pid_to_str (inferior_ptid
));
1978 /* Modify CreateProcess parameters for use of a new separate console.
1980 *FLAGS: DWORD parameter for general process creation flags.
1981 *SI: STARTUPINFO structure, for which the console window size and
1982 console buffer size is filled in if GDB is running in a console.
1983 to create the new console.
1984 The size of the used font is not available on all versions of
1985 Windows OS. Furthermore, the current font might not be the default
1986 font, but this is still better than before.
1987 If the windows and buffer sizes are computed,
1988 SI->DWFLAGS is changed so that this information is used
1989 by CreateProcess function. */
1992 windows_set_console_info (STARTUPINFO
*si
, DWORD
*flags
)
1994 HANDLE hconsole
= CreateFile ("CONOUT$", GENERIC_READ
| GENERIC_WRITE
,
1995 FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, 0, 0);
1997 if (hconsole
!= INVALID_HANDLE_VALUE
)
1999 CONSOLE_SCREEN_BUFFER_INFO sbinfo
;
2001 CONSOLE_FONT_INFO cfi
;
2003 GetCurrentConsoleFont (hconsole
, FALSE
, &cfi
);
2004 font_size
= GetConsoleFontSize (hconsole
, cfi
.nFont
);
2005 GetConsoleScreenBufferInfo(hconsole
, &sbinfo
);
2006 si
->dwXSize
= sbinfo
.srWindow
.Right
- sbinfo
.srWindow
.Left
+ 1;
2007 si
->dwYSize
= sbinfo
.srWindow
.Bottom
- sbinfo
.srWindow
.Top
+ 1;
2009 si
->dwXSize
*= font_size
.X
;
2013 si
->dwYSize
*= font_size
.Y
;
2016 si
->dwXCountChars
= sbinfo
.dwSize
.X
;
2017 si
->dwYCountChars
= sbinfo
.dwSize
.Y
;
2018 si
->dwFlags
|= STARTF_USESIZE
| STARTF_USECOUNTCHARS
;
2020 *flags
|= CREATE_NEW_CONSOLE
;
2024 /* Function called by qsort to sort environment strings. */
2027 envvar_cmp (const void *a
, const void *b
)
2029 const char **p
= (const char **) a
;
2030 const char **q
= (const char **) b
;
2031 return strcasecmp (*p
, *q
);
2037 clear_win32_environment (char **env
)
2041 wchar_t *copy
= NULL
, *equalpos
;
2043 for (i
= 0; env
[i
] && *env
[i
]; i
++)
2045 len
= mbstowcs (NULL
, env
[i
], 0) + 1;
2046 copy
= (wchar_t *) xrealloc (copy
, len
* sizeof (wchar_t));
2047 mbstowcs (copy
, env
[i
], len
);
2048 equalpos
= wcschr (copy
, L
'=');
2051 SetEnvironmentVariableW (copy
, NULL
);
2057 /* Start an inferior windows child process and sets inferior_ptid to its pid.
2058 EXEC_FILE is the file to run.
2059 ALLARGS is a string containing the arguments to the program.
2060 ENV is the environment vector to pass. Errors reported with error(). */
2063 windows_create_inferior (struct target_ops
*ops
, char *exec_file
,
2064 char *allargs
, char **in_env
, int from_tty
)
2068 cygwin_buf_t real_path
[__PMAX
];
2069 cygwin_buf_t shell
[__PMAX
]; /* Path to shell */
2071 cygwin_buf_t
*toexec
;
2072 cygwin_buf_t
*cygallargs
;
2074 char **old_env
= NULL
;
2078 int ostdin
, ostdout
, ostderr
;
2080 char real_path
[__PMAX
];
2081 char shell
[__PMAX
]; /* Path to shell */
2093 PROCESS_INFORMATION pi
;
2096 const char *inferior_io_terminal
= get_inferior_io_terminal ();
2099 error (_("No executable specified, use `target exec'."));
2101 memset (&si
, 0, sizeof (si
));
2102 si
.cb
= sizeof (si
);
2105 flags
|= CREATE_NEW_PROCESS_GROUP
;
2108 windows_set_console_info (&si
, &flags
);
2113 flags
|= DEBUG_ONLY_THIS_PROCESS
;
2114 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W
, exec_file
, real_path
,
2115 __PMAX
* sizeof (cygwin_buf_t
)) < 0)
2116 error (_("Error starting executable: %d"), errno
);
2119 len
= mbstowcs (NULL
, allargs
, 0) + 1;
2120 if (len
== (size_t) -1)
2121 error (_("Error starting executable: %d"), errno
);
2122 cygallargs
= (wchar_t *) alloca (len
* sizeof (wchar_t));
2123 mbstowcs (cygallargs
, allargs
, len
);
2125 cygallargs
= allargs
;
2130 sh
= getenv ("SHELL");
2133 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W
, sh
, shell
, __PMAX
) < 0)
2134 error (_("Error starting executable via shell: %d"), errno
);
2136 len
= sizeof (L
" -c 'exec '") + mbstowcs (NULL
, exec_file
, 0)
2137 + mbstowcs (NULL
, allargs
, 0) + 2;
2138 cygallargs
= (wchar_t *) alloca (len
* sizeof (wchar_t));
2139 swprintf (cygallargs
, len
, L
" -c 'exec %s %s'", exec_file
, allargs
);
2141 len
= (sizeof (" -c 'exec '") + strlen (exec_file
)
2142 + strlen (allargs
) + 2);
2143 cygallargs
= (char *) alloca (len
);
2144 xsnprintf (cygallargs
, len
, " -c 'exec %s %s'", exec_file
, allargs
);
2147 flags
|= DEBUG_PROCESS
;
2151 args
= (cygwin_buf_t
*) alloca ((wcslen (toexec
) + wcslen (cygallargs
) + 2)
2152 * sizeof (wchar_t));
2153 wcscpy (args
, toexec
);
2154 wcscat (args
, L
" ");
2155 wcscat (args
, cygallargs
);
2157 args
= (cygwin_buf_t
*) alloca (strlen (toexec
) + strlen (cygallargs
) + 2);
2158 strcpy (args
, toexec
);
2160 strcat (args
, cygallargs
);
2163 #ifdef CW_CVT_ENV_TO_WINENV
2164 /* First try to create a direct Win32 copy of the POSIX environment. */
2165 w32_env
= (PWCHAR
) cygwin_internal (CW_CVT_ENV_TO_WINENV
, in_env
);
2166 if (w32_env
!= (PWCHAR
) -1)
2167 flags
|= CREATE_UNICODE_ENVIRONMENT
;
2169 /* If that fails, fall back to old method tweaking GDB's environment. */
2172 /* Reset all Win32 environment variables to avoid leftover on next run. */
2173 clear_win32_environment (environ
);
2174 /* Prepare the environment vars for CreateProcess. */
2177 cygwin_internal (CW_SYNC_WINENV
);
2181 if (!inferior_io_terminal
)
2182 tty
= ostdin
= ostdout
= ostderr
= -1;
2185 tty
= open (inferior_io_terminal
, O_RDWR
| O_NOCTTY
);
2188 print_sys_errmsg (inferior_io_terminal
, errno
);
2189 ostdin
= ostdout
= ostderr
= -1;
2202 windows_init_thread_list ();
2203 ret
= CreateProcess (0,
2204 args
, /* command line */
2205 NULL
, /* Security */
2207 TRUE
, /* inherit handles */
2208 flags
, /* start flags */
2209 w32_env
, /* environment */
2210 NULL
, /* current directory */
2214 /* Just free the Win32 environment, if it could be created. */
2218 /* Reset all environment variables to avoid leftover on next run. */
2219 clear_win32_environment (in_env
);
2220 /* Restore normal GDB environment variables. */
2222 cygwin_internal (CW_SYNC_WINENV
);
2237 /* Build the command line, a space-separated list of tokens where
2238 the first token is the name of the module to be executed.
2239 To avoid ambiguities introduced by spaces in the module name,
2241 args_len
= strlen (toexec
) + 2 /* quotes */ + strlen (allargs
) + 2;
2242 args
= (char *) alloca (args_len
);
2243 xsnprintf (args
, args_len
, "\"%s\" %s", toexec
, allargs
);
2245 flags
|= DEBUG_ONLY_THIS_PROCESS
;
2247 if (!inferior_io_terminal
)
2248 tty
= INVALID_HANDLE_VALUE
;
2251 SECURITY_ATTRIBUTES sa
;
2252 sa
.nLength
= sizeof(sa
);
2253 sa
.lpSecurityDescriptor
= 0;
2254 sa
.bInheritHandle
= TRUE
;
2255 tty
= CreateFileA (inferior_io_terminal
, GENERIC_READ
| GENERIC_WRITE
,
2256 0, &sa
, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
2257 if (tty
== INVALID_HANDLE_VALUE
)
2258 warning (_("Warning: Failed to open TTY %s, error %#x."),
2259 inferior_io_terminal
, (unsigned) GetLastError ());
2263 si
.hStdOutput
= tty
;
2265 si
.dwFlags
|= STARTF_USESTDHANDLES
;
2269 /* CreateProcess takes the environment list as a null terminated set of
2270 strings (i.e. two nulls terminate the list). */
2272 /* Get total size for env strings. */
2273 for (envlen
= 0, i
= 0; in_env
[i
] && *in_env
[i
]; i
++)
2274 envlen
+= strlen (in_env
[i
]) + 1;
2276 envsize
= sizeof (in_env
[0]) * (i
+ 1);
2277 env
= (char **) alloca (envsize
);
2278 memcpy (env
, in_env
, envsize
);
2279 /* Windows programs expect the environment block to be sorted. */
2280 qsort (env
, i
, sizeof (char *), envvar_cmp
);
2282 w32env
= (char *) alloca (envlen
+ 1);
2284 /* Copy env strings into new buffer. */
2285 for (temp
= w32env
, i
= 0; env
[i
] && *env
[i
]; i
++)
2287 strcpy (temp
, env
[i
]);
2288 temp
+= strlen (temp
) + 1;
2291 /* Final nil string to terminate new env. */
2294 windows_init_thread_list ();
2295 ret
= CreateProcessA (0,
2296 args
, /* command line */
2297 NULL
, /* Security */
2299 TRUE
, /* inherit handles */
2300 flags
, /* start flags */
2301 w32env
, /* environment */
2302 NULL
, /* current directory */
2305 if (tty
!= INVALID_HANDLE_VALUE
)
2310 error (_("Error creating process %s, (error %u)."),
2311 exec_file
, (unsigned) GetLastError ());
2313 CloseHandle (pi
.hThread
);
2314 CloseHandle (pi
.hProcess
);
2316 if (useshell
&& shell
[0] != '\0')
2321 do_initial_windows_stuff (ops
, pi
.dwProcessId
, 0);
2323 /* windows_continue (DBG_CONTINUE, -1, 0); */
2327 windows_mourn_inferior (struct target_ops
*ops
)
2329 (void) windows_continue (DBG_CONTINUE
, -1, 0);
2330 x86_cleanup_dregs();
2331 if (open_process_used
)
2333 CHECK (CloseHandle (current_process_handle
));
2334 open_process_used
= 0;
2336 inf_child_mourn_inferior (ops
);
2339 /* Send a SIGINT to the process group. This acts just like the user typed a
2340 ^C on the controlling terminal. */
2343 windows_interrupt (struct target_ops
*self
, ptid_t ptid
)
2345 DEBUG_EVENTS (("gdb: GenerateConsoleCtrlEvent (CTRLC_EVENT, 0)\n"));
2346 CHECK (GenerateConsoleCtrlEvent (CTRL_C_EVENT
, current_event
.dwProcessId
));
2347 registers_changed (); /* refresh register state */
2350 /* Helper for windows_xfer_partial that handles memory transfers.
2351 Arguments are like target_xfer_partial. */
2353 static enum target_xfer_status
2354 windows_xfer_memory (gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
2355 ULONGEST memaddr
, ULONGEST len
, ULONGEST
*xfered_len
)
2359 DWORD lasterror
= 0;
2361 if (writebuf
!= NULL
)
2363 DEBUG_MEM (("gdb: write target memory, %s bytes at %s\n",
2364 pulongest (len
), core_addr_to_string (memaddr
)));
2365 success
= WriteProcessMemory (current_process_handle
,
2366 (LPVOID
) (uintptr_t) memaddr
, writebuf
,
2369 lasterror
= GetLastError ();
2370 FlushInstructionCache (current_process_handle
,
2371 (LPCVOID
) (uintptr_t) memaddr
, len
);
2375 DEBUG_MEM (("gdb: read target memory, %s bytes at %s\n",
2376 pulongest (len
), core_addr_to_string (memaddr
)));
2377 success
= ReadProcessMemory (current_process_handle
,
2378 (LPCVOID
) (uintptr_t) memaddr
, readbuf
,
2381 lasterror
= GetLastError ();
2383 *xfered_len
= (ULONGEST
) done
;
2384 if (!success
&& lasterror
== ERROR_PARTIAL_COPY
&& done
> 0)
2385 return TARGET_XFER_OK
;
2387 return success
? TARGET_XFER_OK
: TARGET_XFER_E_IO
;
2391 windows_kill_inferior (struct target_ops
*ops
)
2393 CHECK (TerminateProcess (current_process_handle
, 0));
2397 if (!windows_continue (DBG_CONTINUE
, -1, 1))
2399 if (!WaitForDebugEvent (¤t_event
, INFINITE
))
2401 if (current_event
.dwDebugEventCode
== EXIT_PROCESS_DEBUG_EVENT
)
2405 target_mourn_inferior (); /* Or just windows_mourn_inferior? */
2409 windows_close (struct target_ops
*self
)
2411 DEBUG_EVENTS (("gdb: windows_close, inferior_ptid=%d\n",
2412 ptid_get_pid (inferior_ptid
)));
2415 /* Convert pid to printable format. */
2417 windows_pid_to_str (struct target_ops
*ops
, ptid_t ptid
)
2419 static char buf
[80];
2421 if (ptid_get_tid (ptid
) != 0)
2423 snprintf (buf
, sizeof (buf
), "Thread %d.0x%lx",
2424 ptid_get_pid (ptid
), ptid_get_tid (ptid
));
2428 return normal_pid_to_str (ptid
);
2431 static enum target_xfer_status
2432 windows_xfer_shared_libraries (struct target_ops
*ops
,
2433 enum target_object object
, const char *annex
,
2434 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
2435 ULONGEST offset
, ULONGEST len
,
2436 ULONGEST
*xfered_len
)
2438 struct obstack obstack
;
2444 return TARGET_XFER_E_IO
;
2446 obstack_init (&obstack
);
2447 obstack_grow_str (&obstack
, "<library-list>\n");
2448 for (so
= solib_start
.next
; so
; so
= so
->next
)
2449 windows_xfer_shared_library (so
->so_name
, (CORE_ADDR
)
2450 (uintptr_t) so
->lm_info
->load_addr
,
2451 target_gdbarch (), &obstack
);
2452 obstack_grow_str0 (&obstack
, "</library-list>\n");
2454 buf
= (const char *) obstack_finish (&obstack
);
2455 len_avail
= strlen (buf
);
2456 if (offset
>= len_avail
)
2460 if (len
> len_avail
- offset
)
2461 len
= len_avail
- offset
;
2462 memcpy (readbuf
, buf
+ offset
, len
);
2465 obstack_free (&obstack
, NULL
);
2466 *xfered_len
= (ULONGEST
) len
;
2467 return len
!= 0 ? TARGET_XFER_OK
: TARGET_XFER_EOF
;
2470 static enum target_xfer_status
2471 windows_xfer_partial (struct target_ops
*ops
, enum target_object object
,
2472 const char *annex
, gdb_byte
*readbuf
,
2473 const gdb_byte
*writebuf
, ULONGEST offset
, ULONGEST len
,
2474 ULONGEST
*xfered_len
)
2478 case TARGET_OBJECT_MEMORY
:
2479 return windows_xfer_memory (readbuf
, writebuf
, offset
, len
, xfered_len
);
2481 case TARGET_OBJECT_LIBRARIES
:
2482 return windows_xfer_shared_libraries (ops
, object
, annex
, readbuf
,
2483 writebuf
, offset
, len
, xfered_len
);
2486 return ops
->beneath
->to_xfer_partial (ops
->beneath
, object
, annex
,
2487 readbuf
, writebuf
, offset
, len
,
2492 /* Provide thread local base, i.e. Thread Information Block address.
2493 Returns 1 if ptid is found and sets *ADDR to thread_local_base. */
2496 windows_get_tib_address (struct target_ops
*self
,
2497 ptid_t ptid
, CORE_ADDR
*addr
)
2499 windows_thread_info
*th
;
2501 th
= thread_rec (ptid_get_tid (ptid
), 0);
2506 *addr
= th
->thread_local_base
;
2512 windows_get_ada_task_ptid (struct target_ops
*self
, long lwp
, long thread
)
2514 return ptid_build (ptid_get_pid (inferior_ptid
), 0, lwp
);
2517 static struct target_ops
*
2518 windows_target (void)
2520 struct target_ops
*t
= inf_child_target ();
2522 t
->to_close
= windows_close
;
2523 t
->to_attach
= windows_attach
;
2524 t
->to_attach_no_wait
= 1;
2525 t
->to_detach
= windows_detach
;
2526 t
->to_resume
= windows_resume
;
2527 t
->to_wait
= windows_wait
;
2528 t
->to_fetch_registers
= windows_fetch_inferior_registers
;
2529 t
->to_store_registers
= windows_store_inferior_registers
;
2530 t
->to_xfer_partial
= windows_xfer_partial
;
2531 t
->to_files_info
= windows_files_info
;
2532 t
->to_kill
= windows_kill_inferior
;
2533 t
->to_create_inferior
= windows_create_inferior
;
2534 t
->to_mourn_inferior
= windows_mourn_inferior
;
2535 t
->to_thread_alive
= windows_thread_alive
;
2536 t
->to_pid_to_str
= windows_pid_to_str
;
2537 t
->to_interrupt
= windows_interrupt
;
2538 t
->to_pid_to_exec_file
= windows_pid_to_exec_file
;
2539 t
->to_get_ada_task_ptid
= windows_get_ada_task_ptid
;
2540 t
->to_get_tib_address
= windows_get_tib_address
;
2545 /* -Wmissing-prototypes */
2546 extern initialize_file_ftype _initialize_windows_nat
;
2549 _initialize_windows_nat (void)
2551 struct target_ops
*t
;
2553 t
= windows_target ();
2555 x86_use_watchpoints (t
);
2557 x86_dr_low
.set_control
= cygwin_set_dr7
;
2558 x86_dr_low
.set_addr
= cygwin_set_dr
;
2559 x86_dr_low
.get_addr
= cygwin_get_dr
;
2560 x86_dr_low
.get_status
= cygwin_get_dr6
;
2561 x86_dr_low
.get_control
= cygwin_get_dr7
;
2563 /* x86_dr_low.debug_register_length field is set by
2564 calling x86_set_debug_register_length function
2565 in processor windows specific native file. */
2570 cygwin_internal (CW_SET_DOS_FILE_WARNING
, 0);
2573 add_com ("signal-event", class_run
, signal_event_command
, _("\
2574 Signal a crashed process with event ID, to allow its debugging.\n\
2575 This command is needed in support of setting up GDB as JIT debugger on \
2576 MS-Windows. The command should be invoked from the GDB command line using \
2577 the '-ex' command-line option. The ID of the event that blocks the \
2578 crashed process will be supplied by the Windows JIT debugging mechanism."));
2581 add_setshow_boolean_cmd ("shell", class_support
, &useshell
, _("\
2582 Set use of shell to start subprocess."), _("\
2583 Show use of shell to start subprocess."), NULL
,
2585 NULL
, /* FIXME: i18n: */
2586 &setlist
, &showlist
);
2588 add_setshow_boolean_cmd ("cygwin-exceptions", class_support
,
2589 &cygwin_exceptions
, _("\
2590 Break when an exception is detected in the Cygwin DLL itself."), _("\
2591 Show whether gdb breaks on exceptions in the Cygwin DLL itself."), NULL
,
2593 NULL
, /* FIXME: i18n: */
2594 &setlist
, &showlist
);
2597 add_setshow_boolean_cmd ("new-console", class_support
, &new_console
, _("\
2598 Set creation of new console when creating child process."), _("\
2599 Show creation of new console when creating child process."), NULL
,
2601 NULL
, /* FIXME: i18n: */
2602 &setlist
, &showlist
);
2604 add_setshow_boolean_cmd ("new-group", class_support
, &new_group
, _("\
2605 Set creation of new group when creating child process."), _("\
2606 Show creation of new group when creating child process."), NULL
,
2608 NULL
, /* FIXME: i18n: */
2609 &setlist
, &showlist
);
2611 add_setshow_boolean_cmd ("debugexec", class_support
, &debug_exec
, _("\
2612 Set whether to display execution in child process."), _("\
2613 Show whether to display execution in child process."), NULL
,
2615 NULL
, /* FIXME: i18n: */
2616 &setlist
, &showlist
);
2618 add_setshow_boolean_cmd ("debugevents", class_support
, &debug_events
, _("\
2619 Set whether to display kernel events in child process."), _("\
2620 Show whether to display kernel events in child process."), NULL
,
2622 NULL
, /* FIXME: i18n: */
2623 &setlist
, &showlist
);
2625 add_setshow_boolean_cmd ("debugmemory", class_support
, &debug_memory
, _("\
2626 Set whether to display memory accesses in child process."), _("\
2627 Show whether to display memory accesses in child process."), NULL
,
2629 NULL
, /* FIXME: i18n: */
2630 &setlist
, &showlist
);
2632 add_setshow_boolean_cmd ("debugexceptions", class_support
,
2633 &debug_exceptions
, _("\
2634 Set whether to display kernel exceptions in child process."), _("\
2635 Show whether to display kernel exceptions in child process."), NULL
,
2637 NULL
, /* FIXME: i18n: */
2638 &setlist
, &showlist
);
2640 init_w32_command_list ();
2642 add_cmd ("selector", class_info
, display_selectors
,
2643 _("Display selectors infos."),
2647 /* Hardware watchpoint support, adapted from go32-nat.c code. */
2649 /* Pass the address ADDR to the inferior in the I'th debug register.
2650 Here we just store the address in dr array, the registers will be
2651 actually set up when windows_continue is called. */
2653 cygwin_set_dr (int i
, CORE_ADDR addr
)
2656 internal_error (__FILE__
, __LINE__
,
2657 _("Invalid register %d in cygwin_set_dr.\n"), i
);
2659 debug_registers_changed
= 1;
2660 debug_registers_used
= 1;
2663 /* Pass the value VAL to the inferior in the DR7 debug control
2664 register. Here we just store the address in D_REGS, the watchpoint
2665 will be actually set up in windows_wait. */
2667 cygwin_set_dr7 (unsigned long val
)
2669 dr
[7] = (CORE_ADDR
) val
;
2670 debug_registers_changed
= 1;
2671 debug_registers_used
= 1;
2674 /* Get the value of debug register I from the inferior. */
2677 cygwin_get_dr (int i
)
2682 /* Get the value of the DR6 debug status register from the inferior.
2683 Here we just return the value stored in dr[6]
2684 by the last call to thread_rec for current_event.dwThreadId id. */
2685 static unsigned long
2686 cygwin_get_dr6 (void)
2688 return (unsigned long) dr
[6];
2691 /* Get the value of the DR7 debug status register from the inferior.
2692 Here we just return the value stored in dr[7] by the last call to
2693 thread_rec for current_event.dwThreadId id. */
2695 static unsigned long
2696 cygwin_get_dr7 (void)
2698 return (unsigned long) dr
[7];
2701 /* Determine if the thread referenced by "ptid" is alive
2702 by "polling" it. If WaitForSingleObject returns WAIT_OBJECT_0
2703 it means that the thread has died. Otherwise it is assumed to be alive. */
2705 windows_thread_alive (struct target_ops
*ops
, ptid_t ptid
)
2709 gdb_assert (ptid_get_tid (ptid
) != 0);
2710 tid
= ptid_get_tid (ptid
);
2712 return WaitForSingleObject (thread_rec (tid
, FALSE
)->h
, 0) == WAIT_OBJECT_0
2716 /* -Wmissing-prototypes */
2717 extern initialize_file_ftype _initialize_check_for_gdb_ini
;
2720 _initialize_check_for_gdb_ini (void)
2723 if (inhibit_gdbinit
)
2726 homedir
= getenv ("HOME");
2730 char *oldini
= (char *) alloca (strlen (homedir
) +
2731 sizeof ("gdb.ini") + 1);
2732 strcpy (oldini
, homedir
);
2733 p
= strchr (oldini
, '\0');
2734 if (p
> oldini
&& !IS_DIR_SEPARATOR (p
[-1]))
2736 strcpy (p
, "gdb.ini");
2737 if (access (oldini
, 0) == 0)
2739 int len
= strlen (oldini
);
2740 char *newini
= (char *) alloca (len
+ 2);
2742 xsnprintf (newini
, len
+ 2, "%.*s.gdbinit",
2743 (int) (len
- (sizeof ("gdb.ini") - 1)), oldini
);
2744 warning (_("obsolete '%s' found. Rename to '%s'."), oldini
, newini
);
2749 /* Define dummy functions which always return error for the rare cases where
2750 these functions could not be found. */
2752 bad_DebugActiveProcessStop (DWORD w
)
2757 bad_DebugBreakProcess (HANDLE w
)
2762 bad_DebugSetProcessKillOnExit (BOOL w
)
2767 bad_EnumProcessModules (HANDLE w
, HMODULE
*x
, DWORD y
, LPDWORD z
)
2774 bad_GetModuleFileNameExW (HANDLE w
, HMODULE x
, LPWSTR y
, DWORD z
)
2780 bad_GetModuleFileNameExA (HANDLE w
, HMODULE x
, LPSTR y
, DWORD z
)
2787 bad_GetModuleInformation (HANDLE w
, HMODULE x
, LPMODULEINFO y
, DWORD z
)
2793 bad_OpenProcessToken (HANDLE w
, DWORD x
, PHANDLE y
)
2799 bad_GetCurrentConsoleFont (HANDLE w
, BOOL bMaxWindow
, CONSOLE_FONT_INFO
*f
)
2805 bad_GetConsoleFontSize (HANDLE w
, DWORD nFont
)
2813 /* -Wmissing-prototypes */
2814 extern initialize_file_ftype _initialize_loadable
;
2816 /* Load any functions which may not be available in ancient versions
2820 _initialize_loadable (void)
2824 #define GPA(m, func) \
2825 func = (func ## _ftype *) GetProcAddress (m, #func)
2827 hm
= LoadLibrary ("kernel32.dll");
2830 GPA (hm
, DebugActiveProcessStop
);
2831 GPA (hm
, DebugBreakProcess
);
2832 GPA (hm
, DebugSetProcessKillOnExit
);
2833 GPA (hm
, GetConsoleFontSize
);
2834 GPA (hm
, DebugActiveProcessStop
);
2835 GPA (hm
, GetCurrentConsoleFont
);
2838 /* Set variables to dummy versions of these processes if the function
2839 wasn't found in kernel32.dll. */
2840 if (!DebugBreakProcess
)
2841 DebugBreakProcess
= bad_DebugBreakProcess
;
2842 if (!DebugActiveProcessStop
|| !DebugSetProcessKillOnExit
)
2844 DebugActiveProcessStop
= bad_DebugActiveProcessStop
;
2845 DebugSetProcessKillOnExit
= bad_DebugSetProcessKillOnExit
;
2847 if (!GetConsoleFontSize
)
2848 GetConsoleFontSize
= bad_GetConsoleFontSize
;
2849 if (!GetCurrentConsoleFont
)
2850 GetCurrentConsoleFont
= bad_GetCurrentConsoleFont
;
2852 /* Load optional functions used for retrieving filename information
2853 associated with the currently debugged process or its dlls. */
2854 hm
= LoadLibrary ("psapi.dll");
2857 GPA (hm
, EnumProcessModules
);
2858 GPA (hm
, GetModuleInformation
);
2859 GetModuleFileNameEx
= (GetModuleFileNameEx_ftype
*)
2860 GetProcAddress (hm
, GetModuleFileNameEx_name
);
2863 if (!EnumProcessModules
|| !GetModuleInformation
|| !GetModuleFileNameEx
)
2865 /* Set variables to dummy versions of these processes if the function
2866 wasn't found in psapi.dll. */
2867 EnumProcessModules
= bad_EnumProcessModules
;
2868 GetModuleInformation
= bad_GetModuleInformation
;
2869 GetModuleFileNameEx
= bad_GetModuleFileNameEx
;
2870 /* This will probably fail on Windows 9x/Me. Let the user know
2871 that we're missing some functionality. */
2873 cannot automatically find executable file or library to read symbols.\n\
2874 Use \"file\" or \"dll\" command to load executable/libraries directly."));
2877 hm
= LoadLibrary ("advapi32.dll");
2880 GPA (hm
, OpenProcessToken
);
2881 GPA (hm
, LookupPrivilegeValueA
);
2882 GPA (hm
, AdjustTokenPrivileges
);
2883 /* Only need to set one of these since if OpenProcessToken fails nothing
2885 if (!OpenProcessToken
|| !LookupPrivilegeValueA
2886 || !AdjustTokenPrivileges
)
2887 OpenProcessToken
= bad_OpenProcessToken
;