1 /* Target-vector operations for controlling windows child processes, for GDB.
3 Copyright (C) 1995-2015 Free Software Foundation, Inc.
5 Contributed by Cygnus Solutions, A Red Hat Company.
7 This file is part of GDB.
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>. */
22 /* Originally by Steve Chamberlain, sac@cygnus.com */
25 #include "frame.h" /* required by inferior.h */
31 #include "completer.h"
35 #include <sys/types.h>
42 #include <sys/cygwin.h>
43 #include <cygwin/version.h>
47 #include "filenames.h"
51 #include "gdb_obstack.h"
52 #include "gdbthread.h"
58 #include "xml-support.h"
60 #include "i386-tdep.h"
61 #include "i387-tdep.h"
63 #include "windows-tdep.h"
64 #include "windows-nat.h"
66 #include "complaints.h"
67 #include "inf-child.h"
69 #define AdjustTokenPrivileges dyn_AdjustTokenPrivileges
70 #define DebugActiveProcessStop dyn_DebugActiveProcessStop
71 #define DebugBreakProcess dyn_DebugBreakProcess
72 #define DebugSetProcessKillOnExit dyn_DebugSetProcessKillOnExit
73 #define EnumProcessModules dyn_EnumProcessModules
74 #define GetModuleInformation dyn_GetModuleInformation
75 #define LookupPrivilegeValueA dyn_LookupPrivilegeValueA
76 #define OpenProcessToken dyn_OpenProcessToken
77 #define GetConsoleFontSize dyn_GetConsoleFontSize
78 #define GetCurrentConsoleFont dyn_GetCurrentConsoleFont
80 static BOOL
WINAPI (*AdjustTokenPrivileges
)(HANDLE
, BOOL
, PTOKEN_PRIVILEGES
,
81 DWORD
, PTOKEN_PRIVILEGES
, PDWORD
);
82 static BOOL
WINAPI (*DebugActiveProcessStop
) (DWORD
);
83 static BOOL
WINAPI (*DebugBreakProcess
) (HANDLE
);
84 static BOOL
WINAPI (*DebugSetProcessKillOnExit
) (BOOL
);
85 static BOOL
WINAPI (*EnumProcessModules
) (HANDLE
, HMODULE
*, DWORD
,
87 static BOOL
WINAPI (*GetModuleInformation
) (HANDLE
, HMODULE
, LPMODULEINFO
,
89 static BOOL
WINAPI (*LookupPrivilegeValueA
)(LPCSTR
, LPCSTR
, PLUID
);
90 static BOOL
WINAPI (*OpenProcessToken
)(HANDLE
, DWORD
, PHANDLE
);
91 static BOOL
WINAPI (*GetCurrentConsoleFont
) (HANDLE
, BOOL
,
93 static COORD
WINAPI (*GetConsoleFontSize
) (HANDLE
, DWORD
);
97 #undef GetModuleFileNameEx
100 # define __PMAX (MAX_PATH + 1)
101 static DWORD
WINAPI (*GetModuleFileNameEx
) (HANDLE
, HMODULE
, LPSTR
, DWORD
);
102 # define STARTUPINFO STARTUPINFOA
103 # define CreateProcess CreateProcessA
104 # define GetModuleFileNameEx_name "GetModuleFileNameExA"
105 # define bad_GetModuleFileNameEx bad_GetModuleFileNameExA
107 # define __PMAX PATH_MAX
108 /* The starting and ending address of the cygwin1.dll text segment. */
109 static CORE_ADDR cygwin_load_start
;
110 static CORE_ADDR cygwin_load_end
;
112 typedef wchar_t cygwin_buf_t
;
113 static DWORD
WINAPI (*GetModuleFileNameEx
) (HANDLE
, HMODULE
,
115 # define STARTUPINFO STARTUPINFOW
116 # define CreateProcess CreateProcessW
117 # define GetModuleFileNameEx_name "GetModuleFileNameExW"
118 # define bad_GetModuleFileNameEx bad_GetModuleFileNameExW
121 static int have_saved_context
; /* True if we've saved context from a
123 static CONTEXT saved_context
; /* Containes the saved context from a
126 /* If we're not using the old Cygwin header file set, define the
127 following which never should have been in the generic Win32 API
128 headers in the first place since they were our own invention... */
129 #ifndef _GNU_H_WINDOWS_H
132 FLAG_TRACE_BIT
= 0x100,
133 CONTEXT_DEBUGGER
= (CONTEXT_FULL
| CONTEXT_FLOATING_POINT
)
137 #ifndef CONTEXT_EXTENDED_REGISTERS
138 /* This macro is only defined on ia32. It only makes sense on this target,
139 so define it as zero if not already defined. */
140 #define CONTEXT_EXTENDED_REGISTERS 0
143 #define CONTEXT_DEBUGGER_DR CONTEXT_DEBUGGER | CONTEXT_DEBUG_REGISTERS \
144 | CONTEXT_EXTENDED_REGISTERS
146 static uintptr_t dr
[8];
147 static int debug_registers_changed
;
148 static int debug_registers_used
;
150 static int windows_initialization_done
;
151 #define DR6_CLEAR_VALUE 0xffff0ff0
153 /* The string sent by cygwin when it processes a signal.
154 FIXME: This should be in a cygwin include file. */
155 #ifndef _CYGWIN_SIGNAL_STRING
156 #define _CYGWIN_SIGNAL_STRING "cYgSiGw00f"
159 #define CHECK(x) check (x, __FILE__,__LINE__)
160 #define DEBUG_EXEC(x) if (debug_exec) printf_unfiltered x
161 #define DEBUG_EVENTS(x) if (debug_events) printf_unfiltered x
162 #define DEBUG_MEM(x) if (debug_memory) printf_unfiltered x
163 #define DEBUG_EXCEPT(x) if (debug_exceptions) printf_unfiltered x
165 static void windows_stop (struct target_ops
*self
, ptid_t
);
166 static int windows_thread_alive (struct target_ops
*, ptid_t
);
167 static void windows_kill_inferior (struct target_ops
*);
169 static void cygwin_set_dr (int i
, CORE_ADDR addr
);
170 static void cygwin_set_dr7 (unsigned long val
);
171 static CORE_ADDR
cygwin_get_dr (int i
);
172 static unsigned long cygwin_get_dr6 (void);
173 static unsigned long cygwin_get_dr7 (void);
175 static enum gdb_signal last_sig
= GDB_SIGNAL_0
;
176 /* Set if a signal was received from the debugged process. */
178 /* Thread information structure used to track information that is
179 not available in gdb's thread structure. */
180 typedef struct thread_info_struct
182 struct thread_info_struct
*next
;
185 CORE_ADDR thread_local_base
;
194 static thread_info thread_head
;
196 /* The process and thread handles for the above context. */
198 static DEBUG_EVENT current_event
; /* The current debug event from
200 static HANDLE current_process_handle
; /* Currently executing process */
201 static thread_info
*current_thread
; /* Info on currently selected thread */
202 static DWORD main_thread_id
; /* Thread ID of the main thread */
204 /* Counts of things. */
205 static int exception_count
= 0;
206 static int event_count
= 0;
207 static int saw_create
;
208 static int open_process_used
= 0;
211 static int new_console
= 0;
213 static int cygwin_exceptions
= 0;
215 static int new_group
= 1;
216 static int debug_exec
= 0; /* show execution */
217 static int debug_events
= 0; /* show events from kernel */
218 static int debug_memory
= 0; /* show target memory accesses */
219 static int debug_exceptions
= 0; /* show target exceptions */
220 static int useshell
= 0; /* use shell for subprocesses */
222 /* This vector maps GDB's idea of a register's number into an offset
223 in the windows exception context vector.
225 It also contains the bit mask needed to load the register in question.
227 The contents of this table can only be computed by the units
228 that provide CPU-specific support for Windows native debugging.
229 These units should set the table by calling
230 windows_set_context_register_offsets.
232 One day we could read a reg, we could inspect the context we
233 already have loaded, if it doesn't have the bit set that we need,
234 we read that set of registers in using GetThreadContext. If the
235 context already contains what we need, we just unpack it. Then to
236 write a register, first we have to ensure that the context contains
237 the other regs of the group, and then we copy the info in and set
240 static const int *mappings
;
242 /* The function to use in order to determine whether a register is
243 a segment register or not. */
244 static segment_register_p_ftype
*segment_register_p
;
246 /* This vector maps the target's idea of an exception (extracted
247 from the DEBUG_EVENT structure) to GDB's idea. */
249 struct xlate_exception
255 static const struct xlate_exception
258 {EXCEPTION_ACCESS_VIOLATION
, GDB_SIGNAL_SEGV
},
259 {STATUS_STACK_OVERFLOW
, GDB_SIGNAL_SEGV
},
260 {EXCEPTION_BREAKPOINT
, GDB_SIGNAL_TRAP
},
261 {DBG_CONTROL_C
, GDB_SIGNAL_INT
},
262 {EXCEPTION_SINGLE_STEP
, GDB_SIGNAL_TRAP
},
263 {STATUS_FLOAT_DIVIDE_BY_ZERO
, GDB_SIGNAL_FPE
},
266 /* Set the MAPPINGS static global to OFFSETS.
267 See the description of MAPPINGS for more details. */
270 windows_set_context_register_offsets (const int *offsets
)
275 /* See windows-nat.h. */
278 windows_set_segment_register_p (segment_register_p_ftype
*fun
)
280 segment_register_p
= fun
;
284 check (BOOL ok
, const char *file
, int line
)
287 printf_filtered ("error return %s:%d was %u\n", file
, line
,
288 (unsigned) GetLastError ());
291 /* Find a thread record given a thread id. If GET_CONTEXT is not 0,
292 then also retrieve the context for this thread. If GET_CONTEXT is
293 negative, then don't suspend the thread. */
295 thread_rec (DWORD id
, int get_context
)
299 for (th
= &thread_head
; (th
= th
->next
) != NULL
;)
302 if (!th
->suspended
&& get_context
)
304 if (get_context
> 0 && id
!= current_event
.dwThreadId
)
306 if (SuspendThread (th
->h
) == (DWORD
) -1)
308 DWORD err
= GetLastError ();
310 /* We get Access Denied (5) when trying to suspend
311 threads that Windows started on behalf of the
312 debuggee, usually when those threads are just
314 if (err
!= ERROR_ACCESS_DENIED
)
315 warning (_("SuspendThread (tid=0x%x) failed."
317 (unsigned) id
, (unsigned) err
);
323 else if (get_context
< 0)
325 th
->reload_context
= 1;
333 /* Add a thread to the thread list. */
335 windows_add_thread (ptid_t ptid
, HANDLE h
, void *tlb
)
340 gdb_assert (ptid_get_tid (ptid
) != 0);
342 id
= ptid_get_tid (ptid
);
344 if ((th
= thread_rec (id
, FALSE
)))
347 th
= XCNEW (thread_info
);
350 th
->thread_local_base
= (CORE_ADDR
) (uintptr_t) tlb
;
351 th
->next
= thread_head
.next
;
352 thread_head
.next
= th
;
354 /* Set the debug registers for the new thread if they are used. */
355 if (debug_registers_used
)
357 /* Only change the value of the debug registers. */
358 th
->context
.ContextFlags
= CONTEXT_DEBUG_REGISTERS
;
359 CHECK (GetThreadContext (th
->h
, &th
->context
));
360 th
->context
.Dr0
= dr
[0];
361 th
->context
.Dr1
= dr
[1];
362 th
->context
.Dr2
= dr
[2];
363 th
->context
.Dr3
= dr
[3];
364 th
->context
.Dr6
= DR6_CLEAR_VALUE
;
365 th
->context
.Dr7
= dr
[7];
366 CHECK (SetThreadContext (th
->h
, &th
->context
));
367 th
->context
.ContextFlags
= 0;
372 /* Clear out any old thread list and reintialize it to a
375 windows_init_thread_list (void)
377 thread_info
*th
= &thread_head
;
379 DEBUG_EVENTS (("gdb: windows_init_thread_list\n"));
381 while (th
->next
!= NULL
)
383 thread_info
*here
= th
->next
;
384 th
->next
= here
->next
;
387 thread_head
.next
= NULL
;
390 /* Delete a thread from the list of threads. */
392 windows_delete_thread (ptid_t ptid
, DWORD exit_code
)
397 gdb_assert (ptid_get_tid (ptid
) != 0);
399 id
= ptid_get_tid (ptid
);
402 printf_unfiltered ("[Deleting %s]\n", target_pid_to_str (ptid
));
403 else if (print_thread_events
&& id
!= main_thread_id
)
404 printf_unfiltered (_("[%s exited with code %u]\n"),
405 target_pid_to_str (ptid
), (unsigned) exit_code
);
406 delete_thread (ptid
);
408 for (th
= &thread_head
;
409 th
->next
!= NULL
&& th
->next
->id
!= id
;
413 if (th
->next
!= NULL
)
415 thread_info
*here
= th
->next
;
416 th
->next
= here
->next
;
422 do_windows_fetch_inferior_registers (struct regcache
*regcache
, int r
)
424 char *context_offset
= ((char *) ¤t_thread
->context
) + mappings
[r
];
425 struct gdbarch
*gdbarch
= get_regcache_arch (regcache
);
426 struct gdbarch_tdep
*tdep
= gdbarch_tdep (gdbarch
);
430 return; /* Windows sometimes uses a non-existent thread id in its
433 if (current_thread
->reload_context
)
435 #ifdef __COPY_CONTEXT_SIZE
436 if (have_saved_context
)
438 /* Lie about where the program actually is stopped since
439 cygwin has informed us that we should consider the signal
440 to have occurred at another location which is stored in
442 memcpy (¤t_thread
->context
, &saved_context
,
443 __COPY_CONTEXT_SIZE
);
444 have_saved_context
= 0;
449 thread_info
*th
= current_thread
;
450 th
->context
.ContextFlags
= CONTEXT_DEBUGGER_DR
;
451 CHECK (GetThreadContext (th
->h
, &th
->context
));
452 /* Copy dr values from that thread.
453 But only if there were not modified since last stop.
455 if (!debug_registers_changed
)
457 dr
[0] = th
->context
.Dr0
;
458 dr
[1] = th
->context
.Dr1
;
459 dr
[2] = th
->context
.Dr2
;
460 dr
[3] = th
->context
.Dr3
;
461 dr
[6] = th
->context
.Dr6
;
462 dr
[7] = th
->context
.Dr7
;
465 current_thread
->reload_context
= 0;
468 if (r
== I387_FISEG_REGNUM (tdep
))
470 l
= *((long *) context_offset
) & 0xffff;
471 regcache_raw_supply (regcache
, r
, (char *) &l
);
473 else if (r
== I387_FOP_REGNUM (tdep
))
475 l
= (*((long *) context_offset
) >> 16) & ((1 << 11) - 1);
476 regcache_raw_supply (regcache
, r
, (char *) &l
);
478 else if (segment_register_p (r
))
480 /* GDB treats segment registers as 32bit registers, but they are
481 in fact only 16 bits long. Make sure we do not read extra
482 bits from our source buffer. */
483 l
= *((long *) context_offset
) & 0xffff;
484 regcache_raw_supply (regcache
, r
, (char *) &l
);
487 regcache_raw_supply (regcache
, r
, context_offset
);
490 for (r
= 0; r
< gdbarch_num_regs (gdbarch
); r
++)
491 do_windows_fetch_inferior_registers (regcache
, r
);
496 windows_fetch_inferior_registers (struct target_ops
*ops
,
497 struct regcache
*regcache
, int r
)
499 current_thread
= thread_rec (ptid_get_tid (inferior_ptid
), TRUE
);
500 /* Check if current_thread exists. Windows sometimes uses a non-existent
501 thread id in its events. */
503 do_windows_fetch_inferior_registers (regcache
, r
);
507 do_windows_store_inferior_registers (const struct regcache
*regcache
, int r
)
510 /* Windows sometimes uses a non-existent thread id in its events. */;
512 regcache_raw_collect (regcache
, r
,
513 ((char *) ¤t_thread
->context
) + mappings
[r
]);
516 for (r
= 0; r
< gdbarch_num_regs (get_regcache_arch (regcache
)); r
++)
517 do_windows_store_inferior_registers (regcache
, r
);
521 /* Store a new register value into the current thread context. */
523 windows_store_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_store_inferior_registers (regcache
, r
);
533 /* Encapsulate the information required in a call to
534 symbol_file_add_args. */
535 struct safe_symbol_file_add_args
539 struct section_addr_info
*addrs
;
542 struct ui_file
*err
, *out
;
546 /* Maintain a linked list of "so" information. */
552 static struct so_list solib_start
, *solib_end
;
554 static struct so_list
*
555 windows_make_so (const char *name
, LPVOID load_addr
)
562 WIN32_FIND_DATA w32_fd
;
563 HANDLE h
= FindFirstFile(name
, &w32_fd
);
565 if (h
== INVALID_HANDLE_VALUE
)
571 if (GetCurrentDirectory (MAX_PATH
+ 1, cwd
))
573 p
= strrchr (buf
, '\\');
576 SetCurrentDirectory (buf
);
577 GetFullPathName (w32_fd
.cFileName
, MAX_PATH
, buf
, &p
);
578 SetCurrentDirectory (cwd
);
581 if (strcasecmp (buf
, "ntdll.dll") == 0)
583 GetSystemDirectory (buf
, sizeof (buf
));
584 strcat (buf
, "\\ntdll.dll");
587 cygwin_buf_t buf
[__PMAX
];
590 if (access (name
, F_OK
) != 0)
592 if (strcasecmp (name
, "ntdll.dll") == 0)
595 GetSystemDirectoryW (buf
, sizeof (buf
) / sizeof (wchar_t));
596 wcscat (buf
, L
"\\ntdll.dll");
600 GetSystemDirectoryA (buf
, sizeof (buf
) / sizeof (wchar_t));
601 strcat (buf
, "\\ntdll.dll");
606 so
= XCNEW (struct so_list
);
607 so
->lm_info
= (struct lm_info
*) xmalloc (sizeof (struct lm_info
));
608 so
->lm_info
->load_addr
= load_addr
;
609 strcpy (so
->so_original_name
, name
);
611 strcpy (so
->so_name
, buf
);
614 cygwin_conv_path (CCP_WIN_W_TO_POSIX
, buf
, so
->so_name
,
615 SO_NAME_MAX_PATH_SIZE
);
618 char *rname
= realpath (name
, NULL
);
619 if (rname
&& strlen (rname
) < SO_NAME_MAX_PATH_SIZE
)
621 strcpy (so
->so_name
, rname
);
625 error (_("dll path too long"));
627 /* Record cygwin1.dll .text start/end. */
628 p
= strchr (so
->so_name
, '\0') - (sizeof ("/cygwin1.dll") - 1);
629 if (p
>= so
->so_name
&& strcasecmp (p
, "/cygwin1.dll") == 0)
632 asection
*text
= NULL
;
635 abfd
= gdb_bfd_open (so
->so_name
, "pei-i386", -1);
640 if (bfd_check_format (abfd
, bfd_object
))
641 text
= bfd_get_section_by_name (abfd
, ".text");
645 gdb_bfd_unref (abfd
);
649 /* The symbols in a dll are offset by 0x1000, which is the
650 offset from 0 of the first byte in an image - because of the
651 file header and the section alignment. */
652 cygwin_load_start
= (CORE_ADDR
) (uintptr_t) ((char *)
654 cygwin_load_end
= cygwin_load_start
+ bfd_section_size (abfd
, text
);
656 gdb_bfd_unref (abfd
);
664 get_image_name (HANDLE h
, void *address
, int unicode
)
667 static char buf
[__PMAX
];
669 static char buf
[(2 * __PMAX
) + 1];
671 DWORD size
= unicode
? sizeof (WCHAR
) : sizeof (char);
677 /* Attempt to read the name of the dll that was detected.
678 This is documented to work only when actively debugging
679 a program. It will not work for attached processes. */
683 /* See if we could read the address of a string, and that the
684 address isn't null. */
685 if (!ReadProcessMemory (h
, address
, &address_ptr
,
686 sizeof (address_ptr
), &done
)
687 || done
!= sizeof (address_ptr
) || !address_ptr
)
690 /* Find the length of the string. */
691 while (ReadProcessMemory (h
, address_ptr
+ len
++ * size
, &b
, size
, &done
)
692 && (b
[0] != 0 || b
[size
- 1] != 0) && done
== size
)
696 ReadProcessMemory (h
, address_ptr
, buf
, len
, &done
);
699 WCHAR
*unicode_address
= (WCHAR
*) alloca (len
* sizeof (WCHAR
));
700 ReadProcessMemory (h
, address_ptr
, unicode_address
, len
* sizeof (WCHAR
),
703 wcstombs (buf
, unicode_address
, __PMAX
);
705 WideCharToMultiByte (CP_ACP
, 0, unicode_address
, len
, buf
, sizeof buf
,
713 /* Handle a DLL load event, and return 1.
715 This function assumes that this event did not occur during inferior
716 initialization, where their event info may be incomplete (see
717 do_initial_windows_stuff and windows_add_all_dlls for more info
718 on how we handle DLL loading during that phase). */
721 handle_load_dll (void *dummy
)
723 LOAD_DLL_DEBUG_INFO
*event
= ¤t_event
.u
.LoadDll
;
726 /* Try getting the DLL name via the lpImageName field of the event.
727 Note that Microsoft documents this fields as strictly optional,
728 in the sense that it might be NULL. And the first DLL event in
729 particular is explicitly documented as "likely not pass[ed]"
730 (source: MSDN LOAD_DLL_DEBUG_INFO structure). */
731 dll_name
= get_image_name (current_process_handle
,
732 event
->lpImageName
, event
->fUnicode
);
736 solib_end
->next
= windows_make_so (dll_name
, event
->lpBaseOfDll
);
737 solib_end
= solib_end
->next
;
739 DEBUG_EVENTS (("gdb: Loading dll \"%s\" at %s.\n", solib_end
->so_name
,
740 host_address_to_string (solib_end
->lm_info
->load_addr
)));
746 windows_free_so (struct so_list
*so
)
753 /* Handle a DLL unload event.
754 Return 1 if successful, or zero otherwise.
756 This function assumes that this event did not occur during inferior
757 initialization, where their event info may be incomplete (see
758 do_initial_windows_stuff and windows_add_all_dlls for more info
759 on how we handle DLL loading during that phase). */
762 handle_unload_dll (void *dummy
)
764 LPVOID lpBaseOfDll
= current_event
.u
.UnloadDll
.lpBaseOfDll
;
767 for (so
= &solib_start
; so
->next
!= NULL
; so
= so
->next
)
768 if (so
->next
->lm_info
->load_addr
== lpBaseOfDll
)
770 struct so_list
*sodel
= so
->next
;
772 so
->next
= sodel
->next
;
775 DEBUG_EVENTS (("gdb: Unloading dll \"%s\".\n", sodel
->so_name
));
777 windows_free_so (sodel
);
781 /* We did not find any DLL that was previously loaded at this address,
782 so register a complaint. We do not report an error, because we have
783 observed that this may be happening under some circumstances. For
784 instance, running 32bit applications on x64 Windows causes us to receive
785 4 mysterious UNLOAD_DLL_DEBUG_EVENTs during the startup phase (these
786 events are apparently caused by the WOW layer, the interface between
787 32bit and 64bit worlds). */
788 complaint (&symfile_complaints
, _("dll starting at %s not found."),
789 host_address_to_string (lpBaseOfDll
));
794 /* Clear list of loaded DLLs. */
796 windows_clear_solib (void)
798 solib_start
.next
= NULL
;
799 solib_end
= &solib_start
;
802 /* Handle DEBUG_STRING output from child process.
803 Cygwin prepends its messages with a "cygwin:". Interpret this as
804 a Cygwin signal. Otherwise just print the string as a warning. */
806 handle_output_debug_string (struct target_waitstatus
*ourstatus
)
811 if (!target_read_string
812 ((CORE_ADDR
) (uintptr_t) current_event
.u
.DebugString
.lpDebugStringData
,
816 else if (strncmp (s
, _CYGWIN_SIGNAL_STRING
,
817 sizeof (_CYGWIN_SIGNAL_STRING
) - 1) != 0)
820 if (strncmp (s
, "cYg", 3) != 0)
824 #ifdef __COPY_CONTEXT_SIZE
827 /* Got a cygwin signal marker. A cygwin signal is followed by
828 the signal number itself and then optionally followed by the
829 thread id and address to saved context within the DLL. If
830 these are supplied, then the given thread is assumed to have
831 issued the signal and the context from the thread is assumed
832 to be stored at the given address in the inferior. Tell gdb
833 to treat this like a real signal. */
835 int sig
= strtol (s
+ sizeof (_CYGWIN_SIGNAL_STRING
) - 1, &p
, 0);
836 int gotasig
= gdb_signal_from_host (sig
);
838 ourstatus
->value
.sig
= gotasig
;
844 ourstatus
->kind
= TARGET_WAITKIND_STOPPED
;
845 retval
= strtoul (p
, &p
, 0);
847 retval
= main_thread_id
;
848 else if ((x
= (LPCVOID
) (uintptr_t) strtoull (p
, NULL
, 0))
849 && ReadProcessMemory (current_process_handle
, x
,
851 __COPY_CONTEXT_SIZE
, &n
)
852 && n
== __COPY_CONTEXT_SIZE
)
853 have_saved_context
= 1;
854 current_event
.dwThreadId
= retval
;
865 display_selector (HANDLE thread
, DWORD sel
)
868 if (GetThreadSelectorEntry (thread
, sel
, &info
))
871 printf_filtered ("0x%03x: ", (unsigned) sel
);
872 if (!info
.HighWord
.Bits
.Pres
)
874 puts_filtered ("Segment not present\n");
877 base
= (info
.HighWord
.Bits
.BaseHi
<< 24) +
878 (info
.HighWord
.Bits
.BaseMid
<< 16)
880 limit
= (info
.HighWord
.Bits
.LimitHi
<< 16) + info
.LimitLow
;
881 if (info
.HighWord
.Bits
.Granularity
)
882 limit
= (limit
<< 12) | 0xfff;
883 printf_filtered ("base=0x%08x limit=0x%08x", base
, limit
);
884 if (info
.HighWord
.Bits
.Default_Big
)
885 puts_filtered(" 32-bit ");
887 puts_filtered(" 16-bit ");
888 switch ((info
.HighWord
.Bits
.Type
& 0xf) >> 1)
891 puts_filtered ("Data (Read-Only, Exp-up");
894 puts_filtered ("Data (Read/Write, Exp-up");
897 puts_filtered ("Unused segment (");
900 puts_filtered ("Data (Read/Write, Exp-down");
903 puts_filtered ("Code (Exec-Only, N.Conf");
906 puts_filtered ("Code (Exec/Read, N.Conf");
909 puts_filtered ("Code (Exec-Only, Conf");
912 puts_filtered ("Code (Exec/Read, Conf");
915 printf_filtered ("Unknown type 0x%x",info
.HighWord
.Bits
.Type
);
917 if ((info
.HighWord
.Bits
.Type
& 0x1) == 0)
918 puts_filtered(", N.Acc");
919 puts_filtered (")\n");
920 if ((info
.HighWord
.Bits
.Type
& 0x10) == 0)
921 puts_filtered("System selector ");
922 printf_filtered ("Priviledge level = %d. ", info
.HighWord
.Bits
.Dpl
);
923 if (info
.HighWord
.Bits
.Granularity
)
924 puts_filtered ("Page granular.\n");
926 puts_filtered ("Byte granular.\n");
931 DWORD err
= GetLastError ();
932 if (err
== ERROR_NOT_SUPPORTED
)
933 printf_filtered ("Function not supported\n");
935 printf_filtered ("Invalid selector 0x%x.\n", (unsigned) sel
);
941 display_selectors (char * args
, int from_tty
)
945 puts_filtered ("Impossible to display selectors now.\n");
951 puts_filtered ("Selector $cs\n");
952 display_selector (current_thread
->h
,
953 current_thread
->context
.SegCs
);
954 puts_filtered ("Selector $ds\n");
955 display_selector (current_thread
->h
,
956 current_thread
->context
.SegDs
);
957 puts_filtered ("Selector $es\n");
958 display_selector (current_thread
->h
,
959 current_thread
->context
.SegEs
);
960 puts_filtered ("Selector $ss\n");
961 display_selector (current_thread
->h
,
962 current_thread
->context
.SegSs
);
963 puts_filtered ("Selector $fs\n");
964 display_selector (current_thread
->h
,
965 current_thread
->context
.SegFs
);
966 puts_filtered ("Selector $gs\n");
967 display_selector (current_thread
->h
,
968 current_thread
->context
.SegGs
);
973 sel
= parse_and_eval_long (args
);
974 printf_filtered ("Selector \"%s\"\n",args
);
975 display_selector (current_thread
->h
, sel
);
979 #define DEBUG_EXCEPTION_SIMPLE(x) if (debug_exceptions) \
980 printf_unfiltered ("gdb: Target exception %s at %s\n", x, \
981 host_address_to_string (\
982 current_event.u.Exception.ExceptionRecord.ExceptionAddress))
985 handle_exception (struct target_waitstatus
*ourstatus
)
988 DWORD code
= current_event
.u
.Exception
.ExceptionRecord
.ExceptionCode
;
990 ourstatus
->kind
= TARGET_WAITKIND_STOPPED
;
992 /* Record the context of the current thread. */
993 th
= thread_rec (current_event
.dwThreadId
, -1);
997 case EXCEPTION_ACCESS_VIOLATION
:
998 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ACCESS_VIOLATION");
999 ourstatus
->value
.sig
= GDB_SIGNAL_SEGV
;
1002 /* See if the access violation happened within the cygwin DLL
1003 itself. Cygwin uses a kind of exception handling to deal
1004 with passed-in invalid addresses. gdb should not treat
1005 these as real SEGVs since they will be silently handled by
1006 cygwin. A real SEGV will (theoretically) be caught by
1007 cygwin later in the process and will be sent as a
1008 cygwin-specific-signal. So, ignore SEGVs if they show up
1009 within the text segment of the DLL itself. */
1011 CORE_ADDR addr
= (CORE_ADDR
) (uintptr_t)
1012 current_event
.u
.Exception
.ExceptionRecord
.ExceptionAddress
;
1014 if ((!cygwin_exceptions
&& (addr
>= cygwin_load_start
1015 && addr
< cygwin_load_end
))
1016 || (find_pc_partial_function (addr
, &fn
, NULL
, NULL
)
1017 && strncmp (fn
, "KERNEL32!IsBad",
1018 strlen ("KERNEL32!IsBad")) == 0))
1023 case STATUS_STACK_OVERFLOW
:
1024 DEBUG_EXCEPTION_SIMPLE ("STATUS_STACK_OVERFLOW");
1025 ourstatus
->value
.sig
= GDB_SIGNAL_SEGV
;
1027 case STATUS_FLOAT_DENORMAL_OPERAND
:
1028 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DENORMAL_OPERAND");
1029 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1031 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED
:
1032 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ARRAY_BOUNDS_EXCEEDED");
1033 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1035 case STATUS_FLOAT_INEXACT_RESULT
:
1036 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INEXACT_RESULT");
1037 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1039 case STATUS_FLOAT_INVALID_OPERATION
:
1040 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INVALID_OPERATION");
1041 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1043 case STATUS_FLOAT_OVERFLOW
:
1044 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_OVERFLOW");
1045 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1047 case STATUS_FLOAT_STACK_CHECK
:
1048 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_STACK_CHECK");
1049 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1051 case STATUS_FLOAT_UNDERFLOW
:
1052 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_UNDERFLOW");
1053 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1055 case STATUS_FLOAT_DIVIDE_BY_ZERO
:
1056 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DIVIDE_BY_ZERO");
1057 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1059 case STATUS_INTEGER_DIVIDE_BY_ZERO
:
1060 DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_DIVIDE_BY_ZERO");
1061 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1063 case STATUS_INTEGER_OVERFLOW
:
1064 DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_OVERFLOW");
1065 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1067 case EXCEPTION_BREAKPOINT
:
1068 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_BREAKPOINT");
1069 ourstatus
->value
.sig
= GDB_SIGNAL_TRAP
;
1072 DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_C");
1073 ourstatus
->value
.sig
= GDB_SIGNAL_INT
;
1075 case DBG_CONTROL_BREAK
:
1076 DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_BREAK");
1077 ourstatus
->value
.sig
= GDB_SIGNAL_INT
;
1079 case EXCEPTION_SINGLE_STEP
:
1080 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_SINGLE_STEP");
1081 ourstatus
->value
.sig
= GDB_SIGNAL_TRAP
;
1083 case EXCEPTION_ILLEGAL_INSTRUCTION
:
1084 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ILLEGAL_INSTRUCTION");
1085 ourstatus
->value
.sig
= GDB_SIGNAL_ILL
;
1087 case EXCEPTION_PRIV_INSTRUCTION
:
1088 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_PRIV_INSTRUCTION");
1089 ourstatus
->value
.sig
= GDB_SIGNAL_ILL
;
1091 case EXCEPTION_NONCONTINUABLE_EXCEPTION
:
1092 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_NONCONTINUABLE_EXCEPTION");
1093 ourstatus
->value
.sig
= GDB_SIGNAL_ILL
;
1096 /* Treat unhandled first chance exceptions specially. */
1097 if (current_event
.u
.Exception
.dwFirstChance
)
1099 printf_unfiltered ("gdb: unknown target exception 0x%08x at %s\n",
1100 (unsigned) current_event
.u
.Exception
.ExceptionRecord
.ExceptionCode
,
1101 host_address_to_string (
1102 current_event
.u
.Exception
.ExceptionRecord
.ExceptionAddress
));
1103 ourstatus
->value
.sig
= GDB_SIGNAL_UNKNOWN
;
1107 last_sig
= ourstatus
->value
.sig
;
1111 /* Resume thread specified by ID, or all artificially suspended
1112 threads, if we are continuing execution. KILLED non-zero means we
1113 have killed the inferior, so we should ignore weird errors due to
1114 threads shutting down. */
1116 windows_continue (DWORD continue_status
, int id
, int killed
)
1122 DEBUG_EVENTS (("ContinueDebugEvent (cpid=%d, ctid=0x%x, %s);\n",
1123 (unsigned) current_event
.dwProcessId
,
1124 (unsigned) current_event
.dwThreadId
,
1125 continue_status
== DBG_CONTINUE
?
1126 "DBG_CONTINUE" : "DBG_EXCEPTION_NOT_HANDLED"));
1128 for (th
= &thread_head
; (th
= th
->next
) != NULL
;)
1129 if ((id
== -1 || id
== (int) th
->id
)
1132 if (debug_registers_changed
)
1134 th
->context
.ContextFlags
|= CONTEXT_DEBUG_REGISTERS
;
1135 th
->context
.Dr0
= dr
[0];
1136 th
->context
.Dr1
= dr
[1];
1137 th
->context
.Dr2
= dr
[2];
1138 th
->context
.Dr3
= dr
[3];
1139 th
->context
.Dr6
= DR6_CLEAR_VALUE
;
1140 th
->context
.Dr7
= dr
[7];
1142 if (th
->context
.ContextFlags
)
1146 if (GetExitCodeThread (th
->h
, &ec
)
1147 && ec
== STILL_ACTIVE
)
1149 BOOL status
= SetThreadContext (th
->h
, &th
->context
);
1154 th
->context
.ContextFlags
= 0;
1156 if (th
->suspended
> 0)
1157 (void) ResumeThread (th
->h
);
1161 res
= ContinueDebugEvent (current_event
.dwProcessId
,
1162 current_event
.dwThreadId
,
1165 debug_registers_changed
= 0;
1169 /* Called in pathological case where Windows fails to send a
1170 CREATE_PROCESS_DEBUG_EVENT after an attach. */
1172 fake_create_process (void)
1174 current_process_handle
= OpenProcess (PROCESS_ALL_ACCESS
, FALSE
,
1175 current_event
.dwProcessId
);
1176 if (current_process_handle
!= NULL
)
1177 open_process_used
= 1;
1180 error (_("OpenProcess call failed, GetLastError = %u"),
1181 (unsigned) GetLastError ());
1182 /* We can not debug anything in that case. */
1184 main_thread_id
= current_event
.dwThreadId
;
1185 current_thread
= windows_add_thread (
1186 ptid_build (current_event
.dwProcessId
, 0,
1187 current_event
.dwThreadId
),
1188 current_event
.u
.CreateThread
.hThread
,
1189 current_event
.u
.CreateThread
.lpThreadLocalBase
);
1190 return main_thread_id
;
1194 windows_resume (struct target_ops
*ops
,
1195 ptid_t ptid
, int step
, enum gdb_signal sig
)
1198 DWORD continue_status
= DBG_CONTINUE
;
1200 /* A specific PTID means `step only this thread id'. */
1201 int resume_all
= ptid_equal (ptid
, minus_one_ptid
);
1203 /* If we're continuing all threads, it's the current inferior that
1204 should be handled specially. */
1206 ptid
= inferior_ptid
;
1208 if (sig
!= GDB_SIGNAL_0
)
1210 if (current_event
.dwDebugEventCode
!= EXCEPTION_DEBUG_EVENT
)
1212 DEBUG_EXCEPT(("Cannot continue with signal %d here.\n",sig
));
1214 else if (sig
== last_sig
)
1215 continue_status
= DBG_EXCEPTION_NOT_HANDLED
;
1218 /* This code does not seem to work, because
1219 the kernel does probably not consider changes in the ExceptionRecord
1220 structure when passing the exception to the inferior.
1221 Note that this seems possible in the exception handler itself. */
1224 for (i
= 0; xlate
[i
].them
!= -1; i
++)
1225 if (xlate
[i
].us
== sig
)
1227 current_event
.u
.Exception
.ExceptionRecord
.ExceptionCode
1229 continue_status
= DBG_EXCEPTION_NOT_HANDLED
;
1232 if (continue_status
== DBG_CONTINUE
)
1234 DEBUG_EXCEPT(("Cannot continue with signal %d.\n",sig
));
1238 DEBUG_EXCEPT(("Can only continue with recieved signal %d.\n",
1242 last_sig
= GDB_SIGNAL_0
;
1244 DEBUG_EXEC (("gdb: windows_resume (pid=%d, tid=%ld, step=%d, sig=%d);\n",
1245 ptid_get_pid (ptid
), ptid_get_tid (ptid
), step
, sig
));
1247 /* Get context for currently selected thread. */
1248 th
= thread_rec (ptid_get_tid (inferior_ptid
), FALSE
);
1253 /* Single step by setting t bit. */
1254 struct regcache
*regcache
= get_current_regcache ();
1255 struct gdbarch
*gdbarch
= get_regcache_arch (regcache
);
1256 windows_fetch_inferior_registers (ops
, regcache
,
1257 gdbarch_ps_regnum (gdbarch
));
1258 th
->context
.EFlags
|= FLAG_TRACE_BIT
;
1261 if (th
->context
.ContextFlags
)
1263 if (debug_registers_changed
)
1265 th
->context
.Dr0
= dr
[0];
1266 th
->context
.Dr1
= dr
[1];
1267 th
->context
.Dr2
= dr
[2];
1268 th
->context
.Dr3
= dr
[3];
1269 th
->context
.Dr6
= DR6_CLEAR_VALUE
;
1270 th
->context
.Dr7
= dr
[7];
1272 CHECK (SetThreadContext (th
->h
, &th
->context
));
1273 th
->context
.ContextFlags
= 0;
1277 /* Allow continuing with the same signal that interrupted us.
1278 Otherwise complain. */
1281 windows_continue (continue_status
, -1, 0);
1283 windows_continue (continue_status
, ptid_get_tid (ptid
), 0);
1286 /* Ctrl-C handler used when the inferior is not run in the same console. The
1287 handler is in charge of interrupting the inferior using DebugBreakProcess.
1288 Note that this function is not available prior to Windows XP. In this case
1289 we emit a warning. */
1291 ctrl_c_handler (DWORD event_type
)
1293 const int attach_flag
= current_inferior ()->attach_flag
;
1295 /* Only handle Ctrl-C and Ctrl-Break events. Ignore others. */
1296 if (event_type
!= CTRL_C_EVENT
&& event_type
!= CTRL_BREAK_EVENT
)
1299 /* If the inferior and the debugger share the same console, do nothing as
1300 the inferior has also received the Ctrl-C event. */
1301 if (!new_console
&& !attach_flag
)
1304 if (!DebugBreakProcess (current_process_handle
))
1305 warning (_("Could not interrupt program. "
1306 "Press Ctrl-c in the program console."));
1308 /* Return true to tell that Ctrl-C has been handled. */
1312 /* Get the next event from the child. Return 1 if the event requires
1313 handling by WFI (or whatever). */
1315 get_windows_debug_event (struct target_ops
*ops
,
1316 int pid
, struct target_waitstatus
*ourstatus
)
1319 DWORD continue_status
, event_code
;
1321 static thread_info dummy_thread_info
;
1324 last_sig
= GDB_SIGNAL_0
;
1326 if (!(debug_event
= WaitForDebugEvent (¤t_event
, 1000)))
1330 continue_status
= DBG_CONTINUE
;
1332 event_code
= current_event
.dwDebugEventCode
;
1333 ourstatus
->kind
= TARGET_WAITKIND_SPURIOUS
;
1335 have_saved_context
= 0;
1339 case CREATE_THREAD_DEBUG_EVENT
:
1340 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1341 (unsigned) current_event
.dwProcessId
,
1342 (unsigned) current_event
.dwThreadId
,
1343 "CREATE_THREAD_DEBUG_EVENT"));
1344 if (saw_create
!= 1)
1346 struct inferior
*inf
;
1347 inf
= find_inferior_pid (current_event
.dwProcessId
);
1348 if (!saw_create
&& inf
->attach_flag
)
1350 /* Kludge around a Windows bug where first event is a create
1351 thread event. Caused when attached process does not have
1353 retval
= fake_create_process ();
1359 /* Record the existence of this thread. */
1360 retval
= current_event
.dwThreadId
;
1361 th
= windows_add_thread (ptid_build (current_event
.dwProcessId
, 0,
1362 current_event
.dwThreadId
),
1363 current_event
.u
.CreateThread
.hThread
,
1364 current_event
.u
.CreateThread
.lpThreadLocalBase
);
1368 case EXIT_THREAD_DEBUG_EVENT
:
1369 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1370 (unsigned) current_event
.dwProcessId
,
1371 (unsigned) current_event
.dwThreadId
,
1372 "EXIT_THREAD_DEBUG_EVENT"));
1374 if (current_event
.dwThreadId
!= main_thread_id
)
1376 windows_delete_thread (ptid_build (current_event
.dwProcessId
, 0,
1377 current_event
.dwThreadId
),
1378 current_event
.u
.ExitThread
.dwExitCode
);
1379 th
= &dummy_thread_info
;
1383 case CREATE_PROCESS_DEBUG_EVENT
:
1384 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1385 (unsigned) current_event
.dwProcessId
,
1386 (unsigned) current_event
.dwThreadId
,
1387 "CREATE_PROCESS_DEBUG_EVENT"));
1388 CloseHandle (current_event
.u
.CreateProcessInfo
.hFile
);
1389 if (++saw_create
!= 1)
1392 current_process_handle
= current_event
.u
.CreateProcessInfo
.hProcess
;
1394 windows_delete_thread (ptid_build (current_event
.dwProcessId
, 0,
1397 main_thread_id
= current_event
.dwThreadId
;
1398 /* Add the main thread. */
1399 th
= windows_add_thread (ptid_build (current_event
.dwProcessId
, 0,
1400 current_event
.dwThreadId
),
1401 current_event
.u
.CreateProcessInfo
.hThread
,
1402 current_event
.u
.CreateProcessInfo
.lpThreadLocalBase
);
1403 retval
= current_event
.dwThreadId
;
1406 case EXIT_PROCESS_DEBUG_EVENT
:
1407 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1408 (unsigned) current_event
.dwProcessId
,
1409 (unsigned) current_event
.dwThreadId
,
1410 "EXIT_PROCESS_DEBUG_EVENT"));
1411 if (!windows_initialization_done
)
1413 target_terminal_ours ();
1414 target_mourn_inferior ();
1415 error (_("During startup program exited with code 0x%x."),
1416 (unsigned int) current_event
.u
.ExitProcess
.dwExitCode
);
1418 else if (saw_create
== 1)
1420 ourstatus
->kind
= TARGET_WAITKIND_EXITED
;
1421 ourstatus
->value
.integer
= current_event
.u
.ExitProcess
.dwExitCode
;
1422 retval
= main_thread_id
;
1426 case LOAD_DLL_DEBUG_EVENT
:
1427 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1428 (unsigned) current_event
.dwProcessId
,
1429 (unsigned) current_event
.dwThreadId
,
1430 "LOAD_DLL_DEBUG_EVENT"));
1431 CloseHandle (current_event
.u
.LoadDll
.hFile
);
1432 if (saw_create
!= 1 || ! windows_initialization_done
)
1434 catch_errors (handle_load_dll
, NULL
, (char *) "", RETURN_MASK_ALL
);
1435 ourstatus
->kind
= TARGET_WAITKIND_LOADED
;
1436 ourstatus
->value
.integer
= 0;
1437 retval
= main_thread_id
;
1440 case UNLOAD_DLL_DEBUG_EVENT
:
1441 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1442 (unsigned) current_event
.dwProcessId
,
1443 (unsigned) current_event
.dwThreadId
,
1444 "UNLOAD_DLL_DEBUG_EVENT"));
1445 if (saw_create
!= 1 || ! windows_initialization_done
)
1447 catch_errors (handle_unload_dll
, NULL
, (char *) "", RETURN_MASK_ALL
);
1448 ourstatus
->kind
= TARGET_WAITKIND_LOADED
;
1449 ourstatus
->value
.integer
= 0;
1450 retval
= main_thread_id
;
1453 case EXCEPTION_DEBUG_EVENT
:
1454 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1455 (unsigned) current_event
.dwProcessId
,
1456 (unsigned) current_event
.dwThreadId
,
1457 "EXCEPTION_DEBUG_EVENT"));
1458 if (saw_create
!= 1)
1460 switch (handle_exception (ourstatus
))
1463 continue_status
= DBG_EXCEPTION_NOT_HANDLED
;
1466 retval
= current_event
.dwThreadId
;
1470 continue_status
= -1;
1475 case OUTPUT_DEBUG_STRING_EVENT
: /* Message from the kernel. */
1476 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1477 (unsigned) current_event
.dwProcessId
,
1478 (unsigned) current_event
.dwThreadId
,
1479 "OUTPUT_DEBUG_STRING_EVENT"));
1480 if (saw_create
!= 1)
1482 retval
= handle_output_debug_string (ourstatus
);
1486 if (saw_create
!= 1)
1488 printf_unfiltered ("gdb: kernel event for pid=%u tid=0x%x\n",
1489 (unsigned) current_event
.dwProcessId
,
1490 (unsigned) current_event
.dwThreadId
);
1491 printf_unfiltered (" unknown event code %u\n",
1492 (unsigned) current_event
.dwDebugEventCode
);
1496 if (!retval
|| saw_create
!= 1)
1498 if (continue_status
== -1)
1499 windows_resume (ops
, minus_one_ptid
, 0, 1);
1501 CHECK (windows_continue (continue_status
, -1, 0));
1505 inferior_ptid
= ptid_build (current_event
.dwProcessId
, 0,
1507 current_thread
= th
?: thread_rec (current_event
.dwThreadId
, TRUE
);
1514 /* Wait for interesting events to occur in the target process. */
1516 windows_wait (struct target_ops
*ops
,
1517 ptid_t ptid
, struct target_waitstatus
*ourstatus
, int options
)
1521 target_terminal_ours ();
1523 /* We loop when we get a non-standard exception rather than return
1524 with a SPURIOUS because resume can try and step or modify things,
1525 which needs a current_thread->h. But some of these exceptions mark
1526 the birth or death of threads, which mean that the current thread
1527 isn't necessarily what you think it is. */
1533 /* If the user presses Ctrl-c while the debugger is waiting
1534 for an event, he expects the debugger to interrupt his program
1535 and to get the prompt back. There are two possible situations:
1537 - The debugger and the program do not share the console, in
1538 which case the Ctrl-c event only reached the debugger.
1539 In that case, the ctrl_c handler will take care of interrupting
1540 the inferior. Note that this case is working starting with
1541 Windows XP. For Windows 2000, Ctrl-C should be pressed in the
1544 - The debugger and the program share the same console, in which
1545 case both debugger and inferior will receive the Ctrl-c event.
1546 In that case the ctrl_c handler will ignore the event, as the
1547 Ctrl-c event generated inside the inferior will trigger the
1548 expected debug event.
1550 FIXME: brobecker/2008-05-20: If the inferior receives the
1551 signal first and the delay until GDB receives that signal
1552 is sufficiently long, GDB can sometimes receive the SIGINT
1553 after we have unblocked the CTRL+C handler. This would
1554 lead to the debugger stopping prematurely while handling
1555 the new-thread event that comes with the handling of the SIGINT
1556 inside the inferior, and then stop again immediately when
1557 the user tries to resume the execution in the inferior.
1558 This is a classic race that we should try to fix one day. */
1559 SetConsoleCtrlHandler (&ctrl_c_handler
, TRUE
);
1560 retval
= get_windows_debug_event (ops
, pid
, ourstatus
);
1561 SetConsoleCtrlHandler (&ctrl_c_handler
, FALSE
);
1564 return ptid_build (current_event
.dwProcessId
, 0, retval
);
1569 if (deprecated_ui_loop_hook
!= NULL
)
1570 detach
= deprecated_ui_loop_hook (0);
1573 windows_kill_inferior (ops
);
1578 /* Iterate over all DLLs currently mapped by our inferior, and
1579 add them to our list of solibs. */
1582 windows_add_all_dlls (void)
1585 HMODULE dummy_hmodule
;
1590 if (EnumProcessModules (current_process_handle
, &dummy_hmodule
,
1591 sizeof (HMODULE
), &cb_needed
) == 0)
1597 hmodules
= (HMODULE
*) alloca (cb_needed
);
1598 if (EnumProcessModules (current_process_handle
, hmodules
,
1599 cb_needed
, &cb_needed
) == 0)
1602 for (i
= 1; i
< (int) (cb_needed
/ sizeof (HMODULE
)); i
++)
1606 wchar_t dll_name
[__PMAX
];
1609 char dll_name
[__PMAX
];
1612 if (GetModuleInformation (current_process_handle
, hmodules
[i
],
1613 &mi
, sizeof (mi
)) == 0)
1615 if (GetModuleFileNameEx (current_process_handle
, hmodules
[i
],
1616 dll_name
, sizeof (dll_name
)) == 0)
1619 wcstombs (name
, dll_name
, __PMAX
);
1624 solib_end
->next
= windows_make_so (name
, mi
.lpBaseOfDll
);
1625 solib_end
= solib_end
->next
;
1630 do_initial_windows_stuff (struct target_ops
*ops
, DWORD pid
, int attaching
)
1632 extern int stop_after_trap
;
1634 struct inferior
*inf
;
1635 struct thread_info
*tp
;
1637 last_sig
= GDB_SIGNAL_0
;
1639 exception_count
= 0;
1640 open_process_used
= 0;
1641 debug_registers_changed
= 0;
1642 debug_registers_used
= 0;
1643 for (i
= 0; i
< sizeof (dr
) / sizeof (dr
[0]); i
++)
1646 cygwin_load_start
= cygwin_load_end
= 0;
1648 current_event
.dwProcessId
= pid
;
1649 memset (¤t_event
, 0, sizeof (current_event
));
1650 if (!target_is_pushed (ops
))
1652 disable_breakpoints_in_shlibs ();
1653 windows_clear_solib ();
1654 clear_proceed_status (0);
1655 init_wait_for_inferior ();
1657 inf
= current_inferior ();
1658 inferior_appeared (inf
, pid
);
1659 inf
->attach_flag
= attaching
;
1661 /* Make the new process the current inferior, so terminal handling
1662 can rely on it. When attaching, we don't know about any thread
1663 id here, but that's OK --- nothing should be referencing the
1664 current thread until we report an event out of windows_wait. */
1665 inferior_ptid
= pid_to_ptid (pid
);
1667 target_terminal_init ();
1668 target_terminal_inferior ();
1670 windows_initialization_done
= 0;
1671 inf
->control
.stop_soon
= STOP_QUIETLY
;
1674 stop_after_trap
= 1;
1675 wait_for_inferior ();
1676 tp
= inferior_thread ();
1677 if (tp
->suspend
.stop_signal
!= GDB_SIGNAL_TRAP
)
1678 resume (0, tp
->suspend
.stop_signal
);
1683 /* Now that the inferior has been started and all DLLs have been mapped,
1684 we can iterate over all DLLs and load them in.
1686 We avoid doing it any earlier because, on certain versions of Windows,
1687 LOAD_DLL_DEBUG_EVENTs are sometimes not complete. In particular,
1688 we have seen on Windows 8.1 that the ntdll.dll load event does not
1689 include the DLL name, preventing us from creating an associated SO.
1690 A possible explanation is that ntdll.dll might be mapped before
1691 the SO info gets created by the Windows system -- ntdll.dll is
1692 the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs
1693 do not seem to suffer from that problem.
1695 Rather than try to work around this sort of issue, it is much
1696 simpler to just ignore DLL load/unload events during the startup
1697 phase, and then process them all in one batch now. */
1698 windows_add_all_dlls ();
1700 windows_initialization_done
= 1;
1701 inf
->control
.stop_soon
= NO_STOP_QUIETLY
;
1702 stop_after_trap
= 0;
1706 /* Try to set or remove a user privilege to the current process. Return -1
1707 if that fails, the previous setting of that privilege otherwise.
1709 This code is copied from the Cygwin source code and rearranged to allow
1710 dynamically loading of the needed symbols from advapi32 which is only
1711 available on NT/2K/XP. */
1713 set_process_privilege (const char *privilege
, BOOL enable
)
1715 HANDLE token_hdl
= NULL
;
1717 TOKEN_PRIVILEGES new_priv
, orig_priv
;
1721 if (!OpenProcessToken (GetCurrentProcess (),
1722 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
1726 if (!LookupPrivilegeValueA (NULL
, privilege
, &restore_priv
))
1729 new_priv
.PrivilegeCount
= 1;
1730 new_priv
.Privileges
[0].Luid
= restore_priv
;
1731 new_priv
.Privileges
[0].Attributes
= enable
? SE_PRIVILEGE_ENABLED
: 0;
1733 if (!AdjustTokenPrivileges (token_hdl
, FALSE
, &new_priv
,
1734 sizeof orig_priv
, &orig_priv
, &size
))
1737 /* Disabled, otherwise every `attach' in an unprivileged user session
1738 would raise the "Failed to get SE_DEBUG_NAME privilege" warning in
1739 windows_attach(). */
1740 /* AdjustTokenPrivileges returns TRUE even if the privilege could not
1741 be enabled. GetLastError () returns an correct error code, though. */
1742 if (enable
&& GetLastError () == ERROR_NOT_ALL_ASSIGNED
)
1746 ret
= orig_priv
.Privileges
[0].Attributes
== SE_PRIVILEGE_ENABLED
? 1 : 0;
1750 CloseHandle (token_hdl
);
1755 /* Attach to process PID, then initialize for debugging it. */
1757 windows_attach (struct target_ops
*ops
, const char *args
, int from_tty
)
1762 pid
= parse_pid_to_attach (args
);
1764 if (set_process_privilege (SE_DEBUG_NAME
, TRUE
) < 0)
1766 printf_unfiltered ("Warning: Failed to get SE_DEBUG_NAME privilege\n");
1767 printf_unfiltered ("This can cause attach to "
1768 "fail on Windows NT/2K/XP\n");
1771 windows_init_thread_list ();
1772 ok
= DebugActiveProcess (pid
);
1778 /* Try fall back to Cygwin pid. */
1779 pid
= cygwin_internal (CW_CYGWIN_PID_TO_WINPID
, pid
);
1782 ok
= DebugActiveProcess (pid
);
1787 error (_("Can't attach to process."));
1789 DebugSetProcessKillOnExit (FALSE
);
1793 char *exec_file
= (char *) get_exec_file (0);
1796 printf_unfiltered ("Attaching to program `%s', %s\n", exec_file
,
1797 target_pid_to_str (pid_to_ptid (pid
)));
1799 printf_unfiltered ("Attaching to %s\n",
1800 target_pid_to_str (pid_to_ptid (pid
)));
1802 gdb_flush (gdb_stdout
);
1805 do_initial_windows_stuff (ops
, pid
, 1);
1806 target_terminal_ours ();
1810 windows_detach (struct target_ops
*ops
, const char *args
, int from_tty
)
1815 windows_resume (ops
, ptid
, 0, GDB_SIGNAL_0
);
1817 if (!DebugActiveProcessStop (current_event
.dwProcessId
))
1819 error (_("Can't detach process %u (error %u)"),
1820 (unsigned) current_event
.dwProcessId
, (unsigned) GetLastError ());
1823 DebugSetProcessKillOnExit (FALSE
);
1825 if (detached
&& from_tty
)
1827 char *exec_file
= get_exec_file (0);
1830 printf_unfiltered ("Detaching from program: %s, Pid %u\n", exec_file
,
1831 (unsigned) current_event
.dwProcessId
);
1832 gdb_flush (gdb_stdout
);
1835 x86_cleanup_dregs ();
1836 inferior_ptid
= null_ptid
;
1837 detach_inferior (current_event
.dwProcessId
);
1839 inf_child_maybe_unpush_target (ops
);
1842 /* Try to determine the executable filename.
1844 EXE_NAME_RET is a pointer to a buffer whose size is EXE_NAME_MAX_LEN.
1846 Upon success, the filename is stored inside EXE_NAME_RET, and
1847 this function returns nonzero.
1849 Otherwise, this function returns zero and the contents of
1850 EXE_NAME_RET is undefined. */
1853 windows_get_exec_module_filename (char *exe_name_ret
, size_t exe_name_max_len
)
1860 if (!EnumProcessModules (current_process_handle
, &dh_buf
,
1861 sizeof (HMODULE
), &cbNeeded
) || !cbNeeded
)
1864 /* We know the executable is always first in the list of modules,
1865 which we just fetched. So no need to fetch more. */
1869 /* Cygwin prefers that the path be in /x/y/z format, so extract
1870 the filename into a temporary buffer first, and then convert it
1871 to POSIX format into the destination buffer. */
1872 cygwin_buf_t
*pathbuf
= alloca (exe_name_max_len
* sizeof (cygwin_buf_t
));
1874 len
= GetModuleFileNameEx (current_process_handle
,
1875 dh_buf
, pathbuf
, exe_name_max_len
);
1877 error (_("Error getting executable filename: %u."),
1878 (unsigned) GetLastError ());
1879 if (cygwin_conv_path (CCP_WIN_W_TO_POSIX
, pathbuf
, exe_name_ret
,
1880 exe_name_max_len
) < 0)
1881 error (_("Error converting executable filename to POSIX: %d."), errno
);
1884 len
= GetModuleFileNameEx (current_process_handle
,
1885 dh_buf
, exe_name_ret
, exe_name_max_len
);
1887 error (_("Error getting executable filename: %u."),
1888 (unsigned) GetLastError ());
1891 return 1; /* success */
1894 /* The pid_to_exec_file target_ops method for this platform. */
1897 windows_pid_to_exec_file (struct target_ops
*self
, int pid
)
1899 static char path
[__PMAX
];
1901 /* Try to find exe name as symlink target of /proc/<pid>/exe. */
1903 char procexe
[sizeof ("/proc/4294967295/exe")];
1905 xsnprintf (procexe
, sizeof (procexe
), "/proc/%u/exe", pid
);
1906 nchars
= readlink (procexe
, path
, sizeof(path
));
1907 if (nchars
> 0 && nchars
< sizeof (path
))
1909 path
[nchars
] = '\0'; /* Got it */
1914 /* If we get here then either Cygwin is hosed, this isn't a Cygwin version
1915 of gdb, or we're trying to debug a non-Cygwin windows executable. */
1916 if (!windows_get_exec_module_filename (path
, sizeof (path
)))
1922 /* Print status information about what we're accessing. */
1925 windows_files_info (struct target_ops
*ignore
)
1927 struct inferior
*inf
= current_inferior ();
1929 printf_unfiltered ("\tUsing the running image of %s %s.\n",
1930 inf
->attach_flag
? "attached" : "child",
1931 target_pid_to_str (inferior_ptid
));
1934 /* Modify CreateProcess parameters for use of a new separate console.
1936 *FLAGS: DWORD parameter for general process creation flags.
1937 *SI: STARTUPINFO structure, for which the console window size and
1938 console buffer size is filled in if GDB is running in a console.
1939 to create the new console.
1940 The size of the used font is not available on all versions of
1941 Windows OS. Furthermore, the current font might not be the default
1942 font, but this is still better than before.
1943 If the windows and buffer sizes are computed,
1944 SI->DWFLAGS is changed so that this information is used
1945 by CreateProcess function. */
1948 windows_set_console_info (STARTUPINFO
*si
, DWORD
*flags
)
1950 HANDLE hconsole
= CreateFile ("CONOUT$", GENERIC_READ
| GENERIC_WRITE
,
1951 FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, 0, 0);
1953 if (hconsole
!= INVALID_HANDLE_VALUE
)
1955 CONSOLE_SCREEN_BUFFER_INFO sbinfo
;
1957 CONSOLE_FONT_INFO cfi
;
1959 GetCurrentConsoleFont (hconsole
, FALSE
, &cfi
);
1960 font_size
= GetConsoleFontSize (hconsole
, cfi
.nFont
);
1961 GetConsoleScreenBufferInfo(hconsole
, &sbinfo
);
1962 si
->dwXSize
= sbinfo
.srWindow
.Right
- sbinfo
.srWindow
.Left
+ 1;
1963 si
->dwYSize
= sbinfo
.srWindow
.Bottom
- sbinfo
.srWindow
.Top
+ 1;
1965 si
->dwXSize
*= font_size
.X
;
1969 si
->dwYSize
*= font_size
.Y
;
1972 si
->dwXCountChars
= sbinfo
.dwSize
.X
;
1973 si
->dwYCountChars
= sbinfo
.dwSize
.Y
;
1974 si
->dwFlags
|= STARTF_USESIZE
| STARTF_USECOUNTCHARS
;
1976 *flags
|= CREATE_NEW_CONSOLE
;
1980 /* Function called by qsort to sort environment strings. */
1983 envvar_cmp (const void *a
, const void *b
)
1985 const char **p
= (const char **) a
;
1986 const char **q
= (const char **) b
;
1987 return strcasecmp (*p
, *q
);
1993 clear_win32_environment (char **env
)
1997 wchar_t *copy
= NULL
, *equalpos
;
1999 for (i
= 0; env
[i
] && *env
[i
]; i
++)
2001 len
= mbstowcs (NULL
, env
[i
], 0) + 1;
2002 copy
= (wchar_t *) xrealloc (copy
, len
* sizeof (wchar_t));
2003 mbstowcs (copy
, env
[i
], len
);
2004 equalpos
= wcschr (copy
, L
'=');
2007 SetEnvironmentVariableW (copy
, NULL
);
2013 /* Start an inferior windows child process and sets inferior_ptid to its pid.
2014 EXEC_FILE is the file to run.
2015 ALLARGS is a string containing the arguments to the program.
2016 ENV is the environment vector to pass. Errors reported with error(). */
2019 windows_create_inferior (struct target_ops
*ops
, char *exec_file
,
2020 char *allargs
, char **in_env
, int from_tty
)
2024 cygwin_buf_t real_path
[__PMAX
];
2025 cygwin_buf_t shell
[__PMAX
]; /* Path to shell */
2027 cygwin_buf_t
*toexec
;
2028 cygwin_buf_t
*cygallargs
;
2030 char **old_env
= NULL
;
2034 int ostdin
, ostdout
, ostderr
;
2036 char real_path
[__PMAX
];
2037 char shell
[__PMAX
]; /* Path to shell */
2049 PROCESS_INFORMATION pi
;
2052 const char *inferior_io_terminal
= get_inferior_io_terminal ();
2055 error (_("No executable specified, use `target exec'."));
2057 memset (&si
, 0, sizeof (si
));
2058 si
.cb
= sizeof (si
);
2061 flags
|= CREATE_NEW_PROCESS_GROUP
;
2064 windows_set_console_info (&si
, &flags
);
2069 flags
|= DEBUG_ONLY_THIS_PROCESS
;
2070 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W
, exec_file
, real_path
,
2071 __PMAX
* sizeof (cygwin_buf_t
)) < 0)
2072 error (_("Error starting executable: %d"), errno
);
2075 len
= mbstowcs (NULL
, allargs
, 0) + 1;
2076 if (len
== (size_t) -1)
2077 error (_("Error starting executable: %d"), errno
);
2078 cygallargs
= (wchar_t *) alloca (len
* sizeof (wchar_t));
2079 mbstowcs (cygallargs
, allargs
, len
);
2081 cygallargs
= allargs
;
2086 sh
= getenv ("SHELL");
2089 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W
, sh
, shell
, __PMAX
) < 0)
2090 error (_("Error starting executable via shell: %d"), errno
);
2092 len
= sizeof (L
" -c 'exec '") + mbstowcs (NULL
, exec_file
, 0)
2093 + mbstowcs (NULL
, allargs
, 0) + 2;
2094 cygallargs
= (wchar_t *) alloca (len
* sizeof (wchar_t));
2095 swprintf (cygallargs
, len
, L
" -c 'exec %s %s'", exec_file
, allargs
);
2097 len
= (sizeof (" -c 'exec '") + strlen (exec_file
)
2098 + strlen (allargs
) + 2);
2099 cygallargs
= (char *) alloca (len
);
2100 xsnprintf (cygallargs
, len
, " -c 'exec %s %s'", exec_file
, allargs
);
2103 flags
|= DEBUG_PROCESS
;
2107 args
= (cygwin_buf_t
*) alloca ((wcslen (toexec
) + wcslen (cygallargs
) + 2)
2108 * sizeof (wchar_t));
2109 wcscpy (args
, toexec
);
2110 wcscat (args
, L
" ");
2111 wcscat (args
, cygallargs
);
2113 args
= (cygwin_buf_t
*) alloca (strlen (toexec
) + strlen (cygallargs
) + 2);
2114 strcpy (args
, toexec
);
2116 strcat (args
, cygallargs
);
2119 #ifdef CW_CVT_ENV_TO_WINENV
2120 /* First try to create a direct Win32 copy of the POSIX environment. */
2121 w32_env
= (PWCHAR
) cygwin_internal (CW_CVT_ENV_TO_WINENV
, in_env
);
2122 if (w32_env
!= (PWCHAR
) -1)
2123 flags
|= CREATE_UNICODE_ENVIRONMENT
;
2125 /* If that fails, fall back to old method tweaking GDB's environment. */
2128 /* Reset all Win32 environment variables to avoid leftover on next run. */
2129 clear_win32_environment (environ
);
2130 /* Prepare the environment vars for CreateProcess. */
2133 cygwin_internal (CW_SYNC_WINENV
);
2137 if (!inferior_io_terminal
)
2138 tty
= ostdin
= ostdout
= ostderr
= -1;
2141 tty
= open (inferior_io_terminal
, O_RDWR
| O_NOCTTY
);
2144 print_sys_errmsg (inferior_io_terminal
, errno
);
2145 ostdin
= ostdout
= ostderr
= -1;
2158 windows_init_thread_list ();
2159 ret
= CreateProcess (0,
2160 args
, /* command line */
2161 NULL
, /* Security */
2163 TRUE
, /* inherit handles */
2164 flags
, /* start flags */
2165 w32_env
, /* environment */
2166 NULL
, /* current directory */
2170 /* Just free the Win32 environment, if it could be created. */
2174 /* Reset all environment variables to avoid leftover on next run. */
2175 clear_win32_environment (in_env
);
2176 /* Restore normal GDB environment variables. */
2178 cygwin_internal (CW_SYNC_WINENV
);
2193 /* Build the command line, a space-separated list of tokens where
2194 the first token is the name of the module to be executed.
2195 To avoid ambiguities introduced by spaces in the module name,
2197 args_len
= strlen (toexec
) + 2 /* quotes */ + strlen (allargs
) + 2;
2198 args
= alloca (args_len
);
2199 xsnprintf (args
, args_len
, "\"%s\" %s", toexec
, allargs
);
2201 flags
|= DEBUG_ONLY_THIS_PROCESS
;
2203 if (!inferior_io_terminal
)
2204 tty
= INVALID_HANDLE_VALUE
;
2207 SECURITY_ATTRIBUTES sa
;
2208 sa
.nLength
= sizeof(sa
);
2209 sa
.lpSecurityDescriptor
= 0;
2210 sa
.bInheritHandle
= TRUE
;
2211 tty
= CreateFileA (inferior_io_terminal
, GENERIC_READ
| GENERIC_WRITE
,
2212 0, &sa
, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
2213 if (tty
== INVALID_HANDLE_VALUE
)
2214 warning (_("Warning: Failed to open TTY %s, error %#x."),
2215 inferior_io_terminal
, (unsigned) GetLastError ());
2219 si
.hStdOutput
= tty
;
2221 si
.dwFlags
|= STARTF_USESTDHANDLES
;
2225 /* CreateProcess takes the environment list as a null terminated set of
2226 strings (i.e. two nulls terminate the list). */
2228 /* Get total size for env strings. */
2229 for (envlen
= 0, i
= 0; in_env
[i
] && *in_env
[i
]; i
++)
2230 envlen
+= strlen (in_env
[i
]) + 1;
2232 envsize
= sizeof (in_env
[0]) * (i
+ 1);
2233 env
= (char **) alloca (envsize
);
2234 memcpy (env
, in_env
, envsize
);
2235 /* Windows programs expect the environment block to be sorted. */
2236 qsort (env
, i
, sizeof (char *), envvar_cmp
);
2238 w32env
= alloca (envlen
+ 1);
2240 /* Copy env strings into new buffer. */
2241 for (temp
= w32env
, i
= 0; env
[i
] && *env
[i
]; i
++)
2243 strcpy (temp
, env
[i
]);
2244 temp
+= strlen (temp
) + 1;
2247 /* Final nil string to terminate new env. */
2250 windows_init_thread_list ();
2251 ret
= CreateProcessA (0,
2252 args
, /* command line */
2253 NULL
, /* Security */
2255 TRUE
, /* inherit handles */
2256 flags
, /* start flags */
2257 w32env
, /* environment */
2258 NULL
, /* current directory */
2261 if (tty
!= INVALID_HANDLE_VALUE
)
2266 error (_("Error creating process %s, (error %u)."),
2267 exec_file
, (unsigned) GetLastError ());
2269 CloseHandle (pi
.hThread
);
2270 CloseHandle (pi
.hProcess
);
2272 if (useshell
&& shell
[0] != '\0')
2277 do_initial_windows_stuff (ops
, pi
.dwProcessId
, 0);
2279 /* windows_continue (DBG_CONTINUE, -1, 0); */
2283 windows_mourn_inferior (struct target_ops
*ops
)
2285 (void) windows_continue (DBG_CONTINUE
, -1, 0);
2286 x86_cleanup_dregs();
2287 if (open_process_used
)
2289 CHECK (CloseHandle (current_process_handle
));
2290 open_process_used
= 0;
2292 inf_child_mourn_inferior (ops
);
2295 /* Send a SIGINT to the process group. This acts just like the user typed a
2296 ^C on the controlling terminal. */
2299 windows_stop (struct target_ops
*self
, ptid_t ptid
)
2301 DEBUG_EVENTS (("gdb: GenerateConsoleCtrlEvent (CTRLC_EVENT, 0)\n"));
2302 CHECK (GenerateConsoleCtrlEvent (CTRL_C_EVENT
, current_event
.dwProcessId
));
2303 registers_changed (); /* refresh register state */
2306 /* Helper for windows_xfer_partial that handles memory transfers.
2307 Arguments are like target_xfer_partial. */
2309 static enum target_xfer_status
2310 windows_xfer_memory (gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
2311 ULONGEST memaddr
, ULONGEST len
, ULONGEST
*xfered_len
)
2315 DWORD lasterror
= 0;
2317 if (writebuf
!= NULL
)
2319 DEBUG_MEM (("gdb: write target memory, %s bytes at %s\n",
2320 pulongest (len
), core_addr_to_string (memaddr
)));
2321 success
= WriteProcessMemory (current_process_handle
,
2322 (LPVOID
) (uintptr_t) memaddr
, writebuf
,
2325 lasterror
= GetLastError ();
2326 FlushInstructionCache (current_process_handle
,
2327 (LPCVOID
) (uintptr_t) memaddr
, len
);
2331 DEBUG_MEM (("gdb: read target memory, %s bytes at %s\n",
2332 pulongest (len
), core_addr_to_string (memaddr
)));
2333 success
= ReadProcessMemory (current_process_handle
,
2334 (LPCVOID
) (uintptr_t) memaddr
, readbuf
,
2337 lasterror
= GetLastError ();
2339 *xfered_len
= (ULONGEST
) done
;
2340 if (!success
&& lasterror
== ERROR_PARTIAL_COPY
&& done
> 0)
2341 return TARGET_XFER_OK
;
2343 return success
? TARGET_XFER_OK
: TARGET_XFER_E_IO
;
2347 windows_kill_inferior (struct target_ops
*ops
)
2349 CHECK (TerminateProcess (current_process_handle
, 0));
2353 if (!windows_continue (DBG_CONTINUE
, -1, 1))
2355 if (!WaitForDebugEvent (¤t_event
, INFINITE
))
2357 if (current_event
.dwDebugEventCode
== EXIT_PROCESS_DEBUG_EVENT
)
2361 target_mourn_inferior (); /* Or just windows_mourn_inferior? */
2365 windows_close (struct target_ops
*self
)
2367 DEBUG_EVENTS (("gdb: windows_close, inferior_ptid=%d\n",
2368 ptid_get_pid (inferior_ptid
)));
2371 /* Convert pid to printable format. */
2373 windows_pid_to_str (struct target_ops
*ops
, ptid_t ptid
)
2375 static char buf
[80];
2377 if (ptid_get_tid (ptid
) != 0)
2379 snprintf (buf
, sizeof (buf
), "Thread %d.0x%lx",
2380 ptid_get_pid (ptid
), ptid_get_tid (ptid
));
2384 return normal_pid_to_str (ptid
);
2387 static enum target_xfer_status
2388 windows_xfer_shared_libraries (struct target_ops
*ops
,
2389 enum target_object object
, const char *annex
,
2390 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
2391 ULONGEST offset
, ULONGEST len
,
2392 ULONGEST
*xfered_len
)
2394 struct obstack obstack
;
2400 return TARGET_XFER_E_IO
;
2402 obstack_init (&obstack
);
2403 obstack_grow_str (&obstack
, "<library-list>\n");
2404 for (so
= solib_start
.next
; so
; so
= so
->next
)
2405 windows_xfer_shared_library (so
->so_name
, (CORE_ADDR
)
2406 (uintptr_t) so
->lm_info
->load_addr
,
2407 target_gdbarch (), &obstack
);
2408 obstack_grow_str0 (&obstack
, "</library-list>\n");
2410 buf
= obstack_finish (&obstack
);
2411 len_avail
= strlen (buf
);
2412 if (offset
>= len_avail
)
2416 if (len
> len_avail
- offset
)
2417 len
= len_avail
- offset
;
2418 memcpy (readbuf
, buf
+ offset
, len
);
2421 obstack_free (&obstack
, NULL
);
2422 *xfered_len
= (ULONGEST
) len
;
2423 return len
!= 0 ? TARGET_XFER_OK
: TARGET_XFER_EOF
;
2426 static enum target_xfer_status
2427 windows_xfer_partial (struct target_ops
*ops
, enum target_object object
,
2428 const char *annex
, gdb_byte
*readbuf
,
2429 const gdb_byte
*writebuf
, ULONGEST offset
, ULONGEST len
,
2430 ULONGEST
*xfered_len
)
2434 case TARGET_OBJECT_MEMORY
:
2435 return windows_xfer_memory (readbuf
, writebuf
, offset
, len
, xfered_len
);
2437 case TARGET_OBJECT_LIBRARIES
:
2438 return windows_xfer_shared_libraries (ops
, object
, annex
, readbuf
,
2439 writebuf
, offset
, len
, xfered_len
);
2442 return ops
->beneath
->to_xfer_partial (ops
->beneath
, object
, annex
,
2443 readbuf
, writebuf
, offset
, len
,
2448 /* Provide thread local base, i.e. Thread Information Block address.
2449 Returns 1 if ptid is found and sets *ADDR to thread_local_base. */
2452 windows_get_tib_address (struct target_ops
*self
,
2453 ptid_t ptid
, CORE_ADDR
*addr
)
2457 th
= thread_rec (ptid_get_tid (ptid
), 0);
2462 *addr
= th
->thread_local_base
;
2468 windows_get_ada_task_ptid (struct target_ops
*self
, long lwp
, long thread
)
2470 return ptid_build (ptid_get_pid (inferior_ptid
), 0, lwp
);
2473 static struct target_ops
*
2474 windows_target (void)
2476 struct target_ops
*t
= inf_child_target ();
2478 t
->to_close
= windows_close
;
2479 t
->to_attach
= windows_attach
;
2480 t
->to_attach_no_wait
= 1;
2481 t
->to_detach
= windows_detach
;
2482 t
->to_resume
= windows_resume
;
2483 t
->to_wait
= windows_wait
;
2484 t
->to_fetch_registers
= windows_fetch_inferior_registers
;
2485 t
->to_store_registers
= windows_store_inferior_registers
;
2486 t
->to_xfer_partial
= windows_xfer_partial
;
2487 t
->to_files_info
= windows_files_info
;
2488 t
->to_kill
= windows_kill_inferior
;
2489 t
->to_create_inferior
= windows_create_inferior
;
2490 t
->to_mourn_inferior
= windows_mourn_inferior
;
2491 t
->to_thread_alive
= windows_thread_alive
;
2492 t
->to_pid_to_str
= windows_pid_to_str
;
2493 t
->to_stop
= windows_stop
;
2494 t
->to_pid_to_exec_file
= windows_pid_to_exec_file
;
2495 t
->to_get_ada_task_ptid
= windows_get_ada_task_ptid
;
2496 t
->to_get_tib_address
= windows_get_tib_address
;
2502 set_windows_aliases (char *argv0
)
2504 add_info_alias ("dll", "sharedlibrary", 1);
2507 /* -Wmissing-prototypes */
2508 extern initialize_file_ftype _initialize_windows_nat
;
2511 _initialize_windows_nat (void)
2513 struct target_ops
*t
;
2515 t
= windows_target ();
2517 x86_use_watchpoints (t
);
2519 x86_dr_low
.set_control
= cygwin_set_dr7
;
2520 x86_dr_low
.set_addr
= cygwin_set_dr
;
2521 x86_dr_low
.get_addr
= cygwin_get_dr
;
2522 x86_dr_low
.get_status
= cygwin_get_dr6
;
2523 x86_dr_low
.get_control
= cygwin_get_dr7
;
2525 /* x86_dr_low.debug_register_length field is set by
2526 calling x86_set_debug_register_length function
2527 in processor windows specific native file. */
2532 cygwin_internal (CW_SET_DOS_FILE_WARNING
, 0);
2536 add_setshow_boolean_cmd ("shell", class_support
, &useshell
, _("\
2537 Set use of shell to start subprocess."), _("\
2538 Show use of shell to start subprocess."), NULL
,
2540 NULL
, /* FIXME: i18n: */
2541 &setlist
, &showlist
);
2543 add_setshow_boolean_cmd ("cygwin-exceptions", class_support
,
2544 &cygwin_exceptions
, _("\
2545 Break when an exception is detected in the Cygwin DLL itself."), _("\
2546 Show whether gdb breaks on exceptions in the Cygwin DLL itself."), NULL
,
2548 NULL
, /* FIXME: i18n: */
2549 &setlist
, &showlist
);
2552 add_setshow_boolean_cmd ("new-console", class_support
, &new_console
, _("\
2553 Set creation of new console when creating child process."), _("\
2554 Show creation of new console when creating child process."), NULL
,
2556 NULL
, /* FIXME: i18n: */
2557 &setlist
, &showlist
);
2559 add_setshow_boolean_cmd ("new-group", class_support
, &new_group
, _("\
2560 Set creation of new group when creating child process."), _("\
2561 Show creation of new group when creating child process."), NULL
,
2563 NULL
, /* FIXME: i18n: */
2564 &setlist
, &showlist
);
2566 add_setshow_boolean_cmd ("debugexec", class_support
, &debug_exec
, _("\
2567 Set whether to display execution in child process."), _("\
2568 Show whether to display execution in child process."), NULL
,
2570 NULL
, /* FIXME: i18n: */
2571 &setlist
, &showlist
);
2573 add_setshow_boolean_cmd ("debugevents", class_support
, &debug_events
, _("\
2574 Set whether to display kernel events in child process."), _("\
2575 Show whether to display kernel events in child process."), NULL
,
2577 NULL
, /* FIXME: i18n: */
2578 &setlist
, &showlist
);
2580 add_setshow_boolean_cmd ("debugmemory", class_support
, &debug_memory
, _("\
2581 Set whether to display memory accesses in child process."), _("\
2582 Show whether to display memory accesses in child process."), NULL
,
2584 NULL
, /* FIXME: i18n: */
2585 &setlist
, &showlist
);
2587 add_setshow_boolean_cmd ("debugexceptions", class_support
,
2588 &debug_exceptions
, _("\
2589 Set whether to display kernel exceptions in child process."), _("\
2590 Show whether to display kernel exceptions in child process."), NULL
,
2592 NULL
, /* FIXME: i18n: */
2593 &setlist
, &showlist
);
2595 init_w32_command_list ();
2597 add_cmd ("selector", class_info
, display_selectors
,
2598 _("Display selectors infos."),
2600 deprecated_init_ui_hook
= set_windows_aliases
;
2603 /* Hardware watchpoint support, adapted from go32-nat.c code. */
2605 /* Pass the address ADDR to the inferior in the I'th debug register.
2606 Here we just store the address in dr array, the registers will be
2607 actually set up when windows_continue is called. */
2609 cygwin_set_dr (int i
, CORE_ADDR addr
)
2612 internal_error (__FILE__
, __LINE__
,
2613 _("Invalid register %d in cygwin_set_dr.\n"), i
);
2615 debug_registers_changed
= 1;
2616 debug_registers_used
= 1;
2619 /* Pass the value VAL to the inferior in the DR7 debug control
2620 register. Here we just store the address in D_REGS, the watchpoint
2621 will be actually set up in windows_wait. */
2623 cygwin_set_dr7 (unsigned long val
)
2625 dr
[7] = (CORE_ADDR
) val
;
2626 debug_registers_changed
= 1;
2627 debug_registers_used
= 1;
2630 /* Get the value of debug register I from the inferior. */
2633 cygwin_get_dr (int i
)
2638 /* Get the value of the DR6 debug status register from the inferior.
2639 Here we just return the value stored in dr[6]
2640 by the last call to thread_rec for current_event.dwThreadId id. */
2641 static unsigned long
2642 cygwin_get_dr6 (void)
2644 return (unsigned long) dr
[6];
2647 /* Get the value of the DR7 debug status register from the inferior.
2648 Here we just return the value stored in dr[7] by the last call to
2649 thread_rec for current_event.dwThreadId id. */
2651 static unsigned long
2652 cygwin_get_dr7 (void)
2654 return (unsigned long) dr
[7];
2657 /* Determine if the thread referenced by "ptid" is alive
2658 by "polling" it. If WaitForSingleObject returns WAIT_OBJECT_0
2659 it means that the thread has died. Otherwise it is assumed to be alive. */
2661 windows_thread_alive (struct target_ops
*ops
, ptid_t ptid
)
2665 gdb_assert (ptid_get_tid (ptid
) != 0);
2666 tid
= ptid_get_tid (ptid
);
2668 return WaitForSingleObject (thread_rec (tid
, FALSE
)->h
, 0) == WAIT_OBJECT_0
2672 /* -Wmissing-prototypes */
2673 extern initialize_file_ftype _initialize_check_for_gdb_ini
;
2676 _initialize_check_for_gdb_ini (void)
2679 if (inhibit_gdbinit
)
2682 homedir
= getenv ("HOME");
2686 char *oldini
= (char *) alloca (strlen (homedir
) +
2687 sizeof ("/gdb.ini"));
2688 strcpy (oldini
, homedir
);
2689 p
= strchr (oldini
, '\0');
2690 if (p
> oldini
&& !IS_DIR_SEPARATOR (p
[-1]))
2692 strcpy (p
, "gdb.ini");
2693 if (access (oldini
, 0) == 0)
2695 int len
= strlen (oldini
);
2696 char *newini
= alloca (len
+ 1);
2698 xsnprintf (newini
, len
+ 1, "%.*s.gdbinit",
2699 (int) (len
- (sizeof ("gdb.ini") - 1)), oldini
);
2700 warning (_("obsolete '%s' found. Rename to '%s'."), oldini
, newini
);
2705 /* Define dummy functions which always return error for the rare cases where
2706 these functions could not be found. */
2708 bad_DebugActiveProcessStop (DWORD w
)
2713 bad_DebugBreakProcess (HANDLE w
)
2718 bad_DebugSetProcessKillOnExit (BOOL w
)
2723 bad_EnumProcessModules (HANDLE w
, HMODULE
*x
, DWORD y
, LPDWORD z
)
2730 bad_GetModuleFileNameExW (HANDLE w
, HMODULE x
, LPWSTR y
, DWORD z
)
2736 bad_GetModuleFileNameExA (HANDLE w
, HMODULE x
, LPSTR y
, DWORD z
)
2743 bad_GetModuleInformation (HANDLE w
, HMODULE x
, LPMODULEINFO y
, DWORD z
)
2749 bad_OpenProcessToken (HANDLE w
, DWORD x
, PHANDLE y
)
2755 bad_GetCurrentConsoleFont (HANDLE w
, BOOL bMaxWindow
, CONSOLE_FONT_INFO
*f
)
2761 bad_GetConsoleFontSize (HANDLE w
, DWORD nFont
)
2769 /* -Wmissing-prototypes */
2770 extern initialize_file_ftype _initialize_loadable
;
2772 /* Load any functions which may not be available in ancient versions
2776 _initialize_loadable (void)
2780 hm
= LoadLibrary ("kernel32.dll");
2783 DebugActiveProcessStop
= (void *)
2784 GetProcAddress (hm
, "DebugActiveProcessStop");
2785 DebugBreakProcess
= (void *)
2786 GetProcAddress (hm
, "DebugBreakProcess");
2787 DebugSetProcessKillOnExit
= (void *)
2788 GetProcAddress (hm
, "DebugSetProcessKillOnExit");
2789 GetConsoleFontSize
= (void *)
2790 GetProcAddress (hm
, "GetConsoleFontSize");
2791 GetCurrentConsoleFont
= (void *)
2792 GetProcAddress (hm
, "GetCurrentConsoleFont");
2795 /* Set variables to dummy versions of these processes if the function
2796 wasn't found in kernel32.dll. */
2797 if (!DebugBreakProcess
)
2798 DebugBreakProcess
= bad_DebugBreakProcess
;
2799 if (!DebugActiveProcessStop
|| !DebugSetProcessKillOnExit
)
2801 DebugActiveProcessStop
= bad_DebugActiveProcessStop
;
2802 DebugSetProcessKillOnExit
= bad_DebugSetProcessKillOnExit
;
2804 if (!GetConsoleFontSize
)
2805 GetConsoleFontSize
= bad_GetConsoleFontSize
;
2806 if (!GetCurrentConsoleFont
)
2807 GetCurrentConsoleFont
= bad_GetCurrentConsoleFont
;
2809 /* Load optional functions used for retrieving filename information
2810 associated with the currently debugged process or its dlls. */
2811 hm
= LoadLibrary ("psapi.dll");
2814 EnumProcessModules
= (void *)
2815 GetProcAddress (hm
, "EnumProcessModules");
2816 GetModuleInformation
= (void *)
2817 GetProcAddress (hm
, "GetModuleInformation");
2818 GetModuleFileNameEx
= (void *)
2819 GetProcAddress (hm
, GetModuleFileNameEx_name
);
2822 if (!EnumProcessModules
|| !GetModuleInformation
|| !GetModuleFileNameEx
)
2824 /* Set variables to dummy versions of these processes if the function
2825 wasn't found in psapi.dll. */
2826 EnumProcessModules
= bad_EnumProcessModules
;
2827 GetModuleInformation
= bad_GetModuleInformation
;
2828 GetModuleFileNameEx
= bad_GetModuleFileNameEx
;
2829 /* This will probably fail on Windows 9x/Me. Let the user know
2830 that we're missing some functionality. */
2832 cannot automatically find executable file or library to read symbols.\n\
2833 Use \"file\" or \"dll\" command to load executable/libraries directly."));
2836 hm
= LoadLibrary ("advapi32.dll");
2839 OpenProcessToken
= (void *) GetProcAddress (hm
, "OpenProcessToken");
2840 LookupPrivilegeValueA
= (void *)
2841 GetProcAddress (hm
, "LookupPrivilegeValueA");
2842 AdjustTokenPrivileges
= (void *)
2843 GetProcAddress (hm
, "AdjustTokenPrivileges");
2844 /* Only need to set one of these since if OpenProcessToken fails nothing
2846 if (!OpenProcessToken
|| !LookupPrivilegeValueA
2847 || !AdjustTokenPrivileges
)
2848 OpenProcessToken
= bad_OpenProcessToken
;