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
);
377 create_process (const char *program
, char *args
,
378 DWORD flags
, PROCESS_INFORMATION
*pi
)
383 wchar_t *p
, *wprogram
, *wargs
;
386 wprogram
= alloca ((strlen (program
) + 1) * sizeof (wchar_t));
387 mbstowcs (wprogram
, program
, strlen (program
) + 1);
389 for (p
= wprogram
; *p
; ++p
)
393 argslen
= strlen (args
);
394 wargs
= alloca ((argslen
+ 1) * sizeof (wchar_t));
395 mbstowcs (wargs
, args
, argslen
+ 1);
397 ret
= CreateProcessW (wprogram
, /* image name */
398 wargs
, /* command line */
399 NULL
, /* security, not supported */
400 NULL
, /* thread, not supported */
401 FALSE
, /* inherit handles, not supported */
402 flags
, /* start flags */
403 NULL
, /* environment, not supported */
404 NULL
, /* current directory, not supported */
405 NULL
, /* start info, not supported */
408 STARTUPINFOA si
= { sizeof (STARTUPINFOA
) };
410 ret
= CreateProcessA (program
, /* image name */
411 args
, /* command line */
414 TRUE
, /* inherit handles */
415 flags
, /* start flags */
416 NULL
, /* environment */
417 NULL
, /* current directory */
418 &si
, /* start info */
425 /* Start a new process.
426 PROGRAM is a path to the program to execute.
427 ARGS is a standard NULL-terminated array of arguments,
428 to be passed to the inferior as ``argv''.
429 Returns the new PID on success, -1 on failure. Registers the new
430 process with the process list. */
432 win32_create_inferior (char *program
, char **program_args
)
435 char real_path
[MAXPATHLEN
];
436 char *orig_path
, *new_path
, *path_ptr
;
443 PROCESS_INFORMATION pi
;
447 error ("No executable specified, specify executable to debug.\n");
449 flags
= DEBUG_PROCESS
| DEBUG_ONLY_THIS_PROCESS
;
453 path_ptr
= getenv ("PATH");
456 orig_path
= alloca (strlen (path_ptr
) + 1);
457 new_path
= alloca (cygwin_posix_to_win32_path_list_buf_size (path_ptr
));
458 strcpy (orig_path
, path_ptr
);
459 cygwin_posix_to_win32_path_list (path_ptr
, new_path
);
460 setenv ("PATH", new_path
, 1);
462 cygwin_conv_to_win32_path (program
, real_path
);
467 for (argc
= 1; program_args
[argc
]; argc
++)
468 argslen
+= strlen (program_args
[argc
]) + 1;
469 args
= alloca (argslen
);
471 for (argc
= 1; program_args
[argc
]; argc
++)
473 /* FIXME: Can we do better about quoting? How does Cygwin
476 strcat (args
, program_args
[argc
]);
478 OUTMSG2 (("Command line is \"%s\"\n", args
));
480 #ifdef CREATE_NEW_PROCESS_GROUP
481 flags
|= CREATE_NEW_PROCESS_GROUP
;
484 ret
= create_process (program
, args
, flags
, &pi
);
485 err
= GetLastError ();
486 if (!ret
&& err
== ERROR_FILE_NOT_FOUND
)
488 char *exename
= alloca (strlen (program
) + 5);
489 strcat (strcpy (exename
, program
), ".exe");
490 ret
= create_process (exename
, args
, flags
, &pi
);
491 err
= GetLastError ();
496 setenv ("PATH", orig_path
, 1);
501 error ("Error creating process \"%s%s\", (error %d): %s\n",
502 program
, args
, (int) err
, strwinerror (err
));
506 OUTMSG2 (("Process created: %s\n", (char *) args
));
510 /* On Windows CE this handle can't be closed. The OS reuses
511 it in the debug events, while the 9x/NT versions of Windows
512 probably use a DuplicateHandle'd one. */
513 CloseHandle (pi
.hThread
);
516 current_process_handle
= pi
.hProcess
;
517 current_process_id
= pi
.dwProcessId
;
519 do_initial_child_stuff (current_process_id
);
521 return current_process_id
;
524 /* Attach to a running process.
525 PID is the process ID to attach to, specified by the user
526 or a higher layer. */
528 win32_attach (unsigned long pid
)
530 winapi_DebugActiveProcessStop DebugActiveProcessStop
= NULL
;
531 winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit
= NULL
;
533 HMODULE dll
= GetModuleHandle (_T("COREDLL.DLL"));
535 HMODULE dll
= GetModuleHandle (_T("KERNEL32.DLL"));
537 DebugActiveProcessStop
= GETPROCADDRESS (dll
, DebugActiveProcessStop
);
538 DebugSetProcessKillOnExit
= GETPROCADDRESS (dll
, DebugSetProcessKillOnExit
);
540 if (DebugActiveProcess (pid
))
542 if (DebugSetProcessKillOnExit
!= NULL
)
543 DebugSetProcessKillOnExit (FALSE
);
545 current_process_handle
= OpenProcess (PROCESS_ALL_ACCESS
, FALSE
, pid
);
547 if (current_process_handle
!= NULL
)
549 current_process_id
= pid
;
550 do_initial_child_stuff (pid
);
553 if (DebugActiveProcessStop
!= NULL
)
554 DebugActiveProcessStop (current_process_id
);
557 error ("Attach to process failed.");
560 /* Handle OUTPUT_DEBUG_STRING_EVENT from child process. */
562 handle_output_debug_string (struct target_waitstatus
*ourstatus
)
564 #define READ_BUFFER_LEN 1024
566 char s
[READ_BUFFER_LEN
+ 1] = { 0 };
567 DWORD nbytes
= current_event
.u
.DebugString
.nDebugStringLength
;
572 if (nbytes
> READ_BUFFER_LEN
)
573 nbytes
= READ_BUFFER_LEN
;
575 addr
= (CORE_ADDR
) (size_t) current_event
.u
.DebugString
.lpDebugStringData
;
577 if (current_event
.u
.DebugString
.fUnicode
)
579 /* The event tells us how many bytes, not chars, even
581 WCHAR buffer
[(READ_BUFFER_LEN
+ 1) / sizeof (WCHAR
)] = { 0 };
582 if (read_inferior_memory (addr
, (unsigned char *) buffer
, nbytes
) != 0)
584 wcstombs (s
, buffer
, (nbytes
+ 1) / sizeof (WCHAR
));
588 if (read_inferior_memory (addr
, (unsigned char *) s
, nbytes
) != 0)
592 if (strncmp (s
, "cYg", 3) != 0)
602 #undef READ_BUFFER_LEN
605 /* Kill all inferiors. */
609 win32_thread_info
*current_thread
;
611 if (current_process_handle
== NULL
)
614 TerminateProcess (current_process_handle
, 0);
617 if (!child_continue (DBG_CONTINUE
, -1))
619 if (!WaitForDebugEvent (¤t_event
, INFINITE
))
621 if (current_event
.dwDebugEventCode
== EXIT_PROCESS_DEBUG_EVENT
)
623 else if (current_event
.dwDebugEventCode
== OUTPUT_DEBUG_STRING_EVENT
)
625 struct target_waitstatus our_status
= { 0 };
626 handle_output_debug_string (&our_status
);
630 CloseHandle (current_process_handle
);
632 current_thread
= inferior_target_data (current_inferior
);
633 if (current_thread
&& current_thread
->h
)
635 /* This may fail in an attached process, so don't check. */
636 (void) CloseHandle (current_thread
->h
);
640 /* Detach from all inferiors. */
646 winapi_DebugActiveProcessStop DebugActiveProcessStop
= NULL
;
647 winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit
= NULL
;
649 HMODULE dll
= GetModuleHandle (_T("COREDLL.DLL"));
651 HMODULE dll
= GetModuleHandle (_T("KERNEL32.DLL"));
653 DebugActiveProcessStop
= GETPROCADDRESS (dll
, DebugActiveProcessStop
);
654 DebugSetProcessKillOnExit
= GETPROCADDRESS (dll
, DebugSetProcessKillOnExit
);
656 if (DebugSetProcessKillOnExit
== NULL
657 || DebugActiveProcessStop
== NULL
)
660 /* We need a new handle, since DebugActiveProcessStop
661 closes all the ones that came through the events. */
662 if ((h
= OpenProcess (PROCESS_ALL_ACCESS
,
664 current_process_id
)) == NULL
)
666 /* The process died. */
671 struct thread_resume resume
;
675 resume
.leave_stopped
= 0;
676 win32_resume (&resume
);
679 if (!DebugActiveProcessStop (current_process_id
))
684 DebugSetProcessKillOnExit (FALSE
);
686 current_process_handle
= h
;
690 /* Wait for inferiors to end. */
694 if (current_process_id
== 0
695 || current_process_handle
== NULL
)
698 WaitForSingleObject (current_process_handle
, INFINITE
);
699 CloseHandle (current_process_handle
);
701 current_process_handle
= NULL
;
702 current_process_id
= 0;
705 /* Return 1 iff the thread with thread ID TID is alive. */
707 win32_thread_alive (unsigned long tid
)
711 /* Our thread list is reliable; don't bother to poll target
713 if (find_inferior_id (&all_threads
, tid
) != NULL
)
720 /* Resume the inferior process. RESUME_INFO describes how we want
723 win32_resume (struct thread_resume
*resume_info
)
726 enum target_signal sig
;
728 win32_thread_info
*th
;
729 DWORD continue_status
= DBG_CONTINUE
;
731 /* This handles the very limited set of resume packets that GDB can
732 currently produce. */
734 if (resume_info
[0].thread
== -1)
736 else if (resume_info
[1].thread
== -1 && !resume_info
[1].leave_stopped
)
739 /* Yes, we're ignoring resume_info[0].thread. It'd be tricky to make
740 the Windows resume code do the right thing for thread switching. */
741 tid
= current_event
.dwThreadId
;
743 if (resume_info
[0].thread
!= -1)
745 sig
= resume_info
[0].sig
;
746 step
= resume_info
[0].step
;
754 if (sig
!= TARGET_SIGNAL_0
)
756 if (current_event
.dwDebugEventCode
!= EXCEPTION_DEBUG_EVENT
)
758 OUTMSG (("Cannot continue with signal %d here.\n", sig
));
760 else if (sig
== last_sig
)
761 continue_status
= DBG_EXCEPTION_NOT_HANDLED
;
763 OUTMSG (("Can only continue with recieved signal %d.\n", last_sig
));
766 last_sig
= TARGET_SIGNAL_0
;
768 /* Get context for the currently selected thread. */
769 th
= thread_rec (current_event
.dwThreadId
, FALSE
);
772 if (th
->context
.ContextFlags
)
774 /* Move register values from the inferior into the thread
775 context structure. */
776 regcache_invalidate ();
780 if (the_low_target
.single_step
!= NULL
)
781 (*the_low_target
.single_step
) (th
);
783 error ("Single stepping is not supported "
784 "in this configuration.\n");
787 (*the_low_target
.set_thread_context
) (th
, ¤t_event
);
788 th
->context
.ContextFlags
= 0;
792 /* Allow continuing with the same signal that interrupted us.
793 Otherwise complain. */
795 child_continue (continue_status
, tid
);
799 win32_add_one_solib (const char *name
, CORE_ADDR load_addr
)
801 char buf
[MAX_PATH
+ 1];
802 char buf2
[MAX_PATH
+ 1];
805 WIN32_FIND_DATA w32_fd
;
806 WCHAR wname
[MAX_PATH
+ 1];
807 mbstowcs (wname
, name
, MAX_PATH
);
808 HANDLE h
= FindFirstFile (wname
, &w32_fd
);
810 WIN32_FIND_DATAA w32_fd
;
811 HANDLE h
= FindFirstFileA (name
, &w32_fd
);
814 if (h
== INVALID_HANDLE_VALUE
)
822 char cwd
[MAX_PATH
+ 1];
824 if (GetCurrentDirectoryA (MAX_PATH
+ 1, cwd
))
826 p
= strrchr (buf
, '\\');
829 SetCurrentDirectoryA (buf
);
830 GetFullPathNameA (w32_fd
.cFileName
, MAX_PATH
, buf
, &p
);
831 SetCurrentDirectoryA (cwd
);
838 cygwin_conv_to_posix_path (buf
, buf2
);
843 loaded_dll (buf2
, load_addr
);
847 get_image_name (HANDLE h
, void *address
, int unicode
)
849 static char buf
[(2 * MAX_PATH
) + 1];
850 DWORD size
= unicode
? sizeof (WCHAR
) : sizeof (char);
856 /* Attempt to read the name of the dll that was detected.
857 This is documented to work only when actively debugging
858 a program. It will not work for attached processes. */
863 /* Windows CE reports the address of the image name,
864 instead of an address of a pointer into the image name. */
865 address_ptr
= address
;
867 /* See if we could read the address of a string, and that the
868 address isn't null. */
869 if (!ReadProcessMemory (h
, address
, &address_ptr
,
870 sizeof (address_ptr
), &done
)
871 || done
!= sizeof (address_ptr
)
876 /* Find the length of the string */
877 while (ReadProcessMemory (h
, address_ptr
+ len
++ * size
, &b
, size
, &done
)
878 && (b
[0] != 0 || b
[size
- 1] != 0) && done
== size
)
882 ReadProcessMemory (h
, address_ptr
, buf
, len
, &done
);
885 WCHAR
*unicode_address
= (WCHAR
*) alloca (len
* sizeof (WCHAR
));
886 ReadProcessMemory (h
, address_ptr
, unicode_address
, len
* sizeof (WCHAR
),
889 WideCharToMultiByte (CP_ACP
, 0, unicode_address
, len
, buf
, len
, 0, 0);
895 typedef BOOL (WINAPI
*winapi_EnumProcessModules
) (HANDLE
, HMODULE
*,
897 typedef BOOL (WINAPI
*winapi_GetModuleInformation
) (HANDLE
, HMODULE
,
898 LPMODULEINFO
, DWORD
);
899 typedef DWORD (WINAPI
*winapi_GetModuleFileNameExA
) (HANDLE
, HMODULE
,
902 static winapi_EnumProcessModules win32_EnumProcessModules
;
903 static winapi_GetModuleInformation win32_GetModuleInformation
;
904 static winapi_GetModuleFileNameExA win32_GetModuleFileNameExA
;
909 static int psapi_loaded
= 0;
910 static HMODULE dll
= NULL
;
915 dll
= LoadLibrary (TEXT("psapi.dll"));
918 win32_EnumProcessModules
=
919 GETPROCADDRESS (dll
, EnumProcessModules
);
920 win32_GetModuleInformation
=
921 GETPROCADDRESS (dll
, GetModuleInformation
);
922 win32_GetModuleFileNameExA
=
923 GETPROCADDRESS (dll
, GetModuleFileNameExA
);
926 return (win32_EnumProcessModules
!= NULL
927 && win32_GetModuleInformation
!= NULL
928 && win32_GetModuleFileNameExA
!= NULL
);
932 psapi_get_dll_name (DWORD BaseAddress
, char *dll_name_ret
)
938 HMODULE
*DllHandle
= dh_buf
;
946 ok
= (*win32_EnumProcessModules
) (current_process_handle
,
951 if (!ok
|| !cbNeeded
)
954 DllHandle
= (HMODULE
*) alloca (cbNeeded
);
958 ok
= (*win32_EnumProcessModules
) (current_process_handle
,
965 for (i
= 0; i
< ((size_t) cbNeeded
/ sizeof (HMODULE
)); i
++)
967 if (!(*win32_GetModuleInformation
) (current_process_handle
,
972 DWORD err
= GetLastError ();
973 error ("Can't get module info: (error %d): %s\n",
974 (int) err
, strwinerror (err
));
977 if ((DWORD
) (mi
.lpBaseOfDll
) == BaseAddress
)
979 len
= (*win32_GetModuleFileNameExA
) (current_process_handle
,
985 DWORD err
= GetLastError ();
986 error ("Error getting dll name: (error %d): %s\n",
987 (int) err
, strwinerror (err
));
994 dll_name_ret
[0] = '\0';
998 typedef HANDLE (WINAPI
*winapi_CreateToolhelp32Snapshot
) (DWORD
, DWORD
);
999 typedef BOOL (WINAPI
*winapi_Module32First
) (HANDLE
, LPMODULEENTRY32
);
1000 typedef BOOL (WINAPI
*winapi_Module32Next
) (HANDLE
, LPMODULEENTRY32
);
1002 static winapi_CreateToolhelp32Snapshot win32_CreateToolhelp32Snapshot
;
1003 static winapi_Module32First win32_Module32First
;
1004 static winapi_Module32Next win32_Module32Next
;
1006 typedef BOOL (WINAPI
*winapi_CloseToolhelp32Snapshot
) (HANDLE
);
1007 static winapi_CloseToolhelp32Snapshot win32_CloseToolhelp32Snapshot
;
1011 load_toolhelp (void)
1013 static int toolhelp_loaded
= 0;
1014 static HMODULE dll
= NULL
;
1016 if (!toolhelp_loaded
)
1018 toolhelp_loaded
= 1;
1020 dll
= GetModuleHandle (_T("KERNEL32.DLL"));
1022 dll
= LoadLibrary (L
"TOOLHELP.DLL");
1027 win32_CreateToolhelp32Snapshot
=
1028 GETPROCADDRESS (dll
, CreateToolhelp32Snapshot
);
1029 win32_Module32First
= GETPROCADDRESS (dll
, Module32First
);
1030 win32_Module32Next
= GETPROCADDRESS (dll
, Module32Next
);
1032 win32_CloseToolhelp32Snapshot
=
1033 GETPROCADDRESS (dll
, CloseToolhelp32Snapshot
);
1037 return (win32_CreateToolhelp32Snapshot
!= NULL
1038 && win32_Module32First
!= NULL
1039 && win32_Module32Next
!= NULL
1041 && win32_CloseToolhelp32Snapshot
!= NULL
1047 toolhelp_get_dll_name (DWORD BaseAddress
, char *dll_name_ret
)
1049 HANDLE snapshot_module
;
1050 MODULEENTRY32 modEntry
= { sizeof (MODULEENTRY32
) };
1053 if (!load_toolhelp ())
1056 snapshot_module
= win32_CreateToolhelp32Snapshot (TH32CS_SNAPMODULE
,
1057 current_event
.dwProcessId
);
1058 if (snapshot_module
== INVALID_HANDLE_VALUE
)
1061 /* Ignore the first module, which is the exe. */
1062 if (win32_Module32First (snapshot_module
, &modEntry
))
1063 while (win32_Module32Next (snapshot_module
, &modEntry
))
1064 if ((DWORD
) modEntry
.modBaseAddr
== BaseAddress
)
1067 wcstombs (dll_name_ret
, modEntry
.szExePath
, MAX_PATH
+ 1);
1069 strcpy (dll_name_ret
, modEntry
.szExePath
);
1076 win32_CloseToolhelp32Snapshot (snapshot_module
);
1078 CloseHandle (snapshot_module
);
1084 handle_load_dll (void)
1086 LOAD_DLL_DEBUG_INFO
*event
= ¤t_event
.u
.LoadDll
;
1087 char dll_buf
[MAX_PATH
+ 1];
1088 char *dll_name
= NULL
;
1091 dll_buf
[0] = dll_buf
[sizeof (dll_buf
) - 1] = '\0';
1093 /* Windows does not report the image name of the dlls in the debug
1094 event on attaches. We resort to iterating over the list of
1095 loaded dlls looking for a match by image base. */
1096 if (!psapi_get_dll_name ((DWORD
) event
->lpBaseOfDll
, dll_buf
))
1098 if (!server_waiting
)
1099 /* On some versions of Windows and Windows CE, we can't create
1100 toolhelp snapshots while the inferior is stopped in a
1101 LOAD_DLL_DEBUG_EVENT due to a dll load, but we can while
1102 Windows is reporting the already loaded dlls. */
1103 toolhelp_get_dll_name ((DWORD
) event
->lpBaseOfDll
, dll_buf
);
1108 if (*dll_name
== '\0')
1109 dll_name
= get_image_name (current_process_handle
,
1110 event
->lpImageName
, event
->fUnicode
);
1114 /* The symbols in a dll are offset by 0x1000, which is the
1115 the offset from 0 of the first byte in an image - because
1116 of the file header and the section alignment. */
1118 load_addr
= (DWORD
) event
->lpBaseOfDll
+ 0x1000;
1119 win32_add_one_solib (dll_name
, load_addr
);
1123 handle_unload_dll (void)
1125 CORE_ADDR load_addr
=
1126 (CORE_ADDR
) (DWORD
) current_event
.u
.UnloadDll
.lpBaseOfDll
;
1127 load_addr
+= 0x1000;
1128 unloaded_dll (NULL
, load_addr
);
1132 handle_exception (struct target_waitstatus
*ourstatus
)
1134 DWORD code
= current_event
.u
.Exception
.ExceptionRecord
.ExceptionCode
;
1136 ourstatus
->kind
= TARGET_WAITKIND_STOPPED
;
1140 case EXCEPTION_ACCESS_VIOLATION
:
1141 OUTMSG2 (("EXCEPTION_ACCESS_VIOLATION"));
1142 ourstatus
->value
.sig
= TARGET_SIGNAL_SEGV
;
1144 case STATUS_STACK_OVERFLOW
:
1145 OUTMSG2 (("STATUS_STACK_OVERFLOW"));
1146 ourstatus
->value
.sig
= TARGET_SIGNAL_SEGV
;
1148 case STATUS_FLOAT_DENORMAL_OPERAND
:
1149 OUTMSG2 (("STATUS_FLOAT_DENORMAL_OPERAND"));
1150 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1152 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED
:
1153 OUTMSG2 (("EXCEPTION_ARRAY_BOUNDS_EXCEEDED"));
1154 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1156 case STATUS_FLOAT_INEXACT_RESULT
:
1157 OUTMSG2 (("STATUS_FLOAT_INEXACT_RESULT"));
1158 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1160 case STATUS_FLOAT_INVALID_OPERATION
:
1161 OUTMSG2 (("STATUS_FLOAT_INVALID_OPERATION"));
1162 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1164 case STATUS_FLOAT_OVERFLOW
:
1165 OUTMSG2 (("STATUS_FLOAT_OVERFLOW"));
1166 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1168 case STATUS_FLOAT_STACK_CHECK
:
1169 OUTMSG2 (("STATUS_FLOAT_STACK_CHECK"));
1170 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1172 case STATUS_FLOAT_UNDERFLOW
:
1173 OUTMSG2 (("STATUS_FLOAT_UNDERFLOW"));
1174 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1176 case STATUS_FLOAT_DIVIDE_BY_ZERO
:
1177 OUTMSG2 (("STATUS_FLOAT_DIVIDE_BY_ZERO"));
1178 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1180 case STATUS_INTEGER_DIVIDE_BY_ZERO
:
1181 OUTMSG2 (("STATUS_INTEGER_DIVIDE_BY_ZERO"));
1182 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1184 case STATUS_INTEGER_OVERFLOW
:
1185 OUTMSG2 (("STATUS_INTEGER_OVERFLOW"));
1186 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1188 case EXCEPTION_BREAKPOINT
:
1189 OUTMSG2 (("EXCEPTION_BREAKPOINT"));
1190 ourstatus
->value
.sig
= TARGET_SIGNAL_TRAP
;
1192 /* Remove the initial breakpoint. */
1193 check_breakpoints ((CORE_ADDR
) (long) current_event
1194 .u
.Exception
.ExceptionRecord
.ExceptionAddress
);
1198 OUTMSG2 (("DBG_CONTROL_C"));
1199 ourstatus
->value
.sig
= TARGET_SIGNAL_INT
;
1201 case DBG_CONTROL_BREAK
:
1202 OUTMSG2 (("DBG_CONTROL_BREAK"));
1203 ourstatus
->value
.sig
= TARGET_SIGNAL_INT
;
1205 case EXCEPTION_SINGLE_STEP
:
1206 OUTMSG2 (("EXCEPTION_SINGLE_STEP"));
1207 ourstatus
->value
.sig
= TARGET_SIGNAL_TRAP
;
1209 case EXCEPTION_ILLEGAL_INSTRUCTION
:
1210 OUTMSG2 (("EXCEPTION_ILLEGAL_INSTRUCTION"));
1211 ourstatus
->value
.sig
= TARGET_SIGNAL_ILL
;
1213 case EXCEPTION_PRIV_INSTRUCTION
:
1214 OUTMSG2 (("EXCEPTION_PRIV_INSTRUCTION"));
1215 ourstatus
->value
.sig
= TARGET_SIGNAL_ILL
;
1217 case EXCEPTION_NONCONTINUABLE_EXCEPTION
:
1218 OUTMSG2 (("EXCEPTION_NONCONTINUABLE_EXCEPTION"));
1219 ourstatus
->value
.sig
= TARGET_SIGNAL_ILL
;
1222 if (current_event
.u
.Exception
.dwFirstChance
)
1224 ourstatus
->kind
= TARGET_WAITKIND_SPURIOUS
;
1227 OUTMSG2 (("gdbserver: unknown target exception 0x%08lx at 0x%08lx",
1228 current_event
.u
.Exception
.ExceptionRecord
.ExceptionCode
,
1229 (DWORD
) current_event
.u
.Exception
.ExceptionRecord
.
1231 ourstatus
->value
.sig
= TARGET_SIGNAL_UNKNOWN
;
1235 last_sig
= ourstatus
->value
.sig
;
1238 /* Get the next event from the child. */
1240 get_child_debug_event (struct target_waitstatus
*ourstatus
)
1244 last_sig
= TARGET_SIGNAL_0
;
1245 ourstatus
->kind
= TARGET_WAITKIND_SPURIOUS
;
1247 /* Keep the wait time low enough for confortable remote interruption,
1248 but high enough so gdbserver doesn't become a bottleneck. */
1249 if (!(debug_event
= WaitForDebugEvent (¤t_event
, 250)))
1253 (struct thread_info
*) find_inferior_id (&all_threads
,
1254 current_event
.dwThreadId
);
1256 switch (current_event
.dwDebugEventCode
)
1258 case CREATE_THREAD_DEBUG_EVENT
:
1259 OUTMSG2 (("gdbserver: kernel event CREATE_THREAD_DEBUG_EVENT "
1260 "for pid=%d tid=%x)\n",
1261 (unsigned) current_event
.dwProcessId
,
1262 (unsigned) current_event
.dwThreadId
));
1264 /* Record the existence of this thread. */
1265 child_add_thread (current_event
.dwThreadId
,
1266 current_event
.u
.CreateThread
.hThread
);
1269 case EXIT_THREAD_DEBUG_EVENT
:
1270 OUTMSG2 (("gdbserver: kernel event EXIT_THREAD_DEBUG_EVENT "
1271 "for pid=%d tid=%x\n",
1272 (unsigned) current_event
.dwProcessId
,
1273 (unsigned) current_event
.dwThreadId
));
1274 child_delete_thread (current_event
.dwThreadId
);
1277 case CREATE_PROCESS_DEBUG_EVENT
:
1278 OUTMSG2 (("gdbserver: kernel event CREATE_PROCESS_DEBUG_EVENT "
1279 "for pid=%d tid=%x\n",
1280 (unsigned) current_event
.dwProcessId
,
1281 (unsigned) current_event
.dwThreadId
));
1282 CloseHandle (current_event
.u
.CreateProcessInfo
.hFile
);
1284 current_process_handle
= current_event
.u
.CreateProcessInfo
.hProcess
;
1285 main_thread_id
= current_event
.dwThreadId
;
1287 ourstatus
->kind
= TARGET_WAITKIND_EXECD
;
1288 ourstatus
->value
.execd_pathname
= "Main executable";
1290 /* Add the main thread. */
1291 child_add_thread (main_thread_id
,
1292 current_event
.u
.CreateProcessInfo
.hThread
);
1294 ourstatus
->value
.related_pid
= current_event
.dwThreadId
;
1296 /* Windows CE doesn't set the initial breakpoint automatically
1297 like the desktop versions of Windows do. We add it explicitly
1298 here. It will be removed as soon as it is hit. */
1299 set_breakpoint_at ((CORE_ADDR
) (long) current_event
.u
1300 .CreateProcessInfo
.lpStartAddress
,
1301 delete_breakpoint_at
);
1305 case EXIT_PROCESS_DEBUG_EVENT
:
1306 OUTMSG2 (("gdbserver: kernel event EXIT_PROCESS_DEBUG_EVENT "
1307 "for pid=%d tid=%x\n",
1308 (unsigned) current_event
.dwProcessId
,
1309 (unsigned) current_event
.dwThreadId
));
1310 ourstatus
->kind
= TARGET_WAITKIND_EXITED
;
1311 ourstatus
->value
.integer
= current_event
.u
.ExitProcess
.dwExitCode
;
1312 CloseHandle (current_process_handle
);
1313 current_process_handle
= NULL
;
1316 case LOAD_DLL_DEBUG_EVENT
:
1317 OUTMSG2 (("gdbserver: kernel event LOAD_DLL_DEBUG_EVENT "
1318 "for pid=%d tid=%x\n",
1319 (unsigned) current_event
.dwProcessId
,
1320 (unsigned) current_event
.dwThreadId
));
1321 CloseHandle (current_event
.u
.LoadDll
.hFile
);
1324 ourstatus
->kind
= TARGET_WAITKIND_LOADED
;
1325 ourstatus
->value
.sig
= TARGET_SIGNAL_TRAP
;
1328 case UNLOAD_DLL_DEBUG_EVENT
:
1329 OUTMSG2 (("gdbserver: kernel event UNLOAD_DLL_DEBUG_EVENT "
1330 "for pid=%d tid=%x\n",
1331 (unsigned) current_event
.dwProcessId
,
1332 (unsigned) current_event
.dwThreadId
));
1333 handle_unload_dll ();
1334 ourstatus
->kind
= TARGET_WAITKIND_LOADED
;
1335 ourstatus
->value
.sig
= TARGET_SIGNAL_TRAP
;
1338 case EXCEPTION_DEBUG_EVENT
:
1339 OUTMSG2 (("gdbserver: kernel event EXCEPTION_DEBUG_EVENT "
1340 "for pid=%d tid=%x\n",
1341 (unsigned) current_event
.dwProcessId
,
1342 (unsigned) current_event
.dwThreadId
));
1343 handle_exception (ourstatus
);
1346 case OUTPUT_DEBUG_STRING_EVENT
:
1347 /* A message from the kernel (or Cygwin). */
1348 OUTMSG2 (("gdbserver: kernel event OUTPUT_DEBUG_STRING_EVENT "
1349 "for pid=%d tid=%x\n",
1350 (unsigned) current_event
.dwProcessId
,
1351 (unsigned) current_event
.dwThreadId
));
1352 handle_output_debug_string (ourstatus
);
1356 OUTMSG2 (("gdbserver: kernel event unknown "
1357 "for pid=%d tid=%x code=%ld\n",
1358 (unsigned) current_event
.dwProcessId
,
1359 (unsigned) current_event
.dwThreadId
,
1360 current_event
.dwDebugEventCode
));
1365 (struct thread_info
*) find_inferior_id (&all_threads
,
1366 current_event
.dwThreadId
);
1369 /* Wait for the inferior process to change state.
1370 STATUS will be filled in with a response code to send to GDB.
1371 Returns the signal which caused the process to stop. */
1372 static unsigned char
1373 win32_wait (char *status
)
1375 struct target_waitstatus our_status
;
1381 /* Check if GDB sent us an interrupt request. */
1382 check_remote_input_interrupt_request ();
1384 get_child_debug_event (&our_status
);
1386 switch (our_status
.kind
)
1388 case TARGET_WAITKIND_EXITED
:
1389 OUTMSG2 (("Child exited with retcode = %x\n",
1390 our_status
.value
.integer
));
1394 child_fetch_inferior_registers (-1);
1396 return our_status
.value
.integer
;
1397 case TARGET_WAITKIND_STOPPED
:
1398 case TARGET_WAITKIND_LOADED
:
1399 OUTMSG2 (("Child Stopped with signal = %d \n",
1400 our_status
.value
.sig
));
1404 child_fetch_inferior_registers (-1);
1406 if (our_status
.kind
== TARGET_WAITKIND_LOADED
1409 /* When gdb connects, we want to be stopped at the
1410 initial breakpoint, not in some dll load event. */
1411 child_continue (DBG_CONTINUE
, -1);
1415 return our_status
.value
.sig
;
1417 OUTMSG (("Ignoring unknown internal event, %d\n", our_status
.kind
));
1419 case TARGET_WAITKIND_SPURIOUS
:
1420 case TARGET_WAITKIND_EXECD
:
1421 /* do nothing, just continue */
1422 child_continue (DBG_CONTINUE
, -1);
1428 /* Fetch registers from the inferior process.
1429 If REGNO is -1, fetch all registers; otherwise, fetch at least REGNO. */
1431 win32_fetch_inferior_registers (int regno
)
1433 child_fetch_inferior_registers (regno
);
1436 /* Store registers to the inferior process.
1437 If REGNO is -1, store all registers; otherwise, store at least REGNO. */
1439 win32_store_inferior_registers (int regno
)
1441 child_store_inferior_registers (regno
);
1444 /* Read memory from the inferior process. This should generally be
1445 called through read_inferior_memory, which handles breakpoint shadowing.
1446 Read LEN bytes at MEMADDR into a buffer at MYADDR. */
1448 win32_read_inferior_memory (CORE_ADDR memaddr
, unsigned char *myaddr
, int len
)
1450 return child_xfer_memory (memaddr
, (char *) myaddr
, len
, 0, 0) != len
;
1453 /* Write memory to the inferior process. This should generally be
1454 called through write_inferior_memory, which handles breakpoint shadowing.
1455 Write LEN bytes from the buffer at MYADDR to MEMADDR.
1456 Returns 0 on success and errno on failure. */
1458 win32_write_inferior_memory (CORE_ADDR memaddr
, const unsigned char *myaddr
,
1461 return child_xfer_memory (memaddr
, (char *) myaddr
, len
, 1, 0) != len
;
1464 /* Send an interrupt request to the inferior process. */
1466 win32_request_interrupt (void)
1468 winapi_DebugBreakProcess DebugBreakProcess
;
1469 winapi_GenerateConsoleCtrlEvent GenerateConsoleCtrlEvent
;
1472 HMODULE dll
= GetModuleHandle (_T("COREDLL.DLL"));
1474 HMODULE dll
= GetModuleHandle (_T("KERNEL32.DLL"));
1477 GenerateConsoleCtrlEvent
= GETPROCADDRESS (dll
, GenerateConsoleCtrlEvent
);
1479 if (GenerateConsoleCtrlEvent
!= NULL
1480 && GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT
, current_process_id
))
1483 /* GenerateConsoleCtrlEvent can fail if process id being debugged is
1484 not a process group id.
1485 Fallback to XP/Vista 'DebugBreakProcess', which generates a
1486 breakpoint exception in the interior process. */
1488 DebugBreakProcess
= GETPROCADDRESS (dll
, DebugBreakProcess
);
1490 if (DebugBreakProcess
!= NULL
1491 && DebugBreakProcess (current_process_handle
))
1494 OUTMSG (("Could not interrupt process.\n"));
1498 win32_arch_string (void)
1500 return the_low_target
.arch_string
;
1503 static struct target_ops win32_target_ops
= {
1504 win32_create_inferior
,
1512 win32_fetch_inferior_registers
,
1513 win32_store_inferior_registers
,
1514 win32_read_inferior_memory
,
1515 win32_write_inferior_memory
,
1517 win32_request_interrupt
,
1528 /* Initialize the Win32 backend. */
1530 initialize_low (void)
1532 set_target_ops (&win32_target_ops
);
1533 if (the_low_target
.breakpoint
!= NULL
)
1534 set_breakpoint_data (the_low_target
.breakpoint
,
1535 the_low_target
.breakpoint_len
);