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