gdb/gdbserver/win32-low.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* Low level interface to Windows debugging, for gdbserver.
  2.    Copyright (C) 2006-2015 Free Software Foundation, Inc.

  3.    Contributed by Leo Zayas.  Based on "win32-nat.c" from GDB.

  4.    This file is part of GDB.

  5.    This program is free software; you can redistribute it and/or modify
  6.    it under the terms of the GNU General Public License as published by
  7.    the Free Software Foundation; either version 3 of the License, or
  8.    (at your option) any later version.

  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.

  13.    You should have received a copy of the GNU General Public License
  14.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  15. #include "server.h"
  16. #include "regcache.h"
  17. #include "gdb/fileio.h"
  18. #include "mem-break.h"
  19. #include "win32-low.h"
  20. #include "gdbthread.h"
  21. #include "dll.h"
  22. #include "hostio.h"

  23. #include <stdint.h>
  24. #include <windows.h>
  25. #include <winnt.h>
  26. #include <imagehlp.h>
  27. #include <tlhelp32.h>
  28. #include <psapi.h>
  29. #include <process.h>

  30. #ifndef USE_WIN32API
  31. #include <sys/cygwin.h>
  32. #endif

  33. #define OUTMSG(X) do { printf X; fflush (stderr); } while (0)

  34. #define OUTMSG2(X) \
  35.   do                                                \
  36.     {                                                \
  37.       if (debug_threads)                        \
  38.         {                                        \
  39.           printf X;                                \
  40.           fflush (stderr);                        \
  41.         }                                        \
  42.     } while (0)

  43. #ifndef _T
  44. #define _T(x) TEXT (x)
  45. #endif

  46. #ifndef COUNTOF
  47. #define COUNTOF(STR) (sizeof (STR) / sizeof ((STR)[0]))
  48. #endif

  49. #ifdef _WIN32_WCE
  50. # define GETPROCADDRESS(DLL, PROC) \
  51.   ((winapi_ ## PROC) GetProcAddress (DLL, TEXT (#PROC)))
  52. #else
  53. # define GETPROCADDRESS(DLL, PROC) \
  54.   ((winapi_ ## PROC) GetProcAddress (DLL, #PROC))
  55. #endif

  56. int using_threads = 1;

  57. /* Globals.  */
  58. static int attaching = 0;
  59. static HANDLE current_process_handle = NULL;
  60. static DWORD current_process_id = 0;
  61. static DWORD main_thread_id = 0;
  62. static enum gdb_signal last_sig = GDB_SIGNAL_0;

  63. /* The current debug event from WaitForDebugEvent.  */
  64. static DEBUG_EVENT current_event;

  65. /* A status that hasn't been reported to the core yet, and so
  66.    win32_wait should return it next, instead of fetching the next
  67.    debug event off the win32 API.  */
  68. static struct target_waitstatus cached_status;

  69. /* Non zero if an interrupt request is to be satisfied by suspending
  70.    all threads.  */
  71. static int soft_interrupt_requested = 0;

  72. /* Non zero if the inferior is stopped in a simulated breakpoint done
  73.    by suspending all the threads.  */
  74. static int faked_breakpoint = 0;

  75. const struct target_desc *win32_tdesc;

  76. #define NUM_REGS (the_low_target.num_regs)

  77. typedef BOOL (WINAPI *winapi_DebugActiveProcessStop) (DWORD dwProcessId);
  78. typedef BOOL (WINAPI *winapi_DebugSetProcessKillOnExit) (BOOL KillOnExit);
  79. typedef BOOL (WINAPI *winapi_DebugBreakProcess) (HANDLE);
  80. typedef BOOL (WINAPI *winapi_GenerateConsoleCtrlEvent) (DWORD, DWORD);

  81. static ptid_t win32_wait (ptid_t ptid, struct target_waitstatus *ourstatus,
  82.                           int options);
  83. static void win32_resume (struct thread_resume *resume_info, size_t n);
  84. #ifndef _WIN32_WCE
  85. static void win32_add_all_dlls (void);
  86. #endif

  87. /* Get the thread ID from the current selected inferior (the current
  88.    thread).  */
  89. static ptid_t
  90. current_thread_ptid (void)
  91. {
  92.   return current_ptid;
  93. }

  94. /* The current debug event from WaitForDebugEvent.  */
  95. static ptid_t
  96. debug_event_ptid (DEBUG_EVENT *event)
  97. {
  98.   return ptid_build (event->dwProcessId, event->dwThreadId, 0);
  99. }

  100. /* Get the thread context of the thread associated with TH.  */

  101. static void
  102. win32_get_thread_context (win32_thread_info *th)
  103. {
  104.   memset (&th->context, 0, sizeof (CONTEXT));
  105.   (*the_low_target.get_thread_context) (th);
  106. #ifdef _WIN32_WCE
  107.   memcpy (&th->base_context, &th->context, sizeof (CONTEXT));
  108. #endif
  109. }

  110. /* Set the thread context of the thread associated with TH.  */

  111. static void
  112. win32_set_thread_context (win32_thread_info *th)
  113. {
  114. #ifdef _WIN32_WCE
  115.   /* Calling SuspendThread on a thread that is running kernel code
  116.      will report that the suspending was successful, but in fact, that
  117.      will often not be true.  In those cases, the context returned by
  118.      GetThreadContext will not be correct by the time the thread
  119.      stops, hence we can't set that context back into the thread when
  120.      resuming - it will most likelly crash the inferior.
  121.      Unfortunately, there is no way to know when the thread will
  122.      really stop.  To work around it, we'll only write the context
  123.      back to the thread when either the user or GDB explicitly change
  124.      it between stopping and resuming.  */
  125.   if (memcmp (&th->context, &th->base_context, sizeof (CONTEXT)) != 0)
  126. #endif
  127.     SetThreadContext (th->h, &th->context);
  128. }

  129. /* Set the thread context of the thread associated with TH.  */

  130. static void
  131. win32_prepare_to_resume (win32_thread_info *th)
  132. {
  133.   if (the_low_target.prepare_to_resume != NULL)
  134.     (*the_low_target.prepare_to_resume) (th);
  135. }

  136. /* See win32-low.h.  */

  137. void
  138. win32_require_context (win32_thread_info *th)
  139. {
  140.   if (th->context.ContextFlags == 0)
  141.     {
  142.       if (!th->suspended)
  143.         {
  144.           if (SuspendThread (th->h) == (DWORD) -1)
  145.             {
  146.               DWORD err = GetLastError ();
  147.               OUTMSG (("warning: SuspendThread failed in thread_rec, "
  148.                        "(error %d): %s\n", (int) err, strwinerror (err)));
  149.             }
  150.           else
  151.             th->suspended = 1;
  152.         }

  153.       win32_get_thread_context (th);
  154.     }
  155. }

  156. /* Find a thread record given a thread id.  If GET_CONTEXT is set then
  157.    also retrieve the context for this thread.  */
  158. static win32_thread_info *
  159. thread_rec (ptid_t ptid, int get_context)
  160. {
  161.   struct thread_info *thread;
  162.   win32_thread_info *th;

  163.   thread = (struct thread_info *) find_inferior_id (&all_threads, ptid);
  164.   if (thread == NULL)
  165.     return NULL;

  166.   th = inferior_target_data (thread);
  167.   if (get_context)
  168.     win32_require_context (th);
  169.   return th;
  170. }

  171. /* Add a thread to the thread list.  */
  172. static win32_thread_info *
  173. child_add_thread (DWORD pid, DWORD tid, HANDLE h, void *tlb)
  174. {
  175.   win32_thread_info *th;
  176.   ptid_t ptid = ptid_build (pid, tid, 0);

  177.   if ((th = thread_rec (ptid, FALSE)))
  178.     return th;

  179.   th = xcalloc (1, sizeof (*th));
  180.   th->tid = tid;
  181.   th->h = h;
  182.   th->thread_local_base = (CORE_ADDR) (uintptr_t) tlb;

  183.   add_thread (ptid, th);

  184.   if (the_low_target.thread_added != NULL)
  185.     (*the_low_target.thread_added) (th);

  186.   return th;
  187. }

  188. /* Delete a thread from the list of threads.  */
  189. static void
  190. delete_thread_info (struct inferior_list_entry *thread)
  191. {
  192.   win32_thread_info *th = inferior_target_data ((struct thread_info *) thread);

  193.   remove_thread ((struct thread_info *) thread);
  194.   CloseHandle (th->h);
  195.   free (th);
  196. }

  197. /* Delete a thread from the list of threads.  */
  198. static void
  199. child_delete_thread (DWORD pid, DWORD tid)
  200. {
  201.   struct inferior_list_entry *thread;
  202.   ptid_t ptid;

  203.   /* If the last thread is exiting, just return.  */
  204.   if (one_inferior_p (&all_threads))
  205.     return;

  206.   ptid = ptid_build (pid, tid, 0);
  207.   thread = find_inferior_id (&all_threads, ptid);
  208.   if (thread == NULL)
  209.     return;

  210.   delete_thread_info (thread);
  211. }

  212. /* These watchpoint related wrapper functions simply pass on the function call
  213.    if the low target has registered a corresponding function.  */

  214. static int
  215. win32_supports_z_point_type (char z_type)
  216. {
  217.   return (the_low_target.supports_z_point_type != NULL
  218.           && the_low_target.supports_z_point_type (z_type));
  219. }

  220. static int
  221. win32_insert_point (enum raw_bkpt_type type, CORE_ADDR addr,
  222.                     int size, struct raw_breakpoint *bp)
  223. {
  224.   if (the_low_target.insert_point != NULL)
  225.     return the_low_target.insert_point (type, addr, size, bp);
  226.   else
  227.     /* Unsupported (see target.h).  */
  228.     return 1;
  229. }

  230. static int
  231. win32_remove_point (enum raw_bkpt_type type, CORE_ADDR addr,
  232.                     int size, struct raw_breakpoint *bp)
  233. {
  234.   if (the_low_target.remove_point != NULL)
  235.     return the_low_target.remove_point (type, addr, size, bp);
  236.   else
  237.     /* Unsupported (see target.h).  */
  238.     return 1;
  239. }

  240. static int
  241. win32_stopped_by_watchpoint (void)
  242. {
  243.   if (the_low_target.stopped_by_watchpoint != NULL)
  244.     return the_low_target.stopped_by_watchpoint ();
  245.   else
  246.     return 0;
  247. }

  248. static CORE_ADDR
  249. win32_stopped_data_address (void)
  250. {
  251.   if (the_low_target.stopped_data_address != NULL)
  252.     return the_low_target.stopped_data_address ();
  253.   else
  254.     return 0;
  255. }


  256. /* Transfer memory from/to the debugged process.  */
  257. static int
  258. child_xfer_memory (CORE_ADDR memaddr, char *our, int len,
  259.                    int write, struct target_ops *target)
  260. {
  261.   BOOL success;
  262.   SIZE_T done = 0;
  263.   DWORD lasterror = 0;
  264.   uintptr_t addr = (uintptr_t) memaddr;

  265.   if (write)
  266.     {
  267.       success = WriteProcessMemory (current_process_handle, (LPVOID) addr,
  268.                                     (LPCVOID) our, len, &done);
  269.       if (!success)
  270.         lasterror = GetLastError ();
  271.       FlushInstructionCache (current_process_handle, (LPCVOID) addr, len);
  272.     }
  273.   else
  274.     {
  275.       success = ReadProcessMemory (current_process_handle, (LPCVOID) addr,
  276.                                    (LPVOID) our, len, &done);
  277.       if (!success)
  278.         lasterror = GetLastError ();
  279.     }
  280.   if (!success && lasterror == ERROR_PARTIAL_COPY && done > 0)
  281.     return done;
  282.   else
  283.     return success ? done : -1;
  284. }

  285. /* Clear out any old thread list and reinitialize it to a pristine
  286.    state. */
  287. static void
  288. child_init_thread_list (void)
  289. {
  290.   for_each_inferior (&all_threads, delete_thread_info);
  291. }

  292. /* Zero during the child initialization phase, and nonzero otherwise.  */

  293. static int child_initialization_done = 0;

  294. static void
  295. do_initial_child_stuff (HANDLE proch, DWORD pid, int attached)
  296. {
  297.   struct process_info *proc;

  298.   last_sig = GDB_SIGNAL_0;

  299.   current_process_handle = proch;
  300.   current_process_id = pid;
  301.   main_thread_id = 0;

  302.   soft_interrupt_requested = 0;
  303.   faked_breakpoint = 0;

  304.   memset (&current_event, 0, sizeof (current_event));

  305.   proc = add_process (pid, attached);
  306.   proc->tdesc = win32_tdesc;
  307.   child_init_thread_list ();
  308.   child_initialization_done = 0;

  309.   if (the_low_target.initial_stuff != NULL)
  310.     (*the_low_target.initial_stuff) ();

  311.   cached_status.kind = TARGET_WAITKIND_IGNORE;

  312.   /* Flush all currently pending debug events (thread and dll list) up
  313.      to the initial breakpoint.  */
  314.   while (1)
  315.     {
  316.       struct target_waitstatus status;

  317.       win32_wait (minus_one_ptid, &status, 0);

  318.       /* Note win32_wait doesn't return thread events.  */
  319.       if (status.kind != TARGET_WAITKIND_LOADED)
  320.         {
  321.           cached_status = status;
  322.           break;
  323.         }

  324.       {
  325.         struct thread_resume resume;

  326.         resume.thread = minus_one_ptid;
  327.         resume.kind = resume_continue;
  328.         resume.sig = 0;

  329.         win32_resume (&resume, 1);
  330.       }
  331.     }

  332. #ifndef _WIN32_WCE
  333.   /* Now that the inferior has been started and all DLLs have been mapped,
  334.      we can iterate over all DLLs and load them in.

  335.      We avoid doing it any earlier because, on certain versions of Windows,
  336.      LOAD_DLL_DEBUG_EVENTs are sometimes not complete.  In particular,
  337.      we have seen on Windows 8.1 that the ntdll.dll load event does not
  338.      include the DLL name, preventing us from creating an associated SO.
  339.      A possible explanation is that ntdll.dll might be mapped before
  340.      the SO info gets created by the Windows system -- ntdll.dll is
  341.      the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs
  342.      do not seem to suffer from that problem.

  343.      Rather than try to work around this sort of issue, it is much
  344.      simpler to just ignore DLL load/unload events during the startup
  345.      phase, and then process them all in one batch now.  */
  346.   win32_add_all_dlls ();
  347. #endif

  348.   child_initialization_done = 1;
  349. }

  350. /* Resume all artificially suspended threads if we are continuing
  351.    execution.  */
  352. static int
  353. continue_one_thread (struct inferior_list_entry *this_thread, void *id_ptr)
  354. {
  355.   struct thread_info *thread = (struct thread_info *) this_thread;
  356.   int thread_id = * (int *) id_ptr;
  357.   win32_thread_info *th = inferior_target_data (thread);

  358.   if (thread_id == -1 || thread_id == th->tid)
  359.     {
  360.       win32_prepare_to_resume (th);

  361.       if (th->suspended)
  362.         {
  363.           if (th->context.ContextFlags)
  364.             {
  365.               win32_set_thread_context (th);
  366.               th->context.ContextFlags = 0;
  367.             }

  368.           if (ResumeThread (th->h) == (DWORD) -1)
  369.             {
  370.               DWORD err = GetLastError ();
  371.               OUTMSG (("warning: ResumeThread failed in continue_one_thread, "
  372.                        "(error %d): %s\n", (int) err, strwinerror (err)));
  373.             }
  374.           th->suspended = 0;
  375.         }
  376.     }

  377.   return 0;
  378. }

  379. static BOOL
  380. child_continue (DWORD continue_status, int thread_id)
  381. {
  382.   /* The inferior will only continue after the ContinueDebugEvent
  383.      call.  */
  384.   find_inferior (&all_threads, continue_one_thread, &thread_id);
  385.   faked_breakpoint = 0;

  386.   if (!ContinueDebugEvent (current_event.dwProcessId,
  387.                            current_event.dwThreadId,
  388.                            continue_status))
  389.     return FALSE;

  390.   return TRUE;
  391. }

  392. /* Fetch register(s) from the current thread context.  */
  393. static void
  394. child_fetch_inferior_registers (struct regcache *regcache, int r)
  395. {
  396.   int regno;
  397.   win32_thread_info *th = thread_rec (current_thread_ptid (), TRUE);
  398.   if (r == -1 || r > NUM_REGS)
  399.     child_fetch_inferior_registers (regcache, NUM_REGS);
  400.   else
  401.     for (regno = 0; regno < r; regno++)
  402.       (*the_low_target.fetch_inferior_register) (regcache, th, regno);
  403. }

  404. /* Store a new register value into the current thread context.  We don't
  405.    change the program's context until later, when we resume it.  */
  406. static void
  407. child_store_inferior_registers (struct regcache *regcache, int r)
  408. {
  409.   int regno;
  410.   win32_thread_info *th = thread_rec (current_thread_ptid (), TRUE);
  411.   if (r == -1 || r == 0 || r > NUM_REGS)
  412.     child_store_inferior_registers (regcache, NUM_REGS);
  413.   else
  414.     for (regno = 0; regno < r; regno++)
  415.       (*the_low_target.store_inferior_register) (regcache, th, regno);
  416. }

  417. /* Map the Windows error number in ERROR to a locale-dependent error
  418.    message string and return a pointer to it.  Typically, the values
  419.    for ERROR come from GetLastError.

  420.    The string pointed to shall not be modified by the application,
  421.    but may be overwritten by a subsequent call to strwinerror

  422.    The strwinerror function does not change the current setting
  423.    of GetLastError.  */

  424. char *
  425. strwinerror (DWORD error)
  426. {
  427.   static char buf[1024];
  428.   TCHAR *msgbuf;
  429.   DWORD lasterr = GetLastError ();
  430.   DWORD chars = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
  431.                                | FORMAT_MESSAGE_ALLOCATE_BUFFER,
  432.                                NULL,
  433.                                error,
  434.                                0, /* Default language */
  435.                                (LPVOID)&msgbuf,
  436.                                0,
  437.                                NULL);
  438.   if (chars != 0)
  439.     {
  440.       /* If there is an \r\n appended, zap it.  */
  441.       if (chars >= 2
  442.           && msgbuf[chars - 2] == '\r'
  443.           && msgbuf[chars - 1] == '\n')
  444.         {
  445.           chars -= 2;
  446.           msgbuf[chars] = 0;
  447.         }

  448.       if (chars > ((COUNTOF (buf)) - 1))
  449.         {
  450.           chars = COUNTOF (buf) - 1;
  451.           msgbuf [chars] = 0;
  452.         }

  453. #ifdef UNICODE
  454.       wcstombs (buf, msgbuf, chars + 1);
  455. #else
  456.       strncpy (buf, msgbuf, chars + 1);
  457. #endif
  458.       LocalFree (msgbuf);
  459.     }
  460.   else
  461.     sprintf (buf, "unknown win32 error (%u)", (unsigned) error);

  462.   SetLastError (lasterr);
  463.   return buf;
  464. }

  465. static BOOL
  466. create_process (const char *program, char *args,
  467.                 DWORD flags, PROCESS_INFORMATION *pi)
  468. {
  469.   BOOL ret;

  470. #ifdef _WIN32_WCE
  471.   wchar_t *p, *wprogram, *wargs;
  472.   size_t argslen;

  473.   wprogram = alloca ((strlen (program) + 1) * sizeof (wchar_t));
  474.   mbstowcs (wprogram, program, strlen (program) + 1);

  475.   for (p = wprogram; *p; ++p)
  476.     if (L'/' == *p)
  477.       *p = L'\\';

  478.   argslen = strlen (args);
  479.   wargs = alloca ((argslen + 1) * sizeof (wchar_t));
  480.   mbstowcs (wargs, args, argslen + 1);

  481.   ret = CreateProcessW (wprogram, /* image name */
  482.                         wargs,    /* command line */
  483.                         NULL,     /* security, not supported */
  484.                         NULL,     /* thread, not supported */
  485.                         FALSE,    /* inherit handles, not supported */
  486.                         flags,    /* start flags */
  487.                         NULL,     /* environment, not supported */
  488.                         NULL,     /* current directory, not supported */
  489.                         NULL,     /* start info, not supported */
  490.                         pi);      /* proc info */
  491. #else
  492.   STARTUPINFOA si = { sizeof (STARTUPINFOA) };

  493.   ret = CreateProcessA (program,  /* image name */
  494.                         args,     /* command line */
  495.                         NULL,     /* security */
  496.                         NULL,     /* thread */
  497.                         TRUE,     /* inherit handles */
  498.                         flags,    /* start flags */
  499.                         NULL,     /* environment */
  500.                         NULL,     /* current directory */
  501.                         &si,      /* start info */
  502.                         pi);      /* proc info */
  503. #endif

  504.   return ret;
  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
  513. win32_create_inferior (char *program, char **program_args)
  514. {
  515. #ifndef USE_WIN32API
  516.   char real_path[PATH_MAX];
  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.   /* win32_wait needs to know we're not attaching.  */
  527.   attaching = 0;

  528.   if (!program)
  529.     error ("No executable specified, specify executable to debug.\n");

  530.   flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS;

  531. #ifndef USE_WIN32API
  532.   orig_path = NULL;
  533.   path_ptr = getenv ("PATH");
  534.   if (path_ptr)
  535.     {
  536.       int size = cygwin_conv_path_list (CCP_POSIX_TO_WIN_A, path_ptr, NULL, 0);
  537.       orig_path = alloca (strlen (path_ptr) + 1);
  538.       new_path = alloca (size);
  539.       strcpy (orig_path, path_ptr);
  540.       cygwin_conv_path_list (CCP_POSIX_TO_WIN_A, path_ptr, new_path, size);
  541.       setenv ("PATH", new_path, 1);
  542.      }
  543.   cygwin_conv_path (CCP_POSIX_TO_WIN_A, program, real_path, PATH_MAX);
  544.   program = real_path;
  545. #endif

  546.   argslen = 1;
  547.   for (argc = 1; program_args[argc]; argc++)
  548.     argslen += strlen (program_args[argc]) + 1;
  549.   args = alloca (argslen);
  550.   args[0] = '\0';
  551.   for (argc = 1; program_args[argc]; argc++)
  552.     {
  553.       /* FIXME: Can we do better about quoting?  How does Cygwin
  554.          handle this?  */
  555.       strcat (args, " ");
  556.       strcat (args, program_args[argc]);
  557.     }
  558.   OUTMSG2 (("Command line is \"%s\"\n", args));

  559. #ifdef CREATE_NEW_PROCESS_GROUP
  560.   flags |= CREATE_NEW_PROCESS_GROUP;
  561. #endif

  562.   ret = create_process (program, args, flags, &pi);
  563.   err = GetLastError ();
  564.   if (!ret && err == ERROR_FILE_NOT_FOUND)
  565.     {
  566.       char *exename = alloca (strlen (program) + 5);
  567.       strcat (strcpy (exename, program), ".exe");
  568.       ret = create_process (exename, args, flags, &pi);
  569.       err = GetLastError ();
  570.     }

  571. #ifndef USE_WIN32API
  572.   if (orig_path)
  573.     setenv ("PATH", orig_path, 1);
  574. #endif

  575.   if (!ret)
  576.     {
  577.       error ("Error creating process \"%s%s\", (error %d): %s\n",
  578.              program, args, (int) err, strwinerror (err));
  579.     }
  580.   else
  581.     {
  582.       OUTMSG2 (("Process created: %s\n", (char *) args));
  583.     }

  584. #ifndef _WIN32_WCE
  585.   /* On Windows CE this handle can't be closed.  The OS reuses
  586.      it in the debug events, while the 9x/NT versions of Windows
  587.      probably use a DuplicateHandle'd one.  */
  588.   CloseHandle (pi.hThread);
  589. #endif

  590.   do_initial_child_stuff (pi.hProcess, pi.dwProcessId, 0);

  591.   return current_process_id;
  592. }

  593. /* Attach to a running process.
  594.    PID is the process ID to attach to, specified by the user
  595.    or a higher layer.  */
  596. static int
  597. win32_attach (unsigned long pid)
  598. {
  599.   HANDLE h;
  600.   winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit = NULL;
  601.   DWORD err;
  602. #ifdef _WIN32_WCE
  603.   HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
  604. #else
  605.   HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
  606. #endif
  607.   DebugSetProcessKillOnExit = GETPROCADDRESS (dll, DebugSetProcessKillOnExit);

  608.   h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
  609.   if (h != NULL)
  610.     {
  611.       if (DebugActiveProcess (pid))
  612.         {
  613.           if (DebugSetProcessKillOnExit != NULL)
  614.             DebugSetProcessKillOnExit (FALSE);

  615.           /* win32_wait needs to know we're attaching.  */
  616.           attaching = 1;
  617.           do_initial_child_stuff (h, pid, 1);
  618.           return 0;
  619.         }

  620.       CloseHandle (h);
  621.     }

  622.   err = GetLastError ();
  623.   error ("Attach to process failed (error %d): %s\n",
  624.          (int) err, strwinerror (err));
  625. }

  626. /* Handle OUTPUT_DEBUG_STRING_EVENT from child process.  */
  627. static void
  628. handle_output_debug_string (struct target_waitstatus *ourstatus)
  629. {
  630. #define READ_BUFFER_LEN 1024
  631.   CORE_ADDR addr;
  632.   char s[READ_BUFFER_LEN + 1] = { 0 };
  633.   DWORD nbytes = current_event.u.DebugString.nDebugStringLength;

  634.   if (nbytes == 0)
  635.     return;

  636.   if (nbytes > READ_BUFFER_LEN)
  637.     nbytes = READ_BUFFER_LEN;

  638.   addr = (CORE_ADDR) (size_t) current_event.u.DebugString.lpDebugStringData;

  639.   if (current_event.u.DebugString.fUnicode)
  640.     {
  641.       /* The event tells us how many bytes, not chars, even
  642.          in Unicode.  */
  643.       WCHAR buffer[(READ_BUFFER_LEN + 1) / sizeof (WCHAR)] = { 0 };
  644.       if (read_inferior_memory (addr, (unsigned char *) buffer, nbytes) != 0)
  645.         return;
  646.       wcstombs (s, buffer, (nbytes + 1) / sizeof (WCHAR));
  647.     }
  648.   else
  649.     {
  650.       if (read_inferior_memory (addr, (unsigned char *) s, nbytes) != 0)
  651.         return;
  652.     }

  653.   if (strncmp (s, "cYg", 3) != 0)
  654.     {
  655.       if (!server_waiting)
  656.         {
  657.           OUTMSG2(("%s", s));
  658.           return;
  659.         }

  660.       monitor_output (s);
  661.     }
  662. #undef READ_BUFFER_LEN
  663. }

  664. static void
  665. win32_clear_inferiors (void)
  666. {
  667.   if (current_process_handle != NULL)
  668.     CloseHandle (current_process_handle);

  669.   for_each_inferior (&all_threads, delete_thread_info);
  670.   clear_inferiors ();
  671. }

  672. /* Kill all inferiors.  */
  673. static int
  674. win32_kill (int pid)
  675. {
  676.   struct process_info *process;

  677.   if (current_process_handle == NULL)
  678.     return -1;

  679.   TerminateProcess (current_process_handle, 0);
  680.   for (;;)
  681.     {
  682.       if (!child_continue (DBG_CONTINUE, -1))
  683.         break;
  684.       if (!WaitForDebugEvent (&current_event, INFINITE))
  685.         break;
  686.       if (current_event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
  687.         break;
  688.       else if (current_event.dwDebugEventCode == OUTPUT_DEBUG_STRING_EVENT)
  689.         {
  690.           struct target_waitstatus our_status = { 0 };
  691.           handle_output_debug_string (&our_status);
  692.         }
  693.     }

  694.   win32_clear_inferiors ();

  695.   process = find_process_pid (pid);
  696.   remove_process (process);
  697.   return 0;
  698. }

  699. /* Detach from inferior PID.  */
  700. static int
  701. win32_detach (int pid)
  702. {
  703.   struct process_info *process;
  704.   winapi_DebugActiveProcessStop DebugActiveProcessStop = NULL;
  705.   winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit = NULL;
  706. #ifdef _WIN32_WCE
  707.   HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
  708. #else
  709.   HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
  710. #endif
  711.   DebugActiveProcessStop = GETPROCADDRESS (dll, DebugActiveProcessStop);
  712.   DebugSetProcessKillOnExit = GETPROCADDRESS (dll, DebugSetProcessKillOnExit);

  713.   if (DebugSetProcessKillOnExit == NULL
  714.       || DebugActiveProcessStop == NULL)
  715.     return -1;

  716.   {
  717.     struct thread_resume resume;
  718.     resume.thread = minus_one_ptid;
  719.     resume.kind = resume_continue;
  720.     resume.sig = 0;
  721.     win32_resume (&resume, 1);
  722.   }

  723.   if (!DebugActiveProcessStop (current_process_id))
  724.     return -1;

  725.   DebugSetProcessKillOnExit (FALSE);
  726.   process = find_process_pid (pid);
  727.   remove_process (process);

  728.   win32_clear_inferiors ();
  729.   return 0;
  730. }

  731. static void
  732. win32_mourn (struct process_info *process)
  733. {
  734.   remove_process (process);
  735. }

  736. /* Wait for inferiors to end.  */
  737. static void
  738. win32_join (int pid)
  739. {
  740.   HANDLE h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
  741.   if (h != NULL)
  742.     {
  743.       WaitForSingleObject (h, INFINITE);
  744.       CloseHandle (h);
  745.     }
  746. }

  747. /* Return 1 iff the thread with thread ID TID is alive.  */
  748. static int
  749. win32_thread_alive (ptid_t ptid)
  750. {
  751.   int res;

  752.   /* Our thread list is reliable; don't bother to poll target
  753.      threads.  */
  754.   if (find_inferior_id (&all_threads, ptid) != NULL)
  755.     res = 1;
  756.   else
  757.     res = 0;
  758.   return res;
  759. }

  760. /* Resume the inferior process.  RESUME_INFO describes how we want
  761.    to resume.  */
  762. static void
  763. win32_resume (struct thread_resume *resume_info, size_t n)
  764. {
  765.   DWORD tid;
  766.   enum gdb_signal sig;
  767.   int step;
  768.   win32_thread_info *th;
  769.   DWORD continue_status = DBG_CONTINUE;
  770.   ptid_t ptid;

  771.   /* This handles the very limited set of resume packets that GDB can
  772.      currently produce.  */

  773.   if (n == 1 && ptid_equal (resume_info[0].thread, minus_one_ptid))
  774.     tid = -1;
  775.   else if (n > 1)
  776.     tid = -1;
  777.   else
  778.     /* Yes, we're ignoring resume_info[0].thread.  It'd be tricky to make
  779.        the Windows resume code do the right thing for thread switching.  */
  780.     tid = current_event.dwThreadId;

  781.   if (!ptid_equal (resume_info[0].thread, minus_one_ptid))
  782.     {
  783.       sig = resume_info[0].sig;
  784.       step = resume_info[0].kind == resume_step;
  785.     }
  786.   else
  787.     {
  788.       sig = 0;
  789.       step = 0;
  790.     }

  791.   if (sig != GDB_SIGNAL_0)
  792.     {
  793.       if (current_event.dwDebugEventCode != EXCEPTION_DEBUG_EVENT)
  794.         {
  795.           OUTMSG (("Cannot continue with signal %d here.\n", sig));
  796.         }
  797.       else if (sig == last_sig)
  798.         continue_status = DBG_EXCEPTION_NOT_HANDLED;
  799.       else
  800.         OUTMSG (("Can only continue with recieved signal %d.\n", last_sig));
  801.     }

  802.   last_sig = GDB_SIGNAL_0;

  803.   /* Get context for the currently selected thread.  */
  804.   ptid = debug_event_ptid (&current_event);
  805.   th = thread_rec (ptid, FALSE);
  806.   if (th)
  807.     {
  808.       win32_prepare_to_resume (th);

  809.       if (th->context.ContextFlags)
  810.         {
  811.           /* Move register values from the inferior into the thread
  812.              context structure.  */
  813.           regcache_invalidate ();

  814.           if (step)
  815.             {
  816.               if (the_low_target.single_step != NULL)
  817.                 (*the_low_target.single_step) (th);
  818.               else
  819.                 error ("Single stepping is not supported "
  820.                        "in this configuration.\n");
  821.             }

  822.           win32_set_thread_context (th);
  823.           th->context.ContextFlags = 0;
  824.         }
  825.     }

  826.   /* Allow continuing with the same signal that interrupted us.
  827.      Otherwise complain.  */

  828.   child_continue (continue_status, tid);
  829. }

  830. static void
  831. win32_add_one_solib (const char *name, CORE_ADDR load_addr)
  832. {
  833.   char buf[MAX_PATH + 1];
  834.   char buf2[MAX_PATH + 1];

  835. #ifdef _WIN32_WCE
  836.   WIN32_FIND_DATA w32_fd;
  837.   WCHAR wname[MAX_PATH + 1];
  838.   mbstowcs (wname, name, MAX_PATH);
  839.   HANDLE h = FindFirstFile (wname, &w32_fd);
  840. #else
  841.   WIN32_FIND_DATAA w32_fd;
  842.   HANDLE h = FindFirstFileA (name, &w32_fd);
  843. #endif

  844.   /* The symbols in a dll are offset by 0x1000, which is the
  845.      offset from 0 of the first byte in an image - because
  846.      of the file header and the section alignment. */
  847.   load_addr += 0x1000;

  848.   if (h == INVALID_HANDLE_VALUE)
  849.     strcpy (buf, name);
  850.   else
  851.     {
  852.       FindClose (h);
  853.       strcpy (buf, name);
  854. #ifndef _WIN32_WCE
  855.       {
  856.         char cwd[MAX_PATH + 1];
  857.         char *p;
  858.         if (GetCurrentDirectoryA (MAX_PATH + 1, cwd))
  859.           {
  860.             p = strrchr (buf, '\\');
  861.             if (p)
  862.               p[1] = '\0';
  863.             SetCurrentDirectoryA (buf);
  864.             GetFullPathNameA (w32_fd.cFileName, MAX_PATH, buf, &p);
  865.             SetCurrentDirectoryA (cwd);
  866.           }
  867.       }
  868. #endif
  869.     }

  870. #ifndef _WIN32_WCE
  871.   if (strcasecmp (buf, "ntdll.dll") == 0)
  872.     {
  873.       GetSystemDirectoryA (buf, sizeof (buf));
  874.       strcat (buf, "\\ntdll.dll");
  875.     }
  876. #endif

  877. #ifdef __CYGWIN__
  878.   cygwin_conv_path (CCP_WIN_A_TO_POSIX, buf, buf2, sizeof (buf2));
  879. #else
  880.   strcpy (buf2, buf);
  881. #endif

  882.   loaded_dll (buf2, load_addr);
  883. }

  884. static char *
  885. get_image_name (HANDLE h, void *address, int unicode)
  886. {
  887.   static char buf[(2 * MAX_PATH) + 1];
  888.   DWORD size = unicode ? sizeof (WCHAR) : sizeof (char);
  889.   char *address_ptr;
  890.   int len = 0;
  891.   char b[2];
  892.   SIZE_T done;

  893.   /* Attempt to read the name of the dll that was detected.
  894.      This is documented to work only when actively debugging
  895.      a program.  It will not work for attached processes. */
  896.   if (address == NULL)
  897.     return NULL;

  898. #ifdef _WIN32_WCE
  899.   /* Windows CE reports the address of the image name,
  900.      instead of an address of a pointer into the image name.  */
  901.   address_ptr = address;
  902. #else
  903.   /* See if we could read the address of a string, and that the
  904.      address isn't null. */
  905.   if (!ReadProcessMemory (h, address,  &address_ptr,
  906.                           sizeof (address_ptr), &done)
  907.       || done != sizeof (address_ptr)
  908.       || !address_ptr)
  909.     return NULL;
  910. #endif

  911.   /* Find the length of the string */
  912.   while (ReadProcessMemory (h, address_ptr + len++ * size, &b, size, &done)
  913.          && (b[0] != 0 || b[size - 1] != 0) && done == size)
  914.     continue;

  915.   if (!unicode)
  916.     ReadProcessMemory (h, address_ptr, buf, len, &done);
  917.   else
  918.     {
  919.       WCHAR *unicode_address = (WCHAR *) alloca (len * sizeof (WCHAR));
  920.       ReadProcessMemory (h, address_ptr, unicode_address, len * sizeof (WCHAR),
  921.                          &done);

  922.       WideCharToMultiByte (CP_ACP, 0, unicode_address, len, buf, len, 0, 0);
  923.     }

  924.   return buf;
  925. }

  926. typedef BOOL (WINAPI *winapi_EnumProcessModules) (HANDLE, HMODULE *,
  927.                                                   DWORD, LPDWORD);
  928. typedef BOOL (WINAPI *winapi_GetModuleInformation) (HANDLE, HMODULE,
  929.                                                     LPMODULEINFO, DWORD);
  930. typedef DWORD (WINAPI *winapi_GetModuleFileNameExA) (HANDLE, HMODULE,
  931.                                                      LPSTR, DWORD);

  932. static winapi_EnumProcessModules win32_EnumProcessModules;
  933. static winapi_GetModuleInformation win32_GetModuleInformation;
  934. static winapi_GetModuleFileNameExA win32_GetModuleFileNameExA;

  935. static BOOL
  936. load_psapi (void)
  937. {
  938.   static int psapi_loaded = 0;
  939.   static HMODULE dll = NULL;

  940.   if (!psapi_loaded)
  941.     {
  942.       psapi_loaded = 1;
  943.       dll = LoadLibrary (TEXT("psapi.dll"));
  944.       if (!dll)
  945.         return FALSE;
  946.       win32_EnumProcessModules =
  947.               GETPROCADDRESS (dll, EnumProcessModules);
  948.       win32_GetModuleInformation =
  949.               GETPROCADDRESS (dll, GetModuleInformation);
  950.       win32_GetModuleFileNameExA =
  951.               GETPROCADDRESS (dll, GetModuleFileNameExA);
  952.     }

  953.   return (win32_EnumProcessModules != NULL
  954.           && win32_GetModuleInformation != NULL
  955.           && win32_GetModuleFileNameExA != NULL);
  956. }

  957. #ifndef _WIN32_WCE

  958. /* Iterate over all DLLs currently mapped by our inferior, and
  959.    add them to our list of solibs.  */

  960. static void
  961. win32_add_all_dlls (void)
  962. {
  963.   size_t i;
  964.   HMODULE dh_buf[1];
  965.   HMODULE *DllHandle = dh_buf;
  966.   DWORD cbNeeded;
  967.   BOOL ok;

  968.   if (!load_psapi ())
  969.     return;

  970.   cbNeeded = 0;
  971.   ok = (*win32_EnumProcessModules) (current_process_handle,
  972.                                     DllHandle,
  973.                                     sizeof (HMODULE),
  974.                                     &cbNeeded);

  975.   if (!ok || !cbNeeded)
  976.     return;

  977.   DllHandle = (HMODULE *) alloca (cbNeeded);
  978.   if (!DllHandle)
  979.     return;

  980.   ok = (*win32_EnumProcessModules) (current_process_handle,
  981.                                     DllHandle,
  982.                                     cbNeeded,
  983.                                     &cbNeeded);
  984.   if (!ok)
  985.     return;

  986.   for (i = 1; i < ((size_t) cbNeeded / sizeof (HMODULE)); i++)
  987.     {
  988.       MODULEINFO mi;
  989.       char dll_name[MAX_PATH];

  990.       if (!(*win32_GetModuleInformation) (current_process_handle,
  991.                                           DllHandle[i],
  992.                                           &mi,
  993.                                           sizeof (mi)))
  994.         continue;
  995.       if ((*win32_GetModuleFileNameExA) (current_process_handle,
  996.                                          DllHandle[i],
  997.                                          dll_name,
  998.                                          MAX_PATH) == 0)
  999.         continue;
  1000.       win32_add_one_solib (dll_name, (CORE_ADDR) (uintptr_t) mi.lpBaseOfDll);
  1001.     }
  1002. }
  1003. #endif

  1004. typedef HANDLE (WINAPI *winapi_CreateToolhelp32Snapshot) (DWORD, DWORD);
  1005. typedef BOOL (WINAPI *winapi_Module32First) (HANDLE, LPMODULEENTRY32);
  1006. typedef BOOL (WINAPI *winapi_Module32Next) (HANDLE, LPMODULEENTRY32);

  1007. /* Handle a DLL load event.

  1008.    This function assumes that this event did not occur during inferior
  1009.    initialization, where their event info may be incomplete (see
  1010.    do_initial_child_stuff and win32_add_all_dlls for more info on
  1011.    how we handle DLL loading during that phase).  */

  1012. static void
  1013. handle_load_dll (void)
  1014. {
  1015.   LOAD_DLL_DEBUG_INFO *event = &current_event.u.LoadDll;
  1016.   char *dll_name;

  1017.   dll_name = get_image_name (current_process_handle,
  1018.                              event->lpImageName, event->fUnicode);
  1019.   if (!dll_name)
  1020.     return;

  1021.   win32_add_one_solib (dll_name, (CORE_ADDR) (uintptr_t) event->lpBaseOfDll);
  1022. }

  1023. /* Handle a DLL unload event.

  1024.    This function assumes that this event did not occur during inferior
  1025.    initialization, where their event info may be incomplete (see
  1026.    do_initial_child_stuff and win32_add_one_solib for more info
  1027.    on how we handle DLL loading during that phase).  */

  1028. static void
  1029. handle_unload_dll (void)
  1030. {
  1031.   CORE_ADDR load_addr =
  1032.           (CORE_ADDR) (uintptr_t) current_event.u.UnloadDll.lpBaseOfDll;

  1033.   /* The symbols in a dll are offset by 0x1000, which is the
  1034.      offset from 0 of the first byte in an image - because
  1035.      of the file header and the section alignment. */
  1036.   load_addr += 0x1000;
  1037.   unloaded_dll (NULL, load_addr);
  1038. }

  1039. static void
  1040. handle_exception (struct target_waitstatus *ourstatus)
  1041. {
  1042.   DWORD code = current_event.u.Exception.ExceptionRecord.ExceptionCode;

  1043.   ourstatus->kind = TARGET_WAITKIND_STOPPED;

  1044.   switch (code)
  1045.     {
  1046.     case EXCEPTION_ACCESS_VIOLATION:
  1047.       OUTMSG2 (("EXCEPTION_ACCESS_VIOLATION"));
  1048.       ourstatus->value.sig = GDB_SIGNAL_SEGV;
  1049.       break;
  1050.     case STATUS_STACK_OVERFLOW:
  1051.       OUTMSG2 (("STATUS_STACK_OVERFLOW"));
  1052.       ourstatus->value.sig = GDB_SIGNAL_SEGV;
  1053.       break;
  1054.     case STATUS_FLOAT_DENORMAL_OPERAND:
  1055.       OUTMSG2 (("STATUS_FLOAT_DENORMAL_OPERAND"));
  1056.       ourstatus->value.sig = GDB_SIGNAL_FPE;
  1057.       break;
  1058.     case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
  1059.       OUTMSG2 (("EXCEPTION_ARRAY_BOUNDS_EXCEEDED"));
  1060.       ourstatus->value.sig = GDB_SIGNAL_FPE;
  1061.       break;
  1062.     case STATUS_FLOAT_INEXACT_RESULT:
  1063.       OUTMSG2 (("STATUS_FLOAT_INEXACT_RESULT"));
  1064.       ourstatus->value.sig = GDB_SIGNAL_FPE;
  1065.       break;
  1066.     case STATUS_FLOAT_INVALID_OPERATION:
  1067.       OUTMSG2 (("STATUS_FLOAT_INVALID_OPERATION"));
  1068.       ourstatus->value.sig = GDB_SIGNAL_FPE;
  1069.       break;
  1070.     case STATUS_FLOAT_OVERFLOW:
  1071.       OUTMSG2 (("STATUS_FLOAT_OVERFLOW"));
  1072.       ourstatus->value.sig = GDB_SIGNAL_FPE;
  1073.       break;
  1074.     case STATUS_FLOAT_STACK_CHECK:
  1075.       OUTMSG2 (("STATUS_FLOAT_STACK_CHECK"));
  1076.       ourstatus->value.sig = GDB_SIGNAL_FPE;
  1077.       break;
  1078.     case STATUS_FLOAT_UNDERFLOW:
  1079.       OUTMSG2 (("STATUS_FLOAT_UNDERFLOW"));
  1080.       ourstatus->value.sig = GDB_SIGNAL_FPE;
  1081.       break;
  1082.     case STATUS_FLOAT_DIVIDE_BY_ZERO:
  1083.       OUTMSG2 (("STATUS_FLOAT_DIVIDE_BY_ZERO"));
  1084.       ourstatus->value.sig = GDB_SIGNAL_FPE;
  1085.       break;
  1086.     case STATUS_INTEGER_DIVIDE_BY_ZERO:
  1087.       OUTMSG2 (("STATUS_INTEGER_DIVIDE_BY_ZERO"));
  1088.       ourstatus->value.sig = GDB_SIGNAL_FPE;
  1089.       break;
  1090.     case STATUS_INTEGER_OVERFLOW:
  1091.       OUTMSG2 (("STATUS_INTEGER_OVERFLOW"));
  1092.       ourstatus->value.sig = GDB_SIGNAL_FPE;
  1093.       break;
  1094.     case EXCEPTION_BREAKPOINT:
  1095.       OUTMSG2 (("EXCEPTION_BREAKPOINT"));
  1096.       ourstatus->value.sig = GDB_SIGNAL_TRAP;
  1097. #ifdef _WIN32_WCE
  1098.       /* Remove the initial breakpoint.  */
  1099.       check_breakpoints ((CORE_ADDR) (long) current_event
  1100.                          .u.Exception.ExceptionRecord.ExceptionAddress);
  1101. #endif
  1102.       break;
  1103.     case DBG_CONTROL_C:
  1104.       OUTMSG2 (("DBG_CONTROL_C"));
  1105.       ourstatus->value.sig = GDB_SIGNAL_INT;
  1106.       break;
  1107.     case DBG_CONTROL_BREAK:
  1108.       OUTMSG2 (("DBG_CONTROL_BREAK"));
  1109.       ourstatus->value.sig = GDB_SIGNAL_INT;
  1110.       break;
  1111.     case EXCEPTION_SINGLE_STEP:
  1112.       OUTMSG2 (("EXCEPTION_SINGLE_STEP"));
  1113.       ourstatus->value.sig = GDB_SIGNAL_TRAP;
  1114.       break;
  1115.     case EXCEPTION_ILLEGAL_INSTRUCTION:
  1116.       OUTMSG2 (("EXCEPTION_ILLEGAL_INSTRUCTION"));
  1117.       ourstatus->value.sig = GDB_SIGNAL_ILL;
  1118.       break;
  1119.     case EXCEPTION_PRIV_INSTRUCTION:
  1120.       OUTMSG2 (("EXCEPTION_PRIV_INSTRUCTION"));
  1121.       ourstatus->value.sig = GDB_SIGNAL_ILL;
  1122.       break;
  1123.     case EXCEPTION_NONCONTINUABLE_EXCEPTION:
  1124.       OUTMSG2 (("EXCEPTION_NONCONTINUABLE_EXCEPTION"));
  1125.       ourstatus->value.sig = GDB_SIGNAL_ILL;
  1126.       break;
  1127.     default:
  1128.       if (current_event.u.Exception.dwFirstChance)
  1129.         {
  1130.           ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
  1131.           return;
  1132.         }
  1133.       OUTMSG2 (("gdbserver: unknown target exception 0x%08x at 0x%s",
  1134.             (unsigned) current_event.u.Exception.ExceptionRecord.ExceptionCode,
  1135.             phex_nz ((uintptr_t) current_event.u.Exception.ExceptionRecord.
  1136.             ExceptionAddress, sizeof (uintptr_t))));
  1137.       ourstatus->value.sig = GDB_SIGNAL_UNKNOWN;
  1138.       break;
  1139.     }
  1140.   OUTMSG2 (("\n"));
  1141.   last_sig = ourstatus->value.sig;
  1142. }


  1143. static void
  1144. suspend_one_thread (struct inferior_list_entry *entry)
  1145. {
  1146.   struct thread_info *thread = (struct thread_info *) entry;
  1147.   win32_thread_info *th = inferior_target_data (thread);

  1148.   if (!th->suspended)
  1149.     {
  1150.       if (SuspendThread (th->h) == (DWORD) -1)
  1151.         {
  1152.           DWORD err = GetLastError ();
  1153.           OUTMSG (("warning: SuspendThread failed in suspend_one_thread, "
  1154.                    "(error %d): %s\n", (int) err, strwinerror (err)));
  1155.         }
  1156.       else
  1157.         th->suspended = 1;
  1158.     }
  1159. }

  1160. static void
  1161. fake_breakpoint_event (void)
  1162. {
  1163.   OUTMSG2(("fake_breakpoint_event\n"));

  1164.   faked_breakpoint = 1;

  1165.   memset (&current_event, 0, sizeof (current_event));
  1166.   current_event.dwThreadId = main_thread_id;
  1167.   current_event.dwDebugEventCode = EXCEPTION_DEBUG_EVENT;
  1168.   current_event.u.Exception.ExceptionRecord.ExceptionCode
  1169.     = EXCEPTION_BREAKPOINT;

  1170.   for_each_inferior (&all_threads, suspend_one_thread);
  1171. }

  1172. #ifdef _WIN32_WCE
  1173. static int
  1174. auto_delete_breakpoint (CORE_ADDR stop_pc)
  1175. {
  1176.   return 1;
  1177. }
  1178. #endif

  1179. /* Get the next event from the child.  */

  1180. static int
  1181. get_child_debug_event (struct target_waitstatus *ourstatus)
  1182. {
  1183.   ptid_t ptid;

  1184.   last_sig = GDB_SIGNAL_0;
  1185.   ourstatus->kind = TARGET_WAITKIND_SPURIOUS;

  1186.   /* Check if GDB sent us an interrupt request.  */
  1187.   check_remote_input_interrupt_request ();

  1188.   if (soft_interrupt_requested)
  1189.     {
  1190.       soft_interrupt_requested = 0;
  1191.       fake_breakpoint_event ();
  1192.       goto gotevent;
  1193.     }

  1194. #ifndef _WIN32_WCE
  1195.   attaching = 0;
  1196. #else
  1197.   if (attaching)
  1198.     {
  1199.       /* WinCE doesn't set an initial breakpoint automatically.  To
  1200.          stop the inferior, we flush all currently pending debug
  1201.          events -- the thread list and the dll list are always
  1202.          reported immediatelly without delay, then, we suspend all
  1203.          threads and pretend we saw a trap at the current PC of the
  1204.          main thread.

  1205.          Contrary to desktop Windows, Windows CE *does* report the dll
  1206.          names on LOAD_DLL_DEBUG_EVENTs resulting from a
  1207.          DebugActiveProcess call.  This limits the way we can detect
  1208.          if all the dlls have already been reported.  If we get a real
  1209.          debug event before leaving attaching, the worst that will
  1210.          happen is the user will see a spurious breakpoint.  */

  1211.       current_event.dwDebugEventCode = 0;
  1212.       if (!WaitForDebugEvent (&current_event, 0))
  1213.         {
  1214.           OUTMSG2(("no attach events left\n"));
  1215.           fake_breakpoint_event ();
  1216.           attaching = 0;
  1217.         }
  1218.       else
  1219.         OUTMSG2(("got attach event\n"));
  1220.     }
  1221.   else
  1222. #endif
  1223.     {
  1224.       /* Keep the wait time low enough for confortable remote
  1225.          interruption, but high enough so gdbserver doesn't become a
  1226.          bottleneck.  */
  1227.       if (!WaitForDebugEvent (&current_event, 250))
  1228.         {
  1229.           DWORD e  = GetLastError();

  1230.           if (e == ERROR_PIPE_NOT_CONNECTED)
  1231.             {
  1232.               /* This will happen if the loader fails to succesfully
  1233.                  load the application, e.g., if the main executable
  1234.                  tries to pull in a non-existing export from a
  1235.                  DLL.  */
  1236.               ourstatus->kind = TARGET_WAITKIND_EXITED;
  1237.               ourstatus->value.integer = 1;
  1238.               return 1;
  1239.             }

  1240.           return 0;
  1241.         }
  1242.     }

  1243. gotevent:

  1244.   switch (current_event.dwDebugEventCode)
  1245.     {
  1246.     case CREATE_THREAD_DEBUG_EVENT:
  1247.       OUTMSG2 (("gdbserver: kernel event CREATE_THREAD_DEBUG_EVENT "
  1248.                 "for pid=%u tid=%x)\n",
  1249.                 (unsigned) current_event.dwProcessId,
  1250.                 (unsigned) current_event.dwThreadId));

  1251.       /* Record the existence of this thread.  */
  1252.       child_add_thread (current_event.dwProcessId,
  1253.                         current_event.dwThreadId,
  1254.                         current_event.u.CreateThread.hThread,
  1255.                         current_event.u.CreateThread.lpThreadLocalBase);
  1256.       break;

  1257.     case EXIT_THREAD_DEBUG_EVENT:
  1258.       OUTMSG2 (("gdbserver: kernel event EXIT_THREAD_DEBUG_EVENT "
  1259.                 "for pid=%u tid=%x\n",
  1260.                 (unsigned) current_event.dwProcessId,
  1261.                 (unsigned) current_event.dwThreadId));
  1262.       child_delete_thread (current_event.dwProcessId,
  1263.                            current_event.dwThreadId);

  1264.       current_thread = (struct thread_info *) all_threads.head;
  1265.       return 1;

  1266.     case CREATE_PROCESS_DEBUG_EVENT:
  1267.       OUTMSG2 (("gdbserver: kernel event CREATE_PROCESS_DEBUG_EVENT "
  1268.                 "for pid=%u tid=%x\n",
  1269.                 (unsigned) current_event.dwProcessId,
  1270.                 (unsigned) current_event.dwThreadId));
  1271.       CloseHandle (current_event.u.CreateProcessInfo.hFile);

  1272.       current_process_handle = current_event.u.CreateProcessInfo.hProcess;
  1273.       main_thread_id = current_event.dwThreadId;

  1274.       ourstatus->kind = TARGET_WAITKIND_EXECD;
  1275.       ourstatus->value.execd_pathname = "Main executable";

  1276.       /* Add the main thread.  */
  1277.       child_add_thread (current_event.dwProcessId,
  1278.                         main_thread_id,
  1279.                         current_event.u.CreateProcessInfo.hThread,
  1280.                         current_event.u.CreateProcessInfo.lpThreadLocalBase);

  1281.       ourstatus->value.related_pid = debug_event_ptid (&current_event);
  1282. #ifdef _WIN32_WCE
  1283.       if (!attaching)
  1284.         {
  1285.           /* Windows CE doesn't set the initial breakpoint
  1286.              automatically like the desktop versions of Windows do.
  1287.              We add it explicitly here.         It will be removed as soon as
  1288.              it is hit.         */
  1289.           set_breakpoint_at ((CORE_ADDR) (long) current_event.u
  1290.                              .CreateProcessInfo.lpStartAddress,
  1291.                              auto_delete_breakpoint);
  1292.         }
  1293. #endif
  1294.       break;

  1295.     case EXIT_PROCESS_DEBUG_EVENT:
  1296.       OUTMSG2 (("gdbserver: kernel event EXIT_PROCESS_DEBUG_EVENT "
  1297.                 "for pid=%u tid=%x\n",
  1298.                 (unsigned) current_event.dwProcessId,
  1299.                 (unsigned) current_event.dwThreadId));
  1300.       ourstatus->kind = TARGET_WAITKIND_EXITED;
  1301.       ourstatus->value.integer = current_event.u.ExitProcess.dwExitCode;
  1302.       child_continue (DBG_CONTINUE, -1);
  1303.       CloseHandle (current_process_handle);
  1304.       current_process_handle = NULL;
  1305.       break;

  1306.     case LOAD_DLL_DEBUG_EVENT:
  1307.       OUTMSG2 (("gdbserver: kernel event LOAD_DLL_DEBUG_EVENT "
  1308.                 "for pid=%u tid=%x\n",
  1309.                 (unsigned) current_event.dwProcessId,
  1310.                 (unsigned) current_event.dwThreadId));
  1311.       CloseHandle (current_event.u.LoadDll.hFile);
  1312.       if (! child_initialization_done)
  1313.         break;
  1314.       handle_load_dll ();

  1315.       ourstatus->kind = TARGET_WAITKIND_LOADED;
  1316.       ourstatus->value.sig = GDB_SIGNAL_TRAP;
  1317.       break;

  1318.     case UNLOAD_DLL_DEBUG_EVENT:
  1319.       OUTMSG2 (("gdbserver: kernel event UNLOAD_DLL_DEBUG_EVENT "
  1320.                 "for pid=%u tid=%x\n",
  1321.                 (unsigned) current_event.dwProcessId,
  1322.                 (unsigned) current_event.dwThreadId));
  1323.       if (! child_initialization_done)
  1324.         break;
  1325.       handle_unload_dll ();
  1326.       ourstatus->kind = TARGET_WAITKIND_LOADED;
  1327.       ourstatus->value.sig = GDB_SIGNAL_TRAP;
  1328.       break;

  1329.     case EXCEPTION_DEBUG_EVENT:
  1330.       OUTMSG2 (("gdbserver: kernel event EXCEPTION_DEBUG_EVENT "
  1331.                 "for pid=%u tid=%x\n",
  1332.                 (unsigned) current_event.dwProcessId,
  1333.                 (unsigned) current_event.dwThreadId));
  1334.       handle_exception (ourstatus);
  1335.       break;

  1336.     case OUTPUT_DEBUG_STRING_EVENT:
  1337.       /* A message from the kernel (or Cygwin).  */
  1338.       OUTMSG2 (("gdbserver: kernel event OUTPUT_DEBUG_STRING_EVENT "
  1339.                 "for pid=%u tid=%x\n",
  1340.                 (unsigned) current_event.dwProcessId,
  1341.                 (unsigned) current_event.dwThreadId));
  1342.       handle_output_debug_string (ourstatus);
  1343.       break;

  1344.     default:
  1345.       OUTMSG2 (("gdbserver: kernel event unknown "
  1346.                 "for pid=%u tid=%x code=%x\n",
  1347.                 (unsigned) current_event.dwProcessId,
  1348.                 (unsigned) current_event.dwThreadId,
  1349.                 (unsigned) current_event.dwDebugEventCode));
  1350.       break;
  1351.     }

  1352.   ptid = debug_event_ptid (&current_event);
  1353.   current_thread =
  1354.     (struct thread_info *) find_inferior_id (&all_threads, ptid);
  1355.   return 1;
  1356. }

  1357. /* Wait for the inferior process to change state.
  1358.    STATUS will be filled in with a response code to send to GDB.
  1359.    Returns the signal which caused the process to stop. */
  1360. static ptid_t
  1361. win32_wait (ptid_t ptid, struct target_waitstatus *ourstatus, int options)
  1362. {
  1363.   struct regcache *regcache;

  1364.   if (cached_status.kind != TARGET_WAITKIND_IGNORE)
  1365.     {
  1366.       /* The core always does a wait after creating the inferior, and
  1367.          do_initial_child_stuff already ran the inferior to the
  1368.          initial breakpoint (or an exit, if creating the process
  1369.          fails).  Report it now.  */
  1370.       *ourstatus = cached_status;
  1371.       cached_status.kind = TARGET_WAITKIND_IGNORE;
  1372.       return debug_event_ptid (&current_event);
  1373.     }

  1374.   while (1)
  1375.     {
  1376.       if (!get_child_debug_event (ourstatus))
  1377.         continue;

  1378.       switch (ourstatus->kind)
  1379.         {
  1380.         case TARGET_WAITKIND_EXITED:
  1381.           OUTMSG2 (("Child exited with retcode = %x\n",
  1382.                     ourstatus->value.integer));
  1383.           win32_clear_inferiors ();
  1384.           return pid_to_ptid (current_event.dwProcessId);
  1385.         case TARGET_WAITKIND_STOPPED:
  1386.         case TARGET_WAITKIND_LOADED:
  1387.           OUTMSG2 (("Child Stopped with signal = %d \n",
  1388.                     ourstatus->value.sig));

  1389.           regcache = get_thread_regcache (current_thread, 1);
  1390.           child_fetch_inferior_registers (regcache, -1);
  1391.           return debug_event_ptid (&current_event);
  1392.         default:
  1393.           OUTMSG (("Ignoring unknown internal event, %d\n", ourstatus->kind));
  1394.           /* fall-through */
  1395.         case TARGET_WAITKIND_SPURIOUS:
  1396.         case TARGET_WAITKIND_EXECD:
  1397.           /* do nothing, just continue */
  1398.           child_continue (DBG_CONTINUE, -1);
  1399.           break;
  1400.         }
  1401.     }
  1402. }

  1403. /* Fetch registers from the inferior process.
  1404.    If REGNO is -1, fetch all registers; otherwise, fetch at least REGNO.  */
  1405. static void
  1406. win32_fetch_inferior_registers (struct regcache *regcache, int regno)
  1407. {
  1408.   child_fetch_inferior_registers (regcache, regno);
  1409. }

  1410. /* Store registers to the inferior process.
  1411.    If REGNO is -1, store all registers; otherwise, store at least REGNO.  */
  1412. static void
  1413. win32_store_inferior_registers (struct regcache *regcache, int regno)
  1414. {
  1415.   child_store_inferior_registers (regcache, regno);
  1416. }

  1417. /* Read memory from the inferior process.  This should generally be
  1418.    called through read_inferior_memory, which handles breakpoint shadowing.
  1419.    Read LEN bytes at MEMADDR into a buffer at MYADDR.  */
  1420. static int
  1421. win32_read_inferior_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
  1422. {
  1423.   return child_xfer_memory (memaddr, (char *) myaddr, len, 0, 0) != len;
  1424. }

  1425. /* Write memory to the inferior process.  This should generally be
  1426.    called through write_inferior_memory, which handles breakpoint shadowing.
  1427.    Write LEN bytes from the buffer at MYADDR to MEMADDR.
  1428.    Returns 0 on success and errno on failure.  */
  1429. static int
  1430. win32_write_inferior_memory (CORE_ADDR memaddr, const unsigned char *myaddr,
  1431.                              int len)
  1432. {
  1433.   return child_xfer_memory (memaddr, (char *) myaddr, len, 1, 0) != len;
  1434. }

  1435. /* Send an interrupt request to the inferior process. */
  1436. static void
  1437. win32_request_interrupt (void)
  1438. {
  1439.   winapi_DebugBreakProcess DebugBreakProcess;
  1440.   winapi_GenerateConsoleCtrlEvent GenerateConsoleCtrlEvent;

  1441. #ifdef _WIN32_WCE
  1442.   HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
  1443. #else
  1444.   HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
  1445. #endif

  1446.   GenerateConsoleCtrlEvent = GETPROCADDRESS (dll, GenerateConsoleCtrlEvent);

  1447.   if (GenerateConsoleCtrlEvent != NULL
  1448.       && GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, current_process_id))
  1449.     return;

  1450.   /* GenerateConsoleCtrlEvent can fail if process id being debugged is
  1451.      not a process group id.
  1452.      Fallback to XP/Vista 'DebugBreakProcess', which generates a
  1453.      breakpoint exception in the interior process.  */

  1454.   DebugBreakProcess = GETPROCADDRESS (dll, DebugBreakProcess);

  1455.   if (DebugBreakProcess != NULL
  1456.       && DebugBreakProcess (current_process_handle))
  1457.     return;

  1458.   /* Last resort, suspend all threads manually.  */
  1459.   soft_interrupt_requested = 1;
  1460. }

  1461. #ifdef _WIN32_WCE
  1462. int
  1463. win32_error_to_fileio_error (DWORD err)
  1464. {
  1465.   switch (err)
  1466.     {
  1467.     case ERROR_BAD_PATHNAME:
  1468.     case ERROR_FILE_NOT_FOUND:
  1469.     case ERROR_INVALID_NAME:
  1470.     case ERROR_PATH_NOT_FOUND:
  1471.       return FILEIO_ENOENT;
  1472.     case ERROR_CRC:
  1473.     case ERROR_IO_DEVICE:
  1474.     case ERROR_OPEN_FAILED:
  1475.       return FILEIO_EIO;
  1476.     case ERROR_INVALID_HANDLE:
  1477.       return FILEIO_EBADF;
  1478.     case ERROR_ACCESS_DENIED:
  1479.     case ERROR_SHARING_VIOLATION:
  1480.       return FILEIO_EACCES;
  1481.     case ERROR_NOACCESS:
  1482.       return FILEIO_EFAULT;
  1483.     case ERROR_BUSY:
  1484.       return FILEIO_EBUSY;
  1485.     case ERROR_ALREADY_EXISTS:
  1486.     case ERROR_FILE_EXISTS:
  1487.       return FILEIO_EEXIST;
  1488.     case ERROR_BAD_DEVICE:
  1489.       return FILEIO_ENODEV;
  1490.     case ERROR_DIRECTORY:
  1491.       return FILEIO_ENOTDIR;
  1492.     case ERROR_FILENAME_EXCED_RANGE:
  1493.     case ERROR_INVALID_DATA:
  1494.     case ERROR_INVALID_PARAMETER:
  1495.     case ERROR_NEGATIVE_SEEK:
  1496.       return FILEIO_EINVAL;
  1497.     case ERROR_TOO_MANY_OPEN_FILES:
  1498.       return FILEIO_EMFILE;
  1499.     case ERROR_HANDLE_DISK_FULL:
  1500.     case ERROR_DISK_FULL:
  1501.       return FILEIO_ENOSPC;
  1502.     case ERROR_WRITE_PROTECT:
  1503.       return FILEIO_EROFS;
  1504.     case ERROR_NOT_SUPPORTED:
  1505.       return FILEIO_ENOSYS;
  1506.     }

  1507.   return FILEIO_EUNKNOWN;
  1508. }

  1509. static void
  1510. wince_hostio_last_error (char *buf)
  1511. {
  1512.   DWORD winerr = GetLastError ();
  1513.   int fileio_err = win32_error_to_fileio_error (winerr);
  1514.   sprintf (buf, "F-1,%x", fileio_err);
  1515. }
  1516. #endif

  1517. /* Write Windows OS Thread Information Block address.  */

  1518. static int
  1519. win32_get_tib_address (ptid_t ptid, CORE_ADDR *addr)
  1520. {
  1521.   win32_thread_info *th;
  1522.   th = thread_rec (ptid, 0);
  1523.   if (th == NULL)
  1524.     return 0;
  1525.   if (addr != NULL)
  1526.     *addr = th->thread_local_base;
  1527.   return 1;
  1528. }

  1529. static struct target_ops win32_target_ops = {
  1530.   win32_create_inferior,
  1531.   win32_attach,
  1532.   win32_kill,
  1533.   win32_detach,
  1534.   win32_mourn,
  1535.   win32_join,
  1536.   win32_thread_alive,
  1537.   win32_resume,
  1538.   win32_wait,
  1539.   win32_fetch_inferior_registers,
  1540.   win32_store_inferior_registers,
  1541.   NULL, /* prepare_to_access_memory */
  1542.   NULL, /* done_accessing_memory */
  1543.   win32_read_inferior_memory,
  1544.   win32_write_inferior_memory,
  1545.   NULL, /* lookup_symbols */
  1546.   win32_request_interrupt,
  1547.   NULL, /* read_auxv */
  1548.   win32_supports_z_point_type,
  1549.   win32_insert_point,
  1550.   win32_remove_point,
  1551.   win32_stopped_by_watchpoint,
  1552.   win32_stopped_data_address,
  1553.   NULL, /* read_offsets */
  1554.   NULL, /* get_tls_address */
  1555.   NULL, /* qxfer_spu */
  1556. #ifdef _WIN32_WCE
  1557.   wince_hostio_last_error,
  1558. #else
  1559.   hostio_last_error_from_errno,
  1560. #endif
  1561.   NULL, /* qxfer_osdata */
  1562.   NULL, /* qxfer_siginfo */
  1563.   NULL, /* supports_non_stop */
  1564.   NULL, /* async */
  1565.   NULL, /* start_non_stop */
  1566.   NULL, /* supports_multi_process */
  1567.   NULL, /* handle_monitor_command */
  1568.   NULL, /* core_of_thread */
  1569.   NULL, /* read_loadmap */
  1570.   NULL, /* process_qsupported */
  1571.   NULL, /* supports_tracepoints */
  1572.   NULL, /* read_pc */
  1573.   NULL, /* write_pc */
  1574.   NULL, /* thread_stopped */
  1575.   win32_get_tib_address
  1576. };

  1577. /* Initialize the Win32 backend.  */
  1578. void
  1579. initialize_low (void)
  1580. {
  1581.   set_target_ops (&win32_target_ops);
  1582.   if (the_low_target.breakpoint != NULL)
  1583.     set_breakpoint_data (the_low_target.breakpoint,
  1584.                          the_low_target.breakpoint_len);
  1585.   the_low_target.arch_setup ();
  1586. }