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 typedef BOOL
WINAPI (AdjustTokenPrivileges_ftype
) (HANDLE
, BOOL
,
82 DWORD
, PTOKEN_PRIVILEGES
,
84 static AdjustTokenPrivileges_ftype
*AdjustTokenPrivileges
;
86 typedef BOOL
WINAPI (DebugActiveProcessStop_ftype
) (DWORD
);
87 static DebugActiveProcessStop_ftype
*DebugActiveProcessStop
;
89 typedef BOOL
WINAPI (DebugBreakProcess_ftype
) (HANDLE
);
90 static DebugBreakProcess_ftype
*DebugBreakProcess
;
92 typedef BOOL
WINAPI (DebugSetProcessKillOnExit_ftype
) (BOOL
);
93 static DebugSetProcessKillOnExit_ftype
*DebugSetProcessKillOnExit
;
95 typedef BOOL
WINAPI (EnumProcessModules_ftype
) (HANDLE
, HMODULE
*, DWORD
,
97 static EnumProcessModules_ftype
*EnumProcessModules
;
99 typedef BOOL
WINAPI (GetModuleInformation_ftype
) (HANDLE
, HMODULE
,
100 LPMODULEINFO
, DWORD
);
101 static GetModuleInformation_ftype
*GetModuleInformation
;
103 typedef BOOL
WINAPI (LookupPrivilegeValueA_ftype
) (LPCSTR
, LPCSTR
, PLUID
);
104 static LookupPrivilegeValueA_ftype
*LookupPrivilegeValueA
;
106 typedef BOOL
WINAPI (OpenProcessToken_ftype
) (HANDLE
, DWORD
, PHANDLE
);
107 static OpenProcessToken_ftype
*OpenProcessToken
;
109 typedef BOOL
WINAPI (GetCurrentConsoleFont_ftype
) (HANDLE
, BOOL
,
110 CONSOLE_FONT_INFO
*);
111 static GetCurrentConsoleFont_ftype
*GetCurrentConsoleFont
;
113 typedef COORD
WINAPI (GetConsoleFontSize_ftype
) (HANDLE
, DWORD
);
114 static GetConsoleFontSize_ftype
*GetConsoleFontSize
;
118 #undef GetModuleFileNameEx
121 # define __PMAX (MAX_PATH + 1)
122 typedef DWORD
WINAPI (GetModuleFileNameEx_ftype
) (HANDLE
, HMODULE
, LPSTR
, DWORD
);
123 static GetModuleFileNameEx_ftype
*GetModuleFileNameEx
;
124 # define STARTUPINFO STARTUPINFOA
125 # define CreateProcess CreateProcessA
126 # define GetModuleFileNameEx_name "GetModuleFileNameExA"
127 # define bad_GetModuleFileNameEx bad_GetModuleFileNameExA
129 # define __PMAX PATH_MAX
130 /* The starting and ending address of the cygwin1.dll text segment. */
131 static CORE_ADDR cygwin_load_start
;
132 static CORE_ADDR cygwin_load_end
;
134 typedef wchar_t cygwin_buf_t
;
135 typedef DWORD
WINAPI (GetModuleFileNameEx_ftype
) (HANDLE
, HMODULE
,
137 static GetModuleFileNameEx_ftype
*GetModuleFileNameEx
;
138 # define STARTUPINFO STARTUPINFOW
139 # define CreateProcess CreateProcessW
140 # define GetModuleFileNameEx_name "GetModuleFileNameExW"
141 # define bad_GetModuleFileNameEx bad_GetModuleFileNameExW
144 static int have_saved_context
; /* True if we've saved context from a
146 static CONTEXT saved_context
; /* Containes the saved context from a
149 /* If we're not using the old Cygwin header file set, define the
150 following which never should have been in the generic Win32 API
151 headers in the first place since they were our own invention... */
152 #ifndef _GNU_H_WINDOWS_H
155 FLAG_TRACE_BIT
= 0x100,
159 #ifndef CONTEXT_EXTENDED_REGISTERS
160 /* This macro is only defined on ia32. It only makes sense on this target,
161 so define it as zero if not already defined. */
162 #define CONTEXT_EXTENDED_REGISTERS 0
165 #define CONTEXT_DEBUGGER_DR CONTEXT_FULL | CONTEXT_FLOATING_POINT \
166 | CONTEXT_SEGMENTS | CONTEXT_DEBUG_REGISTERS \
167 | CONTEXT_EXTENDED_REGISTERS
169 static uintptr_t dr
[8];
170 static int debug_registers_changed
;
171 static int debug_registers_used
;
173 static int windows_initialization_done
;
174 #define DR6_CLEAR_VALUE 0xffff0ff0
176 /* The string sent by cygwin when it processes a signal.
177 FIXME: This should be in a cygwin include file. */
178 #ifndef _CYGWIN_SIGNAL_STRING
179 #define _CYGWIN_SIGNAL_STRING "cYgSiGw00f"
182 #define CHECK(x) check (x, __FILE__,__LINE__)
183 #define DEBUG_EXEC(x) if (debug_exec) printf_unfiltered x
184 #define DEBUG_EVENTS(x) if (debug_events) printf_unfiltered x
185 #define DEBUG_MEM(x) if (debug_memory) printf_unfiltered x
186 #define DEBUG_EXCEPT(x) if (debug_exceptions) printf_unfiltered x
188 static void windows_interrupt (struct target_ops
*self
, ptid_t
);
189 static int windows_thread_alive (struct target_ops
*, ptid_t
);
190 static void windows_kill_inferior (struct target_ops
*);
192 static void cygwin_set_dr (int i
, CORE_ADDR addr
);
193 static void cygwin_set_dr7 (unsigned long val
);
194 static CORE_ADDR
cygwin_get_dr (int i
);
195 static unsigned long cygwin_get_dr6 (void);
196 static unsigned long cygwin_get_dr7 (void);
198 static enum gdb_signal last_sig
= GDB_SIGNAL_0
;
199 /* Set if a signal was received from the debugged process. */
201 /* Thread information structure used to track information that is
202 not available in gdb's thread structure. */
203 typedef struct windows_thread_info_struct
205 struct windows_thread_info_struct
*next
;
208 CORE_ADDR thread_local_base
;
217 static windows_thread_info thread_head
;
219 /* The process and thread handles for the above context. */
221 static DEBUG_EVENT current_event
; /* The current debug event from
223 static HANDLE current_process_handle
; /* Currently executing process */
224 static windows_thread_info
*current_thread
; /* Info on currently selected thread */
225 static DWORD main_thread_id
; /* Thread ID of the main thread */
227 /* Counts of things. */
228 static int exception_count
= 0;
229 static int event_count
= 0;
230 static int saw_create
;
231 static int open_process_used
= 0;
234 static int new_console
= 0;
236 static int cygwin_exceptions
= 0;
238 static int new_group
= 1;
239 static int debug_exec
= 0; /* show execution */
240 static int debug_events
= 0; /* show events from kernel */
241 static int debug_memory
= 0; /* show target memory accesses */
242 static int debug_exceptions
= 0; /* show target exceptions */
243 static int useshell
= 0; /* use shell for subprocesses */
245 /* This vector maps GDB's idea of a register's number into an offset
246 in the windows exception context vector.
248 It also contains the bit mask needed to load the register in question.
250 The contents of this table can only be computed by the units
251 that provide CPU-specific support for Windows native debugging.
252 These units should set the table by calling
253 windows_set_context_register_offsets.
255 One day we could read a reg, we could inspect the context we
256 already have loaded, if it doesn't have the bit set that we need,
257 we read that set of registers in using GetThreadContext. If the
258 context already contains what we need, we just unpack it. Then to
259 write a register, first we have to ensure that the context contains
260 the other regs of the group, and then we copy the info in and set
263 static const int *mappings
;
265 /* The function to use in order to determine whether a register is
266 a segment register or not. */
267 static segment_register_p_ftype
*segment_register_p
;
269 /* This vector maps the target's idea of an exception (extracted
270 from the DEBUG_EVENT structure) to GDB's idea. */
272 struct xlate_exception
278 static const struct xlate_exception
281 {EXCEPTION_ACCESS_VIOLATION
, GDB_SIGNAL_SEGV
},
282 {STATUS_STACK_OVERFLOW
, GDB_SIGNAL_SEGV
},
283 {EXCEPTION_BREAKPOINT
, GDB_SIGNAL_TRAP
},
284 {DBG_CONTROL_C
, GDB_SIGNAL_INT
},
285 {EXCEPTION_SINGLE_STEP
, GDB_SIGNAL_TRAP
},
286 {STATUS_FLOAT_DIVIDE_BY_ZERO
, GDB_SIGNAL_FPE
},
287 {-1, GDB_SIGNAL_UNKNOWN
}};
289 /* Set the MAPPINGS static global to OFFSETS.
290 See the description of MAPPINGS for more details. */
293 windows_set_context_register_offsets (const int *offsets
)
298 /* See windows-nat.h. */
301 windows_set_segment_register_p (segment_register_p_ftype
*fun
)
303 segment_register_p
= fun
;
307 check (BOOL ok
, const char *file
, int line
)
310 printf_filtered ("error return %s:%d was %u\n", file
, line
,
311 (unsigned) GetLastError ());
314 /* Find a thread record given a thread id. If GET_CONTEXT is not 0,
315 then also retrieve the context for this thread. If GET_CONTEXT is
316 negative, then don't suspend the thread. */
317 static windows_thread_info
*
318 thread_rec (DWORD id
, int get_context
)
320 windows_thread_info
*th
;
322 for (th
= &thread_head
; (th
= th
->next
) != NULL
;)
325 if (!th
->suspended
&& get_context
)
327 if (get_context
> 0 && id
!= current_event
.dwThreadId
)
329 if (SuspendThread (th
->h
) == (DWORD
) -1)
331 DWORD err
= GetLastError ();
333 /* We get Access Denied (5) when trying to suspend
334 threads that Windows started on behalf of the
335 debuggee, usually when those threads are just
337 We can get Invalid Handle (6) if the main thread
339 if (err
!= ERROR_INVALID_HANDLE
340 && err
!= ERROR_ACCESS_DENIED
)
341 warning (_("SuspendThread (tid=0x%x) failed."
343 (unsigned) id
, (unsigned) err
);
349 else if (get_context
< 0)
351 th
->reload_context
= 1;
359 /* Add a thread to the thread list. */
360 static windows_thread_info
*
361 windows_add_thread (ptid_t ptid
, HANDLE h
, void *tlb
)
363 windows_thread_info
*th
;
366 gdb_assert (ptid_get_tid (ptid
) != 0);
368 id
= ptid_get_tid (ptid
);
370 if ((th
= thread_rec (id
, FALSE
)))
373 th
= XCNEW (windows_thread_info
);
376 th
->thread_local_base
= (CORE_ADDR
) (uintptr_t) tlb
;
377 th
->next
= thread_head
.next
;
378 thread_head
.next
= th
;
380 /* Set the debug registers for the new thread if they are used. */
381 if (debug_registers_used
)
383 /* Only change the value of the debug registers. */
384 th
->context
.ContextFlags
= CONTEXT_DEBUG_REGISTERS
;
385 CHECK (GetThreadContext (th
->h
, &th
->context
));
386 th
->context
.Dr0
= dr
[0];
387 th
->context
.Dr1
= dr
[1];
388 th
->context
.Dr2
= dr
[2];
389 th
->context
.Dr3
= dr
[3];
390 th
->context
.Dr6
= DR6_CLEAR_VALUE
;
391 th
->context
.Dr7
= dr
[7];
392 CHECK (SetThreadContext (th
->h
, &th
->context
));
393 th
->context
.ContextFlags
= 0;
398 /* Clear out any old thread list and reintialize it to a
401 windows_init_thread_list (void)
403 windows_thread_info
*th
= &thread_head
;
405 DEBUG_EVENTS (("gdb: windows_init_thread_list\n"));
407 while (th
->next
!= NULL
)
409 windows_thread_info
*here
= th
->next
;
410 th
->next
= here
->next
;
413 thread_head
.next
= NULL
;
416 /* Delete a thread from the list of threads. */
418 windows_delete_thread (ptid_t ptid
, DWORD exit_code
)
420 windows_thread_info
*th
;
423 gdb_assert (ptid_get_tid (ptid
) != 0);
425 id
= ptid_get_tid (ptid
);
428 printf_unfiltered ("[Deleting %s]\n", target_pid_to_str (ptid
));
429 else if (print_thread_events
&& id
!= main_thread_id
)
430 printf_unfiltered (_("[%s exited with code %u]\n"),
431 target_pid_to_str (ptid
), (unsigned) exit_code
);
432 delete_thread (ptid
);
434 for (th
= &thread_head
;
435 th
->next
!= NULL
&& th
->next
->id
!= id
;
439 if (th
->next
!= NULL
)
441 windows_thread_info
*here
= th
->next
;
442 th
->next
= here
->next
;
448 do_windows_fetch_inferior_registers (struct regcache
*regcache
, int r
)
450 char *context_offset
= ((char *) ¤t_thread
->context
) + mappings
[r
];
451 struct gdbarch
*gdbarch
= get_regcache_arch (regcache
);
452 struct gdbarch_tdep
*tdep
= gdbarch_tdep (gdbarch
);
456 return; /* Windows sometimes uses a non-existent thread id in its
459 if (current_thread
->reload_context
)
462 if (have_saved_context
)
464 /* Lie about where the program actually is stopped since
465 cygwin has informed us that we should consider the signal
466 to have occurred at another location which is stored in
468 memcpy (¤t_thread
->context
, &saved_context
,
469 __COPY_CONTEXT_SIZE
);
470 have_saved_context
= 0;
475 windows_thread_info
*th
= current_thread
;
476 th
->context
.ContextFlags
= CONTEXT_DEBUGGER_DR
;
477 CHECK (GetThreadContext (th
->h
, &th
->context
));
478 /* Copy dr values from that thread.
479 But only if there were not modified since last stop.
481 if (!debug_registers_changed
)
483 dr
[0] = th
->context
.Dr0
;
484 dr
[1] = th
->context
.Dr1
;
485 dr
[2] = th
->context
.Dr2
;
486 dr
[3] = th
->context
.Dr3
;
487 dr
[6] = th
->context
.Dr6
;
488 dr
[7] = th
->context
.Dr7
;
491 current_thread
->reload_context
= 0;
494 if (r
== I387_FISEG_REGNUM (tdep
))
496 l
= *((long *) context_offset
) & 0xffff;
497 regcache_raw_supply (regcache
, r
, (char *) &l
);
499 else if (r
== I387_FOP_REGNUM (tdep
))
501 l
= (*((long *) context_offset
) >> 16) & ((1 << 11) - 1);
502 regcache_raw_supply (regcache
, r
, (char *) &l
);
504 else if (segment_register_p (r
))
506 /* GDB treats segment registers as 32bit registers, but they are
507 in fact only 16 bits long. Make sure we do not read extra
508 bits from our source buffer. */
509 l
= *((long *) context_offset
) & 0xffff;
510 regcache_raw_supply (regcache
, r
, (char *) &l
);
513 regcache_raw_supply (regcache
, r
, context_offset
);
516 for (r
= 0; r
< gdbarch_num_regs (gdbarch
); r
++)
517 do_windows_fetch_inferior_registers (regcache
, r
);
522 windows_fetch_inferior_registers (struct target_ops
*ops
,
523 struct regcache
*regcache
, int r
)
525 current_thread
= thread_rec (ptid_get_tid (inferior_ptid
), TRUE
);
526 /* Check if current_thread exists. Windows sometimes uses a non-existent
527 thread id in its events. */
529 do_windows_fetch_inferior_registers (regcache
, r
);
533 do_windows_store_inferior_registers (const struct regcache
*regcache
, int r
)
536 /* Windows sometimes uses a non-existent thread id in its events. */;
538 regcache_raw_collect (regcache
, r
,
539 ((char *) ¤t_thread
->context
) + mappings
[r
]);
542 for (r
= 0; r
< gdbarch_num_regs (get_regcache_arch (regcache
)); r
++)
543 do_windows_store_inferior_registers (regcache
, r
);
547 /* Store a new register value into the current thread context. */
549 windows_store_inferior_registers (struct target_ops
*ops
,
550 struct regcache
*regcache
, int r
)
552 current_thread
= thread_rec (ptid_get_tid (inferior_ptid
), TRUE
);
553 /* Check if current_thread exists. Windows sometimes uses a non-existent
554 thread id in its events. */
556 do_windows_store_inferior_registers (regcache
, r
);
559 /* Encapsulate the information required in a call to
560 symbol_file_add_args. */
561 struct safe_symbol_file_add_args
565 struct section_addr_info
*addrs
;
568 struct ui_file
*err
, *out
;
572 /* Maintain a linked list of "so" information. */
578 static struct so_list solib_start
, *solib_end
;
580 static struct so_list
*
581 windows_make_so (const char *name
, LPVOID load_addr
)
588 WIN32_FIND_DATA w32_fd
;
589 HANDLE h
= FindFirstFile(name
, &w32_fd
);
591 if (h
== INVALID_HANDLE_VALUE
)
597 if (GetCurrentDirectory (MAX_PATH
+ 1, cwd
))
599 p
= strrchr (buf
, '\\');
602 SetCurrentDirectory (buf
);
603 GetFullPathName (w32_fd
.cFileName
, MAX_PATH
, buf
, &p
);
604 SetCurrentDirectory (cwd
);
607 if (strcasecmp (buf
, "ntdll.dll") == 0)
609 GetSystemDirectory (buf
, sizeof (buf
));
610 strcat (buf
, "\\ntdll.dll");
613 cygwin_buf_t buf
[__PMAX
];
616 if (access (name
, F_OK
) != 0)
618 if (strcasecmp (name
, "ntdll.dll") == 0)
621 GetSystemDirectoryW (buf
, sizeof (buf
) / sizeof (wchar_t));
622 wcscat (buf
, L
"\\ntdll.dll");
626 GetSystemDirectoryA (buf
, sizeof (buf
) / sizeof (wchar_t));
627 strcat (buf
, "\\ntdll.dll");
632 so
= XCNEW (struct so_list
);
633 so
->lm_info
= XNEW (struct lm_info
);
634 so
->lm_info
->load_addr
= load_addr
;
635 strcpy (so
->so_original_name
, name
);
637 strcpy (so
->so_name
, buf
);
640 cygwin_conv_path (CCP_WIN_W_TO_POSIX
, buf
, so
->so_name
,
641 SO_NAME_MAX_PATH_SIZE
);
644 char *rname
= realpath (name
, NULL
);
645 if (rname
&& strlen (rname
) < SO_NAME_MAX_PATH_SIZE
)
647 strcpy (so
->so_name
, rname
);
651 error (_("dll path too long"));
653 /* Record cygwin1.dll .text start/end. */
654 p
= strchr (so
->so_name
, '\0') - (sizeof ("/cygwin1.dll") - 1);
655 if (p
>= so
->so_name
&& strcasecmp (p
, "/cygwin1.dll") == 0)
658 asection
*text
= NULL
;
661 abfd
= gdb_bfd_open (so
->so_name
, "pei-i386", -1);
666 if (bfd_check_format (abfd
, bfd_object
))
667 text
= bfd_get_section_by_name (abfd
, ".text");
671 gdb_bfd_unref (abfd
);
675 /* The symbols in a dll are offset by 0x1000, which is the
676 offset from 0 of the first byte in an image - because of the
677 file header and the section alignment. */
678 cygwin_load_start
= (CORE_ADDR
) (uintptr_t) ((char *)
680 cygwin_load_end
= cygwin_load_start
+ bfd_section_size (abfd
, text
);
682 gdb_bfd_unref (abfd
);
690 get_image_name (HANDLE h
, void *address
, int unicode
)
693 static char buf
[__PMAX
];
695 static char buf
[(2 * __PMAX
) + 1];
697 DWORD size
= unicode
? sizeof (WCHAR
) : sizeof (char);
703 /* Attempt to read the name of the dll that was detected.
704 This is documented to work only when actively debugging
705 a program. It will not work for attached processes. */
709 /* See if we could read the address of a string, and that the
710 address isn't null. */
711 if (!ReadProcessMemory (h
, address
, &address_ptr
,
712 sizeof (address_ptr
), &done
)
713 || done
!= sizeof (address_ptr
) || !address_ptr
)
716 /* Find the length of the string. */
717 while (ReadProcessMemory (h
, address_ptr
+ len
++ * size
, &b
, size
, &done
)
718 && (b
[0] != 0 || b
[size
- 1] != 0) && done
== size
)
722 ReadProcessMemory (h
, address_ptr
, buf
, len
, &done
);
725 WCHAR
*unicode_address
= (WCHAR
*) alloca (len
* sizeof (WCHAR
));
726 ReadProcessMemory (h
, address_ptr
, unicode_address
, len
* sizeof (WCHAR
),
729 wcstombs (buf
, unicode_address
, __PMAX
);
731 WideCharToMultiByte (CP_ACP
, 0, unicode_address
, len
, buf
, sizeof buf
,
739 /* Handle a DLL load event, and return 1.
741 This function assumes that this event did not occur during inferior
742 initialization, where their event info may be incomplete (see
743 do_initial_windows_stuff and windows_add_all_dlls for more info
744 on how we handle DLL loading during that phase). */
747 handle_load_dll (void *dummy
)
749 LOAD_DLL_DEBUG_INFO
*event
= ¤t_event
.u
.LoadDll
;
752 /* Try getting the DLL name via the lpImageName field of the event.
753 Note that Microsoft documents this fields as strictly optional,
754 in the sense that it might be NULL. And the first DLL event in
755 particular is explicitly documented as "likely not pass[ed]"
756 (source: MSDN LOAD_DLL_DEBUG_INFO structure). */
757 dll_name
= get_image_name (current_process_handle
,
758 event
->lpImageName
, event
->fUnicode
);
762 solib_end
->next
= windows_make_so (dll_name
, event
->lpBaseOfDll
);
763 solib_end
= solib_end
->next
;
765 DEBUG_EVENTS (("gdb: Loading dll \"%s\" at %s.\n", solib_end
->so_name
,
766 host_address_to_string (solib_end
->lm_info
->load_addr
)));
772 windows_free_so (struct so_list
*so
)
779 /* Handle a DLL unload event.
780 Return 1 if successful, or zero otherwise.
782 This function assumes that this event did not occur during inferior
783 initialization, where their event info may be incomplete (see
784 do_initial_windows_stuff and windows_add_all_dlls for more info
785 on how we handle DLL loading during that phase). */
788 handle_unload_dll (void *dummy
)
790 LPVOID lpBaseOfDll
= current_event
.u
.UnloadDll
.lpBaseOfDll
;
793 for (so
= &solib_start
; so
->next
!= NULL
; so
= so
->next
)
794 if (so
->next
->lm_info
->load_addr
== lpBaseOfDll
)
796 struct so_list
*sodel
= so
->next
;
798 so
->next
= sodel
->next
;
801 DEBUG_EVENTS (("gdb: Unloading dll \"%s\".\n", sodel
->so_name
));
803 windows_free_so (sodel
);
807 /* We did not find any DLL that was previously loaded at this address,
808 so register a complaint. We do not report an error, because we have
809 observed that this may be happening under some circumstances. For
810 instance, running 32bit applications on x64 Windows causes us to receive
811 4 mysterious UNLOAD_DLL_DEBUG_EVENTs during the startup phase (these
812 events are apparently caused by the WOW layer, the interface between
813 32bit and 64bit worlds). */
814 complaint (&symfile_complaints
, _("dll starting at %s not found."),
815 host_address_to_string (lpBaseOfDll
));
820 /* Clear list of loaded DLLs. */
822 windows_clear_solib (void)
824 solib_start
.next
= NULL
;
825 solib_end
= &solib_start
;
828 /* Handle DEBUG_STRING output from child process.
829 Cygwin prepends its messages with a "cygwin:". Interpret this as
830 a Cygwin signal. Otherwise just print the string as a warning. */
832 handle_output_debug_string (struct target_waitstatus
*ourstatus
)
837 if (!target_read_string
838 ((CORE_ADDR
) (uintptr_t) current_event
.u
.DebugString
.lpDebugStringData
,
842 else if (!startswith (s
, _CYGWIN_SIGNAL_STRING
))
845 if (!startswith (s
, "cYg"))
848 char *p
= strchr (s
, '\0');
850 if (p
> s
&& *--p
== '\n')
858 /* Got a cygwin signal marker. A cygwin signal is followed by
859 the signal number itself and then optionally followed by the
860 thread id and address to saved context within the DLL. If
861 these are supplied, then the given thread is assumed to have
862 issued the signal and the context from the thread is assumed
863 to be stored at the given address in the inferior. Tell gdb
864 to treat this like a real signal. */
866 int sig
= strtol (s
+ sizeof (_CYGWIN_SIGNAL_STRING
) - 1, &p
, 0);
867 int gotasig
= gdb_signal_from_host (sig
);
869 ourstatus
->value
.sig
= gotasig
;
875 ourstatus
->kind
= TARGET_WAITKIND_STOPPED
;
876 retval
= strtoul (p
, &p
, 0);
878 retval
= main_thread_id
;
879 else if ((x
= (LPCVOID
) (uintptr_t) strtoull (p
, NULL
, 0))
880 && ReadProcessMemory (current_process_handle
, x
,
882 __COPY_CONTEXT_SIZE
, &n
)
883 && n
== __COPY_CONTEXT_SIZE
)
884 have_saved_context
= 1;
895 display_selector (HANDLE thread
, DWORD sel
)
898 if (GetThreadSelectorEntry (thread
, sel
, &info
))
901 printf_filtered ("0x%03x: ", (unsigned) sel
);
902 if (!info
.HighWord
.Bits
.Pres
)
904 puts_filtered ("Segment not present\n");
907 base
= (info
.HighWord
.Bits
.BaseHi
<< 24) +
908 (info
.HighWord
.Bits
.BaseMid
<< 16)
910 limit
= (info
.HighWord
.Bits
.LimitHi
<< 16) + info
.LimitLow
;
911 if (info
.HighWord
.Bits
.Granularity
)
912 limit
= (limit
<< 12) | 0xfff;
913 printf_filtered ("base=0x%08x limit=0x%08x", base
, limit
);
914 if (info
.HighWord
.Bits
.Default_Big
)
915 puts_filtered(" 32-bit ");
917 puts_filtered(" 16-bit ");
918 switch ((info
.HighWord
.Bits
.Type
& 0xf) >> 1)
921 puts_filtered ("Data (Read-Only, Exp-up");
924 puts_filtered ("Data (Read/Write, Exp-up");
927 puts_filtered ("Unused segment (");
930 puts_filtered ("Data (Read/Write, Exp-down");
933 puts_filtered ("Code (Exec-Only, N.Conf");
936 puts_filtered ("Code (Exec/Read, N.Conf");
939 puts_filtered ("Code (Exec-Only, Conf");
942 puts_filtered ("Code (Exec/Read, Conf");
945 printf_filtered ("Unknown type 0x%x",info
.HighWord
.Bits
.Type
);
947 if ((info
.HighWord
.Bits
.Type
& 0x1) == 0)
948 puts_filtered(", N.Acc");
949 puts_filtered (")\n");
950 if ((info
.HighWord
.Bits
.Type
& 0x10) == 0)
951 puts_filtered("System selector ");
952 printf_filtered ("Priviledge level = %d. ", info
.HighWord
.Bits
.Dpl
);
953 if (info
.HighWord
.Bits
.Granularity
)
954 puts_filtered ("Page granular.\n");
956 puts_filtered ("Byte granular.\n");
961 DWORD err
= GetLastError ();
962 if (err
== ERROR_NOT_SUPPORTED
)
963 printf_filtered ("Function not supported\n");
965 printf_filtered ("Invalid selector 0x%x.\n", (unsigned) sel
);
971 display_selectors (char * args
, int from_tty
)
975 puts_filtered ("Impossible to display selectors now.\n");
981 puts_filtered ("Selector $cs\n");
982 display_selector (current_thread
->h
,
983 current_thread
->context
.SegCs
);
984 puts_filtered ("Selector $ds\n");
985 display_selector (current_thread
->h
,
986 current_thread
->context
.SegDs
);
987 puts_filtered ("Selector $es\n");
988 display_selector (current_thread
->h
,
989 current_thread
->context
.SegEs
);
990 puts_filtered ("Selector $ss\n");
991 display_selector (current_thread
->h
,
992 current_thread
->context
.SegSs
);
993 puts_filtered ("Selector $fs\n");
994 display_selector (current_thread
->h
,
995 current_thread
->context
.SegFs
);
996 puts_filtered ("Selector $gs\n");
997 display_selector (current_thread
->h
,
998 current_thread
->context
.SegGs
);
1003 sel
= parse_and_eval_long (args
);
1004 printf_filtered ("Selector \"%s\"\n",args
);
1005 display_selector (current_thread
->h
, sel
);
1009 #define DEBUG_EXCEPTION_SIMPLE(x) if (debug_exceptions) \
1010 printf_unfiltered ("gdb: Target exception %s at %s\n", x, \
1011 host_address_to_string (\
1012 current_event.u.Exception.ExceptionRecord.ExceptionAddress))
1015 handle_exception (struct target_waitstatus
*ourstatus
)
1017 windows_thread_info
*th
;
1018 DWORD code
= current_event
.u
.Exception
.ExceptionRecord
.ExceptionCode
;
1020 ourstatus
->kind
= TARGET_WAITKIND_STOPPED
;
1022 /* Record the context of the current thread. */
1023 th
= thread_rec (current_event
.dwThreadId
, -1);
1027 case EXCEPTION_ACCESS_VIOLATION
:
1028 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ACCESS_VIOLATION");
1029 ourstatus
->value
.sig
= GDB_SIGNAL_SEGV
;
1032 /* See if the access violation happened within the cygwin DLL
1033 itself. Cygwin uses a kind of exception handling to deal
1034 with passed-in invalid addresses. gdb should not treat
1035 these as real SEGVs since they will be silently handled by
1036 cygwin. A real SEGV will (theoretically) be caught by
1037 cygwin later in the process and will be sent as a
1038 cygwin-specific-signal. So, ignore SEGVs if they show up
1039 within the text segment of the DLL itself. */
1041 CORE_ADDR addr
= (CORE_ADDR
) (uintptr_t)
1042 current_event
.u
.Exception
.ExceptionRecord
.ExceptionAddress
;
1044 if ((!cygwin_exceptions
&& (addr
>= cygwin_load_start
1045 && addr
< cygwin_load_end
))
1046 || (find_pc_partial_function (addr
, &fn
, NULL
, NULL
)
1047 && startswith (fn
, "KERNEL32!IsBad")))
1052 case STATUS_STACK_OVERFLOW
:
1053 DEBUG_EXCEPTION_SIMPLE ("STATUS_STACK_OVERFLOW");
1054 ourstatus
->value
.sig
= GDB_SIGNAL_SEGV
;
1056 case STATUS_FLOAT_DENORMAL_OPERAND
:
1057 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DENORMAL_OPERAND");
1058 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1060 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED
:
1061 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ARRAY_BOUNDS_EXCEEDED");
1062 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1064 case STATUS_FLOAT_INEXACT_RESULT
:
1065 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INEXACT_RESULT");
1066 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1068 case STATUS_FLOAT_INVALID_OPERATION
:
1069 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INVALID_OPERATION");
1070 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1072 case STATUS_FLOAT_OVERFLOW
:
1073 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_OVERFLOW");
1074 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1076 case STATUS_FLOAT_STACK_CHECK
:
1077 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_STACK_CHECK");
1078 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1080 case STATUS_FLOAT_UNDERFLOW
:
1081 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_UNDERFLOW");
1082 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1084 case STATUS_FLOAT_DIVIDE_BY_ZERO
:
1085 DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DIVIDE_BY_ZERO");
1086 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1088 case STATUS_INTEGER_DIVIDE_BY_ZERO
:
1089 DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_DIVIDE_BY_ZERO");
1090 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1092 case STATUS_INTEGER_OVERFLOW
:
1093 DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_OVERFLOW");
1094 ourstatus
->value
.sig
= GDB_SIGNAL_FPE
;
1096 case EXCEPTION_BREAKPOINT
:
1097 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_BREAKPOINT");
1098 ourstatus
->value
.sig
= GDB_SIGNAL_TRAP
;
1101 DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_C");
1102 ourstatus
->value
.sig
= GDB_SIGNAL_INT
;
1104 case DBG_CONTROL_BREAK
:
1105 DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_BREAK");
1106 ourstatus
->value
.sig
= GDB_SIGNAL_INT
;
1108 case EXCEPTION_SINGLE_STEP
:
1109 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_SINGLE_STEP");
1110 ourstatus
->value
.sig
= GDB_SIGNAL_TRAP
;
1112 case EXCEPTION_ILLEGAL_INSTRUCTION
:
1113 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ILLEGAL_INSTRUCTION");
1114 ourstatus
->value
.sig
= GDB_SIGNAL_ILL
;
1116 case EXCEPTION_PRIV_INSTRUCTION
:
1117 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_PRIV_INSTRUCTION");
1118 ourstatus
->value
.sig
= GDB_SIGNAL_ILL
;
1120 case EXCEPTION_NONCONTINUABLE_EXCEPTION
:
1121 DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_NONCONTINUABLE_EXCEPTION");
1122 ourstatus
->value
.sig
= GDB_SIGNAL_ILL
;
1125 /* Treat unhandled first chance exceptions specially. */
1126 if (current_event
.u
.Exception
.dwFirstChance
)
1128 printf_unfiltered ("gdb: unknown target exception 0x%08x at %s\n",
1129 (unsigned) current_event
.u
.Exception
.ExceptionRecord
.ExceptionCode
,
1130 host_address_to_string (
1131 current_event
.u
.Exception
.ExceptionRecord
.ExceptionAddress
));
1132 ourstatus
->value
.sig
= GDB_SIGNAL_UNKNOWN
;
1136 last_sig
= ourstatus
->value
.sig
;
1140 /* Resume thread specified by ID, or all artificially suspended
1141 threads, if we are continuing execution. KILLED non-zero means we
1142 have killed the inferior, so we should ignore weird errors due to
1143 threads shutting down. */
1145 windows_continue (DWORD continue_status
, int id
, int killed
)
1148 windows_thread_info
*th
;
1151 DEBUG_EVENTS (("ContinueDebugEvent (cpid=%d, ctid=0x%x, %s);\n",
1152 (unsigned) current_event
.dwProcessId
,
1153 (unsigned) current_event
.dwThreadId
,
1154 continue_status
== DBG_CONTINUE
?
1155 "DBG_CONTINUE" : "DBG_EXCEPTION_NOT_HANDLED"));
1157 for (th
= &thread_head
; (th
= th
->next
) != NULL
;)
1158 if ((id
== -1 || id
== (int) th
->id
)
1161 if (debug_registers_changed
)
1163 th
->context
.ContextFlags
|= CONTEXT_DEBUG_REGISTERS
;
1164 th
->context
.Dr0
= dr
[0];
1165 th
->context
.Dr1
= dr
[1];
1166 th
->context
.Dr2
= dr
[2];
1167 th
->context
.Dr3
= dr
[3];
1168 th
->context
.Dr6
= DR6_CLEAR_VALUE
;
1169 th
->context
.Dr7
= dr
[7];
1171 if (th
->context
.ContextFlags
)
1175 if (GetExitCodeThread (th
->h
, &ec
)
1176 && ec
== STILL_ACTIVE
)
1178 BOOL status
= SetThreadContext (th
->h
, &th
->context
);
1183 th
->context
.ContextFlags
= 0;
1185 if (th
->suspended
> 0)
1186 (void) ResumeThread (th
->h
);
1190 res
= ContinueDebugEvent (current_event
.dwProcessId
,
1191 current_event
.dwThreadId
,
1195 error (_("Failed to resume program execution"
1196 " (ContinueDebugEvent failed, error %u)"),
1197 (unsigned int) GetLastError ());
1199 debug_registers_changed
= 0;
1203 /* Called in pathological case where Windows fails to send a
1204 CREATE_PROCESS_DEBUG_EVENT after an attach. */
1206 fake_create_process (void)
1208 current_process_handle
= OpenProcess (PROCESS_ALL_ACCESS
, FALSE
,
1209 current_event
.dwProcessId
);
1210 if (current_process_handle
!= NULL
)
1211 open_process_used
= 1;
1214 error (_("OpenProcess call failed, GetLastError = %u"),
1215 (unsigned) GetLastError ());
1216 /* We can not debug anything in that case. */
1218 main_thread_id
= current_event
.dwThreadId
;
1219 current_thread
= windows_add_thread (
1220 ptid_build (current_event
.dwProcessId
, 0,
1221 current_event
.dwThreadId
),
1222 current_event
.u
.CreateThread
.hThread
,
1223 current_event
.u
.CreateThread
.lpThreadLocalBase
);
1224 return main_thread_id
;
1228 windows_resume (struct target_ops
*ops
,
1229 ptid_t ptid
, int step
, enum gdb_signal sig
)
1231 windows_thread_info
*th
;
1232 DWORD continue_status
= DBG_CONTINUE
;
1234 /* A specific PTID means `step only this thread id'. */
1235 int resume_all
= ptid_equal (ptid
, minus_one_ptid
);
1237 /* If we're continuing all threads, it's the current inferior that
1238 should be handled specially. */
1240 ptid
= inferior_ptid
;
1242 if (sig
!= GDB_SIGNAL_0
)
1244 if (current_event
.dwDebugEventCode
!= EXCEPTION_DEBUG_EVENT
)
1246 DEBUG_EXCEPT(("Cannot continue with signal %d here.\n",sig
));
1248 else if (sig
== last_sig
)
1249 continue_status
= DBG_EXCEPTION_NOT_HANDLED
;
1252 /* This code does not seem to work, because
1253 the kernel does probably not consider changes in the ExceptionRecord
1254 structure when passing the exception to the inferior.
1255 Note that this seems possible in the exception handler itself. */
1258 for (i
= 0; xlate
[i
].them
!= -1; i
++)
1259 if (xlate
[i
].us
== sig
)
1261 current_event
.u
.Exception
.ExceptionRecord
.ExceptionCode
1263 continue_status
= DBG_EXCEPTION_NOT_HANDLED
;
1266 if (continue_status
== DBG_CONTINUE
)
1268 DEBUG_EXCEPT(("Cannot continue with signal %d.\n",sig
));
1272 DEBUG_EXCEPT(("Can only continue with received signal %d.\n",
1276 last_sig
= GDB_SIGNAL_0
;
1278 DEBUG_EXEC (("gdb: windows_resume (pid=%d, tid=%ld, step=%d, sig=%d);\n",
1279 ptid_get_pid (ptid
), ptid_get_tid (ptid
), step
, sig
));
1281 /* Get context for currently selected thread. */
1282 th
= thread_rec (ptid_get_tid (inferior_ptid
), FALSE
);
1287 /* Single step by setting t bit. */
1288 struct regcache
*regcache
= get_current_regcache ();
1289 struct gdbarch
*gdbarch
= get_regcache_arch (regcache
);
1290 windows_fetch_inferior_registers (ops
, regcache
,
1291 gdbarch_ps_regnum (gdbarch
));
1292 th
->context
.EFlags
|= FLAG_TRACE_BIT
;
1295 if (th
->context
.ContextFlags
)
1297 if (debug_registers_changed
)
1299 th
->context
.Dr0
= dr
[0];
1300 th
->context
.Dr1
= dr
[1];
1301 th
->context
.Dr2
= dr
[2];
1302 th
->context
.Dr3
= dr
[3];
1303 th
->context
.Dr6
= DR6_CLEAR_VALUE
;
1304 th
->context
.Dr7
= dr
[7];
1306 CHECK (SetThreadContext (th
->h
, &th
->context
));
1307 th
->context
.ContextFlags
= 0;
1311 /* Allow continuing with the same signal that interrupted us.
1312 Otherwise complain. */
1315 windows_continue (continue_status
, -1, 0);
1317 windows_continue (continue_status
, ptid_get_tid (ptid
), 0);
1320 /* Ctrl-C handler used when the inferior is not run in the same console. The
1321 handler is in charge of interrupting the inferior using DebugBreakProcess.
1322 Note that this function is not available prior to Windows XP. In this case
1323 we emit a warning. */
1325 ctrl_c_handler (DWORD event_type
)
1327 const int attach_flag
= current_inferior ()->attach_flag
;
1329 /* Only handle Ctrl-C and Ctrl-Break events. Ignore others. */
1330 if (event_type
!= CTRL_C_EVENT
&& event_type
!= CTRL_BREAK_EVENT
)
1333 /* If the inferior and the debugger share the same console, do nothing as
1334 the inferior has also received the Ctrl-C event. */
1335 if (!new_console
&& !attach_flag
)
1338 if (!DebugBreakProcess (current_process_handle
))
1339 warning (_("Could not interrupt program. "
1340 "Press Ctrl-c in the program console."));
1342 /* Return true to tell that Ctrl-C has been handled. */
1346 /* Get the next event from the child. Returns a non-zero thread id if the event
1347 requires handling by WFI (or whatever). */
1349 get_windows_debug_event (struct target_ops
*ops
,
1350 int pid
, struct target_waitstatus
*ourstatus
)
1353 DWORD continue_status
, event_code
;
1354 windows_thread_info
*th
;
1355 static windows_thread_info dummy_thread_info
;
1356 DWORD thread_id
= 0;
1358 last_sig
= GDB_SIGNAL_0
;
1360 if (!(debug_event
= WaitForDebugEvent (¤t_event
, 1000)))
1364 continue_status
= DBG_CONTINUE
;
1366 event_code
= current_event
.dwDebugEventCode
;
1367 ourstatus
->kind
= TARGET_WAITKIND_SPURIOUS
;
1369 have_saved_context
= 0;
1373 case CREATE_THREAD_DEBUG_EVENT
:
1374 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1375 (unsigned) current_event
.dwProcessId
,
1376 (unsigned) current_event
.dwThreadId
,
1377 "CREATE_THREAD_DEBUG_EVENT"));
1378 if (saw_create
!= 1)
1380 struct inferior
*inf
;
1381 inf
= find_inferior_pid (current_event
.dwProcessId
);
1382 if (!saw_create
&& inf
->attach_flag
)
1384 /* Kludge around a Windows bug where first event is a create
1385 thread event. Caused when attached process does not have
1387 thread_id
= fake_create_process ();
1393 /* Record the existence of this thread. */
1394 thread_id
= current_event
.dwThreadId
;
1395 th
= windows_add_thread (ptid_build (current_event
.dwProcessId
, 0,
1396 current_event
.dwThreadId
),
1397 current_event
.u
.CreateThread
.hThread
,
1398 current_event
.u
.CreateThread
.lpThreadLocalBase
);
1402 case EXIT_THREAD_DEBUG_EVENT
:
1403 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1404 (unsigned) current_event
.dwProcessId
,
1405 (unsigned) current_event
.dwThreadId
,
1406 "EXIT_THREAD_DEBUG_EVENT"));
1408 if (current_event
.dwThreadId
!= main_thread_id
)
1410 windows_delete_thread (ptid_build (current_event
.dwProcessId
, 0,
1411 current_event
.dwThreadId
),
1412 current_event
.u
.ExitThread
.dwExitCode
);
1413 th
= &dummy_thread_info
;
1417 case CREATE_PROCESS_DEBUG_EVENT
:
1418 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1419 (unsigned) current_event
.dwProcessId
,
1420 (unsigned) current_event
.dwThreadId
,
1421 "CREATE_PROCESS_DEBUG_EVENT"));
1422 CloseHandle (current_event
.u
.CreateProcessInfo
.hFile
);
1423 if (++saw_create
!= 1)
1426 current_process_handle
= current_event
.u
.CreateProcessInfo
.hProcess
;
1428 windows_delete_thread (ptid_build (current_event
.dwProcessId
, 0,
1431 main_thread_id
= current_event
.dwThreadId
;
1432 /* Add the main thread. */
1433 th
= windows_add_thread (ptid_build (current_event
.dwProcessId
, 0,
1434 current_event
.dwThreadId
),
1435 current_event
.u
.CreateProcessInfo
.hThread
,
1436 current_event
.u
.CreateProcessInfo
.lpThreadLocalBase
);
1437 thread_id
= current_event
.dwThreadId
;
1440 case EXIT_PROCESS_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 "EXIT_PROCESS_DEBUG_EVENT"));
1445 if (!windows_initialization_done
)
1447 target_terminal_ours ();
1448 target_mourn_inferior ();
1449 error (_("During startup program exited with code 0x%x."),
1450 (unsigned int) current_event
.u
.ExitProcess
.dwExitCode
);
1452 else if (saw_create
== 1)
1454 ourstatus
->kind
= TARGET_WAITKIND_EXITED
;
1455 ourstatus
->value
.integer
= current_event
.u
.ExitProcess
.dwExitCode
;
1456 thread_id
= main_thread_id
;
1460 case LOAD_DLL_DEBUG_EVENT
:
1461 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1462 (unsigned) current_event
.dwProcessId
,
1463 (unsigned) current_event
.dwThreadId
,
1464 "LOAD_DLL_DEBUG_EVENT"));
1465 CloseHandle (current_event
.u
.LoadDll
.hFile
);
1466 if (saw_create
!= 1 || ! windows_initialization_done
)
1468 catch_errors (handle_load_dll
, NULL
, (char *) "", RETURN_MASK_ALL
);
1469 ourstatus
->kind
= TARGET_WAITKIND_LOADED
;
1470 ourstatus
->value
.integer
= 0;
1471 thread_id
= main_thread_id
;
1474 case UNLOAD_DLL_DEBUG_EVENT
:
1475 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1476 (unsigned) current_event
.dwProcessId
,
1477 (unsigned) current_event
.dwThreadId
,
1478 "UNLOAD_DLL_DEBUG_EVENT"));
1479 if (saw_create
!= 1 || ! windows_initialization_done
)
1481 catch_errors (handle_unload_dll
, NULL
, (char *) "", RETURN_MASK_ALL
);
1482 ourstatus
->kind
= TARGET_WAITKIND_LOADED
;
1483 ourstatus
->value
.integer
= 0;
1484 thread_id
= main_thread_id
;
1487 case EXCEPTION_DEBUG_EVENT
:
1488 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1489 (unsigned) current_event
.dwProcessId
,
1490 (unsigned) current_event
.dwThreadId
,
1491 "EXCEPTION_DEBUG_EVENT"));
1492 if (saw_create
!= 1)
1494 switch (handle_exception (ourstatus
))
1497 continue_status
= DBG_EXCEPTION_NOT_HANDLED
;
1500 thread_id
= current_event
.dwThreadId
;
1504 continue_status
= -1;
1509 case OUTPUT_DEBUG_STRING_EVENT
: /* Message from the kernel. */
1510 DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1511 (unsigned) current_event
.dwProcessId
,
1512 (unsigned) current_event
.dwThreadId
,
1513 "OUTPUT_DEBUG_STRING_EVENT"));
1514 if (saw_create
!= 1)
1516 thread_id
= handle_output_debug_string (ourstatus
);
1520 if (saw_create
!= 1)
1522 printf_unfiltered ("gdb: kernel event for pid=%u tid=0x%x\n",
1523 (unsigned) current_event
.dwProcessId
,
1524 (unsigned) current_event
.dwThreadId
);
1525 printf_unfiltered (" unknown event code %u\n",
1526 (unsigned) current_event
.dwDebugEventCode
);
1530 if (!thread_id
|| saw_create
!= 1)
1532 if (continue_status
== -1)
1533 windows_resume (ops
, minus_one_ptid
, 0, 1);
1535 CHECK (windows_continue (continue_status
, -1, 0));
1539 inferior_ptid
= ptid_build (current_event
.dwProcessId
, 0,
1541 current_thread
= th
;
1542 if (!current_thread
)
1543 current_thread
= thread_rec (thread_id
, TRUE
);
1550 /* Wait for interesting events to occur in the target process. */
1552 windows_wait (struct target_ops
*ops
,
1553 ptid_t ptid
, struct target_waitstatus
*ourstatus
, int options
)
1557 target_terminal_ours ();
1559 /* We loop when we get a non-standard exception rather than return
1560 with a SPURIOUS because resume can try and step or modify things,
1561 which needs a current_thread->h. But some of these exceptions mark
1562 the birth or death of threads, which mean that the current thread
1563 isn't necessarily what you think it is. */
1569 /* If the user presses Ctrl-c while the debugger is waiting
1570 for an event, he expects the debugger to interrupt his program
1571 and to get the prompt back. There are two possible situations:
1573 - The debugger and the program do not share the console, in
1574 which case the Ctrl-c event only reached the debugger.
1575 In that case, the ctrl_c handler will take care of interrupting
1576 the inferior. Note that this case is working starting with
1577 Windows XP. For Windows 2000, Ctrl-C should be pressed in the
1580 - The debugger and the program share the same console, in which
1581 case both debugger and inferior will receive the Ctrl-c event.
1582 In that case the ctrl_c handler will ignore the event, as the
1583 Ctrl-c event generated inside the inferior will trigger the
1584 expected debug event.
1586 FIXME: brobecker/2008-05-20: If the inferior receives the
1587 signal first and the delay until GDB receives that signal
1588 is sufficiently long, GDB can sometimes receive the SIGINT
1589 after we have unblocked the CTRL+C handler. This would
1590 lead to the debugger stopping prematurely while handling
1591 the new-thread event that comes with the handling of the SIGINT
1592 inside the inferior, and then stop again immediately when
1593 the user tries to resume the execution in the inferior.
1594 This is a classic race that we should try to fix one day. */
1595 SetConsoleCtrlHandler (&ctrl_c_handler
, TRUE
);
1596 retval
= get_windows_debug_event (ops
, pid
, ourstatus
);
1597 SetConsoleCtrlHandler (&ctrl_c_handler
, FALSE
);
1600 return ptid_build (current_event
.dwProcessId
, 0, retval
);
1605 if (deprecated_ui_loop_hook
!= NULL
)
1606 detach
= deprecated_ui_loop_hook (0);
1609 windows_kill_inferior (ops
);
1614 /* Iterate over all DLLs currently mapped by our inferior, and
1615 add them to our list of solibs. */
1618 windows_add_all_dlls (void)
1621 HMODULE dummy_hmodule
;
1626 if (EnumProcessModules (current_process_handle
, &dummy_hmodule
,
1627 sizeof (HMODULE
), &cb_needed
) == 0)
1633 hmodules
= (HMODULE
*) alloca (cb_needed
);
1634 if (EnumProcessModules (current_process_handle
, hmodules
,
1635 cb_needed
, &cb_needed
) == 0)
1638 for (i
= 1; i
< (int) (cb_needed
/ sizeof (HMODULE
)); i
++)
1642 wchar_t dll_name
[__PMAX
];
1645 char dll_name
[__PMAX
];
1648 if (GetModuleInformation (current_process_handle
, hmodules
[i
],
1649 &mi
, sizeof (mi
)) == 0)
1651 if (GetModuleFileNameEx (current_process_handle
, hmodules
[i
],
1652 dll_name
, sizeof (dll_name
)) == 0)
1655 wcstombs (name
, dll_name
, __PMAX
);
1660 solib_end
->next
= windows_make_so (name
, mi
.lpBaseOfDll
);
1661 solib_end
= solib_end
->next
;
1666 do_initial_windows_stuff (struct target_ops
*ops
, DWORD pid
, int attaching
)
1669 struct inferior
*inf
;
1670 struct thread_info
*tp
;
1672 last_sig
= GDB_SIGNAL_0
;
1674 exception_count
= 0;
1675 open_process_used
= 0;
1676 debug_registers_changed
= 0;
1677 debug_registers_used
= 0;
1678 for (i
= 0; i
< sizeof (dr
) / sizeof (dr
[0]); i
++)
1681 cygwin_load_start
= cygwin_load_end
= 0;
1683 current_event
.dwProcessId
= pid
;
1684 memset (¤t_event
, 0, sizeof (current_event
));
1685 if (!target_is_pushed (ops
))
1687 disable_breakpoints_in_shlibs ();
1688 windows_clear_solib ();
1689 clear_proceed_status (0);
1690 init_wait_for_inferior ();
1692 inf
= current_inferior ();
1693 inferior_appeared (inf
, pid
);
1694 inf
->attach_flag
= attaching
;
1696 /* Make the new process the current inferior, so terminal handling
1697 can rely on it. When attaching, we don't know about any thread
1698 id here, but that's OK --- nothing should be referencing the
1699 current thread until we report an event out of windows_wait. */
1700 inferior_ptid
= pid_to_ptid (pid
);
1702 target_terminal_init ();
1703 target_terminal_inferior ();
1705 windows_initialization_done
= 0;
1709 struct target_waitstatus status
;
1711 windows_wait (ops
, minus_one_ptid
, &status
, 0);
1713 /* Note windows_wait returns TARGET_WAITKIND_SPURIOUS for thread
1715 if (status
.kind
!= TARGET_WAITKIND_LOADED
1716 && status
.kind
!= TARGET_WAITKIND_SPURIOUS
)
1719 windows_resume (ops
, minus_one_ptid
, 0, GDB_SIGNAL_0
);
1722 /* Now that the inferior has been started and all DLLs have been mapped,
1723 we can iterate over all DLLs and load them in.
1725 We avoid doing it any earlier because, on certain versions of Windows,
1726 LOAD_DLL_DEBUG_EVENTs are sometimes not complete. In particular,
1727 we have seen on Windows 8.1 that the ntdll.dll load event does not
1728 include the DLL name, preventing us from creating an associated SO.
1729 A possible explanation is that ntdll.dll might be mapped before
1730 the SO info gets created by the Windows system -- ntdll.dll is
1731 the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs
1732 do not seem to suffer from that problem.
1734 Rather than try to work around this sort of issue, it is much
1735 simpler to just ignore DLL load/unload events during the startup
1736 phase, and then process them all in one batch now. */
1737 windows_add_all_dlls ();
1739 windows_initialization_done
= 1;
1743 /* Try to set or remove a user privilege to the current process. Return -1
1744 if that fails, the previous setting of that privilege otherwise.
1746 This code is copied from the Cygwin source code and rearranged to allow
1747 dynamically loading of the needed symbols from advapi32 which is only
1748 available on NT/2K/XP. */
1750 set_process_privilege (const char *privilege
, BOOL enable
)
1752 HANDLE token_hdl
= NULL
;
1754 TOKEN_PRIVILEGES new_priv
, orig_priv
;
1758 if (!OpenProcessToken (GetCurrentProcess (),
1759 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
1763 if (!LookupPrivilegeValueA (NULL
, privilege
, &restore_priv
))
1766 new_priv
.PrivilegeCount
= 1;
1767 new_priv
.Privileges
[0].Luid
= restore_priv
;
1768 new_priv
.Privileges
[0].Attributes
= enable
? SE_PRIVILEGE_ENABLED
: 0;
1770 if (!AdjustTokenPrivileges (token_hdl
, FALSE
, &new_priv
,
1771 sizeof orig_priv
, &orig_priv
, &size
))
1774 /* Disabled, otherwise every `attach' in an unprivileged user session
1775 would raise the "Failed to get SE_DEBUG_NAME privilege" warning in
1776 windows_attach(). */
1777 /* AdjustTokenPrivileges returns TRUE even if the privilege could not
1778 be enabled. GetLastError () returns an correct error code, though. */
1779 if (enable
&& GetLastError () == ERROR_NOT_ALL_ASSIGNED
)
1783 ret
= orig_priv
.Privileges
[0].Attributes
== SE_PRIVILEGE_ENABLED
? 1 : 0;
1787 CloseHandle (token_hdl
);
1792 /* Attach to process PID, then initialize for debugging it. */
1794 windows_attach (struct target_ops
*ops
, const char *args
, int from_tty
)
1799 pid
= parse_pid_to_attach (args
);
1801 if (set_process_privilege (SE_DEBUG_NAME
, TRUE
) < 0)
1803 printf_unfiltered ("Warning: Failed to get SE_DEBUG_NAME privilege\n");
1804 printf_unfiltered ("This can cause attach to "
1805 "fail on Windows NT/2K/XP\n");
1808 windows_init_thread_list ();
1809 ok
= DebugActiveProcess (pid
);
1815 /* Try fall back to Cygwin pid. */
1816 pid
= cygwin_internal (CW_CYGWIN_PID_TO_WINPID
, pid
);
1819 ok
= DebugActiveProcess (pid
);
1824 error (_("Can't attach to process."));
1826 DebugSetProcessKillOnExit (FALSE
);
1830 char *exec_file
= (char *) get_exec_file (0);
1833 printf_unfiltered ("Attaching to program `%s', %s\n", exec_file
,
1834 target_pid_to_str (pid_to_ptid (pid
)));
1836 printf_unfiltered ("Attaching to %s\n",
1837 target_pid_to_str (pid_to_ptid (pid
)));
1839 gdb_flush (gdb_stdout
);
1842 do_initial_windows_stuff (ops
, pid
, 1);
1843 target_terminal_ours ();
1847 windows_detach (struct target_ops
*ops
, const char *args
, int from_tty
)
1852 windows_resume (ops
, ptid
, 0, GDB_SIGNAL_0
);
1854 if (!DebugActiveProcessStop (current_event
.dwProcessId
))
1856 error (_("Can't detach process %u (error %u)"),
1857 (unsigned) current_event
.dwProcessId
, (unsigned) GetLastError ());
1860 DebugSetProcessKillOnExit (FALSE
);
1862 if (detached
&& from_tty
)
1864 char *exec_file
= get_exec_file (0);
1867 printf_unfiltered ("Detaching from program: %s, Pid %u\n", exec_file
,
1868 (unsigned) current_event
.dwProcessId
);
1869 gdb_flush (gdb_stdout
);
1872 x86_cleanup_dregs ();
1873 inferior_ptid
= null_ptid
;
1874 detach_inferior (current_event
.dwProcessId
);
1876 inf_child_maybe_unpush_target (ops
);
1879 /* Try to determine the executable filename.
1881 EXE_NAME_RET is a pointer to a buffer whose size is EXE_NAME_MAX_LEN.
1883 Upon success, the filename is stored inside EXE_NAME_RET, and
1884 this function returns nonzero.
1886 Otherwise, this function returns zero and the contents of
1887 EXE_NAME_RET is undefined. */
1890 windows_get_exec_module_filename (char *exe_name_ret
, size_t exe_name_max_len
)
1897 if (!EnumProcessModules (current_process_handle
, &dh_buf
,
1898 sizeof (HMODULE
), &cbNeeded
) || !cbNeeded
)
1901 /* We know the executable is always first in the list of modules,
1902 which we just fetched. So no need to fetch more. */
1906 /* Cygwin prefers that the path be in /x/y/z format, so extract
1907 the filename into a temporary buffer first, and then convert it
1908 to POSIX format into the destination buffer. */
1909 cygwin_buf_t
*pathbuf
= alloca (exe_name_max_len
* sizeof (cygwin_buf_t
));
1911 len
= GetModuleFileNameEx (current_process_handle
,
1912 dh_buf
, pathbuf
, exe_name_max_len
);
1914 error (_("Error getting executable filename: %u."),
1915 (unsigned) GetLastError ());
1916 if (cygwin_conv_path (CCP_WIN_W_TO_POSIX
, pathbuf
, exe_name_ret
,
1917 exe_name_max_len
) < 0)
1918 error (_("Error converting executable filename to POSIX: %d."), errno
);
1921 len
= GetModuleFileNameEx (current_process_handle
,
1922 dh_buf
, exe_name_ret
, exe_name_max_len
);
1924 error (_("Error getting executable filename: %u."),
1925 (unsigned) GetLastError ());
1928 return 1; /* success */
1931 /* The pid_to_exec_file target_ops method for this platform. */
1934 windows_pid_to_exec_file (struct target_ops
*self
, int pid
)
1936 static char path
[__PMAX
];
1938 /* Try to find exe name as symlink target of /proc/<pid>/exe. */
1940 char procexe
[sizeof ("/proc/4294967295/exe")];
1942 xsnprintf (procexe
, sizeof (procexe
), "/proc/%u/exe", pid
);
1943 nchars
= readlink (procexe
, path
, sizeof(path
));
1944 if (nchars
> 0 && nchars
< sizeof (path
))
1946 path
[nchars
] = '\0'; /* Got it */
1951 /* If we get here then either Cygwin is hosed, this isn't a Cygwin version
1952 of gdb, or we're trying to debug a non-Cygwin windows executable. */
1953 if (!windows_get_exec_module_filename (path
, sizeof (path
)))
1959 /* Print status information about what we're accessing. */
1962 windows_files_info (struct target_ops
*ignore
)
1964 struct inferior
*inf
= current_inferior ();
1966 printf_unfiltered ("\tUsing the running image of %s %s.\n",
1967 inf
->attach_flag
? "attached" : "child",
1968 target_pid_to_str (inferior_ptid
));
1971 /* Modify CreateProcess parameters for use of a new separate console.
1973 *FLAGS: DWORD parameter for general process creation flags.
1974 *SI: STARTUPINFO structure, for which the console window size and
1975 console buffer size is filled in if GDB is running in a console.
1976 to create the new console.
1977 The size of the used font is not available on all versions of
1978 Windows OS. Furthermore, the current font might not be the default
1979 font, but this is still better than before.
1980 If the windows and buffer sizes are computed,
1981 SI->DWFLAGS is changed so that this information is used
1982 by CreateProcess function. */
1985 windows_set_console_info (STARTUPINFO
*si
, DWORD
*flags
)
1987 HANDLE hconsole
= CreateFile ("CONOUT$", GENERIC_READ
| GENERIC_WRITE
,
1988 FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, 0, 0);
1990 if (hconsole
!= INVALID_HANDLE_VALUE
)
1992 CONSOLE_SCREEN_BUFFER_INFO sbinfo
;
1994 CONSOLE_FONT_INFO cfi
;
1996 GetCurrentConsoleFont (hconsole
, FALSE
, &cfi
);
1997 font_size
= GetConsoleFontSize (hconsole
, cfi
.nFont
);
1998 GetConsoleScreenBufferInfo(hconsole
, &sbinfo
);
1999 si
->dwXSize
= sbinfo
.srWindow
.Right
- sbinfo
.srWindow
.Left
+ 1;
2000 si
->dwYSize
= sbinfo
.srWindow
.Bottom
- sbinfo
.srWindow
.Top
+ 1;
2002 si
->dwXSize
*= font_size
.X
;
2006 si
->dwYSize
*= font_size
.Y
;
2009 si
->dwXCountChars
= sbinfo
.dwSize
.X
;
2010 si
->dwYCountChars
= sbinfo
.dwSize
.Y
;
2011 si
->dwFlags
|= STARTF_USESIZE
| STARTF_USECOUNTCHARS
;
2013 *flags
|= CREATE_NEW_CONSOLE
;
2017 /* Function called by qsort to sort environment strings. */
2020 envvar_cmp (const void *a
, const void *b
)
2022 const char **p
= (const char **) a
;
2023 const char **q
= (const char **) b
;
2024 return strcasecmp (*p
, *q
);
2030 clear_win32_environment (char **env
)
2034 wchar_t *copy
= NULL
, *equalpos
;
2036 for (i
= 0; env
[i
] && *env
[i
]; i
++)
2038 len
= mbstowcs (NULL
, env
[i
], 0) + 1;
2039 copy
= (wchar_t *) xrealloc (copy
, len
* sizeof (wchar_t));
2040 mbstowcs (copy
, env
[i
], len
);
2041 equalpos
= wcschr (copy
, L
'=');
2044 SetEnvironmentVariableW (copy
, NULL
);
2050 /* Start an inferior windows child process and sets inferior_ptid to its pid.
2051 EXEC_FILE is the file to run.
2052 ALLARGS is a string containing the arguments to the program.
2053 ENV is the environment vector to pass. Errors reported with error(). */
2056 windows_create_inferior (struct target_ops
*ops
, char *exec_file
,
2057 char *allargs
, char **in_env
, int from_tty
)
2061 cygwin_buf_t real_path
[__PMAX
];
2062 cygwin_buf_t shell
[__PMAX
]; /* Path to shell */
2064 cygwin_buf_t
*toexec
;
2065 cygwin_buf_t
*cygallargs
;
2067 char **old_env
= NULL
;
2071 int ostdin
, ostdout
, ostderr
;
2073 char real_path
[__PMAX
];
2074 char shell
[__PMAX
]; /* Path to shell */
2086 PROCESS_INFORMATION pi
;
2089 const char *inferior_io_terminal
= get_inferior_io_terminal ();
2092 error (_("No executable specified, use `target exec'."));
2094 memset (&si
, 0, sizeof (si
));
2095 si
.cb
= sizeof (si
);
2098 flags
|= CREATE_NEW_PROCESS_GROUP
;
2101 windows_set_console_info (&si
, &flags
);
2106 flags
|= DEBUG_ONLY_THIS_PROCESS
;
2107 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W
, exec_file
, real_path
,
2108 __PMAX
* sizeof (cygwin_buf_t
)) < 0)
2109 error (_("Error starting executable: %d"), errno
);
2112 len
= mbstowcs (NULL
, allargs
, 0) + 1;
2113 if (len
== (size_t) -1)
2114 error (_("Error starting executable: %d"), errno
);
2115 cygallargs
= (wchar_t *) alloca (len
* sizeof (wchar_t));
2116 mbstowcs (cygallargs
, allargs
, len
);
2118 cygallargs
= allargs
;
2123 sh
= getenv ("SHELL");
2126 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W
, sh
, shell
, __PMAX
) < 0)
2127 error (_("Error starting executable via shell: %d"), errno
);
2129 len
= sizeof (L
" -c 'exec '") + mbstowcs (NULL
, exec_file
, 0)
2130 + mbstowcs (NULL
, allargs
, 0) + 2;
2131 cygallargs
= (wchar_t *) alloca (len
* sizeof (wchar_t));
2132 swprintf (cygallargs
, len
, L
" -c 'exec %s %s'", exec_file
, allargs
);
2134 len
= (sizeof (" -c 'exec '") + strlen (exec_file
)
2135 + strlen (allargs
) + 2);
2136 cygallargs
= (char *) alloca (len
);
2137 xsnprintf (cygallargs
, len
, " -c 'exec %s %s'", exec_file
, allargs
);
2140 flags
|= DEBUG_PROCESS
;
2144 args
= (cygwin_buf_t
*) alloca ((wcslen (toexec
) + wcslen (cygallargs
) + 2)
2145 * sizeof (wchar_t));
2146 wcscpy (args
, toexec
);
2147 wcscat (args
, L
" ");
2148 wcscat (args
, cygallargs
);
2150 args
= (cygwin_buf_t
*) alloca (strlen (toexec
) + strlen (cygallargs
) + 2);
2151 strcpy (args
, toexec
);
2153 strcat (args
, cygallargs
);
2156 #ifdef CW_CVT_ENV_TO_WINENV
2157 /* First try to create a direct Win32 copy of the POSIX environment. */
2158 w32_env
= (PWCHAR
) cygwin_internal (CW_CVT_ENV_TO_WINENV
, in_env
);
2159 if (w32_env
!= (PWCHAR
) -1)
2160 flags
|= CREATE_UNICODE_ENVIRONMENT
;
2162 /* If that fails, fall back to old method tweaking GDB's environment. */
2165 /* Reset all Win32 environment variables to avoid leftover on next run. */
2166 clear_win32_environment (environ
);
2167 /* Prepare the environment vars for CreateProcess. */
2170 cygwin_internal (CW_SYNC_WINENV
);
2174 if (!inferior_io_terminal
)
2175 tty
= ostdin
= ostdout
= ostderr
= -1;
2178 tty
= open (inferior_io_terminal
, O_RDWR
| O_NOCTTY
);
2181 print_sys_errmsg (inferior_io_terminal
, errno
);
2182 ostdin
= ostdout
= ostderr
= -1;
2195 windows_init_thread_list ();
2196 ret
= CreateProcess (0,
2197 args
, /* command line */
2198 NULL
, /* Security */
2200 TRUE
, /* inherit handles */
2201 flags
, /* start flags */
2202 w32_env
, /* environment */
2203 NULL
, /* current directory */
2207 /* Just free the Win32 environment, if it could be created. */
2211 /* Reset all environment variables to avoid leftover on next run. */
2212 clear_win32_environment (in_env
);
2213 /* Restore normal GDB environment variables. */
2215 cygwin_internal (CW_SYNC_WINENV
);
2230 /* Build the command line, a space-separated list of tokens where
2231 the first token is the name of the module to be executed.
2232 To avoid ambiguities introduced by spaces in the module name,
2234 args_len
= strlen (toexec
) + 2 /* quotes */ + strlen (allargs
) + 2;
2235 args
= (char *) alloca (args_len
);
2236 xsnprintf (args
, args_len
, "\"%s\" %s", toexec
, allargs
);
2238 flags
|= DEBUG_ONLY_THIS_PROCESS
;
2240 if (!inferior_io_terminal
)
2241 tty
= INVALID_HANDLE_VALUE
;
2244 SECURITY_ATTRIBUTES sa
;
2245 sa
.nLength
= sizeof(sa
);
2246 sa
.lpSecurityDescriptor
= 0;
2247 sa
.bInheritHandle
= TRUE
;
2248 tty
= CreateFileA (inferior_io_terminal
, GENERIC_READ
| GENERIC_WRITE
,
2249 0, &sa
, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
2250 if (tty
== INVALID_HANDLE_VALUE
)
2251 warning (_("Warning: Failed to open TTY %s, error %#x."),
2252 inferior_io_terminal
, (unsigned) GetLastError ());
2256 si
.hStdOutput
= tty
;
2258 si
.dwFlags
|= STARTF_USESTDHANDLES
;
2262 /* CreateProcess takes the environment list as a null terminated set of
2263 strings (i.e. two nulls terminate the list). */
2265 /* Get total size for env strings. */
2266 for (envlen
= 0, i
= 0; in_env
[i
] && *in_env
[i
]; i
++)
2267 envlen
+= strlen (in_env
[i
]) + 1;
2269 envsize
= sizeof (in_env
[0]) * (i
+ 1);
2270 env
= (char **) alloca (envsize
);
2271 memcpy (env
, in_env
, envsize
);
2272 /* Windows programs expect the environment block to be sorted. */
2273 qsort (env
, i
, sizeof (char *), envvar_cmp
);
2275 w32env
= (char *) alloca (envlen
+ 1);
2277 /* Copy env strings into new buffer. */
2278 for (temp
= w32env
, i
= 0; env
[i
] && *env
[i
]; i
++)
2280 strcpy (temp
, env
[i
]);
2281 temp
+= strlen (temp
) + 1;
2284 /* Final nil string to terminate new env. */
2287 windows_init_thread_list ();
2288 ret
= CreateProcessA (0,
2289 args
, /* command line */
2290 NULL
, /* Security */
2292 TRUE
, /* inherit handles */
2293 flags
, /* start flags */
2294 w32env
, /* environment */
2295 NULL
, /* current directory */
2298 if (tty
!= INVALID_HANDLE_VALUE
)
2303 error (_("Error creating process %s, (error %u)."),
2304 exec_file
, (unsigned) GetLastError ());
2306 CloseHandle (pi
.hThread
);
2307 CloseHandle (pi
.hProcess
);
2309 if (useshell
&& shell
[0] != '\0')
2314 do_initial_windows_stuff (ops
, pi
.dwProcessId
, 0);
2316 /* windows_continue (DBG_CONTINUE, -1, 0); */
2320 windows_mourn_inferior (struct target_ops
*ops
)
2322 (void) windows_continue (DBG_CONTINUE
, -1, 0);
2323 x86_cleanup_dregs();
2324 if (open_process_used
)
2326 CHECK (CloseHandle (current_process_handle
));
2327 open_process_used
= 0;
2329 inf_child_mourn_inferior (ops
);
2332 /* Send a SIGINT to the process group. This acts just like the user typed a
2333 ^C on the controlling terminal. */
2336 windows_interrupt (struct target_ops
*self
, ptid_t ptid
)
2338 DEBUG_EVENTS (("gdb: GenerateConsoleCtrlEvent (CTRLC_EVENT, 0)\n"));
2339 CHECK (GenerateConsoleCtrlEvent (CTRL_C_EVENT
, current_event
.dwProcessId
));
2340 registers_changed (); /* refresh register state */
2343 /* Helper for windows_xfer_partial that handles memory transfers.
2344 Arguments are like target_xfer_partial. */
2346 static enum target_xfer_status
2347 windows_xfer_memory (gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
2348 ULONGEST memaddr
, ULONGEST len
, ULONGEST
*xfered_len
)
2352 DWORD lasterror
= 0;
2354 if (writebuf
!= NULL
)
2356 DEBUG_MEM (("gdb: write target memory, %s bytes at %s\n",
2357 pulongest (len
), core_addr_to_string (memaddr
)));
2358 success
= WriteProcessMemory (current_process_handle
,
2359 (LPVOID
) (uintptr_t) memaddr
, writebuf
,
2362 lasterror
= GetLastError ();
2363 FlushInstructionCache (current_process_handle
,
2364 (LPCVOID
) (uintptr_t) memaddr
, len
);
2368 DEBUG_MEM (("gdb: read target memory, %s bytes at %s\n",
2369 pulongest (len
), core_addr_to_string (memaddr
)));
2370 success
= ReadProcessMemory (current_process_handle
,
2371 (LPCVOID
) (uintptr_t) memaddr
, readbuf
,
2374 lasterror
= GetLastError ();
2376 *xfered_len
= (ULONGEST
) done
;
2377 if (!success
&& lasterror
== ERROR_PARTIAL_COPY
&& done
> 0)
2378 return TARGET_XFER_OK
;
2380 return success
? TARGET_XFER_OK
: TARGET_XFER_E_IO
;
2384 windows_kill_inferior (struct target_ops
*ops
)
2386 CHECK (TerminateProcess (current_process_handle
, 0));
2390 if (!windows_continue (DBG_CONTINUE
, -1, 1))
2392 if (!WaitForDebugEvent (¤t_event
, INFINITE
))
2394 if (current_event
.dwDebugEventCode
== EXIT_PROCESS_DEBUG_EVENT
)
2398 target_mourn_inferior (); /* Or just windows_mourn_inferior? */
2402 windows_close (struct target_ops
*self
)
2404 DEBUG_EVENTS (("gdb: windows_close, inferior_ptid=%d\n",
2405 ptid_get_pid (inferior_ptid
)));
2408 /* Convert pid to printable format. */
2410 windows_pid_to_str (struct target_ops
*ops
, ptid_t ptid
)
2412 static char buf
[80];
2414 if (ptid_get_tid (ptid
) != 0)
2416 snprintf (buf
, sizeof (buf
), "Thread %d.0x%lx",
2417 ptid_get_pid (ptid
), ptid_get_tid (ptid
));
2421 return normal_pid_to_str (ptid
);
2424 static enum target_xfer_status
2425 windows_xfer_shared_libraries (struct target_ops
*ops
,
2426 enum target_object object
, const char *annex
,
2427 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
2428 ULONGEST offset
, ULONGEST len
,
2429 ULONGEST
*xfered_len
)
2431 struct obstack obstack
;
2437 return TARGET_XFER_E_IO
;
2439 obstack_init (&obstack
);
2440 obstack_grow_str (&obstack
, "<library-list>\n");
2441 for (so
= solib_start
.next
; so
; so
= so
->next
)
2442 windows_xfer_shared_library (so
->so_name
, (CORE_ADDR
)
2443 (uintptr_t) so
->lm_info
->load_addr
,
2444 target_gdbarch (), &obstack
);
2445 obstack_grow_str0 (&obstack
, "</library-list>\n");
2447 buf
= (const char *) obstack_finish (&obstack
);
2448 len_avail
= strlen (buf
);
2449 if (offset
>= len_avail
)
2453 if (len
> len_avail
- offset
)
2454 len
= len_avail
- offset
;
2455 memcpy (readbuf
, buf
+ offset
, len
);
2458 obstack_free (&obstack
, NULL
);
2459 *xfered_len
= (ULONGEST
) len
;
2460 return len
!= 0 ? TARGET_XFER_OK
: TARGET_XFER_EOF
;
2463 static enum target_xfer_status
2464 windows_xfer_partial (struct target_ops
*ops
, enum target_object object
,
2465 const char *annex
, gdb_byte
*readbuf
,
2466 const gdb_byte
*writebuf
, ULONGEST offset
, ULONGEST len
,
2467 ULONGEST
*xfered_len
)
2471 case TARGET_OBJECT_MEMORY
:
2472 return windows_xfer_memory (readbuf
, writebuf
, offset
, len
, xfered_len
);
2474 case TARGET_OBJECT_LIBRARIES
:
2475 return windows_xfer_shared_libraries (ops
, object
, annex
, readbuf
,
2476 writebuf
, offset
, len
, xfered_len
);
2479 return ops
->beneath
->to_xfer_partial (ops
->beneath
, object
, annex
,
2480 readbuf
, writebuf
, offset
, len
,
2485 /* Provide thread local base, i.e. Thread Information Block address.
2486 Returns 1 if ptid is found and sets *ADDR to thread_local_base. */
2489 windows_get_tib_address (struct target_ops
*self
,
2490 ptid_t ptid
, CORE_ADDR
*addr
)
2492 windows_thread_info
*th
;
2494 th
= thread_rec (ptid_get_tid (ptid
), 0);
2499 *addr
= th
->thread_local_base
;
2505 windows_get_ada_task_ptid (struct target_ops
*self
, long lwp
, long thread
)
2507 return ptid_build (ptid_get_pid (inferior_ptid
), 0, lwp
);
2510 static struct target_ops
*
2511 windows_target (void)
2513 struct target_ops
*t
= inf_child_target ();
2515 t
->to_close
= windows_close
;
2516 t
->to_attach
= windows_attach
;
2517 t
->to_attach_no_wait
= 1;
2518 t
->to_detach
= windows_detach
;
2519 t
->to_resume
= windows_resume
;
2520 t
->to_wait
= windows_wait
;
2521 t
->to_fetch_registers
= windows_fetch_inferior_registers
;
2522 t
->to_store_registers
= windows_store_inferior_registers
;
2523 t
->to_xfer_partial
= windows_xfer_partial
;
2524 t
->to_files_info
= windows_files_info
;
2525 t
->to_kill
= windows_kill_inferior
;
2526 t
->to_create_inferior
= windows_create_inferior
;
2527 t
->to_mourn_inferior
= windows_mourn_inferior
;
2528 t
->to_thread_alive
= windows_thread_alive
;
2529 t
->to_pid_to_str
= windows_pid_to_str
;
2530 t
->to_interrupt
= windows_interrupt
;
2531 t
->to_pid_to_exec_file
= windows_pid_to_exec_file
;
2532 t
->to_get_ada_task_ptid
= windows_get_ada_task_ptid
;
2533 t
->to_get_tib_address
= windows_get_tib_address
;
2538 /* -Wmissing-prototypes */
2539 extern initialize_file_ftype _initialize_windows_nat
;
2542 _initialize_windows_nat (void)
2544 struct target_ops
*t
;
2546 t
= windows_target ();
2548 x86_use_watchpoints (t
);
2550 x86_dr_low
.set_control
= cygwin_set_dr7
;
2551 x86_dr_low
.set_addr
= cygwin_set_dr
;
2552 x86_dr_low
.get_addr
= cygwin_get_dr
;
2553 x86_dr_low
.get_status
= cygwin_get_dr6
;
2554 x86_dr_low
.get_control
= cygwin_get_dr7
;
2556 /* x86_dr_low.debug_register_length field is set by
2557 calling x86_set_debug_register_length function
2558 in processor windows specific native file. */
2563 cygwin_internal (CW_SET_DOS_FILE_WARNING
, 0);
2567 add_setshow_boolean_cmd ("shell", class_support
, &useshell
, _("\
2568 Set use of shell to start subprocess."), _("\
2569 Show use of shell to start subprocess."), NULL
,
2571 NULL
, /* FIXME: i18n: */
2572 &setlist
, &showlist
);
2574 add_setshow_boolean_cmd ("cygwin-exceptions", class_support
,
2575 &cygwin_exceptions
, _("\
2576 Break when an exception is detected in the Cygwin DLL itself."), _("\
2577 Show whether gdb breaks on exceptions in the Cygwin DLL itself."), NULL
,
2579 NULL
, /* FIXME: i18n: */
2580 &setlist
, &showlist
);
2583 add_setshow_boolean_cmd ("new-console", class_support
, &new_console
, _("\
2584 Set creation of new console when creating child process."), _("\
2585 Show creation of new console when creating child process."), NULL
,
2587 NULL
, /* FIXME: i18n: */
2588 &setlist
, &showlist
);
2590 add_setshow_boolean_cmd ("new-group", class_support
, &new_group
, _("\
2591 Set creation of new group when creating child process."), _("\
2592 Show creation of new group when creating child process."), NULL
,
2594 NULL
, /* FIXME: i18n: */
2595 &setlist
, &showlist
);
2597 add_setshow_boolean_cmd ("debugexec", class_support
, &debug_exec
, _("\
2598 Set whether to display execution in child process."), _("\
2599 Show whether to display execution in child process."), NULL
,
2601 NULL
, /* FIXME: i18n: */
2602 &setlist
, &showlist
);
2604 add_setshow_boolean_cmd ("debugevents", class_support
, &debug_events
, _("\
2605 Set whether to display kernel events in child process."), _("\
2606 Show whether to display kernel events in child process."), NULL
,
2608 NULL
, /* FIXME: i18n: */
2609 &setlist
, &showlist
);
2611 add_setshow_boolean_cmd ("debugmemory", class_support
, &debug_memory
, _("\
2612 Set whether to display memory accesses in child process."), _("\
2613 Show whether to display memory accesses in child process."), NULL
,
2615 NULL
, /* FIXME: i18n: */
2616 &setlist
, &showlist
);
2618 add_setshow_boolean_cmd ("debugexceptions", class_support
,
2619 &debug_exceptions
, _("\
2620 Set whether to display kernel exceptions in child process."), _("\
2621 Show whether to display kernel exceptions in child process."), NULL
,
2623 NULL
, /* FIXME: i18n: */
2624 &setlist
, &showlist
);
2626 init_w32_command_list ();
2628 add_cmd ("selector", class_info
, display_selectors
,
2629 _("Display selectors infos."),
2633 /* Hardware watchpoint support, adapted from go32-nat.c code. */
2635 /* Pass the address ADDR to the inferior in the I'th debug register.
2636 Here we just store the address in dr array, the registers will be
2637 actually set up when windows_continue is called. */
2639 cygwin_set_dr (int i
, CORE_ADDR addr
)
2642 internal_error (__FILE__
, __LINE__
,
2643 _("Invalid register %d in cygwin_set_dr.\n"), i
);
2645 debug_registers_changed
= 1;
2646 debug_registers_used
= 1;
2649 /* Pass the value VAL to the inferior in the DR7 debug control
2650 register. Here we just store the address in D_REGS, the watchpoint
2651 will be actually set up in windows_wait. */
2653 cygwin_set_dr7 (unsigned long val
)
2655 dr
[7] = (CORE_ADDR
) val
;
2656 debug_registers_changed
= 1;
2657 debug_registers_used
= 1;
2660 /* Get the value of debug register I from the inferior. */
2663 cygwin_get_dr (int i
)
2668 /* Get the value of the DR6 debug status register from the inferior.
2669 Here we just return the value stored in dr[6]
2670 by the last call to thread_rec for current_event.dwThreadId id. */
2671 static unsigned long
2672 cygwin_get_dr6 (void)
2674 return (unsigned long) dr
[6];
2677 /* Get the value of the DR7 debug status register from the inferior.
2678 Here we just return the value stored in dr[7] by the last call to
2679 thread_rec for current_event.dwThreadId id. */
2681 static unsigned long
2682 cygwin_get_dr7 (void)
2684 return (unsigned long) dr
[7];
2687 /* Determine if the thread referenced by "ptid" is alive
2688 by "polling" it. If WaitForSingleObject returns WAIT_OBJECT_0
2689 it means that the thread has died. Otherwise it is assumed to be alive. */
2691 windows_thread_alive (struct target_ops
*ops
, ptid_t ptid
)
2695 gdb_assert (ptid_get_tid (ptid
) != 0);
2696 tid
= ptid_get_tid (ptid
);
2698 return WaitForSingleObject (thread_rec (tid
, FALSE
)->h
, 0) == WAIT_OBJECT_0
2702 /* -Wmissing-prototypes */
2703 extern initialize_file_ftype _initialize_check_for_gdb_ini
;
2706 _initialize_check_for_gdb_ini (void)
2709 if (inhibit_gdbinit
)
2712 homedir
= getenv ("HOME");
2716 char *oldini
= (char *) alloca (strlen (homedir
) +
2717 sizeof ("/gdb.ini"));
2718 strcpy (oldini
, homedir
);
2719 p
= strchr (oldini
, '\0');
2720 if (p
> oldini
&& !IS_DIR_SEPARATOR (p
[-1]))
2722 strcpy (p
, "gdb.ini");
2723 if (access (oldini
, 0) == 0)
2725 int len
= strlen (oldini
);
2726 char *newini
= (char *) alloca (len
+ 1);
2728 xsnprintf (newini
, len
+ 1, "%.*s.gdbinit",
2729 (int) (len
- (sizeof ("gdb.ini") - 1)), oldini
);
2730 warning (_("obsolete '%s' found. Rename to '%s'."), oldini
, newini
);
2735 /* Define dummy functions which always return error for the rare cases where
2736 these functions could not be found. */
2738 bad_DebugActiveProcessStop (DWORD w
)
2743 bad_DebugBreakProcess (HANDLE w
)
2748 bad_DebugSetProcessKillOnExit (BOOL w
)
2753 bad_EnumProcessModules (HANDLE w
, HMODULE
*x
, DWORD y
, LPDWORD z
)
2760 bad_GetModuleFileNameExW (HANDLE w
, HMODULE x
, LPWSTR y
, DWORD z
)
2766 bad_GetModuleFileNameExA (HANDLE w
, HMODULE x
, LPSTR y
, DWORD z
)
2773 bad_GetModuleInformation (HANDLE w
, HMODULE x
, LPMODULEINFO y
, DWORD z
)
2779 bad_OpenProcessToken (HANDLE w
, DWORD x
, PHANDLE y
)
2785 bad_GetCurrentConsoleFont (HANDLE w
, BOOL bMaxWindow
, CONSOLE_FONT_INFO
*f
)
2791 bad_GetConsoleFontSize (HANDLE w
, DWORD nFont
)
2799 /* -Wmissing-prototypes */
2800 extern initialize_file_ftype _initialize_loadable
;
2802 /* Load any functions which may not be available in ancient versions
2806 _initialize_loadable (void)
2810 #define GPA(m, func) \
2811 func = (func ## _ftype *) GetProcAddress (m, #func)
2813 hm
= LoadLibrary ("kernel32.dll");
2816 GPA (hm
, DebugActiveProcessStop
);
2817 GPA (hm
, DebugBreakProcess
);
2818 GPA (hm
, DebugSetProcessKillOnExit
);
2819 GPA (hm
, GetConsoleFontSize
);
2820 GPA (hm
, DebugActiveProcessStop
);
2821 GPA (hm
, GetCurrentConsoleFont
);
2824 /* Set variables to dummy versions of these processes if the function
2825 wasn't found in kernel32.dll. */
2826 if (!DebugBreakProcess
)
2827 DebugBreakProcess
= bad_DebugBreakProcess
;
2828 if (!DebugActiveProcessStop
|| !DebugSetProcessKillOnExit
)
2830 DebugActiveProcessStop
= bad_DebugActiveProcessStop
;
2831 DebugSetProcessKillOnExit
= bad_DebugSetProcessKillOnExit
;
2833 if (!GetConsoleFontSize
)
2834 GetConsoleFontSize
= bad_GetConsoleFontSize
;
2835 if (!GetCurrentConsoleFont
)
2836 GetCurrentConsoleFont
= bad_GetCurrentConsoleFont
;
2838 /* Load optional functions used for retrieving filename information
2839 associated with the currently debugged process or its dlls. */
2840 hm
= LoadLibrary ("psapi.dll");
2843 GPA (hm
, EnumProcessModules
);
2844 GPA (hm
, GetModuleInformation
);
2845 GPA (hm
, GetModuleFileNameEx
);
2848 if (!EnumProcessModules
|| !GetModuleInformation
|| !GetModuleFileNameEx
)
2850 /* Set variables to dummy versions of these processes if the function
2851 wasn't found in psapi.dll. */
2852 EnumProcessModules
= bad_EnumProcessModules
;
2853 GetModuleInformation
= bad_GetModuleInformation
;
2854 GetModuleFileNameEx
= bad_GetModuleFileNameEx
;
2855 /* This will probably fail on Windows 9x/Me. Let the user know
2856 that we're missing some functionality. */
2858 cannot automatically find executable file or library to read symbols.\n\
2859 Use \"file\" or \"dll\" command to load executable/libraries directly."));
2862 hm
= LoadLibrary ("advapi32.dll");
2865 GPA (hm
, OpenProcessToken
);
2866 GPA (hm
, LookupPrivilegeValueA
);
2867 GPA (hm
, AdjustTokenPrivileges
);
2868 /* Only need to set one of these since if OpenProcessToken fails nothing
2870 if (!OpenProcessToken
|| !LookupPrivilegeValueA
2871 || !AdjustTokenPrivileges
)
2872 OpenProcessToken
= bad_OpenProcessToken
;