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