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