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