OSDN Git Service

* win32-low.c (debug_registers_changed,
[pf3gnuchains/pf3gnuchains3x.git] / gdb / gdbserver / win32-low.c
1 /* Low level interface to Windows debugging, for gdbserver.
2    Copyright (C) 2006, 2007 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 2 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, write to the Free Software
20    Foundation, Inc., 51 Franklin Street, Fifth Floor,
21    Boston, MA 02110-1301, USA.  */
22
23 #include "server.h"
24 #include "regcache.h"
25 #include "gdb/signals.h"
26 #include "mem-break.h"
27 #include "win32-low.h"
28
29 #include <windows.h>
30 #include <winnt.h>
31 #include <imagehlp.h>
32 #include <psapi.h>
33 #include <sys/param.h>
34 #include <malloc.h>
35 #include <process.h>
36
37 #ifndef USE_WIN32API
38 #include <sys/cygwin.h>
39 #endif
40
41 #define LOG 0
42
43 #define OUTMSG(X) do { printf X; fflush (stdout); } while (0)
44 #if LOG
45 #define OUTMSG2(X) do { printf X; fflush (stdout); } while (0)
46 #else
47 #define OUTMSG2(X) do ; while (0)
48 #endif
49
50 #ifndef _T
51 #define _T(x) TEXT (x)
52 #endif
53
54 #ifndef COUNTOF
55 #define COUNTOF(STR) (sizeof (STR) / sizeof ((STR)[0]))
56 #endif
57
58 #ifdef _WIN32_WCE
59 # define GETPROCADDRESS(DLL, PROC) \
60   ((winapi_ ## PROC) GetProcAddress (DLL, TEXT (#PROC)))
61 #else
62 # define GETPROCADDRESS(DLL, PROC) \
63   ((winapi_ ## PROC) GetProcAddress (DLL, #PROC))
64 #endif
65
66 int using_threads = 1;
67
68 /* Globals.  */
69 static HANDLE current_process_handle = NULL;
70 static DWORD current_process_id = 0;
71 static enum target_signal last_sig = TARGET_SIGNAL_0;
72
73 /* The current debug event from WaitForDebugEvent.  */
74 static DEBUG_EVENT current_event;
75
76 #define NUM_REGS (the_low_target.num_regs)
77
78 typedef BOOL WINAPI (*winapi_DebugActiveProcessStop) (DWORD dwProcessId);
79 typedef BOOL WINAPI (*winapi_DebugSetProcessKillOnExit) (BOOL KillOnExit);
80
81 static DWORD main_thread_id = 0;
82
83 static void win32_resume (struct thread_resume *resume_info);
84
85 /* Get the thread ID from the current selected inferior (the current
86    thread).  */
87 static DWORD
88 current_inferior_tid (void)
89 {
90   win32_thread_info *th = inferior_target_data (current_inferior);
91   return th->tid;
92 }
93
94 /* Find a thread record given a thread id.  If GET_CONTEXT is set then
95    also retrieve the context for this thread.  */
96 static win32_thread_info *
97 thread_rec (DWORD id, int get_context)
98 {
99   struct thread_info *thread;
100   win32_thread_info *th;
101
102   thread = (struct thread_info *) find_inferior_id (&all_threads, id);
103   if (thread == NULL)
104     return NULL;
105
106   th = inferior_target_data (thread);
107   if (!th->suspend_count && get_context)
108     {
109       if (id != current_event.dwThreadId)
110         th->suspend_count = SuspendThread (th->h) + 1;
111
112       (*the_low_target.get_thread_context) (th, &current_event);
113     }
114
115   return th;
116 }
117
118 /* Add a thread to the thread list.  */
119 static win32_thread_info *
120 child_add_thread (DWORD tid, HANDLE h)
121 {
122   win32_thread_info *th;
123
124   if ((th = thread_rec (tid, FALSE)))
125     return th;
126
127   th = (win32_thread_info *) malloc (sizeof (*th));
128   memset (th, 0, sizeof (*th));
129   th->tid = tid;
130   th->h = h;
131
132   add_thread (tid, th, (unsigned int) tid);
133   set_inferior_regcache_data ((struct thread_info *)
134                               find_inferior_id (&all_threads, tid),
135                               new_register_cache ());
136
137   if (the_low_target.thread_added != NULL)
138     (*the_low_target.thread_added) (th);
139
140   return th;
141 }
142
143 /* Delete a thread from the list of threads.  */
144 static void
145 delete_thread_info (struct inferior_list_entry *thread)
146 {
147   win32_thread_info *th = inferior_target_data ((struct thread_info *) thread);
148
149   remove_thread ((struct thread_info *) thread);
150   CloseHandle (th->h);
151   free (th);
152 }
153
154 /* Delete a thread from the list of threads.  */
155 static void
156 child_delete_thread (DWORD id)
157 {
158   struct inferior_list_entry *thread;
159
160   /* If the last thread is exiting, just return.  */
161   if (all_threads.head == all_threads.tail)
162     return;
163
164   thread = find_inferior_id (&all_threads, id);
165   if (thread == NULL)
166     return;
167
168   delete_thread_info (thread);
169 }
170
171 /* Transfer memory from/to the debugged process.  */
172 static int
173 child_xfer_memory (CORE_ADDR memaddr, char *our, int len,
174                    int write, struct target_ops *target)
175 {
176   SIZE_T done;
177   long addr = (long) memaddr;
178
179   if (write)
180     {
181       WriteProcessMemory (current_process_handle, (LPVOID) addr,
182                           (LPCVOID) our, len, &done);
183       FlushInstructionCache (current_process_handle, (LPCVOID) addr, len);
184     }
185   else
186     {
187       ReadProcessMemory (current_process_handle, (LPCVOID) addr, (LPVOID) our,
188                          len, &done);
189     }
190   return done;
191 }
192
193 /* Generally, what has the program done?  */
194 enum target_waitkind
195 {
196   /* The program has exited.  The exit status is in value.integer.  */
197   TARGET_WAITKIND_EXITED,
198
199   /* The program has stopped with a signal.  Which signal is in
200      value.sig.  */
201   TARGET_WAITKIND_STOPPED,
202
203   /* The program is letting us know that it dynamically loaded something
204      (e.g. it called load(2) on AIX).  */
205   TARGET_WAITKIND_LOADED,
206
207   /* The program has exec'ed a new executable file.  The new file's
208      pathname is pointed to by value.execd_pathname.  */
209   TARGET_WAITKIND_EXECD,
210
211   /* Nothing happened, but we stopped anyway.  This perhaps should be handled
212      within target_wait, but I'm not sure target_wait should be resuming the
213      inferior.  */
214   TARGET_WAITKIND_SPURIOUS,
215 };
216
217 struct target_waitstatus
218 {
219   enum target_waitkind kind;
220
221   /* Forked child pid, execd pathname, exit status or signal number.  */
222   union
223   {
224     int integer;
225     enum target_signal sig;
226     int related_pid;
227     char *execd_pathname;
228     int syscall_id;
229   }
230   value;
231 };
232
233 /* Clear out any old thread list and reinitialize it to a pristine
234    state. */
235 static void
236 child_init_thread_list (void)
237 {
238   for_each_inferior (&all_threads, delete_thread_info);
239 }
240
241 static void
242 do_initial_child_stuff (DWORD pid)
243 {
244   last_sig = TARGET_SIGNAL_0;
245
246   memset (&current_event, 0, sizeof (current_event));
247
248   child_init_thread_list ();
249
250   if (the_low_target.initial_stuff != NULL)
251     (*the_low_target.initial_stuff) ();
252 }
253
254 /* Resume all artificially suspended threads if we are continuing
255    execution.  */
256 static int
257 continue_one_thread (struct inferior_list_entry *this_thread, void *id_ptr)
258 {
259   struct thread_info *thread = (struct thread_info *) this_thread;
260   int thread_id = * (int *) id_ptr;
261   win32_thread_info *th = inferior_target_data (thread);
262   int i;
263
264   if ((thread_id == -1 || thread_id == th->tid)
265       && th->suspend_count)
266     {
267       if (th->context.ContextFlags)
268         {
269           (*the_low_target.set_thread_context) (th, &current_event);
270           th->context.ContextFlags = 0;
271         }
272
273       for (i = 0; i < th->suspend_count; i++)
274         (void) ResumeThread (th->h);
275       th->suspend_count = 0;
276     }
277
278   return 0;
279 }
280
281 static BOOL
282 child_continue (DWORD continue_status, int thread_id)
283 {
284   BOOL res;
285
286   res = ContinueDebugEvent (current_event.dwProcessId,
287                             current_event.dwThreadId, continue_status);
288   if (res)
289     find_inferior (&all_threads, continue_one_thread, &thread_id);
290
291   return res;
292 }
293
294 /* Fetch register(s) from the current thread context.  */
295 static void
296 child_fetch_inferior_registers (int r)
297 {
298   int regno;
299   win32_thread_info *th = thread_rec (current_inferior_tid (), TRUE);
300   if (r == -1 || r == 0 || r > NUM_REGS)
301     child_fetch_inferior_registers (NUM_REGS);
302   else
303     for (regno = 0; regno < r; regno++)
304       (*the_low_target.fetch_inferior_register) (th, regno);
305 }
306
307 /* Store a new register value into the current thread context.  We don't
308    change the program's context until later, when we resume it.  */
309 static void
310 child_store_inferior_registers (int r)
311 {
312   int regno;
313   win32_thread_info *th = thread_rec (current_inferior_tid (), TRUE);
314   if (r == -1 || r == 0 || r > NUM_REGS)
315     child_store_inferior_registers (NUM_REGS);
316   else
317     for (regno = 0; regno < r; regno++)
318       (*the_low_target.store_inferior_register) (th, regno);
319 }
320
321 /* Map the Windows error number in ERROR to a locale-dependent error
322    message string and return a pointer to it.  Typically, the values
323    for ERROR come from GetLastError.
324
325    The string pointed to shall not be modified by the application,
326    but may be overwritten by a subsequent call to strwinerror
327
328    The strwinerror function does not change the current setting
329    of GetLastError.  */
330
331 char *
332 strwinerror (DWORD error)
333 {
334   static char buf[1024];
335   TCHAR *msgbuf;
336   DWORD lasterr = GetLastError ();
337   DWORD chars = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
338                                | FORMAT_MESSAGE_ALLOCATE_BUFFER,
339                                NULL,
340                                error,
341                                0, /* Default language */
342                                (LPVOID)&msgbuf,
343                                0,
344                                NULL);
345   if (chars != 0)
346     {
347       /* If there is an \r\n appended, zap it.  */
348       if (chars >= 2
349           && msgbuf[chars - 2] == '\r'
350           && msgbuf[chars - 1] == '\n')
351         {
352           chars -= 2;
353           msgbuf[chars] = 0;
354         }
355
356       if (chars > ((COUNTOF (buf)) - 1))
357         {
358           chars = COUNTOF (buf) - 1;
359           msgbuf [chars] = 0;
360         }
361
362 #ifdef UNICODE
363       wcstombs (buf, msgbuf, chars + 1);
364 #else
365       strncpy (buf, msgbuf, chars + 1);
366 #endif
367       LocalFree (msgbuf);
368     }
369   else
370     sprintf (buf, "unknown win32 error (%ld)", error);
371
372   SetLastError (lasterr);
373   return buf;
374 }
375
376 /* Start a new process.
377    PROGRAM is a path to the program to execute.
378    ARGS is a standard NULL-terminated array of arguments,
379    to be passed to the inferior as ``argv''.
380    Returns the new PID on success, -1 on failure.  Registers the new
381    process with the process list.  */
382 static int
383 win32_create_inferior (char *program, char **program_args)
384 {
385 #ifndef USE_WIN32API
386   char real_path[MAXPATHLEN];
387   char *orig_path, *new_path, *path_ptr;
388 #endif
389   BOOL ret;
390   DWORD flags;
391   char *args;
392   int argslen;
393   int argc;
394   PROCESS_INFORMATION pi;
395 #ifndef __MINGW32CE__
396   STARTUPINFOA si = { sizeof (STARTUPINFOA) };
397   char *winenv = NULL;
398 #else
399   wchar_t *wargs, *wprogram;
400 #endif
401
402   if (!program)
403     error ("No executable specified, specify executable to debug.\n");
404
405   flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS;
406
407 #ifndef USE_WIN32API
408   orig_path = NULL;
409   path_ptr = getenv ("PATH");
410   if (path_ptr)
411     {
412       orig_path = alloca (strlen (path_ptr) + 1);
413       new_path = alloca (cygwin_posix_to_win32_path_list_buf_size (path_ptr));
414       strcpy (orig_path, path_ptr);
415       cygwin_posix_to_win32_path_list (path_ptr, new_path);
416       setenv ("PATH", new_path, 1);
417     }
418   cygwin_conv_to_win32_path (program, real_path);
419   program = real_path;
420 #endif
421
422   argslen = 1;
423   for (argc = 1; program_args[argc]; argc++)
424     argslen += strlen (program_args[argc]) + 1;
425   args = alloca (argslen);
426   args[0] = '\0';
427   for (argc = 1; program_args[argc]; argc++)
428     {
429       /* FIXME: Can we do better about quoting?  How does Cygwin
430          handle this?  */
431       strcat (args, " ");
432       strcat (args, program_args[argc]);
433     }
434   OUTMSG2 (("Command line is \"%s\"\n", args));
435
436 #ifdef CREATE_NEW_PROCESS_GROUP
437   flags |= CREATE_NEW_PROCESS_GROUP;
438 #endif
439
440 #ifdef __MINGW32CE__
441   to_back_slashes (program);
442   wargs = alloca (argslen * sizeof (wchar_t));
443   mbstowcs (wargs, args, argslen);
444   wprogram = alloca ((strlen (program) + 1) * sizeof (wchar_t));
445   mbstowcs (wprogram, program, strlen (program) + 1);
446   ret = CreateProcessW (wprogram, /* image name */
447                         wargs,    /* command line */
448                         NULL,     /* security, not supported */
449                         NULL,     /* thread, not supported */
450                         FALSE,    /* inherit handles, not supported */
451                         flags,    /* start flags */
452                         NULL,     /* environment, not supported */
453                         NULL,     /* current directory, not supported */
454                         NULL,     /* start info, not supported */
455                         &pi);     /* proc info */
456 #else
457   ret = CreateProcessA (program,  /* image name */
458                         args,     /* command line */
459                         NULL,     /* security */
460                         NULL,     /* thread */
461                         TRUE,     /* inherit handles */
462                         flags,    /* start flags */
463                         winenv,   /* environment */
464                         NULL,     /* current directory */
465                         &si,      /* start info */
466                         &pi);     /* proc info */
467 #endif
468
469 #ifndef USE_WIN32API
470   if (orig_path)
471     setenv ("PATH", orig_path, 1);
472 #endif
473
474   if (!ret)
475     {
476       DWORD err = GetLastError ();
477       error ("Error creating process \"%s%s\", (error %d): %s\n",
478              program, args, (int) err, strwinerror (err));
479     }
480   else
481     {
482       OUTMSG2 (("Process created: %s\n", (char *) args));
483     }
484
485 #ifndef _WIN32_WCE
486   /* On Windows CE this handle can't be closed.  The OS reuses
487      it in the debug events, while the 9x/NT versions of Windows
488      probably use a DuplicateHandle'd one.  */
489   CloseHandle (pi.hThread);
490 #endif
491
492   current_process_handle = pi.hProcess;
493   current_process_id = pi.dwProcessId;
494
495   do_initial_child_stuff (current_process_id);
496
497   return current_process_id;
498 }
499
500 /* Attach to a running process.
501    PID is the process ID to attach to, specified by the user
502    or a higher layer.  */
503 static int
504 win32_attach (unsigned long pid)
505 {
506   winapi_DebugActiveProcessStop DebugActiveProcessStop = NULL;
507   winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit = NULL;
508 #ifdef _WIN32_WCE
509   HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
510 #else
511   HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
512 #endif
513   DebugActiveProcessStop = GETPROCADDRESS (dll, DebugActiveProcessStop);
514   DebugSetProcessKillOnExit = GETPROCADDRESS (dll, DebugSetProcessKillOnExit);
515
516   if (DebugActiveProcess (pid))
517     {
518       if (DebugSetProcessKillOnExit != NULL)
519         DebugSetProcessKillOnExit (FALSE);
520
521       current_process_handle = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
522
523       if (current_process_handle != NULL)
524         {
525           current_process_id = pid;
526           do_initial_child_stuff (pid);
527           return 0;
528         }
529       if (DebugActiveProcessStop != NULL)
530         DebugActiveProcessStop (current_process_id);
531     }
532
533   error ("Attach to process failed.");
534 }
535
536 /* Handle OUTPUT_DEBUG_STRING_EVENT from child process.  */
537 static void
538 handle_output_debug_string (struct target_waitstatus *ourstatus)
539 {
540 #define READ_BUFFER_LEN 1024
541   CORE_ADDR addr;
542   char s[READ_BUFFER_LEN + 1] = { 0 };
543   DWORD nbytes = current_event.u.DebugString.nDebugStringLength;
544
545   if (nbytes == 0)
546     return;
547
548   if (nbytes > READ_BUFFER_LEN)
549     nbytes = READ_BUFFER_LEN;
550
551   addr = (CORE_ADDR) (size_t) current_event.u.DebugString.lpDebugStringData;
552
553   if (current_event.u.DebugString.fUnicode)
554     {
555       /* The event tells us how many bytes, not chars, even
556          in Unicode.  */
557       WCHAR buffer[(READ_BUFFER_LEN + 1) / sizeof (WCHAR)] = { 0 };
558       if (read_inferior_memory (addr, (unsigned char *) buffer, nbytes) != 0)
559         return;
560       wcstombs (s, buffer, (nbytes + 1) / sizeof (WCHAR));
561     }
562   else
563     {
564       if (read_inferior_memory (addr, (unsigned char *) s, nbytes) != 0)
565         return;
566     }
567
568   if (strncmp (s, "cYg", 3) != 0)
569     monitor_output (s);
570 #undef READ_BUFFER_LEN
571 }
572
573 /* Kill all inferiors.  */
574 static void
575 win32_kill (void)
576 {
577   win32_thread_info *current_thread;
578
579   if (current_process_handle == NULL)
580     return;
581
582   TerminateProcess (current_process_handle, 0);
583   for (;;)
584     {
585       if (!child_continue (DBG_CONTINUE, -1))
586         break;
587       if (!WaitForDebugEvent (&current_event, INFINITE))
588         break;
589       if (current_event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
590         break;
591       else if (current_event.dwDebugEventCode == OUTPUT_DEBUG_STRING_EVENT)
592         {
593           struct target_waitstatus our_status = { 0 };
594           handle_output_debug_string (&our_status);
595         }
596     }
597
598   CloseHandle (current_process_handle);
599
600   current_thread = inferior_target_data (current_inferior);
601   if (current_thread && current_thread->h)
602     {
603       /* This may fail in an attached process, so don't check.  */
604       (void) CloseHandle (current_thread->h);
605     }
606 }
607
608 /* Detach from all inferiors.  */
609 static int
610 win32_detach (void)
611 {
612   HANDLE h;
613
614   winapi_DebugActiveProcessStop DebugActiveProcessStop = NULL;
615   winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit = NULL;
616 #ifdef _WIN32_WCE
617   HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
618 #else
619   HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
620 #endif
621   DebugActiveProcessStop = GETPROCADDRESS (dll, DebugActiveProcessStop);
622   DebugSetProcessKillOnExit = GETPROCADDRESS (dll, DebugSetProcessKillOnExit);
623
624   if (DebugSetProcessKillOnExit == NULL
625       || DebugActiveProcessStop == NULL)
626     return -1;
627
628   /* We need a new handle, since DebugActiveProcessStop
629      closes all the ones that came through the events.  */
630   if ((h = OpenProcess (PROCESS_ALL_ACCESS,
631                         FALSE,
632                         current_process_id)) == NULL)
633     {
634       /* The process died.  */
635       return -1;
636     }
637
638   {
639     struct thread_resume resume;
640     resume.thread = -1;
641     resume.step = 0;
642     resume.sig = 0;
643     resume.leave_stopped = 0;
644     win32_resume (&resume);
645   }
646
647   if (!DebugActiveProcessStop (current_process_id))
648     {
649       CloseHandle (h);
650       return -1;
651     }
652   DebugSetProcessKillOnExit (FALSE);
653
654   current_process_handle = h;
655   return 0;
656 }
657
658 /* Wait for inferiors to end.  */
659 static void
660 win32_join (void)
661 {
662   if (current_process_id == 0
663       || current_process_handle == NULL)
664     return;
665
666   WaitForSingleObject (current_process_handle, INFINITE);
667   CloseHandle (current_process_handle);
668
669   current_process_handle = NULL;
670   current_process_id = 0;
671 }
672
673 /* Return 1 iff the thread with thread ID TID is alive.  */
674 static int
675 win32_thread_alive (unsigned long tid)
676 {
677   int res;
678
679   /* Our thread list is reliable; don't bother to poll target
680      threads.  */
681   if (find_inferior_id (&all_threads, tid) != NULL)
682     res = 1;
683   else
684     res = 0;
685   return res;
686 }
687
688 /* Resume the inferior process.  RESUME_INFO describes how we want
689    to resume.  */
690 static void
691 win32_resume (struct thread_resume *resume_info)
692 {
693   DWORD tid;
694   enum target_signal sig;
695   int step;
696   win32_thread_info *th;
697   DWORD continue_status = DBG_CONTINUE;
698
699   /* This handles the very limited set of resume packets that GDB can
700      currently produce.  */
701
702   if (resume_info[0].thread == -1)
703     tid = -1;
704   else if (resume_info[1].thread == -1 && !resume_info[1].leave_stopped)
705     tid = -1;
706   else
707     /* Yes, we're ignoring resume_info[0].thread.  It'd be tricky to make
708        the Windows resume code do the right thing for thread switching.  */
709     tid = current_event.dwThreadId;
710
711   if (resume_info[0].thread != -1)
712     {
713       sig = resume_info[0].sig;
714       step = resume_info[0].step;
715     }
716   else
717     {
718       sig = 0;
719       step = 0;
720     }
721
722   if (sig != TARGET_SIGNAL_0)
723     {
724       if (current_event.dwDebugEventCode != EXCEPTION_DEBUG_EVENT)
725         {
726           OUTMSG (("Cannot continue with signal %d here.\n", sig));
727         }
728       else if (sig == last_sig)
729         continue_status = DBG_EXCEPTION_NOT_HANDLED;
730       else
731         OUTMSG (("Can only continue with recieved signal %d.\n", last_sig));
732     }
733
734   last_sig = TARGET_SIGNAL_0;
735
736   /* Get context for the currently selected thread.  */
737   th = thread_rec (current_event.dwThreadId, FALSE);
738   if (th)
739     {
740       if (th->context.ContextFlags)
741         {
742           /* Move register values from the inferior into the thread
743              context structure.  */
744           regcache_invalidate ();
745
746           if (step)
747             {
748               if (the_low_target.single_step != NULL)
749                 (*the_low_target.single_step) (th);
750               else
751                 error ("Single stepping is not supported "
752                        "in this configuration.\n");
753             }
754
755           (*the_low_target.set_thread_context) (th, &current_event);
756           th->context.ContextFlags = 0;
757         }
758     }
759
760   /* Allow continuing with the same signal that interrupted us.
761      Otherwise complain.  */
762
763   child_continue (continue_status, tid);
764 }
765
766 static void
767 handle_exception (struct target_waitstatus *ourstatus)
768 {
769   DWORD code = current_event.u.Exception.ExceptionRecord.ExceptionCode;
770
771   ourstatus->kind = TARGET_WAITKIND_STOPPED;
772
773   switch (code)
774     {
775     case EXCEPTION_ACCESS_VIOLATION:
776       OUTMSG2 (("EXCEPTION_ACCESS_VIOLATION"));
777       ourstatus->value.sig = TARGET_SIGNAL_SEGV;
778       break;
779     case STATUS_STACK_OVERFLOW:
780       OUTMSG2 (("STATUS_STACK_OVERFLOW"));
781       ourstatus->value.sig = TARGET_SIGNAL_SEGV;
782       break;
783     case STATUS_FLOAT_DENORMAL_OPERAND:
784       OUTMSG2 (("STATUS_FLOAT_DENORMAL_OPERAND"));
785       ourstatus->value.sig = TARGET_SIGNAL_FPE;
786       break;
787     case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
788       OUTMSG2 (("EXCEPTION_ARRAY_BOUNDS_EXCEEDED"));
789       ourstatus->value.sig = TARGET_SIGNAL_FPE;
790       break;
791     case STATUS_FLOAT_INEXACT_RESULT:
792       OUTMSG2 (("STATUS_FLOAT_INEXACT_RESULT"));
793       ourstatus->value.sig = TARGET_SIGNAL_FPE;
794       break;
795     case STATUS_FLOAT_INVALID_OPERATION:
796       OUTMSG2 (("STATUS_FLOAT_INVALID_OPERATION"));
797       ourstatus->value.sig = TARGET_SIGNAL_FPE;
798       break;
799     case STATUS_FLOAT_OVERFLOW:
800       OUTMSG2 (("STATUS_FLOAT_OVERFLOW"));
801       ourstatus->value.sig = TARGET_SIGNAL_FPE;
802       break;
803     case STATUS_FLOAT_STACK_CHECK:
804       OUTMSG2 (("STATUS_FLOAT_STACK_CHECK"));
805       ourstatus->value.sig = TARGET_SIGNAL_FPE;
806       break;
807     case STATUS_FLOAT_UNDERFLOW:
808       OUTMSG2 (("STATUS_FLOAT_UNDERFLOW"));
809       ourstatus->value.sig = TARGET_SIGNAL_FPE;
810       break;
811     case STATUS_FLOAT_DIVIDE_BY_ZERO:
812       OUTMSG2 (("STATUS_FLOAT_DIVIDE_BY_ZERO"));
813       ourstatus->value.sig = TARGET_SIGNAL_FPE;
814       break;
815     case STATUS_INTEGER_DIVIDE_BY_ZERO:
816       OUTMSG2 (("STATUS_INTEGER_DIVIDE_BY_ZERO"));
817       ourstatus->value.sig = TARGET_SIGNAL_FPE;
818       break;
819     case STATUS_INTEGER_OVERFLOW:
820       OUTMSG2 (("STATUS_INTEGER_OVERFLOW"));
821       ourstatus->value.sig = TARGET_SIGNAL_FPE;
822       break;
823     case EXCEPTION_BREAKPOINT:
824       OUTMSG2 (("EXCEPTION_BREAKPOINT"));
825       ourstatus->value.sig = TARGET_SIGNAL_TRAP;
826 #ifdef _WIN32_WCE
827       /* Remove the initial breakpoint.  */
828       check_breakpoints ((CORE_ADDR) (long) current_event
829                          .u.Exception.ExceptionRecord.ExceptionAddress);
830 #endif
831       break;
832     case DBG_CONTROL_C:
833       OUTMSG2 (("DBG_CONTROL_C"));
834       ourstatus->value.sig = TARGET_SIGNAL_INT;
835       break;
836     case DBG_CONTROL_BREAK:
837       OUTMSG2 (("DBG_CONTROL_BREAK"));
838       ourstatus->value.sig = TARGET_SIGNAL_INT;
839       break;
840     case EXCEPTION_SINGLE_STEP:
841       OUTMSG2 (("EXCEPTION_SINGLE_STEP"));
842       ourstatus->value.sig = TARGET_SIGNAL_TRAP;
843       break;
844     case EXCEPTION_ILLEGAL_INSTRUCTION:
845       OUTMSG2 (("EXCEPTION_ILLEGAL_INSTRUCTION"));
846       ourstatus->value.sig = TARGET_SIGNAL_ILL;
847       break;
848     case EXCEPTION_PRIV_INSTRUCTION:
849       OUTMSG2 (("EXCEPTION_PRIV_INSTRUCTION"));
850       ourstatus->value.sig = TARGET_SIGNAL_ILL;
851       break;
852     case EXCEPTION_NONCONTINUABLE_EXCEPTION:
853       OUTMSG2 (("EXCEPTION_NONCONTINUABLE_EXCEPTION"));
854       ourstatus->value.sig = TARGET_SIGNAL_ILL;
855       break;
856     default:
857       if (current_event.u.Exception.dwFirstChance)
858         {
859           ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
860           return;
861         }
862       OUTMSG2 (("gdbserver: unknown target exception 0x%08lx at 0x%08lx",
863                 current_event.u.Exception.ExceptionRecord.ExceptionCode,
864                 (DWORD) current_event.u.Exception.ExceptionRecord.
865                 ExceptionAddress));
866       ourstatus->value.sig = TARGET_SIGNAL_UNKNOWN;
867       break;
868     }
869   OUTMSG2 (("\n"));
870   last_sig = ourstatus->value.sig;
871 }
872
873 /* Get the next event from the child.  */
874 static void
875 get_child_debug_event (struct target_waitstatus *ourstatus)
876 {
877   BOOL debug_event;
878
879   last_sig = TARGET_SIGNAL_0;
880   ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
881
882   if (!(debug_event = WaitForDebugEvent (&current_event, 1000)))
883     return;
884
885   current_inferior =
886     (struct thread_info *) find_inferior_id (&all_threads,
887                                              current_event.dwThreadId);
888
889   switch (current_event.dwDebugEventCode)
890     {
891     case CREATE_THREAD_DEBUG_EVENT:
892       OUTMSG2 (("gdbserver: kernel event CREATE_THREAD_DEBUG_EVENT "
893                 "for pid=%d tid=%x)\n",
894                 (unsigned) current_event.dwProcessId,
895                 (unsigned) current_event.dwThreadId));
896
897       /* Record the existence of this thread.  */
898       child_add_thread (current_event.dwThreadId,
899                              current_event.u.CreateThread.hThread);
900       break;
901
902     case EXIT_THREAD_DEBUG_EVENT:
903       OUTMSG2 (("gdbserver: kernel event EXIT_THREAD_DEBUG_EVENT "
904                 "for pid=%d tid=%x\n",
905                 (unsigned) current_event.dwProcessId,
906                 (unsigned) current_event.dwThreadId));
907       child_delete_thread (current_event.dwThreadId);
908       break;
909
910     case CREATE_PROCESS_DEBUG_EVENT:
911       OUTMSG2 (("gdbserver: kernel event CREATE_PROCESS_DEBUG_EVENT "
912                 "for pid=%d tid=%x\n",
913                 (unsigned) current_event.dwProcessId,
914                 (unsigned) current_event.dwThreadId));
915       CloseHandle (current_event.u.CreateProcessInfo.hFile);
916
917       current_process_handle = current_event.u.CreateProcessInfo.hProcess;
918       main_thread_id = current_event.dwThreadId;
919
920       ourstatus->kind = TARGET_WAITKIND_EXECD;
921       ourstatus->value.execd_pathname = "Main executable";
922
923       /* Add the main thread.  */
924       child_add_thread (main_thread_id,
925                         current_event.u.CreateProcessInfo.hThread);
926
927       ourstatus->value.related_pid = current_event.dwThreadId;
928 #ifdef _WIN32_WCE
929       /* Windows CE doesn't set the initial breakpoint automatically
930          like the desktop versions of Windows do.  We add it explicitly
931          here.  It will be removed as soon as it is hit.  */
932       set_breakpoint_at ((CORE_ADDR) (long) current_event.u
933                          .CreateProcessInfo.lpStartAddress,
934                          delete_breakpoint_at);
935 #endif
936       break;
937
938     case EXIT_PROCESS_DEBUG_EVENT:
939       OUTMSG2 (("gdbserver: kernel event EXIT_PROCESS_DEBUG_EVENT "
940                 "for pid=%d tid=%x\n",
941                 (unsigned) current_event.dwProcessId,
942                 (unsigned) current_event.dwThreadId));
943       ourstatus->kind = TARGET_WAITKIND_EXITED;
944       ourstatus->value.integer = current_event.u.ExitProcess.dwExitCode;
945       CloseHandle (current_process_handle);
946       current_process_handle = NULL;
947       break;
948
949     case LOAD_DLL_DEBUG_EVENT:
950       OUTMSG2 (("gdbserver: kernel event LOAD_DLL_DEBUG_EVENT "
951                 "for pid=%d tid=%x\n",
952                 (unsigned) current_event.dwProcessId,
953                 (unsigned) current_event.dwThreadId));
954       CloseHandle (current_event.u.LoadDll.hFile);
955
956       ourstatus->kind = TARGET_WAITKIND_LOADED;
957       ourstatus->value.integer = 0;
958       break;
959
960     case UNLOAD_DLL_DEBUG_EVENT:
961       OUTMSG2 (("gdbserver: kernel event UNLOAD_DLL_DEBUG_EVENT "
962                 "for pid=%d tid=%x\n",
963                 (unsigned) current_event.dwProcessId,
964                 (unsigned) current_event.dwThreadId));
965       break;
966
967     case EXCEPTION_DEBUG_EVENT:
968       OUTMSG2 (("gdbserver: kernel event EXCEPTION_DEBUG_EVENT "
969                 "for pid=%d tid=%x\n",
970                 (unsigned) current_event.dwProcessId,
971                 (unsigned) current_event.dwThreadId));
972       handle_exception (ourstatus);
973       break;
974
975     case OUTPUT_DEBUG_STRING_EVENT:
976       /* A message from the kernel (or Cygwin).  */
977       OUTMSG2 (("gdbserver: kernel event OUTPUT_DEBUG_STRING_EVENT "
978                 "for pid=%d tid=%x\n",
979                 (unsigned) current_event.dwProcessId,
980                 (unsigned) current_event.dwThreadId));
981       handle_output_debug_string (ourstatus);
982       break;
983
984     default:
985       OUTMSG2 (("gdbserver: kernel event unknown "
986                 "for pid=%d tid=%x code=%ld\n",
987                 (unsigned) current_event.dwProcessId,
988                 (unsigned) current_event.dwThreadId,
989                 current_event.dwDebugEventCode));
990       break;
991     }
992
993   current_inferior =
994     (struct thread_info *) find_inferior_id (&all_threads,
995                                              current_event.dwThreadId);
996 }
997
998 /* Wait for the inferior process to change state.
999    STATUS will be filled in with a response code to send to GDB.
1000    Returns the signal which caused the process to stop. */
1001 static unsigned char
1002 win32_wait (char *status)
1003 {
1004   struct target_waitstatus our_status;
1005
1006   *status = 'T';
1007
1008   while (1)
1009     {
1010       get_child_debug_event (&our_status);
1011
1012       switch (our_status.kind)
1013         {
1014         case TARGET_WAITKIND_EXITED:
1015           OUTMSG2 (("Child exited with retcode = %x\n",
1016                     our_status.value.integer));
1017
1018           *status = 'W';
1019
1020           child_fetch_inferior_registers (-1);
1021
1022           return our_status.value.integer;
1023         case TARGET_WAITKIND_STOPPED:
1024           OUTMSG2 (("Child Stopped with signal = %d \n",
1025                     our_status.value.sig));
1026
1027           *status = 'T';
1028
1029           child_fetch_inferior_registers (-1);
1030
1031           return our_status.value.sig;
1032         default:
1033           OUTMSG (("Ignoring unknown internal event, %d\n", our_status.kind));
1034           /* fall-through */
1035         case TARGET_WAITKIND_SPURIOUS:
1036         case TARGET_WAITKIND_LOADED:
1037         case TARGET_WAITKIND_EXECD:
1038           /* do nothing, just continue */
1039           child_continue (DBG_CONTINUE, -1);
1040           break;
1041         }
1042     }
1043 }
1044
1045 /* Fetch registers from the inferior process.
1046    If REGNO is -1, fetch all registers; otherwise, fetch at least REGNO.  */
1047 static void
1048 win32_fetch_inferior_registers (int regno)
1049 {
1050   child_fetch_inferior_registers (regno);
1051 }
1052
1053 /* Store registers to the inferior process.
1054    If REGNO is -1, store all registers; otherwise, store at least REGNO.  */
1055 static void
1056 win32_store_inferior_registers (int regno)
1057 {
1058   child_store_inferior_registers (regno);
1059 }
1060
1061 /* Read memory from the inferior process.  This should generally be
1062    called through read_inferior_memory, which handles breakpoint shadowing.
1063    Read LEN bytes at MEMADDR into a buffer at MYADDR.  */
1064 static int
1065 win32_read_inferior_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
1066 {
1067   return child_xfer_memory (memaddr, (char *) myaddr, len, 0, 0) != len;
1068 }
1069
1070 /* Write memory to the inferior process.  This should generally be
1071    called through write_inferior_memory, which handles breakpoint shadowing.
1072    Write LEN bytes from the buffer at MYADDR to MEMADDR.
1073    Returns 0 on success and errno on failure.  */
1074 static int
1075 win32_write_inferior_memory (CORE_ADDR memaddr, const unsigned char *myaddr,
1076                              int len)
1077 {
1078   return child_xfer_memory (memaddr, (char *) myaddr, len, 1, 0) != len;
1079 }
1080
1081 static const char *
1082 win32_arch_string (void)
1083 {
1084   return the_low_target.arch_string;
1085 }
1086
1087 static struct target_ops win32_target_ops = {
1088   win32_create_inferior,
1089   win32_attach,
1090   win32_kill,
1091   win32_detach,
1092   win32_join,
1093   win32_thread_alive,
1094   win32_resume,
1095   win32_wait,
1096   win32_fetch_inferior_registers,
1097   win32_store_inferior_registers,
1098   win32_read_inferior_memory,
1099   win32_write_inferior_memory,
1100   NULL,
1101   NULL,
1102   NULL,
1103   NULL,
1104   NULL,
1105   NULL,
1106   NULL,
1107   NULL,
1108   NULL,
1109   win32_arch_string
1110 };
1111
1112 /* Initialize the Win32 backend.  */
1113 void
1114 initialize_low (void)
1115 {
1116   set_target_ops (&win32_target_ops);
1117   if (the_low_target.breakpoint != NULL)
1118     set_breakpoint_data (the_low_target.breakpoint,
1119                          the_low_target.breakpoint_len);
1120   init_registers ();
1121 }