1 /* Low level interface to Windows debugging, for gdbserver.
2 Copyright (C) 2006, 2007 Free Software Foundation, Inc.
4 Contributed by Leo Zayas. Based on "win32-nat.c" from GDB.
6 This file is part of GDB.
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>. */
23 #include "gdb/signals.h"
24 #include "mem-break.h"
25 #include "win32-low.h"
32 #include <sys/param.h>
37 #include <sys/cygwin.h>
42 #define OUTMSG(X) do { printf X; fflush (stdout); } while (0)
44 #define OUTMSG2(X) do { printf X; fflush (stdout); } while (0)
46 #define OUTMSG2(X) do ; while (0)
50 #define _T(x) TEXT (x)
54 #define COUNTOF(STR) (sizeof (STR) / sizeof ((STR)[0]))
58 # define GETPROCADDRESS(DLL, PROC) \
59 ((winapi_ ## PROC) GetProcAddress (DLL, TEXT (#PROC)))
61 # define GETPROCADDRESS(DLL, PROC) \
62 ((winapi_ ## PROC) GetProcAddress (DLL, #PROC))
65 int using_threads
= 1;
68 static HANDLE current_process_handle
= NULL
;
69 static DWORD current_process_id
= 0;
70 static enum target_signal last_sig
= TARGET_SIGNAL_0
;
72 /* The current debug event from WaitForDebugEvent. */
73 static DEBUG_EVENT current_event
;
75 #define NUM_REGS (the_low_target.num_regs)
77 typedef BOOL
WINAPI (*winapi_DebugActiveProcessStop
) (DWORD dwProcessId
);
78 typedef BOOL
WINAPI (*winapi_DebugSetProcessKillOnExit
) (BOOL KillOnExit
);
79 typedef BOOL
WINAPI (*winapi_DebugBreakProcess
) (HANDLE
);
80 typedef BOOL
WINAPI (*winapi_GenerateConsoleCtrlEvent
) (DWORD
, DWORD
);
82 static DWORD main_thread_id
= 0;
84 static void win32_resume (struct thread_resume
*resume_info
);
86 /* Get the thread ID from the current selected inferior (the current
89 current_inferior_tid (void)
91 win32_thread_info
*th
= inferior_target_data (current_inferior
);
95 /* Find a thread record given a thread id. If GET_CONTEXT is set then
96 also retrieve the context for this thread. */
97 static win32_thread_info
*
98 thread_rec (DWORD id
, int get_context
)
100 struct thread_info
*thread
;
101 win32_thread_info
*th
;
103 thread
= (struct thread_info
*) find_inferior_id (&all_threads
, id
);
107 th
= inferior_target_data (thread
);
108 if (!th
->suspend_count
&& get_context
)
110 if (id
!= current_event
.dwThreadId
)
111 th
->suspend_count
= SuspendThread (th
->h
) + 1;
113 (*the_low_target
.get_thread_context
) (th
, ¤t_event
);
119 /* Add a thread to the thread list. */
120 static win32_thread_info
*
121 child_add_thread (DWORD tid
, HANDLE h
)
123 win32_thread_info
*th
;
125 if ((th
= thread_rec (tid
, FALSE
)))
128 th
= (win32_thread_info
*) malloc (sizeof (*th
));
129 memset (th
, 0, sizeof (*th
));
133 add_thread (tid
, th
, (unsigned int) tid
);
134 set_inferior_regcache_data ((struct thread_info
*)
135 find_inferior_id (&all_threads
, tid
),
136 new_register_cache ());
138 if (the_low_target
.thread_added
!= NULL
)
139 (*the_low_target
.thread_added
) (th
);
144 /* Delete a thread from the list of threads. */
146 delete_thread_info (struct inferior_list_entry
*thread
)
148 win32_thread_info
*th
= inferior_target_data ((struct thread_info
*) thread
);
150 remove_thread ((struct thread_info
*) thread
);
155 /* Delete a thread from the list of threads. */
157 child_delete_thread (DWORD id
)
159 struct inferior_list_entry
*thread
;
161 /* If the last thread is exiting, just return. */
162 if (all_threads
.head
== all_threads
.tail
)
165 thread
= find_inferior_id (&all_threads
, id
);
169 delete_thread_info (thread
);
172 /* Transfer memory from/to the debugged process. */
174 child_xfer_memory (CORE_ADDR memaddr
, char *our
, int len
,
175 int write
, struct target_ops
*target
)
178 long addr
= (long) memaddr
;
182 WriteProcessMemory (current_process_handle
, (LPVOID
) addr
,
183 (LPCVOID
) our
, len
, &done
);
184 FlushInstructionCache (current_process_handle
, (LPCVOID
) addr
, len
);
188 ReadProcessMemory (current_process_handle
, (LPCVOID
) addr
, (LPVOID
) our
,
194 /* Generally, what has the program done? */
197 /* The program has exited. The exit status is in value.integer. */
198 TARGET_WAITKIND_EXITED
,
200 /* The program has stopped with a signal. Which signal is in
202 TARGET_WAITKIND_STOPPED
,
204 /* The program is letting us know that it dynamically loaded
205 or unloaded something. */
206 TARGET_WAITKIND_LOADED
,
208 /* The program has exec'ed a new executable file. The new file's
209 pathname is pointed to by value.execd_pathname. */
210 TARGET_WAITKIND_EXECD
,
212 /* Nothing interesting happened, but we stopped anyway. We take the
213 chance to check if GDB requested an interrupt. */
214 TARGET_WAITKIND_SPURIOUS
,
217 struct target_waitstatus
219 enum target_waitkind kind
;
221 /* Forked child pid, execd pathname, exit status or signal number. */
225 enum target_signal sig
;
227 char *execd_pathname
;
233 /* Clear out any old thread list and reinitialize it to a pristine
236 child_init_thread_list (void)
238 for_each_inferior (&all_threads
, delete_thread_info
);
242 do_initial_child_stuff (DWORD pid
)
244 last_sig
= TARGET_SIGNAL_0
;
246 memset (¤t_event
, 0, sizeof (current_event
));
248 child_init_thread_list ();
250 if (the_low_target
.initial_stuff
!= NULL
)
251 (*the_low_target
.initial_stuff
) ();
254 /* Resume all artificially suspended threads if we are continuing
257 continue_one_thread (struct inferior_list_entry
*this_thread
, void *id_ptr
)
259 struct thread_info
*thread
= (struct thread_info
*) this_thread
;
260 int thread_id
= * (int *) id_ptr
;
261 win32_thread_info
*th
= inferior_target_data (thread
);
264 if ((thread_id
== -1 || thread_id
== th
->tid
)
265 && th
->suspend_count
)
267 if (th
->context
.ContextFlags
)
269 (*the_low_target
.set_thread_context
) (th
, ¤t_event
);
270 th
->context
.ContextFlags
= 0;
273 for (i
= 0; i
< th
->suspend_count
; i
++)
274 (void) ResumeThread (th
->h
);
275 th
->suspend_count
= 0;
282 child_continue (DWORD continue_status
, int thread_id
)
286 res
= ContinueDebugEvent (current_event
.dwProcessId
,
287 current_event
.dwThreadId
, continue_status
);
289 find_inferior (&all_threads
, continue_one_thread
, &thread_id
);
294 /* Fetch register(s) from the current thread context. */
296 child_fetch_inferior_registers (int r
)
299 win32_thread_info
*th
= thread_rec (current_inferior_tid (), TRUE
);
300 if (r
== -1 || r
== 0 || r
> NUM_REGS
)
301 child_fetch_inferior_registers (NUM_REGS
);
303 for (regno
= 0; regno
< r
; regno
++)
304 (*the_low_target
.fetch_inferior_register
) (th
, regno
);
307 /* Store a new register value into the current thread context. We don't
308 change the program's context until later, when we resume it. */
310 child_store_inferior_registers (int r
)
313 win32_thread_info
*th
= thread_rec (current_inferior_tid (), TRUE
);
314 if (r
== -1 || r
== 0 || r
> NUM_REGS
)
315 child_store_inferior_registers (NUM_REGS
);
317 for (regno
= 0; regno
< r
; regno
++)
318 (*the_low_target
.store_inferior_register
) (th
, regno
);
321 /* Map the Windows error number in ERROR to a locale-dependent error
322 message string and return a pointer to it. Typically, the values
323 for ERROR come from GetLastError.
325 The string pointed to shall not be modified by the application,
326 but may be overwritten by a subsequent call to strwinerror
328 The strwinerror function does not change the current setting
332 strwinerror (DWORD error
)
334 static char buf
[1024];
336 DWORD lasterr
= GetLastError ();
337 DWORD chars
= FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
338 | FORMAT_MESSAGE_ALLOCATE_BUFFER
,
341 0, /* Default language */
347 /* If there is an \r\n appended, zap it. */
349 && msgbuf
[chars
- 2] == '\r'
350 && msgbuf
[chars
- 1] == '\n')
356 if (chars
> ((COUNTOF (buf
)) - 1))
358 chars
= COUNTOF (buf
) - 1;
363 wcstombs (buf
, msgbuf
, chars
+ 1);
365 strncpy (buf
, msgbuf
, chars
+ 1);
370 sprintf (buf
, "unknown win32 error (%ld)", error
);
372 SetLastError (lasterr
);
376 /* Start a new process.
377 PROGRAM is a path to the program to execute.
378 ARGS is a standard NULL-terminated array of arguments,
379 to be passed to the inferior as ``argv''.
380 Returns the new PID on success, -1 on failure. Registers the new
381 process with the process list. */
383 win32_create_inferior (char *program
, char **program_args
)
386 char real_path
[MAXPATHLEN
];
387 char *orig_path
, *new_path
, *path_ptr
;
394 PROCESS_INFORMATION pi
;
395 #ifndef __MINGW32CE__
396 STARTUPINFOA si
= { sizeof (STARTUPINFOA
) };
399 wchar_t *wargs
, *wprogram
;
403 error ("No executable specified, specify executable to debug.\n");
405 flags
= DEBUG_PROCESS
| DEBUG_ONLY_THIS_PROCESS
;
409 path_ptr
= getenv ("PATH");
412 orig_path
= alloca (strlen (path_ptr
) + 1);
413 new_path
= alloca (cygwin_posix_to_win32_path_list_buf_size (path_ptr
));
414 strcpy (orig_path
, path_ptr
);
415 cygwin_posix_to_win32_path_list (path_ptr
, new_path
);
416 setenv ("PATH", new_path
, 1);
418 cygwin_conv_to_win32_path (program
, real_path
);
423 for (argc
= 1; program_args
[argc
]; argc
++)
424 argslen
+= strlen (program_args
[argc
]) + 1;
425 args
= alloca (argslen
);
427 for (argc
= 1; program_args
[argc
]; argc
++)
429 /* FIXME: Can we do better about quoting? How does Cygwin
432 strcat (args
, program_args
[argc
]);
434 OUTMSG2 (("Command line is \"%s\"\n", args
));
436 #ifdef CREATE_NEW_PROCESS_GROUP
437 flags
|= CREATE_NEW_PROCESS_GROUP
;
441 to_back_slashes (program
);
442 wargs
= alloca (argslen
* sizeof (wchar_t));
443 mbstowcs (wargs
, args
, argslen
);
444 wprogram
= alloca ((strlen (program
) + 1) * sizeof (wchar_t));
445 mbstowcs (wprogram
, program
, strlen (program
) + 1);
446 ret
= CreateProcessW (wprogram
, /* image name */
447 wargs
, /* command line */
448 NULL
, /* security, not supported */
449 NULL
, /* thread, not supported */
450 FALSE
, /* inherit handles, not supported */
451 flags
, /* start flags */
452 NULL
, /* environment, not supported */
453 NULL
, /* current directory, not supported */
454 NULL
, /* start info, not supported */
455 &pi
); /* proc info */
457 ret
= CreateProcessA (program
, /* image name */
458 args
, /* command line */
461 TRUE
, /* inherit handles */
462 flags
, /* start flags */
463 winenv
, /* environment */
464 NULL
, /* current directory */
465 &si
, /* start info */
466 &pi
); /* proc info */
471 setenv ("PATH", orig_path
, 1);
476 DWORD err
= GetLastError ();
477 error ("Error creating process \"%s%s\", (error %d): %s\n",
478 program
, args
, (int) err
, strwinerror (err
));
482 OUTMSG2 (("Process created: %s\n", (char *) args
));
486 /* On Windows CE this handle can't be closed. The OS reuses
487 it in the debug events, while the 9x/NT versions of Windows
488 probably use a DuplicateHandle'd one. */
489 CloseHandle (pi
.hThread
);
492 current_process_handle
= pi
.hProcess
;
493 current_process_id
= pi
.dwProcessId
;
495 do_initial_child_stuff (current_process_id
);
497 return current_process_id
;
500 /* Attach to a running process.
501 PID is the process ID to attach to, specified by the user
502 or a higher layer. */
504 win32_attach (unsigned long pid
)
506 winapi_DebugActiveProcessStop DebugActiveProcessStop
= NULL
;
507 winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit
= NULL
;
509 HMODULE dll
= GetModuleHandle (_T("COREDLL.DLL"));
511 HMODULE dll
= GetModuleHandle (_T("KERNEL32.DLL"));
513 DebugActiveProcessStop
= GETPROCADDRESS (dll
, DebugActiveProcessStop
);
514 DebugSetProcessKillOnExit
= GETPROCADDRESS (dll
, DebugSetProcessKillOnExit
);
516 if (DebugActiveProcess (pid
))
518 if (DebugSetProcessKillOnExit
!= NULL
)
519 DebugSetProcessKillOnExit (FALSE
);
521 current_process_handle
= OpenProcess (PROCESS_ALL_ACCESS
, FALSE
, pid
);
523 if (current_process_handle
!= NULL
)
525 current_process_id
= pid
;
526 do_initial_child_stuff (pid
);
529 if (DebugActiveProcessStop
!= NULL
)
530 DebugActiveProcessStop (current_process_id
);
533 error ("Attach to process failed.");
536 /* Handle OUTPUT_DEBUG_STRING_EVENT from child process. */
538 handle_output_debug_string (struct target_waitstatus
*ourstatus
)
540 #define READ_BUFFER_LEN 1024
542 char s
[READ_BUFFER_LEN
+ 1] = { 0 };
543 DWORD nbytes
= current_event
.u
.DebugString
.nDebugStringLength
;
548 if (nbytes
> READ_BUFFER_LEN
)
549 nbytes
= READ_BUFFER_LEN
;
551 addr
= (CORE_ADDR
) (size_t) current_event
.u
.DebugString
.lpDebugStringData
;
553 if (current_event
.u
.DebugString
.fUnicode
)
555 /* The event tells us how many bytes, not chars, even
557 WCHAR buffer
[(READ_BUFFER_LEN
+ 1) / sizeof (WCHAR
)] = { 0 };
558 if (read_inferior_memory (addr
, (unsigned char *) buffer
, nbytes
) != 0)
560 wcstombs (s
, buffer
, (nbytes
+ 1) / sizeof (WCHAR
));
564 if (read_inferior_memory (addr
, (unsigned char *) s
, nbytes
) != 0)
568 if (strncmp (s
, "cYg", 3) != 0)
578 #undef READ_BUFFER_LEN
581 /* Kill all inferiors. */
585 win32_thread_info
*current_thread
;
587 if (current_process_handle
== NULL
)
590 TerminateProcess (current_process_handle
, 0);
593 if (!child_continue (DBG_CONTINUE
, -1))
595 if (!WaitForDebugEvent (¤t_event
, INFINITE
))
597 if (current_event
.dwDebugEventCode
== EXIT_PROCESS_DEBUG_EVENT
)
599 else if (current_event
.dwDebugEventCode
== OUTPUT_DEBUG_STRING_EVENT
)
601 struct target_waitstatus our_status
= { 0 };
602 handle_output_debug_string (&our_status
);
606 CloseHandle (current_process_handle
);
608 current_thread
= inferior_target_data (current_inferior
);
609 if (current_thread
&& current_thread
->h
)
611 /* This may fail in an attached process, so don't check. */
612 (void) CloseHandle (current_thread
->h
);
616 /* Detach from all inferiors. */
622 winapi_DebugActiveProcessStop DebugActiveProcessStop
= NULL
;
623 winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit
= NULL
;
625 HMODULE dll
= GetModuleHandle (_T("COREDLL.DLL"));
627 HMODULE dll
= GetModuleHandle (_T("KERNEL32.DLL"));
629 DebugActiveProcessStop
= GETPROCADDRESS (dll
, DebugActiveProcessStop
);
630 DebugSetProcessKillOnExit
= GETPROCADDRESS (dll
, DebugSetProcessKillOnExit
);
632 if (DebugSetProcessKillOnExit
== NULL
633 || DebugActiveProcessStop
== NULL
)
636 /* We need a new handle, since DebugActiveProcessStop
637 closes all the ones that came through the events. */
638 if ((h
= OpenProcess (PROCESS_ALL_ACCESS
,
640 current_process_id
)) == NULL
)
642 /* The process died. */
647 struct thread_resume resume
;
651 resume
.leave_stopped
= 0;
652 win32_resume (&resume
);
655 if (!DebugActiveProcessStop (current_process_id
))
660 DebugSetProcessKillOnExit (FALSE
);
662 current_process_handle
= h
;
666 /* Wait for inferiors to end. */
670 if (current_process_id
== 0
671 || current_process_handle
== NULL
)
674 WaitForSingleObject (current_process_handle
, INFINITE
);
675 CloseHandle (current_process_handle
);
677 current_process_handle
= NULL
;
678 current_process_id
= 0;
681 /* Return 1 iff the thread with thread ID TID is alive. */
683 win32_thread_alive (unsigned long tid
)
687 /* Our thread list is reliable; don't bother to poll target
689 if (find_inferior_id (&all_threads
, tid
) != NULL
)
696 /* Resume the inferior process. RESUME_INFO describes how we want
699 win32_resume (struct thread_resume
*resume_info
)
702 enum target_signal sig
;
704 win32_thread_info
*th
;
705 DWORD continue_status
= DBG_CONTINUE
;
707 /* This handles the very limited set of resume packets that GDB can
708 currently produce. */
710 if (resume_info
[0].thread
== -1)
712 else if (resume_info
[1].thread
== -1 && !resume_info
[1].leave_stopped
)
715 /* Yes, we're ignoring resume_info[0].thread. It'd be tricky to make
716 the Windows resume code do the right thing for thread switching. */
717 tid
= current_event
.dwThreadId
;
719 if (resume_info
[0].thread
!= -1)
721 sig
= resume_info
[0].sig
;
722 step
= resume_info
[0].step
;
730 if (sig
!= TARGET_SIGNAL_0
)
732 if (current_event
.dwDebugEventCode
!= EXCEPTION_DEBUG_EVENT
)
734 OUTMSG (("Cannot continue with signal %d here.\n", sig
));
736 else if (sig
== last_sig
)
737 continue_status
= DBG_EXCEPTION_NOT_HANDLED
;
739 OUTMSG (("Can only continue with recieved signal %d.\n", last_sig
));
742 last_sig
= TARGET_SIGNAL_0
;
744 /* Get context for the currently selected thread. */
745 th
= thread_rec (current_event
.dwThreadId
, FALSE
);
748 if (th
->context
.ContextFlags
)
750 /* Move register values from the inferior into the thread
751 context structure. */
752 regcache_invalidate ();
756 if (the_low_target
.single_step
!= NULL
)
757 (*the_low_target
.single_step
) (th
);
759 error ("Single stepping is not supported "
760 "in this configuration.\n");
763 (*the_low_target
.set_thread_context
) (th
, ¤t_event
);
764 th
->context
.ContextFlags
= 0;
768 /* Allow continuing with the same signal that interrupted us.
769 Otherwise complain. */
771 child_continue (continue_status
, tid
);
775 win32_add_one_solib (const char *name
, CORE_ADDR load_addr
)
777 char buf
[MAX_PATH
+ 1];
778 char buf2
[MAX_PATH
+ 1];
781 WIN32_FIND_DATA w32_fd
;
782 WCHAR wname
[MAX_PATH
+ 1];
783 mbstowcs (wname
, name
, MAX_PATH
);
784 HANDLE h
= FindFirstFile (wname
, &w32_fd
);
786 WIN32_FIND_DATAA w32_fd
;
787 HANDLE h
= FindFirstFileA (name
, &w32_fd
);
790 if (h
== INVALID_HANDLE_VALUE
)
798 char cwd
[MAX_PATH
+ 1];
800 if (GetCurrentDirectoryA (MAX_PATH
+ 1, cwd
))
802 p
= strrchr (buf
, '\\');
805 SetCurrentDirectoryA (buf
);
806 GetFullPathNameA (w32_fd
.cFileName
, MAX_PATH
, buf
, &p
);
807 SetCurrentDirectoryA (cwd
);
814 cygwin_conv_to_posix_path (buf
, buf2
);
819 loaded_dll (buf2
, load_addr
);
823 get_image_name (HANDLE h
, void *address
, int unicode
)
825 static char buf
[(2 * MAX_PATH
) + 1];
826 DWORD size
= unicode
? sizeof (WCHAR
) : sizeof (char);
832 /* Attempt to read the name of the dll that was detected.
833 This is documented to work only when actively debugging
834 a program. It will not work for attached processes. */
839 /* Windows CE reports the address of the image name,
840 instead of an address of a pointer into the image name. */
841 address_ptr
= address
;
843 /* See if we could read the address of a string, and that the
844 address isn't null. */
845 if (!ReadProcessMemory (h
, address
, &address_ptr
,
846 sizeof (address_ptr
), &done
)
847 || done
!= sizeof (address_ptr
)
852 /* Find the length of the string */
853 while (ReadProcessMemory (h
, address_ptr
+ len
++ * size
, &b
, size
, &done
)
854 && (b
[0] != 0 || b
[size
- 1] != 0) && done
== size
)
858 ReadProcessMemory (h
, address_ptr
, buf
, len
, &done
);
861 WCHAR
*unicode_address
= (WCHAR
*) alloca (len
* sizeof (WCHAR
));
862 ReadProcessMemory (h
, address_ptr
, unicode_address
, len
* sizeof (WCHAR
),
865 WideCharToMultiByte (CP_ACP
, 0, unicode_address
, len
, buf
, len
, 0, 0);
871 typedef BOOL (WINAPI
*winapi_EnumProcessModules
) (HANDLE
, HMODULE
*,
873 typedef BOOL (WINAPI
*winapi_GetModuleInformation
) (HANDLE
, HMODULE
,
874 LPMODULEINFO
, DWORD
);
875 typedef DWORD (WINAPI
*winapi_GetModuleFileNameExA
) (HANDLE
, HMODULE
,
878 static winapi_EnumProcessModules win32_EnumProcessModules
;
879 static winapi_GetModuleInformation win32_GetModuleInformation
;
880 static winapi_GetModuleFileNameExA win32_GetModuleFileNameExA
;
885 static int psapi_loaded
= 0;
886 static HMODULE dll
= NULL
;
891 dll
= LoadLibrary (TEXT("psapi.dll"));
894 win32_EnumProcessModules
=
895 GETPROCADDRESS (dll
, EnumProcessModules
);
896 win32_GetModuleInformation
=
897 GETPROCADDRESS (dll
, GetModuleInformation
);
898 win32_GetModuleFileNameExA
=
899 GETPROCADDRESS (dll
, GetModuleFileNameExA
);
902 return (win32_EnumProcessModules
!= NULL
903 && win32_GetModuleInformation
!= NULL
904 && win32_GetModuleFileNameExA
!= NULL
);
908 psapi_get_dll_name (DWORD BaseAddress
, char *dll_name_ret
)
914 HMODULE
*DllHandle
= dh_buf
;
922 ok
= (*win32_EnumProcessModules
) (current_process_handle
,
927 if (!ok
|| !cbNeeded
)
930 DllHandle
= (HMODULE
*) alloca (cbNeeded
);
934 ok
= (*win32_EnumProcessModules
) (current_process_handle
,
941 for (i
= 0; i
< ((size_t) cbNeeded
/ sizeof (HMODULE
)); i
++)
943 if (!(*win32_GetModuleInformation
) (current_process_handle
,
948 DWORD err
= GetLastError ();
949 error ("Can't get module info: (error %d): %s\n",
950 (int) err
, strwinerror (err
));
953 if ((DWORD
) (mi
.lpBaseOfDll
) == BaseAddress
)
955 len
= (*win32_GetModuleFileNameExA
) (current_process_handle
,
961 DWORD err
= GetLastError ();
962 error ("Error getting dll name: (error %d): %s\n",
963 (int) err
, strwinerror (err
));
970 dll_name_ret
[0] = '\0';
974 typedef HANDLE (WINAPI
*winapi_CreateToolhelp32Snapshot
) (DWORD
, DWORD
);
975 typedef BOOL (WINAPI
*winapi_Module32First
) (HANDLE
, LPMODULEENTRY32
);
976 typedef BOOL (WINAPI
*winapi_Module32Next
) (HANDLE
, LPMODULEENTRY32
);
978 static winapi_CreateToolhelp32Snapshot win32_CreateToolhelp32Snapshot
;
979 static winapi_Module32First win32_Module32First
;
980 static winapi_Module32Next win32_Module32Next
;
982 typedef BOOL (WINAPI
*winapi_CloseToolhelp32Snapshot
) (HANDLE
);
983 static winapi_CloseToolhelp32Snapshot win32_CloseToolhelp32Snapshot
;
989 static int toolhelp_loaded
= 0;
990 static HMODULE dll
= NULL
;
992 if (!toolhelp_loaded
)
996 dll
= GetModuleHandle (_T("KERNEL32.DLL"));
998 dll
= LoadLibrary (L
"TOOLHELP.DLL");
1003 win32_CreateToolhelp32Snapshot
=
1004 GETPROCADDRESS (dll
, CreateToolhelp32Snapshot
);
1005 win32_Module32First
= GETPROCADDRESS (dll
, Module32First
);
1006 win32_Module32Next
= GETPROCADDRESS (dll
, Module32Next
);
1008 win32_CloseToolhelp32Snapshot
=
1009 GETPROCADDRESS (dll
, CloseToolhelp32Snapshot
);
1013 return (win32_CreateToolhelp32Snapshot
!= NULL
1014 && win32_Module32First
!= NULL
1015 && win32_Module32Next
!= NULL
1017 && win32_CloseToolhelp32Snapshot
!= NULL
1023 toolhelp_get_dll_name (DWORD BaseAddress
, char *dll_name_ret
)
1025 HANDLE snapshot_module
;
1026 MODULEENTRY32 modEntry
= { sizeof (MODULEENTRY32
) };
1029 if (!load_toolhelp ())
1032 snapshot_module
= win32_CreateToolhelp32Snapshot (TH32CS_SNAPMODULE
,
1033 current_event
.dwProcessId
);
1034 if (snapshot_module
== INVALID_HANDLE_VALUE
)
1037 /* Ignore the first module, which is the exe. */
1038 if (win32_Module32First (snapshot_module
, &modEntry
))
1039 while (win32_Module32Next (snapshot_module
, &modEntry
))
1040 if ((DWORD
) modEntry
.modBaseAddr
== BaseAddress
)
1043 wcstombs (dll_name_ret
, modEntry
.szExePath
, MAX_PATH
+ 1);
1045 strcpy (dll_name_ret
, modEntry
.szExePath
);
1052 win32_CloseToolhelp32Snapshot (snapshot_module
);
1054 CloseHandle (snapshot_module
);
1060 handle_load_dll (void)
1062 LOAD_DLL_DEBUG_INFO
*event
= ¤t_event
.u
.LoadDll
;
1063 char dll_buf
[MAX_PATH
+ 1];
1064 char *dll_name
= NULL
;
1067 dll_buf
[0] = dll_buf
[sizeof (dll_buf
) - 1] = '\0';
1069 if (!psapi_get_dll_name ((DWORD
) (event
->lpBaseOfDll
), dll_buf
)
1070 && !toolhelp_get_dll_name ((DWORD
) (event
->lpBaseOfDll
), dll_buf
))
1071 dll_buf
[0] = dll_buf
[sizeof (dll_buf
) - 1] = '\0';
1075 if (*dll_name
== '\0')
1076 dll_name
= get_image_name (current_process_handle
,
1077 event
->lpImageName
, event
->fUnicode
);
1081 /* The symbols in a dll are offset by 0x1000, which is the
1082 the offset from 0 of the first byte in an image - because
1083 of the file header and the section alignment. */
1085 load_addr
= (DWORD
) event
->lpBaseOfDll
+ 0x1000;
1086 win32_add_one_solib (dll_name
, load_addr
);
1090 handle_unload_dll (void)
1092 CORE_ADDR load_addr
=
1093 (CORE_ADDR
) (DWORD
) current_event
.u
.UnloadDll
.lpBaseOfDll
;
1094 load_addr
+= 0x1000;
1095 unloaded_dll (NULL
, load_addr
);
1099 handle_exception (struct target_waitstatus
*ourstatus
)
1101 DWORD code
= current_event
.u
.Exception
.ExceptionRecord
.ExceptionCode
;
1103 ourstatus
->kind
= TARGET_WAITKIND_STOPPED
;
1107 case EXCEPTION_ACCESS_VIOLATION
:
1108 OUTMSG2 (("EXCEPTION_ACCESS_VIOLATION"));
1109 ourstatus
->value
.sig
= TARGET_SIGNAL_SEGV
;
1111 case STATUS_STACK_OVERFLOW
:
1112 OUTMSG2 (("STATUS_STACK_OVERFLOW"));
1113 ourstatus
->value
.sig
= TARGET_SIGNAL_SEGV
;
1115 case STATUS_FLOAT_DENORMAL_OPERAND
:
1116 OUTMSG2 (("STATUS_FLOAT_DENORMAL_OPERAND"));
1117 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1119 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED
:
1120 OUTMSG2 (("EXCEPTION_ARRAY_BOUNDS_EXCEEDED"));
1121 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1123 case STATUS_FLOAT_INEXACT_RESULT
:
1124 OUTMSG2 (("STATUS_FLOAT_INEXACT_RESULT"));
1125 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1127 case STATUS_FLOAT_INVALID_OPERATION
:
1128 OUTMSG2 (("STATUS_FLOAT_INVALID_OPERATION"));
1129 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1131 case STATUS_FLOAT_OVERFLOW
:
1132 OUTMSG2 (("STATUS_FLOAT_OVERFLOW"));
1133 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1135 case STATUS_FLOAT_STACK_CHECK
:
1136 OUTMSG2 (("STATUS_FLOAT_STACK_CHECK"));
1137 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1139 case STATUS_FLOAT_UNDERFLOW
:
1140 OUTMSG2 (("STATUS_FLOAT_UNDERFLOW"));
1141 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1143 case STATUS_FLOAT_DIVIDE_BY_ZERO
:
1144 OUTMSG2 (("STATUS_FLOAT_DIVIDE_BY_ZERO"));
1145 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1147 case STATUS_INTEGER_DIVIDE_BY_ZERO
:
1148 OUTMSG2 (("STATUS_INTEGER_DIVIDE_BY_ZERO"));
1149 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1151 case STATUS_INTEGER_OVERFLOW
:
1152 OUTMSG2 (("STATUS_INTEGER_OVERFLOW"));
1153 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1155 case EXCEPTION_BREAKPOINT
:
1156 OUTMSG2 (("EXCEPTION_BREAKPOINT"));
1157 ourstatus
->value
.sig
= TARGET_SIGNAL_TRAP
;
1159 /* Remove the initial breakpoint. */
1160 check_breakpoints ((CORE_ADDR
) (long) current_event
1161 .u
.Exception
.ExceptionRecord
.ExceptionAddress
);
1165 OUTMSG2 (("DBG_CONTROL_C"));
1166 ourstatus
->value
.sig
= TARGET_SIGNAL_INT
;
1168 case DBG_CONTROL_BREAK
:
1169 OUTMSG2 (("DBG_CONTROL_BREAK"));
1170 ourstatus
->value
.sig
= TARGET_SIGNAL_INT
;
1172 case EXCEPTION_SINGLE_STEP
:
1173 OUTMSG2 (("EXCEPTION_SINGLE_STEP"));
1174 ourstatus
->value
.sig
= TARGET_SIGNAL_TRAP
;
1176 case EXCEPTION_ILLEGAL_INSTRUCTION
:
1177 OUTMSG2 (("EXCEPTION_ILLEGAL_INSTRUCTION"));
1178 ourstatus
->value
.sig
= TARGET_SIGNAL_ILL
;
1180 case EXCEPTION_PRIV_INSTRUCTION
:
1181 OUTMSG2 (("EXCEPTION_PRIV_INSTRUCTION"));
1182 ourstatus
->value
.sig
= TARGET_SIGNAL_ILL
;
1184 case EXCEPTION_NONCONTINUABLE_EXCEPTION
:
1185 OUTMSG2 (("EXCEPTION_NONCONTINUABLE_EXCEPTION"));
1186 ourstatus
->value
.sig
= TARGET_SIGNAL_ILL
;
1189 if (current_event
.u
.Exception
.dwFirstChance
)
1191 ourstatus
->kind
= TARGET_WAITKIND_SPURIOUS
;
1194 OUTMSG2 (("gdbserver: unknown target exception 0x%08lx at 0x%08lx",
1195 current_event
.u
.Exception
.ExceptionRecord
.ExceptionCode
,
1196 (DWORD
) current_event
.u
.Exception
.ExceptionRecord
.
1198 ourstatus
->value
.sig
= TARGET_SIGNAL_UNKNOWN
;
1202 last_sig
= ourstatus
->value
.sig
;
1205 /* Get the next event from the child. */
1207 get_child_debug_event (struct target_waitstatus
*ourstatus
)
1211 last_sig
= TARGET_SIGNAL_0
;
1212 ourstatus
->kind
= TARGET_WAITKIND_SPURIOUS
;
1214 /* Keep the wait time low enough for confortable remote interruption,
1215 but high enough so gdbserver doesn't become a bottleneck. */
1216 if (!(debug_event
= WaitForDebugEvent (¤t_event
, 250)))
1220 (struct thread_info
*) find_inferior_id (&all_threads
,
1221 current_event
.dwThreadId
);
1223 switch (current_event
.dwDebugEventCode
)
1225 case CREATE_THREAD_DEBUG_EVENT
:
1226 OUTMSG2 (("gdbserver: kernel event CREATE_THREAD_DEBUG_EVENT "
1227 "for pid=%d tid=%x)\n",
1228 (unsigned) current_event
.dwProcessId
,
1229 (unsigned) current_event
.dwThreadId
));
1231 /* Record the existence of this thread. */
1232 child_add_thread (current_event
.dwThreadId
,
1233 current_event
.u
.CreateThread
.hThread
);
1236 case EXIT_THREAD_DEBUG_EVENT
:
1237 OUTMSG2 (("gdbserver: kernel event EXIT_THREAD_DEBUG_EVENT "
1238 "for pid=%d tid=%x\n",
1239 (unsigned) current_event
.dwProcessId
,
1240 (unsigned) current_event
.dwThreadId
));
1241 child_delete_thread (current_event
.dwThreadId
);
1244 case CREATE_PROCESS_DEBUG_EVENT
:
1245 OUTMSG2 (("gdbserver: kernel event CREATE_PROCESS_DEBUG_EVENT "
1246 "for pid=%d tid=%x\n",
1247 (unsigned) current_event
.dwProcessId
,
1248 (unsigned) current_event
.dwThreadId
));
1249 CloseHandle (current_event
.u
.CreateProcessInfo
.hFile
);
1251 current_process_handle
= current_event
.u
.CreateProcessInfo
.hProcess
;
1252 main_thread_id
= current_event
.dwThreadId
;
1254 ourstatus
->kind
= TARGET_WAITKIND_EXECD
;
1255 ourstatus
->value
.execd_pathname
= "Main executable";
1257 /* Add the main thread. */
1258 child_add_thread (main_thread_id
,
1259 current_event
.u
.CreateProcessInfo
.hThread
);
1261 ourstatus
->value
.related_pid
= current_event
.dwThreadId
;
1263 /* Windows CE doesn't set the initial breakpoint automatically
1264 like the desktop versions of Windows do. We add it explicitly
1265 here. It will be removed as soon as it is hit. */
1266 set_breakpoint_at ((CORE_ADDR
) (long) current_event
.u
1267 .CreateProcessInfo
.lpStartAddress
,
1268 delete_breakpoint_at
);
1272 case EXIT_PROCESS_DEBUG_EVENT
:
1273 OUTMSG2 (("gdbserver: kernel event EXIT_PROCESS_DEBUG_EVENT "
1274 "for pid=%d tid=%x\n",
1275 (unsigned) current_event
.dwProcessId
,
1276 (unsigned) current_event
.dwThreadId
));
1277 ourstatus
->kind
= TARGET_WAITKIND_EXITED
;
1278 ourstatus
->value
.integer
= current_event
.u
.ExitProcess
.dwExitCode
;
1279 CloseHandle (current_process_handle
);
1280 current_process_handle
= NULL
;
1283 case LOAD_DLL_DEBUG_EVENT
:
1284 OUTMSG2 (("gdbserver: kernel event LOAD_DLL_DEBUG_EVENT "
1285 "for pid=%d tid=%x\n",
1286 (unsigned) current_event
.dwProcessId
,
1287 (unsigned) current_event
.dwThreadId
));
1288 CloseHandle (current_event
.u
.LoadDll
.hFile
);
1291 ourstatus
->kind
= TARGET_WAITKIND_LOADED
;
1292 ourstatus
->value
.sig
= TARGET_SIGNAL_TRAP
;
1295 case UNLOAD_DLL_DEBUG_EVENT
:
1296 OUTMSG2 (("gdbserver: kernel event UNLOAD_DLL_DEBUG_EVENT "
1297 "for pid=%d tid=%x\n",
1298 (unsigned) current_event
.dwProcessId
,
1299 (unsigned) current_event
.dwThreadId
));
1300 handle_unload_dll ();
1301 ourstatus
->kind
= TARGET_WAITKIND_LOADED
;
1302 ourstatus
->value
.sig
= TARGET_SIGNAL_TRAP
;
1305 case EXCEPTION_DEBUG_EVENT
:
1306 OUTMSG2 (("gdbserver: kernel event EXCEPTION_DEBUG_EVENT "
1307 "for pid=%d tid=%x\n",
1308 (unsigned) current_event
.dwProcessId
,
1309 (unsigned) current_event
.dwThreadId
));
1310 handle_exception (ourstatus
);
1313 case OUTPUT_DEBUG_STRING_EVENT
:
1314 /* A message from the kernel (or Cygwin). */
1315 OUTMSG2 (("gdbserver: kernel event OUTPUT_DEBUG_STRING_EVENT "
1316 "for pid=%d tid=%x\n",
1317 (unsigned) current_event
.dwProcessId
,
1318 (unsigned) current_event
.dwThreadId
));
1319 handle_output_debug_string (ourstatus
);
1323 OUTMSG2 (("gdbserver: kernel event unknown "
1324 "for pid=%d tid=%x code=%ld\n",
1325 (unsigned) current_event
.dwProcessId
,
1326 (unsigned) current_event
.dwThreadId
,
1327 current_event
.dwDebugEventCode
));
1332 (struct thread_info
*) find_inferior_id (&all_threads
,
1333 current_event
.dwThreadId
);
1336 /* Wait for the inferior process to change state.
1337 STATUS will be filled in with a response code to send to GDB.
1338 Returns the signal which caused the process to stop. */
1339 static unsigned char
1340 win32_wait (char *status
)
1342 struct target_waitstatus our_status
;
1348 /* Check if GDB sent us an interrupt request. */
1349 check_remote_input_interrupt_request ();
1351 get_child_debug_event (&our_status
);
1353 switch (our_status
.kind
)
1355 case TARGET_WAITKIND_EXITED
:
1356 OUTMSG2 (("Child exited with retcode = %x\n",
1357 our_status
.value
.integer
));
1361 child_fetch_inferior_registers (-1);
1363 return our_status
.value
.integer
;
1364 case TARGET_WAITKIND_STOPPED
:
1365 case TARGET_WAITKIND_LOADED
:
1366 OUTMSG2 (("Child Stopped with signal = %d \n",
1367 our_status
.value
.sig
));
1371 child_fetch_inferior_registers (-1);
1373 if (our_status
.kind
== TARGET_WAITKIND_LOADED
1376 /* When gdb connects, we want to be stopped at the
1377 initial breakpoint, not in some dll load event. */
1378 child_continue (DBG_CONTINUE
, -1);
1382 return our_status
.value
.sig
;
1384 OUTMSG (("Ignoring unknown internal event, %d\n", our_status
.kind
));
1386 case TARGET_WAITKIND_SPURIOUS
:
1387 case TARGET_WAITKIND_EXECD
:
1388 /* do nothing, just continue */
1389 child_continue (DBG_CONTINUE
, -1);
1395 /* Fetch registers from the inferior process.
1396 If REGNO is -1, fetch all registers; otherwise, fetch at least REGNO. */
1398 win32_fetch_inferior_registers (int regno
)
1400 child_fetch_inferior_registers (regno
);
1403 /* Store registers to the inferior process.
1404 If REGNO is -1, store all registers; otherwise, store at least REGNO. */
1406 win32_store_inferior_registers (int regno
)
1408 child_store_inferior_registers (regno
);
1411 /* Read memory from the inferior process. This should generally be
1412 called through read_inferior_memory, which handles breakpoint shadowing.
1413 Read LEN bytes at MEMADDR into a buffer at MYADDR. */
1415 win32_read_inferior_memory (CORE_ADDR memaddr
, unsigned char *myaddr
, int len
)
1417 return child_xfer_memory (memaddr
, (char *) myaddr
, len
, 0, 0) != len
;
1420 /* Write memory to the inferior process. This should generally be
1421 called through write_inferior_memory, which handles breakpoint shadowing.
1422 Write LEN bytes from the buffer at MYADDR to MEMADDR.
1423 Returns 0 on success and errno on failure. */
1425 win32_write_inferior_memory (CORE_ADDR memaddr
, const unsigned char *myaddr
,
1428 return child_xfer_memory (memaddr
, (char *) myaddr
, len
, 1, 0) != len
;
1431 /* Send an interrupt request to the inferior process. */
1433 win32_request_interrupt (void)
1435 winapi_DebugBreakProcess DebugBreakProcess
;
1436 winapi_GenerateConsoleCtrlEvent GenerateConsoleCtrlEvent
;
1439 HMODULE dll
= GetModuleHandle (_T("COREDLL.DLL"));
1441 HMODULE dll
= GetModuleHandle (_T("KERNEL32.DLL"));
1444 GenerateConsoleCtrlEvent
= GETPROCADDRESS (dll
, GenerateConsoleCtrlEvent
);
1446 if (GenerateConsoleCtrlEvent
!= NULL
1447 && GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT
, current_process_id
))
1450 /* GenerateConsoleCtrlEvent can fail if process id being debugged is
1451 not a process group id.
1452 Fallback to XP/Vista 'DebugBreakProcess', which generates a
1453 breakpoint exception in the interior process. */
1455 DebugBreakProcess
= GETPROCADDRESS (dll
, DebugBreakProcess
);
1457 if (DebugBreakProcess
!= NULL
1458 && DebugBreakProcess (current_process_handle
))
1461 OUTMSG (("Could not interrupt process.\n"));
1465 win32_arch_string (void)
1467 return the_low_target
.arch_string
;
1470 static struct target_ops win32_target_ops
= {
1471 win32_create_inferior
,
1479 win32_fetch_inferior_registers
,
1480 win32_store_inferior_registers
,
1481 win32_read_inferior_memory
,
1482 win32_write_inferior_memory
,
1484 win32_request_interrupt
,
1495 /* Initialize the Win32 backend. */
1497 initialize_low (void)
1499 set_target_ops (&win32_target_ops
);
1500 if (the_low_target
.breakpoint
!= NULL
)
1501 set_breakpoint_data (the_low_target
.breakpoint
,
1502 the_low_target
.breakpoint_len
);