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