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