]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdbserver/win32-low.cc
gdbserver: turn target op 'resume' into a method
[thirdparty/binutils-gdb.git] / gdbserver / win32-low.cc
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 EXCEPTION_RECORD siginfo_er; /* Contents of $_siginfo */
79 static enum gdb_signal last_sig = GDB_SIGNAL_0;
80
81 /* The current debug event from WaitForDebugEvent. */
82 static DEBUG_EVENT current_event;
83
84 /* A status that hasn't been reported to the core yet, and so
85 win32_wait should return it next, instead of fetching the next
86 debug event off the win32 API. */
87 static struct target_waitstatus cached_status;
88
89 /* Non zero if an interrupt request is to be satisfied by suspending
90 all threads. */
91 static int soft_interrupt_requested = 0;
92
93 /* Non zero if the inferior is stopped in a simulated breakpoint done
94 by suspending all the threads. */
95 static int faked_breakpoint = 0;
96
97 const struct target_desc *win32_tdesc;
98
99 #define NUM_REGS (the_low_target.num_regs)
100
101 typedef BOOL (WINAPI *winapi_DebugActiveProcessStop) (DWORD dwProcessId);
102 typedef BOOL (WINAPI *winapi_DebugSetProcessKillOnExit) (BOOL KillOnExit);
103 typedef BOOL (WINAPI *winapi_DebugBreakProcess) (HANDLE);
104 typedef BOOL (WINAPI *winapi_GenerateConsoleCtrlEvent) (DWORD, DWORD);
105
106 static ptid_t win32_wait (ptid_t ptid, struct target_waitstatus *ourstatus,
107 int options);
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 the_target->pt->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 size_t argslen, proglen;
562
563 proglen = strlen (program) + 1;
564 argslen = strlen (args) + proglen;
565
566 #ifdef _WIN32_WCE
567 wchar_t *p, *wprogram, *wargs, *wcwd = NULL;
568
569 wprogram = (wchar_t *) alloca (proglen * sizeof (wchar_t));
570 mbstowcs (wprogram, program, proglen);
571
572 for (p = wprogram; *p; ++p)
573 if (L'/' == *p)
574 *p = L'\\';
575
576 wargs = alloca ((argslen + 1) * sizeof (wchar_t));
577 wcscpy (wargs, wprogram);
578 wcscat (wargs, L" ");
579 mbstowcs (wargs + proglen, args, argslen + 1 - proglen);
580
581 if (inferior_cwd != NULL)
582 {
583 std::string expanded_infcwd = gdb_tilde_expand (inferior_cwd);
584 std::replace (expanded_infcwd.begin (), expanded_infcwd.end (),
585 '/', '\\');
586 wcwd = alloca ((expanded_infcwd.size () + 1) * sizeof (wchar_t));
587 if (mbstowcs (wcwd, expanded_infcwd.c_str (),
588 expanded_infcwd.size () + 1) == NULL)
589 {
590 error (_("\
591 Could not convert the expanded inferior cwd to wide-char."));
592 }
593 }
594
595 ret = CreateProcessW (wprogram, /* image name */
596 wargs, /* command line */
597 NULL, /* security, not supported */
598 NULL, /* thread, not supported */
599 FALSE, /* inherit handles, not supported */
600 flags, /* start flags */
601 NULL, /* environment, not supported */
602 wcwd, /* current directory */
603 NULL, /* start info, not supported */
604 pi); /* proc info */
605 #else
606 STARTUPINFOA si = { sizeof (STARTUPINFOA) };
607 char *program_and_args = (char *) alloca (argslen + 1);
608
609 strcpy (program_and_args, program);
610 strcat (program_and_args, " ");
611 strcat (program_and_args, args);
612 ret = CreateProcessA (program, /* image name */
613 program_and_args, /* command line */
614 NULL, /* security */
615 NULL, /* thread */
616 TRUE, /* inherit handles */
617 flags, /* start flags */
618 NULL, /* environment */
619 /* current directory */
620 (inferior_cwd == NULL
621 ? NULL
622 : gdb_tilde_expand (inferior_cwd).c_str()),
623 &si, /* start info */
624 pi); /* proc info */
625 #endif
626
627 return ret;
628 }
629
630 /* Start a new process.
631 PROGRAM is the program name.
632 PROGRAM_ARGS is the vector containing the inferior's args.
633 Returns the new PID on success, -1 on failure. Registers the new
634 process with the process list. */
635 int
636 win32_process_target::create_inferior (const char *program,
637 const std::vector<char *> &program_args)
638 {
639 client_state &cs = get_client_state ();
640 #ifndef USE_WIN32API
641 char real_path[PATH_MAX];
642 char *orig_path, *new_path, *path_ptr;
643 #endif
644 BOOL ret;
645 DWORD flags;
646 PROCESS_INFORMATION pi;
647 DWORD err;
648 std::string str_program_args = stringify_argv (program_args);
649 char *args = (char *) str_program_args.c_str ();
650
651 /* win32_wait needs to know we're not attaching. */
652 attaching = 0;
653
654 if (!program)
655 error ("No executable specified, specify executable to debug.\n");
656
657 flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS;
658
659 #ifndef USE_WIN32API
660 orig_path = NULL;
661 path_ptr = getenv ("PATH");
662 if (path_ptr)
663 {
664 int size = cygwin_conv_path_list (CCP_POSIX_TO_WIN_A, path_ptr, NULL, 0);
665 orig_path = (char *) alloca (strlen (path_ptr) + 1);
666 new_path = (char *) alloca (size);
667 strcpy (orig_path, path_ptr);
668 cygwin_conv_path_list (CCP_POSIX_TO_WIN_A, path_ptr, new_path, size);
669 setenv ("PATH", new_path, 1);
670 }
671 cygwin_conv_path (CCP_POSIX_TO_WIN_A, program, real_path, PATH_MAX);
672 program = real_path;
673 #endif
674
675 OUTMSG2 (("Command line is \"%s %s\"\n", program, args));
676
677 #ifdef CREATE_NEW_PROCESS_GROUP
678 flags |= CREATE_NEW_PROCESS_GROUP;
679 #endif
680
681 ret = create_process (program, args, flags, &pi);
682 err = GetLastError ();
683 if (!ret && err == ERROR_FILE_NOT_FOUND)
684 {
685 char *exename = (char *) alloca (strlen (program) + 5);
686 strcat (strcpy (exename, program), ".exe");
687 ret = create_process (exename, args, flags, &pi);
688 err = GetLastError ();
689 }
690
691 #ifndef USE_WIN32API
692 if (orig_path)
693 setenv ("PATH", orig_path, 1);
694 #endif
695
696 if (!ret)
697 {
698 error ("Error creating process \"%s %s\", (error %d): %s\n",
699 program, args, (int) err, strwinerror (err));
700 }
701 else
702 {
703 OUTMSG2 (("Process created: %s %s\n", program, (char *) args));
704 }
705
706 #ifndef _WIN32_WCE
707 /* On Windows CE this handle can't be closed. The OS reuses
708 it in the debug events, while the 9x/NT versions of Windows
709 probably use a DuplicateHandle'd one. */
710 CloseHandle (pi.hThread);
711 #endif
712
713 do_initial_child_stuff (pi.hProcess, pi.dwProcessId, 0);
714
715 /* Wait till we are at 1st instruction in program, return new pid
716 (assuming success). */
717 cs.last_ptid = win32_wait (ptid_t (current_process_id), &cs.last_status, 0);
718
719 /* Necessary for handle_v_kill. */
720 signal_pid = current_process_id;
721
722 return current_process_id;
723 }
724
725 /* Attach to a running process.
726 PID is the process ID to attach to, specified by the user
727 or a higher layer. */
728 int
729 win32_process_target::attach (unsigned long pid)
730 {
731 HANDLE h;
732 winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit = NULL;
733 DWORD err;
734 #ifdef _WIN32_WCE
735 HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
736 #else
737 HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
738 #endif
739 DebugSetProcessKillOnExit = GETPROCADDRESS (dll, DebugSetProcessKillOnExit);
740
741 h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
742 if (h != NULL)
743 {
744 if (DebugActiveProcess (pid))
745 {
746 if (DebugSetProcessKillOnExit != NULL)
747 DebugSetProcessKillOnExit (FALSE);
748
749 /* win32_wait needs to know we're attaching. */
750 attaching = 1;
751 do_initial_child_stuff (h, pid, 1);
752 return 0;
753 }
754
755 CloseHandle (h);
756 }
757
758 err = GetLastError ();
759 error ("Attach to process failed (error %d): %s\n",
760 (int) err, strwinerror (err));
761 }
762
763 /* Handle OUTPUT_DEBUG_STRING_EVENT from child process. */
764 static void
765 handle_output_debug_string (void)
766 {
767 #define READ_BUFFER_LEN 1024
768 CORE_ADDR addr;
769 char s[READ_BUFFER_LEN + 1] = { 0 };
770 DWORD nbytes = current_event.u.DebugString.nDebugStringLength;
771
772 if (nbytes == 0)
773 return;
774
775 if (nbytes > READ_BUFFER_LEN)
776 nbytes = READ_BUFFER_LEN;
777
778 addr = (CORE_ADDR) (size_t) current_event.u.DebugString.lpDebugStringData;
779
780 if (current_event.u.DebugString.fUnicode)
781 {
782 /* The event tells us how many bytes, not chars, even
783 in Unicode. */
784 WCHAR buffer[(READ_BUFFER_LEN + 1) / sizeof (WCHAR)] = { 0 };
785 if (read_inferior_memory (addr, (unsigned char *) buffer, nbytes) != 0)
786 return;
787 wcstombs (s, buffer, (nbytes + 1) / sizeof (WCHAR));
788 }
789 else
790 {
791 if (read_inferior_memory (addr, (unsigned char *) s, nbytes) != 0)
792 return;
793 }
794
795 if (!startswith (s, "cYg"))
796 {
797 if (!server_waiting)
798 {
799 OUTMSG2(("%s", s));
800 return;
801 }
802
803 monitor_output (s);
804 }
805 #undef READ_BUFFER_LEN
806 }
807
808 static void
809 win32_clear_inferiors (void)
810 {
811 if (current_process_handle != NULL)
812 CloseHandle (current_process_handle);
813
814 for_each_thread (delete_thread_info);
815 siginfo_er.ExceptionCode = 0;
816 clear_inferiors ();
817 }
818
819 /* Implementation of target_ops::kill. */
820
821 int
822 win32_process_target::kill (process_info *process)
823 {
824 TerminateProcess (current_process_handle, 0);
825 for (;;)
826 {
827 if (!child_continue (DBG_CONTINUE, -1))
828 break;
829 if (!WaitForDebugEvent (&current_event, INFINITE))
830 break;
831 if (current_event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
832 break;
833 else if (current_event.dwDebugEventCode == OUTPUT_DEBUG_STRING_EVENT)
834 handle_output_debug_string ();
835 }
836
837 win32_clear_inferiors ();
838
839 remove_process (process);
840 return 0;
841 }
842
843 /* Implementation of target_ops::detach. */
844
845 int
846 win32_process_target::detach (process_info *process)
847 {
848 winapi_DebugActiveProcessStop DebugActiveProcessStop = NULL;
849 winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit = NULL;
850 #ifdef _WIN32_WCE
851 HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
852 #else
853 HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
854 #endif
855 DebugActiveProcessStop = GETPROCADDRESS (dll, DebugActiveProcessStop);
856 DebugSetProcessKillOnExit = GETPROCADDRESS (dll, DebugSetProcessKillOnExit);
857
858 if (DebugSetProcessKillOnExit == NULL
859 || DebugActiveProcessStop == NULL)
860 return -1;
861
862 {
863 struct thread_resume resume;
864 resume.thread = minus_one_ptid;
865 resume.kind = resume_continue;
866 resume.sig = 0;
867 this->resume (&resume, 1);
868 }
869
870 if (!DebugActiveProcessStop (current_process_id))
871 return -1;
872
873 DebugSetProcessKillOnExit (FALSE);
874 remove_process (process);
875
876 win32_clear_inferiors ();
877 return 0;
878 }
879
880 void
881 win32_process_target::mourn (struct process_info *process)
882 {
883 remove_process (process);
884 }
885
886 /* Implementation of target_ops::join. */
887
888 void
889 win32_process_target::join (int pid)
890 {
891 HANDLE h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
892 if (h != NULL)
893 {
894 WaitForSingleObject (h, INFINITE);
895 CloseHandle (h);
896 }
897 }
898
899 /* Return true iff the thread with thread ID TID is alive. */
900 bool
901 win32_process_target::thread_alive (ptid_t ptid)
902 {
903 /* Our thread list is reliable; don't bother to poll target
904 threads. */
905 return find_thread_ptid (ptid) != NULL;
906 }
907
908 /* Resume the inferior process. RESUME_INFO describes how we want
909 to resume. */
910 void
911 win32_process_target::resume (thread_resume *resume_info, size_t n)
912 {
913 DWORD tid;
914 enum gdb_signal sig;
915 int step;
916 win32_thread_info *th;
917 DWORD continue_status = DBG_CONTINUE;
918 ptid_t ptid;
919
920 /* This handles the very limited set of resume packets that GDB can
921 currently produce. */
922
923 if (n == 1 && resume_info[0].thread == minus_one_ptid)
924 tid = -1;
925 else if (n > 1)
926 tid = -1;
927 else
928 /* Yes, we're ignoring resume_info[0].thread. It'd be tricky to make
929 the Windows resume code do the right thing for thread switching. */
930 tid = current_event.dwThreadId;
931
932 if (resume_info[0].thread != minus_one_ptid)
933 {
934 sig = gdb_signal_from_host (resume_info[0].sig);
935 step = resume_info[0].kind == resume_step;
936 }
937 else
938 {
939 sig = GDB_SIGNAL_0;
940 step = 0;
941 }
942
943 if (sig != GDB_SIGNAL_0)
944 {
945 if (current_event.dwDebugEventCode != EXCEPTION_DEBUG_EVENT)
946 {
947 OUTMSG (("Cannot continue with signal %s here.\n",
948 gdb_signal_to_string (sig)));
949 }
950 else if (sig == last_sig)
951 continue_status = DBG_EXCEPTION_NOT_HANDLED;
952 else
953 OUTMSG (("Can only continue with received signal %s.\n",
954 gdb_signal_to_string (last_sig)));
955 }
956
957 last_sig = GDB_SIGNAL_0;
958
959 /* Get context for the currently selected thread. */
960 ptid = debug_event_ptid (&current_event);
961 th = thread_rec (ptid, FALSE);
962 if (th)
963 {
964 win32_prepare_to_resume (th);
965
966 if (th->context.ContextFlags)
967 {
968 /* Move register values from the inferior into the thread
969 context structure. */
970 regcache_invalidate ();
971
972 if (step)
973 {
974 if (the_low_target.single_step != NULL)
975 (*the_low_target.single_step) (th);
976 else
977 error ("Single stepping is not supported "
978 "in this configuration.\n");
979 }
980
981 win32_set_thread_context (th);
982 th->context.ContextFlags = 0;
983 }
984 }
985
986 /* Allow continuing with the same signal that interrupted us.
987 Otherwise complain. */
988
989 child_continue (continue_status, tid);
990 }
991
992 static void
993 win32_add_one_solib (const char *name, CORE_ADDR load_addr)
994 {
995 char buf[MAX_PATH + 1];
996 char buf2[MAX_PATH + 1];
997
998 #ifdef _WIN32_WCE
999 WIN32_FIND_DATA w32_fd;
1000 WCHAR wname[MAX_PATH + 1];
1001 mbstowcs (wname, name, MAX_PATH);
1002 HANDLE h = FindFirstFile (wname, &w32_fd);
1003 #else
1004 WIN32_FIND_DATAA w32_fd;
1005 HANDLE h = FindFirstFileA (name, &w32_fd);
1006 #endif
1007
1008 /* The symbols in a dll are offset by 0x1000, which is the
1009 offset from 0 of the first byte in an image - because
1010 of the file header and the section alignment. */
1011 load_addr += 0x1000;
1012
1013 if (h == INVALID_HANDLE_VALUE)
1014 strcpy (buf, name);
1015 else
1016 {
1017 FindClose (h);
1018 strcpy (buf, name);
1019 #ifndef _WIN32_WCE
1020 {
1021 char cwd[MAX_PATH + 1];
1022 char *p;
1023 if (GetCurrentDirectoryA (MAX_PATH + 1, cwd))
1024 {
1025 p = strrchr (buf, '\\');
1026 if (p)
1027 p[1] = '\0';
1028 SetCurrentDirectoryA (buf);
1029 GetFullPathNameA (w32_fd.cFileName, MAX_PATH, buf, &p);
1030 SetCurrentDirectoryA (cwd);
1031 }
1032 }
1033 #endif
1034 }
1035
1036 #ifndef _WIN32_WCE
1037 if (strcasecmp (buf, "ntdll.dll") == 0)
1038 {
1039 GetSystemDirectoryA (buf, sizeof (buf));
1040 strcat (buf, "\\ntdll.dll");
1041 }
1042 #endif
1043
1044 #ifdef __CYGWIN__
1045 cygwin_conv_path (CCP_WIN_A_TO_POSIX, buf, buf2, sizeof (buf2));
1046 #else
1047 strcpy (buf2, buf);
1048 #endif
1049
1050 loaded_dll (buf2, load_addr);
1051 }
1052
1053 static char *
1054 get_image_name (HANDLE h, void *address, int unicode)
1055 {
1056 static char buf[(2 * MAX_PATH) + 1];
1057 DWORD size = unicode ? sizeof (WCHAR) : sizeof (char);
1058 char *address_ptr;
1059 int len = 0;
1060 char b[2];
1061 SIZE_T done;
1062
1063 /* Attempt to read the name of the dll that was detected.
1064 This is documented to work only when actively debugging
1065 a program. It will not work for attached processes. */
1066 if (address == NULL)
1067 return NULL;
1068
1069 #ifdef _WIN32_WCE
1070 /* Windows CE reports the address of the image name,
1071 instead of an address of a pointer into the image name. */
1072 address_ptr = address;
1073 #else
1074 /* See if we could read the address of a string, and that the
1075 address isn't null. */
1076 if (!ReadProcessMemory (h, address, &address_ptr,
1077 sizeof (address_ptr), &done)
1078 || done != sizeof (address_ptr)
1079 || !address_ptr)
1080 return NULL;
1081 #endif
1082
1083 /* Find the length of the string */
1084 while (ReadProcessMemory (h, address_ptr + len++ * size, &b, size, &done)
1085 && (b[0] != 0 || b[size - 1] != 0) && done == size)
1086 continue;
1087
1088 if (!unicode)
1089 ReadProcessMemory (h, address_ptr, buf, len, &done);
1090 else
1091 {
1092 WCHAR *unicode_address = XALLOCAVEC (WCHAR, len);
1093 ReadProcessMemory (h, address_ptr, unicode_address, len * sizeof (WCHAR),
1094 &done);
1095
1096 WideCharToMultiByte (CP_ACP, 0, unicode_address, len, buf, len, 0, 0);
1097 }
1098
1099 return buf;
1100 }
1101
1102 typedef BOOL (WINAPI *winapi_EnumProcessModules) (HANDLE, HMODULE *,
1103 DWORD, LPDWORD);
1104 typedef BOOL (WINAPI *winapi_GetModuleInformation) (HANDLE, HMODULE,
1105 LPMODULEINFO, DWORD);
1106 typedef DWORD (WINAPI *winapi_GetModuleFileNameExA) (HANDLE, HMODULE,
1107 LPSTR, DWORD);
1108
1109 static winapi_EnumProcessModules win32_EnumProcessModules;
1110 static winapi_GetModuleInformation win32_GetModuleInformation;
1111 static winapi_GetModuleFileNameExA win32_GetModuleFileNameExA;
1112
1113 static BOOL
1114 load_psapi (void)
1115 {
1116 static int psapi_loaded = 0;
1117 static HMODULE dll = NULL;
1118
1119 if (!psapi_loaded)
1120 {
1121 psapi_loaded = 1;
1122 dll = LoadLibrary (TEXT("psapi.dll"));
1123 if (!dll)
1124 return FALSE;
1125 win32_EnumProcessModules =
1126 GETPROCADDRESS (dll, EnumProcessModules);
1127 win32_GetModuleInformation =
1128 GETPROCADDRESS (dll, GetModuleInformation);
1129 win32_GetModuleFileNameExA =
1130 GETPROCADDRESS (dll, GetModuleFileNameExA);
1131 }
1132
1133 return (win32_EnumProcessModules != NULL
1134 && win32_GetModuleInformation != NULL
1135 && win32_GetModuleFileNameExA != NULL);
1136 }
1137
1138 #ifndef _WIN32_WCE
1139
1140 /* Iterate over all DLLs currently mapped by our inferior, and
1141 add them to our list of solibs. */
1142
1143 static void
1144 win32_add_all_dlls (void)
1145 {
1146 size_t i;
1147 HMODULE dh_buf[1];
1148 HMODULE *DllHandle = dh_buf;
1149 DWORD cbNeeded;
1150 BOOL ok;
1151
1152 if (!load_psapi ())
1153 return;
1154
1155 cbNeeded = 0;
1156 ok = (*win32_EnumProcessModules) (current_process_handle,
1157 DllHandle,
1158 sizeof (HMODULE),
1159 &cbNeeded);
1160
1161 if (!ok || !cbNeeded)
1162 return;
1163
1164 DllHandle = (HMODULE *) alloca (cbNeeded);
1165 if (!DllHandle)
1166 return;
1167
1168 ok = (*win32_EnumProcessModules) (current_process_handle,
1169 DllHandle,
1170 cbNeeded,
1171 &cbNeeded);
1172 if (!ok)
1173 return;
1174
1175 for (i = 1; i < ((size_t) cbNeeded / sizeof (HMODULE)); i++)
1176 {
1177 MODULEINFO mi;
1178 char dll_name[MAX_PATH];
1179
1180 if (!(*win32_GetModuleInformation) (current_process_handle,
1181 DllHandle[i],
1182 &mi,
1183 sizeof (mi)))
1184 continue;
1185 if ((*win32_GetModuleFileNameExA) (current_process_handle,
1186 DllHandle[i],
1187 dll_name,
1188 MAX_PATH) == 0)
1189 continue;
1190 win32_add_one_solib (dll_name, (CORE_ADDR) (uintptr_t) mi.lpBaseOfDll);
1191 }
1192 }
1193 #endif
1194
1195 typedef HANDLE (WINAPI *winapi_CreateToolhelp32Snapshot) (DWORD, DWORD);
1196 typedef BOOL (WINAPI *winapi_Module32First) (HANDLE, LPMODULEENTRY32);
1197 typedef BOOL (WINAPI *winapi_Module32Next) (HANDLE, LPMODULEENTRY32);
1198
1199 /* Handle a DLL load event.
1200
1201 This function assumes that this event did not occur during inferior
1202 initialization, where their event info may be incomplete (see
1203 do_initial_child_stuff and win32_add_all_dlls for more info on
1204 how we handle DLL loading during that phase). */
1205
1206 static void
1207 handle_load_dll (void)
1208 {
1209 LOAD_DLL_DEBUG_INFO *event = &current_event.u.LoadDll;
1210 char *dll_name;
1211
1212 dll_name = get_image_name (current_process_handle,
1213 event->lpImageName, event->fUnicode);
1214 if (!dll_name)
1215 return;
1216
1217 win32_add_one_solib (dll_name, (CORE_ADDR) (uintptr_t) event->lpBaseOfDll);
1218 }
1219
1220 /* Handle a DLL unload event.
1221
1222 This function assumes that this event did not occur during inferior
1223 initialization, where their event info may be incomplete (see
1224 do_initial_child_stuff and win32_add_one_solib for more info
1225 on how we handle DLL loading during that phase). */
1226
1227 static void
1228 handle_unload_dll (void)
1229 {
1230 CORE_ADDR load_addr =
1231 (CORE_ADDR) (uintptr_t) current_event.u.UnloadDll.lpBaseOfDll;
1232
1233 /* The symbols in a dll are offset by 0x1000, which is the
1234 offset from 0 of the first byte in an image - because
1235 of the file header and the section alignment. */
1236 load_addr += 0x1000;
1237 unloaded_dll (NULL, load_addr);
1238 }
1239
1240 static void
1241 handle_exception (struct target_waitstatus *ourstatus)
1242 {
1243 DWORD code = current_event.u.Exception.ExceptionRecord.ExceptionCode;
1244
1245 memcpy (&siginfo_er, &current_event.u.Exception.ExceptionRecord,
1246 sizeof siginfo_er);
1247
1248 ourstatus->kind = TARGET_WAITKIND_STOPPED;
1249
1250 switch (code)
1251 {
1252 case EXCEPTION_ACCESS_VIOLATION:
1253 OUTMSG2 (("EXCEPTION_ACCESS_VIOLATION"));
1254 ourstatus->value.sig = GDB_SIGNAL_SEGV;
1255 break;
1256 case STATUS_STACK_OVERFLOW:
1257 OUTMSG2 (("STATUS_STACK_OVERFLOW"));
1258 ourstatus->value.sig = GDB_SIGNAL_SEGV;
1259 break;
1260 case STATUS_FLOAT_DENORMAL_OPERAND:
1261 OUTMSG2 (("STATUS_FLOAT_DENORMAL_OPERAND"));
1262 ourstatus->value.sig = GDB_SIGNAL_FPE;
1263 break;
1264 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
1265 OUTMSG2 (("EXCEPTION_ARRAY_BOUNDS_EXCEEDED"));
1266 ourstatus->value.sig = GDB_SIGNAL_FPE;
1267 break;
1268 case STATUS_FLOAT_INEXACT_RESULT:
1269 OUTMSG2 (("STATUS_FLOAT_INEXACT_RESULT"));
1270 ourstatus->value.sig = GDB_SIGNAL_FPE;
1271 break;
1272 case STATUS_FLOAT_INVALID_OPERATION:
1273 OUTMSG2 (("STATUS_FLOAT_INVALID_OPERATION"));
1274 ourstatus->value.sig = GDB_SIGNAL_FPE;
1275 break;
1276 case STATUS_FLOAT_OVERFLOW:
1277 OUTMSG2 (("STATUS_FLOAT_OVERFLOW"));
1278 ourstatus->value.sig = GDB_SIGNAL_FPE;
1279 break;
1280 case STATUS_FLOAT_STACK_CHECK:
1281 OUTMSG2 (("STATUS_FLOAT_STACK_CHECK"));
1282 ourstatus->value.sig = GDB_SIGNAL_FPE;
1283 break;
1284 case STATUS_FLOAT_UNDERFLOW:
1285 OUTMSG2 (("STATUS_FLOAT_UNDERFLOW"));
1286 ourstatus->value.sig = GDB_SIGNAL_FPE;
1287 break;
1288 case STATUS_FLOAT_DIVIDE_BY_ZERO:
1289 OUTMSG2 (("STATUS_FLOAT_DIVIDE_BY_ZERO"));
1290 ourstatus->value.sig = GDB_SIGNAL_FPE;
1291 break;
1292 case STATUS_INTEGER_DIVIDE_BY_ZERO:
1293 OUTMSG2 (("STATUS_INTEGER_DIVIDE_BY_ZERO"));
1294 ourstatus->value.sig = GDB_SIGNAL_FPE;
1295 break;
1296 case STATUS_INTEGER_OVERFLOW:
1297 OUTMSG2 (("STATUS_INTEGER_OVERFLOW"));
1298 ourstatus->value.sig = GDB_SIGNAL_FPE;
1299 break;
1300 case EXCEPTION_BREAKPOINT:
1301 OUTMSG2 (("EXCEPTION_BREAKPOINT"));
1302 ourstatus->value.sig = GDB_SIGNAL_TRAP;
1303 #ifdef _WIN32_WCE
1304 /* Remove the initial breakpoint. */
1305 check_breakpoints ((CORE_ADDR) (long) current_event
1306 .u.Exception.ExceptionRecord.ExceptionAddress);
1307 #endif
1308 break;
1309 case DBG_CONTROL_C:
1310 OUTMSG2 (("DBG_CONTROL_C"));
1311 ourstatus->value.sig = GDB_SIGNAL_INT;
1312 break;
1313 case DBG_CONTROL_BREAK:
1314 OUTMSG2 (("DBG_CONTROL_BREAK"));
1315 ourstatus->value.sig = GDB_SIGNAL_INT;
1316 break;
1317 case EXCEPTION_SINGLE_STEP:
1318 OUTMSG2 (("EXCEPTION_SINGLE_STEP"));
1319 ourstatus->value.sig = GDB_SIGNAL_TRAP;
1320 break;
1321 case EXCEPTION_ILLEGAL_INSTRUCTION:
1322 OUTMSG2 (("EXCEPTION_ILLEGAL_INSTRUCTION"));
1323 ourstatus->value.sig = GDB_SIGNAL_ILL;
1324 break;
1325 case EXCEPTION_PRIV_INSTRUCTION:
1326 OUTMSG2 (("EXCEPTION_PRIV_INSTRUCTION"));
1327 ourstatus->value.sig = GDB_SIGNAL_ILL;
1328 break;
1329 case EXCEPTION_NONCONTINUABLE_EXCEPTION:
1330 OUTMSG2 (("EXCEPTION_NONCONTINUABLE_EXCEPTION"));
1331 ourstatus->value.sig = GDB_SIGNAL_ILL;
1332 break;
1333 default:
1334 if (current_event.u.Exception.dwFirstChance)
1335 {
1336 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
1337 return;
1338 }
1339 OUTMSG2 (("gdbserver: unknown target exception 0x%08x at 0x%s",
1340 (unsigned) current_event.u.Exception.ExceptionRecord.ExceptionCode,
1341 phex_nz ((uintptr_t) current_event.u.Exception.ExceptionRecord.
1342 ExceptionAddress, sizeof (uintptr_t))));
1343 ourstatus->value.sig = GDB_SIGNAL_UNKNOWN;
1344 break;
1345 }
1346 OUTMSG2 (("\n"));
1347 last_sig = ourstatus->value.sig;
1348 }
1349
1350
1351 static void
1352 suspend_one_thread (thread_info *thread)
1353 {
1354 win32_thread_info *th = (win32_thread_info *) thread_target_data (thread);
1355
1356 if (!th->suspended)
1357 {
1358 if (SuspendThread (th->h) == (DWORD) -1)
1359 {
1360 DWORD err = GetLastError ();
1361 OUTMSG (("warning: SuspendThread failed in suspend_one_thread, "
1362 "(error %d): %s\n", (int) err, strwinerror (err)));
1363 }
1364 else
1365 th->suspended = 1;
1366 }
1367 }
1368
1369 static void
1370 fake_breakpoint_event (void)
1371 {
1372 OUTMSG2(("fake_breakpoint_event\n"));
1373
1374 faked_breakpoint = 1;
1375
1376 memset (&current_event, 0, sizeof (current_event));
1377 current_event.dwThreadId = main_thread_id;
1378 current_event.dwDebugEventCode = EXCEPTION_DEBUG_EVENT;
1379 current_event.u.Exception.ExceptionRecord.ExceptionCode
1380 = EXCEPTION_BREAKPOINT;
1381
1382 for_each_thread (suspend_one_thread);
1383 }
1384
1385 #ifdef _WIN32_WCE
1386 static int
1387 auto_delete_breakpoint (CORE_ADDR stop_pc)
1388 {
1389 return 1;
1390 }
1391 #endif
1392
1393 /* Get the next event from the child. */
1394
1395 static int
1396 get_child_debug_event (struct target_waitstatus *ourstatus)
1397 {
1398 ptid_t ptid;
1399
1400 last_sig = GDB_SIGNAL_0;
1401 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
1402
1403 /* Check if GDB sent us an interrupt request. */
1404 check_remote_input_interrupt_request ();
1405
1406 if (soft_interrupt_requested)
1407 {
1408 soft_interrupt_requested = 0;
1409 fake_breakpoint_event ();
1410 goto gotevent;
1411 }
1412
1413 #ifndef _WIN32_WCE
1414 attaching = 0;
1415 #else
1416 if (attaching)
1417 {
1418 /* WinCE doesn't set an initial breakpoint automatically. To
1419 stop the inferior, we flush all currently pending debug
1420 events -- the thread list and the dll list are always
1421 reported immediatelly without delay, then, we suspend all
1422 threads and pretend we saw a trap at the current PC of the
1423 main thread.
1424
1425 Contrary to desktop Windows, Windows CE *does* report the dll
1426 names on LOAD_DLL_DEBUG_EVENTs resulting from a
1427 DebugActiveProcess call. This limits the way we can detect
1428 if all the dlls have already been reported. If we get a real
1429 debug event before leaving attaching, the worst that will
1430 happen is the user will see a spurious breakpoint. */
1431
1432 current_event.dwDebugEventCode = 0;
1433 if (!WaitForDebugEvent (&current_event, 0))
1434 {
1435 OUTMSG2(("no attach events left\n"));
1436 fake_breakpoint_event ();
1437 attaching = 0;
1438 }
1439 else
1440 OUTMSG2(("got attach event\n"));
1441 }
1442 else
1443 #endif
1444 {
1445 /* Keep the wait time low enough for comfortable remote
1446 interruption, but high enough so gdbserver doesn't become a
1447 bottleneck. */
1448 if (!WaitForDebugEvent (&current_event, 250))
1449 {
1450 DWORD e = GetLastError();
1451
1452 if (e == ERROR_PIPE_NOT_CONNECTED)
1453 {
1454 /* This will happen if the loader fails to succesfully
1455 load the application, e.g., if the main executable
1456 tries to pull in a non-existing export from a
1457 DLL. */
1458 ourstatus->kind = TARGET_WAITKIND_EXITED;
1459 ourstatus->value.integer = 1;
1460 return 1;
1461 }
1462
1463 return 0;
1464 }
1465 }
1466
1467 gotevent:
1468
1469 switch (current_event.dwDebugEventCode)
1470 {
1471 case CREATE_THREAD_DEBUG_EVENT:
1472 OUTMSG2 (("gdbserver: kernel event CREATE_THREAD_DEBUG_EVENT "
1473 "for pid=%u tid=%x)\n",
1474 (unsigned) current_event.dwProcessId,
1475 (unsigned) current_event.dwThreadId));
1476
1477 /* Record the existence of this thread. */
1478 child_add_thread (current_event.dwProcessId,
1479 current_event.dwThreadId,
1480 current_event.u.CreateThread.hThread,
1481 current_event.u.CreateThread.lpThreadLocalBase);
1482 break;
1483
1484 case EXIT_THREAD_DEBUG_EVENT:
1485 OUTMSG2 (("gdbserver: kernel event EXIT_THREAD_DEBUG_EVENT "
1486 "for pid=%u tid=%x\n",
1487 (unsigned) current_event.dwProcessId,
1488 (unsigned) current_event.dwThreadId));
1489 child_delete_thread (current_event.dwProcessId,
1490 current_event.dwThreadId);
1491
1492 current_thread = get_first_thread ();
1493 return 1;
1494
1495 case CREATE_PROCESS_DEBUG_EVENT:
1496 OUTMSG2 (("gdbserver: kernel event CREATE_PROCESS_DEBUG_EVENT "
1497 "for pid=%u tid=%x\n",
1498 (unsigned) current_event.dwProcessId,
1499 (unsigned) current_event.dwThreadId));
1500 CloseHandle (current_event.u.CreateProcessInfo.hFile);
1501
1502 current_process_handle = current_event.u.CreateProcessInfo.hProcess;
1503 main_thread_id = current_event.dwThreadId;
1504
1505 /* Add the main thread. */
1506 child_add_thread (current_event.dwProcessId,
1507 main_thread_id,
1508 current_event.u.CreateProcessInfo.hThread,
1509 current_event.u.CreateProcessInfo.lpThreadLocalBase);
1510
1511 #ifdef _WIN32_WCE
1512 if (!attaching)
1513 {
1514 /* Windows CE doesn't set the initial breakpoint
1515 automatically like the desktop versions of Windows do.
1516 We add it explicitly here. It will be removed as soon as
1517 it is hit. */
1518 set_breakpoint_at ((CORE_ADDR) (long) current_event.u
1519 .CreateProcessInfo.lpStartAddress,
1520 auto_delete_breakpoint);
1521 }
1522 #endif
1523 break;
1524
1525 case EXIT_PROCESS_DEBUG_EVENT:
1526 OUTMSG2 (("gdbserver: kernel event EXIT_PROCESS_DEBUG_EVENT "
1527 "for pid=%u tid=%x\n",
1528 (unsigned) current_event.dwProcessId,
1529 (unsigned) current_event.dwThreadId));
1530 {
1531 DWORD exit_status = current_event.u.ExitProcess.dwExitCode;
1532 /* If the exit status looks like a fatal exception, but we
1533 don't recognize the exception's code, make the original
1534 exit status value available, to avoid losing information. */
1535 int exit_signal
1536 = WIFSIGNALED (exit_status) ? WTERMSIG (exit_status) : -1;
1537 if (exit_signal == -1)
1538 {
1539 ourstatus->kind = TARGET_WAITKIND_EXITED;
1540 ourstatus->value.integer = exit_status;
1541 }
1542 else
1543 {
1544 ourstatus->kind = TARGET_WAITKIND_SIGNALLED;
1545 ourstatus->value.sig = gdb_signal_from_host (exit_signal);
1546 }
1547 }
1548 child_continue (DBG_CONTINUE, -1);
1549 CloseHandle (current_process_handle);
1550 current_process_handle = NULL;
1551 break;
1552
1553 case LOAD_DLL_DEBUG_EVENT:
1554 OUTMSG2 (("gdbserver: kernel event LOAD_DLL_DEBUG_EVENT "
1555 "for pid=%u tid=%x\n",
1556 (unsigned) current_event.dwProcessId,
1557 (unsigned) current_event.dwThreadId));
1558 CloseHandle (current_event.u.LoadDll.hFile);
1559 if (! child_initialization_done)
1560 break;
1561 handle_load_dll ();
1562
1563 ourstatus->kind = TARGET_WAITKIND_LOADED;
1564 ourstatus->value.sig = GDB_SIGNAL_TRAP;
1565 break;
1566
1567 case UNLOAD_DLL_DEBUG_EVENT:
1568 OUTMSG2 (("gdbserver: kernel event UNLOAD_DLL_DEBUG_EVENT "
1569 "for pid=%u tid=%x\n",
1570 (unsigned) current_event.dwProcessId,
1571 (unsigned) current_event.dwThreadId));
1572 if (! child_initialization_done)
1573 break;
1574 handle_unload_dll ();
1575 ourstatus->kind = TARGET_WAITKIND_LOADED;
1576 ourstatus->value.sig = GDB_SIGNAL_TRAP;
1577 break;
1578
1579 case EXCEPTION_DEBUG_EVENT:
1580 OUTMSG2 (("gdbserver: kernel event EXCEPTION_DEBUG_EVENT "
1581 "for pid=%u tid=%x\n",
1582 (unsigned) current_event.dwProcessId,
1583 (unsigned) current_event.dwThreadId));
1584 handle_exception (ourstatus);
1585 break;
1586
1587 case OUTPUT_DEBUG_STRING_EVENT:
1588 /* A message from the kernel (or Cygwin). */
1589 OUTMSG2 (("gdbserver: kernel event OUTPUT_DEBUG_STRING_EVENT "
1590 "for pid=%u tid=%x\n",
1591 (unsigned) current_event.dwProcessId,
1592 (unsigned) current_event.dwThreadId));
1593 handle_output_debug_string ();
1594 break;
1595
1596 default:
1597 OUTMSG2 (("gdbserver: kernel event unknown "
1598 "for pid=%u tid=%x code=%x\n",
1599 (unsigned) current_event.dwProcessId,
1600 (unsigned) current_event.dwThreadId,
1601 (unsigned) current_event.dwDebugEventCode));
1602 break;
1603 }
1604
1605 ptid = debug_event_ptid (&current_event);
1606 current_thread = find_thread_ptid (ptid);
1607 return 1;
1608 }
1609
1610 /* Wait for the inferior process to change state.
1611 STATUS will be filled in with a response code to send to GDB.
1612 Returns the signal which caused the process to stop. */
1613 static ptid_t
1614 win32_wait (ptid_t ptid, struct target_waitstatus *ourstatus, int options)
1615 {
1616 struct regcache *regcache;
1617
1618 if (cached_status.kind != TARGET_WAITKIND_IGNORE)
1619 {
1620 /* The core always does a wait after creating the inferior, and
1621 do_initial_child_stuff already ran the inferior to the
1622 initial breakpoint (or an exit, if creating the process
1623 fails). Report it now. */
1624 *ourstatus = cached_status;
1625 cached_status.kind = TARGET_WAITKIND_IGNORE;
1626 return debug_event_ptid (&current_event);
1627 }
1628
1629 while (1)
1630 {
1631 if (!get_child_debug_event (ourstatus))
1632 continue;
1633
1634 switch (ourstatus->kind)
1635 {
1636 case TARGET_WAITKIND_EXITED:
1637 OUTMSG2 (("Child exited with retcode = %x\n",
1638 ourstatus->value.integer));
1639 win32_clear_inferiors ();
1640 return ptid_t (current_event.dwProcessId);
1641 case TARGET_WAITKIND_STOPPED:
1642 case TARGET_WAITKIND_SIGNALLED:
1643 case TARGET_WAITKIND_LOADED:
1644 OUTMSG2 (("Child Stopped with signal = %d \n",
1645 ourstatus->value.sig));
1646
1647 regcache = get_thread_regcache (current_thread, 1);
1648 child_fetch_inferior_registers (regcache, -1);
1649 return debug_event_ptid (&current_event);
1650 default:
1651 OUTMSG (("Ignoring unknown internal event, %d\n", ourstatus->kind));
1652 /* fall-through */
1653 case TARGET_WAITKIND_SPURIOUS:
1654 /* do nothing, just continue */
1655 child_continue (DBG_CONTINUE, -1);
1656 break;
1657 }
1658 }
1659 }
1660
1661 /* Fetch registers from the inferior process.
1662 If REGNO is -1, fetch all registers; otherwise, fetch at least REGNO. */
1663 static void
1664 win32_fetch_inferior_registers (struct regcache *regcache, int regno)
1665 {
1666 child_fetch_inferior_registers (regcache, regno);
1667 }
1668
1669 /* Store registers to the inferior process.
1670 If REGNO is -1, store all registers; otherwise, store at least REGNO. */
1671 static void
1672 win32_store_inferior_registers (struct regcache *regcache, int regno)
1673 {
1674 child_store_inferior_registers (regcache, regno);
1675 }
1676
1677 /* Read memory from the inferior process. This should generally be
1678 called through read_inferior_memory, which handles breakpoint shadowing.
1679 Read LEN bytes at MEMADDR into a buffer at MYADDR. */
1680 static int
1681 win32_read_inferior_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
1682 {
1683 return child_xfer_memory (memaddr, (char *) myaddr, len, 0, 0) != len;
1684 }
1685
1686 /* Write memory to the inferior process. This should generally be
1687 called through write_inferior_memory, which handles breakpoint shadowing.
1688 Write LEN bytes from the buffer at MYADDR to MEMADDR.
1689 Returns 0 on success and errno on failure. */
1690 static int
1691 win32_write_inferior_memory (CORE_ADDR memaddr, const unsigned char *myaddr,
1692 int len)
1693 {
1694 return child_xfer_memory (memaddr, (char *) myaddr, len, 1, 0) != len;
1695 }
1696
1697 /* Send an interrupt request to the inferior process. */
1698 static void
1699 win32_request_interrupt (void)
1700 {
1701 winapi_DebugBreakProcess DebugBreakProcess;
1702 winapi_GenerateConsoleCtrlEvent GenerateConsoleCtrlEvent;
1703
1704 #ifdef _WIN32_WCE
1705 HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
1706 #else
1707 HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
1708 #endif
1709
1710 GenerateConsoleCtrlEvent = GETPROCADDRESS (dll, GenerateConsoleCtrlEvent);
1711
1712 if (GenerateConsoleCtrlEvent != NULL
1713 && GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, current_process_id))
1714 return;
1715
1716 /* GenerateConsoleCtrlEvent can fail if process id being debugged is
1717 not a process group id.
1718 Fallback to XP/Vista 'DebugBreakProcess', which generates a
1719 breakpoint exception in the interior process. */
1720
1721 DebugBreakProcess = GETPROCADDRESS (dll, DebugBreakProcess);
1722
1723 if (DebugBreakProcess != NULL
1724 && DebugBreakProcess (current_process_handle))
1725 return;
1726
1727 /* Last resort, suspend all threads manually. */
1728 soft_interrupt_requested = 1;
1729 }
1730
1731 #ifdef _WIN32_WCE
1732 int
1733 win32_error_to_fileio_error (DWORD err)
1734 {
1735 switch (err)
1736 {
1737 case ERROR_BAD_PATHNAME:
1738 case ERROR_FILE_NOT_FOUND:
1739 case ERROR_INVALID_NAME:
1740 case ERROR_PATH_NOT_FOUND:
1741 return FILEIO_ENOENT;
1742 case ERROR_CRC:
1743 case ERROR_IO_DEVICE:
1744 case ERROR_OPEN_FAILED:
1745 return FILEIO_EIO;
1746 case ERROR_INVALID_HANDLE:
1747 return FILEIO_EBADF;
1748 case ERROR_ACCESS_DENIED:
1749 case ERROR_SHARING_VIOLATION:
1750 return FILEIO_EACCES;
1751 case ERROR_NOACCESS:
1752 return FILEIO_EFAULT;
1753 case ERROR_BUSY:
1754 return FILEIO_EBUSY;
1755 case ERROR_ALREADY_EXISTS:
1756 case ERROR_FILE_EXISTS:
1757 return FILEIO_EEXIST;
1758 case ERROR_BAD_DEVICE:
1759 return FILEIO_ENODEV;
1760 case ERROR_DIRECTORY:
1761 return FILEIO_ENOTDIR;
1762 case ERROR_FILENAME_EXCED_RANGE:
1763 case ERROR_INVALID_DATA:
1764 case ERROR_INVALID_PARAMETER:
1765 case ERROR_NEGATIVE_SEEK:
1766 return FILEIO_EINVAL;
1767 case ERROR_TOO_MANY_OPEN_FILES:
1768 return FILEIO_EMFILE;
1769 case ERROR_HANDLE_DISK_FULL:
1770 case ERROR_DISK_FULL:
1771 return FILEIO_ENOSPC;
1772 case ERROR_WRITE_PROTECT:
1773 return FILEIO_EROFS;
1774 case ERROR_NOT_SUPPORTED:
1775 return FILEIO_ENOSYS;
1776 }
1777
1778 return FILEIO_EUNKNOWN;
1779 }
1780
1781 static void
1782 wince_hostio_last_error (char *buf)
1783 {
1784 DWORD winerr = GetLastError ();
1785 int fileio_err = win32_error_to_fileio_error (winerr);
1786 sprintf (buf, "F-1,%x", fileio_err);
1787 }
1788 #endif
1789
1790 /* Write Windows signal info. */
1791
1792 static int
1793 win32_xfer_siginfo (const char *annex, unsigned char *readbuf,
1794 unsigned const char *writebuf, CORE_ADDR offset, int len)
1795 {
1796 if (siginfo_er.ExceptionCode == 0)
1797 return -1;
1798
1799 if (readbuf == nullptr)
1800 return -1;
1801
1802 if (offset > sizeof (siginfo_er))
1803 return -1;
1804
1805 if (offset + len > sizeof (siginfo_er))
1806 len = sizeof (siginfo_er) - offset;
1807
1808 memcpy (readbuf, (char *) &siginfo_er + offset, len);
1809
1810 return len;
1811 }
1812
1813 /* Write Windows OS Thread Information Block address. */
1814
1815 static int
1816 win32_get_tib_address (ptid_t ptid, CORE_ADDR *addr)
1817 {
1818 win32_thread_info *th;
1819 th = thread_rec (ptid, 0);
1820 if (th == NULL)
1821 return 0;
1822 if (addr != NULL)
1823 *addr = th->thread_local_base;
1824 return 1;
1825 }
1826
1827 /* Implementation of the target_ops method "sw_breakpoint_from_kind". */
1828
1829 static const gdb_byte *
1830 win32_sw_breakpoint_from_kind (int kind, int *size)
1831 {
1832 *size = the_low_target.breakpoint_len;
1833 return the_low_target.breakpoint;
1834 }
1835
1836 /* The win32 target ops object. */
1837
1838 static win32_process_target the_win32_target;
1839
1840 static process_stratum_target win32_target_ops = {
1841 win32_wait,
1842 win32_fetch_inferior_registers,
1843 win32_store_inferior_registers,
1844 NULL, /* prepare_to_access_memory */
1845 NULL, /* done_accessing_memory */
1846 win32_read_inferior_memory,
1847 win32_write_inferior_memory,
1848 NULL, /* lookup_symbols */
1849 win32_request_interrupt,
1850 NULL, /* read_auxv */
1851 win32_supports_z_point_type,
1852 win32_insert_point,
1853 win32_remove_point,
1854 NULL, /* stopped_by_sw_breakpoint */
1855 NULL, /* supports_stopped_by_sw_breakpoint */
1856 NULL, /* stopped_by_hw_breakpoint */
1857 NULL, /* supports_stopped_by_hw_breakpoint */
1858 target_can_do_hardware_single_step,
1859 win32_stopped_by_watchpoint,
1860 win32_stopped_data_address,
1861 NULL, /* read_offsets */
1862 NULL, /* get_tls_address */
1863 #ifdef _WIN32_WCE
1864 wince_hostio_last_error,
1865 #else
1866 hostio_last_error_from_errno,
1867 #endif
1868 NULL, /* qxfer_osdata */
1869 win32_xfer_siginfo,
1870 NULL, /* supports_non_stop */
1871 NULL, /* async */
1872 NULL, /* start_non_stop */
1873 NULL, /* supports_multi_process */
1874 NULL, /* supports_fork_events */
1875 NULL, /* supports_vfork_events */
1876 NULL, /* supports_exec_events */
1877 NULL, /* handle_new_gdb_connection */
1878 NULL, /* handle_monitor_command */
1879 NULL, /* core_of_thread */
1880 NULL, /* read_loadmap */
1881 NULL, /* process_qsupported */
1882 NULL, /* supports_tracepoints */
1883 NULL, /* read_pc */
1884 NULL, /* write_pc */
1885 NULL, /* thread_stopped */
1886 win32_get_tib_address,
1887 NULL, /* pause_all */
1888 NULL, /* unpause_all */
1889 NULL, /* stabilize_threads */
1890 NULL, /* install_fast_tracepoint_jump_pad */
1891 NULL, /* emit_ops */
1892 NULL, /* supports_disable_randomization */
1893 NULL, /* get_min_fast_tracepoint_insn_len */
1894 NULL, /* qxfer_libraries_svr4 */
1895 NULL, /* support_agent */
1896 NULL, /* enable_btrace */
1897 NULL, /* disable_btrace */
1898 NULL, /* read_btrace */
1899 NULL, /* read_btrace_conf */
1900 NULL, /* supports_range_stepping */
1901 NULL, /* pid_to_exec_file */
1902 NULL, /* multifs_open */
1903 NULL, /* multifs_unlink */
1904 NULL, /* multifs_readlink */
1905 NULL, /* breakpoint_kind_from_pc */
1906 win32_sw_breakpoint_from_kind,
1907 NULL, /* thread_name */
1908 NULL, /* breakpoint_kind_from_current_state */
1909 NULL, /* supports_software_single_step */
1910 NULL, /* supports_catch_syscall */
1911 NULL, /* get_ipa_tdesc_idx */
1912 NULL, /* thread_handle */
1913 &the_win32_target,
1914 };
1915
1916 /* Initialize the Win32 backend. */
1917 void
1918 initialize_low (void)
1919 {
1920 set_target_ops (&win32_target_ops);
1921 the_low_target.arch_setup ();
1922 }