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 2 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, write to the Free Software
20 Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 Boston, MA 02110-1301, USA. */
25 #include "gdb/signals.h"
26 #include "mem-break.h"
27 #include "win32-low.h"
34 #include <sys/param.h>
39 #include <sys/cygwin.h>
44 #define OUTMSG(X) do { printf X; fflush (stdout); } while (0)
46 #define OUTMSG2(X) do { printf X; fflush (stdout); } while (0)
48 #define OUTMSG2(X) do ; while (0)
52 #define _T(x) TEXT (x)
56 #define COUNTOF(STR) (sizeof (STR) / sizeof ((STR)[0]))
60 # define GETPROCADDRESS(DLL, PROC) \
61 ((winapi_ ## PROC) GetProcAddress (DLL, TEXT (#PROC)))
63 # define GETPROCADDRESS(DLL, PROC) \
64 ((winapi_ ## PROC) GetProcAddress (DLL, #PROC))
67 int using_threads = 1;
70 static HANDLE current_process_handle = NULL;
71 static DWORD current_process_id = 0;
72 static enum target_signal last_sig = TARGET_SIGNAL_0;
74 /* The current debug event from WaitForDebugEvent. */
75 static DEBUG_EVENT current_event;
77 #define NUM_REGS (the_low_target.num_regs)
79 typedef BOOL WINAPI (*winapi_DebugActiveProcessStop) (DWORD dwProcessId);
80 typedef BOOL WINAPI (*winapi_DebugSetProcessKillOnExit) (BOOL KillOnExit);
81 typedef BOOL WINAPI (*winapi_DebugBreakProcess) (HANDLE);
82 typedef BOOL WINAPI (*winapi_GenerateConsoleCtrlEvent) (DWORD, DWORD);
84 static DWORD main_thread_id = 0;
86 static void win32_resume (struct thread_resume *resume_info);
88 /* Get the thread ID from the current selected inferior (the current
91 current_inferior_tid (void)
93 win32_thread_info *th = inferior_target_data (current_inferior);
97 /* Find a thread record given a thread id. If GET_CONTEXT is set then
98 also retrieve the context for this thread. */
99 static win32_thread_info *
100 thread_rec (DWORD id, int get_context)
102 struct thread_info *thread;
103 win32_thread_info *th;
105 thread = (struct thread_info *) find_inferior_id (&all_threads, id);
109 th = inferior_target_data (thread);
110 if (!th->suspend_count && get_context)
112 if (id != current_event.dwThreadId)
113 th->suspend_count = SuspendThread (th->h) + 1;
115 (*the_low_target.get_thread_context) (th, ¤t_event);
121 /* Add a thread to the thread list. */
122 static win32_thread_info *
123 child_add_thread (DWORD tid, HANDLE h)
125 win32_thread_info *th;
127 if ((th = thread_rec (tid, FALSE)))
130 th = (win32_thread_info *) malloc (sizeof (*th));
131 memset (th, 0, sizeof (*th));
135 add_thread (tid, th, (unsigned int) tid);
136 set_inferior_regcache_data ((struct thread_info *)
137 find_inferior_id (&all_threads, tid),
138 new_register_cache ());
140 if (the_low_target.thread_added != NULL)
141 (*the_low_target.thread_added) (th);
146 /* Delete a thread from the list of threads. */
148 delete_thread_info (struct inferior_list_entry *thread)
150 win32_thread_info *th = inferior_target_data ((struct thread_info *) thread);
152 remove_thread ((struct thread_info *) thread);
157 /* Delete a thread from the list of threads. */
159 child_delete_thread (DWORD id)
161 struct inferior_list_entry *thread;
163 /* If the last thread is exiting, just return. */
164 if (all_threads.head == all_threads.tail)
167 thread = find_inferior_id (&all_threads, id);
171 delete_thread_info (thread);
174 /* Transfer memory from/to the debugged process. */
176 child_xfer_memory (CORE_ADDR memaddr, char *our, int len,
177 int write, struct target_ops *target)
180 long addr = (long) memaddr;
184 WriteProcessMemory (current_process_handle, (LPVOID) addr,
185 (LPCVOID) our, len, &done);
186 FlushInstructionCache (current_process_handle, (LPCVOID) addr, len);
190 ReadProcessMemory (current_process_handle, (LPCVOID) addr, (LPVOID) our,
196 /* Generally, what has the program done? */
199 /* The program has exited. The exit status is in value.integer. */
200 TARGET_WAITKIND_EXITED,
202 /* The program has stopped with a signal. Which signal is in
204 TARGET_WAITKIND_STOPPED,
206 /* The program is letting us know that it dynamically loaded
207 or unloaded something. */
208 TARGET_WAITKIND_LOADED,
210 /* The program has exec'ed a new executable file. The new file's
211 pathname is pointed to by value.execd_pathname. */
212 TARGET_WAITKIND_EXECD,
214 /* Nothing interesting happened, but we stopped anyway. We take the
215 chance to check if GDB requested an interrupt. */
216 TARGET_WAITKIND_SPURIOUS,
219 struct target_waitstatus
221 enum target_waitkind kind;
223 /* Forked child pid, execd pathname, exit status or signal number. */
227 enum target_signal sig;
229 char *execd_pathname;
235 /* Clear out any old thread list and reinitialize it to a pristine
238 child_init_thread_list (void)
240 for_each_inferior (&all_threads, delete_thread_info);
244 do_initial_child_stuff (DWORD pid)
246 last_sig = TARGET_SIGNAL_0;
248 memset (¤t_event, 0, sizeof (current_event));
250 child_init_thread_list ();
252 if (the_low_target.initial_stuff != NULL)
253 (*the_low_target.initial_stuff) ();
256 /* Resume all artificially suspended threads if we are continuing
259 continue_one_thread (struct inferior_list_entry *this_thread, void *id_ptr)
261 struct thread_info *thread = (struct thread_info *) this_thread;
262 int thread_id = * (int *) id_ptr;
263 win32_thread_info *th = inferior_target_data (thread);
266 if ((thread_id == -1 || thread_id == th->tid)
267 && th->suspend_count)
269 if (th->context.ContextFlags)
271 (*the_low_target.set_thread_context) (th, ¤t_event);
272 th->context.ContextFlags = 0;
275 for (i = 0; i < th->suspend_count; i++)
276 (void) ResumeThread (th->h);
277 th->suspend_count = 0;
284 child_continue (DWORD continue_status, int thread_id)
288 res = ContinueDebugEvent (current_event.dwProcessId,
289 current_event.dwThreadId, continue_status);
291 find_inferior (&all_threads, continue_one_thread, &thread_id);
296 /* Fetch register(s) from the current thread context. */
298 child_fetch_inferior_registers (int r)
301 win32_thread_info *th = thread_rec (current_inferior_tid (), TRUE);
302 if (r == -1 || r == 0 || r > NUM_REGS)
303 child_fetch_inferior_registers (NUM_REGS);
305 for (regno = 0; regno < r; regno++)
306 (*the_low_target.fetch_inferior_register) (th, regno);
309 /* Store a new register value into the current thread context. We don't
310 change the program's context until later, when we resume it. */
312 child_store_inferior_registers (int r)
315 win32_thread_info *th = thread_rec (current_inferior_tid (), TRUE);
316 if (r == -1 || r == 0 || r > NUM_REGS)
317 child_store_inferior_registers (NUM_REGS);
319 for (regno = 0; regno < r; regno++)
320 (*the_low_target.store_inferior_register) (th, regno);
323 /* Map the Windows error number in ERROR to a locale-dependent error
324 message string and return a pointer to it. Typically, the values
325 for ERROR come from GetLastError.
327 The string pointed to shall not be modified by the application,
328 but may be overwritten by a subsequent call to strwinerror
330 The strwinerror function does not change the current setting
334 strwinerror (DWORD error)
336 static char buf[1024];
338 DWORD lasterr = GetLastError ();
339 DWORD chars = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
340 | FORMAT_MESSAGE_ALLOCATE_BUFFER,
343 0, /* Default language */
349 /* If there is an \r\n appended, zap it. */
351 && msgbuf[chars - 2] == '\r'
352 && msgbuf[chars - 1] == '\n')
358 if (chars > ((COUNTOF (buf)) - 1))
360 chars = COUNTOF (buf) - 1;
365 wcstombs (buf, msgbuf, chars + 1);
367 strncpy (buf, msgbuf, chars + 1);
372 sprintf (buf, "unknown win32 error (%ld)", error);
374 SetLastError (lasterr);
378 /* Start a new process.
379 PROGRAM is a path to the program to execute.
380 ARGS is a standard NULL-terminated array of arguments,
381 to be passed to the inferior as ``argv''.
382 Returns the new PID on success, -1 on failure. Registers the new
383 process with the process list. */
385 win32_create_inferior (char *program, char **program_args)
388 char real_path[MAXPATHLEN];
389 char *orig_path, *new_path, *path_ptr;
396 PROCESS_INFORMATION pi;
397 #ifndef __MINGW32CE__
398 STARTUPINFOA si = { sizeof (STARTUPINFOA) };
401 wchar_t *wargs, *wprogram;
405 error ("No executable specified, specify executable to debug.\n");
407 flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS;
411 path_ptr = getenv ("PATH");
414 orig_path = alloca (strlen (path_ptr) + 1);
415 new_path = alloca (cygwin_posix_to_win32_path_list_buf_size (path_ptr));
416 strcpy (orig_path, path_ptr);
417 cygwin_posix_to_win32_path_list (path_ptr, new_path);
418 setenv ("PATH", new_path, 1);
420 cygwin_conv_to_win32_path (program, real_path);
425 for (argc = 1; program_args[argc]; argc++)
426 argslen += strlen (program_args[argc]) + 1;
427 args = alloca (argslen);
429 for (argc = 1; program_args[argc]; argc++)
431 /* FIXME: Can we do better about quoting? How does Cygwin
434 strcat (args, program_args[argc]);
436 OUTMSG2 (("Command line is \"%s\"\n", args));
438 #ifdef CREATE_NEW_PROCESS_GROUP
439 flags |= CREATE_NEW_PROCESS_GROUP;
443 to_back_slashes (program);
444 wargs = alloca (argslen * sizeof (wchar_t));
445 mbstowcs (wargs, args, argslen);
446 wprogram = alloca ((strlen (program) + 1) * sizeof (wchar_t));
447 mbstowcs (wprogram, program, strlen (program) + 1);
448 ret = CreateProcessW (wprogram, /* image name */
449 wargs, /* command line */
450 NULL, /* security, not supported */
451 NULL, /* thread, not supported */
452 FALSE, /* inherit handles, not supported */
453 flags, /* start flags */
454 NULL, /* environment, not supported */
455 NULL, /* current directory, not supported */
456 NULL, /* start info, not supported */
457 &pi); /* proc info */
459 ret = CreateProcessA (program, /* image name */
460 args, /* command line */
463 TRUE, /* inherit handles */
464 flags, /* start flags */
465 winenv, /* environment */
466 NULL, /* current directory */
467 &si, /* start info */
468 &pi); /* proc info */
473 setenv ("PATH", orig_path, 1);
478 DWORD err = GetLastError ();
479 error ("Error creating process \"%s%s\", (error %d): %s\n",
480 program, args, (int) err, strwinerror (err));
484 OUTMSG2 (("Process created: %s\n", (char *) args));
488 /* On Windows CE this handle can't be closed. The OS reuses
489 it in the debug events, while the 9x/NT versions of Windows
490 probably use a DuplicateHandle'd one. */
491 CloseHandle (pi.hThread);
494 current_process_handle = pi.hProcess;
495 current_process_id = pi.dwProcessId;
497 do_initial_child_stuff (current_process_id);
499 return current_process_id;
502 /* Attach to a running process.
503 PID is the process ID to attach to, specified by the user
504 or a higher layer. */
506 win32_attach (unsigned long pid)
508 winapi_DebugActiveProcessStop DebugActiveProcessStop = NULL;
509 winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit = NULL;
511 HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
513 HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
515 DebugActiveProcessStop = GETPROCADDRESS (dll, DebugActiveProcessStop);
516 DebugSetProcessKillOnExit = GETPROCADDRESS (dll, DebugSetProcessKillOnExit);
518 if (DebugActiveProcess (pid))
520 if (DebugSetProcessKillOnExit != NULL)
521 DebugSetProcessKillOnExit (FALSE);
523 current_process_handle = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
525 if (current_process_handle != NULL)
527 current_process_id = pid;
528 do_initial_child_stuff (pid);
531 if (DebugActiveProcessStop != NULL)
532 DebugActiveProcessStop (current_process_id);
535 error ("Attach to process failed.");
538 /* Handle OUTPUT_DEBUG_STRING_EVENT from child process. */
540 handle_output_debug_string (struct target_waitstatus *ourstatus)
542 #define READ_BUFFER_LEN 1024
544 char s[READ_BUFFER_LEN + 1] = { 0 };
545 DWORD nbytes = current_event.u.DebugString.nDebugStringLength;
550 if (nbytes > READ_BUFFER_LEN)
551 nbytes = READ_BUFFER_LEN;
553 addr = (CORE_ADDR) (size_t) current_event.u.DebugString.lpDebugStringData;
555 if (current_event.u.DebugString.fUnicode)
557 /* The event tells us how many bytes, not chars, even
559 WCHAR buffer[(READ_BUFFER_LEN + 1) / sizeof (WCHAR)] = { 0 };
560 if (read_inferior_memory (addr, (unsigned char *) buffer, nbytes) != 0)
562 wcstombs (s, buffer, (nbytes + 1) / sizeof (WCHAR));
566 if (read_inferior_memory (addr, (unsigned char *) s, nbytes) != 0)
570 if (strncmp (s, "cYg", 3) != 0)
580 #undef READ_BUFFER_LEN
583 /* Kill all inferiors. */
587 win32_thread_info *current_thread;
589 if (current_process_handle == NULL)
592 TerminateProcess (current_process_handle, 0);
595 if (!child_continue (DBG_CONTINUE, -1))
597 if (!WaitForDebugEvent (¤t_event, INFINITE))
599 if (current_event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
601 else if (current_event.dwDebugEventCode == OUTPUT_DEBUG_STRING_EVENT)
603 struct target_waitstatus our_status = { 0 };
604 handle_output_debug_string (&our_status);
608 CloseHandle (current_process_handle);
610 current_thread = inferior_target_data (current_inferior);
611 if (current_thread && current_thread->h)
613 /* This may fail in an attached process, so don't check. */
614 (void) CloseHandle (current_thread->h);
618 /* Detach from all inferiors. */
624 winapi_DebugActiveProcessStop DebugActiveProcessStop = NULL;
625 winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit = NULL;
627 HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
629 HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
631 DebugActiveProcessStop = GETPROCADDRESS (dll, DebugActiveProcessStop);
632 DebugSetProcessKillOnExit = GETPROCADDRESS (dll, DebugSetProcessKillOnExit);
634 if (DebugSetProcessKillOnExit == NULL
635 || DebugActiveProcessStop == NULL)
638 /* We need a new handle, since DebugActiveProcessStop
639 closes all the ones that came through the events. */
640 if ((h = OpenProcess (PROCESS_ALL_ACCESS,
642 current_process_id)) == NULL)
644 /* The process died. */
649 struct thread_resume resume;
653 resume.leave_stopped = 0;
654 win32_resume (&resume);
657 if (!DebugActiveProcessStop (current_process_id))
662 DebugSetProcessKillOnExit (FALSE);
664 current_process_handle = h;
668 /* Wait for inferiors to end. */
672 if (current_process_id == 0
673 || current_process_handle == NULL)
676 WaitForSingleObject (current_process_handle, INFINITE);
677 CloseHandle (current_process_handle);
679 current_process_handle = NULL;
680 current_process_id = 0;
683 /* Return 1 iff the thread with thread ID TID is alive. */
685 win32_thread_alive (unsigned long tid)
689 /* Our thread list is reliable; don't bother to poll target
691 if (find_inferior_id (&all_threads, tid) != NULL)
698 /* Resume the inferior process. RESUME_INFO describes how we want
701 win32_resume (struct thread_resume *resume_info)
704 enum target_signal sig;
706 win32_thread_info *th;
707 DWORD continue_status = DBG_CONTINUE;
709 /* This handles the very limited set of resume packets that GDB can
710 currently produce. */
712 if (resume_info[0].thread == -1)
714 else if (resume_info[1].thread == -1 && !resume_info[1].leave_stopped)
717 /* Yes, we're ignoring resume_info[0].thread. It'd be tricky to make
718 the Windows resume code do the right thing for thread switching. */
719 tid = current_event.dwThreadId;
721 if (resume_info[0].thread != -1)
723 sig = resume_info[0].sig;
724 step = resume_info[0].step;
732 if (sig != TARGET_SIGNAL_0)
734 if (current_event.dwDebugEventCode != EXCEPTION_DEBUG_EVENT)
736 OUTMSG (("Cannot continue with signal %d here.\n", sig));
738 else if (sig == last_sig)
739 continue_status = DBG_EXCEPTION_NOT_HANDLED;
741 OUTMSG (("Can only continue with recieved signal %d.\n", last_sig));
744 last_sig = TARGET_SIGNAL_0;
746 /* Get context for the currently selected thread. */
747 th = thread_rec (current_event.dwThreadId, FALSE);
750 if (th->context.ContextFlags)
752 /* Move register values from the inferior into the thread
753 context structure. */
754 regcache_invalidate ();
758 if (the_low_target.single_step != NULL)
759 (*the_low_target.single_step) (th);
761 error ("Single stepping is not supported "
762 "in this configuration.\n");
765 (*the_low_target.set_thread_context) (th, ¤t_event);
766 th->context.ContextFlags = 0;
770 /* Allow continuing with the same signal that interrupted us.
771 Otherwise complain. */
773 child_continue (continue_status, tid);
777 win32_add_one_solib (const char *name, CORE_ADDR load_addr)
779 char buf[MAX_PATH + 1];
780 char buf2[MAX_PATH + 1];
783 WIN32_FIND_DATA w32_fd;
784 WCHAR wname[MAX_PATH + 1];
785 mbstowcs (wname, name, MAX_PATH);
786 HANDLE h = FindFirstFile (wname, &w32_fd);
788 WIN32_FIND_DATAA w32_fd;
789 HANDLE h = FindFirstFileA (name, &w32_fd);
792 if (h == INVALID_HANDLE_VALUE)
800 char cwd[MAX_PATH + 1];
802 if (GetCurrentDirectoryA (MAX_PATH + 1, cwd))
804 p = strrchr (buf, '\\');
807 SetCurrentDirectoryA (buf);
808 GetFullPathNameA (w32_fd.cFileName, MAX_PATH, buf, &p);
809 SetCurrentDirectoryA (cwd);
816 cygwin_conv_to_posix_path (buf, buf2);
821 loaded_dll (buf2, load_addr);
825 get_image_name (HANDLE h, void *address, int unicode)
827 static char buf[(2 * MAX_PATH) + 1];
828 DWORD size = unicode ? sizeof (WCHAR) : sizeof (char);
834 /* Attempt to read the name of the dll that was detected.
835 This is documented to work only when actively debugging
836 a program. It will not work for attached processes. */
841 /* Windows CE reports the address of the image name,
842 instead of an address of a pointer into the image name. */
843 address_ptr = address;
845 /* See if we could read the address of a string, and that the
846 address isn't null. */
847 if (!ReadProcessMemory (h, address, &address_ptr,
848 sizeof (address_ptr), &done)
849 || done != sizeof (address_ptr)
854 /* Find the length of the string */
855 while (ReadProcessMemory (h, address_ptr + len++ * size, &b, size, &done)
856 && (b[0] != 0 || b[size - 1] != 0) && done == size)
860 ReadProcessMemory (h, address_ptr, buf, len, &done);
863 WCHAR *unicode_address = (WCHAR *) alloca (len * sizeof (WCHAR));
864 ReadProcessMemory (h, address_ptr, unicode_address, len * sizeof (WCHAR),
867 WideCharToMultiByte (CP_ACP, 0, unicode_address, len, buf, len, 0, 0);
873 typedef BOOL (WINAPI *winapi_EnumProcessModules) (HANDLE, HMODULE *,
875 typedef BOOL (WINAPI *winapi_GetModuleInformation) (HANDLE, HMODULE,
876 LPMODULEINFO, DWORD);
877 typedef DWORD (WINAPI *winapi_GetModuleFileNameExA) (HANDLE, HMODULE,
880 static winapi_EnumProcessModules win32_EnumProcessModules;
881 static winapi_GetModuleInformation win32_GetModuleInformation;
882 static winapi_GetModuleFileNameExA win32_GetModuleFileNameExA;
887 static int psapi_loaded = 0;
888 static HMODULE dll = NULL;
893 dll = LoadLibrary (TEXT("psapi.dll"));
896 win32_EnumProcessModules =
897 GETPROCADDRESS (dll, EnumProcessModules);
898 win32_GetModuleInformation =
899 GETPROCADDRESS (dll, GetModuleInformation);
900 win32_GetModuleFileNameExA =
901 GETPROCADDRESS (dll, GetModuleFileNameExA);
904 return (win32_EnumProcessModules != NULL
905 && win32_GetModuleInformation != NULL
906 && win32_GetModuleFileNameExA != NULL);
910 psapi_get_dll_name (DWORD BaseAddress, char *dll_name_ret)
916 HMODULE *DllHandle = dh_buf;
924 ok = (*win32_EnumProcessModules) (current_process_handle,
929 if (!ok || !cbNeeded)
932 DllHandle = (HMODULE *) alloca (cbNeeded);
936 ok = (*win32_EnumProcessModules) (current_process_handle,
943 for (i = 0; i < ((size_t) cbNeeded / sizeof (HMODULE)); i++)
945 if (!(*win32_GetModuleInformation) (current_process_handle,
950 DWORD err = GetLastError ();
951 error ("Can't get module info: (error %d): %s\n",
952 (int) err, strwinerror (err));
955 if ((DWORD) (mi.lpBaseOfDll) == BaseAddress)
957 len = (*win32_GetModuleFileNameExA) (current_process_handle,
963 DWORD err = GetLastError ();
964 error ("Error getting dll name: (error %d): %s\n",
965 (int) err, strwinerror (err));
972 dll_name_ret[0] = '\0';
976 typedef HANDLE (WINAPI *winapi_CreateToolhelp32Snapshot) (DWORD, DWORD);
977 typedef BOOL (WINAPI *winapi_Module32First) (HANDLE, LPMODULEENTRY32);
978 typedef BOOL (WINAPI *winapi_Module32Next) (HANDLE, LPMODULEENTRY32);
980 static winapi_CreateToolhelp32Snapshot win32_CreateToolhelp32Snapshot;
981 static winapi_Module32First win32_Module32First;
982 static winapi_Module32Next win32_Module32Next;
987 static int toolhelp_loaded = 0;
988 static HMODULE dll = NULL;
990 if (!toolhelp_loaded)
994 dll = GetModuleHandle (_T("KERNEL32.DLL"));
996 dll = GetModuleHandle (_T("COREDLL.DLL"));
1001 win32_CreateToolhelp32Snapshot =
1002 GETPROCADDRESS (dll, CreateToolhelp32Snapshot);
1003 win32_Module32First = GETPROCADDRESS (dll, Module32First);
1004 win32_Module32Next = GETPROCADDRESS (dll, Module32Next);
1007 return (win32_CreateToolhelp32Snapshot != NULL
1008 && win32_Module32First != NULL
1009 && win32_Module32Next != NULL);
1013 toolhelp_get_dll_name (DWORD BaseAddress, char *dll_name_ret)
1015 HANDLE snapshot_module;
1016 MODULEENTRY32 modEntry = { sizeof (MODULEENTRY32) };
1018 if (!load_toolhelp ())
1021 snapshot_module = win32_CreateToolhelp32Snapshot (TH32CS_SNAPMODULE,
1022 current_event.dwProcessId);
1023 if (snapshot_module == INVALID_HANDLE_VALUE)
1026 /* Ignore the first module, which is the exe. */
1027 if (!win32_Module32First (snapshot_module, &modEntry))
1030 while (win32_Module32Next (snapshot_module, &modEntry))
1031 if ((DWORD) modEntry.modBaseAddr == BaseAddress)
1034 wcstombs (dll_name_ret, modEntry.szExePath, MAX_PATH + 1);
1036 strcpy (dll_name_ret, modEntry.szExePath);
1038 CloseHandle (snapshot_module);
1043 CloseHandle (snapshot_module);
1048 handle_load_dll (void)
1050 LOAD_DLL_DEBUG_INFO *event = ¤t_event.u.LoadDll;
1051 char dll_buf[MAX_PATH + 1];
1052 char *dll_name = NULL;
1055 dll_buf[0] = dll_buf[sizeof (dll_buf) - 1] = '\0';
1057 if (!psapi_get_dll_name ((DWORD) (event->lpBaseOfDll), dll_buf)
1058 && !toolhelp_get_dll_name ((DWORD) (event->lpBaseOfDll), dll_buf))
1059 dll_buf[0] = dll_buf[sizeof (dll_buf) - 1] = '\0';
1063 if (*dll_name == '\0')
1064 dll_name = get_image_name (current_process_handle,
1065 event->lpImageName, event->fUnicode);
1069 /* The symbols in a dll are offset by 0x1000, which is the
1070 the offset from 0 of the first byte in an image - because
1071 of the file header and the section alignment. */
1073 load_addr = (DWORD) event->lpBaseOfDll + 0x1000;
1074 win32_add_one_solib (dll_name, load_addr);
1078 handle_unload_dll (void)
1080 CORE_ADDR load_addr =
1081 (CORE_ADDR) (DWORD) current_event.u.UnloadDll.lpBaseOfDll;
1082 load_addr += 0x1000;
1083 unloaded_dll (NULL, load_addr);
1087 handle_exception (struct target_waitstatus *ourstatus)
1089 DWORD code = current_event.u.Exception.ExceptionRecord.ExceptionCode;
1091 ourstatus->kind = TARGET_WAITKIND_STOPPED;
1095 case EXCEPTION_ACCESS_VIOLATION:
1096 OUTMSG2 (("EXCEPTION_ACCESS_VIOLATION"));
1097 ourstatus->value.sig = TARGET_SIGNAL_SEGV;
1099 case STATUS_STACK_OVERFLOW:
1100 OUTMSG2 (("STATUS_STACK_OVERFLOW"));
1101 ourstatus->value.sig = TARGET_SIGNAL_SEGV;
1103 case STATUS_FLOAT_DENORMAL_OPERAND:
1104 OUTMSG2 (("STATUS_FLOAT_DENORMAL_OPERAND"));
1105 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1107 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
1108 OUTMSG2 (("EXCEPTION_ARRAY_BOUNDS_EXCEEDED"));
1109 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1111 case STATUS_FLOAT_INEXACT_RESULT:
1112 OUTMSG2 (("STATUS_FLOAT_INEXACT_RESULT"));
1113 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1115 case STATUS_FLOAT_INVALID_OPERATION:
1116 OUTMSG2 (("STATUS_FLOAT_INVALID_OPERATION"));
1117 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1119 case STATUS_FLOAT_OVERFLOW:
1120 OUTMSG2 (("STATUS_FLOAT_OVERFLOW"));
1121 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1123 case STATUS_FLOAT_STACK_CHECK:
1124 OUTMSG2 (("STATUS_FLOAT_STACK_CHECK"));
1125 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1127 case STATUS_FLOAT_UNDERFLOW:
1128 OUTMSG2 (("STATUS_FLOAT_UNDERFLOW"));
1129 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1131 case STATUS_FLOAT_DIVIDE_BY_ZERO:
1132 OUTMSG2 (("STATUS_FLOAT_DIVIDE_BY_ZERO"));
1133 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1135 case STATUS_INTEGER_DIVIDE_BY_ZERO:
1136 OUTMSG2 (("STATUS_INTEGER_DIVIDE_BY_ZERO"));
1137 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1139 case STATUS_INTEGER_OVERFLOW:
1140 OUTMSG2 (("STATUS_INTEGER_OVERFLOW"));
1141 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1143 case EXCEPTION_BREAKPOINT:
1144 OUTMSG2 (("EXCEPTION_BREAKPOINT"));
1145 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
1147 /* Remove the initial breakpoint. */
1148 check_breakpoints ((CORE_ADDR) (long) current_event
1149 .u.Exception.ExceptionRecord.ExceptionAddress);
1153 OUTMSG2 (("DBG_CONTROL_C"));
1154 ourstatus->value.sig = TARGET_SIGNAL_INT;
1156 case DBG_CONTROL_BREAK:
1157 OUTMSG2 (("DBG_CONTROL_BREAK"));
1158 ourstatus->value.sig = TARGET_SIGNAL_INT;
1160 case EXCEPTION_SINGLE_STEP:
1161 OUTMSG2 (("EXCEPTION_SINGLE_STEP"));
1162 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
1164 case EXCEPTION_ILLEGAL_INSTRUCTION:
1165 OUTMSG2 (("EXCEPTION_ILLEGAL_INSTRUCTION"));
1166 ourstatus->value.sig = TARGET_SIGNAL_ILL;
1168 case EXCEPTION_PRIV_INSTRUCTION:
1169 OUTMSG2 (("EXCEPTION_PRIV_INSTRUCTION"));
1170 ourstatus->value.sig = TARGET_SIGNAL_ILL;
1172 case EXCEPTION_NONCONTINUABLE_EXCEPTION:
1173 OUTMSG2 (("EXCEPTION_NONCONTINUABLE_EXCEPTION"));
1174 ourstatus->value.sig = TARGET_SIGNAL_ILL;
1177 if (current_event.u.Exception.dwFirstChance)
1179 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
1182 OUTMSG2 (("gdbserver: unknown target exception 0x%08lx at 0x%08lx",
1183 current_event.u.Exception.ExceptionRecord.ExceptionCode,
1184 (DWORD) current_event.u.Exception.ExceptionRecord.
1186 ourstatus->value.sig = TARGET_SIGNAL_UNKNOWN;
1190 last_sig = ourstatus->value.sig;
1193 /* Get the next event from the child. */
1195 get_child_debug_event (struct target_waitstatus *ourstatus)
1199 last_sig = TARGET_SIGNAL_0;
1200 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
1202 /* Keep the wait time low enough for confortable remote interruption,
1203 but high enough so gdbserver doesn't become a bottleneck. */
1204 if (!(debug_event = WaitForDebugEvent (¤t_event, 250)))
1208 (struct thread_info *) find_inferior_id (&all_threads,
1209 current_event.dwThreadId);
1211 switch (current_event.dwDebugEventCode)
1213 case CREATE_THREAD_DEBUG_EVENT:
1214 OUTMSG2 (("gdbserver: kernel event CREATE_THREAD_DEBUG_EVENT "
1215 "for pid=%d tid=%x)\n",
1216 (unsigned) current_event.dwProcessId,
1217 (unsigned) current_event.dwThreadId));
1219 /* Record the existence of this thread. */
1220 child_add_thread (current_event.dwThreadId,
1221 current_event.u.CreateThread.hThread);
1224 case EXIT_THREAD_DEBUG_EVENT:
1225 OUTMSG2 (("gdbserver: kernel event EXIT_THREAD_DEBUG_EVENT "
1226 "for pid=%d tid=%x\n",
1227 (unsigned) current_event.dwProcessId,
1228 (unsigned) current_event.dwThreadId));
1229 child_delete_thread (current_event.dwThreadId);
1232 case CREATE_PROCESS_DEBUG_EVENT:
1233 OUTMSG2 (("gdbserver: kernel event CREATE_PROCESS_DEBUG_EVENT "
1234 "for pid=%d tid=%x\n",
1235 (unsigned) current_event.dwProcessId,
1236 (unsigned) current_event.dwThreadId));
1237 CloseHandle (current_event.u.CreateProcessInfo.hFile);
1239 current_process_handle = current_event.u.CreateProcessInfo.hProcess;
1240 main_thread_id = current_event.dwThreadId;
1242 ourstatus->kind = TARGET_WAITKIND_EXECD;
1243 ourstatus->value.execd_pathname = "Main executable";
1245 /* Add the main thread. */
1246 child_add_thread (main_thread_id,
1247 current_event.u.CreateProcessInfo.hThread);
1249 ourstatus->value.related_pid = current_event.dwThreadId;
1251 /* Windows CE doesn't set the initial breakpoint automatically
1252 like the desktop versions of Windows do. We add it explicitly
1253 here. It will be removed as soon as it is hit. */
1254 set_breakpoint_at ((CORE_ADDR) (long) current_event.u
1255 .CreateProcessInfo.lpStartAddress,
1256 delete_breakpoint_at);
1260 case EXIT_PROCESS_DEBUG_EVENT:
1261 OUTMSG2 (("gdbserver: kernel event EXIT_PROCESS_DEBUG_EVENT "
1262 "for pid=%d tid=%x\n",
1263 (unsigned) current_event.dwProcessId,
1264 (unsigned) current_event.dwThreadId));
1265 ourstatus->kind = TARGET_WAITKIND_EXITED;
1266 ourstatus->value.integer = current_event.u.ExitProcess.dwExitCode;
1267 CloseHandle (current_process_handle);
1268 current_process_handle = NULL;
1271 case LOAD_DLL_DEBUG_EVENT:
1272 OUTMSG2 (("gdbserver: kernel event LOAD_DLL_DEBUG_EVENT "
1273 "for pid=%d tid=%x\n",
1274 (unsigned) current_event.dwProcessId,
1275 (unsigned) current_event.dwThreadId));
1276 CloseHandle (current_event.u.LoadDll.hFile);
1279 ourstatus->kind = TARGET_WAITKIND_LOADED;
1280 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
1283 case UNLOAD_DLL_DEBUG_EVENT:
1284 OUTMSG2 (("gdbserver: kernel event UNLOAD_DLL_DEBUG_EVENT "
1285 "for pid=%d tid=%x\n",
1286 (unsigned) current_event.dwProcessId,
1287 (unsigned) current_event.dwThreadId));
1288 handle_unload_dll ();
1289 ourstatus->kind = TARGET_WAITKIND_LOADED;
1290 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
1293 case EXCEPTION_DEBUG_EVENT:
1294 OUTMSG2 (("gdbserver: kernel event EXCEPTION_DEBUG_EVENT "
1295 "for pid=%d tid=%x\n",
1296 (unsigned) current_event.dwProcessId,
1297 (unsigned) current_event.dwThreadId));
1298 handle_exception (ourstatus);
1301 case OUTPUT_DEBUG_STRING_EVENT:
1302 /* A message from the kernel (or Cygwin). */
1303 OUTMSG2 (("gdbserver: kernel event OUTPUT_DEBUG_STRING_EVENT "
1304 "for pid=%d tid=%x\n",
1305 (unsigned) current_event.dwProcessId,
1306 (unsigned) current_event.dwThreadId));
1307 handle_output_debug_string (ourstatus);
1311 OUTMSG2 (("gdbserver: kernel event unknown "
1312 "for pid=%d tid=%x code=%ld\n",
1313 (unsigned) current_event.dwProcessId,
1314 (unsigned) current_event.dwThreadId,
1315 current_event.dwDebugEventCode));
1320 (struct thread_info *) find_inferior_id (&all_threads,
1321 current_event.dwThreadId);
1324 /* Wait for the inferior process to change state.
1325 STATUS will be filled in with a response code to send to GDB.
1326 Returns the signal which caused the process to stop. */
1327 static unsigned char
1328 win32_wait (char *status)
1330 struct target_waitstatus our_status;
1336 /* Check if GDB sent us an interrupt request. */
1337 check_remote_input_interrupt_request ();
1339 get_child_debug_event (&our_status);
1341 switch (our_status.kind)
1343 case TARGET_WAITKIND_EXITED:
1344 OUTMSG2 (("Child exited with retcode = %x\n",
1345 our_status.value.integer));
1349 child_fetch_inferior_registers (-1);
1351 return our_status.value.integer;
1352 case TARGET_WAITKIND_STOPPED:
1353 case TARGET_WAITKIND_LOADED:
1354 OUTMSG2 (("Child Stopped with signal = %d \n",
1355 our_status.value.sig));
1359 child_fetch_inferior_registers (-1);
1361 if (our_status.kind == TARGET_WAITKIND_LOADED
1364 /* When gdb connects, we want to be stopped at the
1365 initial breakpoint, not in some dll load event. */
1366 child_continue (DBG_CONTINUE, -1);
1370 return our_status.value.sig;
1372 OUTMSG (("Ignoring unknown internal event, %d\n", our_status.kind));
1374 case TARGET_WAITKIND_SPURIOUS:
1375 case TARGET_WAITKIND_EXECD:
1376 /* do nothing, just continue */
1377 child_continue (DBG_CONTINUE, -1);
1383 /* Fetch registers from the inferior process.
1384 If REGNO is -1, fetch all registers; otherwise, fetch at least REGNO. */
1386 win32_fetch_inferior_registers (int regno)
1388 child_fetch_inferior_registers (regno);
1391 /* Store registers to the inferior process.
1392 If REGNO is -1, store all registers; otherwise, store at least REGNO. */
1394 win32_store_inferior_registers (int regno)
1396 child_store_inferior_registers (regno);
1399 /* Read memory from the inferior process. This should generally be
1400 called through read_inferior_memory, which handles breakpoint shadowing.
1401 Read LEN bytes at MEMADDR into a buffer at MYADDR. */
1403 win32_read_inferior_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
1405 return child_xfer_memory (memaddr, (char *) myaddr, len, 0, 0) != len;
1408 /* Write memory to the inferior process. This should generally be
1409 called through write_inferior_memory, which handles breakpoint shadowing.
1410 Write LEN bytes from the buffer at MYADDR to MEMADDR.
1411 Returns 0 on success and errno on failure. */
1413 win32_write_inferior_memory (CORE_ADDR memaddr, const unsigned char *myaddr,
1416 return child_xfer_memory (memaddr, (char *) myaddr, len, 1, 0) != len;
1419 /* Send an interrupt request to the inferior process. */
1421 win32_request_interrupt (void)
1423 winapi_DebugBreakProcess DebugBreakProcess;
1424 winapi_GenerateConsoleCtrlEvent GenerateConsoleCtrlEvent;
1427 HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
1429 HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
1432 GenerateConsoleCtrlEvent = GETPROCADDRESS (dll, GenerateConsoleCtrlEvent);
1434 if (GenerateConsoleCtrlEvent != NULL
1435 && GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, current_process_id))
1438 /* GenerateConsoleCtrlEvent can fail if process id being debugged is
1439 not a process group id.
1440 Fallback to XP/Vista 'DebugBreakProcess', which generates a
1441 breakpoint exception in the interior process. */
1443 DebugBreakProcess = GETPROCADDRESS (dll, DebugBreakProcess);
1445 if (DebugBreakProcess != NULL
1446 && DebugBreakProcess (current_process_handle))
1449 OUTMSG (("Could not interrupt process.\n"));
1453 win32_arch_string (void)
1455 return the_low_target.arch_string;
1458 static struct target_ops win32_target_ops = {
1459 win32_create_inferior,
1467 win32_fetch_inferior_registers,
1468 win32_store_inferior_registers,
1469 win32_read_inferior_memory,
1470 win32_write_inferior_memory,
1472 win32_request_interrupt,
1483 /* Initialize the Win32 backend. */
1485 initialize_low (void)
1487 set_target_ops (&win32_target_ops);
1488 if (the_low_target.breakpoint != NULL)
1489 set_breakpoint_data (the_low_target.breakpoint,
1490 the_low_target.breakpoint_len);