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