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