]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/gdbserver/win32-low.c
* server.c (main): Don't report dll events on the initial
[thirdparty/binutils-gdb.git] / gdb / gdbserver / win32-low.c
CommitLineData
b80864fb 1/* Low level interface to Windows debugging, for gdbserver.
6aba47ca 2 Copyright (C) 2006, 2007 Free Software Foundation, Inc.
b80864fb
DJ
3
4 Contributed by Leo Zayas. Based on "win32-nat.c" from GDB.
5
6 This file is part of GDB.
7
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
a9762ec7 10 the Free Software Foundation; either version 3 of the License, or
b80864fb
DJ
11 (at your option) any later version.
12
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.
17
18 You should have received a copy of the GNU General Public License
a9762ec7 19 along with this program. If not, see <http://www.gnu.org/licenses/>. */
b80864fb
DJ
20
21#include "server.h"
22#include "regcache.h"
23#include "gdb/signals.h"
ed50f18f
PA
24#include "mem-break.h"
25#include "win32-low.h"
b80864fb
DJ
26
27#include <windows.h>
ed50f18f 28#include <winnt.h>
b80864fb 29#include <imagehlp.h>
255e7678 30#include <tlhelp32.h>
b80864fb
DJ
31#include <psapi.h>
32#include <sys/param.h>
33#include <malloc.h>
34#include <process.h>
35
36#ifndef USE_WIN32API
37#include <sys/cygwin.h>
38#endif
39
40#define LOG 0
41
42#define OUTMSG(X) do { printf X; fflush (stdout); } while (0)
43#if LOG
44#define OUTMSG2(X) do { printf X; fflush (stdout); } while (0)
45#else
ed50f18f
PA
46#define OUTMSG2(X) do ; while (0)
47#endif
48
49#ifndef _T
50#define _T(x) TEXT (x)
51#endif
52
53#ifndef COUNTOF
54#define COUNTOF(STR) (sizeof (STR) / sizeof ((STR)[0]))
b80864fb
DJ
55#endif
56
bf914831
PA
57#ifdef _WIN32_WCE
58# define GETPROCADDRESS(DLL, PROC) \
59 ((winapi_ ## PROC) GetProcAddress (DLL, TEXT (#PROC)))
60#else
61# define GETPROCADDRESS(DLL, PROC) \
62 ((winapi_ ## PROC) GetProcAddress (DLL, #PROC))
63#endif
64
b80864fb
DJ
65int using_threads = 1;
66
67/* Globals. */
68static HANDLE current_process_handle = NULL;
69static DWORD current_process_id = 0;
70static enum target_signal last_sig = TARGET_SIGNAL_0;
71
72/* The current debug event from WaitForDebugEvent. */
73static DEBUG_EVENT current_event;
74
4d5d1aaa
PA
75/* Non zero if an interrupt request is to be satisfied by suspending
76 all threads. */
77static int soft_interrupt_requested = 0;
78
79/* Non zero if the inferior is stopped in a simulated breakpoint done
80 by suspending all the threads. */
81static int faked_breakpoint = 0;
82
ed50f18f 83#define NUM_REGS (the_low_target.num_regs)
b80864fb 84
bf914831
PA
85typedef BOOL WINAPI (*winapi_DebugActiveProcessStop) (DWORD dwProcessId);
86typedef BOOL WINAPI (*winapi_DebugSetProcessKillOnExit) (BOOL KillOnExit);
7390519e
PA
87typedef BOOL WINAPI (*winapi_DebugBreakProcess) (HANDLE);
88typedef BOOL WINAPI (*winapi_GenerateConsoleCtrlEvent) (DWORD, DWORD);
b80864fb 89
b80864fb
DJ
90static DWORD main_thread_id = 0;
91
34b34921
PA
92static void win32_resume (struct thread_resume *resume_info);
93
b80864fb
DJ
94/* Get the thread ID from the current selected inferior (the current
95 thread). */
96static DWORD
97current_inferior_tid (void)
98{
41093d81 99 win32_thread_info *th = inferior_target_data (current_inferior);
b80864fb
DJ
100 return th->tid;
101}
102
9c6c8194
PA
103/* Get the thread context of the thread associated with TH. */
104
105static void
106win32_get_thread_context (win32_thread_info *th)
107{
108 memset (&th->context, 0, sizeof (CONTEXT));
109 (*the_low_target.get_thread_context) (th, &current_event);
110#ifdef _WIN32_WCE
111 memcpy (&th->base_context, &th->context, sizeof (CONTEXT));
112#endif
113}
114
115/* Set the thread context of the thread associated with TH. */
116
117static void
118win32_set_thread_context (win32_thread_info *th)
119{
120#ifdef _WIN32_WCE
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)
132#endif
133 (*the_low_target.set_thread_context) (th, &current_event);
134}
135
b80864fb
DJ
136/* Find a thread record given a thread id. If GET_CONTEXT is set then
137 also retrieve the context for this thread. */
41093d81 138static win32_thread_info *
b80864fb
DJ
139thread_rec (DWORD id, int get_context)
140{
141 struct thread_info *thread;
41093d81 142 win32_thread_info *th;
b80864fb
DJ
143
144 thread = (struct thread_info *) find_inferior_id (&all_threads, id);
145 if (thread == NULL)
146 return NULL;
147
148 th = inferior_target_data (thread);
c436e841 149 if (get_context && th->context.ContextFlags == 0)
b80864fb 150 {
c436e841
PA
151 if (!th->suspended)
152 {
153 if (SuspendThread (th->h) == (DWORD) -1)
154 {
155 DWORD err = GetLastError ();
156 OUTMSG (("warning: SuspendThread failed in thread_rec, "
157 "(error %d): %s\n", (int) err, strwinerror (err)));
158 }
159 else
160 th->suspended = 1;
161 }
b80864fb 162
9c6c8194 163 win32_get_thread_context (th);
b80864fb
DJ
164 }
165
166 return th;
167}
168
169/* Add a thread to the thread list. */
41093d81 170static win32_thread_info *
b80864fb
DJ
171child_add_thread (DWORD tid, HANDLE h)
172{
41093d81 173 win32_thread_info *th;
b80864fb
DJ
174
175 if ((th = thread_rec (tid, FALSE)))
176 return th;
177
4d5d1aaa 178 th = calloc (1, sizeof (*th));
b80864fb
DJ
179 th->tid = tid;
180 th->h = h;
181
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 ());
186
34b34921
PA
187 if (the_low_target.thread_added != NULL)
188 (*the_low_target.thread_added) (th);
b80864fb
DJ
189
190 return th;
191}
192
193/* Delete a thread from the list of threads. */
194static void
195delete_thread_info (struct inferior_list_entry *thread)
196{
41093d81 197 win32_thread_info *th = inferior_target_data ((struct thread_info *) thread);
b80864fb
DJ
198
199 remove_thread ((struct thread_info *) thread);
200 CloseHandle (th->h);
201 free (th);
202}
203
204/* Delete a thread from the list of threads. */
205static void
206child_delete_thread (DWORD id)
207{
208 struct inferior_list_entry *thread;
209
210 /* If the last thread is exiting, just return. */
211 if (all_threads.head == all_threads.tail)
212 return;
213
214 thread = find_inferior_id (&all_threads, id);
215 if (thread == NULL)
216 return;
217
218 delete_thread_info (thread);
219}
220
221/* Transfer memory from/to the debugged process. */
222static int
223child_xfer_memory (CORE_ADDR memaddr, char *our, int len,
224 int write, struct target_ops *target)
225{
226 SIZE_T done;
227 long addr = (long) memaddr;
228
229 if (write)
230 {
231 WriteProcessMemory (current_process_handle, (LPVOID) addr,
232 (LPCVOID) our, len, &done);
233 FlushInstructionCache (current_process_handle, (LPCVOID) addr, len);
234 }
235 else
236 {
237 ReadProcessMemory (current_process_handle, (LPCVOID) addr, (LPVOID) our,
238 len, &done);
239 }
240 return done;
241}
242
243/* Generally, what has the program done? */
244enum target_waitkind
245{
246 /* The program has exited. The exit status is in value.integer. */
247 TARGET_WAITKIND_EXITED,
248
249 /* The program has stopped with a signal. Which signal is in
250 value.sig. */
251 TARGET_WAITKIND_STOPPED,
252
255e7678
DJ
253 /* The program is letting us know that it dynamically loaded
254 or unloaded something. */
b80864fb
DJ
255 TARGET_WAITKIND_LOADED,
256
257 /* The program has exec'ed a new executable file. The new file's
258 pathname is pointed to by value.execd_pathname. */
b80864fb
DJ
259 TARGET_WAITKIND_EXECD,
260
7390519e
PA
261 /* Nothing interesting happened, but we stopped anyway. We take the
262 chance to check if GDB requested an interrupt. */
b80864fb
DJ
263 TARGET_WAITKIND_SPURIOUS,
264};
265
266struct target_waitstatus
267{
268 enum target_waitkind kind;
269
270 /* Forked child pid, execd pathname, exit status or signal number. */
271 union
272 {
273 int integer;
274 enum target_signal sig;
275 int related_pid;
276 char *execd_pathname;
277 int syscall_id;
278 }
279 value;
280};
281
ed50f18f 282/* Clear out any old thread list and reinitialize it to a pristine
b80864fb
DJ
283 state. */
284static void
285child_init_thread_list (void)
286{
287 for_each_inferior (&all_threads, delete_thread_info);
288}
289
290static void
291do_initial_child_stuff (DWORD pid)
292{
b80864fb
DJ
293 last_sig = TARGET_SIGNAL_0;
294
b80864fb
DJ
295 memset (&current_event, 0, sizeof (current_event));
296
297 child_init_thread_list ();
ed50f18f
PA
298
299 if (the_low_target.initial_stuff != NULL)
300 (*the_low_target.initial_stuff) ();
b80864fb
DJ
301}
302
303/* Resume all artificially suspended threads if we are continuing
304 execution. */
305static int
306continue_one_thread (struct inferior_list_entry *this_thread, void *id_ptr)
307{
308 struct thread_info *thread = (struct thread_info *) this_thread;
309 int thread_id = * (int *) id_ptr;
41093d81 310 win32_thread_info *th = inferior_target_data (thread);
b80864fb
DJ
311
312 if ((thread_id == -1 || thread_id == th->tid)
c436e841 313 && th->suspended)
b80864fb 314 {
34b34921 315 if (th->context.ContextFlags)
b80864fb 316 {
9c6c8194 317 win32_set_thread_context (th);
b80864fb
DJ
318 th->context.ContextFlags = 0;
319 }
34b34921 320
c436e841
PA
321 if (ResumeThread (th->h) == (DWORD) -1)
322 {
323 DWORD err = GetLastError ();
324 OUTMSG (("warning: ResumeThread failed in continue_one_thread, "
325 "(error %d): %s\n", (int) err, strwinerror (err)));
326 }
327 th->suspended = 0;
b80864fb
DJ
328 }
329
330 return 0;
331}
332
333static BOOL
334child_continue (DWORD continue_status, int thread_id)
335{
4d5d1aaa
PA
336 /* The inferior will only continue after the ContinueDebugEvent
337 call. */
338 find_inferior (&all_threads, continue_one_thread, &thread_id);
339 faked_breakpoint = 0;
b80864fb 340
4d5d1aaa
PA
341 if (!ContinueDebugEvent (current_event.dwProcessId,
342 current_event.dwThreadId,
343 continue_status))
344 return FALSE;
b80864fb 345
4d5d1aaa 346 return TRUE;
b80864fb
DJ
347}
348
b80864fb
DJ
349/* Fetch register(s) from the current thread context. */
350static void
351child_fetch_inferior_registers (int r)
352{
353 int regno;
41093d81 354 win32_thread_info *th = thread_rec (current_inferior_tid (), TRUE);
b80864fb
DJ
355 if (r == -1 || r == 0 || r > NUM_REGS)
356 child_fetch_inferior_registers (NUM_REGS);
357 else
358 for (regno = 0; regno < r; regno++)
34b34921 359 (*the_low_target.fetch_inferior_register) (th, regno);
b80864fb
DJ
360}
361
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. */
364static void
365child_store_inferior_registers (int r)
366{
367 int regno;
41093d81 368 win32_thread_info *th = thread_rec (current_inferior_tid (), TRUE);
b80864fb
DJ
369 if (r == -1 || r == 0 || r > NUM_REGS)
370 child_store_inferior_registers (NUM_REGS);
371 else
372 for (regno = 0; regno < r; regno++)
34b34921 373 (*the_low_target.store_inferior_register) (th, regno);
b80864fb
DJ
374}
375
ed50f18f
PA
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.
379
380 The string pointed to shall not be modified by the application,
381 but may be overwritten by a subsequent call to strwinerror
382
383 The strwinerror function does not change the current setting
384 of GetLastError. */
385
386char *
387strwinerror (DWORD error)
388{
389 static char buf[1024];
390 TCHAR *msgbuf;
391 DWORD lasterr = GetLastError ();
392 DWORD chars = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
393 | FORMAT_MESSAGE_ALLOCATE_BUFFER,
394 NULL,
395 error,
396 0, /* Default language */
397 (LPVOID)&msgbuf,
398 0,
399 NULL);
400 if (chars != 0)
401 {
402 /* If there is an \r\n appended, zap it. */
403 if (chars >= 2
404 && msgbuf[chars - 2] == '\r'
405 && msgbuf[chars - 1] == '\n')
406 {
407 chars -= 2;
408 msgbuf[chars] = 0;
409 }
410
411 if (chars > ((COUNTOF (buf)) - 1))
412 {
413 chars = COUNTOF (buf) - 1;
414 msgbuf [chars] = 0;
415 }
416
417#ifdef UNICODE
418 wcstombs (buf, msgbuf, chars + 1);
419#else
420 strncpy (buf, msgbuf, chars + 1);
421#endif
422 LocalFree (msgbuf);
423 }
424 else
425 sprintf (buf, "unknown win32 error (%ld)", error);
426
427 SetLastError (lasterr);
428 return buf;
429}
430
aec18585
PA
431static BOOL
432create_process (const char *program, char *args,
433 DWORD flags, PROCESS_INFORMATION *pi)
434{
435 BOOL ret;
436
437#ifdef _WIN32_WCE
438 wchar_t *p, *wprogram, *wargs;
439 size_t argslen;
440
441 wprogram = alloca ((strlen (program) + 1) * sizeof (wchar_t));
442 mbstowcs (wprogram, program, strlen (program) + 1);
443
444 for (p = wprogram; *p; ++p)
445 if (L'/' == *p)
446 *p = L'\\';
447
448 argslen = strlen (args);
449 wargs = alloca ((argslen + 1) * sizeof (wchar_t));
450 mbstowcs (wargs, args, argslen + 1);
451
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 */
461 pi); /* proc info */
462#else
463 STARTUPINFOA si = { sizeof (STARTUPINFOA) };
464
465 ret = CreateProcessA (program, /* image name */
466 args, /* command line */
467 NULL, /* security */
468 NULL, /* thread */
469 TRUE, /* inherit handles */
470 flags, /* start flags */
471 NULL, /* environment */
472 NULL, /* current directory */
473 &si, /* start info */
474 pi); /* proc info */
475#endif
476
477 return ret;
478}
479
b80864fb
DJ
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. */
486static int
487win32_create_inferior (char *program, char **program_args)
488{
489#ifndef USE_WIN32API
490 char real_path[MAXPATHLEN];
491 char *orig_path, *new_path, *path_ptr;
492#endif
b80864fb
DJ
493 BOOL ret;
494 DWORD flags;
495 char *args;
496 int argslen;
497 int argc;
ed50f18f 498 PROCESS_INFORMATION pi;
aec18585 499 DWORD err;
b80864fb
DJ
500
501 if (!program)
502 error ("No executable specified, specify executable to debug.\n");
503
b80864fb
DJ
504 flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS;
505
506#ifndef USE_WIN32API
507 orig_path = NULL;
508 path_ptr = getenv ("PATH");
509 if (path_ptr)
510 {
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);
516 }
517 cygwin_conv_to_win32_path (program, real_path);
518 program = real_path;
519#endif
520
ed50f18f 521 argslen = 1;
b80864fb
DJ
522 for (argc = 1; program_args[argc]; argc++)
523 argslen += strlen (program_args[argc]) + 1;
524 args = alloca (argslen);
ed50f18f 525 args[0] = '\0';
b80864fb
DJ
526 for (argc = 1; program_args[argc]; argc++)
527 {
528 /* FIXME: Can we do better about quoting? How does Cygwin
529 handle this? */
530 strcat (args, " ");
531 strcat (args, program_args[argc]);
532 }
ed50f18f 533 OUTMSG2 (("Command line is \"%s\"\n", args));
b80864fb 534
ed50f18f 535#ifdef CREATE_NEW_PROCESS_GROUP
b80864fb 536 flags |= CREATE_NEW_PROCESS_GROUP;
ed50f18f 537#endif
b80864fb 538
aec18585
PA
539 ret = create_process (program, args, flags, &pi);
540 err = GetLastError ();
541 if (!ret && err == ERROR_FILE_NOT_FOUND)
542 {
543 char *exename = alloca (strlen (program) + 5);
544 strcat (strcpy (exename, program), ".exe");
545 ret = create_process (exename, args, flags, &pi);
546 err = GetLastError ();
547 }
b80864fb
DJ
548
549#ifndef USE_WIN32API
550 if (orig_path)
551 setenv ("PATH", orig_path, 1);
552#endif
553
554 if (!ret)
555 {
ed50f18f
PA
556 error ("Error creating process \"%s%s\", (error %d): %s\n",
557 program, args, (int) err, strwinerror (err));
b80864fb
DJ
558 }
559 else
560 {
561 OUTMSG2 (("Process created: %s\n", (char *) args));
562 }
563
ed50f18f
PA
564#ifndef _WIN32_WCE
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. */
b80864fb 568 CloseHandle (pi.hThread);
ed50f18f 569#endif
b80864fb
DJ
570
571 current_process_handle = pi.hProcess;
572 current_process_id = pi.dwProcessId;
573
574 do_initial_child_stuff (current_process_id);
575
576 return current_process_id;
577}
578
579/* Attach to a running process.
580 PID is the process ID to attach to, specified by the user
581 or a higher layer. */
582static int
583win32_attach (unsigned long pid)
584{
5ca906e6 585 HANDLE h;
bf914831 586 winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit = NULL;
5ca906e6 587 DWORD err;
ed50f18f
PA
588#ifdef _WIN32_WCE
589 HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
590#else
591 HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
592#endif
bf914831 593 DebugSetProcessKillOnExit = GETPROCADDRESS (dll, DebugSetProcessKillOnExit);
b80864fb 594
5ca906e6
PA
595 h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
596 if (h != NULL)
1d5315fe 597 {
5ca906e6
PA
598 if (DebugActiveProcess (pid))
599 {
600 if (DebugSetProcessKillOnExit != NULL)
601 DebugSetProcessKillOnExit (FALSE);
602
603 current_process_handle = h;
604 current_process_id = pid;
605 do_initial_child_stuff (pid);
606 return 0;
607 }
608
609 CloseHandle (h);
b80864fb
DJ
610 }
611
5ca906e6
PA
612 err = GetLastError ();
613 error ("Attach to process failed (error %d): %s\n",
614 (int) err, strwinerror (err));
b80864fb
DJ
615}
616
bce7165d
PA
617/* Handle OUTPUT_DEBUG_STRING_EVENT from child process. */
618static void
619handle_output_debug_string (struct target_waitstatus *ourstatus)
620{
621#define READ_BUFFER_LEN 1024
622 CORE_ADDR addr;
623 char s[READ_BUFFER_LEN + 1] = { 0 };
624 DWORD nbytes = current_event.u.DebugString.nDebugStringLength;
625
626 if (nbytes == 0)
627 return;
628
629 if (nbytes > READ_BUFFER_LEN)
630 nbytes = READ_BUFFER_LEN;
631
632 addr = (CORE_ADDR) (size_t) current_event.u.DebugString.lpDebugStringData;
633
634 if (current_event.u.DebugString.fUnicode)
635 {
636 /* The event tells us how many bytes, not chars, even
637 in Unicode. */
638 WCHAR buffer[(READ_BUFFER_LEN + 1) / sizeof (WCHAR)] = { 0 };
639 if (read_inferior_memory (addr, (unsigned char *) buffer, nbytes) != 0)
640 return;
641 wcstombs (s, buffer, (nbytes + 1) / sizeof (WCHAR));
642 }
643 else
644 {
645 if (read_inferior_memory (addr, (unsigned char *) s, nbytes) != 0)
646 return;
647 }
648
649 if (strncmp (s, "cYg", 3) != 0)
45e2715e
PA
650 {
651 if (!server_waiting)
652 {
653 OUTMSG2(("%s", s));
654 return;
655 }
656
657 monitor_output (s);
658 }
bce7165d
PA
659#undef READ_BUFFER_LEN
660}
661
b80864fb
DJ
662/* Kill all inferiors. */
663static void
664win32_kill (void)
665{
ed50f18f
PA
666 win32_thread_info *current_thread;
667
9d606399
DJ
668 if (current_process_handle == NULL)
669 return;
670
b80864fb
DJ
671 TerminateProcess (current_process_handle, 0);
672 for (;;)
673 {
674 if (!child_continue (DBG_CONTINUE, -1))
675 break;
676 if (!WaitForDebugEvent (&current_event, INFINITE))
677 break;
678 if (current_event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
679 break;
bce7165d
PA
680 else if (current_event.dwDebugEventCode == OUTPUT_DEBUG_STRING_EVENT)
681 {
682 struct target_waitstatus our_status = { 0 };
683 handle_output_debug_string (&our_status);
684 }
b80864fb 685 }
ed50f18f
PA
686
687 CloseHandle (current_process_handle);
688
689 current_thread = inferior_target_data (current_inferior);
690 if (current_thread && current_thread->h)
691 {
692 /* This may fail in an attached process, so don't check. */
693 (void) CloseHandle (current_thread->h);
694 }
b80864fb
DJ
695}
696
697/* Detach from all inferiors. */
444d6139 698static int
b80864fb
DJ
699win32_detach (void)
700{
444d6139
PA
701 HANDLE h;
702
bf914831
PA
703 winapi_DebugActiveProcessStop DebugActiveProcessStop = NULL;
704 winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit = NULL;
ed50f18f
PA
705#ifdef _WIN32_WCE
706 HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
707#else
708 HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
709#endif
bf914831
PA
710 DebugActiveProcessStop = GETPROCADDRESS (dll, DebugActiveProcessStop);
711 DebugSetProcessKillOnExit = GETPROCADDRESS (dll, DebugSetProcessKillOnExit);
b80864fb 712
444d6139
PA
713 if (DebugSetProcessKillOnExit == NULL
714 || DebugActiveProcessStop == NULL)
715 return -1;
b80864fb 716
444d6139
PA
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,
720 FALSE,
721 current_process_id)) == NULL)
722 {
723 /* The process died. */
724 return -1;
725 }
726
727 {
728 struct thread_resume resume;
729 resume.thread = -1;
730 resume.step = 0;
731 resume.sig = 0;
732 resume.leave_stopped = 0;
733 win32_resume (&resume);
734 }
735
736 if (!DebugActiveProcessStop (current_process_id))
737 {
738 CloseHandle (h);
739 return -1;
740 }
741 DebugSetProcessKillOnExit (FALSE);
742
743 current_process_handle = h;
744 return 0;
745}
746
747/* Wait for inferiors to end. */
748static void
749win32_join (void)
750{
751 if (current_process_id == 0
752 || current_process_handle == NULL)
753 return;
754
755 WaitForSingleObject (current_process_handle, INFINITE);
756 CloseHandle (current_process_handle);
757
758 current_process_handle = NULL;
759 current_process_id = 0;
b80864fb
DJ
760}
761
762/* Return 1 iff the thread with thread ID TID is alive. */
763static int
764win32_thread_alive (unsigned long tid)
765{
766 int res;
767
768 /* Our thread list is reliable; don't bother to poll target
769 threads. */
770 if (find_inferior_id (&all_threads, tid) != NULL)
771 res = 1;
772 else
773 res = 0;
774 return res;
775}
776
777/* Resume the inferior process. RESUME_INFO describes how we want
778 to resume. */
779static void
780win32_resume (struct thread_resume *resume_info)
781{
782 DWORD tid;
783 enum target_signal sig;
784 int step;
41093d81 785 win32_thread_info *th;
b80864fb
DJ
786 DWORD continue_status = DBG_CONTINUE;
787
788 /* This handles the very limited set of resume packets that GDB can
789 currently produce. */
790
791 if (resume_info[0].thread == -1)
792 tid = -1;
793 else if (resume_info[1].thread == -1 && !resume_info[1].leave_stopped)
794 tid = -1;
795 else
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;
799
800 if (resume_info[0].thread != -1)
801 {
802 sig = resume_info[0].sig;
803 step = resume_info[0].step;
804 }
805 else
806 {
807 sig = 0;
808 step = 0;
809 }
810
811 if (sig != TARGET_SIGNAL_0)
812 {
813 if (current_event.dwDebugEventCode != EXCEPTION_DEBUG_EVENT)
814 {
815 OUTMSG (("Cannot continue with signal %d here.\n", sig));
816 }
817 else if (sig == last_sig)
818 continue_status = DBG_EXCEPTION_NOT_HANDLED;
819 else
820 OUTMSG (("Can only continue with recieved signal %d.\n", last_sig));
821 }
822
823 last_sig = TARGET_SIGNAL_0;
824
825 /* Get context for the currently selected thread. */
826 th = thread_rec (current_event.dwThreadId, FALSE);
827 if (th)
828 {
829 if (th->context.ContextFlags)
830 {
b80864fb
DJ
831 /* Move register values from the inferior into the thread
832 context structure. */
833 regcache_invalidate ();
834
835 if (step)
ed50f18f
PA
836 {
837 if (the_low_target.single_step != NULL)
838 (*the_low_target.single_step) (th);
839 else
840 error ("Single stepping is not supported "
841 "in this configuration.\n");
842 }
34b34921 843
9c6c8194 844 win32_set_thread_context (th);
b80864fb
DJ
845 th->context.ContextFlags = 0;
846 }
847 }
848
849 /* Allow continuing with the same signal that interrupted us.
850 Otherwise complain. */
851
852 child_continue (continue_status, tid);
853}
854
255e7678
DJ
855static void
856win32_add_one_solib (const char *name, CORE_ADDR load_addr)
857{
858 char buf[MAX_PATH + 1];
859 char buf2[MAX_PATH + 1];
860
861#ifdef _WIN32_WCE
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);
866#else
867 WIN32_FIND_DATAA w32_fd;
868 HANDLE h = FindFirstFileA (name, &w32_fd);
869#endif
870
871 if (h == INVALID_HANDLE_VALUE)
872 strcpy (buf, name);
873 else
874 {
875 FindClose (h);
876 strcpy (buf, name);
877#ifndef _WIN32_WCE
878 {
879 char cwd[MAX_PATH + 1];
880 char *p;
881 if (GetCurrentDirectoryA (MAX_PATH + 1, cwd))
882 {
883 p = strrchr (buf, '\\');
884 if (p)
885 p[1] = '\0';
886 SetCurrentDirectoryA (buf);
887 GetFullPathNameA (w32_fd.cFileName, MAX_PATH, buf, &p);
888 SetCurrentDirectoryA (cwd);
889 }
890 }
891#endif
892 }
893
894#ifdef __CYGWIN__
895 cygwin_conv_to_posix_path (buf, buf2);
896#else
897 strcpy (buf2, buf);
898#endif
899
900 loaded_dll (buf2, load_addr);
901}
902
903static char *
904get_image_name (HANDLE h, void *address, int unicode)
905{
906 static char buf[(2 * MAX_PATH) + 1];
907 DWORD size = unicode ? sizeof (WCHAR) : sizeof (char);
908 char *address_ptr;
909 int len = 0;
910 char b[2];
911 DWORD done;
912
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. */
916 if (address == NULL)
917 return NULL;
918
919#ifdef _WIN32_WCE
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;
923#else
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)
929 || !address_ptr)
930 return NULL;
931#endif
932
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)
936 continue;
937
938 if (!unicode)
939 ReadProcessMemory (h, address_ptr, buf, len, &done);
940 else
941 {
942 WCHAR *unicode_address = (WCHAR *) alloca (len * sizeof (WCHAR));
943 ReadProcessMemory (h, address_ptr, unicode_address, len * sizeof (WCHAR),
944 &done);
945
946 WideCharToMultiByte (CP_ACP, 0, unicode_address, len, buf, len, 0, 0);
947 }
948
949 return buf;
950}
951
952typedef BOOL (WINAPI *winapi_EnumProcessModules) (HANDLE, HMODULE *,
953 DWORD, LPDWORD);
954typedef BOOL (WINAPI *winapi_GetModuleInformation) (HANDLE, HMODULE,
955 LPMODULEINFO, DWORD);
956typedef DWORD (WINAPI *winapi_GetModuleFileNameExA) (HANDLE, HMODULE,
957 LPSTR, DWORD);
958
959static winapi_EnumProcessModules win32_EnumProcessModules;
960static winapi_GetModuleInformation win32_GetModuleInformation;
961static winapi_GetModuleFileNameExA win32_GetModuleFileNameExA;
962
963static BOOL
964load_psapi (void)
965{
966 static int psapi_loaded = 0;
967 static HMODULE dll = NULL;
968
969 if (!psapi_loaded)
970 {
971 psapi_loaded = 1;
972 dll = LoadLibrary (TEXT("psapi.dll"));
973 if (!dll)
974 return FALSE;
975 win32_EnumProcessModules =
976 GETPROCADDRESS (dll, EnumProcessModules);
977 win32_GetModuleInformation =
978 GETPROCADDRESS (dll, GetModuleInformation);
979 win32_GetModuleFileNameExA =
980 GETPROCADDRESS (dll, GetModuleFileNameExA);
981 }
982
983 return (win32_EnumProcessModules != NULL
984 && win32_GetModuleInformation != NULL
985 && win32_GetModuleFileNameExA != NULL);
986}
987
988static int
989psapi_get_dll_name (DWORD BaseAddress, char *dll_name_ret)
990{
991 DWORD len;
992 MODULEINFO mi;
993 size_t i;
994 HMODULE dh_buf[1];
995 HMODULE *DllHandle = dh_buf;
996 DWORD cbNeeded;
997 BOOL ok;
998
999 if (!load_psapi ())
1000 goto failed;
1001
1002 cbNeeded = 0;
1003 ok = (*win32_EnumProcessModules) (current_process_handle,
1004 DllHandle,
1005 sizeof (HMODULE),
1006 &cbNeeded);
1007
1008 if (!ok || !cbNeeded)
1009 goto failed;
1010
1011 DllHandle = (HMODULE *) alloca (cbNeeded);
1012 if (!DllHandle)
1013 goto failed;
1014
1015 ok = (*win32_EnumProcessModules) (current_process_handle,
1016 DllHandle,
1017 cbNeeded,
1018 &cbNeeded);
1019 if (!ok)
1020 goto failed;
1021
1022 for (i = 0; i < ((size_t) cbNeeded / sizeof (HMODULE)); i++)
1023 {
1024 if (!(*win32_GetModuleInformation) (current_process_handle,
1025 DllHandle[i],
1026 &mi,
1027 sizeof (mi)))
1028 {
1029 DWORD err = GetLastError ();
1030 error ("Can't get module info: (error %d): %s\n",
1031 (int) err, strwinerror (err));
1032 }
1033
1034 if ((DWORD) (mi.lpBaseOfDll) == BaseAddress)
1035 {
1036 len = (*win32_GetModuleFileNameExA) (current_process_handle,
1037 DllHandle[i],
1038 dll_name_ret,
1039 MAX_PATH);
1040 if (len == 0)
1041 {
1042 DWORD err = GetLastError ();
1043 error ("Error getting dll name: (error %d): %s\n",
1044 (int) err, strwinerror (err));
1045 }
1046 return 1;
1047 }
1048 }
1049
1050failed:
1051 dll_name_ret[0] = '\0';
1052 return 0;
1053}
1054
1055typedef HANDLE (WINAPI *winapi_CreateToolhelp32Snapshot) (DWORD, DWORD);
1056typedef BOOL (WINAPI *winapi_Module32First) (HANDLE, LPMODULEENTRY32);
1057typedef BOOL (WINAPI *winapi_Module32Next) (HANDLE, LPMODULEENTRY32);
1058
1059static winapi_CreateToolhelp32Snapshot win32_CreateToolhelp32Snapshot;
1060static winapi_Module32First win32_Module32First;
1061static winapi_Module32Next win32_Module32Next;
6b3d9b83
PA
1062#ifdef _WIN32_WCE
1063typedef BOOL (WINAPI *winapi_CloseToolhelp32Snapshot) (HANDLE);
1064static winapi_CloseToolhelp32Snapshot win32_CloseToolhelp32Snapshot;
1065#endif
255e7678
DJ
1066
1067static BOOL
1068load_toolhelp (void)
1069{
1070 static int toolhelp_loaded = 0;
1071 static HMODULE dll = NULL;
1072
1073 if (!toolhelp_loaded)
1074 {
1075 toolhelp_loaded = 1;
1076#ifndef _WIN32_WCE
1077 dll = GetModuleHandle (_T("KERNEL32.DLL"));
1078#else
6b3d9b83 1079 dll = LoadLibrary (L"TOOLHELP.DLL");
255e7678
DJ
1080#endif
1081 if (!dll)
1082 return FALSE;
1083
1084 win32_CreateToolhelp32Snapshot =
1085 GETPROCADDRESS (dll, CreateToolhelp32Snapshot);
1086 win32_Module32First = GETPROCADDRESS (dll, Module32First);
1087 win32_Module32Next = GETPROCADDRESS (dll, Module32Next);
6b3d9b83
PA
1088#ifdef _WIN32_WCE
1089 win32_CloseToolhelp32Snapshot =
1090 GETPROCADDRESS (dll, CloseToolhelp32Snapshot);
1091#endif
255e7678
DJ
1092 }
1093
1094 return (win32_CreateToolhelp32Snapshot != NULL
1095 && win32_Module32First != NULL
6b3d9b83
PA
1096 && win32_Module32Next != NULL
1097#ifdef _WIN32_WCE
1098 && win32_CloseToolhelp32Snapshot != NULL
1099#endif
1100 );
255e7678
DJ
1101}
1102
1103static int
1104toolhelp_get_dll_name (DWORD BaseAddress, char *dll_name_ret)
1105{
1106 HANDLE snapshot_module;
1107 MODULEENTRY32 modEntry = { sizeof (MODULEENTRY32) };
6b3d9b83 1108 int found = 0;
255e7678
DJ
1109
1110 if (!load_toolhelp ())
1111 return 0;
1112
1113 snapshot_module = win32_CreateToolhelp32Snapshot (TH32CS_SNAPMODULE,
1114 current_event.dwProcessId);
1115 if (snapshot_module == INVALID_HANDLE_VALUE)
1116 return 0;
1117
1118 /* Ignore the first module, which is the exe. */
6b3d9b83
PA
1119 if (win32_Module32First (snapshot_module, &modEntry))
1120 while (win32_Module32Next (snapshot_module, &modEntry))
1121 if ((DWORD) modEntry.modBaseAddr == BaseAddress)
1122 {
255e7678 1123#ifdef UNICODE
6b3d9b83 1124 wcstombs (dll_name_ret, modEntry.szExePath, MAX_PATH + 1);
255e7678 1125#else
6b3d9b83 1126 strcpy (dll_name_ret, modEntry.szExePath);
255e7678 1127#endif
6b3d9b83
PA
1128 found = 1;
1129 break;
1130 }
255e7678 1131
6b3d9b83
PA
1132#ifdef _WIN32_WCE
1133 win32_CloseToolhelp32Snapshot (snapshot_module);
1134#else
255e7678 1135 CloseHandle (snapshot_module);
6b3d9b83
PA
1136#endif
1137 return found;
255e7678
DJ
1138}
1139
1140static void
1141handle_load_dll (void)
1142{
1143 LOAD_DLL_DEBUG_INFO *event = &current_event.u.LoadDll;
1144 char dll_buf[MAX_PATH + 1];
1145 char *dll_name = NULL;
1146 DWORD load_addr;
1147
1148 dll_buf[0] = dll_buf[sizeof (dll_buf) - 1] = '\0';
1149
34d86ddd
PA
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))
1154 {
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);
1161 }
255e7678
DJ
1162
1163 dll_name = dll_buf;
1164
1165 if (*dll_name == '\0')
1166 dll_name = get_image_name (current_process_handle,
1167 event->lpImageName, event->fUnicode);
1168 if (!dll_name)
1169 return;
1170
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. */
1174
1175 load_addr = (DWORD) event->lpBaseOfDll + 0x1000;
1176 win32_add_one_solib (dll_name, load_addr);
1177}
1178
1179static void
1180handle_unload_dll (void)
1181{
1182 CORE_ADDR load_addr =
1183 (CORE_ADDR) (DWORD) current_event.u.UnloadDll.lpBaseOfDll;
1184 load_addr += 0x1000;
1185 unloaded_dll (NULL, load_addr);
1186}
1187
34b34921 1188static void
b80864fb
DJ
1189handle_exception (struct target_waitstatus *ourstatus)
1190{
b80864fb
DJ
1191 DWORD code = current_event.u.Exception.ExceptionRecord.ExceptionCode;
1192
1193 ourstatus->kind = TARGET_WAITKIND_STOPPED;
1194
b80864fb
DJ
1195 switch (code)
1196 {
1197 case EXCEPTION_ACCESS_VIOLATION:
1198 OUTMSG2 (("EXCEPTION_ACCESS_VIOLATION"));
1199 ourstatus->value.sig = TARGET_SIGNAL_SEGV;
1200 break;
1201 case STATUS_STACK_OVERFLOW:
1202 OUTMSG2 (("STATUS_STACK_OVERFLOW"));
1203 ourstatus->value.sig = TARGET_SIGNAL_SEGV;
1204 break;
1205 case STATUS_FLOAT_DENORMAL_OPERAND:
1206 OUTMSG2 (("STATUS_FLOAT_DENORMAL_OPERAND"));
1207 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1208 break;
1209 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
1210 OUTMSG2 (("EXCEPTION_ARRAY_BOUNDS_EXCEEDED"));
1211 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1212 break;
1213 case STATUS_FLOAT_INEXACT_RESULT:
1214 OUTMSG2 (("STATUS_FLOAT_INEXACT_RESULT"));
1215 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1216 break;
1217 case STATUS_FLOAT_INVALID_OPERATION:
1218 OUTMSG2 (("STATUS_FLOAT_INVALID_OPERATION"));
1219 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1220 break;
1221 case STATUS_FLOAT_OVERFLOW:
1222 OUTMSG2 (("STATUS_FLOAT_OVERFLOW"));
1223 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1224 break;
1225 case STATUS_FLOAT_STACK_CHECK:
1226 OUTMSG2 (("STATUS_FLOAT_STACK_CHECK"));
1227 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1228 break;
1229 case STATUS_FLOAT_UNDERFLOW:
1230 OUTMSG2 (("STATUS_FLOAT_UNDERFLOW"));
1231 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1232 break;
1233 case STATUS_FLOAT_DIVIDE_BY_ZERO:
1234 OUTMSG2 (("STATUS_FLOAT_DIVIDE_BY_ZERO"));
1235 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1236 break;
1237 case STATUS_INTEGER_DIVIDE_BY_ZERO:
1238 OUTMSG2 (("STATUS_INTEGER_DIVIDE_BY_ZERO"));
1239 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1240 break;
1241 case STATUS_INTEGER_OVERFLOW:
1242 OUTMSG2 (("STATUS_INTEGER_OVERFLOW"));
1243 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1244 break;
1245 case EXCEPTION_BREAKPOINT:
1246 OUTMSG2 (("EXCEPTION_BREAKPOINT"));
1247 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
ed50f18f
PA
1248#ifdef _WIN32_WCE
1249 /* Remove the initial breakpoint. */
1250 check_breakpoints ((CORE_ADDR) (long) current_event
1251 .u.Exception.ExceptionRecord.ExceptionAddress);
1252#endif
b80864fb
DJ
1253 break;
1254 case DBG_CONTROL_C:
1255 OUTMSG2 (("DBG_CONTROL_C"));
1256 ourstatus->value.sig = TARGET_SIGNAL_INT;
1257 break;
1258 case DBG_CONTROL_BREAK:
1259 OUTMSG2 (("DBG_CONTROL_BREAK"));
1260 ourstatus->value.sig = TARGET_SIGNAL_INT;
1261 break;
1262 case EXCEPTION_SINGLE_STEP:
1263 OUTMSG2 (("EXCEPTION_SINGLE_STEP"));
1264 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
1265 break;
1266 case EXCEPTION_ILLEGAL_INSTRUCTION:
1267 OUTMSG2 (("EXCEPTION_ILLEGAL_INSTRUCTION"));
1268 ourstatus->value.sig = TARGET_SIGNAL_ILL;
1269 break;
1270 case EXCEPTION_PRIV_INSTRUCTION:
1271 OUTMSG2 (("EXCEPTION_PRIV_INSTRUCTION"));
1272 ourstatus->value.sig = TARGET_SIGNAL_ILL;
1273 break;
1274 case EXCEPTION_NONCONTINUABLE_EXCEPTION:
1275 OUTMSG2 (("EXCEPTION_NONCONTINUABLE_EXCEPTION"));
1276 ourstatus->value.sig = TARGET_SIGNAL_ILL;
1277 break;
1278 default:
1279 if (current_event.u.Exception.dwFirstChance)
34b34921
PA
1280 {
1281 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
1282 return;
1283 }
b80864fb
DJ
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.
1287 ExceptionAddress));
1288 ourstatus->value.sig = TARGET_SIGNAL_UNKNOWN;
1289 break;
1290 }
1291 OUTMSG2 (("\n"));
1292 last_sig = ourstatus->value.sig;
b80864fb
DJ
1293}
1294
4d5d1aaa 1295
34b34921 1296static void
4d5d1aaa
PA
1297suspend_one_thread (struct inferior_list_entry *entry)
1298{
1299 struct thread_info *thread = (struct thread_info *) entry;
1300 win32_thread_info *th = inferior_target_data (thread);
1301
1302 if (!th->suspended)
1303 {
1304 if (SuspendThread (th->h) == (DWORD) -1)
1305 {
1306 DWORD err = GetLastError ();
1307 OUTMSG (("warning: SuspendThread failed in suspend_one_thread, "
1308 "(error %d): %s\n", (int) err, strwinerror (err)));
1309 }
1310 else
1311 th->suspended = 1;
1312 }
1313}
1314
1315static void
1316fake_breakpoint_event (void)
b80864fb 1317{
4d5d1aaa 1318 OUTMSG2(("fake_breakpoint_event\n"));
b80864fb 1319
4d5d1aaa
PA
1320 faked_breakpoint = 1;
1321
1322 memset (&current_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;
1327
1328 for_each_inferior (&all_threads, suspend_one_thread);
1329}
1330
1331/* Get the next event from the child. */
1332
1333static int
1334get_child_debug_event (struct target_waitstatus *ourstatus)
1335{
b80864fb
DJ
1336 last_sig = TARGET_SIGNAL_0;
1337 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
1338
4d5d1aaa
PA
1339 /* Check if GDB sent us an interrupt request. */
1340 check_remote_input_interrupt_request ();
1341
1342 if (soft_interrupt_requested)
1343 {
1344 soft_interrupt_requested = 0;
1345 fake_breakpoint_event ();
1346 goto gotevent;
1347 }
1348
1349 /* Keep the wait time low enough for confortable remote
1350 interruption, but high enough so gdbserver doesn't become a
1351 bottleneck. */
1352 if (!WaitForDebugEvent (&current_event, 250))
1353 return 0;
1354
1355 gotevent:
b80864fb
DJ
1356
1357 current_inferior =
1358 (struct thread_info *) find_inferior_id (&all_threads,
1359 current_event.dwThreadId);
1360
34b34921 1361 switch (current_event.dwDebugEventCode)
b80864fb
DJ
1362 {
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));
1368
1369 /* Record the existence of this thread. */
34b34921 1370 child_add_thread (current_event.dwThreadId,
b80864fb 1371 current_event.u.CreateThread.hThread);
b80864fb
DJ
1372 break;
1373
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);
b80864fb
DJ
1380 break;
1381
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);
1388
1389 current_process_handle = current_event.u.CreateProcessInfo.hProcess;
1390 main_thread_id = current_event.dwThreadId;
1391
1392 ourstatus->kind = TARGET_WAITKIND_EXECD;
1393 ourstatus->value.execd_pathname = "Main executable";
1394
1395 /* Add the main thread. */
34b34921
PA
1396 child_add_thread (main_thread_id,
1397 current_event.u.CreateProcessInfo.hThread);
b80864fb 1398
34b34921 1399 ourstatus->value.related_pid = current_event.dwThreadId;
ed50f18f
PA
1400#ifdef _WIN32_WCE
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);
1407#endif
b80864fb
DJ
1408 break;
1409
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);
9d606399 1418 current_process_handle = NULL;
b80864fb
DJ
1419 break;
1420
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);
255e7678 1427 handle_load_dll ();
b80864fb
DJ
1428
1429 ourstatus->kind = TARGET_WAITKIND_LOADED;
255e7678 1430 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
b80864fb
DJ
1431 break;
1432
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));
255e7678
DJ
1438 handle_unload_dll ();
1439 ourstatus->kind = TARGET_WAITKIND_LOADED;
1440 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
b80864fb
DJ
1441 break;
1442
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));
34b34921 1448 handle_exception (ourstatus);
b80864fb
DJ
1449 break;
1450
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));
bce7165d 1457 handle_output_debug_string (ourstatus);
b80864fb
DJ
1458 break;
1459
1460 default:
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));
1466 break;
1467 }
1468
1469 current_inferior =
1470 (struct thread_info *) find_inferior_id (&all_threads,
1471 current_event.dwThreadId);
4d5d1aaa 1472 return 1;
b80864fb
DJ
1473}
1474
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. */
1478static unsigned char
1479win32_wait (char *status)
1480{
1481 struct target_waitstatus our_status;
1482
1483 *status = 'T';
1484
1485 while (1)
1486 {
4d5d1aaa
PA
1487 if (!get_child_debug_event (&our_status))
1488 continue;
b80864fb 1489
34b34921 1490 switch (our_status.kind)
b80864fb 1491 {
34b34921 1492 case TARGET_WAITKIND_EXITED:
b80864fb
DJ
1493 OUTMSG2 (("Child exited with retcode = %x\n",
1494 our_status.value.integer));
1495
1496 *status = 'W';
b80864fb 1497 return our_status.value.integer;
34b34921 1498 case TARGET_WAITKIND_STOPPED:
255e7678 1499 case TARGET_WAITKIND_LOADED:
f72f3e60 1500 OUTMSG2 (("Child Stopped with signal = %d \n",
ed50f18f 1501 our_status.value.sig));
b80864fb
DJ
1502
1503 *status = 'T';
1504
1505 child_fetch_inferior_registers (-1);
1506
255e7678
DJ
1507 if (our_status.kind == TARGET_WAITKIND_LOADED
1508 && !server_waiting)
1509 {
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);
1513 break;
1514 }
1515
b80864fb 1516 return our_status.value.sig;
34b34921
PA
1517 default:
1518 OUTMSG (("Ignoring unknown internal event, %d\n", our_status.kind));
1519 /* fall-through */
1520 case TARGET_WAITKIND_SPURIOUS:
34b34921
PA
1521 case TARGET_WAITKIND_EXECD:
1522 /* do nothing, just continue */
1523 child_continue (DBG_CONTINUE, -1);
1524 break;
b80864fb 1525 }
b80864fb
DJ
1526 }
1527}
1528
1529/* Fetch registers from the inferior process.
1530 If REGNO is -1, fetch all registers; otherwise, fetch at least REGNO. */
1531static void
1532win32_fetch_inferior_registers (int regno)
1533{
1534 child_fetch_inferior_registers (regno);
1535}
1536
1537/* Store registers to the inferior process.
1538 If REGNO is -1, store all registers; otherwise, store at least REGNO. */
1539static void
1540win32_store_inferior_registers (int regno)
1541{
1542 child_store_inferior_registers (regno);
1543}
1544
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. */
1548static int
1549win32_read_inferior_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
1550{
ed50f18f 1551 return child_xfer_memory (memaddr, (char *) myaddr, len, 0, 0) != len;
b80864fb
DJ
1552}
1553
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. */
1558static int
1559win32_write_inferior_memory (CORE_ADDR memaddr, const unsigned char *myaddr,
1560 int len)
1561{
1562 return child_xfer_memory (memaddr, (char *) myaddr, len, 1, 0) != len;
1563}
1564
7390519e
PA
1565/* Send an interrupt request to the inferior process. */
1566static void
1567win32_request_interrupt (void)
1568{
1569 winapi_DebugBreakProcess DebugBreakProcess;
1570 winapi_GenerateConsoleCtrlEvent GenerateConsoleCtrlEvent;
1571
1572#ifdef _WIN32_WCE
1573 HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
1574#else
1575 HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
1576#endif
1577
1578 GenerateConsoleCtrlEvent = GETPROCADDRESS (dll, GenerateConsoleCtrlEvent);
1579
1580 if (GenerateConsoleCtrlEvent != NULL
1581 && GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, current_process_id))
1582 return;
1583
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. */
1588
1589 DebugBreakProcess = GETPROCADDRESS (dll, DebugBreakProcess);
1590
1591 if (DebugBreakProcess != NULL
1592 && DebugBreakProcess (current_process_handle))
1593 return;
1594
4d5d1aaa
PA
1595 /* Last resort, suspend all threads manually. */
1596 soft_interrupt_requested = 1;
7390519e
PA
1597}
1598
820f2bda
PA
1599static const char *
1600win32_arch_string (void)
1601{
ed50f18f 1602 return the_low_target.arch_string;
820f2bda
PA
1603}
1604
b80864fb
DJ
1605static struct target_ops win32_target_ops = {
1606 win32_create_inferior,
1607 win32_attach,
1608 win32_kill,
1609 win32_detach,
444d6139 1610 win32_join,
b80864fb
DJ
1611 win32_thread_alive,
1612 win32_resume,
1613 win32_wait,
1614 win32_fetch_inferior_registers,
1615 win32_store_inferior_registers,
1616 win32_read_inferior_memory,
1617 win32_write_inferior_memory,
820f2bda 1618 NULL,
7390519e 1619 win32_request_interrupt,
820f2bda
PA
1620 NULL,
1621 NULL,
1622 NULL,
1623 NULL,
1624 NULL,
1625 NULL,
1626 NULL,
1627 win32_arch_string
b80864fb
DJ
1628};
1629
1630/* Initialize the Win32 backend. */
1631void
1632initialize_low (void)
1633{
1634 set_target_ops (&win32_target_ops);
ed50f18f
PA
1635 if (the_low_target.breakpoint != NULL)
1636 set_breakpoint_data (the_low_target.breakpoint,
1637 the_low_target.breakpoint_len);
b80864fb
DJ
1638 init_registers ();
1639}