]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/gdbserver/win32-low.c
* target.h (struct thread_resume): Delete leave_stopped member.
[thirdparty/binutils-gdb.git] / gdb / gdbserver / win32-low.c
CommitLineData
b80864fb 1/* Low level interface to Windows debugging, for gdbserver.
0fb0cc75 2 Copyright (C) 2006, 2007, 2008, 2009 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"
59a016f0 24#include "gdb/fileio.h"
ed50f18f
PA
25#include "mem-break.h"
26#include "win32-low.h"
b80864fb
DJ
27
28#include <windows.h>
ed50f18f 29#include <winnt.h>
b80864fb 30#include <imagehlp.h>
255e7678 31#include <tlhelp32.h>
b80864fb
DJ
32#include <psapi.h>
33#include <sys/param.h>
34#include <malloc.h>
35#include <process.h>
36
37#ifndef USE_WIN32API
38#include <sys/cygwin.h>
39#endif
40
41#define LOG 0
42
43#define OUTMSG(X) do { printf X; fflush (stdout); } while (0)
44#if LOG
45#define OUTMSG2(X) do { printf X; fflush (stdout); } while (0)
46#else
ed50f18f
PA
47#define OUTMSG2(X) do ; while (0)
48#endif
49
50#ifndef _T
51#define _T(x) TEXT (x)
52#endif
53
54#ifndef COUNTOF
55#define COUNTOF(STR) (sizeof (STR) / sizeof ((STR)[0]))
b80864fb
DJ
56#endif
57
bf914831
PA
58#ifdef _WIN32_WCE
59# define GETPROCADDRESS(DLL, PROC) \
60 ((winapi_ ## PROC) GetProcAddress (DLL, TEXT (#PROC)))
61#else
62# define GETPROCADDRESS(DLL, PROC) \
63 ((winapi_ ## PROC) GetProcAddress (DLL, #PROC))
64#endif
65
b80864fb
DJ
66int using_threads = 1;
67
68/* Globals. */
d97903b2 69static int attaching = 0;
b80864fb
DJ
70static HANDLE current_process_handle = NULL;
71static DWORD current_process_id = 0;
5ac588cf 72static DWORD main_thread_id = 0;
b80864fb
DJ
73static enum target_signal last_sig = TARGET_SIGNAL_0;
74
75/* The current debug event from WaitForDebugEvent. */
76static DEBUG_EVENT current_event;
77
4d5d1aaa
PA
78/* Non zero if an interrupt request is to be satisfied by suspending
79 all threads. */
80static int soft_interrupt_requested = 0;
81
82/* Non zero if the inferior is stopped in a simulated breakpoint done
83 by suspending all the threads. */
84static int faked_breakpoint = 0;
85
ed50f18f 86#define NUM_REGS (the_low_target.num_regs)
b80864fb 87
bf914831
PA
88typedef BOOL WINAPI (*winapi_DebugActiveProcessStop) (DWORD dwProcessId);
89typedef BOOL WINAPI (*winapi_DebugSetProcessKillOnExit) (BOOL KillOnExit);
7390519e
PA
90typedef BOOL WINAPI (*winapi_DebugBreakProcess) (HANDLE);
91typedef BOOL WINAPI (*winapi_GenerateConsoleCtrlEvent) (DWORD, DWORD);
b80864fb 92
2bd7c093 93static void win32_resume (struct thread_resume *resume_info, size_t n);
34b34921 94
b80864fb
DJ
95/* Get the thread ID from the current selected inferior (the current
96 thread). */
97static DWORD
98current_inferior_tid (void)
99{
41093d81 100 win32_thread_info *th = inferior_target_data (current_inferior);
b80864fb
DJ
101 return th->tid;
102}
103
9c6c8194
PA
104/* Get the thread context of the thread associated with TH. */
105
106static void
107win32_get_thread_context (win32_thread_info *th)
108{
109 memset (&th->context, 0, sizeof (CONTEXT));
110 (*the_low_target.get_thread_context) (th, &current_event);
111#ifdef _WIN32_WCE
112 memcpy (&th->base_context, &th->context, sizeof (CONTEXT));
113#endif
114}
115
116/* Set the thread context of the thread associated with TH. */
117
118static void
119win32_set_thread_context (win32_thread_info *th)
120{
121#ifdef _WIN32_WCE
122 /* Calling SuspendThread on a thread that is running kernel code
123 will report that the suspending was successful, but in fact, that
124 will often not be true. In those cases, the context returned by
125 GetThreadContext will not be correct by the time the thread
126 stops, hence we can't set that context back into the thread when
127 resuming - it will most likelly crash the inferior.
128 Unfortunately, there is no way to know when the thread will
129 really stop. To work around it, we'll only write the context
130 back to the thread when either the user or GDB explicitly change
131 it between stopping and resuming. */
132 if (memcmp (&th->context, &th->base_context, sizeof (CONTEXT)) != 0)
133#endif
134 (*the_low_target.set_thread_context) (th, &current_event);
135}
136
b80864fb
DJ
137/* Find a thread record given a thread id. If GET_CONTEXT is set then
138 also retrieve the context for this thread. */
41093d81 139static win32_thread_info *
b80864fb
DJ
140thread_rec (DWORD id, int get_context)
141{
142 struct thread_info *thread;
41093d81 143 win32_thread_info *th;
b80864fb
DJ
144
145 thread = (struct thread_info *) find_inferior_id (&all_threads, id);
146 if (thread == NULL)
147 return NULL;
148
149 th = inferior_target_data (thread);
c436e841 150 if (get_context && th->context.ContextFlags == 0)
b80864fb 151 {
c436e841
PA
152 if (!th->suspended)
153 {
154 if (SuspendThread (th->h) == (DWORD) -1)
155 {
156 DWORD err = GetLastError ();
157 OUTMSG (("warning: SuspendThread failed in thread_rec, "
158 "(error %d): %s\n", (int) err, strwinerror (err)));
159 }
160 else
161 th->suspended = 1;
162 }
b80864fb 163
9c6c8194 164 win32_get_thread_context (th);
b80864fb
DJ
165 }
166
167 return th;
168}
169
170/* Add a thread to the thread list. */
41093d81 171static win32_thread_info *
b80864fb
DJ
172child_add_thread (DWORD tid, HANDLE h)
173{
41093d81 174 win32_thread_info *th;
b80864fb
DJ
175
176 if ((th = thread_rec (tid, FALSE)))
177 return th;
178
bca929d3 179 th = xcalloc (1, sizeof (*th));
b80864fb
DJ
180 th->tid = tid;
181 th->h = h;
182
183 add_thread (tid, th, (unsigned int) tid);
184 set_inferior_regcache_data ((struct thread_info *)
185 find_inferior_id (&all_threads, tid),
186 new_register_cache ());
187
34b34921
PA
188 if (the_low_target.thread_added != NULL)
189 (*the_low_target.thread_added) (th);
b80864fb
DJ
190
191 return th;
192}
193
194/* Delete a thread from the list of threads. */
195static void
196delete_thread_info (struct inferior_list_entry *thread)
197{
41093d81 198 win32_thread_info *th = inferior_target_data ((struct thread_info *) thread);
b80864fb
DJ
199
200 remove_thread ((struct thread_info *) thread);
201 CloseHandle (th->h);
202 free (th);
203}
204
205/* Delete a thread from the list of threads. */
206static void
207child_delete_thread (DWORD id)
208{
209 struct inferior_list_entry *thread;
210
211 /* If the last thread is exiting, just return. */
212 if (all_threads.head == all_threads.tail)
213 return;
214
215 thread = find_inferior_id (&all_threads, id);
216 if (thread == NULL)
217 return;
218
219 delete_thread_info (thread);
220}
221
222/* Transfer memory from/to the debugged process. */
223static int
224child_xfer_memory (CORE_ADDR memaddr, char *our, int len,
225 int write, struct target_ops *target)
226{
227 SIZE_T done;
228 long addr = (long) memaddr;
229
230 if (write)
231 {
232 WriteProcessMemory (current_process_handle, (LPVOID) addr,
233 (LPCVOID) our, len, &done);
234 FlushInstructionCache (current_process_handle, (LPCVOID) addr, len);
235 }
236 else
237 {
238 ReadProcessMemory (current_process_handle, (LPCVOID) addr, (LPVOID) our,
239 len, &done);
240 }
241 return done;
242}
243
244/* Generally, what has the program done? */
245enum target_waitkind
246{
247 /* The program has exited. The exit status is in value.integer. */
248 TARGET_WAITKIND_EXITED,
249
250 /* The program has stopped with a signal. Which signal is in
251 value.sig. */
252 TARGET_WAITKIND_STOPPED,
253
255e7678
DJ
254 /* The program is letting us know that it dynamically loaded
255 or unloaded something. */
b80864fb
DJ
256 TARGET_WAITKIND_LOADED,
257
258 /* The program has exec'ed a new executable file. The new file's
259 pathname is pointed to by value.execd_pathname. */
b80864fb
DJ
260 TARGET_WAITKIND_EXECD,
261
7390519e
PA
262 /* Nothing interesting happened, but we stopped anyway. We take the
263 chance to check if GDB requested an interrupt. */
b80864fb
DJ
264 TARGET_WAITKIND_SPURIOUS,
265};
266
267struct target_waitstatus
268{
269 enum target_waitkind kind;
270
271 /* Forked child pid, execd pathname, exit status or signal number. */
272 union
273 {
274 int integer;
275 enum target_signal sig;
276 int related_pid;
277 char *execd_pathname;
278 int syscall_id;
279 }
280 value;
281};
282
ed50f18f 283/* Clear out any old thread list and reinitialize it to a pristine
b80864fb
DJ
284 state. */
285static void
286child_init_thread_list (void)
287{
288 for_each_inferior (&all_threads, delete_thread_info);
289}
290
291static void
5ac588cf 292do_initial_child_stuff (HANDLE proch, DWORD pid)
b80864fb 293{
b80864fb
DJ
294 last_sig = TARGET_SIGNAL_0;
295
5ac588cf
PA
296 current_process_handle = proch;
297 current_process_id = pid;
298 main_thread_id = 0;
299
300 soft_interrupt_requested = 0;
301 faked_breakpoint = 0;
302
b80864fb
DJ
303 memset (&current_event, 0, sizeof (current_event));
304
305 child_init_thread_list ();
ed50f18f
PA
306
307 if (the_low_target.initial_stuff != NULL)
308 (*the_low_target.initial_stuff) ();
b80864fb
DJ
309}
310
311/* Resume all artificially suspended threads if we are continuing
312 execution. */
313static int
314continue_one_thread (struct inferior_list_entry *this_thread, void *id_ptr)
315{
316 struct thread_info *thread = (struct thread_info *) this_thread;
317 int thread_id = * (int *) id_ptr;
41093d81 318 win32_thread_info *th = inferior_target_data (thread);
b80864fb
DJ
319
320 if ((thread_id == -1 || thread_id == th->tid)
c436e841 321 && th->suspended)
b80864fb 322 {
34b34921 323 if (th->context.ContextFlags)
b80864fb 324 {
9c6c8194 325 win32_set_thread_context (th);
b80864fb
DJ
326 th->context.ContextFlags = 0;
327 }
34b34921 328
c436e841
PA
329 if (ResumeThread (th->h) == (DWORD) -1)
330 {
331 DWORD err = GetLastError ();
332 OUTMSG (("warning: ResumeThread failed in continue_one_thread, "
333 "(error %d): %s\n", (int) err, strwinerror (err)));
334 }
335 th->suspended = 0;
b80864fb
DJ
336 }
337
338 return 0;
339}
340
341static BOOL
342child_continue (DWORD continue_status, int thread_id)
343{
4d5d1aaa
PA
344 /* The inferior will only continue after the ContinueDebugEvent
345 call. */
346 find_inferior (&all_threads, continue_one_thread, &thread_id);
347 faked_breakpoint = 0;
b80864fb 348
4d5d1aaa
PA
349 if (!ContinueDebugEvent (current_event.dwProcessId,
350 current_event.dwThreadId,
351 continue_status))
352 return FALSE;
b80864fb 353
4d5d1aaa 354 return TRUE;
b80864fb
DJ
355}
356
b80864fb
DJ
357/* Fetch register(s) from the current thread context. */
358static void
359child_fetch_inferior_registers (int r)
360{
361 int regno;
41093d81 362 win32_thread_info *th = thread_rec (current_inferior_tid (), TRUE);
b80864fb
DJ
363 if (r == -1 || r == 0 || r > NUM_REGS)
364 child_fetch_inferior_registers (NUM_REGS);
365 else
366 for (regno = 0; regno < r; regno++)
34b34921 367 (*the_low_target.fetch_inferior_register) (th, regno);
b80864fb
DJ
368}
369
370/* Store a new register value into the current thread context. We don't
371 change the program's context until later, when we resume it. */
372static void
373child_store_inferior_registers (int r)
374{
375 int regno;
41093d81 376 win32_thread_info *th = thread_rec (current_inferior_tid (), TRUE);
b80864fb
DJ
377 if (r == -1 || r == 0 || r > NUM_REGS)
378 child_store_inferior_registers (NUM_REGS);
379 else
380 for (regno = 0; regno < r; regno++)
34b34921 381 (*the_low_target.store_inferior_register) (th, regno);
b80864fb
DJ
382}
383
ed50f18f
PA
384/* Map the Windows error number in ERROR to a locale-dependent error
385 message string and return a pointer to it. Typically, the values
386 for ERROR come from GetLastError.
387
388 The string pointed to shall not be modified by the application,
389 but may be overwritten by a subsequent call to strwinerror
390
391 The strwinerror function does not change the current setting
392 of GetLastError. */
393
394char *
395strwinerror (DWORD error)
396{
397 static char buf[1024];
398 TCHAR *msgbuf;
399 DWORD lasterr = GetLastError ();
400 DWORD chars = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
401 | FORMAT_MESSAGE_ALLOCATE_BUFFER,
402 NULL,
403 error,
404 0, /* Default language */
405 (LPVOID)&msgbuf,
406 0,
407 NULL);
408 if (chars != 0)
409 {
410 /* If there is an \r\n appended, zap it. */
411 if (chars >= 2
412 && msgbuf[chars - 2] == '\r'
413 && msgbuf[chars - 1] == '\n')
414 {
415 chars -= 2;
416 msgbuf[chars] = 0;
417 }
418
419 if (chars > ((COUNTOF (buf)) - 1))
420 {
421 chars = COUNTOF (buf) - 1;
422 msgbuf [chars] = 0;
423 }
424
425#ifdef UNICODE
426 wcstombs (buf, msgbuf, chars + 1);
427#else
428 strncpy (buf, msgbuf, chars + 1);
429#endif
430 LocalFree (msgbuf);
431 }
432 else
433 sprintf (buf, "unknown win32 error (%ld)", error);
434
435 SetLastError (lasterr);
436 return buf;
437}
438
aec18585
PA
439static BOOL
440create_process (const char *program, char *args,
441 DWORD flags, PROCESS_INFORMATION *pi)
442{
443 BOOL ret;
444
445#ifdef _WIN32_WCE
446 wchar_t *p, *wprogram, *wargs;
447 size_t argslen;
448
449 wprogram = alloca ((strlen (program) + 1) * sizeof (wchar_t));
450 mbstowcs (wprogram, program, strlen (program) + 1);
451
452 for (p = wprogram; *p; ++p)
453 if (L'/' == *p)
454 *p = L'\\';
455
456 argslen = strlen (args);
457 wargs = alloca ((argslen + 1) * sizeof (wchar_t));
458 mbstowcs (wargs, args, argslen + 1);
459
460 ret = CreateProcessW (wprogram, /* image name */
1b3f6016
PA
461 wargs, /* command line */
462 NULL, /* security, not supported */
463 NULL, /* thread, not supported */
464 FALSE, /* inherit handles, not supported */
465 flags, /* start flags */
466 NULL, /* environment, not supported */
467 NULL, /* current directory, not supported */
468 NULL, /* start info, not supported */
469 pi); /* proc info */
aec18585
PA
470#else
471 STARTUPINFOA si = { sizeof (STARTUPINFOA) };
472
473 ret = CreateProcessA (program, /* image name */
474 args, /* command line */
475 NULL, /* security */
476 NULL, /* thread */
477 TRUE, /* inherit handles */
478 flags, /* start flags */
479 NULL, /* environment */
480 NULL, /* current directory */
481 &si, /* start info */
482 pi); /* proc info */
483#endif
484
485 return ret;
486}
487
b80864fb
DJ
488/* Start a new process.
489 PROGRAM is a path to the program to execute.
490 ARGS is a standard NULL-terminated array of arguments,
491 to be passed to the inferior as ``argv''.
492 Returns the new PID on success, -1 on failure. Registers the new
493 process with the process list. */
494static int
495win32_create_inferior (char *program, char **program_args)
496{
497#ifndef USE_WIN32API
498 char real_path[MAXPATHLEN];
499 char *orig_path, *new_path, *path_ptr;
500#endif
b80864fb
DJ
501 BOOL ret;
502 DWORD flags;
503 char *args;
504 int argslen;
505 int argc;
ed50f18f 506 PROCESS_INFORMATION pi;
aec18585 507 DWORD err;
b80864fb 508
d97903b2
PA
509 /* win32_wait needs to know we're not attaching. */
510 attaching = 0;
511
b80864fb
DJ
512 if (!program)
513 error ("No executable specified, specify executable to debug.\n");
514
b80864fb
DJ
515 flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS;
516
517#ifndef USE_WIN32API
518 orig_path = NULL;
519 path_ptr = getenv ("PATH");
520 if (path_ptr)
521 {
522 orig_path = alloca (strlen (path_ptr) + 1);
523 new_path = alloca (cygwin_posix_to_win32_path_list_buf_size (path_ptr));
524 strcpy (orig_path, path_ptr);
525 cygwin_posix_to_win32_path_list (path_ptr, new_path);
526 setenv ("PATH", new_path, 1);
527 }
528 cygwin_conv_to_win32_path (program, real_path);
529 program = real_path;
530#endif
531
ed50f18f 532 argslen = 1;
b80864fb
DJ
533 for (argc = 1; program_args[argc]; argc++)
534 argslen += strlen (program_args[argc]) + 1;
535 args = alloca (argslen);
ed50f18f 536 args[0] = '\0';
b80864fb
DJ
537 for (argc = 1; program_args[argc]; argc++)
538 {
539 /* FIXME: Can we do better about quoting? How does Cygwin
1b3f6016 540 handle this? */
b80864fb
DJ
541 strcat (args, " ");
542 strcat (args, program_args[argc]);
543 }
ed50f18f 544 OUTMSG2 (("Command line is \"%s\"\n", args));
b80864fb 545
ed50f18f 546#ifdef CREATE_NEW_PROCESS_GROUP
b80864fb 547 flags |= CREATE_NEW_PROCESS_GROUP;
ed50f18f 548#endif
b80864fb 549
aec18585
PA
550 ret = create_process (program, args, flags, &pi);
551 err = GetLastError ();
552 if (!ret && err == ERROR_FILE_NOT_FOUND)
553 {
554 char *exename = alloca (strlen (program) + 5);
555 strcat (strcpy (exename, program), ".exe");
556 ret = create_process (exename, args, flags, &pi);
557 err = GetLastError ();
558 }
b80864fb
DJ
559
560#ifndef USE_WIN32API
561 if (orig_path)
562 setenv ("PATH", orig_path, 1);
563#endif
564
565 if (!ret)
566 {
ed50f18f
PA
567 error ("Error creating process \"%s%s\", (error %d): %s\n",
568 program, args, (int) err, strwinerror (err));
b80864fb
DJ
569 }
570 else
571 {
572 OUTMSG2 (("Process created: %s\n", (char *) args));
573 }
574
ed50f18f
PA
575#ifndef _WIN32_WCE
576 /* On Windows CE this handle can't be closed. The OS reuses
577 it in the debug events, while the 9x/NT versions of Windows
578 probably use a DuplicateHandle'd one. */
b80864fb 579 CloseHandle (pi.hThread);
ed50f18f 580#endif
b80864fb 581
5ac588cf 582 do_initial_child_stuff (pi.hProcess, pi.dwProcessId);
b80864fb
DJ
583
584 return current_process_id;
585}
586
587/* Attach to a running process.
588 PID is the process ID to attach to, specified by the user
589 or a higher layer. */
590static int
591win32_attach (unsigned long pid)
592{
5ca906e6 593 HANDLE h;
bf914831 594 winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit = NULL;
5ca906e6 595 DWORD err;
ed50f18f
PA
596#ifdef _WIN32_WCE
597 HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
598#else
599 HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
600#endif
bf914831 601 DebugSetProcessKillOnExit = GETPROCADDRESS (dll, DebugSetProcessKillOnExit);
b80864fb 602
5ca906e6
PA
603 h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
604 if (h != NULL)
1d5315fe 605 {
5ca906e6
PA
606 if (DebugActiveProcess (pid))
607 {
608 if (DebugSetProcessKillOnExit != NULL)
609 DebugSetProcessKillOnExit (FALSE);
610
d97903b2 611 /* win32_wait needs to know we're attaching. */
1b3f6016 612 attaching = 1;
5ac588cf 613 do_initial_child_stuff (h, pid);
5ca906e6
PA
614 return 0;
615 }
616
617 CloseHandle (h);
b80864fb
DJ
618 }
619
5ca906e6
PA
620 err = GetLastError ();
621 error ("Attach to process failed (error %d): %s\n",
622 (int) err, strwinerror (err));
b80864fb
DJ
623}
624
bce7165d
PA
625/* Handle OUTPUT_DEBUG_STRING_EVENT from child process. */
626static void
627handle_output_debug_string (struct target_waitstatus *ourstatus)
628{
629#define READ_BUFFER_LEN 1024
630 CORE_ADDR addr;
631 char s[READ_BUFFER_LEN + 1] = { 0 };
632 DWORD nbytes = current_event.u.DebugString.nDebugStringLength;
633
634 if (nbytes == 0)
635 return;
636
637 if (nbytes > READ_BUFFER_LEN)
638 nbytes = READ_BUFFER_LEN;
639
640 addr = (CORE_ADDR) (size_t) current_event.u.DebugString.lpDebugStringData;
641
642 if (current_event.u.DebugString.fUnicode)
643 {
644 /* The event tells us how many bytes, not chars, even
1b3f6016 645 in Unicode. */
bce7165d
PA
646 WCHAR buffer[(READ_BUFFER_LEN + 1) / sizeof (WCHAR)] = { 0 };
647 if (read_inferior_memory (addr, (unsigned char *) buffer, nbytes) != 0)
648 return;
649 wcstombs (s, buffer, (nbytes + 1) / sizeof (WCHAR));
650 }
651 else
652 {
653 if (read_inferior_memory (addr, (unsigned char *) s, nbytes) != 0)
654 return;
655 }
656
657 if (strncmp (s, "cYg", 3) != 0)
45e2715e
PA
658 {
659 if (!server_waiting)
660 {
661 OUTMSG2(("%s", s));
662 return;
663 }
664
665 monitor_output (s);
666 }
bce7165d
PA
667#undef READ_BUFFER_LEN
668}
669
5ac588cf
PA
670static void
671win32_clear_inferiors (void)
672{
673 if (current_process_handle != NULL)
674 CloseHandle (current_process_handle);
675
676 for_each_inferior (&all_threads, delete_thread_info);
677 clear_inferiors ();
678}
679
b80864fb
DJ
680/* Kill all inferiors. */
681static void
682win32_kill (void)
683{
9d606399
DJ
684 if (current_process_handle == NULL)
685 return;
686
b80864fb
DJ
687 TerminateProcess (current_process_handle, 0);
688 for (;;)
689 {
690 if (!child_continue (DBG_CONTINUE, -1))
691 break;
692 if (!WaitForDebugEvent (&current_event, INFINITE))
693 break;
694 if (current_event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
695 break;
bce7165d
PA
696 else if (current_event.dwDebugEventCode == OUTPUT_DEBUG_STRING_EVENT)
697 {
1b3f6016 698 struct target_waitstatus our_status = { 0 };
bce7165d 699 handle_output_debug_string (&our_status);
1b3f6016 700 }
b80864fb 701 }
ed50f18f 702
5ac588cf 703 win32_clear_inferiors ();
b80864fb
DJ
704}
705
706/* Detach from all inferiors. */
444d6139 707static int
b80864fb
DJ
708win32_detach (void)
709{
bf914831
PA
710 winapi_DebugActiveProcessStop DebugActiveProcessStop = NULL;
711 winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit = NULL;
ed50f18f
PA
712#ifdef _WIN32_WCE
713 HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
714#else
715 HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
716#endif
bf914831
PA
717 DebugActiveProcessStop = GETPROCADDRESS (dll, DebugActiveProcessStop);
718 DebugSetProcessKillOnExit = GETPROCADDRESS (dll, DebugSetProcessKillOnExit);
b80864fb 719
444d6139
PA
720 if (DebugSetProcessKillOnExit == NULL
721 || DebugActiveProcessStop == NULL)
722 return -1;
b80864fb 723
444d6139
PA
724 {
725 struct thread_resume resume;
726 resume.thread = -1;
727 resume.step = 0;
728 resume.sig = 0;
2bd7c093 729 win32_resume (&resume, 1);
444d6139
PA
730 }
731
732 if (!DebugActiveProcessStop (current_process_id))
5ac588cf
PA
733 return -1;
734
444d6139
PA
735 DebugSetProcessKillOnExit (FALSE);
736
5ac588cf 737 win32_clear_inferiors ();
444d6139
PA
738 return 0;
739}
740
741/* Wait for inferiors to end. */
742static void
743win32_join (void)
744{
5ac588cf 745 extern unsigned long signal_pid;
444d6139 746
5ac588cf
PA
747 HANDLE h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, signal_pid);
748 if (h != NULL)
749 {
750 WaitForSingleObject (h, INFINITE);
751 CloseHandle (h);
752 }
b80864fb
DJ
753}
754
755/* Return 1 iff the thread with thread ID TID is alive. */
756static int
757win32_thread_alive (unsigned long tid)
758{
759 int res;
760
761 /* Our thread list is reliable; don't bother to poll target
762 threads. */
763 if (find_inferior_id (&all_threads, tid) != NULL)
764 res = 1;
765 else
766 res = 0;
767 return res;
768}
769
770/* Resume the inferior process. RESUME_INFO describes how we want
771 to resume. */
772static void
2bd7c093 773win32_resume (struct thread_resume *resume_info, size_t n)
b80864fb
DJ
774{
775 DWORD tid;
776 enum target_signal sig;
777 int step;
41093d81 778 win32_thread_info *th;
b80864fb
DJ
779 DWORD continue_status = DBG_CONTINUE;
780
781 /* This handles the very limited set of resume packets that GDB can
782 currently produce. */
783
2bd7c093 784 if (n == 1 && resume_info[0].thread == -1)
b80864fb 785 tid = -1;
2bd7c093 786 else if (n > 1)
b80864fb
DJ
787 tid = -1;
788 else
789 /* Yes, we're ignoring resume_info[0].thread. It'd be tricky to make
790 the Windows resume code do the right thing for thread switching. */
791 tid = current_event.dwThreadId;
792
793 if (resume_info[0].thread != -1)
794 {
795 sig = resume_info[0].sig;
796 step = resume_info[0].step;
797 }
798 else
799 {
800 sig = 0;
801 step = 0;
802 }
803
804 if (sig != TARGET_SIGNAL_0)
805 {
806 if (current_event.dwDebugEventCode != EXCEPTION_DEBUG_EVENT)
807 {
808 OUTMSG (("Cannot continue with signal %d here.\n", sig));
809 }
810 else if (sig == last_sig)
811 continue_status = DBG_EXCEPTION_NOT_HANDLED;
812 else
813 OUTMSG (("Can only continue with recieved signal %d.\n", last_sig));
814 }
815
816 last_sig = TARGET_SIGNAL_0;
817
818 /* Get context for the currently selected thread. */
819 th = thread_rec (current_event.dwThreadId, FALSE);
820 if (th)
821 {
822 if (th->context.ContextFlags)
823 {
b80864fb
DJ
824 /* Move register values from the inferior into the thread
825 context structure. */
826 regcache_invalidate ();
827
828 if (step)
ed50f18f
PA
829 {
830 if (the_low_target.single_step != NULL)
831 (*the_low_target.single_step) (th);
832 else
833 error ("Single stepping is not supported "
834 "in this configuration.\n");
835 }
34b34921 836
9c6c8194 837 win32_set_thread_context (th);
b80864fb
DJ
838 th->context.ContextFlags = 0;
839 }
840 }
841
842 /* Allow continuing with the same signal that interrupted us.
843 Otherwise complain. */
844
845 child_continue (continue_status, tid);
846}
847
255e7678
DJ
848static void
849win32_add_one_solib (const char *name, CORE_ADDR load_addr)
850{
851 char buf[MAX_PATH + 1];
852 char buf2[MAX_PATH + 1];
853
854#ifdef _WIN32_WCE
855 WIN32_FIND_DATA w32_fd;
856 WCHAR wname[MAX_PATH + 1];
857 mbstowcs (wname, name, MAX_PATH);
858 HANDLE h = FindFirstFile (wname, &w32_fd);
859#else
860 WIN32_FIND_DATAA w32_fd;
861 HANDLE h = FindFirstFileA (name, &w32_fd);
862#endif
863
864 if (h == INVALID_HANDLE_VALUE)
865 strcpy (buf, name);
866 else
867 {
868 FindClose (h);
869 strcpy (buf, name);
870#ifndef _WIN32_WCE
871 {
872 char cwd[MAX_PATH + 1];
873 char *p;
874 if (GetCurrentDirectoryA (MAX_PATH + 1, cwd))
875 {
876 p = strrchr (buf, '\\');
877 if (p)
878 p[1] = '\0';
879 SetCurrentDirectoryA (buf);
880 GetFullPathNameA (w32_fd.cFileName, MAX_PATH, buf, &p);
881 SetCurrentDirectoryA (cwd);
882 }
883 }
884#endif
885 }
886
887#ifdef __CYGWIN__
888 cygwin_conv_to_posix_path (buf, buf2);
889#else
890 strcpy (buf2, buf);
891#endif
892
893 loaded_dll (buf2, load_addr);
894}
895
896static char *
897get_image_name (HANDLE h, void *address, int unicode)
898{
899 static char buf[(2 * MAX_PATH) + 1];
900 DWORD size = unicode ? sizeof (WCHAR) : sizeof (char);
901 char *address_ptr;
902 int len = 0;
903 char b[2];
904 DWORD done;
905
906 /* Attempt to read the name of the dll that was detected.
907 This is documented to work only when actively debugging
908 a program. It will not work for attached processes. */
909 if (address == NULL)
910 return NULL;
911
912#ifdef _WIN32_WCE
913 /* Windows CE reports the address of the image name,
914 instead of an address of a pointer into the image name. */
915 address_ptr = address;
916#else
917 /* See if we could read the address of a string, and that the
918 address isn't null. */
919 if (!ReadProcessMemory (h, address, &address_ptr,
920 sizeof (address_ptr), &done)
921 || done != sizeof (address_ptr)
922 || !address_ptr)
923 return NULL;
924#endif
925
926 /* Find the length of the string */
927 while (ReadProcessMemory (h, address_ptr + len++ * size, &b, size, &done)
928 && (b[0] != 0 || b[size - 1] != 0) && done == size)
929 continue;
930
931 if (!unicode)
932 ReadProcessMemory (h, address_ptr, buf, len, &done);
933 else
934 {
935 WCHAR *unicode_address = (WCHAR *) alloca (len * sizeof (WCHAR));
936 ReadProcessMemory (h, address_ptr, unicode_address, len * sizeof (WCHAR),
937 &done);
938
939 WideCharToMultiByte (CP_ACP, 0, unicode_address, len, buf, len, 0, 0);
940 }
941
942 return buf;
943}
944
945typedef BOOL (WINAPI *winapi_EnumProcessModules) (HANDLE, HMODULE *,
946 DWORD, LPDWORD);
947typedef BOOL (WINAPI *winapi_GetModuleInformation) (HANDLE, HMODULE,
948 LPMODULEINFO, DWORD);
949typedef DWORD (WINAPI *winapi_GetModuleFileNameExA) (HANDLE, HMODULE,
950 LPSTR, DWORD);
951
952static winapi_EnumProcessModules win32_EnumProcessModules;
953static winapi_GetModuleInformation win32_GetModuleInformation;
954static winapi_GetModuleFileNameExA win32_GetModuleFileNameExA;
955
956static BOOL
957load_psapi (void)
958{
959 static int psapi_loaded = 0;
960 static HMODULE dll = NULL;
961
962 if (!psapi_loaded)
963 {
964 psapi_loaded = 1;
965 dll = LoadLibrary (TEXT("psapi.dll"));
966 if (!dll)
967 return FALSE;
968 win32_EnumProcessModules =
969 GETPROCADDRESS (dll, EnumProcessModules);
970 win32_GetModuleInformation =
971 GETPROCADDRESS (dll, GetModuleInformation);
972 win32_GetModuleFileNameExA =
973 GETPROCADDRESS (dll, GetModuleFileNameExA);
974 }
975
976 return (win32_EnumProcessModules != NULL
977 && win32_GetModuleInformation != NULL
978 && win32_GetModuleFileNameExA != NULL);
979}
980
981static int
982psapi_get_dll_name (DWORD BaseAddress, char *dll_name_ret)
983{
984 DWORD len;
985 MODULEINFO mi;
986 size_t i;
987 HMODULE dh_buf[1];
988 HMODULE *DllHandle = dh_buf;
989 DWORD cbNeeded;
990 BOOL ok;
991
992 if (!load_psapi ())
993 goto failed;
994
995 cbNeeded = 0;
996 ok = (*win32_EnumProcessModules) (current_process_handle,
997 DllHandle,
998 sizeof (HMODULE),
999 &cbNeeded);
1000
1001 if (!ok || !cbNeeded)
1002 goto failed;
1003
1004 DllHandle = (HMODULE *) alloca (cbNeeded);
1005 if (!DllHandle)
1006 goto failed;
1007
1008 ok = (*win32_EnumProcessModules) (current_process_handle,
1009 DllHandle,
1010 cbNeeded,
1011 &cbNeeded);
1012 if (!ok)
1013 goto failed;
1014
1015 for (i = 0; i < ((size_t) cbNeeded / sizeof (HMODULE)); i++)
1016 {
1017 if (!(*win32_GetModuleInformation) (current_process_handle,
1018 DllHandle[i],
1019 &mi,
1020 sizeof (mi)))
1021 {
1022 DWORD err = GetLastError ();
1023 error ("Can't get module info: (error %d): %s\n",
1024 (int) err, strwinerror (err));
1025 }
1026
1027 if ((DWORD) (mi.lpBaseOfDll) == BaseAddress)
1028 {
1029 len = (*win32_GetModuleFileNameExA) (current_process_handle,
1030 DllHandle[i],
1031 dll_name_ret,
1032 MAX_PATH);
1033 if (len == 0)
1034 {
1035 DWORD err = GetLastError ();
1036 error ("Error getting dll name: (error %d): %s\n",
1037 (int) err, strwinerror (err));
1038 }
1039 return 1;
1040 }
1041 }
1042
1043failed:
1044 dll_name_ret[0] = '\0';
1045 return 0;
1046}
1047
1048typedef HANDLE (WINAPI *winapi_CreateToolhelp32Snapshot) (DWORD, DWORD);
1049typedef BOOL (WINAPI *winapi_Module32First) (HANDLE, LPMODULEENTRY32);
1050typedef BOOL (WINAPI *winapi_Module32Next) (HANDLE, LPMODULEENTRY32);
1051
1052static winapi_CreateToolhelp32Snapshot win32_CreateToolhelp32Snapshot;
1053static winapi_Module32First win32_Module32First;
1054static winapi_Module32Next win32_Module32Next;
6b3d9b83
PA
1055#ifdef _WIN32_WCE
1056typedef BOOL (WINAPI *winapi_CloseToolhelp32Snapshot) (HANDLE);
1057static winapi_CloseToolhelp32Snapshot win32_CloseToolhelp32Snapshot;
1058#endif
255e7678
DJ
1059
1060static BOOL
1061load_toolhelp (void)
1062{
1063 static int toolhelp_loaded = 0;
1064 static HMODULE dll = NULL;
1065
1066 if (!toolhelp_loaded)
1067 {
1068 toolhelp_loaded = 1;
1069#ifndef _WIN32_WCE
1070 dll = GetModuleHandle (_T("KERNEL32.DLL"));
1071#else
6b3d9b83 1072 dll = LoadLibrary (L"TOOLHELP.DLL");
255e7678
DJ
1073#endif
1074 if (!dll)
1075 return FALSE;
1076
1077 win32_CreateToolhelp32Snapshot =
1078 GETPROCADDRESS (dll, CreateToolhelp32Snapshot);
1079 win32_Module32First = GETPROCADDRESS (dll, Module32First);
1080 win32_Module32Next = GETPROCADDRESS (dll, Module32Next);
6b3d9b83
PA
1081#ifdef _WIN32_WCE
1082 win32_CloseToolhelp32Snapshot =
1083 GETPROCADDRESS (dll, CloseToolhelp32Snapshot);
1084#endif
255e7678
DJ
1085 }
1086
1087 return (win32_CreateToolhelp32Snapshot != NULL
1088 && win32_Module32First != NULL
6b3d9b83
PA
1089 && win32_Module32Next != NULL
1090#ifdef _WIN32_WCE
1091 && win32_CloseToolhelp32Snapshot != NULL
1092#endif
1093 );
255e7678
DJ
1094}
1095
1096static int
1097toolhelp_get_dll_name (DWORD BaseAddress, char *dll_name_ret)
1098{
1099 HANDLE snapshot_module;
1100 MODULEENTRY32 modEntry = { sizeof (MODULEENTRY32) };
6b3d9b83 1101 int found = 0;
255e7678
DJ
1102
1103 if (!load_toolhelp ())
1104 return 0;
1105
1106 snapshot_module = win32_CreateToolhelp32Snapshot (TH32CS_SNAPMODULE,
1107 current_event.dwProcessId);
1108 if (snapshot_module == INVALID_HANDLE_VALUE)
1109 return 0;
1110
1111 /* Ignore the first module, which is the exe. */
6b3d9b83
PA
1112 if (win32_Module32First (snapshot_module, &modEntry))
1113 while (win32_Module32Next (snapshot_module, &modEntry))
1114 if ((DWORD) modEntry.modBaseAddr == BaseAddress)
1115 {
255e7678 1116#ifdef UNICODE
6b3d9b83 1117 wcstombs (dll_name_ret, modEntry.szExePath, MAX_PATH + 1);
255e7678 1118#else
6b3d9b83 1119 strcpy (dll_name_ret, modEntry.szExePath);
255e7678 1120#endif
6b3d9b83
PA
1121 found = 1;
1122 break;
1123 }
255e7678 1124
6b3d9b83
PA
1125#ifdef _WIN32_WCE
1126 win32_CloseToolhelp32Snapshot (snapshot_module);
1127#else
255e7678 1128 CloseHandle (snapshot_module);
6b3d9b83
PA
1129#endif
1130 return found;
255e7678
DJ
1131}
1132
1133static void
1134handle_load_dll (void)
1135{
1136 LOAD_DLL_DEBUG_INFO *event = &current_event.u.LoadDll;
1137 char dll_buf[MAX_PATH + 1];
1138 char *dll_name = NULL;
1139 DWORD load_addr;
1140
1141 dll_buf[0] = dll_buf[sizeof (dll_buf) - 1] = '\0';
1142
34d86ddd
PA
1143 /* Windows does not report the image name of the dlls in the debug
1144 event on attaches. We resort to iterating over the list of
1145 loaded dlls looking for a match by image base. */
1146 if (!psapi_get_dll_name ((DWORD) event->lpBaseOfDll, dll_buf))
1147 {
1148 if (!server_waiting)
1149 /* On some versions of Windows and Windows CE, we can't create
1150 toolhelp snapshots while the inferior is stopped in a
1151 LOAD_DLL_DEBUG_EVENT due to a dll load, but we can while
1152 Windows is reporting the already loaded dlls. */
1153 toolhelp_get_dll_name ((DWORD) event->lpBaseOfDll, dll_buf);
1154 }
255e7678
DJ
1155
1156 dll_name = dll_buf;
1157
1158 if (*dll_name == '\0')
1159 dll_name = get_image_name (current_process_handle,
1160 event->lpImageName, event->fUnicode);
1161 if (!dll_name)
1162 return;
1163
1164 /* The symbols in a dll are offset by 0x1000, which is the
1165 the offset from 0 of the first byte in an image - because
1166 of the file header and the section alignment. */
1167
1168 load_addr = (DWORD) event->lpBaseOfDll + 0x1000;
1169 win32_add_one_solib (dll_name, load_addr);
1170}
1171
1172static void
1173handle_unload_dll (void)
1174{
1175 CORE_ADDR load_addr =
1176 (CORE_ADDR) (DWORD) current_event.u.UnloadDll.lpBaseOfDll;
1177 load_addr += 0x1000;
1178 unloaded_dll (NULL, load_addr);
1179}
1180
34b34921 1181static void
b80864fb
DJ
1182handle_exception (struct target_waitstatus *ourstatus)
1183{
b80864fb
DJ
1184 DWORD code = current_event.u.Exception.ExceptionRecord.ExceptionCode;
1185
1186 ourstatus->kind = TARGET_WAITKIND_STOPPED;
1187
b80864fb
DJ
1188 switch (code)
1189 {
1190 case EXCEPTION_ACCESS_VIOLATION:
1191 OUTMSG2 (("EXCEPTION_ACCESS_VIOLATION"));
1192 ourstatus->value.sig = TARGET_SIGNAL_SEGV;
1193 break;
1194 case STATUS_STACK_OVERFLOW:
1195 OUTMSG2 (("STATUS_STACK_OVERFLOW"));
1196 ourstatus->value.sig = TARGET_SIGNAL_SEGV;
1197 break;
1198 case STATUS_FLOAT_DENORMAL_OPERAND:
1199 OUTMSG2 (("STATUS_FLOAT_DENORMAL_OPERAND"));
1200 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1201 break;
1202 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
1203 OUTMSG2 (("EXCEPTION_ARRAY_BOUNDS_EXCEEDED"));
1204 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1205 break;
1206 case STATUS_FLOAT_INEXACT_RESULT:
1207 OUTMSG2 (("STATUS_FLOAT_INEXACT_RESULT"));
1208 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1209 break;
1210 case STATUS_FLOAT_INVALID_OPERATION:
1211 OUTMSG2 (("STATUS_FLOAT_INVALID_OPERATION"));
1212 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1213 break;
1214 case STATUS_FLOAT_OVERFLOW:
1215 OUTMSG2 (("STATUS_FLOAT_OVERFLOW"));
1216 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1217 break;
1218 case STATUS_FLOAT_STACK_CHECK:
1219 OUTMSG2 (("STATUS_FLOAT_STACK_CHECK"));
1220 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1221 break;
1222 case STATUS_FLOAT_UNDERFLOW:
1223 OUTMSG2 (("STATUS_FLOAT_UNDERFLOW"));
1224 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1225 break;
1226 case STATUS_FLOAT_DIVIDE_BY_ZERO:
1227 OUTMSG2 (("STATUS_FLOAT_DIVIDE_BY_ZERO"));
1228 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1229 break;
1230 case STATUS_INTEGER_DIVIDE_BY_ZERO:
1231 OUTMSG2 (("STATUS_INTEGER_DIVIDE_BY_ZERO"));
1232 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1233 break;
1234 case STATUS_INTEGER_OVERFLOW:
1235 OUTMSG2 (("STATUS_INTEGER_OVERFLOW"));
1236 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1237 break;
1238 case EXCEPTION_BREAKPOINT:
1239 OUTMSG2 (("EXCEPTION_BREAKPOINT"));
1240 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
ed50f18f
PA
1241#ifdef _WIN32_WCE
1242 /* Remove the initial breakpoint. */
1243 check_breakpoints ((CORE_ADDR) (long) current_event
1b3f6016 1244 .u.Exception.ExceptionRecord.ExceptionAddress);
ed50f18f 1245#endif
b80864fb
DJ
1246 break;
1247 case DBG_CONTROL_C:
1248 OUTMSG2 (("DBG_CONTROL_C"));
1249 ourstatus->value.sig = TARGET_SIGNAL_INT;
1250 break;
1251 case DBG_CONTROL_BREAK:
1252 OUTMSG2 (("DBG_CONTROL_BREAK"));
1253 ourstatus->value.sig = TARGET_SIGNAL_INT;
1254 break;
1255 case EXCEPTION_SINGLE_STEP:
1256 OUTMSG2 (("EXCEPTION_SINGLE_STEP"));
1257 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
1258 break;
1259 case EXCEPTION_ILLEGAL_INSTRUCTION:
1260 OUTMSG2 (("EXCEPTION_ILLEGAL_INSTRUCTION"));
1261 ourstatus->value.sig = TARGET_SIGNAL_ILL;
1262 break;
1263 case EXCEPTION_PRIV_INSTRUCTION:
1264 OUTMSG2 (("EXCEPTION_PRIV_INSTRUCTION"));
1265 ourstatus->value.sig = TARGET_SIGNAL_ILL;
1266 break;
1267 case EXCEPTION_NONCONTINUABLE_EXCEPTION:
1268 OUTMSG2 (("EXCEPTION_NONCONTINUABLE_EXCEPTION"));
1269 ourstatus->value.sig = TARGET_SIGNAL_ILL;
1270 break;
1271 default:
1272 if (current_event.u.Exception.dwFirstChance)
34b34921
PA
1273 {
1274 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
1275 return;
1276 }
b80864fb
DJ
1277 OUTMSG2 (("gdbserver: unknown target exception 0x%08lx at 0x%08lx",
1278 current_event.u.Exception.ExceptionRecord.ExceptionCode,
1279 (DWORD) current_event.u.Exception.ExceptionRecord.
1280 ExceptionAddress));
1281 ourstatus->value.sig = TARGET_SIGNAL_UNKNOWN;
1282 break;
1283 }
1284 OUTMSG2 (("\n"));
1285 last_sig = ourstatus->value.sig;
b80864fb
DJ
1286}
1287
4d5d1aaa 1288
34b34921 1289static void
4d5d1aaa
PA
1290suspend_one_thread (struct inferior_list_entry *entry)
1291{
1292 struct thread_info *thread = (struct thread_info *) entry;
1293 win32_thread_info *th = inferior_target_data (thread);
1294
1295 if (!th->suspended)
1296 {
1297 if (SuspendThread (th->h) == (DWORD) -1)
1298 {
1299 DWORD err = GetLastError ();
1300 OUTMSG (("warning: SuspendThread failed in suspend_one_thread, "
1301 "(error %d): %s\n", (int) err, strwinerror (err)));
1302 }
1303 else
1304 th->suspended = 1;
1305 }
1306}
1307
1308static void
1309fake_breakpoint_event (void)
b80864fb 1310{
4d5d1aaa 1311 OUTMSG2(("fake_breakpoint_event\n"));
b80864fb 1312
4d5d1aaa
PA
1313 faked_breakpoint = 1;
1314
1315 memset (&current_event, 0, sizeof (current_event));
1316 current_event.dwThreadId = main_thread_id;
1317 current_event.dwDebugEventCode = EXCEPTION_DEBUG_EVENT;
1318 current_event.u.Exception.ExceptionRecord.ExceptionCode
1319 = EXCEPTION_BREAKPOINT;
1320
1321 for_each_inferior (&all_threads, suspend_one_thread);
1322}
1323
b65d95c5
DJ
1324#ifdef _WIN32_WCE
1325static int
1326auto_delete_breakpoint (CORE_ADDR stop_pc)
1327{
1328 return 1;
1329}
1330#endif
1331
4d5d1aaa
PA
1332/* Get the next event from the child. */
1333
1334static int
1335get_child_debug_event (struct target_waitstatus *ourstatus)
1336{
b80864fb
DJ
1337 last_sig = TARGET_SIGNAL_0;
1338 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
1339
4d5d1aaa
PA
1340 /* Check if GDB sent us an interrupt request. */
1341 check_remote_input_interrupt_request ();
1342
1343 if (soft_interrupt_requested)
1344 {
1345 soft_interrupt_requested = 0;
1346 fake_breakpoint_event ();
1347 goto gotevent;
1348 }
1349
d97903b2
PA
1350#ifndef _WIN32_WCE
1351 attaching = 0;
1352#else
1353 if (attaching)
1354 {
1355 /* WinCE doesn't set an initial breakpoint automatically. To
1b3f6016
PA
1356 stop the inferior, we flush all currently pending debug
1357 events -- the thread list and the dll list are always
1358 reported immediatelly without delay, then, we suspend all
1359 threads and pretend we saw a trap at the current PC of the
1360 main thread.
1361
1362 Contrary to desktop Windows, Windows CE *does* report the dll
1363 names on LOAD_DLL_DEBUG_EVENTs resulting from a
1364 DebugActiveProcess call. This limits the way we can detect
1365 if all the dlls have already been reported. If we get a real
1366 debug event before leaving attaching, the worst that will
1367 happen is the user will see a spurious breakpoint. */
d97903b2
PA
1368
1369 current_event.dwDebugEventCode = 0;
1370 if (!WaitForDebugEvent (&current_event, 0))
1b3f6016
PA
1371 {
1372 OUTMSG2(("no attach events left\n"));
1373 fake_breakpoint_event ();
1374 attaching = 0;
1375 }
d97903b2 1376 else
1b3f6016 1377 OUTMSG2(("got attach event\n"));
d97903b2
PA
1378 }
1379 else
1380#endif
1381 {
1382 /* Keep the wait time low enough for confortable remote
1b3f6016
PA
1383 interruption, but high enough so gdbserver doesn't become a
1384 bottleneck. */
d97903b2 1385 if (!WaitForDebugEvent (&current_event, 250))
1b3f6016 1386 return 0;
d97903b2 1387 }
4d5d1aaa
PA
1388
1389 gotevent:
b80864fb
DJ
1390
1391 current_inferior =
1392 (struct thread_info *) find_inferior_id (&all_threads,
1393 current_event.dwThreadId);
1394
34b34921 1395 switch (current_event.dwDebugEventCode)
b80864fb
DJ
1396 {
1397 case CREATE_THREAD_DEBUG_EVENT:
1398 OUTMSG2 (("gdbserver: kernel event CREATE_THREAD_DEBUG_EVENT "
1399 "for pid=%d tid=%x)\n",
1400 (unsigned) current_event.dwProcessId,
1401 (unsigned) current_event.dwThreadId));
1402
1403 /* Record the existence of this thread. */
34b34921 1404 child_add_thread (current_event.dwThreadId,
b80864fb 1405 current_event.u.CreateThread.hThread);
b80864fb
DJ
1406 break;
1407
1408 case EXIT_THREAD_DEBUG_EVENT:
1409 OUTMSG2 (("gdbserver: kernel event EXIT_THREAD_DEBUG_EVENT "
1410 "for pid=%d tid=%x\n",
1411 (unsigned) current_event.dwProcessId,
1412 (unsigned) current_event.dwThreadId));
1413 child_delete_thread (current_event.dwThreadId);
b80864fb
DJ
1414 break;
1415
1416 case CREATE_PROCESS_DEBUG_EVENT:
1417 OUTMSG2 (("gdbserver: kernel event CREATE_PROCESS_DEBUG_EVENT "
1418 "for pid=%d tid=%x\n",
1419 (unsigned) current_event.dwProcessId,
1420 (unsigned) current_event.dwThreadId));
1421 CloseHandle (current_event.u.CreateProcessInfo.hFile);
1422
1423 current_process_handle = current_event.u.CreateProcessInfo.hProcess;
1424 main_thread_id = current_event.dwThreadId;
1425
1426 ourstatus->kind = TARGET_WAITKIND_EXECD;
1427 ourstatus->value.execd_pathname = "Main executable";
1428
1429 /* Add the main thread. */
34b34921
PA
1430 child_add_thread (main_thread_id,
1431 current_event.u.CreateProcessInfo.hThread);
b80864fb 1432
34b34921 1433 ourstatus->value.related_pid = current_event.dwThreadId;
ed50f18f 1434#ifdef _WIN32_WCE
d97903b2
PA
1435 if (!attaching)
1436 {
1437 /* Windows CE doesn't set the initial breakpoint
1438 automatically like the desktop versions of Windows do.
1439 We add it explicitly here. It will be removed as soon as
1440 it is hit. */
1441 set_breakpoint_at ((CORE_ADDR) (long) current_event.u
1442 .CreateProcessInfo.lpStartAddress,
b65d95c5 1443 auto_delete_breakpoint);
d97903b2 1444 }
ed50f18f 1445#endif
b80864fb
DJ
1446 break;
1447
1448 case EXIT_PROCESS_DEBUG_EVENT:
1449 OUTMSG2 (("gdbserver: kernel event EXIT_PROCESS_DEBUG_EVENT "
1450 "for pid=%d tid=%x\n",
1451 (unsigned) current_event.dwProcessId,
1452 (unsigned) current_event.dwThreadId));
1453 ourstatus->kind = TARGET_WAITKIND_EXITED;
1454 ourstatus->value.integer = current_event.u.ExitProcess.dwExitCode;
18aae699 1455 child_continue (DBG_CONTINUE, -1);
b80864fb 1456 CloseHandle (current_process_handle);
9d606399 1457 current_process_handle = NULL;
b80864fb
DJ
1458 break;
1459
1460 case LOAD_DLL_DEBUG_EVENT:
1461 OUTMSG2 (("gdbserver: kernel event LOAD_DLL_DEBUG_EVENT "
1462 "for pid=%d tid=%x\n",
1463 (unsigned) current_event.dwProcessId,
1464 (unsigned) current_event.dwThreadId));
1465 CloseHandle (current_event.u.LoadDll.hFile);
255e7678 1466 handle_load_dll ();
b80864fb
DJ
1467
1468 ourstatus->kind = TARGET_WAITKIND_LOADED;
255e7678 1469 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
b80864fb
DJ
1470 break;
1471
1472 case UNLOAD_DLL_DEBUG_EVENT:
1473 OUTMSG2 (("gdbserver: kernel event UNLOAD_DLL_DEBUG_EVENT "
1474 "for pid=%d tid=%x\n",
1475 (unsigned) current_event.dwProcessId,
1476 (unsigned) current_event.dwThreadId));
255e7678
DJ
1477 handle_unload_dll ();
1478 ourstatus->kind = TARGET_WAITKIND_LOADED;
1479 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
b80864fb
DJ
1480 break;
1481
1482 case EXCEPTION_DEBUG_EVENT:
1483 OUTMSG2 (("gdbserver: kernel event EXCEPTION_DEBUG_EVENT "
1484 "for pid=%d tid=%x\n",
1485 (unsigned) current_event.dwProcessId,
1486 (unsigned) current_event.dwThreadId));
34b34921 1487 handle_exception (ourstatus);
b80864fb
DJ
1488 break;
1489
1490 case OUTPUT_DEBUG_STRING_EVENT:
1491 /* A message from the kernel (or Cygwin). */
1492 OUTMSG2 (("gdbserver: kernel event OUTPUT_DEBUG_STRING_EVENT "
1493 "for pid=%d tid=%x\n",
1494 (unsigned) current_event.dwProcessId,
1495 (unsigned) current_event.dwThreadId));
bce7165d 1496 handle_output_debug_string (ourstatus);
b80864fb
DJ
1497 break;
1498
1499 default:
1500 OUTMSG2 (("gdbserver: kernel event unknown "
1501 "for pid=%d tid=%x code=%ld\n",
1502 (unsigned) current_event.dwProcessId,
1503 (unsigned) current_event.dwThreadId,
1504 current_event.dwDebugEventCode));
1505 break;
1506 }
1507
1508 current_inferior =
1509 (struct thread_info *) find_inferior_id (&all_threads,
1510 current_event.dwThreadId);
4d5d1aaa 1511 return 1;
b80864fb
DJ
1512}
1513
1514/* Wait for the inferior process to change state.
1515 STATUS will be filled in with a response code to send to GDB.
1516 Returns the signal which caused the process to stop. */
1517static unsigned char
1518win32_wait (char *status)
1519{
1520 struct target_waitstatus our_status;
1521
1522 *status = 'T';
1523
1524 while (1)
1525 {
4d5d1aaa
PA
1526 if (!get_child_debug_event (&our_status))
1527 continue;
b80864fb 1528
34b34921 1529 switch (our_status.kind)
b80864fb 1530 {
34b34921 1531 case TARGET_WAITKIND_EXITED:
b80864fb
DJ
1532 OUTMSG2 (("Child exited with retcode = %x\n",
1533 our_status.value.integer));
1534
1535 *status = 'W';
5ac588cf 1536 win32_clear_inferiors ();
b80864fb 1537 return our_status.value.integer;
34b34921 1538 case TARGET_WAITKIND_STOPPED:
1b3f6016 1539 case TARGET_WAITKIND_LOADED:
f72f3e60 1540 OUTMSG2 (("Child Stopped with signal = %d \n",
ed50f18f 1541 our_status.value.sig));
b80864fb
DJ
1542
1543 *status = 'T';
1544
1545 child_fetch_inferior_registers (-1);
1546
255e7678
DJ
1547 if (our_status.kind == TARGET_WAITKIND_LOADED
1548 && !server_waiting)
1549 {
1550 /* When gdb connects, we want to be stopped at the
1551 initial breakpoint, not in some dll load event. */
1552 child_continue (DBG_CONTINUE, -1);
1553 break;
1554 }
1555
b80864fb 1556 return our_status.value.sig;
1b3f6016 1557 default:
34b34921 1558 OUTMSG (("Ignoring unknown internal event, %d\n", our_status.kind));
1b3f6016
PA
1559 /* fall-through */
1560 case TARGET_WAITKIND_SPURIOUS:
1561 case TARGET_WAITKIND_EXECD:
34b34921
PA
1562 /* do nothing, just continue */
1563 child_continue (DBG_CONTINUE, -1);
1564 break;
b80864fb 1565 }
b80864fb
DJ
1566 }
1567}
1568
1569/* Fetch registers from the inferior process.
1570 If REGNO is -1, fetch all registers; otherwise, fetch at least REGNO. */
1571static void
1572win32_fetch_inferior_registers (int regno)
1573{
1574 child_fetch_inferior_registers (regno);
1575}
1576
1577/* Store registers to the inferior process.
1578 If REGNO is -1, store all registers; otherwise, store at least REGNO. */
1579static void
1580win32_store_inferior_registers (int regno)
1581{
1582 child_store_inferior_registers (regno);
1583}
1584
1585/* Read memory from the inferior process. This should generally be
1586 called through read_inferior_memory, which handles breakpoint shadowing.
1587 Read LEN bytes at MEMADDR into a buffer at MYADDR. */
1588static int
1589win32_read_inferior_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
1590{
ed50f18f 1591 return child_xfer_memory (memaddr, (char *) myaddr, len, 0, 0) != len;
b80864fb
DJ
1592}
1593
1594/* Write memory to the inferior process. This should generally be
1595 called through write_inferior_memory, which handles breakpoint shadowing.
1596 Write LEN bytes from the buffer at MYADDR to MEMADDR.
1597 Returns 0 on success and errno on failure. */
1598static int
1599win32_write_inferior_memory (CORE_ADDR memaddr, const unsigned char *myaddr,
1600 int len)
1601{
1602 return child_xfer_memory (memaddr, (char *) myaddr, len, 1, 0) != len;
1603}
1604
7390519e
PA
1605/* Send an interrupt request to the inferior process. */
1606static void
1607win32_request_interrupt (void)
1608{
1609 winapi_DebugBreakProcess DebugBreakProcess;
1610 winapi_GenerateConsoleCtrlEvent GenerateConsoleCtrlEvent;
1611
1612#ifdef _WIN32_WCE
1613 HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
1614#else
1615 HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
1616#endif
1617
1618 GenerateConsoleCtrlEvent = GETPROCADDRESS (dll, GenerateConsoleCtrlEvent);
1619
1620 if (GenerateConsoleCtrlEvent != NULL
1621 && GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, current_process_id))
1622 return;
1623
1624 /* GenerateConsoleCtrlEvent can fail if process id being debugged is
1625 not a process group id.
1626 Fallback to XP/Vista 'DebugBreakProcess', which generates a
1627 breakpoint exception in the interior process. */
1628
1629 DebugBreakProcess = GETPROCADDRESS (dll, DebugBreakProcess);
1630
1631 if (DebugBreakProcess != NULL
1632 && DebugBreakProcess (current_process_handle))
1633 return;
1634
4d5d1aaa
PA
1635 /* Last resort, suspend all threads manually. */
1636 soft_interrupt_requested = 1;
7390519e
PA
1637}
1638
59a016f0
PA
1639#ifdef _WIN32_WCE
1640int
1641win32_error_to_fileio_error (DWORD err)
1642{
1643 switch (err)
1644 {
1645 case ERROR_BAD_PATHNAME:
1646 case ERROR_FILE_NOT_FOUND:
1647 case ERROR_INVALID_NAME:
1648 case ERROR_PATH_NOT_FOUND:
1649 return FILEIO_ENOENT;
1650 case ERROR_CRC:
1651 case ERROR_IO_DEVICE:
1652 case ERROR_OPEN_FAILED:
1653 return FILEIO_EIO;
1654 case ERROR_INVALID_HANDLE:
1655 return FILEIO_EBADF;
1656 case ERROR_ACCESS_DENIED:
1657 case ERROR_SHARING_VIOLATION:
1658 return FILEIO_EACCES;
1659 case ERROR_NOACCESS:
1660 return FILEIO_EFAULT;
1661 case ERROR_BUSY:
1662 return FILEIO_EBUSY;
1663 case ERROR_ALREADY_EXISTS:
1664 case ERROR_FILE_EXISTS:
1665 return FILEIO_EEXIST;
1666 case ERROR_BAD_DEVICE:
1667 return FILEIO_ENODEV;
1668 case ERROR_DIRECTORY:
1669 return FILEIO_ENOTDIR;
1670 case ERROR_FILENAME_EXCED_RANGE:
1671 case ERROR_INVALID_DATA:
1672 case ERROR_INVALID_PARAMETER:
1673 case ERROR_NEGATIVE_SEEK:
1674 return FILEIO_EINVAL;
1675 case ERROR_TOO_MANY_OPEN_FILES:
1676 return FILEIO_EMFILE;
1677 case ERROR_HANDLE_DISK_FULL:
1678 case ERROR_DISK_FULL:
1679 return FILEIO_ENOSPC;
1680 case ERROR_WRITE_PROTECT:
1681 return FILEIO_EROFS;
1682 case ERROR_NOT_SUPPORTED:
1683 return FILEIO_ENOSYS;
1684 }
1685
1686 return FILEIO_EUNKNOWN;
1687}
1688
1689static void
1690wince_hostio_last_error (char *buf)
1691{
1692 DWORD winerr = GetLastError ();
1693 int fileio_err = win32_error_to_fileio_error (winerr);
1694 sprintf (buf, "F-1,%x", fileio_err);
1695}
1696#endif
1697
b80864fb
DJ
1698static struct target_ops win32_target_ops = {
1699 win32_create_inferior,
1700 win32_attach,
1701 win32_kill,
1702 win32_detach,
444d6139 1703 win32_join,
b80864fb
DJ
1704 win32_thread_alive,
1705 win32_resume,
1706 win32_wait,
1707 win32_fetch_inferior_registers,
1708 win32_store_inferior_registers,
1709 win32_read_inferior_memory,
1710 win32_write_inferior_memory,
820f2bda 1711 NULL,
7390519e 1712 win32_request_interrupt,
820f2bda
PA
1713 NULL,
1714 NULL,
1715 NULL,
1716 NULL,
1717 NULL,
1718 NULL,
1719 NULL,
59a016f0
PA
1720 NULL,
1721#ifdef _WIN32_WCE
1722 wince_hostio_last_error,
1723#else
1724 hostio_last_error_from_errno,
1725#endif
b80864fb
DJ
1726};
1727
1728/* Initialize the Win32 backend. */
1729void
1730initialize_low (void)
1731{
1732 set_target_ops (&win32_target_ops);
ed50f18f
PA
1733 if (the_low_target.breakpoint != NULL)
1734 set_breakpoint_data (the_low_target.breakpoint,
1735 the_low_target.breakpoint_len);
d05b4ac3 1736 the_low_target.arch_setup ();
b80864fb 1737}