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 /* Non zero if an interrupt request is to be satisfied by suspending
77 static int soft_interrupt_requested
= 0;
79 /* Non zero if the inferior is stopped in a simulated breakpoint done
80 by suspending all the threads. */
81 static int faked_breakpoint
= 0;
83 #define NUM_REGS (the_low_target.num_regs)
85 typedef BOOL
WINAPI (*winapi_DebugActiveProcessStop
) (DWORD dwProcessId
);
86 typedef BOOL
WINAPI (*winapi_DebugSetProcessKillOnExit
) (BOOL KillOnExit
);
87 typedef BOOL
WINAPI (*winapi_DebugBreakProcess
) (HANDLE
);
88 typedef BOOL
WINAPI (*winapi_GenerateConsoleCtrlEvent
) (DWORD
, DWORD
);
90 static DWORD main_thread_id
= 0;
92 static void win32_resume (struct thread_resume
*resume_info
);
94 /* Get the thread ID from the current selected inferior (the current
97 current_inferior_tid (void)
99 win32_thread_info
*th
= inferior_target_data (current_inferior
);
103 /* Get the thread context of the thread associated with TH. */
106 win32_get_thread_context (win32_thread_info
*th
)
108 memset (&th
->context
, 0, sizeof (CONTEXT
));
109 (*the_low_target
.get_thread_context
) (th
, ¤t_event
);
111 memcpy (&th
->base_context
, &th
->context
, sizeof (CONTEXT
));
115 /* Set the thread context of the thread associated with TH. */
118 win32_set_thread_context (win32_thread_info
*th
)
121 /* Calling SuspendThread on a thread that is running kernel code
122 will report that the suspending was successful, but in fact, that
123 will often not be true. In those cases, the context returned by
124 GetThreadContext will not be correct by the time the thread
125 stops, hence we can't set that context back into the thread when
126 resuming - it will most likelly crash the inferior.
127 Unfortunately, there is no way to know when the thread will
128 really stop. To work around it, we'll only write the context
129 back to the thread when either the user or GDB explicitly change
130 it between stopping and resuming. */
131 if (memcmp (&th
->context
, &th
->base_context
, sizeof (CONTEXT
)) != 0)
133 (*the_low_target
.set_thread_context
) (th
, ¤t_event
);
136 /* Find a thread record given a thread id. If GET_CONTEXT is set then
137 also retrieve the context for this thread. */
138 static win32_thread_info
*
139 thread_rec (DWORD id
, int get_context
)
141 struct thread_info
*thread
;
142 win32_thread_info
*th
;
144 thread
= (struct thread_info
*) find_inferior_id (&all_threads
, id
);
148 th
= inferior_target_data (thread
);
149 if (get_context
&& th
->context
.ContextFlags
== 0)
153 if (SuspendThread (th
->h
) == (DWORD
) -1)
155 DWORD err
= GetLastError ();
156 OUTMSG (("warning: SuspendThread failed in thread_rec, "
157 "(error %d): %s\n", (int) err
, strwinerror (err
)));
163 win32_get_thread_context (th
);
169 /* Add a thread to the thread list. */
170 static win32_thread_info
*
171 child_add_thread (DWORD tid
, HANDLE h
)
173 win32_thread_info
*th
;
175 if ((th
= thread_rec (tid
, FALSE
)))
178 th
= calloc (1, sizeof (*th
));
182 add_thread (tid
, th
, (unsigned int) tid
);
183 set_inferior_regcache_data ((struct thread_info
*)
184 find_inferior_id (&all_threads
, tid
),
185 new_register_cache ());
187 if (the_low_target
.thread_added
!= NULL
)
188 (*the_low_target
.thread_added
) (th
);
193 /* Delete a thread from the list of threads. */
195 delete_thread_info (struct inferior_list_entry
*thread
)
197 win32_thread_info
*th
= inferior_target_data ((struct thread_info
*) thread
);
199 remove_thread ((struct thread_info
*) thread
);
204 /* Delete a thread from the list of threads. */
206 child_delete_thread (DWORD id
)
208 struct inferior_list_entry
*thread
;
210 /* If the last thread is exiting, just return. */
211 if (all_threads
.head
== all_threads
.tail
)
214 thread
= find_inferior_id (&all_threads
, id
);
218 delete_thread_info (thread
);
221 /* Transfer memory from/to the debugged process. */
223 child_xfer_memory (CORE_ADDR memaddr
, char *our
, int len
,
224 int write
, struct target_ops
*target
)
227 long addr
= (long) memaddr
;
231 WriteProcessMemory (current_process_handle
, (LPVOID
) addr
,
232 (LPCVOID
) our
, len
, &done
);
233 FlushInstructionCache (current_process_handle
, (LPCVOID
) addr
, len
);
237 ReadProcessMemory (current_process_handle
, (LPCVOID
) addr
, (LPVOID
) our
,
243 /* Generally, what has the program done? */
246 /* The program has exited. The exit status is in value.integer. */
247 TARGET_WAITKIND_EXITED
,
249 /* The program has stopped with a signal. Which signal is in
251 TARGET_WAITKIND_STOPPED
,
253 /* The program is letting us know that it dynamically loaded
254 or unloaded something. */
255 TARGET_WAITKIND_LOADED
,
257 /* The program has exec'ed a new executable file. The new file's
258 pathname is pointed to by value.execd_pathname. */
259 TARGET_WAITKIND_EXECD
,
261 /* Nothing interesting happened, but we stopped anyway. We take the
262 chance to check if GDB requested an interrupt. */
263 TARGET_WAITKIND_SPURIOUS
,
266 struct target_waitstatus
268 enum target_waitkind kind
;
270 /* Forked child pid, execd pathname, exit status or signal number. */
274 enum target_signal sig
;
276 char *execd_pathname
;
282 /* Clear out any old thread list and reinitialize it to a pristine
285 child_init_thread_list (void)
287 for_each_inferior (&all_threads
, delete_thread_info
);
291 do_initial_child_stuff (DWORD pid
)
293 last_sig
= TARGET_SIGNAL_0
;
295 memset (¤t_event
, 0, sizeof (current_event
));
297 child_init_thread_list ();
299 if (the_low_target
.initial_stuff
!= NULL
)
300 (*the_low_target
.initial_stuff
) ();
303 /* Resume all artificially suspended threads if we are continuing
306 continue_one_thread (struct inferior_list_entry
*this_thread
, void *id_ptr
)
308 struct thread_info
*thread
= (struct thread_info
*) this_thread
;
309 int thread_id
= * (int *) id_ptr
;
310 win32_thread_info
*th
= inferior_target_data (thread
);
312 if ((thread_id
== -1 || thread_id
== th
->tid
)
315 if (th
->context
.ContextFlags
)
317 win32_set_thread_context (th
);
318 th
->context
.ContextFlags
= 0;
321 if (ResumeThread (th
->h
) == (DWORD
) -1)
323 DWORD err
= GetLastError ();
324 OUTMSG (("warning: ResumeThread failed in continue_one_thread, "
325 "(error %d): %s\n", (int) err
, strwinerror (err
)));
334 child_continue (DWORD continue_status
, int thread_id
)
336 /* The inferior will only continue after the ContinueDebugEvent
338 find_inferior (&all_threads
, continue_one_thread
, &thread_id
);
339 faked_breakpoint
= 0;
341 if (!ContinueDebugEvent (current_event
.dwProcessId
,
342 current_event
.dwThreadId
,
349 /* Fetch register(s) from the current thread context. */
351 child_fetch_inferior_registers (int r
)
354 win32_thread_info
*th
= thread_rec (current_inferior_tid (), TRUE
);
355 if (r
== -1 || r
== 0 || r
> NUM_REGS
)
356 child_fetch_inferior_registers (NUM_REGS
);
358 for (regno
= 0; regno
< r
; regno
++)
359 (*the_low_target
.fetch_inferior_register
) (th
, regno
);
362 /* Store a new register value into the current thread context. We don't
363 change the program's context until later, when we resume it. */
365 child_store_inferior_registers (int r
)
368 win32_thread_info
*th
= thread_rec (current_inferior_tid (), TRUE
);
369 if (r
== -1 || r
== 0 || r
> NUM_REGS
)
370 child_store_inferior_registers (NUM_REGS
);
372 for (regno
= 0; regno
< r
; regno
++)
373 (*the_low_target
.store_inferior_register
) (th
, regno
);
376 /* Map the Windows error number in ERROR to a locale-dependent error
377 message string and return a pointer to it. Typically, the values
378 for ERROR come from GetLastError.
380 The string pointed to shall not be modified by the application,
381 but may be overwritten by a subsequent call to strwinerror
383 The strwinerror function does not change the current setting
387 strwinerror (DWORD error
)
389 static char buf
[1024];
391 DWORD lasterr
= GetLastError ();
392 DWORD chars
= FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
393 | FORMAT_MESSAGE_ALLOCATE_BUFFER
,
396 0, /* Default language */
402 /* If there is an \r\n appended, zap it. */
404 && msgbuf
[chars
- 2] == '\r'
405 && msgbuf
[chars
- 1] == '\n')
411 if (chars
> ((COUNTOF (buf
)) - 1))
413 chars
= COUNTOF (buf
) - 1;
418 wcstombs (buf
, msgbuf
, chars
+ 1);
420 strncpy (buf
, msgbuf
, chars
+ 1);
425 sprintf (buf
, "unknown win32 error (%ld)", error
);
427 SetLastError (lasterr
);
432 create_process (const char *program
, char *args
,
433 DWORD flags
, PROCESS_INFORMATION
*pi
)
438 wchar_t *p
, *wprogram
, *wargs
;
441 wprogram
= alloca ((strlen (program
) + 1) * sizeof (wchar_t));
442 mbstowcs (wprogram
, program
, strlen (program
) + 1);
444 for (p
= wprogram
; *p
; ++p
)
448 argslen
= strlen (args
);
449 wargs
= alloca ((argslen
+ 1) * sizeof (wchar_t));
450 mbstowcs (wargs
, args
, argslen
+ 1);
452 ret
= CreateProcessW (wprogram
, /* image name */
453 wargs
, /* command line */
454 NULL
, /* security, not supported */
455 NULL
, /* thread, not supported */
456 FALSE
, /* inherit handles, not supported */
457 flags
, /* start flags */
458 NULL
, /* environment, not supported */
459 NULL
, /* current directory, not supported */
460 NULL
, /* start info, not supported */
463 STARTUPINFOA si
= { sizeof (STARTUPINFOA
) };
465 ret
= CreateProcessA (program
, /* image name */
466 args
, /* command line */
469 TRUE
, /* inherit handles */
470 flags
, /* start flags */
471 NULL
, /* environment */
472 NULL
, /* current directory */
473 &si
, /* start info */
480 /* Start a new process.
481 PROGRAM is a path to the program to execute.
482 ARGS is a standard NULL-terminated array of arguments,
483 to be passed to the inferior as ``argv''.
484 Returns the new PID on success, -1 on failure. Registers the new
485 process with the process list. */
487 win32_create_inferior (char *program
, char **program_args
)
490 char real_path
[MAXPATHLEN
];
491 char *orig_path
, *new_path
, *path_ptr
;
498 PROCESS_INFORMATION pi
;
502 error ("No executable specified, specify executable to debug.\n");
504 flags
= DEBUG_PROCESS
| DEBUG_ONLY_THIS_PROCESS
;
508 path_ptr
= getenv ("PATH");
511 orig_path
= alloca (strlen (path_ptr
) + 1);
512 new_path
= alloca (cygwin_posix_to_win32_path_list_buf_size (path_ptr
));
513 strcpy (orig_path
, path_ptr
);
514 cygwin_posix_to_win32_path_list (path_ptr
, new_path
);
515 setenv ("PATH", new_path
, 1);
517 cygwin_conv_to_win32_path (program
, real_path
);
522 for (argc
= 1; program_args
[argc
]; argc
++)
523 argslen
+= strlen (program_args
[argc
]) + 1;
524 args
= alloca (argslen
);
526 for (argc
= 1; program_args
[argc
]; argc
++)
528 /* FIXME: Can we do better about quoting? How does Cygwin
531 strcat (args
, program_args
[argc
]);
533 OUTMSG2 (("Command line is \"%s\"\n", args
));
535 #ifdef CREATE_NEW_PROCESS_GROUP
536 flags
|= CREATE_NEW_PROCESS_GROUP
;
539 ret
= create_process (program
, args
, flags
, &pi
);
540 err
= GetLastError ();
541 if (!ret
&& err
== ERROR_FILE_NOT_FOUND
)
543 char *exename
= alloca (strlen (program
) + 5);
544 strcat (strcpy (exename
, program
), ".exe");
545 ret
= create_process (exename
, args
, flags
, &pi
);
546 err
= GetLastError ();
551 setenv ("PATH", orig_path
, 1);
556 error ("Error creating process \"%s%s\", (error %d): %s\n",
557 program
, args
, (int) err
, strwinerror (err
));
561 OUTMSG2 (("Process created: %s\n", (char *) args
));
565 /* On Windows CE this handle can't be closed. The OS reuses
566 it in the debug events, while the 9x/NT versions of Windows
567 probably use a DuplicateHandle'd one. */
568 CloseHandle (pi
.hThread
);
571 current_process_handle
= pi
.hProcess
;
572 current_process_id
= pi
.dwProcessId
;
574 do_initial_child_stuff (current_process_id
);
576 return current_process_id
;
579 /* Attach to a running process.
580 PID is the process ID to attach to, specified by the user
581 or a higher layer. */
583 win32_attach (unsigned long pid
)
586 winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit
= NULL
;
589 HMODULE dll
= GetModuleHandle (_T("COREDLL.DLL"));
591 HMODULE dll
= GetModuleHandle (_T("KERNEL32.DLL"));
593 DebugSetProcessKillOnExit
= GETPROCADDRESS (dll
, DebugSetProcessKillOnExit
);
595 h
= OpenProcess (PROCESS_ALL_ACCESS
, FALSE
, pid
);
598 if (DebugActiveProcess (pid
))
600 if (DebugSetProcessKillOnExit
!= NULL
)
601 DebugSetProcessKillOnExit (FALSE
);
603 current_process_handle
= h
;
604 current_process_id
= pid
;
605 do_initial_child_stuff (pid
);
612 err
= GetLastError ();
613 error ("Attach to process failed (error %d): %s\n",
614 (int) err
, strwinerror (err
));
617 /* Handle OUTPUT_DEBUG_STRING_EVENT from child process. */
619 handle_output_debug_string (struct target_waitstatus
*ourstatus
)
621 #define READ_BUFFER_LEN 1024
623 char s
[READ_BUFFER_LEN
+ 1] = { 0 };
624 DWORD nbytes
= current_event
.u
.DebugString
.nDebugStringLength
;
629 if (nbytes
> READ_BUFFER_LEN
)
630 nbytes
= READ_BUFFER_LEN
;
632 addr
= (CORE_ADDR
) (size_t) current_event
.u
.DebugString
.lpDebugStringData
;
634 if (current_event
.u
.DebugString
.fUnicode
)
636 /* The event tells us how many bytes, not chars, even
638 WCHAR buffer
[(READ_BUFFER_LEN
+ 1) / sizeof (WCHAR
)] = { 0 };
639 if (read_inferior_memory (addr
, (unsigned char *) buffer
, nbytes
) != 0)
641 wcstombs (s
, buffer
, (nbytes
+ 1) / sizeof (WCHAR
));
645 if (read_inferior_memory (addr
, (unsigned char *) s
, nbytes
) != 0)
649 if (strncmp (s
, "cYg", 3) != 0)
659 #undef READ_BUFFER_LEN
662 /* Kill all inferiors. */
666 win32_thread_info
*current_thread
;
668 if (current_process_handle
== NULL
)
671 TerminateProcess (current_process_handle
, 0);
674 if (!child_continue (DBG_CONTINUE
, -1))
676 if (!WaitForDebugEvent (¤t_event
, INFINITE
))
678 if (current_event
.dwDebugEventCode
== EXIT_PROCESS_DEBUG_EVENT
)
680 else if (current_event
.dwDebugEventCode
== OUTPUT_DEBUG_STRING_EVENT
)
682 struct target_waitstatus our_status
= { 0 };
683 handle_output_debug_string (&our_status
);
687 CloseHandle (current_process_handle
);
689 current_thread
= inferior_target_data (current_inferior
);
690 if (current_thread
&& current_thread
->h
)
692 /* This may fail in an attached process, so don't check. */
693 (void) CloseHandle (current_thread
->h
);
697 /* Detach from all inferiors. */
703 winapi_DebugActiveProcessStop DebugActiveProcessStop
= NULL
;
704 winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit
= NULL
;
706 HMODULE dll
= GetModuleHandle (_T("COREDLL.DLL"));
708 HMODULE dll
= GetModuleHandle (_T("KERNEL32.DLL"));
710 DebugActiveProcessStop
= GETPROCADDRESS (dll
, DebugActiveProcessStop
);
711 DebugSetProcessKillOnExit
= GETPROCADDRESS (dll
, DebugSetProcessKillOnExit
);
713 if (DebugSetProcessKillOnExit
== NULL
714 || DebugActiveProcessStop
== NULL
)
717 /* We need a new handle, since DebugActiveProcessStop
718 closes all the ones that came through the events. */
719 if ((h
= OpenProcess (PROCESS_ALL_ACCESS
,
721 current_process_id
)) == NULL
)
723 /* The process died. */
728 struct thread_resume resume
;
732 resume
.leave_stopped
= 0;
733 win32_resume (&resume
);
736 if (!DebugActiveProcessStop (current_process_id
))
741 DebugSetProcessKillOnExit (FALSE
);
743 current_process_handle
= h
;
747 /* Wait for inferiors to end. */
751 if (current_process_id
== 0
752 || current_process_handle
== NULL
)
755 WaitForSingleObject (current_process_handle
, INFINITE
);
756 CloseHandle (current_process_handle
);
758 current_process_handle
= NULL
;
759 current_process_id
= 0;
762 /* Return 1 iff the thread with thread ID TID is alive. */
764 win32_thread_alive (unsigned long tid
)
768 /* Our thread list is reliable; don't bother to poll target
770 if (find_inferior_id (&all_threads
, tid
) != NULL
)
777 /* Resume the inferior process. RESUME_INFO describes how we want
780 win32_resume (struct thread_resume
*resume_info
)
783 enum target_signal sig
;
785 win32_thread_info
*th
;
786 DWORD continue_status
= DBG_CONTINUE
;
788 /* This handles the very limited set of resume packets that GDB can
789 currently produce. */
791 if (resume_info
[0].thread
== -1)
793 else if (resume_info
[1].thread
== -1 && !resume_info
[1].leave_stopped
)
796 /* Yes, we're ignoring resume_info[0].thread. It'd be tricky to make
797 the Windows resume code do the right thing for thread switching. */
798 tid
= current_event
.dwThreadId
;
800 if (resume_info
[0].thread
!= -1)
802 sig
= resume_info
[0].sig
;
803 step
= resume_info
[0].step
;
811 if (sig
!= TARGET_SIGNAL_0
)
813 if (current_event
.dwDebugEventCode
!= EXCEPTION_DEBUG_EVENT
)
815 OUTMSG (("Cannot continue with signal %d here.\n", sig
));
817 else if (sig
== last_sig
)
818 continue_status
= DBG_EXCEPTION_NOT_HANDLED
;
820 OUTMSG (("Can only continue with recieved signal %d.\n", last_sig
));
823 last_sig
= TARGET_SIGNAL_0
;
825 /* Get context for the currently selected thread. */
826 th
= thread_rec (current_event
.dwThreadId
, FALSE
);
829 if (th
->context
.ContextFlags
)
831 /* Move register values from the inferior into the thread
832 context structure. */
833 regcache_invalidate ();
837 if (the_low_target
.single_step
!= NULL
)
838 (*the_low_target
.single_step
) (th
);
840 error ("Single stepping is not supported "
841 "in this configuration.\n");
844 win32_set_thread_context (th
);
845 th
->context
.ContextFlags
= 0;
849 /* Allow continuing with the same signal that interrupted us.
850 Otherwise complain. */
852 child_continue (continue_status
, tid
);
856 win32_add_one_solib (const char *name
, CORE_ADDR load_addr
)
858 char buf
[MAX_PATH
+ 1];
859 char buf2
[MAX_PATH
+ 1];
862 WIN32_FIND_DATA w32_fd
;
863 WCHAR wname
[MAX_PATH
+ 1];
864 mbstowcs (wname
, name
, MAX_PATH
);
865 HANDLE h
= FindFirstFile (wname
, &w32_fd
);
867 WIN32_FIND_DATAA w32_fd
;
868 HANDLE h
= FindFirstFileA (name
, &w32_fd
);
871 if (h
== INVALID_HANDLE_VALUE
)
879 char cwd
[MAX_PATH
+ 1];
881 if (GetCurrentDirectoryA (MAX_PATH
+ 1, cwd
))
883 p
= strrchr (buf
, '\\');
886 SetCurrentDirectoryA (buf
);
887 GetFullPathNameA (w32_fd
.cFileName
, MAX_PATH
, buf
, &p
);
888 SetCurrentDirectoryA (cwd
);
895 cygwin_conv_to_posix_path (buf
, buf2
);
900 loaded_dll (buf2
, load_addr
);
904 get_image_name (HANDLE h
, void *address
, int unicode
)
906 static char buf
[(2 * MAX_PATH
) + 1];
907 DWORD size
= unicode
? sizeof (WCHAR
) : sizeof (char);
913 /* Attempt to read the name of the dll that was detected.
914 This is documented to work only when actively debugging
915 a program. It will not work for attached processes. */
920 /* Windows CE reports the address of the image name,
921 instead of an address of a pointer into the image name. */
922 address_ptr
= address
;
924 /* See if we could read the address of a string, and that the
925 address isn't null. */
926 if (!ReadProcessMemory (h
, address
, &address_ptr
,
927 sizeof (address_ptr
), &done
)
928 || done
!= sizeof (address_ptr
)
933 /* Find the length of the string */
934 while (ReadProcessMemory (h
, address_ptr
+ len
++ * size
, &b
, size
, &done
)
935 && (b
[0] != 0 || b
[size
- 1] != 0) && done
== size
)
939 ReadProcessMemory (h
, address_ptr
, buf
, len
, &done
);
942 WCHAR
*unicode_address
= (WCHAR
*) alloca (len
* sizeof (WCHAR
));
943 ReadProcessMemory (h
, address_ptr
, unicode_address
, len
* sizeof (WCHAR
),
946 WideCharToMultiByte (CP_ACP
, 0, unicode_address
, len
, buf
, len
, 0, 0);
952 typedef BOOL (WINAPI
*winapi_EnumProcessModules
) (HANDLE
, HMODULE
*,
954 typedef BOOL (WINAPI
*winapi_GetModuleInformation
) (HANDLE
, HMODULE
,
955 LPMODULEINFO
, DWORD
);
956 typedef DWORD (WINAPI
*winapi_GetModuleFileNameExA
) (HANDLE
, HMODULE
,
959 static winapi_EnumProcessModules win32_EnumProcessModules
;
960 static winapi_GetModuleInformation win32_GetModuleInformation
;
961 static winapi_GetModuleFileNameExA win32_GetModuleFileNameExA
;
966 static int psapi_loaded
= 0;
967 static HMODULE dll
= NULL
;
972 dll
= LoadLibrary (TEXT("psapi.dll"));
975 win32_EnumProcessModules
=
976 GETPROCADDRESS (dll
, EnumProcessModules
);
977 win32_GetModuleInformation
=
978 GETPROCADDRESS (dll
, GetModuleInformation
);
979 win32_GetModuleFileNameExA
=
980 GETPROCADDRESS (dll
, GetModuleFileNameExA
);
983 return (win32_EnumProcessModules
!= NULL
984 && win32_GetModuleInformation
!= NULL
985 && win32_GetModuleFileNameExA
!= NULL
);
989 psapi_get_dll_name (DWORD BaseAddress
, char *dll_name_ret
)
995 HMODULE
*DllHandle
= dh_buf
;
1003 ok
= (*win32_EnumProcessModules
) (current_process_handle
,
1008 if (!ok
|| !cbNeeded
)
1011 DllHandle
= (HMODULE
*) alloca (cbNeeded
);
1015 ok
= (*win32_EnumProcessModules
) (current_process_handle
,
1022 for (i
= 0; i
< ((size_t) cbNeeded
/ sizeof (HMODULE
)); i
++)
1024 if (!(*win32_GetModuleInformation
) (current_process_handle
,
1029 DWORD err
= GetLastError ();
1030 error ("Can't get module info: (error %d): %s\n",
1031 (int) err
, strwinerror (err
));
1034 if ((DWORD
) (mi
.lpBaseOfDll
) == BaseAddress
)
1036 len
= (*win32_GetModuleFileNameExA
) (current_process_handle
,
1042 DWORD err
= GetLastError ();
1043 error ("Error getting dll name: (error %d): %s\n",
1044 (int) err
, strwinerror (err
));
1051 dll_name_ret
[0] = '\0';
1055 typedef HANDLE (WINAPI
*winapi_CreateToolhelp32Snapshot
) (DWORD
, DWORD
);
1056 typedef BOOL (WINAPI
*winapi_Module32First
) (HANDLE
, LPMODULEENTRY32
);
1057 typedef BOOL (WINAPI
*winapi_Module32Next
) (HANDLE
, LPMODULEENTRY32
);
1059 static winapi_CreateToolhelp32Snapshot win32_CreateToolhelp32Snapshot
;
1060 static winapi_Module32First win32_Module32First
;
1061 static winapi_Module32Next win32_Module32Next
;
1063 typedef BOOL (WINAPI
*winapi_CloseToolhelp32Snapshot
) (HANDLE
);
1064 static winapi_CloseToolhelp32Snapshot win32_CloseToolhelp32Snapshot
;
1068 load_toolhelp (void)
1070 static int toolhelp_loaded
= 0;
1071 static HMODULE dll
= NULL
;
1073 if (!toolhelp_loaded
)
1075 toolhelp_loaded
= 1;
1077 dll
= GetModuleHandle (_T("KERNEL32.DLL"));
1079 dll
= LoadLibrary (L
"TOOLHELP.DLL");
1084 win32_CreateToolhelp32Snapshot
=
1085 GETPROCADDRESS (dll
, CreateToolhelp32Snapshot
);
1086 win32_Module32First
= GETPROCADDRESS (dll
, Module32First
);
1087 win32_Module32Next
= GETPROCADDRESS (dll
, Module32Next
);
1089 win32_CloseToolhelp32Snapshot
=
1090 GETPROCADDRESS (dll
, CloseToolhelp32Snapshot
);
1094 return (win32_CreateToolhelp32Snapshot
!= NULL
1095 && win32_Module32First
!= NULL
1096 && win32_Module32Next
!= NULL
1098 && win32_CloseToolhelp32Snapshot
!= NULL
1104 toolhelp_get_dll_name (DWORD BaseAddress
, char *dll_name_ret
)
1106 HANDLE snapshot_module
;
1107 MODULEENTRY32 modEntry
= { sizeof (MODULEENTRY32
) };
1110 if (!load_toolhelp ())
1113 snapshot_module
= win32_CreateToolhelp32Snapshot (TH32CS_SNAPMODULE
,
1114 current_event
.dwProcessId
);
1115 if (snapshot_module
== INVALID_HANDLE_VALUE
)
1118 /* Ignore the first module, which is the exe. */
1119 if (win32_Module32First (snapshot_module
, &modEntry
))
1120 while (win32_Module32Next (snapshot_module
, &modEntry
))
1121 if ((DWORD
) modEntry
.modBaseAddr
== BaseAddress
)
1124 wcstombs (dll_name_ret
, modEntry
.szExePath
, MAX_PATH
+ 1);
1126 strcpy (dll_name_ret
, modEntry
.szExePath
);
1133 win32_CloseToolhelp32Snapshot (snapshot_module
);
1135 CloseHandle (snapshot_module
);
1141 handle_load_dll (void)
1143 LOAD_DLL_DEBUG_INFO
*event
= ¤t_event
.u
.LoadDll
;
1144 char dll_buf
[MAX_PATH
+ 1];
1145 char *dll_name
= NULL
;
1148 dll_buf
[0] = dll_buf
[sizeof (dll_buf
) - 1] = '\0';
1150 /* Windows does not report the image name of the dlls in the debug
1151 event on attaches. We resort to iterating over the list of
1152 loaded dlls looking for a match by image base. */
1153 if (!psapi_get_dll_name ((DWORD
) event
->lpBaseOfDll
, dll_buf
))
1155 if (!server_waiting
)
1156 /* On some versions of Windows and Windows CE, we can't create
1157 toolhelp snapshots while the inferior is stopped in a
1158 LOAD_DLL_DEBUG_EVENT due to a dll load, but we can while
1159 Windows is reporting the already loaded dlls. */
1160 toolhelp_get_dll_name ((DWORD
) event
->lpBaseOfDll
, dll_buf
);
1165 if (*dll_name
== '\0')
1166 dll_name
= get_image_name (current_process_handle
,
1167 event
->lpImageName
, event
->fUnicode
);
1171 /* The symbols in a dll are offset by 0x1000, which is the
1172 the offset from 0 of the first byte in an image - because
1173 of the file header and the section alignment. */
1175 load_addr
= (DWORD
) event
->lpBaseOfDll
+ 0x1000;
1176 win32_add_one_solib (dll_name
, load_addr
);
1180 handle_unload_dll (void)
1182 CORE_ADDR load_addr
=
1183 (CORE_ADDR
) (DWORD
) current_event
.u
.UnloadDll
.lpBaseOfDll
;
1184 load_addr
+= 0x1000;
1185 unloaded_dll (NULL
, load_addr
);
1189 handle_exception (struct target_waitstatus
*ourstatus
)
1191 DWORD code
= current_event
.u
.Exception
.ExceptionRecord
.ExceptionCode
;
1193 ourstatus
->kind
= TARGET_WAITKIND_STOPPED
;
1197 case EXCEPTION_ACCESS_VIOLATION
:
1198 OUTMSG2 (("EXCEPTION_ACCESS_VIOLATION"));
1199 ourstatus
->value
.sig
= TARGET_SIGNAL_SEGV
;
1201 case STATUS_STACK_OVERFLOW
:
1202 OUTMSG2 (("STATUS_STACK_OVERFLOW"));
1203 ourstatus
->value
.sig
= TARGET_SIGNAL_SEGV
;
1205 case STATUS_FLOAT_DENORMAL_OPERAND
:
1206 OUTMSG2 (("STATUS_FLOAT_DENORMAL_OPERAND"));
1207 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1209 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED
:
1210 OUTMSG2 (("EXCEPTION_ARRAY_BOUNDS_EXCEEDED"));
1211 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1213 case STATUS_FLOAT_INEXACT_RESULT
:
1214 OUTMSG2 (("STATUS_FLOAT_INEXACT_RESULT"));
1215 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1217 case STATUS_FLOAT_INVALID_OPERATION
:
1218 OUTMSG2 (("STATUS_FLOAT_INVALID_OPERATION"));
1219 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1221 case STATUS_FLOAT_OVERFLOW
:
1222 OUTMSG2 (("STATUS_FLOAT_OVERFLOW"));
1223 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1225 case STATUS_FLOAT_STACK_CHECK
:
1226 OUTMSG2 (("STATUS_FLOAT_STACK_CHECK"));
1227 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1229 case STATUS_FLOAT_UNDERFLOW
:
1230 OUTMSG2 (("STATUS_FLOAT_UNDERFLOW"));
1231 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1233 case STATUS_FLOAT_DIVIDE_BY_ZERO
:
1234 OUTMSG2 (("STATUS_FLOAT_DIVIDE_BY_ZERO"));
1235 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1237 case STATUS_INTEGER_DIVIDE_BY_ZERO
:
1238 OUTMSG2 (("STATUS_INTEGER_DIVIDE_BY_ZERO"));
1239 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1241 case STATUS_INTEGER_OVERFLOW
:
1242 OUTMSG2 (("STATUS_INTEGER_OVERFLOW"));
1243 ourstatus
->value
.sig
= TARGET_SIGNAL_FPE
;
1245 case EXCEPTION_BREAKPOINT
:
1246 OUTMSG2 (("EXCEPTION_BREAKPOINT"));
1247 ourstatus
->value
.sig
= TARGET_SIGNAL_TRAP
;
1249 /* Remove the initial breakpoint. */
1250 check_breakpoints ((CORE_ADDR
) (long) current_event
1251 .u
.Exception
.ExceptionRecord
.ExceptionAddress
);
1255 OUTMSG2 (("DBG_CONTROL_C"));
1256 ourstatus
->value
.sig
= TARGET_SIGNAL_INT
;
1258 case DBG_CONTROL_BREAK
:
1259 OUTMSG2 (("DBG_CONTROL_BREAK"));
1260 ourstatus
->value
.sig
= TARGET_SIGNAL_INT
;
1262 case EXCEPTION_SINGLE_STEP
:
1263 OUTMSG2 (("EXCEPTION_SINGLE_STEP"));
1264 ourstatus
->value
.sig
= TARGET_SIGNAL_TRAP
;
1266 case EXCEPTION_ILLEGAL_INSTRUCTION
:
1267 OUTMSG2 (("EXCEPTION_ILLEGAL_INSTRUCTION"));
1268 ourstatus
->value
.sig
= TARGET_SIGNAL_ILL
;
1270 case EXCEPTION_PRIV_INSTRUCTION
:
1271 OUTMSG2 (("EXCEPTION_PRIV_INSTRUCTION"));
1272 ourstatus
->value
.sig
= TARGET_SIGNAL_ILL
;
1274 case EXCEPTION_NONCONTINUABLE_EXCEPTION
:
1275 OUTMSG2 (("EXCEPTION_NONCONTINUABLE_EXCEPTION"));
1276 ourstatus
->value
.sig
= TARGET_SIGNAL_ILL
;
1279 if (current_event
.u
.Exception
.dwFirstChance
)
1281 ourstatus
->kind
= TARGET_WAITKIND_SPURIOUS
;
1284 OUTMSG2 (("gdbserver: unknown target exception 0x%08lx at 0x%08lx",
1285 current_event
.u
.Exception
.ExceptionRecord
.ExceptionCode
,
1286 (DWORD
) current_event
.u
.Exception
.ExceptionRecord
.
1288 ourstatus
->value
.sig
= TARGET_SIGNAL_UNKNOWN
;
1292 last_sig
= ourstatus
->value
.sig
;
1297 suspend_one_thread (struct inferior_list_entry
*entry
)
1299 struct thread_info
*thread
= (struct thread_info
*) entry
;
1300 win32_thread_info
*th
= inferior_target_data (thread
);
1304 if (SuspendThread (th
->h
) == (DWORD
) -1)
1306 DWORD err
= GetLastError ();
1307 OUTMSG (("warning: SuspendThread failed in suspend_one_thread, "
1308 "(error %d): %s\n", (int) err
, strwinerror (err
)));
1316 fake_breakpoint_event (void)
1318 OUTMSG2(("fake_breakpoint_event\n"));
1320 faked_breakpoint
= 1;
1322 memset (¤t_event
, 0, sizeof (current_event
));
1323 current_event
.dwThreadId
= main_thread_id
;
1324 current_event
.dwDebugEventCode
= EXCEPTION_DEBUG_EVENT
;
1325 current_event
.u
.Exception
.ExceptionRecord
.ExceptionCode
1326 = EXCEPTION_BREAKPOINT
;
1328 for_each_inferior (&all_threads
, suspend_one_thread
);
1331 /* Get the next event from the child. */
1334 get_child_debug_event (struct target_waitstatus
*ourstatus
)
1336 last_sig
= TARGET_SIGNAL_0
;
1337 ourstatus
->kind
= TARGET_WAITKIND_SPURIOUS
;
1339 /* Check if GDB sent us an interrupt request. */
1340 check_remote_input_interrupt_request ();
1342 if (soft_interrupt_requested
)
1344 soft_interrupt_requested
= 0;
1345 fake_breakpoint_event ();
1349 /* Keep the wait time low enough for confortable remote
1350 interruption, but high enough so gdbserver doesn't become a
1352 if (!WaitForDebugEvent (¤t_event
, 250))
1358 (struct thread_info
*) find_inferior_id (&all_threads
,
1359 current_event
.dwThreadId
);
1361 switch (current_event
.dwDebugEventCode
)
1363 case CREATE_THREAD_DEBUG_EVENT
:
1364 OUTMSG2 (("gdbserver: kernel event CREATE_THREAD_DEBUG_EVENT "
1365 "for pid=%d tid=%x)\n",
1366 (unsigned) current_event
.dwProcessId
,
1367 (unsigned) current_event
.dwThreadId
));
1369 /* Record the existence of this thread. */
1370 child_add_thread (current_event
.dwThreadId
,
1371 current_event
.u
.CreateThread
.hThread
);
1374 case EXIT_THREAD_DEBUG_EVENT
:
1375 OUTMSG2 (("gdbserver: kernel event EXIT_THREAD_DEBUG_EVENT "
1376 "for pid=%d tid=%x\n",
1377 (unsigned) current_event
.dwProcessId
,
1378 (unsigned) current_event
.dwThreadId
));
1379 child_delete_thread (current_event
.dwThreadId
);
1382 case CREATE_PROCESS_DEBUG_EVENT
:
1383 OUTMSG2 (("gdbserver: kernel event CREATE_PROCESS_DEBUG_EVENT "
1384 "for pid=%d tid=%x\n",
1385 (unsigned) current_event
.dwProcessId
,
1386 (unsigned) current_event
.dwThreadId
));
1387 CloseHandle (current_event
.u
.CreateProcessInfo
.hFile
);
1389 current_process_handle
= current_event
.u
.CreateProcessInfo
.hProcess
;
1390 main_thread_id
= current_event
.dwThreadId
;
1392 ourstatus
->kind
= TARGET_WAITKIND_EXECD
;
1393 ourstatus
->value
.execd_pathname
= "Main executable";
1395 /* Add the main thread. */
1396 child_add_thread (main_thread_id
,
1397 current_event
.u
.CreateProcessInfo
.hThread
);
1399 ourstatus
->value
.related_pid
= current_event
.dwThreadId
;
1401 /* Windows CE doesn't set the initial breakpoint automatically
1402 like the desktop versions of Windows do. We add it explicitly
1403 here. It will be removed as soon as it is hit. */
1404 set_breakpoint_at ((CORE_ADDR
) (long) current_event
.u
1405 .CreateProcessInfo
.lpStartAddress
,
1406 delete_breakpoint_at
);
1410 case EXIT_PROCESS_DEBUG_EVENT
:
1411 OUTMSG2 (("gdbserver: kernel event EXIT_PROCESS_DEBUG_EVENT "
1412 "for pid=%d tid=%x\n",
1413 (unsigned) current_event
.dwProcessId
,
1414 (unsigned) current_event
.dwThreadId
));
1415 ourstatus
->kind
= TARGET_WAITKIND_EXITED
;
1416 ourstatus
->value
.integer
= current_event
.u
.ExitProcess
.dwExitCode
;
1417 CloseHandle (current_process_handle
);
1418 current_process_handle
= NULL
;
1421 case LOAD_DLL_DEBUG_EVENT
:
1422 OUTMSG2 (("gdbserver: kernel event LOAD_DLL_DEBUG_EVENT "
1423 "for pid=%d tid=%x\n",
1424 (unsigned) current_event
.dwProcessId
,
1425 (unsigned) current_event
.dwThreadId
));
1426 CloseHandle (current_event
.u
.LoadDll
.hFile
);
1429 ourstatus
->kind
= TARGET_WAITKIND_LOADED
;
1430 ourstatus
->value
.sig
= TARGET_SIGNAL_TRAP
;
1433 case UNLOAD_DLL_DEBUG_EVENT
:
1434 OUTMSG2 (("gdbserver: kernel event UNLOAD_DLL_DEBUG_EVENT "
1435 "for pid=%d tid=%x\n",
1436 (unsigned) current_event
.dwProcessId
,
1437 (unsigned) current_event
.dwThreadId
));
1438 handle_unload_dll ();
1439 ourstatus
->kind
= TARGET_WAITKIND_LOADED
;
1440 ourstatus
->value
.sig
= TARGET_SIGNAL_TRAP
;
1443 case EXCEPTION_DEBUG_EVENT
:
1444 OUTMSG2 (("gdbserver: kernel event EXCEPTION_DEBUG_EVENT "
1445 "for pid=%d tid=%x\n",
1446 (unsigned) current_event
.dwProcessId
,
1447 (unsigned) current_event
.dwThreadId
));
1448 handle_exception (ourstatus
);
1451 case OUTPUT_DEBUG_STRING_EVENT
:
1452 /* A message from the kernel (or Cygwin). */
1453 OUTMSG2 (("gdbserver: kernel event OUTPUT_DEBUG_STRING_EVENT "
1454 "for pid=%d tid=%x\n",
1455 (unsigned) current_event
.dwProcessId
,
1456 (unsigned) current_event
.dwThreadId
));
1457 handle_output_debug_string (ourstatus
);
1461 OUTMSG2 (("gdbserver: kernel event unknown "
1462 "for pid=%d tid=%x code=%ld\n",
1463 (unsigned) current_event
.dwProcessId
,
1464 (unsigned) current_event
.dwThreadId
,
1465 current_event
.dwDebugEventCode
));
1470 (struct thread_info
*) find_inferior_id (&all_threads
,
1471 current_event
.dwThreadId
);
1475 /* Wait for the inferior process to change state.
1476 STATUS will be filled in with a response code to send to GDB.
1477 Returns the signal which caused the process to stop. */
1478 static unsigned char
1479 win32_wait (char *status
)
1481 struct target_waitstatus our_status
;
1487 if (!get_child_debug_event (&our_status
))
1490 switch (our_status
.kind
)
1492 case TARGET_WAITKIND_EXITED
:
1493 OUTMSG2 (("Child exited with retcode = %x\n",
1494 our_status
.value
.integer
));
1497 return our_status
.value
.integer
;
1498 case TARGET_WAITKIND_STOPPED
:
1499 case TARGET_WAITKIND_LOADED
:
1500 OUTMSG2 (("Child Stopped with signal = %d \n",
1501 our_status
.value
.sig
));
1505 child_fetch_inferior_registers (-1);
1507 if (our_status
.kind
== TARGET_WAITKIND_LOADED
1510 /* When gdb connects, we want to be stopped at the
1511 initial breakpoint, not in some dll load event. */
1512 child_continue (DBG_CONTINUE
, -1);
1516 return our_status
.value
.sig
;
1518 OUTMSG (("Ignoring unknown internal event, %d\n", our_status
.kind
));
1520 case TARGET_WAITKIND_SPURIOUS
:
1521 case TARGET_WAITKIND_EXECD
:
1522 /* do nothing, just continue */
1523 child_continue (DBG_CONTINUE
, -1);
1529 /* Fetch registers from the inferior process.
1530 If REGNO is -1, fetch all registers; otherwise, fetch at least REGNO. */
1532 win32_fetch_inferior_registers (int regno
)
1534 child_fetch_inferior_registers (regno
);
1537 /* Store registers to the inferior process.
1538 If REGNO is -1, store all registers; otherwise, store at least REGNO. */
1540 win32_store_inferior_registers (int regno
)
1542 child_store_inferior_registers (regno
);
1545 /* Read memory from the inferior process. This should generally be
1546 called through read_inferior_memory, which handles breakpoint shadowing.
1547 Read LEN bytes at MEMADDR into a buffer at MYADDR. */
1549 win32_read_inferior_memory (CORE_ADDR memaddr
, unsigned char *myaddr
, int len
)
1551 return child_xfer_memory (memaddr
, (char *) myaddr
, len
, 0, 0) != len
;
1554 /* Write memory to the inferior process. This should generally be
1555 called through write_inferior_memory, which handles breakpoint shadowing.
1556 Write LEN bytes from the buffer at MYADDR to MEMADDR.
1557 Returns 0 on success and errno on failure. */
1559 win32_write_inferior_memory (CORE_ADDR memaddr
, const unsigned char *myaddr
,
1562 return child_xfer_memory (memaddr
, (char *) myaddr
, len
, 1, 0) != len
;
1565 /* Send an interrupt request to the inferior process. */
1567 win32_request_interrupt (void)
1569 winapi_DebugBreakProcess DebugBreakProcess
;
1570 winapi_GenerateConsoleCtrlEvent GenerateConsoleCtrlEvent
;
1573 HMODULE dll
= GetModuleHandle (_T("COREDLL.DLL"));
1575 HMODULE dll
= GetModuleHandle (_T("KERNEL32.DLL"));
1578 GenerateConsoleCtrlEvent
= GETPROCADDRESS (dll
, GenerateConsoleCtrlEvent
);
1580 if (GenerateConsoleCtrlEvent
!= NULL
1581 && GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT
, current_process_id
))
1584 /* GenerateConsoleCtrlEvent can fail if process id being debugged is
1585 not a process group id.
1586 Fallback to XP/Vista 'DebugBreakProcess', which generates a
1587 breakpoint exception in the interior process. */
1589 DebugBreakProcess
= GETPROCADDRESS (dll
, DebugBreakProcess
);
1591 if (DebugBreakProcess
!= NULL
1592 && DebugBreakProcess (current_process_handle
))
1595 /* Last resort, suspend all threads manually. */
1596 soft_interrupt_requested
= 1;
1600 win32_arch_string (void)
1602 return the_low_target
.arch_string
;
1605 static struct target_ops win32_target_ops
= {
1606 win32_create_inferior
,
1614 win32_fetch_inferior_registers
,
1615 win32_store_inferior_registers
,
1616 win32_read_inferior_memory
,
1617 win32_write_inferior_memory
,
1619 win32_request_interrupt
,
1630 /* Initialize the Win32 backend. */
1632 initialize_low (void)
1634 set_target_ops (&win32_target_ops
);
1635 if (the_low_target
.breakpoint
!= NULL
)
1636 set_breakpoint_data (the_low_target
.breakpoint
,
1637 the_low_target
.breakpoint_len
);