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