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