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