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