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