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