]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/gdbserver/win32-low.c
* win32-low.c (win32_get_thread_context)
[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{
bf914831
PA
585 winapi_DebugActiveProcessStop DebugActiveProcessStop = NULL;
586 winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit = NULL;
ed50f18f
PA
587#ifdef _WIN32_WCE
588 HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
589#else
590 HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
591#endif
bf914831
PA
592 DebugActiveProcessStop = GETPROCADDRESS (dll, DebugActiveProcessStop);
593 DebugSetProcessKillOnExit = GETPROCADDRESS (dll, DebugSetProcessKillOnExit);
b80864fb 594
1d5315fe
PA
595 if (DebugActiveProcess (pid))
596 {
597 if (DebugSetProcessKillOnExit != NULL)
598 DebugSetProcessKillOnExit (FALSE);
b80864fb 599
1d5315fe 600 current_process_handle = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
b80864fb 601
1d5315fe
PA
602 if (current_process_handle != NULL)
603 {
604 current_process_id = pid;
605 do_initial_child_stuff (pid);
606 return 0;
607 }
b80864fb
DJ
608 if (DebugActiveProcessStop != NULL)
609 DebugActiveProcessStop (current_process_id);
610 }
611
1d5315fe 612 error ("Attach to process failed.");
b80864fb
DJ
613}
614
bce7165d
PA
615/* Handle OUTPUT_DEBUG_STRING_EVENT from child process. */
616static void
617handle_output_debug_string (struct target_waitstatus *ourstatus)
618{
619#define READ_BUFFER_LEN 1024
620 CORE_ADDR addr;
621 char s[READ_BUFFER_LEN + 1] = { 0 };
622 DWORD nbytes = current_event.u.DebugString.nDebugStringLength;
623
624 if (nbytes == 0)
625 return;
626
627 if (nbytes > READ_BUFFER_LEN)
628 nbytes = READ_BUFFER_LEN;
629
630 addr = (CORE_ADDR) (size_t) current_event.u.DebugString.lpDebugStringData;
631
632 if (current_event.u.DebugString.fUnicode)
633 {
634 /* The event tells us how many bytes, not chars, even
635 in Unicode. */
636 WCHAR buffer[(READ_BUFFER_LEN + 1) / sizeof (WCHAR)] = { 0 };
637 if (read_inferior_memory (addr, (unsigned char *) buffer, nbytes) != 0)
638 return;
639 wcstombs (s, buffer, (nbytes + 1) / sizeof (WCHAR));
640 }
641 else
642 {
643 if (read_inferior_memory (addr, (unsigned char *) s, nbytes) != 0)
644 return;
645 }
646
647 if (strncmp (s, "cYg", 3) != 0)
45e2715e
PA
648 {
649 if (!server_waiting)
650 {
651 OUTMSG2(("%s", s));
652 return;
653 }
654
655 monitor_output (s);
656 }
bce7165d
PA
657#undef READ_BUFFER_LEN
658}
659
b80864fb
DJ
660/* Kill all inferiors. */
661static void
662win32_kill (void)
663{
ed50f18f
PA
664 win32_thread_info *current_thread;
665
9d606399
DJ
666 if (current_process_handle == NULL)
667 return;
668
b80864fb
DJ
669 TerminateProcess (current_process_handle, 0);
670 for (;;)
671 {
672 if (!child_continue (DBG_CONTINUE, -1))
673 break;
674 if (!WaitForDebugEvent (&current_event, INFINITE))
675 break;
676 if (current_event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
677 break;
bce7165d
PA
678 else if (current_event.dwDebugEventCode == OUTPUT_DEBUG_STRING_EVENT)
679 {
680 struct target_waitstatus our_status = { 0 };
681 handle_output_debug_string (&our_status);
682 }
b80864fb 683 }
ed50f18f
PA
684
685 CloseHandle (current_process_handle);
686
687 current_thread = inferior_target_data (current_inferior);
688 if (current_thread && current_thread->h)
689 {
690 /* This may fail in an attached process, so don't check. */
691 (void) CloseHandle (current_thread->h);
692 }
b80864fb
DJ
693}
694
695/* Detach from all inferiors. */
444d6139 696static int
b80864fb
DJ
697win32_detach (void)
698{
444d6139
PA
699 HANDLE h;
700
bf914831
PA
701 winapi_DebugActiveProcessStop DebugActiveProcessStop = NULL;
702 winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit = NULL;
ed50f18f
PA
703#ifdef _WIN32_WCE
704 HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
705#else
706 HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
707#endif
bf914831
PA
708 DebugActiveProcessStop = GETPROCADDRESS (dll, DebugActiveProcessStop);
709 DebugSetProcessKillOnExit = GETPROCADDRESS (dll, DebugSetProcessKillOnExit);
b80864fb 710
444d6139
PA
711 if (DebugSetProcessKillOnExit == NULL
712 || DebugActiveProcessStop == NULL)
713 return -1;
b80864fb 714
444d6139
PA
715 /* We need a new handle, since DebugActiveProcessStop
716 closes all the ones that came through the events. */
717 if ((h = OpenProcess (PROCESS_ALL_ACCESS,
718 FALSE,
719 current_process_id)) == NULL)
720 {
721 /* The process died. */
722 return -1;
723 }
724
725 {
726 struct thread_resume resume;
727 resume.thread = -1;
728 resume.step = 0;
729 resume.sig = 0;
730 resume.leave_stopped = 0;
731 win32_resume (&resume);
732 }
733
734 if (!DebugActiveProcessStop (current_process_id))
735 {
736 CloseHandle (h);
737 return -1;
738 }
739 DebugSetProcessKillOnExit (FALSE);
740
741 current_process_handle = h;
742 return 0;
743}
744
745/* Wait for inferiors to end. */
746static void
747win32_join (void)
748{
749 if (current_process_id == 0
750 || current_process_handle == NULL)
751 return;
752
753 WaitForSingleObject (current_process_handle, INFINITE);
754 CloseHandle (current_process_handle);
755
756 current_process_handle = NULL;
757 current_process_id = 0;
b80864fb
DJ
758}
759
760/* Return 1 iff the thread with thread ID TID is alive. */
761static int
762win32_thread_alive (unsigned long tid)
763{
764 int res;
765
766 /* Our thread list is reliable; don't bother to poll target
767 threads. */
768 if (find_inferior_id (&all_threads, tid) != NULL)
769 res = 1;
770 else
771 res = 0;
772 return res;
773}
774
775/* Resume the inferior process. RESUME_INFO describes how we want
776 to resume. */
777static void
778win32_resume (struct thread_resume *resume_info)
779{
780 DWORD tid;
781 enum target_signal sig;
782 int step;
41093d81 783 win32_thread_info *th;
b80864fb
DJ
784 DWORD continue_status = DBG_CONTINUE;
785
786 /* This handles the very limited set of resume packets that GDB can
787 currently produce. */
788
789 if (resume_info[0].thread == -1)
790 tid = -1;
791 else if (resume_info[1].thread == -1 && !resume_info[1].leave_stopped)
792 tid = -1;
793 else
794 /* Yes, we're ignoring resume_info[0].thread. It'd be tricky to make
795 the Windows resume code do the right thing for thread switching. */
796 tid = current_event.dwThreadId;
797
798 if (resume_info[0].thread != -1)
799 {
800 sig = resume_info[0].sig;
801 step = resume_info[0].step;
802 }
803 else
804 {
805 sig = 0;
806 step = 0;
807 }
808
809 if (sig != TARGET_SIGNAL_0)
810 {
811 if (current_event.dwDebugEventCode != EXCEPTION_DEBUG_EVENT)
812 {
813 OUTMSG (("Cannot continue with signal %d here.\n", sig));
814 }
815 else if (sig == last_sig)
816 continue_status = DBG_EXCEPTION_NOT_HANDLED;
817 else
818 OUTMSG (("Can only continue with recieved signal %d.\n", last_sig));
819 }
820
821 last_sig = TARGET_SIGNAL_0;
822
823 /* Get context for the currently selected thread. */
824 th = thread_rec (current_event.dwThreadId, FALSE);
825 if (th)
826 {
827 if (th->context.ContextFlags)
828 {
b80864fb
DJ
829 /* Move register values from the inferior into the thread
830 context structure. */
831 regcache_invalidate ();
832
833 if (step)
ed50f18f
PA
834 {
835 if (the_low_target.single_step != NULL)
836 (*the_low_target.single_step) (th);
837 else
838 error ("Single stepping is not supported "
839 "in this configuration.\n");
840 }
34b34921 841
9c6c8194 842 win32_set_thread_context (th);
b80864fb
DJ
843 th->context.ContextFlags = 0;
844 }
845 }
846
847 /* Allow continuing with the same signal that interrupted us.
848 Otherwise complain. */
849
850 child_continue (continue_status, tid);
851}
852
255e7678
DJ
853static void
854win32_add_one_solib (const char *name, CORE_ADDR load_addr)
855{
856 char buf[MAX_PATH + 1];
857 char buf2[MAX_PATH + 1];
858
859#ifdef _WIN32_WCE
860 WIN32_FIND_DATA w32_fd;
861 WCHAR wname[MAX_PATH + 1];
862 mbstowcs (wname, name, MAX_PATH);
863 HANDLE h = FindFirstFile (wname, &w32_fd);
864#else
865 WIN32_FIND_DATAA w32_fd;
866 HANDLE h = FindFirstFileA (name, &w32_fd);
867#endif
868
869 if (h == INVALID_HANDLE_VALUE)
870 strcpy (buf, name);
871 else
872 {
873 FindClose (h);
874 strcpy (buf, name);
875#ifndef _WIN32_WCE
876 {
877 char cwd[MAX_PATH + 1];
878 char *p;
879 if (GetCurrentDirectoryA (MAX_PATH + 1, cwd))
880 {
881 p = strrchr (buf, '\\');
882 if (p)
883 p[1] = '\0';
884 SetCurrentDirectoryA (buf);
885 GetFullPathNameA (w32_fd.cFileName, MAX_PATH, buf, &p);
886 SetCurrentDirectoryA (cwd);
887 }
888 }
889#endif
890 }
891
892#ifdef __CYGWIN__
893 cygwin_conv_to_posix_path (buf, buf2);
894#else
895 strcpy (buf2, buf);
896#endif
897
898 loaded_dll (buf2, load_addr);
899}
900
901static char *
902get_image_name (HANDLE h, void *address, int unicode)
903{
904 static char buf[(2 * MAX_PATH) + 1];
905 DWORD size = unicode ? sizeof (WCHAR) : sizeof (char);
906 char *address_ptr;
907 int len = 0;
908 char b[2];
909 DWORD done;
910
911 /* Attempt to read the name of the dll that was detected.
912 This is documented to work only when actively debugging
913 a program. It will not work for attached processes. */
914 if (address == NULL)
915 return NULL;
916
917#ifdef _WIN32_WCE
918 /* Windows CE reports the address of the image name,
919 instead of an address of a pointer into the image name. */
920 address_ptr = address;
921#else
922 /* See if we could read the address of a string, and that the
923 address isn't null. */
924 if (!ReadProcessMemory (h, address, &address_ptr,
925 sizeof (address_ptr), &done)
926 || done != sizeof (address_ptr)
927 || !address_ptr)
928 return NULL;
929#endif
930
931 /* Find the length of the string */
932 while (ReadProcessMemory (h, address_ptr + len++ * size, &b, size, &done)
933 && (b[0] != 0 || b[size - 1] != 0) && done == size)
934 continue;
935
936 if (!unicode)
937 ReadProcessMemory (h, address_ptr, buf, len, &done);
938 else
939 {
940 WCHAR *unicode_address = (WCHAR *) alloca (len * sizeof (WCHAR));
941 ReadProcessMemory (h, address_ptr, unicode_address, len * sizeof (WCHAR),
942 &done);
943
944 WideCharToMultiByte (CP_ACP, 0, unicode_address, len, buf, len, 0, 0);
945 }
946
947 return buf;
948}
949
950typedef BOOL (WINAPI *winapi_EnumProcessModules) (HANDLE, HMODULE *,
951 DWORD, LPDWORD);
952typedef BOOL (WINAPI *winapi_GetModuleInformation) (HANDLE, HMODULE,
953 LPMODULEINFO, DWORD);
954typedef DWORD (WINAPI *winapi_GetModuleFileNameExA) (HANDLE, HMODULE,
955 LPSTR, DWORD);
956
957static winapi_EnumProcessModules win32_EnumProcessModules;
958static winapi_GetModuleInformation win32_GetModuleInformation;
959static winapi_GetModuleFileNameExA win32_GetModuleFileNameExA;
960
961static BOOL
962load_psapi (void)
963{
964 static int psapi_loaded = 0;
965 static HMODULE dll = NULL;
966
967 if (!psapi_loaded)
968 {
969 psapi_loaded = 1;
970 dll = LoadLibrary (TEXT("psapi.dll"));
971 if (!dll)
972 return FALSE;
973 win32_EnumProcessModules =
974 GETPROCADDRESS (dll, EnumProcessModules);
975 win32_GetModuleInformation =
976 GETPROCADDRESS (dll, GetModuleInformation);
977 win32_GetModuleFileNameExA =
978 GETPROCADDRESS (dll, GetModuleFileNameExA);
979 }
980
981 return (win32_EnumProcessModules != NULL
982 && win32_GetModuleInformation != NULL
983 && win32_GetModuleFileNameExA != NULL);
984}
985
986static int
987psapi_get_dll_name (DWORD BaseAddress, char *dll_name_ret)
988{
989 DWORD len;
990 MODULEINFO mi;
991 size_t i;
992 HMODULE dh_buf[1];
993 HMODULE *DllHandle = dh_buf;
994 DWORD cbNeeded;
995 BOOL ok;
996
997 if (!load_psapi ())
998 goto failed;
999
1000 cbNeeded = 0;
1001 ok = (*win32_EnumProcessModules) (current_process_handle,
1002 DllHandle,
1003 sizeof (HMODULE),
1004 &cbNeeded);
1005
1006 if (!ok || !cbNeeded)
1007 goto failed;
1008
1009 DllHandle = (HMODULE *) alloca (cbNeeded);
1010 if (!DllHandle)
1011 goto failed;
1012
1013 ok = (*win32_EnumProcessModules) (current_process_handle,
1014 DllHandle,
1015 cbNeeded,
1016 &cbNeeded);
1017 if (!ok)
1018 goto failed;
1019
1020 for (i = 0; i < ((size_t) cbNeeded / sizeof (HMODULE)); i++)
1021 {
1022 if (!(*win32_GetModuleInformation) (current_process_handle,
1023 DllHandle[i],
1024 &mi,
1025 sizeof (mi)))
1026 {
1027 DWORD err = GetLastError ();
1028 error ("Can't get module info: (error %d): %s\n",
1029 (int) err, strwinerror (err));
1030 }
1031
1032 if ((DWORD) (mi.lpBaseOfDll) == BaseAddress)
1033 {
1034 len = (*win32_GetModuleFileNameExA) (current_process_handle,
1035 DllHandle[i],
1036 dll_name_ret,
1037 MAX_PATH);
1038 if (len == 0)
1039 {
1040 DWORD err = GetLastError ();
1041 error ("Error getting dll name: (error %d): %s\n",
1042 (int) err, strwinerror (err));
1043 }
1044 return 1;
1045 }
1046 }
1047
1048failed:
1049 dll_name_ret[0] = '\0';
1050 return 0;
1051}
1052
1053typedef HANDLE (WINAPI *winapi_CreateToolhelp32Snapshot) (DWORD, DWORD);
1054typedef BOOL (WINAPI *winapi_Module32First) (HANDLE, LPMODULEENTRY32);
1055typedef BOOL (WINAPI *winapi_Module32Next) (HANDLE, LPMODULEENTRY32);
1056
1057static winapi_CreateToolhelp32Snapshot win32_CreateToolhelp32Snapshot;
1058static winapi_Module32First win32_Module32First;
1059static winapi_Module32Next win32_Module32Next;
6b3d9b83
PA
1060#ifdef _WIN32_WCE
1061typedef BOOL (WINAPI *winapi_CloseToolhelp32Snapshot) (HANDLE);
1062static winapi_CloseToolhelp32Snapshot win32_CloseToolhelp32Snapshot;
1063#endif
255e7678
DJ
1064
1065static BOOL
1066load_toolhelp (void)
1067{
1068 static int toolhelp_loaded = 0;
1069 static HMODULE dll = NULL;
1070
1071 if (!toolhelp_loaded)
1072 {
1073 toolhelp_loaded = 1;
1074#ifndef _WIN32_WCE
1075 dll = GetModuleHandle (_T("KERNEL32.DLL"));
1076#else
6b3d9b83 1077 dll = LoadLibrary (L"TOOLHELP.DLL");
255e7678
DJ
1078#endif
1079 if (!dll)
1080 return FALSE;
1081
1082 win32_CreateToolhelp32Snapshot =
1083 GETPROCADDRESS (dll, CreateToolhelp32Snapshot);
1084 win32_Module32First = GETPROCADDRESS (dll, Module32First);
1085 win32_Module32Next = GETPROCADDRESS (dll, Module32Next);
6b3d9b83
PA
1086#ifdef _WIN32_WCE
1087 win32_CloseToolhelp32Snapshot =
1088 GETPROCADDRESS (dll, CloseToolhelp32Snapshot);
1089#endif
255e7678
DJ
1090 }
1091
1092 return (win32_CreateToolhelp32Snapshot != NULL
1093 && win32_Module32First != NULL
6b3d9b83
PA
1094 && win32_Module32Next != NULL
1095#ifdef _WIN32_WCE
1096 && win32_CloseToolhelp32Snapshot != NULL
1097#endif
1098 );
255e7678
DJ
1099}
1100
1101static int
1102toolhelp_get_dll_name (DWORD BaseAddress, char *dll_name_ret)
1103{
1104 HANDLE snapshot_module;
1105 MODULEENTRY32 modEntry = { sizeof (MODULEENTRY32) };
6b3d9b83 1106 int found = 0;
255e7678
DJ
1107
1108 if (!load_toolhelp ())
1109 return 0;
1110
1111 snapshot_module = win32_CreateToolhelp32Snapshot (TH32CS_SNAPMODULE,
1112 current_event.dwProcessId);
1113 if (snapshot_module == INVALID_HANDLE_VALUE)
1114 return 0;
1115
1116 /* Ignore the first module, which is the exe. */
6b3d9b83
PA
1117 if (win32_Module32First (snapshot_module, &modEntry))
1118 while (win32_Module32Next (snapshot_module, &modEntry))
1119 if ((DWORD) modEntry.modBaseAddr == BaseAddress)
1120 {
255e7678 1121#ifdef UNICODE
6b3d9b83 1122 wcstombs (dll_name_ret, modEntry.szExePath, MAX_PATH + 1);
255e7678 1123#else
6b3d9b83 1124 strcpy (dll_name_ret, modEntry.szExePath);
255e7678 1125#endif
6b3d9b83
PA
1126 found = 1;
1127 break;
1128 }
255e7678 1129
6b3d9b83
PA
1130#ifdef _WIN32_WCE
1131 win32_CloseToolhelp32Snapshot (snapshot_module);
1132#else
255e7678 1133 CloseHandle (snapshot_module);
6b3d9b83
PA
1134#endif
1135 return found;
255e7678
DJ
1136}
1137
1138static void
1139handle_load_dll (void)
1140{
1141 LOAD_DLL_DEBUG_INFO *event = &current_event.u.LoadDll;
1142 char dll_buf[MAX_PATH + 1];
1143 char *dll_name = NULL;
1144 DWORD load_addr;
1145
1146 dll_buf[0] = dll_buf[sizeof (dll_buf) - 1] = '\0';
1147
34d86ddd
PA
1148 /* Windows does not report the image name of the dlls in the debug
1149 event on attaches. We resort to iterating over the list of
1150 loaded dlls looking for a match by image base. */
1151 if (!psapi_get_dll_name ((DWORD) event->lpBaseOfDll, dll_buf))
1152 {
1153 if (!server_waiting)
1154 /* On some versions of Windows and Windows CE, we can't create
1155 toolhelp snapshots while the inferior is stopped in a
1156 LOAD_DLL_DEBUG_EVENT due to a dll load, but we can while
1157 Windows is reporting the already loaded dlls. */
1158 toolhelp_get_dll_name ((DWORD) event->lpBaseOfDll, dll_buf);
1159 }
255e7678
DJ
1160
1161 dll_name = dll_buf;
1162
1163 if (*dll_name == '\0')
1164 dll_name = get_image_name (current_process_handle,
1165 event->lpImageName, event->fUnicode);
1166 if (!dll_name)
1167 return;
1168
1169 /* The symbols in a dll are offset by 0x1000, which is the
1170 the offset from 0 of the first byte in an image - because
1171 of the file header and the section alignment. */
1172
1173 load_addr = (DWORD) event->lpBaseOfDll + 0x1000;
1174 win32_add_one_solib (dll_name, load_addr);
1175}
1176
1177static void
1178handle_unload_dll (void)
1179{
1180 CORE_ADDR load_addr =
1181 (CORE_ADDR) (DWORD) current_event.u.UnloadDll.lpBaseOfDll;
1182 load_addr += 0x1000;
1183 unloaded_dll (NULL, load_addr);
1184}
1185
34b34921 1186static void
b80864fb
DJ
1187handle_exception (struct target_waitstatus *ourstatus)
1188{
b80864fb
DJ
1189 DWORD code = current_event.u.Exception.ExceptionRecord.ExceptionCode;
1190
1191 ourstatus->kind = TARGET_WAITKIND_STOPPED;
1192
b80864fb
DJ
1193 switch (code)
1194 {
1195 case EXCEPTION_ACCESS_VIOLATION:
1196 OUTMSG2 (("EXCEPTION_ACCESS_VIOLATION"));
1197 ourstatus->value.sig = TARGET_SIGNAL_SEGV;
1198 break;
1199 case STATUS_STACK_OVERFLOW:
1200 OUTMSG2 (("STATUS_STACK_OVERFLOW"));
1201 ourstatus->value.sig = TARGET_SIGNAL_SEGV;
1202 break;
1203 case STATUS_FLOAT_DENORMAL_OPERAND:
1204 OUTMSG2 (("STATUS_FLOAT_DENORMAL_OPERAND"));
1205 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1206 break;
1207 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
1208 OUTMSG2 (("EXCEPTION_ARRAY_BOUNDS_EXCEEDED"));
1209 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1210 break;
1211 case STATUS_FLOAT_INEXACT_RESULT:
1212 OUTMSG2 (("STATUS_FLOAT_INEXACT_RESULT"));
1213 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1214 break;
1215 case STATUS_FLOAT_INVALID_OPERATION:
1216 OUTMSG2 (("STATUS_FLOAT_INVALID_OPERATION"));
1217 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1218 break;
1219 case STATUS_FLOAT_OVERFLOW:
1220 OUTMSG2 (("STATUS_FLOAT_OVERFLOW"));
1221 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1222 break;
1223 case STATUS_FLOAT_STACK_CHECK:
1224 OUTMSG2 (("STATUS_FLOAT_STACK_CHECK"));
1225 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1226 break;
1227 case STATUS_FLOAT_UNDERFLOW:
1228 OUTMSG2 (("STATUS_FLOAT_UNDERFLOW"));
1229 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1230 break;
1231 case STATUS_FLOAT_DIVIDE_BY_ZERO:
1232 OUTMSG2 (("STATUS_FLOAT_DIVIDE_BY_ZERO"));
1233 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1234 break;
1235 case STATUS_INTEGER_DIVIDE_BY_ZERO:
1236 OUTMSG2 (("STATUS_INTEGER_DIVIDE_BY_ZERO"));
1237 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1238 break;
1239 case STATUS_INTEGER_OVERFLOW:
1240 OUTMSG2 (("STATUS_INTEGER_OVERFLOW"));
1241 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1242 break;
1243 case EXCEPTION_BREAKPOINT:
1244 OUTMSG2 (("EXCEPTION_BREAKPOINT"));
1245 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
ed50f18f
PA
1246#ifdef _WIN32_WCE
1247 /* Remove the initial breakpoint. */
1248 check_breakpoints ((CORE_ADDR) (long) current_event
1249 .u.Exception.ExceptionRecord.ExceptionAddress);
1250#endif
b80864fb
DJ
1251 break;
1252 case DBG_CONTROL_C:
1253 OUTMSG2 (("DBG_CONTROL_C"));
1254 ourstatus->value.sig = TARGET_SIGNAL_INT;
1255 break;
1256 case DBG_CONTROL_BREAK:
1257 OUTMSG2 (("DBG_CONTROL_BREAK"));
1258 ourstatus->value.sig = TARGET_SIGNAL_INT;
1259 break;
1260 case EXCEPTION_SINGLE_STEP:
1261 OUTMSG2 (("EXCEPTION_SINGLE_STEP"));
1262 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
1263 break;
1264 case EXCEPTION_ILLEGAL_INSTRUCTION:
1265 OUTMSG2 (("EXCEPTION_ILLEGAL_INSTRUCTION"));
1266 ourstatus->value.sig = TARGET_SIGNAL_ILL;
1267 break;
1268 case EXCEPTION_PRIV_INSTRUCTION:
1269 OUTMSG2 (("EXCEPTION_PRIV_INSTRUCTION"));
1270 ourstatus->value.sig = TARGET_SIGNAL_ILL;
1271 break;
1272 case EXCEPTION_NONCONTINUABLE_EXCEPTION:
1273 OUTMSG2 (("EXCEPTION_NONCONTINUABLE_EXCEPTION"));
1274 ourstatus->value.sig = TARGET_SIGNAL_ILL;
1275 break;
1276 default:
1277 if (current_event.u.Exception.dwFirstChance)
34b34921
PA
1278 {
1279 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
1280 return;
1281 }
b80864fb
DJ
1282 OUTMSG2 (("gdbserver: unknown target exception 0x%08lx at 0x%08lx",
1283 current_event.u.Exception.ExceptionRecord.ExceptionCode,
1284 (DWORD) current_event.u.Exception.ExceptionRecord.
1285 ExceptionAddress));
1286 ourstatus->value.sig = TARGET_SIGNAL_UNKNOWN;
1287 break;
1288 }
1289 OUTMSG2 (("\n"));
1290 last_sig = ourstatus->value.sig;
b80864fb
DJ
1291}
1292
4d5d1aaa 1293
34b34921 1294static void
4d5d1aaa
PA
1295suspend_one_thread (struct inferior_list_entry *entry)
1296{
1297 struct thread_info *thread = (struct thread_info *) entry;
1298 win32_thread_info *th = inferior_target_data (thread);
1299
1300 if (!th->suspended)
1301 {
1302 if (SuspendThread (th->h) == (DWORD) -1)
1303 {
1304 DWORD err = GetLastError ();
1305 OUTMSG (("warning: SuspendThread failed in suspend_one_thread, "
1306 "(error %d): %s\n", (int) err, strwinerror (err)));
1307 }
1308 else
1309 th->suspended = 1;
1310 }
1311}
1312
1313static void
1314fake_breakpoint_event (void)
b80864fb 1315{
4d5d1aaa 1316 OUTMSG2(("fake_breakpoint_event\n"));
b80864fb 1317
4d5d1aaa
PA
1318 faked_breakpoint = 1;
1319
1320 memset (&current_event, 0, sizeof (current_event));
1321 current_event.dwThreadId = main_thread_id;
1322 current_event.dwDebugEventCode = EXCEPTION_DEBUG_EVENT;
1323 current_event.u.Exception.ExceptionRecord.ExceptionCode
1324 = EXCEPTION_BREAKPOINT;
1325
1326 for_each_inferior (&all_threads, suspend_one_thread);
1327}
1328
1329/* Get the next event from the child. */
1330
1331static int
1332get_child_debug_event (struct target_waitstatus *ourstatus)
1333{
b80864fb
DJ
1334 last_sig = TARGET_SIGNAL_0;
1335 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
1336
4d5d1aaa
PA
1337 /* Check if GDB sent us an interrupt request. */
1338 check_remote_input_interrupt_request ();
1339
1340 if (soft_interrupt_requested)
1341 {
1342 soft_interrupt_requested = 0;
1343 fake_breakpoint_event ();
1344 goto gotevent;
1345 }
1346
1347 /* Keep the wait time low enough for confortable remote
1348 interruption, but high enough so gdbserver doesn't become a
1349 bottleneck. */
1350 if (!WaitForDebugEvent (&current_event, 250))
1351 return 0;
1352
1353 gotevent:
b80864fb
DJ
1354
1355 current_inferior =
1356 (struct thread_info *) find_inferior_id (&all_threads,
1357 current_event.dwThreadId);
1358
34b34921 1359 switch (current_event.dwDebugEventCode)
b80864fb
DJ
1360 {
1361 case CREATE_THREAD_DEBUG_EVENT:
1362 OUTMSG2 (("gdbserver: kernel event CREATE_THREAD_DEBUG_EVENT "
1363 "for pid=%d tid=%x)\n",
1364 (unsigned) current_event.dwProcessId,
1365 (unsigned) current_event.dwThreadId));
1366
1367 /* Record the existence of this thread. */
34b34921 1368 child_add_thread (current_event.dwThreadId,
b80864fb 1369 current_event.u.CreateThread.hThread);
b80864fb
DJ
1370 break;
1371
1372 case EXIT_THREAD_DEBUG_EVENT:
1373 OUTMSG2 (("gdbserver: kernel event EXIT_THREAD_DEBUG_EVENT "
1374 "for pid=%d tid=%x\n",
1375 (unsigned) current_event.dwProcessId,
1376 (unsigned) current_event.dwThreadId));
1377 child_delete_thread (current_event.dwThreadId);
b80864fb
DJ
1378 break;
1379
1380 case CREATE_PROCESS_DEBUG_EVENT:
1381 OUTMSG2 (("gdbserver: kernel event CREATE_PROCESS_DEBUG_EVENT "
1382 "for pid=%d tid=%x\n",
1383 (unsigned) current_event.dwProcessId,
1384 (unsigned) current_event.dwThreadId));
1385 CloseHandle (current_event.u.CreateProcessInfo.hFile);
1386
1387 current_process_handle = current_event.u.CreateProcessInfo.hProcess;
1388 main_thread_id = current_event.dwThreadId;
1389
1390 ourstatus->kind = TARGET_WAITKIND_EXECD;
1391 ourstatus->value.execd_pathname = "Main executable";
1392
1393 /* Add the main thread. */
34b34921
PA
1394 child_add_thread (main_thread_id,
1395 current_event.u.CreateProcessInfo.hThread);
b80864fb 1396
34b34921 1397 ourstatus->value.related_pid = current_event.dwThreadId;
ed50f18f
PA
1398#ifdef _WIN32_WCE
1399 /* Windows CE doesn't set the initial breakpoint automatically
1400 like the desktop versions of Windows do. We add it explicitly
1401 here. It will be removed as soon as it is hit. */
1402 set_breakpoint_at ((CORE_ADDR) (long) current_event.u
1403 .CreateProcessInfo.lpStartAddress,
1404 delete_breakpoint_at);
1405#endif
b80864fb
DJ
1406 break;
1407
1408 case EXIT_PROCESS_DEBUG_EVENT:
1409 OUTMSG2 (("gdbserver: kernel event EXIT_PROCESS_DEBUG_EVENT "
1410 "for pid=%d tid=%x\n",
1411 (unsigned) current_event.dwProcessId,
1412 (unsigned) current_event.dwThreadId));
1413 ourstatus->kind = TARGET_WAITKIND_EXITED;
1414 ourstatus->value.integer = current_event.u.ExitProcess.dwExitCode;
1415 CloseHandle (current_process_handle);
9d606399 1416 current_process_handle = NULL;
b80864fb
DJ
1417 break;
1418
1419 case LOAD_DLL_DEBUG_EVENT:
1420 OUTMSG2 (("gdbserver: kernel event LOAD_DLL_DEBUG_EVENT "
1421 "for pid=%d tid=%x\n",
1422 (unsigned) current_event.dwProcessId,
1423 (unsigned) current_event.dwThreadId));
1424 CloseHandle (current_event.u.LoadDll.hFile);
255e7678 1425 handle_load_dll ();
b80864fb
DJ
1426
1427 ourstatus->kind = TARGET_WAITKIND_LOADED;
255e7678 1428 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
b80864fb
DJ
1429 break;
1430
1431 case UNLOAD_DLL_DEBUG_EVENT:
1432 OUTMSG2 (("gdbserver: kernel event UNLOAD_DLL_DEBUG_EVENT "
1433 "for pid=%d tid=%x\n",
1434 (unsigned) current_event.dwProcessId,
1435 (unsigned) current_event.dwThreadId));
255e7678
DJ
1436 handle_unload_dll ();
1437 ourstatus->kind = TARGET_WAITKIND_LOADED;
1438 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
b80864fb
DJ
1439 break;
1440
1441 case EXCEPTION_DEBUG_EVENT:
1442 OUTMSG2 (("gdbserver: kernel event EXCEPTION_DEBUG_EVENT "
1443 "for pid=%d tid=%x\n",
1444 (unsigned) current_event.dwProcessId,
1445 (unsigned) current_event.dwThreadId));
34b34921 1446 handle_exception (ourstatus);
b80864fb
DJ
1447 break;
1448
1449 case OUTPUT_DEBUG_STRING_EVENT:
1450 /* A message from the kernel (or Cygwin). */
1451 OUTMSG2 (("gdbserver: kernel event OUTPUT_DEBUG_STRING_EVENT "
1452 "for pid=%d tid=%x\n",
1453 (unsigned) current_event.dwProcessId,
1454 (unsigned) current_event.dwThreadId));
bce7165d 1455 handle_output_debug_string (ourstatus);
b80864fb
DJ
1456 break;
1457
1458 default:
1459 OUTMSG2 (("gdbserver: kernel event unknown "
1460 "for pid=%d tid=%x code=%ld\n",
1461 (unsigned) current_event.dwProcessId,
1462 (unsigned) current_event.dwThreadId,
1463 current_event.dwDebugEventCode));
1464 break;
1465 }
1466
1467 current_inferior =
1468 (struct thread_info *) find_inferior_id (&all_threads,
1469 current_event.dwThreadId);
4d5d1aaa 1470 return 1;
b80864fb
DJ
1471}
1472
1473/* Wait for the inferior process to change state.
1474 STATUS will be filled in with a response code to send to GDB.
1475 Returns the signal which caused the process to stop. */
1476static unsigned char
1477win32_wait (char *status)
1478{
1479 struct target_waitstatus our_status;
1480
1481 *status = 'T';
1482
1483 while (1)
1484 {
4d5d1aaa
PA
1485 if (!get_child_debug_event (&our_status))
1486 continue;
b80864fb 1487
34b34921 1488 switch (our_status.kind)
b80864fb 1489 {
34b34921 1490 case TARGET_WAITKIND_EXITED:
b80864fb
DJ
1491 OUTMSG2 (("Child exited with retcode = %x\n",
1492 our_status.value.integer));
1493
1494 *status = 'W';
b80864fb 1495 return our_status.value.integer;
34b34921 1496 case TARGET_WAITKIND_STOPPED:
255e7678 1497 case TARGET_WAITKIND_LOADED:
f72f3e60 1498 OUTMSG2 (("Child Stopped with signal = %d \n",
ed50f18f 1499 our_status.value.sig));
b80864fb
DJ
1500
1501 *status = 'T';
1502
1503 child_fetch_inferior_registers (-1);
1504
255e7678
DJ
1505 if (our_status.kind == TARGET_WAITKIND_LOADED
1506 && !server_waiting)
1507 {
1508 /* When gdb connects, we want to be stopped at the
1509 initial breakpoint, not in some dll load event. */
1510 child_continue (DBG_CONTINUE, -1);
1511 break;
1512 }
1513
b80864fb 1514 return our_status.value.sig;
34b34921
PA
1515 default:
1516 OUTMSG (("Ignoring unknown internal event, %d\n", our_status.kind));
1517 /* fall-through */
1518 case TARGET_WAITKIND_SPURIOUS:
34b34921
PA
1519 case TARGET_WAITKIND_EXECD:
1520 /* do nothing, just continue */
1521 child_continue (DBG_CONTINUE, -1);
1522 break;
b80864fb 1523 }
b80864fb
DJ
1524 }
1525}
1526
1527/* Fetch registers from the inferior process.
1528 If REGNO is -1, fetch all registers; otherwise, fetch at least REGNO. */
1529static void
1530win32_fetch_inferior_registers (int regno)
1531{
1532 child_fetch_inferior_registers (regno);
1533}
1534
1535/* Store registers to the inferior process.
1536 If REGNO is -1, store all registers; otherwise, store at least REGNO. */
1537static void
1538win32_store_inferior_registers (int regno)
1539{
1540 child_store_inferior_registers (regno);
1541}
1542
1543/* Read memory from the inferior process. This should generally be
1544 called through read_inferior_memory, which handles breakpoint shadowing.
1545 Read LEN bytes at MEMADDR into a buffer at MYADDR. */
1546static int
1547win32_read_inferior_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
1548{
ed50f18f 1549 return child_xfer_memory (memaddr, (char *) myaddr, len, 0, 0) != len;
b80864fb
DJ
1550}
1551
1552/* Write memory to the inferior process. This should generally be
1553 called through write_inferior_memory, which handles breakpoint shadowing.
1554 Write LEN bytes from the buffer at MYADDR to MEMADDR.
1555 Returns 0 on success and errno on failure. */
1556static int
1557win32_write_inferior_memory (CORE_ADDR memaddr, const unsigned char *myaddr,
1558 int len)
1559{
1560 return child_xfer_memory (memaddr, (char *) myaddr, len, 1, 0) != len;
1561}
1562
7390519e
PA
1563/* Send an interrupt request to the inferior process. */
1564static void
1565win32_request_interrupt (void)
1566{
1567 winapi_DebugBreakProcess DebugBreakProcess;
1568 winapi_GenerateConsoleCtrlEvent GenerateConsoleCtrlEvent;
1569
1570#ifdef _WIN32_WCE
1571 HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
1572#else
1573 HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
1574#endif
1575
1576 GenerateConsoleCtrlEvent = GETPROCADDRESS (dll, GenerateConsoleCtrlEvent);
1577
1578 if (GenerateConsoleCtrlEvent != NULL
1579 && GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, current_process_id))
1580 return;
1581
1582 /* GenerateConsoleCtrlEvent can fail if process id being debugged is
1583 not a process group id.
1584 Fallback to XP/Vista 'DebugBreakProcess', which generates a
1585 breakpoint exception in the interior process. */
1586
1587 DebugBreakProcess = GETPROCADDRESS (dll, DebugBreakProcess);
1588
1589 if (DebugBreakProcess != NULL
1590 && DebugBreakProcess (current_process_handle))
1591 return;
1592
4d5d1aaa
PA
1593 /* Last resort, suspend all threads manually. */
1594 soft_interrupt_requested = 1;
7390519e
PA
1595}
1596
820f2bda
PA
1597static const char *
1598win32_arch_string (void)
1599{
ed50f18f 1600 return the_low_target.arch_string;
820f2bda
PA
1601}
1602
b80864fb
DJ
1603static struct target_ops win32_target_ops = {
1604 win32_create_inferior,
1605 win32_attach,
1606 win32_kill,
1607 win32_detach,
444d6139 1608 win32_join,
b80864fb
DJ
1609 win32_thread_alive,
1610 win32_resume,
1611 win32_wait,
1612 win32_fetch_inferior_registers,
1613 win32_store_inferior_registers,
1614 win32_read_inferior_memory,
1615 win32_write_inferior_memory,
820f2bda 1616 NULL,
7390519e 1617 win32_request_interrupt,
820f2bda
PA
1618 NULL,
1619 NULL,
1620 NULL,
1621 NULL,
1622 NULL,
1623 NULL,
1624 NULL,
1625 win32_arch_string
b80864fb
DJ
1626};
1627
1628/* Initialize the Win32 backend. */
1629void
1630initialize_low (void)
1631{
1632 set_target_ops (&win32_target_ops);
ed50f18f
PA
1633 if (the_low_target.breakpoint != NULL)
1634 set_breakpoint_data (the_low_target.breakpoint,
1635 the_low_target.breakpoint_len);
b80864fb
DJ
1636 init_registers ();
1637}