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