gdb/windows-nat.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* Target-vector operations for controlling windows child processes, for GDB.

  2.    Copyright (C) 1995-2015 Free Software Foundation, Inc.

  3.    Contributed by Cygnus Solutions, A Red Hat Company.

  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. /* Originally by Steve Chamberlain, sac@cygnus.com */

  16. #include "defs.h"
  17. #include "frame.h"                /* required by inferior.h */
  18. #include "inferior.h"
  19. #include "infrun.h"
  20. #include "target.h"
  21. #include "gdbcore.h"
  22. #include "command.h"
  23. #include "completer.h"
  24. #include "regcache.h"
  25. #include "top.h"
  26. #include <signal.h>
  27. #include <sys/types.h>
  28. #include <fcntl.h>
  29. #include <windows.h>
  30. #include <imagehlp.h>
  31. #include <psapi.h>
  32. #ifdef __CYGWIN__
  33. #include <wchar.h>
  34. #include <sys/cygwin.h>
  35. #include <cygwin/version.h>
  36. #endif

  37. #include "buildsym.h"
  38. #include "filenames.h"
  39. #include "symfile.h"
  40. #include "objfiles.h"
  41. #include "gdb_bfd.h"
  42. #include "gdb_obstack.h"
  43. #include "gdbthread.h"
  44. #include "gdbcmd.h"
  45. #include <unistd.h>
  46. #include "exec.h"
  47. #include "solist.h"
  48. #include "solib.h"
  49. #include "xml-support.h"

  50. #include "i386-tdep.h"
  51. #include "i387-tdep.h"

  52. #include "windows-tdep.h"
  53. #include "windows-nat.h"
  54. #include "x86-nat.h"
  55. #include "complaints.h"
  56. #include "inf-child.h"

  57. #define AdjustTokenPrivileges                dyn_AdjustTokenPrivileges
  58. #define DebugActiveProcessStop                dyn_DebugActiveProcessStop
  59. #define DebugBreakProcess                dyn_DebugBreakProcess
  60. #define DebugSetProcessKillOnExit        dyn_DebugSetProcessKillOnExit
  61. #define EnumProcessModules                dyn_EnumProcessModules
  62. #define GetModuleInformation                dyn_GetModuleInformation
  63. #define LookupPrivilegeValueA                dyn_LookupPrivilegeValueA
  64. #define OpenProcessToken                dyn_OpenProcessToken
  65. #define GetConsoleFontSize                dyn_GetConsoleFontSize
  66. #define GetCurrentConsoleFont                dyn_GetCurrentConsoleFont

  67. static BOOL WINAPI (*AdjustTokenPrivileges)(HANDLE, BOOL, PTOKEN_PRIVILEGES,
  68.                                             DWORD, PTOKEN_PRIVILEGES, PDWORD);
  69. static BOOL WINAPI (*DebugActiveProcessStop) (DWORD);
  70. static BOOL WINAPI (*DebugBreakProcess) (HANDLE);
  71. static BOOL WINAPI (*DebugSetProcessKillOnExit) (BOOL);
  72. static BOOL WINAPI (*EnumProcessModules) (HANDLE, HMODULE *, DWORD,
  73.                                           LPDWORD);
  74. static BOOL WINAPI (*GetModuleInformation) (HANDLE, HMODULE, LPMODULEINFO,
  75.                                             DWORD);
  76. static BOOL WINAPI (*LookupPrivilegeValueA)(LPCSTR, LPCSTR, PLUID);
  77. static BOOL WINAPI (*OpenProcessToken)(HANDLE, DWORD, PHANDLE);
  78. static BOOL WINAPI (*GetCurrentConsoleFont) (HANDLE, BOOL,
  79.                                              CONSOLE_FONT_INFO *);
  80. static COORD WINAPI (*GetConsoleFontSize) (HANDLE, DWORD);

  81. #undef STARTUPINFO
  82. #undef CreateProcess
  83. #undef GetModuleFileNameEx

  84. #ifndef __CYGWIN__
  85. # define __PMAX        (MAX_PATH + 1)
  86.   static DWORD WINAPI (*GetModuleFileNameEx) (HANDLE, HMODULE, LPSTR, DWORD);
  87. # define STARTUPINFO STARTUPINFOA
  88. # define CreateProcess CreateProcessA
  89. # define GetModuleFileNameEx_name "GetModuleFileNameExA"
  90. # define bad_GetModuleFileNameEx bad_GetModuleFileNameExA
  91. #else
  92. # define __PMAX        PATH_MAX
  93. /* The starting and ending address of the cygwin1.dll text segment.  */
  94.   static CORE_ADDR cygwin_load_start;
  95.   static CORE_ADDR cygwin_load_end;
  96. #   define __USEWIDE
  97.     typedef wchar_t cygwin_buf_t;
  98.     static DWORD WINAPI (*GetModuleFileNameEx) (HANDLE, HMODULE,
  99.                                                 LPWSTR, DWORD);
  100. #   define STARTUPINFO STARTUPINFOW
  101. #   define CreateProcess CreateProcessW
  102. #   define GetModuleFileNameEx_name "GetModuleFileNameExW"
  103. #   define bad_GetModuleFileNameEx bad_GetModuleFileNameExW
  104. #endif

  105. static int have_saved_context;        /* True if we've saved context from a
  106.                                    cygwin signal.  */
  107. static CONTEXT saved_context;        /* Containes the saved context from a
  108.                                    cygwin signal.  */

  109. /* If we're not using the old Cygwin header file set, define the
  110.    following which never should have been in the generic Win32 API
  111.    headers in the first place since they were our own invention...  */
  112. #ifndef _GNU_H_WINDOWS_H
  113. enum
  114.   {
  115.     FLAG_TRACE_BIT = 0x100,
  116.     CONTEXT_DEBUGGER = (CONTEXT_FULL | CONTEXT_FLOATING_POINT)
  117.   };
  118. #endif

  119. #ifndef CONTEXT_EXTENDED_REGISTERS
  120. /* This macro is only defined on ia32.  It only makes sense on this target,
  121.    so define it as zero if not already defined.  */
  122. #define CONTEXT_EXTENDED_REGISTERS 0
  123. #endif

  124. #define CONTEXT_DEBUGGER_DR CONTEXT_DEBUGGER | CONTEXT_DEBUG_REGISTERS \
  125.         | CONTEXT_EXTENDED_REGISTERS

  126. static uintptr_t dr[8];
  127. static int debug_registers_changed;
  128. static int debug_registers_used;

  129. static int windows_initialization_done;
  130. #define DR6_CLEAR_VALUE 0xffff0ff0

  131. /* The string sent by cygwin when it processes a signal.
  132.    FIXME: This should be in a cygwin include file.  */
  133. #ifndef _CYGWIN_SIGNAL_STRING
  134. #define _CYGWIN_SIGNAL_STRING "cYgSiGw00f"
  135. #endif

  136. #define CHECK(x)        check (x, __FILE__,__LINE__)
  137. #define DEBUG_EXEC(x)        if (debug_exec)                printf_unfiltered x
  138. #define DEBUG_EVENTS(x)        if (debug_events)        printf_unfiltered x
  139. #define DEBUG_MEM(x)        if (debug_memory)        printf_unfiltered x
  140. #define DEBUG_EXCEPT(x)        if (debug_exceptions)        printf_unfiltered x

  141. static void windows_stop (struct target_ops *self, ptid_t);
  142. static int windows_thread_alive (struct target_ops *, ptid_t);
  143. static void windows_kill_inferior (struct target_ops *);

  144. static void cygwin_set_dr (int i, CORE_ADDR addr);
  145. static void cygwin_set_dr7 (unsigned long val);
  146. static CORE_ADDR cygwin_get_dr (int i);
  147. static unsigned long cygwin_get_dr6 (void);
  148. static unsigned long cygwin_get_dr7 (void);

  149. static enum gdb_signal last_sig = GDB_SIGNAL_0;
  150. /* Set if a signal was received from the debugged process.  */

  151. /* Thread information structure used to track information that is
  152.    not available in gdb's thread structure.  */
  153. typedef struct thread_info_struct
  154.   {
  155.     struct thread_info_struct *next;
  156.     DWORD id;
  157.     HANDLE h;
  158.     CORE_ADDR thread_local_base;
  159.     char *name;
  160.     int suspended;
  161.     int reload_context;
  162.     CONTEXT context;
  163.     STACKFRAME sf;
  164.   }
  165. thread_info;

  166. static thread_info thread_head;

  167. /* The process and thread handles for the above context.  */

  168. static DEBUG_EVENT current_event;        /* The current debug event from
  169.                                            WaitForDebugEvent */
  170. static HANDLE current_process_handle;        /* Currently executing process */
  171. static thread_info *current_thread;        /* Info on currently selected thread */
  172. static DWORD main_thread_id;                /* Thread ID of the main thread */

  173. /* Counts of things.  */
  174. static int exception_count = 0;
  175. static int event_count = 0;
  176. static int saw_create;
  177. static int open_process_used = 0;

  178. /* User options.  */
  179. static int new_console = 0;
  180. #ifdef __CYGWIN__
  181. static int cygwin_exceptions = 0;
  182. #endif
  183. static int new_group = 1;
  184. static int debug_exec = 0;                /* show execution */
  185. static int debug_events = 0;                /* show events from kernel */
  186. static int debug_memory = 0;                /* show target memory accesses */
  187. static int debug_exceptions = 0;        /* show target exceptions */
  188. static int useshell = 0;                /* use shell for subprocesses */

  189. /* This vector maps GDB's idea of a register's number into an offset
  190.    in the windows exception context vector.

  191.    It also contains the bit mask needed to load the register in question.

  192.    The contents of this table can only be computed by the units
  193.    that provide CPU-specific support for Windows native debugging.
  194.    These units should set the table by calling
  195.    windows_set_context_register_offsets.

  196.    One day we could read a reg, we could inspect the context we
  197.    already have loaded, if it doesn't have the bit set that we need,
  198.    we read that set of registers in using GetThreadContext.  If the
  199.    context already contains what we need, we just unpack it.  Then to
  200.    write a register, first we have to ensure that the context contains
  201.    the other regs of the group, and then we copy the info in and set
  202.    out bit.  */

  203. static const int *mappings;

  204. /* The function to use in order to determine whether a register is
  205.    a segment register or not.  */
  206. static segment_register_p_ftype *segment_register_p;

  207. /* This vector maps the target's idea of an exception (extracted
  208.    from the DEBUG_EVENT structure) to GDB's idea.  */

  209. struct xlate_exception
  210.   {
  211.     int them;
  212.     enum gdb_signal us;
  213.   };

  214. static const struct xlate_exception
  215.   xlate[] =
  216. {
  217.   {EXCEPTION_ACCESS_VIOLATION, GDB_SIGNAL_SEGV},
  218.   {STATUS_STACK_OVERFLOW, GDB_SIGNAL_SEGV},
  219.   {EXCEPTION_BREAKPOINT, GDB_SIGNAL_TRAP},
  220.   {DBG_CONTROL_C, GDB_SIGNAL_INT},
  221.   {EXCEPTION_SINGLE_STEP, GDB_SIGNAL_TRAP},
  222.   {STATUS_FLOAT_DIVIDE_BY_ZERO, GDB_SIGNAL_FPE},
  223.   {-1, -1}};

  224. /* Set the MAPPINGS static global to OFFSETS.
  225.    See the description of MAPPINGS for more details.  */

  226. void
  227. windows_set_context_register_offsets (const int *offsets)
  228. {
  229.   mappings = offsets;
  230. }

  231. /* See windows-nat.h.  */

  232. void
  233. windows_set_segment_register_p (segment_register_p_ftype *fun)
  234. {
  235.   segment_register_p = fun;
  236. }

  237. static void
  238. check (BOOL ok, const char *file, int line)
  239. {
  240.   if (!ok)
  241.     printf_filtered ("error return %s:%d was %u\n", file, line,
  242.                      (unsigned) GetLastError ());
  243. }

  244. /* Find a thread record given a thread id.  If GET_CONTEXT is not 0,
  245.    then also retrieve the context for this thread.  If GET_CONTEXT is
  246.    negative, then don't suspend the thread.  */
  247. static thread_info *
  248. thread_rec (DWORD id, int get_context)
  249. {
  250.   thread_info *th;

  251.   for (th = &thread_head; (th = th->next) != NULL;)
  252.     if (th->id == id)
  253.       {
  254.         if (!th->suspended && get_context)
  255.           {
  256.             if (get_context > 0 && id != current_event.dwThreadId)
  257.               {
  258.                 if (SuspendThread (th->h) == (DWORD) -1)
  259.                   {
  260.                     DWORD err = GetLastError ();

  261.                     /* We get Access Denied (5) when trying to suspend
  262.                        threads that Windows started on behalf of the
  263.                        debuggee, usually when those threads are just
  264.                        about to exit.  */
  265.                     if (err != ERROR_ACCESS_DENIED)
  266.                       warning (_("SuspendThread (tid=0x%x) failed."
  267.                                  " (winerr %u)"),
  268.                                (unsigned) id, (unsigned) err);
  269.                     th->suspended = -1;
  270.                   }
  271.                 else
  272.                   th->suspended = 1;
  273.               }
  274.             else if (get_context < 0)
  275.               th->suspended = -1;
  276.             th->reload_context = 1;
  277.           }
  278.         return th;
  279.       }

  280.   return NULL;
  281. }

  282. /* Add a thread to the thread list.  */
  283. static thread_info *
  284. windows_add_thread (ptid_t ptid, HANDLE h, void *tlb)
  285. {
  286.   thread_info *th;
  287.   DWORD id;

  288.   gdb_assert (ptid_get_tid (ptid) != 0);

  289.   id = ptid_get_tid (ptid);

  290.   if ((th = thread_rec (id, FALSE)))
  291.     return th;

  292.   th = XCNEW (thread_info);
  293.   th->id = id;
  294.   th->h = h;
  295.   th->thread_local_base = (CORE_ADDR) (uintptr_t) tlb;
  296.   th->next = thread_head.next;
  297.   thread_head.next = th;
  298.   add_thread (ptid);
  299.   /* Set the debug registers for the new thread if they are used.  */
  300.   if (debug_registers_used)
  301.     {
  302.       /* Only change the value of the debug registers.  */
  303.       th->context.ContextFlags = CONTEXT_DEBUG_REGISTERS;
  304.       CHECK (GetThreadContext (th->h, &th->context));
  305.       th->context.Dr0 = dr[0];
  306.       th->context.Dr1 = dr[1];
  307.       th->context.Dr2 = dr[2];
  308.       th->context.Dr3 = dr[3];
  309.       th->context.Dr6 = DR6_CLEAR_VALUE;
  310.       th->context.Dr7 = dr[7];
  311.       CHECK (SetThreadContext (th->h, &th->context));
  312.       th->context.ContextFlags = 0;
  313.     }
  314.   return th;
  315. }

  316. /* Clear out any old thread list and reintialize it to a
  317.    pristine state.  */
  318. static void
  319. windows_init_thread_list (void)
  320. {
  321.   thread_info *th = &thread_head;

  322.   DEBUG_EVENTS (("gdb: windows_init_thread_list\n"));
  323.   init_thread_list ();
  324.   while (th->next != NULL)
  325.     {
  326.       thread_info *here = th->next;
  327.       th->next = here->next;
  328.       xfree (here);
  329.     }
  330.   thread_head.next = NULL;
  331. }

  332. /* Delete a thread from the list of threads.  */
  333. static void
  334. windows_delete_thread (ptid_t ptid, DWORD exit_code)
  335. {
  336.   thread_info *th;
  337.   DWORD id;

  338.   gdb_assert (ptid_get_tid (ptid) != 0);

  339.   id = ptid_get_tid (ptid);

  340.   if (info_verbose)
  341.     printf_unfiltered ("[Deleting %s]\n", target_pid_to_str (ptid));
  342.   else if (print_thread_events && id != main_thread_id)
  343.     printf_unfiltered (_("[%s exited with code %u]\n"),
  344.                        target_pid_to_str (ptid), (unsigned) exit_code);
  345.   delete_thread (ptid);

  346.   for (th = &thread_head;
  347.        th->next != NULL && th->next->id != id;
  348.        th = th->next)
  349.     continue;

  350.   if (th->next != NULL)
  351.     {
  352.       thread_info *here = th->next;
  353.       th->next = here->next;
  354.       xfree (here);
  355.     }
  356. }

  357. static void
  358. do_windows_fetch_inferior_registers (struct regcache *regcache, int r)
  359. {
  360.   char *context_offset = ((char *) &current_thread->context) + mappings[r];
  361.   struct gdbarch *gdbarch = get_regcache_arch (regcache);
  362.   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
  363.   long l;

  364.   if (!current_thread)
  365.     return;        /* Windows sometimes uses a non-existent thread id in its
  366.                    events.  */

  367.   if (current_thread->reload_context)
  368.     {
  369. #ifdef __COPY_CONTEXT_SIZE
  370.       if (have_saved_context)
  371.         {
  372.           /* Lie about where the program actually is stopped since
  373.              cygwin has informed us that we should consider the signal
  374.              to have occurred at another location which is stored in
  375.              "saved_context.  */
  376.           memcpy (&current_thread->context, &saved_context,
  377.                   __COPY_CONTEXT_SIZE);
  378.           have_saved_context = 0;
  379.         }
  380.       else
  381. #endif
  382.         {
  383.           thread_info *th = current_thread;
  384.           th->context.ContextFlags = CONTEXT_DEBUGGER_DR;
  385.           CHECK (GetThreadContext (th->h, &th->context));
  386.           /* Copy dr values from that thread.
  387.              But only if there were not modified since last stop.
  388.              PR gdb/2388 */
  389.           if (!debug_registers_changed)
  390.             {
  391.               dr[0] = th->context.Dr0;
  392.               dr[1] = th->context.Dr1;
  393.               dr[2] = th->context.Dr2;
  394.               dr[3] = th->context.Dr3;
  395.               dr[6] = th->context.Dr6;
  396.               dr[7] = th->context.Dr7;
  397.             }
  398.         }
  399.       current_thread->reload_context = 0;
  400.     }

  401.   if (r == I387_FISEG_REGNUM (tdep))
  402.     {
  403.       l = *((long *) context_offset) & 0xffff;
  404.       regcache_raw_supply (regcache, r, (char *) &l);
  405.     }
  406.   else if (r == I387_FOP_REGNUM (tdep))
  407.     {
  408.       l = (*((long *) context_offset) >> 16) & ((1 << 11) - 1);
  409.       regcache_raw_supply (regcache, r, (char *) &l);
  410.     }
  411.   else if (segment_register_p (r))
  412.     {
  413.       /* GDB treats segment registers as 32bit registers, but they are
  414.          in fact only 16 bits long.  Make sure we do not read extra
  415.          bits from our source buffer.  */
  416.       l = *((long *) context_offset) & 0xffff;
  417.       regcache_raw_supply (regcache, r, (char *) &l);
  418.     }
  419.   else if (r >= 0)
  420.     regcache_raw_supply (regcache, r, context_offset);
  421.   else
  422.     {
  423.       for (r = 0; r < gdbarch_num_regs (gdbarch); r++)
  424.         do_windows_fetch_inferior_registers (regcache, r);
  425.     }
  426. }

  427. static void
  428. windows_fetch_inferior_registers (struct target_ops *ops,
  429.                                   struct regcache *regcache, int r)
  430. {
  431.   current_thread = thread_rec (ptid_get_tid (inferior_ptid), TRUE);
  432.   /* Check if current_thread exists.  Windows sometimes uses a non-existent
  433.      thread id in its events.  */
  434.   if (current_thread)
  435.     do_windows_fetch_inferior_registers (regcache, r);
  436. }

  437. static void
  438. do_windows_store_inferior_registers (const struct regcache *regcache, int r)
  439. {
  440.   if (!current_thread)
  441.     /* Windows sometimes uses a non-existent thread id in its events.  */;
  442.   else if (r >= 0)
  443.     regcache_raw_collect (regcache, r,
  444.                           ((char *) &current_thread->context) + mappings[r]);
  445.   else
  446.     {
  447.       for (r = 0; r < gdbarch_num_regs (get_regcache_arch (regcache)); r++)
  448.         do_windows_store_inferior_registers (regcache, r);
  449.     }
  450. }

  451. /* Store a new register value into the current thread context.  */
  452. static void
  453. windows_store_inferior_registers (struct target_ops *ops,
  454.                                   struct regcache *regcache, int r)
  455. {
  456.   current_thread = thread_rec (ptid_get_tid (inferior_ptid), TRUE);
  457.   /* Check if current_thread exists.  Windows sometimes uses a non-existent
  458.      thread id in its events.  */
  459.   if (current_thread)
  460.     do_windows_store_inferior_registers (regcache, r);
  461. }

  462. /* Encapsulate the information required in a call to
  463.    symbol_file_add_args.  */
  464. struct safe_symbol_file_add_args
  465. {
  466.   char *name;
  467.   int from_tty;
  468.   struct section_addr_info *addrs;
  469.   int mainline;
  470.   int flags;
  471.   struct ui_file *err, *out;
  472.   struct objfile *ret;
  473. };

  474. /* Maintain a linked list of "so" information.  */
  475. struct lm_info
  476. {
  477.   LPVOID load_addr;
  478. };

  479. static struct so_list solib_start, *solib_end;

  480. static struct so_list *
  481. windows_make_so (const char *name, LPVOID load_addr)
  482. {
  483.   struct so_list *so;
  484.   char *p;
  485. #ifndef __CYGWIN__
  486.   char buf[__PMAX];
  487.   char cwd[__PMAX];
  488.   WIN32_FIND_DATA w32_fd;
  489.   HANDLE h = FindFirstFile(name, &w32_fd);

  490.   if (h == INVALID_HANDLE_VALUE)
  491.     strcpy (buf, name);
  492.   else
  493.     {
  494.       FindClose (h);
  495.       strcpy (buf, name);
  496.       if (GetCurrentDirectory (MAX_PATH + 1, cwd))
  497.         {
  498.           p = strrchr (buf, '\\');
  499.           if (p)
  500.             p[1] = '\0';
  501.           SetCurrentDirectory (buf);
  502.           GetFullPathName (w32_fd.cFileName, MAX_PATH, buf, &p);
  503.           SetCurrentDirectory (cwd);
  504.         }
  505.     }
  506.   if (strcasecmp (buf, "ntdll.dll") == 0)
  507.     {
  508.       GetSystemDirectory (buf, sizeof (buf));
  509.       strcat (buf, "\\ntdll.dll");
  510.     }
  511. #else
  512.   cygwin_buf_t buf[__PMAX];

  513.   buf[0] = 0;
  514.   if (access (name, F_OK) != 0)
  515.     {
  516.       if (strcasecmp (name, "ntdll.dll") == 0)
  517. #ifdef __USEWIDE
  518.         {
  519.           GetSystemDirectoryW (buf, sizeof (buf) / sizeof (wchar_t));
  520.           wcscat (buf, L"\\ntdll.dll");
  521.         }
  522. #else
  523.         {
  524.           GetSystemDirectoryA (buf, sizeof (buf) / sizeof (wchar_t));
  525.           strcat (buf, "\\ntdll.dll");
  526.         }
  527. #endif
  528.     }
  529. #endif
  530.   so = XCNEW (struct so_list);
  531.   so->lm_info = (struct lm_info *) xmalloc (sizeof (struct lm_info));
  532.   so->lm_info->load_addr = load_addr;
  533.   strcpy (so->so_original_name, name);
  534. #ifndef __CYGWIN__
  535.   strcpy (so->so_name, buf);
  536. #else
  537.   if (buf[0])
  538.     cygwin_conv_path (CCP_WIN_W_TO_POSIX, buf, so->so_name,
  539.                       SO_NAME_MAX_PATH_SIZE);
  540.   else
  541.     {
  542.       char *rname = realpath (name, NULL);
  543.       if (rname && strlen (rname) < SO_NAME_MAX_PATH_SIZE)
  544.         {
  545.           strcpy (so->so_name, rname);
  546.           free (rname);
  547.         }
  548.       else
  549.         error (_("dll path too long"));
  550.     }
  551.   /* Record cygwin1.dll .text start/end.  */
  552.   p = strchr (so->so_name, '\0') - (sizeof ("/cygwin1.dll") - 1);
  553.   if (p >= so->so_name && strcasecmp (p, "/cygwin1.dll") == 0)
  554.     {
  555.       bfd *abfd;
  556.       asection *text = NULL;
  557.       CORE_ADDR text_vma;

  558.       abfd = gdb_bfd_open (so->so_name, "pei-i386", -1);

  559.       if (!abfd)
  560.         return so;

  561.       if (bfd_check_format (abfd, bfd_object))
  562.         text = bfd_get_section_by_name (abfd, ".text");

  563.       if (!text)
  564.         {
  565.           gdb_bfd_unref (abfd);
  566.           return so;
  567.         }

  568.       /* The symbols in a dll are offset by 0x1000, which is the
  569.          offset from 0 of the first byte in an image - because of the
  570.          file header and the section alignment.  */
  571.       cygwin_load_start = (CORE_ADDR) (uintptr_t) ((char *)
  572.                                                    load_addr + 0x1000);
  573.       cygwin_load_end = cygwin_load_start + bfd_section_size (abfd, text);

  574.       gdb_bfd_unref (abfd);
  575.     }
  576. #endif

  577.   return so;
  578. }

  579. static char *
  580. get_image_name (HANDLE h, void *address, int unicode)
  581. {
  582. #ifdef __CYGWIN__
  583.   static char buf[__PMAX];
  584. #else
  585.   static char buf[(2 * __PMAX) + 1];
  586. #endif
  587.   DWORD size = unicode ? sizeof (WCHAR) : sizeof (char);
  588.   char *address_ptr;
  589.   int len = 0;
  590.   char b[2];
  591.   SIZE_T done;

  592.   /* Attempt to read the name of the dll that was detected.
  593.      This is documented to work only when actively debugging
  594.      a program.  It will not work for attached processes.  */
  595.   if (address == NULL)
  596.     return NULL;

  597.   /* See if we could read the address of a string, and that the
  598.      address isn't null.  */
  599.   if (!ReadProcessMemory (h, address,  &address_ptr,
  600.                           sizeof (address_ptr), &done)
  601.       || done != sizeof (address_ptr) || !address_ptr)
  602.     return NULL;

  603.   /* Find the length of the string.  */
  604.   while (ReadProcessMemory (h, address_ptr + len++ * size, &b, size, &done)
  605.          && (b[0] != 0 || b[size - 1] != 0) && done == size)
  606.     continue;

  607.   if (!unicode)
  608.     ReadProcessMemory (h, address_ptr, buf, len, &done);
  609.   else
  610.     {
  611.       WCHAR *unicode_address = (WCHAR *) alloca (len * sizeof (WCHAR));
  612.       ReadProcessMemory (h, address_ptr, unicode_address, len * sizeof (WCHAR),
  613.                          &done);
  614. #ifdef __CYGWIN__
  615.       wcstombs (buf, unicode_address, __PMAX);
  616. #else
  617.       WideCharToMultiByte (CP_ACP, 0, unicode_address, len, buf, sizeof buf,
  618.                            0, 0);
  619. #endif
  620.     }

  621.   return buf;
  622. }

  623. /* Handle a DLL load event, and return 1.

  624.    This function assumes that this event did not occur during inferior
  625.    initialization, where their event info may be incomplete (see
  626.    do_initial_windows_stuff and windows_add_all_dlls for more info
  627.    on how we handle DLL loading during that phase).  */

  628. static int
  629. handle_load_dll (void *dummy)
  630. {
  631.   LOAD_DLL_DEBUG_INFO *event = &current_event.u.LoadDll;
  632.   char *dll_name;

  633.   /* Try getting the DLL name via the lpImageName field of the event.
  634.      Note that Microsoft documents this fields as strictly optional,
  635.      in the sense that it might be NULL.  And the first DLL event in
  636.      particular is explicitly documented as "likely not pass[ed]"
  637.      (source: MSDN LOAD_DLL_DEBUG_INFO structure).  */
  638.   dll_name = get_image_name (current_process_handle,
  639.                              event->lpImageName, event->fUnicode);
  640.   if (!dll_name)
  641.     return 1;

  642.   solib_end->next = windows_make_so (dll_name, event->lpBaseOfDll);
  643.   solib_end = solib_end->next;

  644.   DEBUG_EVENTS (("gdb: Loading dll \"%s\" at %s.\n", solib_end->so_name,
  645.                  host_address_to_string (solib_end->lm_info->load_addr)));

  646.   return 1;
  647. }

  648. static void
  649. windows_free_so (struct so_list *so)
  650. {
  651.   if (so->lm_info)
  652.     xfree (so->lm_info);
  653.   xfree (so);
  654. }

  655. /* Handle a DLL unload event.
  656.    Return 1 if successful, or zero otherwise.

  657.    This function assumes that this event did not occur during inferior
  658.    initialization, where their event info may be incomplete (see
  659.    do_initial_windows_stuff and windows_add_all_dlls for more info
  660.    on how we handle DLL loading during that phase).  */

  661. static int
  662. handle_unload_dll (void *dummy)
  663. {
  664.   LPVOID lpBaseOfDll = current_event.u.UnloadDll.lpBaseOfDll;
  665.   struct so_list *so;

  666.   for (so = &solib_start; so->next != NULL; so = so->next)
  667.     if (so->next->lm_info->load_addr == lpBaseOfDll)
  668.       {
  669.         struct so_list *sodel = so->next;

  670.         so->next = sodel->next;
  671.         if (!so->next)
  672.           solib_end = so;
  673.         DEBUG_EVENTS (("gdb: Unloading dll \"%s\".\n", sodel->so_name));

  674.         windows_free_so (sodel);
  675.         return 1;
  676.       }

  677.   /* We did not find any DLL that was previously loaded at this address,
  678.      so register a complaint.  We do not report an error, because we have
  679.      observed that this may be happening under some circumstances.  For
  680.      instance, running 32bit applications on x64 Windows causes us to receive
  681.      4 mysterious UNLOAD_DLL_DEBUG_EVENTs during the startup phase (these
  682.      events are apparently caused by the WOW layer, the interface between
  683.      32bit and 64bit worlds).  */
  684.   complaint (&symfile_complaints, _("dll starting at %s not found."),
  685.              host_address_to_string (lpBaseOfDll));

  686.   return 0;
  687. }

  688. /* Clear list of loaded DLLs.  */
  689. static void
  690. windows_clear_solib (void)
  691. {
  692.   solib_start.next = NULL;
  693.   solib_end = &solib_start;
  694. }

  695. /* Handle DEBUG_STRING output from child process.
  696.    Cygwin prepends its messages with a "cygwin:".  Interpret this as
  697.    a Cygwin signal.  Otherwise just print the string as a warning.  */
  698. static int
  699. handle_output_debug_string (struct target_waitstatus *ourstatus)
  700. {
  701.   char *s = NULL;
  702.   int retval = 0;

  703.   if (!target_read_string
  704.         ((CORE_ADDR) (uintptr_t) current_event.u.DebugString.lpDebugStringData,
  705.         &s, 1024, 0)
  706.       || !s || !*s)
  707.     /* nothing to do */;
  708.   else if (strncmp (s, _CYGWIN_SIGNAL_STRING,
  709.                     sizeof (_CYGWIN_SIGNAL_STRING) - 1) != 0)
  710.     {
  711. #ifdef __CYGWIN__
  712.       if (strncmp (s, "cYg", 3) != 0)
  713. #endif
  714.         warning (("%s"), s);
  715.     }
  716. #ifdef __COPY_CONTEXT_SIZE
  717.   else
  718.     {
  719.       /* Got a cygwin signal markerA cygwin signal is followed by
  720.          the signal number itself and then optionally followed by the
  721.          thread id and address to saved context within the DLL.  If
  722.          these are supplied, then the given thread is assumed to have
  723.          issued the signal and the context from the thread is assumed
  724.          to be stored at the given address in the inferior.  Tell gdb
  725.          to treat this like a real signal.  */
  726.       char *p;
  727.       int sig = strtol (s + sizeof (_CYGWIN_SIGNAL_STRING) - 1, &p, 0);
  728.       int gotasig = gdb_signal_from_host (sig);

  729.       ourstatus->value.sig = gotasig;
  730.       if (gotasig)
  731.         {
  732.           LPCVOID x;
  733.           SIZE_T n;

  734.           ourstatus->kind = TARGET_WAITKIND_STOPPED;
  735.           retval = strtoul (p, &p, 0);
  736.           if (!retval)
  737.             retval = main_thread_id;
  738.           else if ((x = (LPCVOID) (uintptr_t) strtoull (p, NULL, 0))
  739.                    && ReadProcessMemory (current_process_handle, x,
  740.                                          &saved_context,
  741.                                          __COPY_CONTEXT_SIZE, &n)
  742.                    && n == __COPY_CONTEXT_SIZE)
  743.             have_saved_context = 1;
  744.           current_event.dwThreadId = retval;
  745.         }
  746.     }
  747. #endif

  748.   if (s)
  749.     xfree (s);
  750.   return retval;
  751. }

  752. static int
  753. display_selector (HANDLE thread, DWORD sel)
  754. {
  755.   LDT_ENTRY info;
  756.   if (GetThreadSelectorEntry (thread, sel, &info))
  757.     {
  758.       int base, limit;
  759.       printf_filtered ("0x%03x: ", (unsigned) sel);
  760.       if (!info.HighWord.Bits.Pres)
  761.         {
  762.           puts_filtered ("Segment not present\n");
  763.           return 0;
  764.         }
  765.       base = (info.HighWord.Bits.BaseHi << 24) +
  766.              (info.HighWord.Bits.BaseMid << 16)
  767.              + info.BaseLow;
  768.       limit = (info.HighWord.Bits.LimitHi << 16) + info.LimitLow;
  769.       if (info.HighWord.Bits.Granularity)
  770.         limit = (limit << 12) | 0xfff;
  771.       printf_filtered ("base=0x%08x limit=0x%08x", base, limit);
  772.       if (info.HighWord.Bits.Default_Big)
  773.         puts_filtered(" 32-bit ");
  774.       else
  775.         puts_filtered(" 16-bit ");
  776.       switch ((info.HighWord.Bits.Type & 0xf) >> 1)
  777.         {
  778.         case 0:
  779.           puts_filtered ("Data (Read-Only, Exp-up");
  780.           break;
  781.         case 1:
  782.           puts_filtered ("Data (Read/Write, Exp-up");
  783.           break;
  784.         case 2:
  785.           puts_filtered ("Unused segment (");
  786.           break;
  787.         case 3:
  788.           puts_filtered ("Data (Read/Write, Exp-down");
  789.           break;
  790.         case 4:
  791.           puts_filtered ("Code (Exec-Only, N.Conf");
  792.           break;
  793.         case 5:
  794.           puts_filtered ("Code (Exec/Read, N.Conf");
  795.           break;
  796.         case 6:
  797.           puts_filtered ("Code (Exec-Only, Conf");
  798.           break;
  799.         case 7:
  800.           puts_filtered ("Code (Exec/Read, Conf");
  801.           break;
  802.         default:
  803.           printf_filtered ("Unknown type 0x%x",info.HighWord.Bits.Type);
  804.         }
  805.       if ((info.HighWord.Bits.Type & 0x1) == 0)
  806.         puts_filtered(", N.Acc");
  807.       puts_filtered (")\n");
  808.       if ((info.HighWord.Bits.Type & 0x10) == 0)
  809.         puts_filtered("System selector ");
  810.       printf_filtered ("Priviledge level = %d. ", info.HighWord.Bits.Dpl);
  811.       if (info.HighWord.Bits.Granularity)
  812.         puts_filtered ("Page granular.\n");
  813.       else
  814.         puts_filtered ("Byte granular.\n");
  815.       return 1;
  816.     }
  817.   else
  818.     {
  819.       DWORD err = GetLastError ();
  820.       if (err == ERROR_NOT_SUPPORTED)
  821.         printf_filtered ("Function not supported\n");
  822.       else
  823.         printf_filtered ("Invalid selector 0x%x.\n", (unsigned) sel);
  824.       return 0;
  825.     }
  826. }

  827. static void
  828. display_selectors (char * args, int from_tty)
  829. {
  830.   if (!current_thread)
  831.     {
  832.       puts_filtered ("Impossible to display selectors now.\n");
  833.       return;
  834.     }
  835.   if (!args)
  836.     {

  837.       puts_filtered ("Selector $cs\n");
  838.       display_selector (current_thread->h,
  839.         current_thread->context.SegCs);
  840.       puts_filtered ("Selector $ds\n");
  841.       display_selector (current_thread->h,
  842.         current_thread->context.SegDs);
  843.       puts_filtered ("Selector $es\n");
  844.       display_selector (current_thread->h,
  845.         current_thread->context.SegEs);
  846.       puts_filtered ("Selector $ss\n");
  847.       display_selector (current_thread->h,
  848.         current_thread->context.SegSs);
  849.       puts_filtered ("Selector $fs\n");
  850.       display_selector (current_thread->h,
  851.         current_thread->context.SegFs);
  852.       puts_filtered ("Selector $gs\n");
  853.       display_selector (current_thread->h,
  854.         current_thread->context.SegGs);
  855.     }
  856.   else
  857.     {
  858.       int sel;
  859.       sel = parse_and_eval_long (args);
  860.       printf_filtered ("Selector \"%s\"\n",args);
  861.       display_selector (current_thread->h, sel);
  862.     }
  863. }

  864. #define DEBUG_EXCEPTION_SIMPLE(x)       if (debug_exceptions) \
  865.   printf_unfiltered ("gdb: Target exception %s at %s\n", x, \
  866.     host_address_to_string (\
  867.       current_event.u.Exception.ExceptionRecord.ExceptionAddress))

  868. static int
  869. handle_exception (struct target_waitstatus *ourstatus)
  870. {
  871.   thread_info *th;
  872.   DWORD code = current_event.u.Exception.ExceptionRecord.ExceptionCode;

  873.   ourstatus->kind = TARGET_WAITKIND_STOPPED;

  874.   /* Record the context of the current thread.  */
  875.   th = thread_rec (current_event.dwThreadId, -1);

  876.   switch (code)
  877.     {
  878.     case EXCEPTION_ACCESS_VIOLATION:
  879.       DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ACCESS_VIOLATION");
  880.       ourstatus->value.sig = GDB_SIGNAL_SEGV;
  881. #ifdef __CYGWIN__
  882.       {
  883.         /* See if the access violation happened within the cygwin DLL
  884.            itself.  Cygwin uses a kind of exception handling to deal
  885.            with passed-in invalid addresses.  gdb should not treat
  886.            these as real SEGVs since they will be silently handled by
  887.            cygwin.  A real SEGV will (theoretically) be caught by
  888.            cygwin later in the process and will be sent as a
  889.            cygwin-specific-signal.  So, ignore SEGVs if they show up
  890.            within the text segment of the DLL itself.  */
  891.         const char *fn;
  892.         CORE_ADDR addr = (CORE_ADDR) (uintptr_t)
  893.           current_event.u.Exception.ExceptionRecord.ExceptionAddress;

  894.         if ((!cygwin_exceptions && (addr >= cygwin_load_start
  895.                                     && addr < cygwin_load_end))
  896.             || (find_pc_partial_function (addr, &fn, NULL, NULL)
  897.                 && strncmp (fn, "KERNEL32!IsBad",
  898.                             strlen ("KERNEL32!IsBad")) == 0))
  899.           return 0;
  900.       }
  901. #endif
  902.       break;
  903.     case STATUS_STACK_OVERFLOW:
  904.       DEBUG_EXCEPTION_SIMPLE ("STATUS_STACK_OVERFLOW");
  905.       ourstatus->value.sig = GDB_SIGNAL_SEGV;
  906.       break;
  907.     case STATUS_FLOAT_DENORMAL_OPERAND:
  908.       DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DENORMAL_OPERAND");
  909.       ourstatus->value.sig = GDB_SIGNAL_FPE;
  910.       break;
  911.     case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
  912.       DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ARRAY_BOUNDS_EXCEEDED");
  913.       ourstatus->value.sig = GDB_SIGNAL_FPE;
  914.       break;
  915.     case STATUS_FLOAT_INEXACT_RESULT:
  916.       DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INEXACT_RESULT");
  917.       ourstatus->value.sig = GDB_SIGNAL_FPE;
  918.       break;
  919.     case STATUS_FLOAT_INVALID_OPERATION:
  920.       DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INVALID_OPERATION");
  921.       ourstatus->value.sig = GDB_SIGNAL_FPE;
  922.       break;
  923.     case STATUS_FLOAT_OVERFLOW:
  924.       DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_OVERFLOW");
  925.       ourstatus->value.sig = GDB_SIGNAL_FPE;
  926.       break;
  927.     case STATUS_FLOAT_STACK_CHECK:
  928.       DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_STACK_CHECK");
  929.       ourstatus->value.sig = GDB_SIGNAL_FPE;
  930.       break;
  931.     case STATUS_FLOAT_UNDERFLOW:
  932.       DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_UNDERFLOW");
  933.       ourstatus->value.sig = GDB_SIGNAL_FPE;
  934.       break;
  935.     case STATUS_FLOAT_DIVIDE_BY_ZERO:
  936.       DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DIVIDE_BY_ZERO");
  937.       ourstatus->value.sig = GDB_SIGNAL_FPE;
  938.       break;
  939.     case STATUS_INTEGER_DIVIDE_BY_ZERO:
  940.       DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_DIVIDE_BY_ZERO");
  941.       ourstatus->value.sig = GDB_SIGNAL_FPE;
  942.       break;
  943.     case STATUS_INTEGER_OVERFLOW:
  944.       DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_OVERFLOW");
  945.       ourstatus->value.sig = GDB_SIGNAL_FPE;
  946.       break;
  947.     case EXCEPTION_BREAKPOINT:
  948.       DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_BREAKPOINT");
  949.       ourstatus->value.sig = GDB_SIGNAL_TRAP;
  950.       break;
  951.     case DBG_CONTROL_C:
  952.       DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_C");
  953.       ourstatus->value.sig = GDB_SIGNAL_INT;
  954.       break;
  955.     case DBG_CONTROL_BREAK:
  956.       DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_BREAK");
  957.       ourstatus->value.sig = GDB_SIGNAL_INT;
  958.       break;
  959.     case EXCEPTION_SINGLE_STEP:
  960.       DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_SINGLE_STEP");
  961.       ourstatus->value.sig = GDB_SIGNAL_TRAP;
  962.       break;
  963.     case EXCEPTION_ILLEGAL_INSTRUCTION:
  964.       DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ILLEGAL_INSTRUCTION");
  965.       ourstatus->value.sig = GDB_SIGNAL_ILL;
  966.       break;
  967.     case EXCEPTION_PRIV_INSTRUCTION:
  968.       DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_PRIV_INSTRUCTION");
  969.       ourstatus->value.sig = GDB_SIGNAL_ILL;
  970.       break;
  971.     case EXCEPTION_NONCONTINUABLE_EXCEPTION:
  972.       DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_NONCONTINUABLE_EXCEPTION");
  973.       ourstatus->value.sig = GDB_SIGNAL_ILL;
  974.       break;
  975.     default:
  976.       /* Treat unhandled first chance exceptions specially.  */
  977.       if (current_event.u.Exception.dwFirstChance)
  978.         return -1;
  979.       printf_unfiltered ("gdb: unknown target exception 0x%08x at %s\n",
  980.         (unsigned) current_event.u.Exception.ExceptionRecord.ExceptionCode,
  981.         host_address_to_string (
  982.           current_event.u.Exception.ExceptionRecord.ExceptionAddress));
  983.       ourstatus->value.sig = GDB_SIGNAL_UNKNOWN;
  984.       break;
  985.     }
  986.   exception_count++;
  987.   last_sig = ourstatus->value.sig;
  988.   return 1;
  989. }

  990. /* Resume thread specified by ID, or all artificially suspended
  991.    threads, if we are continuing execution.  KILLED non-zero means we
  992.    have killed the inferior, so we should ignore weird errors due to
  993.    threads shutting down.  */
  994. static BOOL
  995. windows_continue (DWORD continue_status, int id, int killed)
  996. {
  997.   int i;
  998.   thread_info *th;
  999.   BOOL res;

  1000.   DEBUG_EVENTS (("ContinueDebugEvent (cpid=%d, ctid=0x%x, %s);\n",
  1001.                   (unsigned) current_event.dwProcessId,
  1002.                   (unsigned) current_event.dwThreadId,
  1003.                   continue_status == DBG_CONTINUE ?
  1004.                   "DBG_CONTINUE" : "DBG_EXCEPTION_NOT_HANDLED"));

  1005.   for (th = &thread_head; (th = th->next) != NULL;)
  1006.     if ((id == -1 || id == (int) th->id)
  1007.         && th->suspended)
  1008.       {
  1009.         if (debug_registers_changed)
  1010.           {
  1011.             th->context.ContextFlags |= CONTEXT_DEBUG_REGISTERS;
  1012.             th->context.Dr0 = dr[0];
  1013.             th->context.Dr1 = dr[1];
  1014.             th->context.Dr2 = dr[2];
  1015.             th->context.Dr3 = dr[3];
  1016.             th->context.Dr6 = DR6_CLEAR_VALUE;
  1017.             th->context.Dr7 = dr[7];
  1018.           }
  1019.         if (th->context.ContextFlags)
  1020.           {
  1021.             DWORD ec = 0;

  1022.             if (GetExitCodeThread (th->h, &ec)
  1023.                 && ec == STILL_ACTIVE)
  1024.               {
  1025.                 BOOL status = SetThreadContext (th->h, &th->context);

  1026.                 if (!killed)
  1027.                   CHECK (status);
  1028.               }
  1029.             th->context.ContextFlags = 0;
  1030.           }
  1031.         if (th->suspended > 0)
  1032.           (void) ResumeThread (th->h);
  1033.         th->suspended = 0;
  1034.       }

  1035.   res = ContinueDebugEvent (current_event.dwProcessId,
  1036.                             current_event.dwThreadId,
  1037.                             continue_status);

  1038.   debug_registers_changed = 0;
  1039.   return res;
  1040. }

  1041. /* Called in pathological case where Windows fails to send a
  1042.    CREATE_PROCESS_DEBUG_EVENT after an attach.  */
  1043. static DWORD
  1044. fake_create_process (void)
  1045. {
  1046.   current_process_handle = OpenProcess (PROCESS_ALL_ACCESS, FALSE,
  1047.                                         current_event.dwProcessId);
  1048.   if (current_process_handle != NULL)
  1049.     open_process_used = 1;
  1050.   else
  1051.     {
  1052.       error (_("OpenProcess call failed, GetLastError = %u"),
  1053.        (unsigned) GetLastError ());
  1054.       /*  We can not debug anything in that case.  */
  1055.     }
  1056.   main_thread_id = current_event.dwThreadId;
  1057.   current_thread = windows_add_thread (
  1058.                      ptid_build (current_event.dwProcessId, 0,
  1059.                                  current_event.dwThreadId),
  1060.                      current_event.u.CreateThread.hThread,
  1061.                      current_event.u.CreateThread.lpThreadLocalBase);
  1062.   return main_thread_id;
  1063. }

  1064. static void
  1065. windows_resume (struct target_ops *ops,
  1066.                 ptid_t ptid, int step, enum gdb_signal sig)
  1067. {
  1068.   thread_info *th;
  1069.   DWORD continue_status = DBG_CONTINUE;

  1070.   /* A specific PTID means `step only this thread id'.  */
  1071.   int resume_all = ptid_equal (ptid, minus_one_ptid);

  1072.   /* If we're continuing all threads, it's the current inferior that
  1073.      should be handled specially.  */
  1074.   if (resume_all)
  1075.     ptid = inferior_ptid;

  1076.   if (sig != GDB_SIGNAL_0)
  1077.     {
  1078.       if (current_event.dwDebugEventCode != EXCEPTION_DEBUG_EVENT)
  1079.         {
  1080.           DEBUG_EXCEPT(("Cannot continue with signal %d here.\n",sig));
  1081.         }
  1082.       else if (sig == last_sig)
  1083.         continue_status = DBG_EXCEPTION_NOT_HANDLED;
  1084.       else
  1085. #if 0
  1086. /* This code does not seem to work, because
  1087.   the kernel does probably not consider changes in the ExceptionRecord
  1088.   structure when passing the exception to the inferior.
  1089.   Note that this seems possible in the exception handler itself.  */
  1090.         {
  1091.           int i;
  1092.           for (i = 0; xlate[i].them != -1; i++)
  1093.             if (xlate[i].us == sig)
  1094.               {
  1095.                 current_event.u.Exception.ExceptionRecord.ExceptionCode
  1096.                   = xlate[i].them;
  1097.                 continue_status = DBG_EXCEPTION_NOT_HANDLED;
  1098.                 break;
  1099.               }
  1100.           if (continue_status == DBG_CONTINUE)
  1101.             {
  1102.               DEBUG_EXCEPT(("Cannot continue with signal %d.\n",sig));
  1103.             }
  1104.         }
  1105. #endif
  1106.         DEBUG_EXCEPT(("Can only continue with recieved signal %d.\n",
  1107.           last_sig));
  1108.     }

  1109.   last_sig = GDB_SIGNAL_0;

  1110.   DEBUG_EXEC (("gdb: windows_resume (pid=%d, tid=%ld, step=%d, sig=%d);\n",
  1111.                ptid_get_pid (ptid), ptid_get_tid (ptid), step, sig));

  1112.   /* Get context for currently selected thread.  */
  1113.   th = thread_rec (ptid_get_tid (inferior_ptid), FALSE);
  1114.   if (th)
  1115.     {
  1116.       if (step)
  1117.         {
  1118.           /* Single step by setting t bit.  */
  1119.           struct regcache *regcache = get_current_regcache ();
  1120.           struct gdbarch *gdbarch = get_regcache_arch (regcache);
  1121.           windows_fetch_inferior_registers (ops, regcache,
  1122.                                             gdbarch_ps_regnum (gdbarch));
  1123.           th->context.EFlags |= FLAG_TRACE_BIT;
  1124.         }

  1125.       if (th->context.ContextFlags)
  1126.         {
  1127.           if (debug_registers_changed)
  1128.             {
  1129.               th->context.Dr0 = dr[0];
  1130.               th->context.Dr1 = dr[1];
  1131.               th->context.Dr2 = dr[2];
  1132.               th->context.Dr3 = dr[3];
  1133.               th->context.Dr6 = DR6_CLEAR_VALUE;
  1134.               th->context.Dr7 = dr[7];
  1135.             }
  1136.           CHECK (SetThreadContext (th->h, &th->context));
  1137.           th->context.ContextFlags = 0;
  1138.         }
  1139.     }

  1140.   /* Allow continuing with the same signal that interrupted us.
  1141.      Otherwise complain.  */

  1142.   if (resume_all)
  1143.     windows_continue (continue_status, -1, 0);
  1144.   else
  1145.     windows_continue (continue_status, ptid_get_tid (ptid), 0);
  1146. }

  1147. /* Ctrl-C handler used when the inferior is not run in the same console.  The
  1148.    handler is in charge of interrupting the inferior using DebugBreakProcess.
  1149.    Note that this function is not available prior to Windows XP.  In this case
  1150.    we emit a warning.  */
  1151. static BOOL WINAPI
  1152. ctrl_c_handler (DWORD event_type)
  1153. {
  1154.   const int attach_flag = current_inferior ()->attach_flag;

  1155.   /* Only handle Ctrl-C and Ctrl-Break events.  Ignore others.  */
  1156.   if (event_type != CTRL_C_EVENT && event_type != CTRL_BREAK_EVENT)
  1157.     return FALSE;

  1158.   /* If the inferior and the debugger share the same console, do nothing as
  1159.      the inferior has also received the Ctrl-C event.  */
  1160.   if (!new_console && !attach_flag)
  1161.     return TRUE;

  1162.   if (!DebugBreakProcess (current_process_handle))
  1163.     warning (_("Could not interrupt program.  "
  1164.                "Press Ctrl-c in the program console."));

  1165.   /* Return true to tell that Ctrl-C has been handled.  */
  1166.   return TRUE;
  1167. }

  1168. /* Get the next event from the child.  Return 1 if the event requires
  1169.    handling by WFI (or whatever).  */
  1170. static int
  1171. get_windows_debug_event (struct target_ops *ops,
  1172.                          int pid, struct target_waitstatus *ourstatus)
  1173. {
  1174.   BOOL debug_event;
  1175.   DWORD continue_status, event_code;
  1176.   thread_info *th;
  1177.   static thread_info dummy_thread_info;
  1178.   int retval = 0;

  1179.   last_sig = GDB_SIGNAL_0;

  1180.   if (!(debug_event = WaitForDebugEvent (&current_event, 1000)))
  1181.     goto out;

  1182.   event_count++;
  1183.   continue_status = DBG_CONTINUE;

  1184.   event_code = current_event.dwDebugEventCode;
  1185.   ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
  1186.   th = NULL;
  1187.   have_saved_context = 0;

  1188.   switch (event_code)
  1189.     {
  1190.     case CREATE_THREAD_DEBUG_EVENT:
  1191.       DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
  1192.                      (unsigned) current_event.dwProcessId,
  1193.                      (unsigned) current_event.dwThreadId,
  1194.                      "CREATE_THREAD_DEBUG_EVENT"));
  1195.       if (saw_create != 1)
  1196.         {
  1197.           struct inferior *inf;
  1198.           inf = find_inferior_pid (current_event.dwProcessId);
  1199.           if (!saw_create && inf->attach_flag)
  1200.             {
  1201.               /* Kludge around a Windows bug where first event is a create
  1202.                  thread event.  Caused when attached process does not have
  1203.                  a main thread.  */
  1204.               retval = fake_create_process ();
  1205.               if (retval)
  1206.                 saw_create++;
  1207.             }
  1208.           break;
  1209.         }
  1210.       /* Record the existence of this thread.  */
  1211.       retval = current_event.dwThreadId;
  1212.       th = windows_add_thread (ptid_build (current_event.dwProcessId, 0,
  1213.                                          current_event.dwThreadId),
  1214.                              current_event.u.CreateThread.hThread,
  1215.                              current_event.u.CreateThread.lpThreadLocalBase);

  1216.       break;

  1217.     case EXIT_THREAD_DEBUG_EVENT:
  1218.       DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
  1219.                      (unsigned) current_event.dwProcessId,
  1220.                      (unsigned) current_event.dwThreadId,
  1221.                      "EXIT_THREAD_DEBUG_EVENT"));

  1222.       if (current_event.dwThreadId != main_thread_id)
  1223.         {
  1224.           windows_delete_thread (ptid_build (current_event.dwProcessId, 0,
  1225.                                              current_event.dwThreadId),
  1226.                                  current_event.u.ExitThread.dwExitCode);
  1227.           th = &dummy_thread_info;
  1228.         }
  1229.       break;

  1230.     case CREATE_PROCESS_DEBUG_EVENT:
  1231.       DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
  1232.                      (unsigned) current_event.dwProcessId,
  1233.                      (unsigned) current_event.dwThreadId,
  1234.                      "CREATE_PROCESS_DEBUG_EVENT"));
  1235.       CloseHandle (current_event.u.CreateProcessInfo.hFile);
  1236.       if (++saw_create != 1)
  1237.         break;

  1238.       current_process_handle = current_event.u.CreateProcessInfo.hProcess;
  1239.       if (main_thread_id)
  1240.         windows_delete_thread (ptid_build (current_event.dwProcessId, 0,
  1241.                                            main_thread_id),
  1242.                                0);
  1243.       main_thread_id = current_event.dwThreadId;
  1244.       /* Add the main thread.  */
  1245.       th = windows_add_thread (ptid_build (current_event.dwProcessId, 0,
  1246.                                            current_event.dwThreadId),
  1247.              current_event.u.CreateProcessInfo.hThread,
  1248.              current_event.u.CreateProcessInfo.lpThreadLocalBase);
  1249.       retval = current_event.dwThreadId;
  1250.       break;

  1251.     case EXIT_PROCESS_DEBUG_EVENT:
  1252.       DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
  1253.                      (unsigned) current_event.dwProcessId,
  1254.                      (unsigned) current_event.dwThreadId,
  1255.                      "EXIT_PROCESS_DEBUG_EVENT"));
  1256.       if (!windows_initialization_done)
  1257.         {
  1258.           target_terminal_ours ();
  1259.           target_mourn_inferior ();
  1260.           error (_("During startup program exited with code 0x%x."),
  1261.                  (unsigned int) current_event.u.ExitProcess.dwExitCode);
  1262.         }
  1263.       else if (saw_create == 1)
  1264.         {
  1265.           ourstatus->kind = TARGET_WAITKIND_EXITED;
  1266.           ourstatus->value.integer = current_event.u.ExitProcess.dwExitCode;
  1267.           retval = main_thread_id;
  1268.         }
  1269.       break;

  1270.     case LOAD_DLL_DEBUG_EVENT:
  1271.       DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
  1272.                      (unsigned) current_event.dwProcessId,
  1273.                      (unsigned) current_event.dwThreadId,
  1274.                      "LOAD_DLL_DEBUG_EVENT"));
  1275.       CloseHandle (current_event.u.LoadDll.hFile);
  1276.       if (saw_create != 1 || ! windows_initialization_done)
  1277.         break;
  1278.       catch_errors (handle_load_dll, NULL, (char *) "", RETURN_MASK_ALL);
  1279.       ourstatus->kind = TARGET_WAITKIND_LOADED;
  1280.       ourstatus->value.integer = 0;
  1281.       retval = main_thread_id;
  1282.       break;

  1283.     case UNLOAD_DLL_DEBUG_EVENT:
  1284.       DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
  1285.                      (unsigned) current_event.dwProcessId,
  1286.                      (unsigned) current_event.dwThreadId,
  1287.                      "UNLOAD_DLL_DEBUG_EVENT"));
  1288.       if (saw_create != 1 || ! windows_initialization_done)
  1289.         break;
  1290.       catch_errors (handle_unload_dll, NULL, (char *) "", RETURN_MASK_ALL);
  1291.       ourstatus->kind = TARGET_WAITKIND_LOADED;
  1292.       ourstatus->value.integer = 0;
  1293.       retval = main_thread_id;
  1294.       break;

  1295.     case EXCEPTION_DEBUG_EVENT:
  1296.       DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
  1297.                      (unsigned) current_event.dwProcessId,
  1298.                      (unsigned) current_event.dwThreadId,
  1299.                      "EXCEPTION_DEBUG_EVENT"));
  1300.       if (saw_create != 1)
  1301.         break;
  1302.       switch (handle_exception (ourstatus))
  1303.         {
  1304.         case 0:
  1305.           continue_status = DBG_EXCEPTION_NOT_HANDLED;
  1306.           break;
  1307.         case 1:
  1308.           retval = current_event.dwThreadId;
  1309.           break;
  1310.         case -1:
  1311.           last_sig = 1;
  1312.           continue_status = -1;
  1313.           break;
  1314.         }
  1315.       break;

  1316.     case OUTPUT_DEBUG_STRING_EVENT:        /* Message from the kernel.  */
  1317.       DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
  1318.                      (unsigned) current_event.dwProcessId,
  1319.                      (unsigned) current_event.dwThreadId,
  1320.                      "OUTPUT_DEBUG_STRING_EVENT"));
  1321.       if (saw_create != 1)
  1322.         break;
  1323.       retval = handle_output_debug_string (ourstatus);
  1324.       break;

  1325.     default:
  1326.       if (saw_create != 1)
  1327.         break;
  1328.       printf_unfiltered ("gdb: kernel event for pid=%u tid=0x%x\n",
  1329.                          (unsigned) current_event.dwProcessId,
  1330.                          (unsigned) current_event.dwThreadId);
  1331.       printf_unfiltered ("                 unknown event code %u\n",
  1332.                          (unsigned) current_event.dwDebugEventCode);
  1333.       break;
  1334.     }

  1335.   if (!retval || saw_create != 1)
  1336.     {
  1337.       if (continue_status == -1)
  1338.         windows_resume (ops, minus_one_ptid, 0, 1);
  1339.       else
  1340.         CHECK (windows_continue (continue_status, -1, 0));
  1341.     }
  1342.   else
  1343.     {
  1344.       inferior_ptid = ptid_build (current_event.dwProcessId, 0,
  1345.                                   retval);
  1346.       current_thread = th ?: thread_rec (current_event.dwThreadId, TRUE);
  1347.     }

  1348. out:
  1349.   return retval;
  1350. }

  1351. /* Wait for interesting events to occur in the target process.  */
  1352. static ptid_t
  1353. windows_wait (struct target_ops *ops,
  1354.               ptid_t ptid, struct target_waitstatus *ourstatus, int options)
  1355. {
  1356.   int pid = -1;

  1357.   target_terminal_ours ();

  1358.   /* We loop when we get a non-standard exception rather than return
  1359.      with a SPURIOUS because resume can try and step or modify things,
  1360.      which needs a current_thread->h.  But some of these exceptions mark
  1361.      the birth or death of threads, which mean that the current thread
  1362.      isn't necessarily what you think it is.  */

  1363.   while (1)
  1364.     {
  1365.       int retval;

  1366.       /* If the user presses Ctrl-c while the debugger is waiting
  1367.          for an event, he expects the debugger to interrupt his program
  1368.          and to get the prompt back.  There are two possible situations:

  1369.            - The debugger and the program do not share the console, in
  1370.              which case the Ctrl-c event only reached the debugger.
  1371.              In that case, the ctrl_c handler will take care of interrupting
  1372.              the inferior.  Note that this case is working starting with
  1373.              Windows XP.  For Windows 2000, Ctrl-C should be pressed in the
  1374.              inferior console.

  1375.            - The debugger and the program share the same console, in which
  1376.              case both debugger and inferior will receive the Ctrl-c event.
  1377.              In that case the ctrl_c handler will ignore the event, as the
  1378.              Ctrl-c event generated inside the inferior will trigger the
  1379.              expected debug event.

  1380.              FIXME: brobecker/2008-05-20: If the inferior receives the
  1381.              signal first and the delay until GDB receives that signal
  1382.              is sufficiently long, GDB can sometimes receive the SIGINT
  1383.              after we have unblocked the CTRL+C handler.  This would
  1384.              lead to the debugger stopping prematurely while handling
  1385.              the new-thread event that comes with the handling of the SIGINT
  1386.              inside the inferior, and then stop again immediately when
  1387.              the user tries to resume the execution in the inferior.
  1388.              This is a classic race that we should try to fix one day.  */
  1389.       SetConsoleCtrlHandler (&ctrl_c_handler, TRUE);
  1390.       retval = get_windows_debug_event (ops, pid, ourstatus);
  1391.       SetConsoleCtrlHandler (&ctrl_c_handler, FALSE);

  1392.       if (retval)
  1393.         return ptid_build (current_event.dwProcessId, 0, retval);
  1394.       else
  1395.         {
  1396.           int detach = 0;

  1397.           if (deprecated_ui_loop_hook != NULL)
  1398.             detach = deprecated_ui_loop_hook (0);

  1399.           if (detach)
  1400.             windows_kill_inferior (ops);
  1401.         }
  1402.     }
  1403. }

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

  1406. static void
  1407. windows_add_all_dlls (void)
  1408. {
  1409.   struct so_list *so;
  1410.   HMODULE dummy_hmodule;
  1411.   DWORD cb_needed;
  1412.   HMODULE *hmodules;
  1413.   int i;

  1414.   if (EnumProcessModules (current_process_handle, &dummy_hmodule,
  1415.                           sizeof (HMODULE), &cb_needed) == 0)
  1416.     return;

  1417.   if (cb_needed < 1)
  1418.     return;

  1419.   hmodules = (HMODULE *) alloca (cb_needed);
  1420.   if (EnumProcessModules (current_process_handle, hmodules,
  1421.                           cb_needed, &cb_needed) == 0)
  1422.     return;

  1423.   for (i = 1; i < (int) (cb_needed / sizeof (HMODULE)); i++)
  1424.     {
  1425.       MODULEINFO mi;
  1426. #ifdef __USEWIDE
  1427.       wchar_t dll_name[__PMAX];
  1428.       char name[__PMAX];
  1429. #else
  1430.       char dll_name[__PMAX];
  1431.       char *name;
  1432. #endif
  1433.       if (GetModuleInformation (current_process_handle, hmodules[i],
  1434.                                 &mi, sizeof (mi)) == 0)
  1435.         continue;
  1436.       if (GetModuleFileNameEx (current_process_handle, hmodules[i],
  1437.                                dll_name, sizeof (dll_name)) == 0)
  1438.         continue;
  1439. #ifdef __USEWIDE
  1440.       wcstombs (name, dll_name, __PMAX);
  1441. #else
  1442.       name = dll_name;
  1443. #endif

  1444.       solib_end->next = windows_make_so (name, mi.lpBaseOfDll);
  1445.       solib_end = solib_end->next;
  1446.     }
  1447. }

  1448. static void
  1449. do_initial_windows_stuff (struct target_ops *ops, DWORD pid, int attaching)
  1450. {
  1451.   extern int stop_after_trap;
  1452.   int i;
  1453.   struct inferior *inf;
  1454.   struct thread_info *tp;

  1455.   last_sig = GDB_SIGNAL_0;
  1456.   event_count = 0;
  1457.   exception_count = 0;
  1458.   open_process_used = 0;
  1459.   debug_registers_changed = 0;
  1460.   debug_registers_used = 0;
  1461.   for (i = 0; i < sizeof (dr) / sizeof (dr[0]); i++)
  1462.     dr[i] = 0;
  1463. #ifdef __CYGWIN__
  1464.   cygwin_load_start = cygwin_load_end = 0;
  1465. #endif
  1466.   current_event.dwProcessId = pid;
  1467.   memset (&current_event, 0, sizeof (current_event));
  1468.   if (!target_is_pushed (ops))
  1469.     push_target (ops);
  1470.   disable_breakpoints_in_shlibs ();
  1471.   windows_clear_solib ();
  1472.   clear_proceed_status (0);
  1473.   init_wait_for_inferior ();

  1474.   inf = current_inferior ();
  1475.   inferior_appeared (inf, pid);
  1476.   inf->attach_flag = attaching;

  1477.   /* Make the new process the current inferior, so terminal handling
  1478.      can rely on it.  When attaching, we don't know about any thread
  1479.      id here, but that's OK --- nothing should be referencing the
  1480.      current thread until we report an event out of windows_wait.  */
  1481.   inferior_ptid = pid_to_ptid (pid);

  1482.   target_terminal_init ();
  1483.   target_terminal_inferior ();

  1484.   windows_initialization_done = 0;
  1485.   inf->control.stop_soon = STOP_QUIETLY;
  1486.   while (1)
  1487.     {
  1488.       stop_after_trap = 1;
  1489.       wait_for_inferior ();
  1490.       tp = inferior_thread ();
  1491.       if (tp->suspend.stop_signal != GDB_SIGNAL_TRAP)
  1492.         resume (0, tp->suspend.stop_signal);
  1493.       else
  1494.         break;
  1495.     }

  1496.   /* Now that the inferior has been started and all DLLs have been mapped,
  1497.      we can iterate over all DLLs and load them in.

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

  1506.      Rather than try to work around this sort of issue, it is much
  1507.      simpler to just ignore DLL load/unload events during the startup
  1508.      phase, and then process them all in one batch now.  */
  1509.   windows_add_all_dlls ();

  1510.   windows_initialization_done = 1;
  1511.   inf->control.stop_soon = NO_STOP_QUIETLY;
  1512.   stop_after_trap = 0;
  1513.   return;
  1514. }

  1515. /* Try to set or remove a user privilege to the current process.  Return -1
  1516.    if that fails, the previous setting of that privilege otherwise.

  1517.    This code is copied from the Cygwin source code and rearranged to allow
  1518.    dynamically loading of the needed symbols from advapi32 which is only
  1519.    available on NT/2K/XP.  */
  1520. static int
  1521. set_process_privilege (const char *privilege, BOOL enable)
  1522. {
  1523.   HANDLE token_hdl = NULL;
  1524.   LUID restore_priv;
  1525.   TOKEN_PRIVILEGES new_priv, orig_priv;
  1526.   int ret = -1;
  1527.   DWORD size;

  1528.   if (!OpenProcessToken (GetCurrentProcess (),
  1529.                          TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
  1530.                          &token_hdl))
  1531.     goto out;

  1532.   if (!LookupPrivilegeValueA (NULL, privilege, &restore_priv))
  1533.     goto out;

  1534.   new_priv.PrivilegeCount = 1;
  1535.   new_priv.Privileges[0].Luid = restore_priv;
  1536.   new_priv.Privileges[0].Attributes = enable ? SE_PRIVILEGE_ENABLED : 0;

  1537.   if (!AdjustTokenPrivileges (token_hdl, FALSE, &new_priv,
  1538.                               sizeof orig_priv, &orig_priv, &size))
  1539.     goto out;
  1540. #if 0
  1541.   /* Disabled, otherwise every `attach' in an unprivileged user session
  1542.      would raise the "Failed to get SE_DEBUG_NAME privilege" warning in
  1543.      windows_attach().  */
  1544.   /* AdjustTokenPrivileges returns TRUE even if the privilege could not
  1545.      be enabled.  GetLastError () returns an correct error code, though.  */
  1546.   if (enable && GetLastError () == ERROR_NOT_ALL_ASSIGNED)
  1547.     goto out;
  1548. #endif

  1549.   ret = orig_priv.Privileges[0].Attributes == SE_PRIVILEGE_ENABLED ? 1 : 0;

  1550. out:
  1551.   if (token_hdl)
  1552.     CloseHandle (token_hdl);

  1553.   return ret;
  1554. }

  1555. /* Attach to process PID, then initialize for debugging it.  */
  1556. static void
  1557. windows_attach (struct target_ops *ops, const char *args, int from_tty)
  1558. {
  1559.   BOOL ok;
  1560.   DWORD pid;

  1561.   pid = parse_pid_to_attach (args);

  1562.   if (set_process_privilege (SE_DEBUG_NAME, TRUE) < 0)
  1563.     {
  1564.       printf_unfiltered ("Warning: Failed to get SE_DEBUG_NAME privilege\n");
  1565.       printf_unfiltered ("This can cause attach to "
  1566.                          "fail on Windows NT/2K/XP\n");
  1567.     }

  1568.   windows_init_thread_list ();
  1569.   ok = DebugActiveProcess (pid);
  1570.   saw_create = 0;

  1571. #ifdef __CYGWIN__
  1572.   if (!ok)
  1573.     {
  1574.       /* Try fall back to Cygwin pid.  */
  1575.       pid = cygwin_internal (CW_CYGWIN_PID_TO_WINPID, pid);

  1576.       if (pid > 0)
  1577.         ok = DebugActiveProcess (pid);
  1578.   }
  1579. #endif

  1580.   if (!ok)
  1581.     error (_("Can't attach to process."));

  1582.   DebugSetProcessKillOnExit (FALSE);

  1583.   if (from_tty)
  1584.     {
  1585.       char *exec_file = (char *) get_exec_file (0);

  1586.       if (exec_file)
  1587.         printf_unfiltered ("Attaching to program `%s', %s\n", exec_file,
  1588.                            target_pid_to_str (pid_to_ptid (pid)));
  1589.       else
  1590.         printf_unfiltered ("Attaching to %s\n",
  1591.                            target_pid_to_str (pid_to_ptid (pid)));

  1592.       gdb_flush (gdb_stdout);
  1593.     }

  1594.   do_initial_windows_stuff (ops, pid, 1);
  1595.   target_terminal_ours ();
  1596. }

  1597. static void
  1598. windows_detach (struct target_ops *ops, const char *args, int from_tty)
  1599. {
  1600.   int detached = 1;

  1601.   ptid_t ptid = {-1};
  1602.   windows_resume (ops, ptid, 0, GDB_SIGNAL_0);

  1603.   if (!DebugActiveProcessStop (current_event.dwProcessId))
  1604.     {
  1605.       error (_("Can't detach process %u (error %u)"),
  1606.              (unsigned) current_event.dwProcessId, (unsigned) GetLastError ());
  1607.       detached = 0;
  1608.     }
  1609.   DebugSetProcessKillOnExit (FALSE);

  1610.   if (detached && from_tty)
  1611.     {
  1612.       char *exec_file = get_exec_file (0);
  1613.       if (exec_file == 0)
  1614.         exec_file = "";
  1615.       printf_unfiltered ("Detaching from program: %s, Pid %u\n", exec_file,
  1616.                          (unsigned) current_event.dwProcessId);
  1617.       gdb_flush (gdb_stdout);
  1618.     }

  1619.   x86_cleanup_dregs ();
  1620.   inferior_ptid = null_ptid;
  1621.   detach_inferior (current_event.dwProcessId);

  1622.   inf_child_maybe_unpush_target (ops);
  1623. }

  1624. /* Try to determine the executable filename.

  1625.    EXE_NAME_RET is a pointer to a buffer whose size is EXE_NAME_MAX_LEN.

  1626.    Upon success, the filename is stored inside EXE_NAME_RET, and
  1627.    this function returns nonzero.

  1628.    Otherwise, this function returns zero and the contents of
  1629.    EXE_NAME_RET is undefined.  */

  1630. static int
  1631. windows_get_exec_module_filename (char *exe_name_ret, size_t exe_name_max_len)
  1632. {
  1633.   DWORD len;
  1634.   HMODULE dh_buf;
  1635.   DWORD cbNeeded;

  1636.   cbNeeded = 0;
  1637.   if (!EnumProcessModules (current_process_handle, &dh_buf,
  1638.                            sizeof (HMODULE), &cbNeeded) || !cbNeeded)
  1639.     return 0;

  1640.   /* We know the executable is always first in the list of modules,
  1641.      which we just fetched.  So no need to fetch more.  */

  1642. #ifdef __CYGWIN__
  1643.   {
  1644.     /* Cygwin prefers that the path be in /x/y/z format, so extract
  1645.        the filename into a temporary buffer first, and then convert it
  1646.        to POSIX format into the destination buffer.  */
  1647.     cygwin_buf_t *pathbuf = alloca (exe_name_max_len * sizeof (cygwin_buf_t));

  1648.     len = GetModuleFileNameEx (current_process_handle,
  1649.                                dh_buf, pathbuf, exe_name_max_len);
  1650.     if (len == 0)
  1651.       error (_("Error getting executable filename: %u."),
  1652.              (unsigned) GetLastError ());
  1653.     if (cygwin_conv_path (CCP_WIN_W_TO_POSIX, pathbuf, exe_name_ret,
  1654.                           exe_name_max_len) < 0)
  1655.       error (_("Error converting executable filename to POSIX: %d."), errno);
  1656.   }
  1657. #else
  1658.   len = GetModuleFileNameEx (current_process_handle,
  1659.                              dh_buf, exe_name_ret, exe_name_max_len);
  1660.   if (len == 0)
  1661.     error (_("Error getting executable filename: %u."),
  1662.            (unsigned) GetLastError ());
  1663. #endif

  1664.     return 1;        /* success */
  1665. }

  1666. /* The pid_to_exec_file target_ops method for this platform.  */

  1667. static char *
  1668. windows_pid_to_exec_file (struct target_ops *self, int pid)
  1669. {
  1670.   static char path[__PMAX];
  1671. #ifdef __CYGWIN__
  1672.   /* Try to find exe name as symlink target of /proc/<pid>/exe.  */
  1673.   int nchars;
  1674.   char procexe[sizeof ("/proc/4294967295/exe")];

  1675.   xsnprintf (procexe, sizeof (procexe), "/proc/%u/exe", pid);
  1676.   nchars = readlink (procexe, path, sizeof(path));
  1677.   if (nchars > 0 && nchars < sizeof (path))
  1678.     {
  1679.       path[nchars] = '\0';        /* Got it */
  1680.       return path;
  1681.     }
  1682. #endif

  1683.   /* If we get here then either Cygwin is hosed, this isn't a Cygwin version
  1684.      of gdb, or we're trying to debug a non-Cygwin windows executable.  */
  1685.   if (!windows_get_exec_module_filename (path, sizeof (path)))
  1686.     path[0] = '\0';

  1687.   return path;
  1688. }

  1689. /* Print status information about what we're accessing.  */

  1690. static void
  1691. windows_files_info (struct target_ops *ignore)
  1692. {
  1693.   struct inferior *inf = current_inferior ();

  1694.   printf_unfiltered ("\tUsing the running image of %s %s.\n",
  1695.                      inf->attach_flag ? "attached" : "child",
  1696.                      target_pid_to_str (inferior_ptid));
  1697. }

  1698. /* Modify CreateProcess parameters for use of a new separate console.
  1699.    Parameters are:
  1700.    *FLAGS: DWORD parameter for general process creation flags.
  1701.    *SI: STARTUPINFO structure, for which the console window size and
  1702.    console buffer size is filled in if GDB is running in a console.
  1703.    to create the new console.
  1704.    The size of the used font is not available on all versions of
  1705.    Windows OS.  Furthermore, the current font might not be the default
  1706.    font, but this is still better than before.
  1707.    If the windows and buffer sizes are computed,
  1708.    SI->DWFLAGS is changed so that this information is used
  1709.    by CreateProcess function.  */

  1710. static void
  1711. windows_set_console_info (STARTUPINFO *si, DWORD *flags)
  1712. {
  1713.   HANDLE hconsole = CreateFile ("CONOUT$", GENERIC_READ | GENERIC_WRITE,
  1714.                                 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);

  1715.   if (hconsole != INVALID_HANDLE_VALUE)
  1716.     {
  1717.       CONSOLE_SCREEN_BUFFER_INFO sbinfo;
  1718.       COORD font_size;
  1719.       CONSOLE_FONT_INFO cfi;

  1720.       GetCurrentConsoleFont (hconsole, FALSE, &cfi);
  1721.       font_size = GetConsoleFontSize (hconsole, cfi.nFont);
  1722.       GetConsoleScreenBufferInfo(hconsole, &sbinfo);
  1723.       si->dwXSize = sbinfo.srWindow.Right - sbinfo.srWindow.Left + 1;
  1724.       si->dwYSize = sbinfo.srWindow.Bottom - sbinfo.srWindow.Top + 1;
  1725.       if (font_size.X)
  1726.         si->dwXSize *= font_size.X;
  1727.       else
  1728.         si->dwXSize *= 8;
  1729.       if (font_size.Y)
  1730.         si->dwYSize *= font_size.Y;
  1731.       else
  1732.         si->dwYSize *= 12;
  1733.       si->dwXCountChars = sbinfo.dwSize.X;
  1734.       si->dwYCountChars = sbinfo.dwSize.Y;
  1735.       si->dwFlags |= STARTF_USESIZE | STARTF_USECOUNTCHARS;
  1736.     }
  1737.   *flags |= CREATE_NEW_CONSOLE;
  1738. }

  1739. #ifndef __CYGWIN__
  1740. /* Function called by qsort to sort environment strings.  */

  1741. static int
  1742. envvar_cmp (const void *a, const void *b)
  1743. {
  1744.   const char **p = (const char **) a;
  1745.   const char **q = (const char **) b;
  1746.   return strcasecmp (*p, *q);
  1747. }
  1748. #endif

  1749. #ifdef __CYGWIN__
  1750. static void
  1751. clear_win32_environment (char **env)
  1752. {
  1753.   int i;
  1754.   size_t len;
  1755.   wchar_t *copy = NULL, *equalpos;

  1756.   for (i = 0; env[i] && *env[i]; i++)
  1757.     {
  1758.       len = mbstowcs (NULL, env[i], 0) + 1;
  1759.       copy = (wchar_t *) xrealloc (copy, len * sizeof (wchar_t));
  1760.       mbstowcs (copy, env[i], len);
  1761.       equalpos = wcschr (copy, L'=');
  1762.       if (equalpos)
  1763.         *equalpos = L'\0';
  1764.       SetEnvironmentVariableW (copy, NULL);
  1765.     }
  1766.   xfree (copy);
  1767. }
  1768. #endif

  1769. /* Start an inferior windows child process and sets inferior_ptid to its pid.
  1770.    EXEC_FILE is the file to run.
  1771.    ALLARGS is a string containing the arguments to the program.
  1772.    ENV is the environment vector to pass.  Errors reported with error().  */

  1773. static void
  1774. windows_create_inferior (struct target_ops *ops, char *exec_file,
  1775.                        char *allargs, char **in_env, int from_tty)
  1776. {
  1777.   STARTUPINFO si;
  1778. #ifdef __CYGWIN__
  1779.   cygwin_buf_t real_path[__PMAX];
  1780.   cygwin_buf_t shell[__PMAX]; /* Path to shell */
  1781.   const char *sh;
  1782.   cygwin_buf_t *toexec;
  1783.   cygwin_buf_t *cygallargs;
  1784.   cygwin_buf_t *args;
  1785.   char **old_env = NULL;
  1786.   PWCHAR w32_env;
  1787.   size_t len;
  1788.   int tty;
  1789.   int ostdin, ostdout, ostderr;
  1790. #else
  1791.   char real_path[__PMAX];
  1792.   char shell[__PMAX]; /* Path to shell */
  1793.   char *toexec;
  1794.   char *args;
  1795.   size_t args_len;
  1796.   HANDLE tty;
  1797.   char *w32env;
  1798.   char *temp;
  1799.   size_t envlen;
  1800.   int i;
  1801.   size_t envsize;
  1802.   char **env;
  1803. #endif
  1804.   PROCESS_INFORMATION pi;
  1805.   BOOL ret;
  1806.   DWORD flags = 0;
  1807.   const char *inferior_io_terminal = get_inferior_io_terminal ();

  1808.   if (!exec_file)
  1809.     error (_("No executable specified, use `target exec'."));

  1810.   memset (&si, 0, sizeof (si));
  1811.   si.cb = sizeof (si);

  1812.   if (new_group)
  1813.     flags |= CREATE_NEW_PROCESS_GROUP;

  1814.   if (new_console)
  1815.     windows_set_console_info (&si, &flags);

  1816. #ifdef __CYGWIN__
  1817.   if (!useshell)
  1818.     {
  1819.       flags |= DEBUG_ONLY_THIS_PROCESS;
  1820.       if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, exec_file, real_path,
  1821.                             __PMAX * sizeof (cygwin_buf_t)) < 0)
  1822.         error (_("Error starting executable: %d"), errno);
  1823.       toexec = real_path;
  1824. #ifdef __USEWIDE
  1825.       len = mbstowcs (NULL, allargs, 0) + 1;
  1826.       if (len == (size_t) -1)
  1827.         error (_("Error starting executable: %d"), errno);
  1828.       cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
  1829.       mbstowcs (cygallargs, allargs, len);
  1830. #else
  1831.       cygallargs = allargs;
  1832. #endif
  1833.     }
  1834.   else
  1835.     {
  1836.       sh = getenv ("SHELL");
  1837.       if (!sh)
  1838.         sh = "/bin/sh";
  1839.       if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, sh, shell, __PMAX) < 0)
  1840.               error (_("Error starting executable via shell: %d"), errno);
  1841. #ifdef __USEWIDE
  1842.       len = sizeof (L" -c 'exec  '") + mbstowcs (NULL, exec_file, 0)
  1843.             + mbstowcs (NULL, allargs, 0) + 2;
  1844.       cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
  1845.       swprintf (cygallargs, len, L" -c 'exec %s %s'", exec_file, allargs);
  1846. #else
  1847.       len = (sizeof (" -c 'exec  '") + strlen (exec_file)
  1848.              + strlen (allargs) + 2);
  1849.       cygallargs = (char *) alloca (len);
  1850.       xsnprintf (cygallargs, len, " -c 'exec %s %s'", exec_file, allargs);
  1851. #endif
  1852.       toexec = shell;
  1853.       flags |= DEBUG_PROCESS;
  1854.     }

  1855. #ifdef __USEWIDE
  1856.   args = (cygwin_buf_t *) alloca ((wcslen (toexec) + wcslen (cygallargs) + 2)
  1857.                                   * sizeof (wchar_t));
  1858.   wcscpy (args, toexec);
  1859.   wcscat (args, L" ");
  1860.   wcscat (args, cygallargs);
  1861. #else
  1862.   args = (cygwin_buf_t *) alloca (strlen (toexec) + strlen (cygallargs) + 2);
  1863.   strcpy (args, toexec);
  1864.   strcat (args, " ");
  1865.   strcat (args, cygallargs);
  1866. #endif

  1867. #ifdef CW_CVT_ENV_TO_WINENV
  1868.   /* First try to create a direct Win32 copy of the POSIX environment. */
  1869.   w32_env = (PWCHAR) cygwin_internal (CW_CVT_ENV_TO_WINENV, in_env);
  1870.   if (w32_env != (PWCHAR) -1)
  1871.     flags |= CREATE_UNICODE_ENVIRONMENT;
  1872.   else
  1873.     /* If that fails, fall back to old method tweaking GDB's environment. */
  1874. #endif
  1875.     {
  1876.       /* Reset all Win32 environment variables to avoid leftover on next run. */
  1877.       clear_win32_environment (environ);
  1878.       /* Prepare the environment vars for CreateProcess.  */
  1879.       old_env = environ;
  1880.       environ = in_env;
  1881.       cygwin_internal (CW_SYNC_WINENV);
  1882.       w32_env = NULL;
  1883.     }

  1884.   if (!inferior_io_terminal)
  1885.     tty = ostdin = ostdout = ostderr = -1;
  1886.   else
  1887.     {
  1888.       tty = open (inferior_io_terminal, O_RDWR | O_NOCTTY);
  1889.       if (tty < 0)
  1890.         {
  1891.           print_sys_errmsg (inferior_io_terminal, errno);
  1892.           ostdin = ostdout = ostderr = -1;
  1893.         }
  1894.       else
  1895.         {
  1896.           ostdin = dup (0);
  1897.           ostdout = dup (1);
  1898.           ostderr = dup (2);
  1899.           dup2 (tty, 0);
  1900.           dup2 (tty, 1);
  1901.           dup2 (tty, 2);
  1902.         }
  1903.     }

  1904.   windows_init_thread_list ();
  1905.   ret = CreateProcess (0,
  1906.                        args,        /* command line */
  1907.                        NULL,        /* Security */
  1908.                        NULL,        /* thread */
  1909.                        TRUE,        /* inherit handles */
  1910.                        flags,        /* start flags */
  1911.                        w32_env,        /* environment */
  1912.                        NULL,        /* current directory */
  1913.                        &si,
  1914.                        &pi);
  1915.   if (w32_env)
  1916.     /* Just free the Win32 environment, if it could be created. */
  1917.     free (w32_env);
  1918.   else
  1919.     {
  1920.       /* Reset all environment variables to avoid leftover on next run. */
  1921.       clear_win32_environment (in_env);
  1922.       /* Restore normal GDB environment variables.  */
  1923.       environ = old_env;
  1924.       cygwin_internal (CW_SYNC_WINENV);
  1925.     }

  1926.   if (tty >= 0)
  1927.     {
  1928.       close (tty);
  1929.       dup2 (ostdin, 0);
  1930.       dup2 (ostdout, 1);
  1931.       dup2 (ostderr, 2);
  1932.       close (ostdin);
  1933.       close (ostdout);
  1934.       close (ostderr);
  1935.     }
  1936. #else
  1937.   toexec = exec_file;
  1938.   /* Build the command line, a space-separated list of tokens where
  1939.      the first token is the name of the module to be executed.
  1940.      To avoid ambiguities introduced by spaces in the module name,
  1941.      we quote it.  */
  1942.   args_len = strlen (toexec) + 2 /* quotes */ + strlen (allargs) + 2;
  1943.   args = alloca (args_len);
  1944.   xsnprintf (args, args_len, "\"%s\" %s", toexec, allargs);

  1945.   flags |= DEBUG_ONLY_THIS_PROCESS;

  1946.   if (!inferior_io_terminal)
  1947.     tty = INVALID_HANDLE_VALUE;
  1948.   else
  1949.     {
  1950.       SECURITY_ATTRIBUTES sa;
  1951.       sa.nLength = sizeof(sa);
  1952.       sa.lpSecurityDescriptor = 0;
  1953.       sa.bInheritHandle = TRUE;
  1954.       tty = CreateFileA (inferior_io_terminal, GENERIC_READ | GENERIC_WRITE,
  1955.                          0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  1956.       if (tty == INVALID_HANDLE_VALUE)
  1957.         warning (_("Warning: Failed to open TTY %s, error %#x."),
  1958.                  inferior_io_terminal, (unsigned) GetLastError ());
  1959.       else
  1960.         {
  1961.           si.hStdInput = tty;
  1962.           si.hStdOutput = tty;
  1963.           si.hStdError = tty;
  1964.           si.dwFlags |= STARTF_USESTDHANDLES;
  1965.         }
  1966.     }

  1967.   /* CreateProcess takes the environment list as a null terminated set of
  1968.      strings (i.e. two nulls terminate the list).  */

  1969.   /* Get total size for env strings.  */
  1970.   for (envlen = 0, i = 0; in_env[i] && *in_env[i]; i++)
  1971.     envlen += strlen (in_env[i]) + 1;

  1972.   envsize = sizeof (in_env[0]) * (i + 1);
  1973.   env = (char **) alloca (envsize);
  1974.   memcpy (env, in_env, envsize);
  1975.   /* Windows programs expect the environment block to be sorted.  */
  1976.   qsort (env, i, sizeof (char *), envvar_cmp);

  1977.   w32env = alloca (envlen + 1);

  1978.   /* Copy env strings into new buffer.  */
  1979.   for (temp = w32env, i = 0; env[i] && *env[i]; i++)
  1980.     {
  1981.       strcpy (temp, env[i]);
  1982.       temp += strlen (temp) + 1;
  1983.     }

  1984.   /* Final nil string to terminate new env.  */
  1985.   *temp = 0;

  1986.   windows_init_thread_list ();
  1987.   ret = CreateProcessA (0,
  1988.                         args,        /* command line */
  1989.                         NULL,        /* Security */
  1990.                         NULL,        /* thread */
  1991.                         TRUE,        /* inherit handles */
  1992.                         flags,        /* start flags */
  1993.                         w32env,        /* environment */
  1994.                         NULL,        /* current directory */
  1995.                         &si,
  1996.                         &pi);
  1997.   if (tty != INVALID_HANDLE_VALUE)
  1998.     CloseHandle (tty);
  1999. #endif

  2000.   if (!ret)
  2001.     error (_("Error creating process %s, (error %u)."),
  2002.            exec_file, (unsigned) GetLastError ());

  2003.   CloseHandle (pi.hThread);
  2004.   CloseHandle (pi.hProcess);

  2005.   if (useshell && shell[0] != '\0')
  2006.     saw_create = -1;
  2007.   else
  2008.     saw_create = 0;

  2009.   do_initial_windows_stuff (ops, pi.dwProcessId, 0);

  2010.   /* windows_continue (DBG_CONTINUE, -1, 0); */
  2011. }

  2012. static void
  2013. windows_mourn_inferior (struct target_ops *ops)
  2014. {
  2015.   (void) windows_continue (DBG_CONTINUE, -1, 0);
  2016.   x86_cleanup_dregs();
  2017.   if (open_process_used)
  2018.     {
  2019.       CHECK (CloseHandle (current_process_handle));
  2020.       open_process_used = 0;
  2021.     }
  2022.   inf_child_mourn_inferior (ops);
  2023. }

  2024. /* Send a SIGINT to the process group.  This acts just like the user typed a
  2025.    ^C on the controlling terminal.  */

  2026. static void
  2027. windows_stop (struct target_ops *self, ptid_t ptid)
  2028. {
  2029.   DEBUG_EVENTS (("gdb: GenerateConsoleCtrlEvent (CTRLC_EVENT, 0)\n"));
  2030.   CHECK (GenerateConsoleCtrlEvent (CTRL_C_EVENT, current_event.dwProcessId));
  2031.   registers_changed ();                /* refresh register state */
  2032. }

  2033. /* Helper for windows_xfer_partial that handles memory transfers.
  2034.    Arguments are like target_xfer_partial.  */

  2035. static enum target_xfer_status
  2036. windows_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
  2037.                      ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
  2038. {
  2039.   SIZE_T done = 0;
  2040.   BOOL success;
  2041.   DWORD lasterror = 0;

  2042.   if (writebuf != NULL)
  2043.     {
  2044.       DEBUG_MEM (("gdb: write target memory, %s bytes at %s\n",
  2045.                   pulongest (len), core_addr_to_string (memaddr)));
  2046.       success = WriteProcessMemory (current_process_handle,
  2047.                                     (LPVOID) (uintptr_t) memaddr, writebuf,
  2048.                                     len, &done);
  2049.       if (!success)
  2050.         lasterror = GetLastError ();
  2051.       FlushInstructionCache (current_process_handle,
  2052.                              (LPCVOID) (uintptr_t) memaddr, len);
  2053.     }
  2054.   else
  2055.     {
  2056.       DEBUG_MEM (("gdb: read target memory, %s bytes at %s\n",
  2057.                   pulongest (len), core_addr_to_string (memaddr)));
  2058.       success = ReadProcessMemory (current_process_handle,
  2059.                                    (LPCVOID) (uintptr_t) memaddr, readbuf,
  2060.                                    len, &done);
  2061.       if (!success)
  2062.         lasterror = GetLastError ();
  2063.     }
  2064.   *xfered_len = (ULONGEST) done;
  2065.   if (!success && lasterror == ERROR_PARTIAL_COPY && done > 0)
  2066.     return TARGET_XFER_OK;
  2067.   else
  2068.     return success ? TARGET_XFER_OK : TARGET_XFER_E_IO;
  2069. }

  2070. static void
  2071. windows_kill_inferior (struct target_ops *ops)
  2072. {
  2073.   CHECK (TerminateProcess (current_process_handle, 0));

  2074.   for (;;)
  2075.     {
  2076.       if (!windows_continue (DBG_CONTINUE, -1, 1))
  2077.         break;
  2078.       if (!WaitForDebugEvent (&current_event, INFINITE))
  2079.         break;
  2080.       if (current_event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
  2081.         break;
  2082.     }

  2083.   target_mourn_inferior ();        /* Or just windows_mourn_inferior?  */
  2084. }

  2085. static void
  2086. windows_close (struct target_ops *self)
  2087. {
  2088.   DEBUG_EVENTS (("gdb: windows_close, inferior_ptid=%d\n",
  2089.                 ptid_get_pid (inferior_ptid)));
  2090. }

  2091. /* Convert pid to printable format.  */
  2092. static char *
  2093. windows_pid_to_str (struct target_ops *ops, ptid_t ptid)
  2094. {
  2095.   static char buf[80];

  2096.   if (ptid_get_tid (ptid) != 0)
  2097.     {
  2098.       snprintf (buf, sizeof (buf), "Thread %d.0x%lx",
  2099.                 ptid_get_pid (ptid), ptid_get_tid (ptid));
  2100.       return buf;
  2101.     }

  2102.   return normal_pid_to_str (ptid);
  2103. }

  2104. static enum target_xfer_status
  2105. windows_xfer_shared_libraries (struct target_ops *ops,
  2106.                                enum target_object object, const char *annex,
  2107.                                gdb_byte *readbuf, const gdb_byte *writebuf,
  2108.                                ULONGEST offset, ULONGEST len,
  2109.                                ULONGEST *xfered_len)
  2110. {
  2111.   struct obstack obstack;
  2112.   const char *buf;
  2113.   LONGEST len_avail;
  2114.   struct so_list *so;

  2115.   if (writebuf)
  2116.     return TARGET_XFER_E_IO;

  2117.   obstack_init (&obstack);
  2118.   obstack_grow_str (&obstack, "<library-list>\n");
  2119.   for (so = solib_start.next; so; so = so->next)
  2120.     windows_xfer_shared_library (so->so_name, (CORE_ADDR)
  2121.                                  (uintptr_t) so->lm_info->load_addr,
  2122.                                  target_gdbarch (), &obstack);
  2123.   obstack_grow_str0 (&obstack, "</library-list>\n");

  2124.   buf = obstack_finish (&obstack);
  2125.   len_avail = strlen (buf);
  2126.   if (offset >= len_avail)
  2127.     len= 0;
  2128.   else
  2129.     {
  2130.       if (len > len_avail - offset)
  2131.         len = len_avail - offset;
  2132.       memcpy (readbuf, buf + offset, len);
  2133.     }

  2134.   obstack_free (&obstack, NULL);
  2135.   *xfered_len = (ULONGEST) len;
  2136.   return len != 0 ? TARGET_XFER_OK : TARGET_XFER_EOF;
  2137. }

  2138. static enum target_xfer_status
  2139. windows_xfer_partial (struct target_ops *ops, enum target_object object,
  2140.                       const char *annex, gdb_byte *readbuf,
  2141.                       const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
  2142.                       ULONGEST *xfered_len)
  2143. {
  2144.   switch (object)
  2145.     {
  2146.     case TARGET_OBJECT_MEMORY:
  2147.       return windows_xfer_memory (readbuf, writebuf, offset, len, xfered_len);

  2148.     case TARGET_OBJECT_LIBRARIES:
  2149.       return windows_xfer_shared_libraries (ops, object, annex, readbuf,
  2150.                                             writebuf, offset, len, xfered_len);

  2151.     default:
  2152.       return ops->beneath->to_xfer_partial (ops->beneath, object, annex,
  2153.                                             readbuf, writebuf, offset, len,
  2154.                                             xfered_len);
  2155.     }
  2156. }

  2157. /* Provide thread local base, i.e. Thread Information Block address.
  2158.    Returns 1 if ptid is found and sets *ADDR to thread_local_base.  */

  2159. static int
  2160. windows_get_tib_address (struct target_ops *self,
  2161.                          ptid_t ptid, CORE_ADDR *addr)
  2162. {
  2163.   thread_info *th;

  2164.   th = thread_rec (ptid_get_tid (ptid), 0);
  2165.   if (th == NULL)
  2166.     return 0;

  2167.   if (addr != NULL)
  2168.     *addr = th->thread_local_base;

  2169.   return 1;
  2170. }

  2171. static ptid_t
  2172. windows_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
  2173. {
  2174.   return ptid_build (ptid_get_pid (inferior_ptid), 0, lwp);
  2175. }

  2176. static struct target_ops *
  2177. windows_target (void)
  2178. {
  2179.   struct target_ops *t = inf_child_target ();

  2180.   t->to_close = windows_close;
  2181.   t->to_attach = windows_attach;
  2182.   t->to_attach_no_wait = 1;
  2183.   t->to_detach = windows_detach;
  2184.   t->to_resume = windows_resume;
  2185.   t->to_wait = windows_wait;
  2186.   t->to_fetch_registers = windows_fetch_inferior_registers;
  2187.   t->to_store_registers = windows_store_inferior_registers;
  2188.   t->to_xfer_partial = windows_xfer_partial;
  2189.   t->to_files_info = windows_files_info;
  2190.   t->to_kill = windows_kill_inferior;
  2191.   t->to_create_inferior = windows_create_inferior;
  2192.   t->to_mourn_inferior = windows_mourn_inferior;
  2193.   t->to_thread_alive = windows_thread_alive;
  2194.   t->to_pid_to_str = windows_pid_to_str;
  2195.   t->to_stop = windows_stop;
  2196.   t->to_pid_to_exec_file = windows_pid_to_exec_file;
  2197.   t->to_get_ada_task_ptid = windows_get_ada_task_ptid;
  2198.   t->to_get_tib_address = windows_get_tib_address;

  2199.   return t;
  2200. }

  2201. static void
  2202. set_windows_aliases (char *argv0)
  2203. {
  2204.   add_info_alias ("dll", "sharedlibrary", 1);
  2205. }

  2206. /* -Wmissing-prototypes */
  2207. extern initialize_file_ftype _initialize_windows_nat;

  2208. void
  2209. _initialize_windows_nat (void)
  2210. {
  2211.   struct target_ops *t;

  2212.   t = windows_target ();

  2213.   x86_use_watchpoints (t);

  2214.   x86_dr_low.set_control = cygwin_set_dr7;
  2215.   x86_dr_low.set_addr = cygwin_set_dr;
  2216.   x86_dr_low.get_addr = cygwin_get_dr;
  2217.   x86_dr_low.get_status = cygwin_get_dr6;
  2218.   x86_dr_low.get_control = cygwin_get_dr7;

  2219.   /* x86_dr_low.debug_register_length field is set by
  2220.      calling x86_set_debug_register_length function
  2221.      in processor windows specific native file.  */

  2222.   add_target (t);

  2223. #ifdef __CYGWIN__
  2224.   cygwin_internal (CW_SET_DOS_FILE_WARNING, 0);
  2225. #endif

  2226. #ifdef __CYGWIN__
  2227.   add_setshow_boolean_cmd ("shell", class_support, &useshell, _("\
  2228. Set use of shell to start subprocess."), _("\
  2229. Show use of shell to start subprocess."), NULL,
  2230.                            NULL,
  2231.                            NULL, /* FIXME: i18n: */
  2232.                            &setlist, &showlist);

  2233.   add_setshow_boolean_cmd ("cygwin-exceptions", class_support,
  2234.                            &cygwin_exceptions, _("\
  2235. Break when an exception is detected in the Cygwin DLL itself."), _("\
  2236. Show whether gdb breaks on exceptions in the Cygwin DLL itself."), NULL,
  2237.                            NULL,
  2238.                            NULL, /* FIXME: i18n: */
  2239.                            &setlist, &showlist);
  2240. #endif

  2241.   add_setshow_boolean_cmd ("new-console", class_support, &new_console, _("\
  2242. Set creation of new console when creating child process."), _("\
  2243. Show creation of new console when creating child process."), NULL,
  2244.                            NULL,
  2245.                            NULL, /* FIXME: i18n: */
  2246.                            &setlist, &showlist);

  2247.   add_setshow_boolean_cmd ("new-group", class_support, &new_group, _("\
  2248. Set creation of new group when creating child process."), _("\
  2249. Show creation of new group when creating child process."), NULL,
  2250.                            NULL,
  2251.                            NULL, /* FIXME: i18n: */
  2252.                            &setlist, &showlist);

  2253.   add_setshow_boolean_cmd ("debugexec", class_support, &debug_exec, _("\
  2254. Set whether to display execution in child process."), _("\
  2255. Show whether to display execution in child process."), NULL,
  2256.                            NULL,
  2257.                            NULL, /* FIXME: i18n: */
  2258.                            &setlist, &showlist);

  2259.   add_setshow_boolean_cmd ("debugevents", class_support, &debug_events, _("\
  2260. Set whether to display kernel events in child process."), _("\
  2261. Show whether to display kernel events in child process."), NULL,
  2262.                            NULL,
  2263.                            NULL, /* FIXME: i18n: */
  2264.                            &setlist, &showlist);

  2265.   add_setshow_boolean_cmd ("debugmemory", class_support, &debug_memory, _("\
  2266. Set whether to display memory accesses in child process."), _("\
  2267. Show whether to display memory accesses in child process."), NULL,
  2268.                            NULL,
  2269.                            NULL, /* FIXME: i18n: */
  2270.                            &setlist, &showlist);

  2271.   add_setshow_boolean_cmd ("debugexceptions", class_support,
  2272.                            &debug_exceptions, _("\
  2273. Set whether to display kernel exceptions in child process."), _("\
  2274. Show whether to display kernel exceptions in child process."), NULL,
  2275.                            NULL,
  2276.                            NULL, /* FIXME: i18n: */
  2277.                            &setlist, &showlist);

  2278.   init_w32_command_list ();

  2279.   add_cmd ("selector", class_info, display_selectors,
  2280.            _("Display selectors infos."),
  2281.            &info_w32_cmdlist);
  2282.   deprecated_init_ui_hook = set_windows_aliases;
  2283. }

  2284. /* Hardware watchpoint support, adapted from go32-nat.c code.  */

  2285. /* Pass the address ADDR to the inferior in the I'th debug register.
  2286.    Here we just store the address in dr array, the registers will be
  2287.    actually set up when windows_continue is called.  */
  2288. static void
  2289. cygwin_set_dr (int i, CORE_ADDR addr)
  2290. {
  2291.   if (i < 0 || i > 3)
  2292.     internal_error (__FILE__, __LINE__,
  2293.                     _("Invalid register %d in cygwin_set_dr.\n"), i);
  2294.   dr[i] = addr;
  2295.   debug_registers_changed = 1;
  2296.   debug_registers_used = 1;
  2297. }

  2298. /* Pass the value VAL to the inferior in the DR7 debug control
  2299.    register.  Here we just store the address in D_REGS, the watchpoint
  2300.    will be actually set up in windows_wait.  */
  2301. static void
  2302. cygwin_set_dr7 (unsigned long val)
  2303. {
  2304.   dr[7] = (CORE_ADDR) val;
  2305.   debug_registers_changed = 1;
  2306.   debug_registers_used = 1;
  2307. }

  2308. /* Get the value of debug register I from the inferior.  */

  2309. static CORE_ADDR
  2310. cygwin_get_dr (int i)
  2311. {
  2312.   return dr[i];
  2313. }

  2314. /* Get the value of the DR6 debug status register from the inferior.
  2315.    Here we just return the value stored in dr[6]
  2316.    by the last call to thread_rec for current_event.dwThreadId id.  */
  2317. static unsigned long
  2318. cygwin_get_dr6 (void)
  2319. {
  2320.   return (unsigned long) dr[6];
  2321. }

  2322. /* Get the value of the DR7 debug status register from the inferior.
  2323.    Here we just return the value stored in dr[7] by the last call to
  2324.    thread_rec for current_event.dwThreadId id.  */

  2325. static unsigned long
  2326. cygwin_get_dr7 (void)
  2327. {
  2328.   return (unsigned long) dr[7];
  2329. }

  2330. /* Determine if the thread referenced by "ptid" is alive
  2331.    by "polling" it.  If WaitForSingleObject returns WAIT_OBJECT_0
  2332.    it means that the thread has died.  Otherwise it is assumed to be alive.  */
  2333. static int
  2334. windows_thread_alive (struct target_ops *ops, ptid_t ptid)
  2335. {
  2336.   int tid;

  2337.   gdb_assert (ptid_get_tid (ptid) != 0);
  2338.   tid = ptid_get_tid (ptid);

  2339.   return WaitForSingleObject (thread_rec (tid, FALSE)->h, 0) == WAIT_OBJECT_0
  2340.     ? FALSE : TRUE;
  2341. }

  2342. /* -Wmissing-prototypes */
  2343. extern initialize_file_ftype _initialize_check_for_gdb_ini;

  2344. void
  2345. _initialize_check_for_gdb_ini (void)
  2346. {
  2347.   char *homedir;
  2348.   if (inhibit_gdbinit)
  2349.     return;

  2350.   homedir = getenv ("HOME");
  2351.   if (homedir)
  2352.     {
  2353.       char *p;
  2354.       char *oldini = (char *) alloca (strlen (homedir) +
  2355.                                       sizeof ("/gdb.ini"));
  2356.       strcpy (oldini, homedir);
  2357.       p = strchr (oldini, '\0');
  2358.       if (p > oldini && !IS_DIR_SEPARATOR (p[-1]))
  2359.         *p++ = '/';
  2360.       strcpy (p, "gdb.ini");
  2361.       if (access (oldini, 0) == 0)
  2362.         {
  2363.           int len = strlen (oldini);
  2364.           char *newini = alloca (len + 1);

  2365.           xsnprintf (newini, len + 1, "%.*s.gdbinit",
  2366.                      (int) (len - (sizeof ("gdb.ini") - 1)), oldini);
  2367.           warning (_("obsolete '%s' found. Rename to '%s'."), oldini, newini);
  2368.         }
  2369.     }
  2370. }

  2371. /* Define dummy functions which always return error for the rare cases where
  2372.    these functions could not be found.  */
  2373. static BOOL WINAPI
  2374. bad_DebugActiveProcessStop (DWORD w)
  2375. {
  2376.   return FALSE;
  2377. }
  2378. static BOOL WINAPI
  2379. bad_DebugBreakProcess (HANDLE w)
  2380. {
  2381.   return FALSE;
  2382. }
  2383. static BOOL WINAPI
  2384. bad_DebugSetProcessKillOnExit (BOOL w)
  2385. {
  2386.   return FALSE;
  2387. }
  2388. static BOOL WINAPI
  2389. bad_EnumProcessModules (HANDLE w, HMODULE *x, DWORD y, LPDWORD z)
  2390. {
  2391.   return FALSE;
  2392. }

  2393. #ifdef __USEWIDE
  2394. static DWORD WINAPI
  2395. bad_GetModuleFileNameExW (HANDLE w, HMODULE x, LPWSTR y, DWORD z)
  2396. {
  2397.   return 0;
  2398. }
  2399. #else
  2400. static DWORD WINAPI
  2401. bad_GetModuleFileNameExA (HANDLE w, HMODULE x, LPSTR y, DWORD z)
  2402. {
  2403.   return 0;
  2404. }
  2405. #endif

  2406. static BOOL WINAPI
  2407. bad_GetModuleInformation (HANDLE w, HMODULE x, LPMODULEINFO y, DWORD z)
  2408. {
  2409.   return FALSE;
  2410. }

  2411. static BOOL WINAPI
  2412. bad_OpenProcessToken (HANDLE w, DWORD x, PHANDLE y)
  2413. {
  2414.   return FALSE;
  2415. }

  2416. static BOOL WINAPI
  2417. bad_GetCurrentConsoleFont (HANDLE w, BOOL bMaxWindow, CONSOLE_FONT_INFO *f)
  2418. {
  2419.   f->nFont = 0;
  2420.   return 1;
  2421. }
  2422. static COORD WINAPI
  2423. bad_GetConsoleFontSize (HANDLE w, DWORD nFont)
  2424. {
  2425.   COORD size;
  2426.   size.X = 8;
  2427.   size.Y = 12;
  2428.   return size;
  2429. }

  2430. /* -Wmissing-prototypes */
  2431. extern initialize_file_ftype _initialize_loadable;

  2432. /* Load any functions which may not be available in ancient versions
  2433.    of Windows.  */

  2434. void
  2435. _initialize_loadable (void)
  2436. {
  2437.   HMODULE hm = NULL;

  2438.   hm = LoadLibrary ("kernel32.dll");
  2439.   if (hm)
  2440.     {
  2441.       DebugActiveProcessStop = (void *)
  2442.         GetProcAddress (hm, "DebugActiveProcessStop");
  2443.       DebugBreakProcess = (void *)
  2444.         GetProcAddress (hm, "DebugBreakProcess");
  2445.       DebugSetProcessKillOnExit = (void *)
  2446.         GetProcAddress (hm, "DebugSetProcessKillOnExit");
  2447.       GetConsoleFontSize = (void *)
  2448.         GetProcAddress (hm, "GetConsoleFontSize");
  2449.       GetCurrentConsoleFont = (void *)
  2450.         GetProcAddress (hm, "GetCurrentConsoleFont");
  2451.     }

  2452.   /* Set variables to dummy versions of these processes if the function
  2453.      wasn't found in kernel32.dll.  */
  2454.   if (!DebugBreakProcess)
  2455.     DebugBreakProcess = bad_DebugBreakProcess;
  2456.   if (!DebugActiveProcessStop || !DebugSetProcessKillOnExit)
  2457.     {
  2458.       DebugActiveProcessStop = bad_DebugActiveProcessStop;
  2459.       DebugSetProcessKillOnExit = bad_DebugSetProcessKillOnExit;
  2460.     }
  2461.   if (!GetConsoleFontSize)
  2462.     GetConsoleFontSize = bad_GetConsoleFontSize;
  2463.   if (!GetCurrentConsoleFont)
  2464.     GetCurrentConsoleFont = bad_GetCurrentConsoleFont;

  2465.   /* Load optional functions used for retrieving filename information
  2466.      associated with the currently debugged process or its dlls.  */
  2467.   hm = LoadLibrary ("psapi.dll");
  2468.   if (hm)
  2469.     {
  2470.       EnumProcessModules = (void *)
  2471.         GetProcAddress (hm, "EnumProcessModules");
  2472.       GetModuleInformation = (void *)
  2473.         GetProcAddress (hm, "GetModuleInformation");
  2474.       GetModuleFileNameEx = (void *)
  2475.         GetProcAddress (hm, GetModuleFileNameEx_name);
  2476.     }

  2477.   if (!EnumProcessModules || !GetModuleInformation || !GetModuleFileNameEx)
  2478.     {
  2479.       /* Set variables to dummy versions of these processes if the function
  2480.          wasn't found in psapi.dll.  */
  2481.       EnumProcessModules = bad_EnumProcessModules;
  2482.       GetModuleInformation = bad_GetModuleInformation;
  2483.       GetModuleFileNameEx = bad_GetModuleFileNameEx;
  2484.       /* This will probably fail on Windows 9x/Me.  Let the user know
  2485.          that we're missing some functionality.  */
  2486.       warning(_("\
  2487. cannot automatically find executable file or library to read symbols.\n\
  2488. Use \"file\" or \"dll\" command to load executable/libraries directly."));
  2489.     }

  2490.   hm = LoadLibrary ("advapi32.dll");
  2491.   if (hm)
  2492.     {
  2493.       OpenProcessToken = (void *) GetProcAddress (hm, "OpenProcessToken");
  2494.       LookupPrivilegeValueA = (void *)
  2495.         GetProcAddress (hm, "LookupPrivilegeValueA");
  2496.       AdjustTokenPrivileges = (void *)
  2497.         GetProcAddress (hm, "AdjustTokenPrivileges");
  2498.       /* Only need to set one of these since if OpenProcessToken fails nothing
  2499.          else is needed.  */
  2500.       if (!OpenProcessToken || !LookupPrivilegeValueA
  2501.           || !AdjustTokenPrivileges)
  2502.         OpenProcessToken = bad_OpenProcessToken;
  2503.     }
  2504. }