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