2009-06-16 Paul Pluzhnikov <ppluzhnikov@google.com>
[external/binutils.git] / gdb / windows-nat.c
1 /* Target-vector operations for controlling windows child processes, for GDB.
2
3    Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4    2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
5
6    Contributed by Cygnus Solutions, A Red Hat Company.
7
8    This file is part of GDB.
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
22
23 /* Originally by Steve Chamberlain, sac@cygnus.com */
24
25 #include "defs.h"
26 #include "frame.h"              /* required by inferior.h */
27 #include "inferior.h"
28 #include "target.h"
29 #include "exceptions.h"
30 #include "gdbcore.h"
31 #include "command.h"
32 #include "completer.h"
33 #include "regcache.h"
34 #include "top.h"
35 #include <signal.h>
36 #include <sys/types.h>
37 #include <fcntl.h>
38 #include <stdlib.h>
39 #include <windows.h>
40 #include <imagehlp.h>
41 #include <psapi.h>
42 #ifdef __CYGWIN__
43 #include <sys/cygwin.h>
44 #endif
45 #include <signal.h>
46
47 #include "buildsym.h"
48 #include "symfile.h"
49 #include "objfiles.h"
50 #include "gdb_obstack.h"
51 #include "gdb_string.h"
52 #include "gdbthread.h"
53 #include "gdbcmd.h"
54 #include <sys/param.h>
55 #include <unistd.h>
56 #include "exec.h"
57 #include "solist.h"
58 #include "solib.h"
59 #include "xml-support.h"
60
61 #include "i386-tdep.h"
62 #include "i387-tdep.h"
63
64 #include "windows-tdep.h"
65 #include "windows-nat.h"
66 #include "i386-nat.h"
67
68 #define AdjustTokenPrivileges           dyn_AdjustTokenPrivileges
69 #define DebugActiveProcessStop          dyn_DebugActiveProcessStop
70 #define DebugBreakProcess               dyn_DebugBreakProcess
71 #define DebugSetProcessKillOnExit       dyn_DebugSetProcessKillOnExit
72 #define EnumProcessModules              dyn_EnumProcessModules
73 #define GetModuleFileNameExA            dyn_GetModuleFileNameExA
74 #define GetModuleInformation            dyn_GetModuleInformation
75 #define LookupPrivilegeValueA           dyn_LookupPrivilegeValueA
76 #define OpenProcessToken                dyn_OpenProcessToken
77
78 static BOOL WINAPI (*AdjustTokenPrivileges)(HANDLE, BOOL, PTOKEN_PRIVILEGES,
79                                             DWORD, PTOKEN_PRIVILEGES, PDWORD);
80 static BOOL WINAPI (*DebugActiveProcessStop) (DWORD);
81 static BOOL WINAPI (*DebugBreakProcess) (HANDLE);
82 static BOOL WINAPI (*DebugSetProcessKillOnExit) (BOOL);
83 static BOOL WINAPI (*EnumProcessModules) (HANDLE, HMODULE *, DWORD,
84                                           LPDWORD);
85 static DWORD WINAPI (*GetModuleFileNameExA) (HANDLE, HMODULE, LPSTR,
86                                             DWORD);
87 static BOOL WINAPI (*GetModuleInformation) (HANDLE, HMODULE, LPMODULEINFO,
88                                             DWORD);
89 static BOOL WINAPI (*LookupPrivilegeValueA)(LPCSTR, LPCSTR, PLUID);
90 static BOOL WINAPI (*OpenProcessToken)(HANDLE, DWORD, PHANDLE);
91
92 static struct target_ops windows_ops;
93
94 #ifdef __CYGWIN__
95 /* The starting and ending address of the cygwin1.dll text segment. */
96 static CORE_ADDR cygwin_load_start;
97 static CORE_ADDR cygwin_load_end;
98 #endif
99
100 static int have_saved_context;  /* True if we've saved context from a cygwin signal. */
101 static CONTEXT saved_context;   /* Containes the saved context from a cygwin signal. */
102
103 /* If we're not using the old Cygwin header file set, define the
104    following which never should have been in the generic Win32 API
105    headers in the first place since they were our own invention... */
106 #ifndef _GNU_H_WINDOWS_H
107 enum
108   {
109     FLAG_TRACE_BIT = 0x100,
110     CONTEXT_DEBUGGER = (CONTEXT_FULL | CONTEXT_FLOATING_POINT)
111   };
112 #endif
113
114 #ifndef CONTEXT_EXTENDED_REGISTERS
115 /* This macro is only defined on ia32.  It only makes sense on this target,
116    so define it as zero if not already defined.  */
117 #define CONTEXT_EXTENDED_REGISTERS 0
118 #endif
119
120 #define CONTEXT_DEBUGGER_DR CONTEXT_DEBUGGER | CONTEXT_DEBUG_REGISTERS \
121         | CONTEXT_EXTENDED_REGISTERS
122
123 static uintptr_t dr[8];
124 static int debug_registers_changed;
125 static int debug_registers_used;
126 #define DR6_CLEAR_VALUE 0xffff0ff0
127
128 /* The string sent by cygwin when it processes a signal.
129    FIXME: This should be in a cygwin include file. */
130 #ifndef _CYGWIN_SIGNAL_STRING
131 #define _CYGWIN_SIGNAL_STRING "cYgSiGw00f"
132 #endif
133
134 #define CHECK(x)        check (x, __FILE__,__LINE__)
135 #define DEBUG_EXEC(x)   if (debug_exec)         printf_unfiltered x
136 #define DEBUG_EVENTS(x) if (debug_events)       printf_unfiltered x
137 #define DEBUG_MEM(x)    if (debug_memory)       printf_unfiltered x
138 #define DEBUG_EXCEPT(x) if (debug_exceptions)   printf_unfiltered x
139
140 static void windows_stop (ptid_t);
141 static int windows_thread_alive (struct target_ops *, ptid_t);
142 static void windows_kill_inferior (struct target_ops *);
143
144 static void cygwin_set_dr (int i, CORE_ADDR addr);
145 static void cygwin_set_dr7 (unsigned long val);
146 static unsigned long cygwin_get_dr6 (void);
147
148 static enum target_signal last_sig = TARGET_SIGNAL_0;
149 /* Set if a signal was received from the debugged process */
150
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     char *name;
159     int suspended;
160     int reload_context;
161     CONTEXT context;
162     STACKFRAME sf;
163   }
164 thread_info;
165
166 static thread_info thread_head;
167
168 /* The process and thread handles for the above context. */
169
170 static DEBUG_EVENT current_event;       /* The current debug event from
171                                            WaitForDebugEvent */
172 static HANDLE current_process_handle;   /* Currently executing process */
173 static thread_info *current_thread;     /* Info on currently selected thread */
174 static DWORD main_thread_id;            /* Thread ID of the main thread */
175
176 /* Counts of things. */
177 static int exception_count = 0;
178 static int event_count = 0;
179 static int saw_create;
180 static int open_process_used = 0;
181
182 /* User options. */
183 static int new_console = 0;
184 #ifdef __CYGWIN__
185 static int cygwin_exceptions = 0;
186 #endif
187 static int new_group = 1;
188 static int debug_exec = 0;              /* show execution */
189 static int debug_events = 0;            /* show events from kernel */
190 static int debug_memory = 0;            /* show target memory accesses */
191 static int debug_exceptions = 0;        /* show target exceptions */
192 static int useshell = 0;                /* use shell for subprocesses */
193
194 /* This vector maps GDB's idea of a register's number into an offset
195    in the windows exception context vector.
196
197    It also contains the bit mask needed to load the register in question.
198
199    The contents of this table can only be computed by the units
200    that provide CPU-specific support for Windows native debugging.
201    These units should set the table by calling
202    windows_set_context_register_offsets.
203
204    One day we could read a reg, we could inspect the context we
205    already have loaded, if it doesn't have the bit set that we need,
206    we read that set of registers in using GetThreadContext.  If the
207    context already contains what we need, we just unpack it. Then to
208    write a register, first we have to ensure that the context contains
209    the other regs of the group, and then we copy the info in and set
210    out bit. */
211
212 static const int *mappings;
213
214 /* This vector maps the target's idea of an exception (extracted
215    from the DEBUG_EVENT structure) to GDB's idea. */
216
217 struct xlate_exception
218   {
219     int them;
220     enum target_signal us;
221   };
222
223 static const struct xlate_exception
224   xlate[] =
225 {
226   {EXCEPTION_ACCESS_VIOLATION, TARGET_SIGNAL_SEGV},
227   {STATUS_STACK_OVERFLOW, TARGET_SIGNAL_SEGV},
228   {EXCEPTION_BREAKPOINT, TARGET_SIGNAL_TRAP},
229   {DBG_CONTROL_C, TARGET_SIGNAL_INT},
230   {EXCEPTION_SINGLE_STEP, TARGET_SIGNAL_TRAP},
231   {STATUS_FLOAT_DIVIDE_BY_ZERO, TARGET_SIGNAL_FPE},
232   {-1, -1}};
233
234 /* Set the MAPPINGS static global to OFFSETS.
235    See the description of MAPPINGS for more details.  */
236
237 void
238 windows_set_context_register_offsets (const int *offsets)
239 {
240   mappings = offsets;
241 }
242
243 static void
244 check (BOOL ok, const char *file, int line)
245 {
246   if (!ok)
247     printf_filtered ("error return %s:%d was %lu\n", file, line,
248                      GetLastError ());
249 }
250
251 /* Find a thread record given a thread id.  If GET_CONTEXT is not 0,
252    then also retrieve the context for this thread.  If GET_CONTEXT is
253    negative, then don't suspend the thread.  */
254 static thread_info *
255 thread_rec (DWORD id, int get_context)
256 {
257   thread_info *th;
258
259   for (th = &thread_head; (th = th->next) != NULL;)
260     if (th->id == id)
261       {
262         if (!th->suspended && get_context)
263           {
264             if (get_context > 0 && id != current_event.dwThreadId)
265               {
266                 if (SuspendThread (th->h) == (DWORD) -1)
267                   {
268                     DWORD err = GetLastError ();
269                     warning (_("SuspendThread failed. (winerr %d)"),
270                              (int) err);
271                     return NULL;
272                   }
273                 th->suspended = 1;
274               }
275             else if (get_context < 0)
276               th->suspended = -1;
277             th->reload_context = 1;
278           }
279         return th;
280       }
281
282   return NULL;
283 }
284
285 /* Add a thread to the thread list.  */
286 static thread_info *
287 windows_add_thread (ptid_t ptid, HANDLE h)
288 {
289   thread_info *th;
290   DWORD id;
291
292   gdb_assert (ptid_get_tid (ptid) != 0);
293
294   id = ptid_get_tid (ptid);
295
296   if ((th = thread_rec (id, FALSE)))
297     return th;
298
299   th = XZALLOC (thread_info);
300   th->id = id;
301   th->h = h;
302   th->next = thread_head.next;
303   thread_head.next = th;
304   add_thread (ptid);
305   /* Set the debug registers for the new thread if they are used.  */
306   if (debug_registers_used)
307     {
308       /* Only change the value of the debug registers.  */
309       th->context.ContextFlags = CONTEXT_DEBUG_REGISTERS;
310       CHECK (GetThreadContext (th->h, &th->context));
311       th->context.Dr0 = dr[0];
312       th->context.Dr1 = dr[1];
313       th->context.Dr2 = dr[2];
314       th->context.Dr3 = dr[3];
315       th->context.Dr6 = DR6_CLEAR_VALUE;
316       th->context.Dr7 = dr[7];
317       CHECK (SetThreadContext (th->h, &th->context));
318       th->context.ContextFlags = 0;
319     }
320   return th;
321 }
322
323 /* Clear out any old thread list and reintialize it to a
324    pristine state. */
325 static void
326 windows_init_thread_list (void)
327 {
328   thread_info *th = &thread_head;
329
330   DEBUG_EVENTS (("gdb: windows_init_thread_list\n"));
331   init_thread_list ();
332   while (th->next != NULL)
333     {
334       thread_info *here = th->next;
335       th->next = here->next;
336       xfree (here);
337     }
338   thread_head.next = NULL;
339 }
340
341 /* Delete a thread from the list of threads */
342 static void
343 windows_delete_thread (ptid_t ptid)
344 {
345   thread_info *th;
346   DWORD id;
347
348   gdb_assert (ptid_get_tid (ptid) != 0);
349
350   id = ptid_get_tid (ptid);
351
352   if (info_verbose)
353     printf_unfiltered ("[Deleting %s]\n", target_pid_to_str (ptid));
354   delete_thread (ptid);
355
356   for (th = &thread_head;
357        th->next != NULL && th->next->id != id;
358        th = th->next)
359     continue;
360
361   if (th->next != NULL)
362     {
363       thread_info *here = th->next;
364       th->next = here->next;
365       xfree (here);
366     }
367 }
368
369 static void
370 do_windows_fetch_inferior_registers (struct regcache *regcache, int r)
371 {
372   char *context_offset = ((char *) &current_thread->context) + mappings[r];
373   struct gdbarch *gdbarch = get_regcache_arch (regcache);
374   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
375   long l;
376
377   if (!current_thread)
378     return;     /* Windows sometimes uses a non-existent thread id in its
379                    events */
380
381   if (current_thread->reload_context)
382     {
383 #ifdef __COPY_CONTEXT_SIZE
384       if (have_saved_context)
385         {
386           /* Lie about where the program actually is stopped since cygwin has informed us that
387              we should consider the signal to have occurred at another location which is stored
388              in "saved_context. */
389           memcpy (&current_thread->context, &saved_context, __COPY_CONTEXT_SIZE);
390           have_saved_context = 0;
391         }
392       else
393 #endif
394         {
395           thread_info *th = current_thread;
396           th->context.ContextFlags = CONTEXT_DEBUGGER_DR;
397           GetThreadContext (th->h, &th->context);
398           /* Copy dr values from that thread.
399              But only if there were not modified since last stop. PR gdb/2388 */
400           if (!debug_registers_changed)
401             {
402               dr[0] = th->context.Dr0;
403               dr[1] = th->context.Dr1;
404               dr[2] = th->context.Dr2;
405               dr[3] = th->context.Dr3;
406               dr[6] = th->context.Dr6;
407               dr[7] = th->context.Dr7;
408             }
409         }
410       current_thread->reload_context = 0;
411     }
412
413   if (r == I387_FISEG_REGNUM (tdep))
414     {
415       l = *((long *) context_offset) & 0xffff;
416       regcache_raw_supply (regcache, r, (char *) &l);
417     }
418   else if (r == I387_FOP_REGNUM (tdep))
419     {
420       l = (*((long *) context_offset) >> 16) & ((1 << 11) - 1);
421       regcache_raw_supply (regcache, r, (char *) &l);
422     }
423   else if (r >= 0)
424     regcache_raw_supply (regcache, r, context_offset);
425   else
426     {
427       for (r = 0; r < gdbarch_num_regs (gdbarch); r++)
428         do_windows_fetch_inferior_registers (regcache, r);
429     }
430 }
431
432 static void
433 windows_fetch_inferior_registers (struct target_ops *ops,
434                                   struct regcache *regcache, int r)
435 {
436   current_thread = thread_rec (ptid_get_tid (inferior_ptid), TRUE);
437   /* Check if current_thread exists.  Windows sometimes uses a non-existent
438      thread id in its events */
439   if (current_thread)
440     do_windows_fetch_inferior_registers (regcache, r);
441 }
442
443 static void
444 do_windows_store_inferior_registers (const struct regcache *regcache, int r)
445 {
446   if (!current_thread)
447     /* Windows sometimes uses a non-existent thread id in its events */;
448   else if (r >= 0)
449     regcache_raw_collect (regcache, r,
450                           ((char *) &current_thread->context) + mappings[r]);
451   else
452     {
453       for (r = 0; r < gdbarch_num_regs (get_regcache_arch (regcache)); r++)
454         do_windows_store_inferior_registers (regcache, r);
455     }
456 }
457
458 /* Store a new register value into the current thread context */
459 static void
460 windows_store_inferior_registers (struct target_ops *ops,
461                                   struct regcache *regcache, int r)
462 {
463   current_thread = thread_rec (ptid_get_tid (inferior_ptid), TRUE);
464   /* Check if current_thread exists.  Windows sometimes uses a non-existent
465      thread id in its events */
466   if (current_thread)
467     do_windows_store_inferior_registers (regcache, r);
468 }
469
470 /* Get the name of a given module at at given base address.  If base_address
471    is zero return the first loaded module (which is always the name of the
472    executable).  */
473 static int
474 get_module_name (LPVOID base_address, char *dll_name_ret)
475 {
476   DWORD len;
477   MODULEINFO mi;
478   int i;
479   HMODULE dh_buf[1];
480   HMODULE *DllHandle = dh_buf;  /* Set to temporary storage for initial query */
481   DWORD cbNeeded;
482 #ifdef __CYGWIN__
483   char pathbuf[PATH_MAX + 1];   /* Temporary storage prior to converting to
484                                    posix form */
485 #else
486   char *pathbuf = dll_name_ret; /* Just copy directly to passed-in arg */
487 #endif
488
489   cbNeeded = 0;
490   /* Find size of buffer needed to handle list of modules loaded in inferior */
491   if (!EnumProcessModules (current_process_handle, DllHandle,
492                            sizeof (HMODULE), &cbNeeded) || !cbNeeded)
493     goto failed;
494
495   /* Allocate correct amount of space for module list */
496   DllHandle = (HMODULE *) alloca (cbNeeded);
497   if (!DllHandle)
498     goto failed;
499
500   /* Get the list of modules */
501   if (!EnumProcessModules (current_process_handle, DllHandle, cbNeeded,
502                                  &cbNeeded))
503     goto failed;
504
505   for (i = 0; i < (int) (cbNeeded / sizeof (HMODULE)); i++)
506     {
507       /* Get information on this module */
508       if (!GetModuleInformation (current_process_handle, DllHandle[i],
509                                  &mi, sizeof (mi)))
510         error (_("Can't get module info"));
511
512       if (!base_address || mi.lpBaseOfDll == base_address)
513         {
514           /* Try to find the name of the given module */
515           len = GetModuleFileNameExA (current_process_handle,
516                                       DllHandle[i], pathbuf, MAX_PATH);
517           if (len == 0)
518             error (_("Error getting dll name: %u."), (unsigned) GetLastError ());
519 #ifdef __CYGWIN__
520           /* Cygwin prefers that the path be in /x/y/z format */
521           cygwin_conv_to_full_posix_path (pathbuf, dll_name_ret);
522 #endif
523           return 1;     /* success */
524         }
525     }
526
527 failed:
528   dll_name_ret[0] = '\0';
529   return 0;             /* failure */
530 }
531
532 /* Encapsulate the information required in a call to
533    symbol_file_add_args */
534 struct safe_symbol_file_add_args
535 {
536   char *name;
537   int from_tty;
538   struct section_addr_info *addrs;
539   int mainline;
540   int flags;
541   struct ui_file *err, *out;
542   struct objfile *ret;
543 };
544
545 /* Maintain a linked list of "so" information. */
546 struct lm_info
547 {
548   LPVOID load_addr;
549 };
550
551 static struct so_list solib_start, *solib_end;
552
553 /* Call symbol_file_add with stderr redirected.  We don't care if there
554    are errors. */
555 static int
556 safe_symbol_file_add_stub (void *argv)
557 {
558 #define p ((struct safe_symbol_file_add_args *) argv)
559   const int add_flags = ((p->from_tty ? SYMFILE_VERBOSE : 0)
560                          | (p->mainline ? SYMFILE_MAINLINE : 0));
561   p->ret = symbol_file_add (p->name, add_flags, p->addrs, p->flags);
562   return !!p->ret;
563 #undef p
564 }
565
566 /* Restore gdb's stderr after calling symbol_file_add */
567 static void
568 safe_symbol_file_add_cleanup (void *p)
569 {
570 #define sp ((struct safe_symbol_file_add_args *)p)
571   gdb_flush (gdb_stderr);
572   gdb_flush (gdb_stdout);
573   ui_file_delete (gdb_stderr);
574   ui_file_delete (gdb_stdout);
575   gdb_stderr = sp->err;
576   gdb_stdout = sp->out;
577 #undef sp
578 }
579
580 /* symbol_file_add wrapper that prevents errors from being displayed. */
581 static struct objfile *
582 safe_symbol_file_add (char *name, int from_tty,
583                       struct section_addr_info *addrs,
584                       int mainline, int flags)
585 {
586   struct safe_symbol_file_add_args p;
587   struct cleanup *cleanup;
588
589   cleanup = make_cleanup (safe_symbol_file_add_cleanup, &p);
590
591   p.err = gdb_stderr;
592   p.out = gdb_stdout;
593   gdb_flush (gdb_stderr);
594   gdb_flush (gdb_stdout);
595   gdb_stderr = ui_file_new ();
596   gdb_stdout = ui_file_new ();
597   p.name = name;
598   p.from_tty = from_tty;
599   p.addrs = addrs;
600   p.mainline = mainline;
601   p.flags = flags;
602   catch_errors (safe_symbol_file_add_stub, &p, "", RETURN_MASK_ERROR);
603
604   do_cleanups (cleanup);
605   return p.ret;
606 }
607
608 static struct so_list *
609 windows_make_so (const char *name, LPVOID load_addr)
610 {
611   struct so_list *so;
612   char buf[MAX_PATH + 1];
613   char cwd[MAX_PATH + 1];
614   char *p;
615   WIN32_FIND_DATA w32_fd;
616   HANDLE h = FindFirstFile(name, &w32_fd);
617   MEMORY_BASIC_INFORMATION m;
618
619   if (h == INVALID_HANDLE_VALUE)
620     strcpy (buf, name);
621   else
622     {
623       FindClose (h);
624       strcpy (buf, name);
625       if (GetCurrentDirectory (MAX_PATH + 1, cwd))
626         {
627           p = strrchr (buf, '\\');
628           if (p)
629             p[1] = '\0';
630           SetCurrentDirectory (buf);
631           GetFullPathName (w32_fd.cFileName, MAX_PATH, buf, &p);
632           SetCurrentDirectory (cwd);
633         }
634     }
635
636   if (strcasecmp (buf, "ntdll.dll") == 0)
637     {
638       GetSystemDirectory (buf, sizeof (buf));
639       strcat (buf, "\\ntdll.dll");
640     }
641   so = XZALLOC (struct so_list);
642   so->lm_info = (struct lm_info *) xmalloc (sizeof (struct lm_info));
643   so->lm_info->load_addr = load_addr;
644   strcpy (so->so_original_name, name);
645 #ifndef __CYGWIN__
646   strcpy (so->so_name, buf);
647 #else
648   cygwin_conv_to_posix_path (buf, so->so_name);
649   /* Record cygwin1.dll .text start/end.  */
650   p = strchr (so->so_name, '\0') - (sizeof ("/cygwin1.dll") - 1);
651   if (p >= so->so_name && strcasecmp (p, "/cygwin1.dll") == 0)
652     {
653       bfd *abfd;
654       asection *text = NULL;
655       CORE_ADDR text_vma;
656
657       abfd = bfd_openr (so->so_name, "pei-i386");
658
659       if (!abfd)
660         return so;
661
662       if (bfd_check_format (abfd, bfd_object))
663         text = bfd_get_section_by_name (abfd, ".text");
664
665       if (!text)
666         {
667           bfd_close (abfd);
668           return so;
669         }
670
671       /* The symbols in a dll are offset by 0x1000, which is the the
672          offset from 0 of the first byte in an image - because of the
673          file header and the section alignment. */
674       cygwin_load_start = (CORE_ADDR) (uintptr_t) ((char *) load_addr + 0x1000);
675       cygwin_load_end = cygwin_load_start + bfd_section_size (abfd, text);
676
677       bfd_close (abfd);
678     }
679 #endif
680
681   return so;
682 }
683
684 static char *
685 get_image_name (HANDLE h, void *address, int unicode)
686 {
687   static char buf[(2 * MAX_PATH) + 1];
688   DWORD size = unicode ? sizeof (WCHAR) : sizeof (char);
689   char *address_ptr;
690   int len = 0;
691   char b[2];
692   SIZE_T done;
693
694   /* Attempt to read the name of the dll that was detected.
695      This is documented to work only when actively debugging
696      a program.  It will not work for attached processes. */
697   if (address == NULL)
698     return NULL;
699
700   /* See if we could read the address of a string, and that the
701      address isn't null. */
702   if (!ReadProcessMemory (h, address,  &address_ptr, sizeof (address_ptr), &done)
703       || done != sizeof (address_ptr) || !address_ptr)
704     return NULL;
705
706   /* Find the length of the string */
707   while (ReadProcessMemory (h, address_ptr + len++ * size, &b, size, &done)
708          && (b[0] != 0 || b[size - 1] != 0) && done == size)
709     continue;
710
711   if (!unicode)
712     ReadProcessMemory (h, address_ptr, buf, len, &done);
713   else
714     {
715       WCHAR *unicode_address = (WCHAR *) alloca (len * sizeof (WCHAR));
716       ReadProcessMemory (h, address_ptr, unicode_address, len * sizeof (WCHAR),
717                          &done);
718
719       WideCharToMultiByte (CP_ACP, 0, unicode_address, len, buf, len, 0, 0);
720     }
721
722   return buf;
723 }
724
725 /* Wait for child to do something.  Return pid of child, or -1 in case
726    of error; store status through argument pointer OURSTATUS.  */
727 static int
728 handle_load_dll (void *dummy)
729 {
730   LOAD_DLL_DEBUG_INFO *event = &current_event.u.LoadDll;
731   char dll_buf[MAX_PATH + 1];
732   char *dll_name = NULL;
733
734   dll_buf[0] = dll_buf[sizeof (dll_buf) - 1] = '\0';
735
736   if (!get_module_name (event->lpBaseOfDll, dll_buf))
737     dll_buf[0] = dll_buf[sizeof (dll_buf) - 1] = '\0';
738
739   dll_name = dll_buf;
740
741   if (*dll_name == '\0')
742     dll_name = get_image_name (current_process_handle,
743                                event->lpImageName, event->fUnicode);
744   if (!dll_name)
745     return 1;
746
747   solib_end->next = windows_make_so (dll_name, event->lpBaseOfDll);
748   solib_end = solib_end->next;
749
750   DEBUG_EVENTS (("gdb: Loading dll \"%s\" at %s.\n", solib_end->so_name,
751                  host_address_to_string (solib_end->lm_info->load_addr)));
752
753   return 1;
754 }
755
756 static void
757 windows_free_so (struct so_list *so)
758 {
759   if (so->lm_info)
760     xfree (so->lm_info);
761   xfree (so);
762 }
763
764 static int
765 handle_unload_dll (void *dummy)
766 {
767   LPVOID lpBaseOfDll = current_event.u.UnloadDll.lpBaseOfDll;
768   struct so_list *so;
769
770   for (so = &solib_start; so->next != NULL; so = so->next)
771     if (so->next->lm_info->load_addr == lpBaseOfDll)
772       {
773         struct so_list *sodel = so->next;
774         so->next = sodel->next;
775         if (!so->next)
776           solib_end = so;
777         DEBUG_EVENTS (("gdb: Unloading dll \"%s\".\n", sodel->so_name));
778
779         windows_free_so (sodel);
780         solib_add (NULL, 0, NULL, auto_solib_add);
781         return 1;
782       }
783
784   error (_("Error: dll starting at %s not found."),
785            host_address_to_string (lpBaseOfDll));
786
787   return 0;
788 }
789
790 /* Clear list of loaded DLLs. */
791 static void
792 windows_clear_solib (void)
793 {
794   solib_start.next = NULL;
795   solib_end = &solib_start;
796 }
797
798 /* Load DLL symbol info. */
799 void
800 dll_symbol_command (char *args, int from_tty)
801 {
802   int n;
803   dont_repeat ();
804
805   if (args == NULL)
806     error (_("dll-symbols requires a file name"));
807
808   n = strlen (args);
809   if (n > 4 && strcasecmp (args + n - 4, ".dll") != 0)
810     {
811       char *newargs = (char *) alloca (n + 4 + 1);
812       strcpy (newargs, args);
813       strcat (newargs, ".dll");
814       args = newargs;
815     }
816
817   safe_symbol_file_add (args, from_tty, NULL, 0, OBJF_SHARED | OBJF_USERLOADED);
818 }
819
820 /* Handle DEBUG_STRING output from child process.
821    Cygwin prepends its messages with a "cygwin:".  Interpret this as
822    a Cygwin signal.  Otherwise just print the string as a warning. */
823 static int
824 handle_output_debug_string (struct target_waitstatus *ourstatus)
825 {
826   char *s = NULL;
827   int retval = 0;
828
829   if (!target_read_string
830         ((CORE_ADDR) (uintptr_t) current_event.u.DebugString.lpDebugStringData,
831         &s, 1024, 0)
832       || !s || !*s)
833     /* nothing to do */;
834   else if (strncmp (s, _CYGWIN_SIGNAL_STRING, sizeof (_CYGWIN_SIGNAL_STRING) - 1) != 0)
835     {
836 #ifdef __CYGWIN__
837       if (strncmp (s, "cYg", 3) != 0)
838 #endif
839         warning (("%s"), s);
840     }
841 #ifdef __COPY_CONTEXT_SIZE
842   else
843     {
844       /* Got a cygwin signal marker.  A cygwin signal is followed by the signal number
845          itself and then optionally followed by the thread id and address to saved context
846          within the DLL.  If these are supplied, then the given thread is assumed to have
847          issued the signal and the context from the thread is assumed to be stored at the
848          given address in the inferior.  Tell gdb to treat this like a real signal.  */
849       char *p;
850       int sig = strtol (s + sizeof (_CYGWIN_SIGNAL_STRING) - 1, &p, 0);
851       int gotasig = target_signal_from_host (sig);
852       ourstatus->value.sig = gotasig;
853       if (gotasig)
854         {
855           LPCVOID x;
856           DWORD n;
857           ourstatus->kind = TARGET_WAITKIND_STOPPED;
858           retval = strtoul (p, &p, 0);
859           if (!retval)
860             retval = main_thread_id;
861           else if ((x = (LPCVOID) strtoul (p, &p, 0))
862                    && ReadProcessMemory (current_process_handle, x,
863                                          &saved_context, __COPY_CONTEXT_SIZE, &n)
864                    && n == __COPY_CONTEXT_SIZE)
865             have_saved_context = 1;
866           current_event.dwThreadId = retval;
867         }
868     }
869 #endif
870
871   if (s)
872     xfree (s);
873   return retval;
874 }
875
876 static int
877 display_selector (HANDLE thread, DWORD sel)
878 {
879   LDT_ENTRY info;
880   if (GetThreadSelectorEntry (thread, sel, &info))
881     {
882       int base, limit;
883       printf_filtered ("0x%03lx: ", sel);
884       if (!info.HighWord.Bits.Pres)
885         {
886           puts_filtered ("Segment not present\n");
887           return 0;
888         }
889       base = (info.HighWord.Bits.BaseHi << 24) +
890              (info.HighWord.Bits.BaseMid << 16)
891              + info.BaseLow;
892       limit = (info.HighWord.Bits.LimitHi << 16) + info.LimitLow;
893       if (info.HighWord.Bits.Granularity)
894         limit = (limit << 12) | 0xfff;
895       printf_filtered ("base=0x%08x limit=0x%08x", base, limit);
896       if (info.HighWord.Bits.Default_Big)
897         puts_filtered(" 32-bit ");
898       else
899         puts_filtered(" 16-bit ");
900       switch ((info.HighWord.Bits.Type & 0xf) >> 1)
901         {
902         case 0:
903           puts_filtered ("Data (Read-Only, Exp-up");
904           break;
905         case 1:
906           puts_filtered ("Data (Read/Write, Exp-up");
907           break;
908         case 2:
909           puts_filtered ("Unused segment (");
910           break;
911         case 3:
912           puts_filtered ("Data (Read/Write, Exp-down");
913           break;
914         case 4:
915           puts_filtered ("Code (Exec-Only, N.Conf");
916           break;
917         case 5:
918           puts_filtered ("Code (Exec/Read, N.Conf");
919           break;
920         case 6:
921           puts_filtered ("Code (Exec-Only, Conf");
922           break;
923         case 7:
924           puts_filtered ("Code (Exec/Read, Conf");
925           break;
926         default:
927           printf_filtered ("Unknown type 0x%x",info.HighWord.Bits.Type);
928         }
929       if ((info.HighWord.Bits.Type & 0x1) == 0)
930         puts_filtered(", N.Acc");
931       puts_filtered (")\n");
932       if ((info.HighWord.Bits.Type & 0x10) == 0)
933         puts_filtered("System selector ");
934       printf_filtered ("Priviledge level = %d. ", info.HighWord.Bits.Dpl);
935       if (info.HighWord.Bits.Granularity)
936         puts_filtered ("Page granular.\n");
937       else
938         puts_filtered ("Byte granular.\n");
939       return 1;
940     }
941   else
942     {
943       printf_filtered ("Invalid selector 0x%lx.\n",sel);
944       return 0;
945     }
946 }
947
948 static void
949 display_selectors (char * args, int from_tty)
950 {
951   if (!current_thread)
952     {
953       puts_filtered ("Impossible to display selectors now.\n");
954       return;
955     }
956   if (!args)
957     {
958
959       puts_filtered ("Selector $cs\n");
960       display_selector (current_thread->h,
961         current_thread->context.SegCs);
962       puts_filtered ("Selector $ds\n");
963       display_selector (current_thread->h,
964         current_thread->context.SegDs);
965       puts_filtered ("Selector $es\n");
966       display_selector (current_thread->h,
967         current_thread->context.SegEs);
968       puts_filtered ("Selector $ss\n");
969       display_selector (current_thread->h,
970         current_thread->context.SegSs);
971       puts_filtered ("Selector $fs\n");
972       display_selector (current_thread->h,
973         current_thread->context.SegFs);
974       puts_filtered ("Selector $gs\n");
975       display_selector (current_thread->h,
976         current_thread->context.SegGs);
977     }
978   else
979     {
980       int sel;
981       sel = parse_and_eval_long (args);
982       printf_filtered ("Selector \"%s\"\n",args);
983       display_selector (current_thread->h, sel);
984     }
985 }
986
987 static struct cmd_list_element *info_w32_cmdlist = NULL;
988
989 static void
990 info_w32_command (char *args, int from_tty)
991 {
992   help_list (info_w32_cmdlist, "info w32 ", class_info, gdb_stdout);
993 }
994
995
996 #define DEBUG_EXCEPTION_SIMPLE(x)       if (debug_exceptions) \
997   printf_unfiltered ("gdb: Target exception %s at %s\n", x, \
998     host_address_to_string (\
999       current_event.u.Exception.ExceptionRecord.ExceptionAddress))
1000
1001 static int
1002 handle_exception (struct target_waitstatus *ourstatus)
1003 {
1004   thread_info *th;
1005   DWORD code = current_event.u.Exception.ExceptionRecord.ExceptionCode;
1006
1007   ourstatus->kind = TARGET_WAITKIND_STOPPED;
1008
1009   /* Record the context of the current thread */
1010   th = thread_rec (current_event.dwThreadId, -1);
1011
1012   switch (code)
1013     {
1014     case EXCEPTION_ACCESS_VIOLATION:
1015       DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ACCESS_VIOLATION");
1016       ourstatus->value.sig = TARGET_SIGNAL_SEGV;
1017 #ifdef __CYGWIN__
1018       {
1019         /* See if the access violation happened within the cygwin DLL itself.  Cygwin uses
1020            a kind of exception handling to deal with passed-in invalid addresses. gdb
1021            should not treat these as real SEGVs since they will be silently handled by
1022            cygwin.  A real SEGV will (theoretically) be caught by cygwin later in the process
1023            and will be sent as a cygwin-specific-signal.  So, ignore SEGVs if they show up
1024            within the text segment of the DLL itself. */
1025         char *fn;
1026         CORE_ADDR addr = (CORE_ADDR) (uintptr_t) current_event.u.Exception.ExceptionRecord.ExceptionAddress;
1027         if ((!cygwin_exceptions && (addr >= cygwin_load_start && addr < cygwin_load_end))
1028             || (find_pc_partial_function (addr, &fn, NULL, NULL)
1029                 && strncmp (fn, "KERNEL32!IsBad", strlen ("KERNEL32!IsBad")) == 0))
1030           return 0;
1031       }
1032 #endif
1033       break;
1034     case STATUS_STACK_OVERFLOW:
1035       DEBUG_EXCEPTION_SIMPLE ("STATUS_STACK_OVERFLOW");
1036       ourstatus->value.sig = TARGET_SIGNAL_SEGV;
1037       break;
1038     case STATUS_FLOAT_DENORMAL_OPERAND:
1039       DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DENORMAL_OPERAND");
1040       ourstatus->value.sig = TARGET_SIGNAL_FPE;
1041       break;
1042     case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
1043       DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ARRAY_BOUNDS_EXCEEDED");
1044       ourstatus->value.sig = TARGET_SIGNAL_FPE;
1045       break;
1046     case STATUS_FLOAT_INEXACT_RESULT:
1047       DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INEXACT_RESULT");
1048       ourstatus->value.sig = TARGET_SIGNAL_FPE;
1049       break;
1050     case STATUS_FLOAT_INVALID_OPERATION:
1051       DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INVALID_OPERATION");
1052       ourstatus->value.sig = TARGET_SIGNAL_FPE;
1053       break;
1054     case STATUS_FLOAT_OVERFLOW:
1055       DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_OVERFLOW");
1056       ourstatus->value.sig = TARGET_SIGNAL_FPE;
1057       break;
1058     case STATUS_FLOAT_STACK_CHECK:
1059       DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_STACK_CHECK");
1060       ourstatus->value.sig = TARGET_SIGNAL_FPE;
1061       break;
1062     case STATUS_FLOAT_UNDERFLOW:
1063       DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_UNDERFLOW");
1064       ourstatus->value.sig = TARGET_SIGNAL_FPE;
1065       break;
1066     case STATUS_FLOAT_DIVIDE_BY_ZERO:
1067       DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DIVIDE_BY_ZERO");
1068       ourstatus->value.sig = TARGET_SIGNAL_FPE;
1069       break;
1070     case STATUS_INTEGER_DIVIDE_BY_ZERO:
1071       DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_DIVIDE_BY_ZERO");
1072       ourstatus->value.sig = TARGET_SIGNAL_FPE;
1073       break;
1074     case STATUS_INTEGER_OVERFLOW:
1075       DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_OVERFLOW");
1076       ourstatus->value.sig = TARGET_SIGNAL_FPE;
1077       break;
1078     case EXCEPTION_BREAKPOINT:
1079       DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_BREAKPOINT");
1080       ourstatus->value.sig = TARGET_SIGNAL_TRAP;
1081       break;
1082     case DBG_CONTROL_C:
1083       DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_C");
1084       ourstatus->value.sig = TARGET_SIGNAL_INT;
1085       break;
1086     case DBG_CONTROL_BREAK:
1087       DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_BREAK");
1088       ourstatus->value.sig = TARGET_SIGNAL_INT;
1089       break;
1090     case EXCEPTION_SINGLE_STEP:
1091       DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_SINGLE_STEP");
1092       ourstatus->value.sig = TARGET_SIGNAL_TRAP;
1093       break;
1094     case EXCEPTION_ILLEGAL_INSTRUCTION:
1095       DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ILLEGAL_INSTRUCTION");
1096       ourstatus->value.sig = TARGET_SIGNAL_ILL;
1097       break;
1098     case EXCEPTION_PRIV_INSTRUCTION:
1099       DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_PRIV_INSTRUCTION");
1100       ourstatus->value.sig = TARGET_SIGNAL_ILL;
1101       break;
1102     case EXCEPTION_NONCONTINUABLE_EXCEPTION:
1103       DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_NONCONTINUABLE_EXCEPTION");
1104       ourstatus->value.sig = TARGET_SIGNAL_ILL;
1105       break;
1106     default:
1107       /* Treat unhandled first chance exceptions specially. */
1108       if (current_event.u.Exception.dwFirstChance)
1109         return -1;
1110       printf_unfiltered ("gdb: unknown target exception 0x%08lx at %s\n",
1111         current_event.u.Exception.ExceptionRecord.ExceptionCode,
1112         host_address_to_string (
1113           current_event.u.Exception.ExceptionRecord.ExceptionAddress));
1114       ourstatus->value.sig = TARGET_SIGNAL_UNKNOWN;
1115       break;
1116     }
1117   exception_count++;
1118   last_sig = ourstatus->value.sig;
1119   return 1;
1120 }
1121
1122 /* Resume all artificially suspended threads if we are continuing
1123    execution */
1124 static BOOL
1125 windows_continue (DWORD continue_status, int id)
1126 {
1127   int i;
1128   thread_info *th;
1129   BOOL res;
1130
1131   DEBUG_EVENTS (("ContinueDebugEvent (cpid=%ld, ctid=%ld, %s);\n",
1132                   current_event.dwProcessId, current_event.dwThreadId,
1133                   continue_status == DBG_CONTINUE ?
1134                   "DBG_CONTINUE" : "DBG_EXCEPTION_NOT_HANDLED"));
1135
1136   for (th = &thread_head; (th = th->next) != NULL;)
1137     if ((id == -1 || id == (int) th->id)
1138         && th->suspended)
1139       {
1140         if (debug_registers_changed)
1141           {
1142             th->context.ContextFlags |= CONTEXT_DEBUG_REGISTERS;
1143             th->context.Dr0 = dr[0];
1144             th->context.Dr1 = dr[1];
1145             th->context.Dr2 = dr[2];
1146             th->context.Dr3 = dr[3];
1147             th->context.Dr6 = DR6_CLEAR_VALUE;
1148             th->context.Dr7 = dr[7];
1149           }
1150         if (th->context.ContextFlags)
1151           {
1152             CHECK (SetThreadContext (th->h, &th->context));
1153             th->context.ContextFlags = 0;
1154           }
1155         if (th->suspended > 0)
1156           (void) ResumeThread (th->h);
1157         th->suspended = 0;
1158       }
1159
1160   res = ContinueDebugEvent (current_event.dwProcessId,
1161                             current_event.dwThreadId,
1162                             continue_status);
1163
1164   debug_registers_changed = 0;
1165   return res;
1166 }
1167
1168 /* Called in pathological case where Windows fails to send a
1169    CREATE_PROCESS_DEBUG_EVENT after an attach.  */
1170 static DWORD
1171 fake_create_process (void)
1172 {
1173   current_process_handle = OpenProcess (PROCESS_ALL_ACCESS, FALSE,
1174                                         current_event.dwProcessId);
1175   if (current_process_handle != NULL)
1176     open_process_used = 1;
1177   else
1178     {
1179       error (_("OpenProcess call failed, GetLastError = %lud\n"),
1180        GetLastError ());
1181       /*  We can not debug anything in that case.  */
1182     }
1183   main_thread_id = current_event.dwThreadId;
1184   current_thread = windows_add_thread (ptid_build (current_event.dwProcessId, 0,
1185                                                    current_event.dwThreadId),
1186                                        current_event.u.CreateThread.hThread);
1187   return main_thread_id;
1188 }
1189
1190 static void
1191 windows_resume (struct target_ops *ops,
1192                 ptid_t ptid, int step, enum target_signal sig)
1193 {
1194   thread_info *th;
1195   DWORD continue_status = DBG_CONTINUE;
1196
1197   /* A specific PTID means `step only this thread id'.  */
1198   int resume_all = ptid_equal (ptid, minus_one_ptid);
1199
1200   /* If we're continuing all threads, it's the current inferior that
1201      should be handled specially.  */
1202   if (resume_all)
1203     ptid = inferior_ptid;
1204
1205   if (sig != TARGET_SIGNAL_0)
1206     {
1207       if (current_event.dwDebugEventCode != EXCEPTION_DEBUG_EVENT)
1208         {
1209           DEBUG_EXCEPT(("Cannot continue with signal %d here.\n",sig));
1210         }
1211       else if (sig == last_sig)
1212         continue_status = DBG_EXCEPTION_NOT_HANDLED;
1213       else
1214 #if 0
1215 /* This code does not seem to work, because
1216   the kernel does probably not consider changes in the ExceptionRecord
1217   structure when passing the exception to the inferior.
1218   Note that this seems possible in the exception handler itself.  */
1219         {
1220           int i;
1221           for (i = 0; xlate[i].them != -1; i++)
1222             if (xlate[i].us == sig)
1223               {
1224                 current_event.u.Exception.ExceptionRecord.ExceptionCode =
1225                   xlate[i].them;
1226                 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1227                 break;
1228               }
1229           if (continue_status == DBG_CONTINUE)
1230             {
1231               DEBUG_EXCEPT(("Cannot continue with signal %d.\n",sig));
1232             }
1233         }
1234 #endif
1235         DEBUG_EXCEPT(("Can only continue with recieved signal %d.\n",
1236           last_sig));
1237     }
1238
1239   last_sig = TARGET_SIGNAL_0;
1240
1241   DEBUG_EXEC (("gdb: windows_resume (pid=%d, tid=%ld, step=%d, sig=%d);\n",
1242                ptid_get_pid (ptid), ptid_get_tid (ptid), step, sig));
1243
1244   /* Get context for currently selected thread */
1245   th = thread_rec (ptid_get_tid (inferior_ptid), FALSE);
1246   if (th)
1247     {
1248       if (step)
1249         {
1250           /* Single step by setting t bit */
1251           windows_fetch_inferior_registers (ops,
1252                                             get_current_regcache (),
1253                                             gdbarch_ps_regnum (current_gdbarch));
1254           th->context.EFlags |= FLAG_TRACE_BIT;
1255         }
1256
1257       if (th->context.ContextFlags)
1258         {
1259           if (debug_registers_changed)
1260             {
1261               th->context.Dr0 = dr[0];
1262               th->context.Dr1 = dr[1];
1263               th->context.Dr2 = dr[2];
1264               th->context.Dr3 = dr[3];
1265               th->context.Dr6 = DR6_CLEAR_VALUE;
1266               th->context.Dr7 = dr[7];
1267             }
1268           CHECK (SetThreadContext (th->h, &th->context));
1269           th->context.ContextFlags = 0;
1270         }
1271     }
1272
1273   /* Allow continuing with the same signal that interrupted us.
1274      Otherwise complain. */
1275
1276   if (resume_all)
1277     windows_continue (continue_status, -1);
1278   else
1279     windows_continue (continue_status, ptid_get_tid (ptid));
1280 }
1281
1282 /* Ctrl-C handler used when the inferior is not run in the same console.  The
1283    handler is in charge of interrupting the inferior using DebugBreakProcess.
1284    Note that this function is not available prior to Windows XP.  In this case
1285    we emit a warning.  */
1286 BOOL WINAPI
1287 ctrl_c_handler (DWORD event_type)
1288 {
1289   const int attach_flag = current_inferior ()->attach_flag;
1290
1291   /* Only handle Ctrl-C event.  Ignore others.  */
1292   if (event_type != CTRL_C_EVENT)
1293     return FALSE;
1294
1295   /* If the inferior and the debugger share the same console, do nothing as
1296      the inferior has also received the Ctrl-C event.  */
1297   if (!new_console && !attach_flag)
1298     return TRUE;
1299
1300   if (!DebugBreakProcess (current_process_handle))
1301     warning (_("\
1302 Could not interrupt program.  Press Ctrl-c in the program console."));
1303
1304   /* Return true to tell that Ctrl-C has been handled.  */
1305   return TRUE;
1306 }
1307
1308 /* Get the next event from the child.  Return 1 if the event requires
1309    handling by WFI (or whatever).  */
1310 static int
1311 get_windows_debug_event (struct target_ops *ops,
1312                          int pid, struct target_waitstatus *ourstatus)
1313 {
1314   BOOL debug_event;
1315   DWORD continue_status, event_code;
1316   thread_info *th;
1317   static thread_info dummy_thread_info;
1318   int retval = 0;
1319
1320   last_sig = TARGET_SIGNAL_0;
1321
1322   if (!(debug_event = WaitForDebugEvent (&current_event, 1000)))
1323     goto out;
1324
1325   event_count++;
1326   continue_status = DBG_CONTINUE;
1327
1328   event_code = current_event.dwDebugEventCode;
1329   ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
1330   th = NULL;
1331   have_saved_context = 0;
1332
1333   switch (event_code)
1334     {
1335     case CREATE_THREAD_DEBUG_EVENT:
1336       DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%x code=%s)\n",
1337                      (unsigned) current_event.dwProcessId,
1338                      (unsigned) current_event.dwThreadId,
1339                      "CREATE_THREAD_DEBUG_EVENT"));
1340       if (saw_create != 1)
1341         {
1342           struct inferior *inf;
1343           inf = find_inferior_pid (current_event.dwProcessId);
1344           if (!saw_create && inf->attach_flag)
1345             {
1346               /* Kludge around a Windows bug where first event is a create
1347                  thread event.  Caused when attached process does not have
1348                  a main thread. */
1349               retval = fake_create_process ();
1350               if (retval)
1351                 saw_create++;
1352             }
1353           break;
1354         }
1355       /* Record the existence of this thread */
1356       retval = current_event.dwThreadId;
1357       th = windows_add_thread (ptid_build (current_event.dwProcessId, 0,
1358                                          current_event.dwThreadId),
1359                              current_event.u.CreateThread.hThread);
1360       break;
1361
1362     case EXIT_THREAD_DEBUG_EVENT:
1363       DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
1364                      (unsigned) current_event.dwProcessId,
1365                      (unsigned) current_event.dwThreadId,
1366                      "EXIT_THREAD_DEBUG_EVENT"));
1367       if (current_event.dwThreadId != main_thread_id)
1368         {
1369           windows_delete_thread (ptid_build (current_event.dwProcessId, 0,
1370                                            current_event.dwThreadId));
1371           th = &dummy_thread_info;
1372         }
1373       break;
1374
1375     case CREATE_PROCESS_DEBUG_EVENT:
1376       DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
1377                      (unsigned) current_event.dwProcessId,
1378                      (unsigned) current_event.dwThreadId,
1379                      "CREATE_PROCESS_DEBUG_EVENT"));
1380       CloseHandle (current_event.u.CreateProcessInfo.hFile);
1381       if (++saw_create != 1)
1382         break;
1383
1384       current_process_handle = current_event.u.CreateProcessInfo.hProcess;
1385       if (main_thread_id)
1386         windows_delete_thread (ptid_build (current_event.dwProcessId, 0,
1387                                            main_thread_id));
1388       main_thread_id = current_event.dwThreadId;
1389       /* Add the main thread */
1390       th = windows_add_thread (ptid_build (current_event.dwProcessId, 0,
1391                                            current_event.dwThreadId),
1392                                current_event.u.CreateProcessInfo.hThread);
1393       retval = current_event.dwThreadId;
1394       break;
1395
1396     case EXIT_PROCESS_DEBUG_EVENT:
1397       DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
1398                      (unsigned) current_event.dwProcessId,
1399                      (unsigned) current_event.dwThreadId,
1400                      "EXIT_PROCESS_DEBUG_EVENT"));
1401       if (saw_create != 1)
1402         break;
1403       ourstatus->kind = TARGET_WAITKIND_EXITED;
1404       ourstatus->value.integer = current_event.u.ExitProcess.dwExitCode;
1405       retval = main_thread_id;
1406       break;
1407
1408     case LOAD_DLL_DEBUG_EVENT:
1409       DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
1410                      (unsigned) current_event.dwProcessId,
1411                      (unsigned) current_event.dwThreadId,
1412                      "LOAD_DLL_DEBUG_EVENT"));
1413       CloseHandle (current_event.u.LoadDll.hFile);
1414       if (saw_create != 1)
1415         break;
1416       catch_errors (handle_load_dll, NULL, (char *) "", RETURN_MASK_ALL);
1417       ourstatus->kind = TARGET_WAITKIND_LOADED;
1418       ourstatus->value.integer = 0;
1419       retval = main_thread_id;
1420       break;
1421
1422     case UNLOAD_DLL_DEBUG_EVENT:
1423       DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
1424                      (unsigned) current_event.dwProcessId,
1425                      (unsigned) current_event.dwThreadId,
1426                      "UNLOAD_DLL_DEBUG_EVENT"));
1427       if (saw_create != 1)
1428         break;
1429       catch_errors (handle_unload_dll, NULL, (char *) "", RETURN_MASK_ALL);
1430       ourstatus->kind = TARGET_WAITKIND_LOADED;
1431       ourstatus->value.integer = 0;
1432       retval = main_thread_id;
1433       break;
1434
1435     case EXCEPTION_DEBUG_EVENT:
1436       DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
1437                      (unsigned) current_event.dwProcessId,
1438                      (unsigned) current_event.dwThreadId,
1439                      "EXCEPTION_DEBUG_EVENT"));
1440       if (saw_create != 1)
1441         break;
1442       switch (handle_exception (ourstatus))
1443         {
1444         case 0:
1445           continue_status = DBG_EXCEPTION_NOT_HANDLED;
1446           break;
1447         case 1:
1448           retval = current_event.dwThreadId;
1449           break;
1450         case -1:
1451           last_sig = 1;
1452           continue_status = -1;
1453           break;
1454         }
1455       break;
1456
1457     case OUTPUT_DEBUG_STRING_EVENT:     /* message from the kernel */
1458       DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
1459                      (unsigned) current_event.dwProcessId,
1460                      (unsigned) current_event.dwThreadId,
1461                      "OUTPUT_DEBUG_STRING_EVENT"));
1462       if (saw_create != 1)
1463         break;
1464       retval = handle_output_debug_string (ourstatus);
1465       break;
1466
1467     default:
1468       if (saw_create != 1)
1469         break;
1470       printf_unfiltered ("gdb: kernel event for pid=%ld tid=%ld\n",
1471                          (DWORD) current_event.dwProcessId,
1472                          (DWORD) current_event.dwThreadId);
1473       printf_unfiltered ("                 unknown event code %ld\n",
1474                          current_event.dwDebugEventCode);
1475       break;
1476     }
1477
1478   if (!retval || saw_create != 1)
1479     {
1480       if (continue_status == -1)
1481         windows_resume (ops, minus_one_ptid, 0, 1);
1482       else
1483         CHECK (windows_continue (continue_status, -1));
1484     }
1485   else
1486     {
1487       inferior_ptid = ptid_build (current_event.dwProcessId, 0,
1488                                   retval);
1489       current_thread = th ?: thread_rec (current_event.dwThreadId, TRUE);
1490     }
1491
1492 out:
1493   return retval;
1494 }
1495
1496 /* Wait for interesting events to occur in the target process.  */
1497 static ptid_t
1498 windows_wait (struct target_ops *ops,
1499               ptid_t ptid, struct target_waitstatus *ourstatus, int options)
1500 {
1501   int pid = -1;
1502
1503   target_terminal_ours ();
1504
1505   /* We loop when we get a non-standard exception rather than return
1506      with a SPURIOUS because resume can try and step or modify things,
1507      which needs a current_thread->h.  But some of these exceptions mark
1508      the birth or death of threads, which mean that the current thread
1509      isn't necessarily what you think it is. */
1510
1511   while (1)
1512     {
1513       int retval;
1514
1515       /* If the user presses Ctrl-c while the debugger is waiting
1516          for an event, he expects the debugger to interrupt his program
1517          and to get the prompt back.  There are two possible situations:
1518
1519            - The debugger and the program do not share the console, in
1520              which case the Ctrl-c event only reached the debugger.
1521              In that case, the ctrl_c handler will take care of interrupting
1522              the inferior. Note that this case is working starting with
1523              Windows XP. For Windows 2000, Ctrl-C should be pressed in the
1524              inferior console.
1525
1526            - The debugger and the program share the same console, in which
1527              case both debugger and inferior will receive the Ctrl-c event.
1528              In that case the ctrl_c handler will ignore the event, as the
1529              Ctrl-c event generated inside the inferior will trigger the
1530              expected debug event.
1531
1532              FIXME: brobecker/2008-05-20: If the inferior receives the
1533              signal first and the delay until GDB receives that signal
1534              is sufficiently long, GDB can sometimes receive the SIGINT
1535              after we have unblocked the CTRL+C handler.  This would
1536              lead to the debugger stopping prematurely while handling
1537              the new-thread event that comes with the handling of the SIGINT
1538              inside the inferior, and then stop again immediately when
1539              the user tries to resume the execution in the inferior.
1540              This is a classic race that we should try to fix one day.  */
1541       SetConsoleCtrlHandler (&ctrl_c_handler, TRUE);
1542       retval = get_windows_debug_event (ops, pid, ourstatus);
1543       SetConsoleCtrlHandler (&ctrl_c_handler, FALSE);
1544
1545       if (retval)
1546         return ptid_build (current_event.dwProcessId, 0, retval);
1547       else
1548         {
1549           int detach = 0;
1550
1551           if (deprecated_ui_loop_hook != NULL)
1552             detach = deprecated_ui_loop_hook (0);
1553
1554           if (detach)
1555             windows_kill_inferior (ops);
1556         }
1557     }
1558 }
1559
1560 static void
1561 do_initial_windows_stuff (struct target_ops *ops, DWORD pid, int attaching)
1562 {
1563   extern int stop_after_trap;
1564   int i;
1565   struct inferior *inf;
1566   struct thread_info *tp;
1567
1568   last_sig = TARGET_SIGNAL_0;
1569   event_count = 0;
1570   exception_count = 0;
1571   open_process_used = 0;
1572   debug_registers_changed = 0;
1573   debug_registers_used = 0;
1574   for (i = 0; i < sizeof (dr) / sizeof (dr[0]); i++)
1575     dr[i] = 0;
1576 #ifdef __CYGWIN__
1577   cygwin_load_start = cygwin_load_end = 0;
1578 #endif
1579   current_event.dwProcessId = pid;
1580   memset (&current_event, 0, sizeof (current_event));
1581   push_target (ops);
1582   disable_breakpoints_in_shlibs ();
1583   windows_clear_solib ();
1584   clear_proceed_status ();
1585   init_wait_for_inferior ();
1586
1587   inf = add_inferior (pid);
1588   inf->attach_flag = attaching;
1589
1590   /* Make the new process the current inferior, so terminal handling
1591      can rely on it.  When attaching, we don't know about any thread
1592      id here, but that's OK --- nothing should be referencing the
1593      current thread until we report an event out of windows_wait.  */
1594   inferior_ptid = pid_to_ptid (pid);
1595
1596   terminal_init_inferior_with_pgrp (pid);
1597   target_terminal_inferior ();
1598
1599   inf->stop_soon = STOP_QUIETLY;
1600   while (1)
1601     {
1602       stop_after_trap = 1;
1603       wait_for_inferior (0);
1604       tp = inferior_thread ();
1605       if (tp->stop_signal != TARGET_SIGNAL_TRAP)
1606         resume (0, tp->stop_signal);
1607       else
1608         break;
1609     }
1610
1611   inf->stop_soon = NO_STOP_QUIETLY;
1612   stop_after_trap = 0;
1613   return;
1614 }
1615
1616 /* Try to set or remove a user privilege to the current process.  Return -1
1617    if that fails, the previous setting of that privilege otherwise.
1618
1619    This code is copied from the Cygwin source code and rearranged to allow
1620    dynamically loading of the needed symbols from advapi32 which is only
1621    available on NT/2K/XP. */
1622 static int
1623 set_process_privilege (const char *privilege, BOOL enable)
1624 {
1625   HANDLE token_hdl = NULL;
1626   LUID restore_priv;
1627   TOKEN_PRIVILEGES new_priv, orig_priv;
1628   int ret = -1;
1629   DWORD size;
1630
1631   if (!OpenProcessToken (GetCurrentProcess (),
1632                          TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
1633                          &token_hdl))
1634     goto out;
1635
1636   if (!LookupPrivilegeValueA (NULL, privilege, &restore_priv))
1637     goto out;
1638
1639   new_priv.PrivilegeCount = 1;
1640   new_priv.Privileges[0].Luid = restore_priv;
1641   new_priv.Privileges[0].Attributes = enable ? SE_PRIVILEGE_ENABLED : 0;
1642
1643   if (!AdjustTokenPrivileges (token_hdl, FALSE, &new_priv,
1644                               sizeof orig_priv, &orig_priv, &size))
1645     goto out;
1646 #if 0
1647   /* Disabled, otherwise every `attach' in an unprivileged user session
1648      would raise the "Failed to get SE_DEBUG_NAME privilege" warning in
1649      windows_attach(). */
1650   /* AdjustTokenPrivileges returns TRUE even if the privilege could not
1651      be enabled. GetLastError () returns an correct error code, though. */
1652   if (enable && GetLastError () == ERROR_NOT_ALL_ASSIGNED)
1653     goto out;
1654 #endif
1655
1656   ret = orig_priv.Privileges[0].Attributes == SE_PRIVILEGE_ENABLED ? 1 : 0;
1657
1658 out:
1659   if (token_hdl)
1660     CloseHandle (token_hdl);
1661
1662   return ret;
1663 }
1664
1665 /* Attach to process PID, then initialize for debugging it.  */
1666 static void
1667 windows_attach (struct target_ops *ops, char *args, int from_tty)
1668 {
1669   BOOL ok;
1670   DWORD pid;
1671
1672   if (!args)
1673     error_no_arg (_("process-id to attach"));
1674
1675   if (set_process_privilege (SE_DEBUG_NAME, TRUE) < 0)
1676     {
1677       printf_unfiltered ("Warning: Failed to get SE_DEBUG_NAME privilege\n");
1678       printf_unfiltered ("This can cause attach to fail on Windows NT/2K/XP\n");
1679     }
1680
1681   pid = strtoul (args, 0, 0);           /* Windows pid */
1682
1683   windows_init_thread_list ();
1684   ok = DebugActiveProcess (pid);
1685   saw_create = 0;
1686
1687 #ifdef __CYGWIN__
1688   if (!ok)
1689     {
1690       /* Try fall back to Cygwin pid */
1691       pid = cygwin_internal (CW_CYGWIN_PID_TO_WINPID, pid);
1692
1693       if (pid > 0)
1694         ok = DebugActiveProcess (pid);
1695   }
1696 #endif
1697
1698   if (!ok)
1699     error (_("Can't attach to process."));
1700
1701   DebugSetProcessKillOnExit (FALSE);
1702
1703   if (from_tty)
1704     {
1705       char *exec_file = (char *) get_exec_file (0);
1706
1707       if (exec_file)
1708         printf_unfiltered ("Attaching to program `%s', %s\n", exec_file,
1709                            target_pid_to_str (pid_to_ptid (pid)));
1710       else
1711         printf_unfiltered ("Attaching to %s\n",
1712                            target_pid_to_str (pid_to_ptid (pid)));
1713
1714       gdb_flush (gdb_stdout);
1715     }
1716
1717   do_initial_windows_stuff (ops, pid, 1);
1718   target_terminal_ours ();
1719 }
1720
1721 static void
1722 windows_detach (struct target_ops *ops, char *args, int from_tty)
1723 {
1724   int detached = 1;
1725
1726   ptid_t ptid = {-1};
1727   windows_resume (ops, ptid, 0, TARGET_SIGNAL_0);
1728
1729   if (!DebugActiveProcessStop (current_event.dwProcessId))
1730     {
1731       error (_("Can't detach process %lu (error %lu)"),
1732              current_event.dwProcessId, GetLastError ());
1733       detached = 0;
1734     }
1735   DebugSetProcessKillOnExit (FALSE);
1736
1737   if (detached && from_tty)
1738     {
1739       char *exec_file = get_exec_file (0);
1740       if (exec_file == 0)
1741         exec_file = "";
1742       printf_unfiltered ("Detaching from program: %s, Pid %lu\n", exec_file,
1743                          current_event.dwProcessId);
1744       gdb_flush (gdb_stdout);
1745     }
1746
1747   inferior_ptid = null_ptid;
1748   detach_inferior (current_event.dwProcessId);
1749
1750   unpush_target (ops);
1751 }
1752
1753 static char *
1754 windows_pid_to_exec_file (int pid)
1755 {
1756   static char path[MAX_PATH + 1];
1757
1758 #ifdef __CYGWIN__
1759   /* Try to find exe name as symlink target of /proc/<pid>/exe */
1760   int nchars;
1761   char procexe[sizeof ("/proc/4294967295/exe")];
1762   sprintf (procexe, "/proc/%u/exe", pid);
1763   nchars = readlink (procexe, path, sizeof(path));
1764   if (nchars > 0 && nchars < sizeof (path))
1765     {
1766       path[nchars] = '\0';      /* Got it */
1767       return path;
1768     }
1769 #endif
1770
1771   /* If we get here then either Cygwin is hosed, this isn't a Cygwin version
1772      of gdb, or we're trying to debug a non-Cygwin windows executable. */
1773   if (!get_module_name (0, path))
1774     path[0] = '\0';
1775
1776   return path;
1777 }
1778
1779 /* Print status information about what we're accessing.  */
1780
1781 static void
1782 windows_files_info (struct target_ops *ignore)
1783 {
1784   struct inferior *inf = current_inferior ();
1785
1786   printf_unfiltered ("\tUsing the running image of %s %s.\n",
1787                      inf->attach_flag ? "attached" : "child",
1788                      target_pid_to_str (inferior_ptid));
1789 }
1790
1791 static void
1792 windows_open (char *arg, int from_tty)
1793 {
1794   error (_("Use the \"run\" command to start a Unix child process."));
1795 }
1796
1797 /* Start an inferior windows child process and sets inferior_ptid to its pid.
1798    EXEC_FILE is the file to run.
1799    ALLARGS is a string containing the arguments to the program.
1800    ENV is the environment vector to pass.  Errors reported with error().  */
1801
1802 static void
1803 windows_create_inferior (struct target_ops *ops, char *exec_file,
1804                        char *allargs, char **in_env, int from_tty)
1805 {
1806   STARTUPINFO si;
1807   PROCESS_INFORMATION pi;
1808   BOOL ret;
1809   DWORD flags;
1810   char *args;
1811   char real_path[MAXPATHLEN];
1812   char *toexec;
1813   char shell[MAX_PATH + 1]; /* Path to shell */
1814   const char *sh;
1815 #ifdef __CYGWIN__
1816   int tty;
1817   int ostdin, ostdout, ostderr;
1818 #else
1819   HANDLE tty;
1820 #endif
1821   const char *inferior_io_terminal = get_inferior_io_terminal ();
1822
1823   if (!exec_file)
1824     error (_("No executable specified, use `target exec'."));
1825
1826   memset (&si, 0, sizeof (si));
1827   si.cb = sizeof (si);
1828
1829 #ifdef __CYGWIN__
1830   if (!useshell)
1831     {
1832       flags = DEBUG_ONLY_THIS_PROCESS;
1833       cygwin_conv_to_win32_path (exec_file, real_path);
1834       toexec = real_path;
1835     }
1836   else
1837     {
1838       char *newallargs;
1839       sh = getenv ("SHELL");
1840       if (!sh)
1841         sh = "/bin/sh";
1842       cygwin_conv_to_win32_path (sh, shell);
1843       newallargs = alloca (sizeof (" -c 'exec  '") + strlen (exec_file)
1844                            + strlen (allargs) + 2);
1845       sprintf (newallargs, " -c 'exec %s %s'", exec_file, allargs);
1846       allargs = newallargs;
1847       toexec = shell;
1848       flags = DEBUG_PROCESS;
1849     }
1850 #else
1851   toexec = exec_file;
1852   flags = DEBUG_ONLY_THIS_PROCESS;
1853 #endif
1854
1855   if (new_group)
1856     flags |= CREATE_NEW_PROCESS_GROUP;
1857
1858   if (new_console)
1859     flags |= CREATE_NEW_CONSOLE;
1860
1861   args = alloca (strlen (toexec) + strlen (allargs) + 2);
1862   strcpy (args, toexec);
1863   strcat (args, " ");
1864   strcat (args, allargs);
1865
1866 #ifdef __CYGWIN__
1867   /* Prepare the environment vars for CreateProcess.  */
1868   cygwin_internal (CW_SYNC_WINENV);
1869
1870   if (!inferior_io_terminal)
1871     tty = ostdin = ostdout = ostderr = -1;
1872   else
1873     {
1874       tty = open (inferior_io_terminal, O_RDWR | O_NOCTTY);
1875       if (tty < 0)
1876         {
1877           print_sys_errmsg (inferior_io_terminal, errno);
1878           ostdin = ostdout = ostderr = -1;
1879         }
1880       else
1881         {
1882           ostdin = dup (0);
1883           ostdout = dup (1);
1884           ostderr = dup (2);
1885           dup2 (tty, 0);
1886           dup2 (tty, 1);
1887           dup2 (tty, 2);
1888         }
1889     }
1890 #else
1891   if (!inferior_io_terminal)
1892     tty = INVALID_HANDLE_VALUE;
1893   else
1894     {
1895       SECURITY_ATTRIBUTES sa;
1896       sa.nLength = sizeof(sa);
1897       sa.lpSecurityDescriptor = 0;
1898       sa.bInheritHandle = TRUE;
1899       tty = CreateFileA (inferior_io_terminal, GENERIC_READ | GENERIC_WRITE,
1900                          0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
1901       if (tty == INVALID_HANDLE_VALUE)
1902         warning (_("Warning: Failed to open TTY %s, error %#x."),
1903                  inferior_io_terminal, (unsigned) GetLastError ());
1904       else
1905         {
1906           si.hStdInput = tty;
1907           si.hStdOutput = tty;
1908           si.hStdError = tty;
1909           si.dwFlags |= STARTF_USESTDHANDLES;
1910         }
1911     }
1912 #endif
1913
1914   windows_init_thread_list ();
1915   ret = CreateProcess (0,
1916                        args,    /* command line */
1917                        NULL,    /* Security */
1918                        NULL,    /* thread */
1919                        TRUE,    /* inherit handles */
1920                        flags,   /* start flags */
1921                        NULL,    /* environment */
1922                        NULL,    /* current directory */
1923                        &si,
1924                        &pi);
1925
1926 #ifdef __CYGWIN__
1927   if (tty >= 0)
1928     {
1929       close (tty);
1930       dup2 (ostdin, 0);
1931       dup2 (ostdout, 1);
1932       dup2 (ostderr, 2);
1933       close (ostdin);
1934       close (ostdout);
1935       close (ostderr);
1936     }
1937 #else
1938   if (tty != INVALID_HANDLE_VALUE)
1939     CloseHandle (tty);
1940 #endif
1941
1942   if (!ret)
1943     error (_("Error creating process %s, (error %d)."),
1944            exec_file, (unsigned) GetLastError ());
1945
1946   CloseHandle (pi.hThread);
1947   CloseHandle (pi.hProcess);
1948
1949   if (useshell && shell[0] != '\0')
1950     saw_create = -1;
1951   else
1952     saw_create = 0;
1953
1954   do_initial_windows_stuff (ops, pi.dwProcessId, 0);
1955
1956   /* windows_continue (DBG_CONTINUE, -1); */
1957 }
1958
1959 static void
1960 windows_mourn_inferior (struct target_ops *ops)
1961 {
1962   (void) windows_continue (DBG_CONTINUE, -1);
1963   i386_cleanup_dregs();
1964   if (open_process_used)
1965     {
1966       CHECK (CloseHandle (current_process_handle));
1967       open_process_used = 0;
1968     }
1969   unpush_target (ops);
1970   generic_mourn_inferior ();
1971 }
1972
1973 /* Send a SIGINT to the process group.  This acts just like the user typed a
1974    ^C on the controlling terminal. */
1975
1976 static void
1977 windows_stop (ptid_t ptid)
1978 {
1979   DEBUG_EVENTS (("gdb: GenerateConsoleCtrlEvent (CTRLC_EVENT, 0)\n"));
1980   CHECK (GenerateConsoleCtrlEvent (CTRL_C_EVENT, current_event.dwProcessId));
1981   registers_changed ();         /* refresh register state */
1982 }
1983
1984 static int
1985 windows_xfer_memory (CORE_ADDR memaddr, gdb_byte *our, int len,
1986                    int write, struct mem_attrib *mem,
1987                    struct target_ops *target)
1988 {
1989   SIZE_T done = 0;
1990   if (write)
1991     {
1992       DEBUG_MEM (("gdb: write target memory, %d bytes at 0x%08lx\n",
1993                   len, (DWORD) (uintptr_t) memaddr));
1994       if (!WriteProcessMemory (current_process_handle,
1995                                (LPVOID) (uintptr_t) memaddr, our,
1996                                len, &done))
1997         done = 0;
1998       FlushInstructionCache (current_process_handle,
1999                              (LPCVOID) (uintptr_t) memaddr, len);
2000     }
2001   else
2002     {
2003       DEBUG_MEM (("gdb: read target memory, %d bytes at 0x%08lx\n",
2004                   len, (DWORD) (uintptr_t) memaddr));
2005       if (!ReadProcessMemory (current_process_handle,
2006                               (LPCVOID) (uintptr_t) memaddr, our,
2007                               len, &done))
2008         done = 0;
2009     }
2010   return done;
2011 }
2012
2013 static void
2014 windows_kill_inferior (struct target_ops *ops)
2015 {
2016   CHECK (TerminateProcess (current_process_handle, 0));
2017
2018   for (;;)
2019     {
2020       if (!windows_continue (DBG_CONTINUE, -1))
2021         break;
2022       if (!WaitForDebugEvent (&current_event, INFINITE))
2023         break;
2024       if (current_event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
2025         break;
2026     }
2027
2028   target_mourn_inferior ();     /* or just windows_mourn_inferior? */
2029 }
2030
2031 static void
2032 windows_prepare_to_store (struct regcache *regcache)
2033 {
2034   /* Do nothing, since we can store individual regs */
2035 }
2036
2037 static int
2038 windows_can_run (void)
2039 {
2040   return 1;
2041 }
2042
2043 static void
2044 windows_close (int x)
2045 {
2046   DEBUG_EVENTS (("gdb: windows_close, inferior_ptid=%d\n",
2047                 PIDGET (inferior_ptid)));
2048 }
2049
2050 /* Convert pid to printable format. */
2051 static char *
2052 windows_pid_to_str (struct target_ops *ops, ptid_t ptid)
2053 {
2054   static char buf[80];
2055
2056   if (ptid_get_tid (ptid) != 0)
2057     {
2058       snprintf (buf, sizeof (buf), "Thread %d.0x%lx",
2059                 ptid_get_pid (ptid), ptid_get_tid (ptid));
2060       return buf;
2061     }
2062
2063   return normal_pid_to_str (ptid);
2064 }
2065
2066 static LONGEST
2067 windows_xfer_shared_libraries (struct target_ops *ops,
2068                              enum target_object object, const char *annex,
2069                              gdb_byte *readbuf, const gdb_byte *writebuf,
2070                              ULONGEST offset, LONGEST len)
2071 {
2072   struct obstack obstack;
2073   const char *buf;
2074   LONGEST len_avail;
2075   struct so_list *so;
2076
2077   if (writebuf)
2078     return -1;
2079
2080   obstack_init (&obstack);
2081   obstack_grow_str (&obstack, "<library-list>\n");
2082   for (so = solib_start.next; so; so = so->next)
2083     windows_xfer_shared_library (so->so_name, (CORE_ADDR) (uintptr_t) so->lm_info->load_addr,
2084                                  &obstack);
2085   obstack_grow_str0 (&obstack, "</library-list>\n");
2086
2087   buf = obstack_finish (&obstack);
2088   len_avail = strlen (buf);
2089   if (offset >= len_avail)
2090     return 0;
2091
2092   if (len > len_avail - offset)
2093     len = len_avail - offset;
2094   memcpy (readbuf, buf + offset, len);
2095
2096   obstack_free (&obstack, NULL);
2097   return len;
2098 }
2099
2100 static LONGEST
2101 windows_xfer_partial (struct target_ops *ops, enum target_object object,
2102                     const char *annex, gdb_byte *readbuf,
2103                     const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
2104 {
2105   switch (object)
2106     {
2107     case TARGET_OBJECT_MEMORY:
2108       if (readbuf)
2109         return (*ops->deprecated_xfer_memory) (offset, readbuf,
2110                                                len, 0/*read*/, NULL, ops);
2111       if (writebuf)
2112         return (*ops->deprecated_xfer_memory) (offset, (gdb_byte *) writebuf,
2113                                                len, 1/*write*/, NULL, ops);
2114       return -1;
2115
2116     case TARGET_OBJECT_LIBRARIES:
2117       return windows_xfer_shared_libraries (ops, object, annex, readbuf,
2118                                           writebuf, offset, len);
2119
2120     default:
2121       if (ops->beneath != NULL)
2122         return ops->beneath->to_xfer_partial (ops->beneath, object, annex,
2123                                               readbuf, writebuf, offset, len);
2124       return -1;
2125     }
2126 }
2127
2128 static ptid_t
2129 windows_get_ada_task_ptid (long lwp, long thread)
2130 {
2131   return ptid_build (ptid_get_pid (inferior_ptid), 0, lwp);
2132 }
2133
2134 static void
2135 init_windows_ops (void)
2136 {
2137   windows_ops.to_shortname = "child";
2138   windows_ops.to_longname = "Win32 child process";
2139   windows_ops.to_doc = "Win32 child process (started by the \"run\" command).";
2140   windows_ops.to_open = windows_open;
2141   windows_ops.to_close = windows_close;
2142   windows_ops.to_attach = windows_attach;
2143   windows_ops.to_attach_no_wait = 1;
2144   windows_ops.to_detach = windows_detach;
2145   windows_ops.to_resume = windows_resume;
2146   windows_ops.to_wait = windows_wait;
2147   windows_ops.to_fetch_registers = windows_fetch_inferior_registers;
2148   windows_ops.to_store_registers = windows_store_inferior_registers;
2149   windows_ops.to_prepare_to_store = windows_prepare_to_store;
2150   windows_ops.deprecated_xfer_memory = windows_xfer_memory;
2151   windows_ops.to_xfer_partial = windows_xfer_partial;
2152   windows_ops.to_files_info = windows_files_info;
2153   windows_ops.to_insert_breakpoint = memory_insert_breakpoint;
2154   windows_ops.to_remove_breakpoint = memory_remove_breakpoint;
2155   windows_ops.to_terminal_init = terminal_init_inferior;
2156   windows_ops.to_terminal_inferior = terminal_inferior;
2157   windows_ops.to_terminal_ours_for_output = terminal_ours_for_output;
2158   windows_ops.to_terminal_ours = terminal_ours;
2159   windows_ops.to_terminal_save_ours = terminal_save_ours;
2160   windows_ops.to_terminal_info = child_terminal_info;
2161   windows_ops.to_kill = windows_kill_inferior;
2162   windows_ops.to_create_inferior = windows_create_inferior;
2163   windows_ops.to_mourn_inferior = windows_mourn_inferior;
2164   windows_ops.to_can_run = windows_can_run;
2165   windows_ops.to_thread_alive = windows_thread_alive;
2166   windows_ops.to_pid_to_str = windows_pid_to_str;
2167   windows_ops.to_stop = windows_stop;
2168   windows_ops.to_stratum = process_stratum;
2169   windows_ops.to_has_all_memory = default_child_has_all_memory;
2170   windows_ops.to_has_memory = default_child_has_memory;
2171   windows_ops.to_has_stack = default_child_has_stack;
2172   windows_ops.to_has_registers = default_child_has_registers;
2173   windows_ops.to_has_execution = default_child_has_execution;
2174   windows_ops.to_pid_to_exec_file = windows_pid_to_exec_file;
2175   windows_ops.to_get_ada_task_ptid = windows_get_ada_task_ptid;
2176
2177   i386_use_watchpoints (&windows_ops);
2178
2179   i386_dr_low.set_control = cygwin_set_dr7;
2180   i386_dr_low.set_addr = cygwin_set_dr;
2181   i386_dr_low.reset_addr = NULL;
2182   i386_dr_low.get_status = cygwin_get_dr6;
2183
2184   /* i386_dr_low.debug_register_length field is set by
2185      calling i386_set_debug_register_length function
2186      in processor windows specific native file.  */
2187
2188   windows_ops.to_magic = OPS_MAGIC;
2189 }
2190
2191 static void
2192 set_windows_aliases (char *argv0)
2193 {
2194   add_info_alias ("dll", "sharedlibrary", 1);
2195 }
2196
2197 void
2198 _initialize_windows_nat (void)
2199 {
2200   struct cmd_list_element *c;
2201
2202   init_windows_ops ();
2203
2204   c = add_com ("dll-symbols", class_files, dll_symbol_command,
2205                _("Load dll library symbols from FILE."));
2206   set_cmd_completer (c, filename_completer);
2207
2208   add_com_alias ("sharedlibrary", "dll-symbols", class_alias, 1);
2209
2210   add_com_alias ("add-shared-symbol-files", "dll-symbols", class_alias, 1);
2211
2212   add_com_alias ("assf", "dll-symbols", class_alias, 1);
2213
2214 #ifdef __CYGWIN__
2215   add_setshow_boolean_cmd ("shell", class_support, &useshell, _("\
2216 Set use of shell to start subprocess."), _("\
2217 Show use of shell to start subprocess."), NULL,
2218                            NULL,
2219                            NULL, /* FIXME: i18n: */
2220                            &setlist, &showlist);
2221
2222   add_setshow_boolean_cmd ("cygwin-exceptions", class_support, &cygwin_exceptions, _("\
2223 Break when an exception is detected in the Cygwin DLL itself."), _("\
2224 Show whether gdb breaks on exceptions in the Cygwin DLL itself."), NULL,
2225                            NULL,
2226                            NULL, /* FIXME: i18n: */
2227                            &setlist, &showlist);
2228 #endif
2229
2230   add_setshow_boolean_cmd ("new-console", class_support, &new_console, _("\
2231 Set creation of new console when creating child process."), _("\
2232 Show creation of new console when creating child process."), NULL,
2233                            NULL,
2234                            NULL, /* FIXME: i18n: */
2235                            &setlist, &showlist);
2236
2237   add_setshow_boolean_cmd ("new-group", class_support, &new_group, _("\
2238 Set creation of new group when creating child process."), _("\
2239 Show creation of new group when creating child process."), NULL,
2240                            NULL,
2241                            NULL, /* FIXME: i18n: */
2242                            &setlist, &showlist);
2243
2244   add_setshow_boolean_cmd ("debugexec", class_support, &debug_exec, _("\
2245 Set whether to display execution in child process."), _("\
2246 Show whether to display execution in child process."), NULL,
2247                            NULL,
2248                            NULL, /* FIXME: i18n: */
2249                            &setlist, &showlist);
2250
2251   add_setshow_boolean_cmd ("debugevents", class_support, &debug_events, _("\
2252 Set whether to display kernel events in child process."), _("\
2253 Show whether to display kernel events in child process."), NULL,
2254                            NULL,
2255                            NULL, /* FIXME: i18n: */
2256                            &setlist, &showlist);
2257
2258   add_setshow_boolean_cmd ("debugmemory", class_support, &debug_memory, _("\
2259 Set whether to display memory accesses in child process."), _("\
2260 Show whether to display memory accesses in child process."), NULL,
2261                            NULL,
2262                            NULL, /* FIXME: i18n: */
2263                            &setlist, &showlist);
2264
2265   add_setshow_boolean_cmd ("debugexceptions", class_support,
2266                            &debug_exceptions, _("\
2267 Set whether to display kernel exceptions in child process."), _("\
2268 Show whether to display kernel exceptions in child process."), NULL,
2269                            NULL,
2270                            NULL, /* FIXME: i18n: */
2271                            &setlist, &showlist);
2272
2273   add_prefix_cmd ("w32", class_info, info_w32_command,
2274                   _("Print information specific to Win32 debugging."),
2275                   &info_w32_cmdlist, "info w32 ", 0, &infolist);
2276
2277   add_cmd ("selector", class_info, display_selectors,
2278            _("Display selectors infos."),
2279            &info_w32_cmdlist);
2280   add_target (&windows_ops);
2281   deprecated_init_ui_hook = set_windows_aliases;
2282 }
2283
2284 /* Hardware watchpoint support, adapted from go32-nat.c code.  */
2285
2286 /* Pass the address ADDR to the inferior in the I'th debug register.
2287    Here we just store the address in dr array, the registers will be
2288    actually set up when windows_continue is called.  */
2289 static void
2290 cygwin_set_dr (int i, CORE_ADDR addr)
2291 {
2292   if (i < 0 || i > 3)
2293     internal_error (__FILE__, __LINE__,
2294                     _("Invalid register %d in cygwin_set_dr.\n"), i);
2295   dr[i] = addr;
2296   debug_registers_changed = 1;
2297   debug_registers_used = 1;
2298 }
2299
2300 /* Pass the value VAL to the inferior in the DR7 debug control
2301    register.  Here we just store the address in D_REGS, the watchpoint
2302    will be actually set up in windows_wait.  */
2303 static void
2304 cygwin_set_dr7 (unsigned long val)
2305 {
2306   dr[7] = (CORE_ADDR) val;
2307   debug_registers_changed = 1;
2308   debug_registers_used = 1;
2309 }
2310
2311 /* Get the value of the DR6 debug status register from the inferior.
2312    Here we just return the value stored in dr[6]
2313    by the last call to thread_rec for current_event.dwThreadId id.  */
2314 static unsigned long
2315 cygwin_get_dr6 (void)
2316 {
2317   return (unsigned long) dr[6];
2318 }
2319
2320 /* Determine if the thread referenced by "ptid" is alive
2321    by "polling" it.  If WaitForSingleObject returns WAIT_OBJECT_0
2322    it means that the thread has died.  Otherwise it is assumed to be alive. */
2323 static int
2324 windows_thread_alive (struct target_ops *ops, ptid_t ptid)
2325 {
2326   int tid;
2327
2328   gdb_assert (ptid_get_tid (ptid) != 0);
2329   tid = ptid_get_tid (ptid);
2330
2331   return WaitForSingleObject (thread_rec (tid, FALSE)->h, 0) == WAIT_OBJECT_0 ?
2332     FALSE : TRUE;
2333 }
2334
2335 void
2336 _initialize_check_for_gdb_ini (void)
2337 {
2338   char *homedir;
2339   if (inhibit_gdbinit)
2340     return;
2341
2342   homedir = getenv ("HOME");
2343   if (homedir)
2344     {
2345       char *p;
2346       char *oldini = (char *) alloca (strlen (homedir) +
2347                                       sizeof ("/gdb.ini"));
2348       strcpy (oldini, homedir);
2349       p = strchr (oldini, '\0');
2350       if (p > oldini && p[-1] != '/')
2351         *p++ = '/';
2352       strcpy (p, "gdb.ini");
2353       if (access (oldini, 0) == 0)
2354         {
2355           int len = strlen (oldini);
2356           char *newini = alloca (len + 1);
2357           sprintf (newini, "%.*s.gdbinit",
2358             (int) (len - (sizeof ("gdb.ini") - 1)), oldini);
2359           warning (_("obsolete '%s' found. Rename to '%s'."), oldini, newini);
2360         }
2361     }
2362 }
2363
2364 /* Define dummy functions which always return error for the rare cases where
2365    these functions could not be found. */
2366 static BOOL WINAPI
2367 bad_DebugActiveProcessStop (DWORD w)
2368 {
2369   return FALSE;
2370 }
2371 static BOOL WINAPI
2372 bad_DebugBreakProcess (HANDLE w)
2373 {
2374   return FALSE;
2375 }
2376 static BOOL WINAPI
2377 bad_DebugSetProcessKillOnExit (BOOL w)
2378 {
2379   return FALSE;
2380 }
2381 static BOOL WINAPI
2382 bad_EnumProcessModules (HANDLE w, HMODULE *x, DWORD y, LPDWORD z)
2383 {
2384   return FALSE;
2385 }
2386 static DWORD WINAPI
2387 bad_GetModuleFileNameExA (HANDLE w, HMODULE x, LPSTR y, DWORD z)
2388 {
2389   return 0;
2390 }
2391 static BOOL WINAPI
2392 bad_GetModuleInformation (HANDLE w, HMODULE x, LPMODULEINFO y, DWORD z)
2393 {
2394   return FALSE;
2395 }
2396
2397 static BOOL WINAPI
2398 bad_OpenProcessToken (HANDLE w, DWORD x, PHANDLE y)
2399 {
2400   return FALSE;
2401 }
2402
2403 /* Load any functions which may not be available in ancient versions
2404    of Windows. */
2405 void
2406 _initialize_loadable (void)
2407 {
2408   HMODULE hm = NULL;
2409
2410   hm = LoadLibrary ("kernel32.dll");
2411   if (hm)
2412     {
2413       dyn_DebugActiveProcessStop = (void *)
2414         GetProcAddress (hm, "DebugActiveProcessStop");
2415       dyn_DebugBreakProcess = (void *)
2416         GetProcAddress (hm, "DebugBreakProcess");
2417       dyn_DebugSetProcessKillOnExit = (void *)
2418         GetProcAddress (hm, "DebugSetProcessKillOnExit");
2419     }
2420
2421   /* Set variables to dummy versions of these processes if the function
2422      wasn't found in kernel32.dll. */
2423   if (!dyn_DebugBreakProcess)
2424     dyn_DebugBreakProcess = bad_DebugBreakProcess;
2425   if (!dyn_DebugActiveProcessStop || !dyn_DebugSetProcessKillOnExit)
2426     {
2427       dyn_DebugActiveProcessStop = bad_DebugActiveProcessStop;
2428       dyn_DebugSetProcessKillOnExit = bad_DebugSetProcessKillOnExit;
2429     }
2430
2431   /* Load optional functions used for retrieving filename information
2432      associated with the currently debugged process or its dlls. */
2433   hm = LoadLibrary ("psapi.dll");
2434   if (hm)
2435     {
2436       dyn_EnumProcessModules = (void *)
2437         GetProcAddress (hm, "EnumProcessModules");
2438       dyn_GetModuleInformation = (void *)
2439         GetProcAddress (hm, "GetModuleInformation");
2440       dyn_GetModuleFileNameExA = (void *)
2441         GetProcAddress (hm, "GetModuleFileNameExA");
2442     }
2443
2444   if (!dyn_EnumProcessModules || !dyn_GetModuleInformation || !dyn_GetModuleFileNameExA)
2445     {
2446       /* Set variables to dummy versions of these processes if the function
2447          wasn't found in psapi.dll. */
2448       dyn_EnumProcessModules = bad_EnumProcessModules;
2449       dyn_GetModuleInformation = bad_GetModuleInformation;
2450       dyn_GetModuleFileNameExA = bad_GetModuleFileNameExA;
2451       /* This will probably fail on Windows 9x/Me.  Let the user know that we're
2452          missing some functionality. */
2453       warning(_("cannot automatically find executable file or library to read symbols.\nUse \"file\" or \"dll\" command to load executable/libraries directly."));
2454     }
2455
2456   hm = LoadLibrary ("advapi32.dll");
2457   if (hm)
2458     {
2459       dyn_OpenProcessToken = (void *)
2460         GetProcAddress (hm, "OpenProcessToken");
2461       dyn_LookupPrivilegeValueA = (void *)
2462         GetProcAddress (hm, "LookupPrivilegeValueA");
2463       dyn_AdjustTokenPrivileges = (void *)
2464         GetProcAddress (hm, "AdjustTokenPrivileges");
2465       /* Only need to set one of these since if OpenProcessToken fails nothing
2466          else is needed. */
2467       if (!dyn_OpenProcessToken || !dyn_LookupPrivilegeValueA || !dyn_AdjustTokenPrivileges)
2468         dyn_OpenProcessToken = bad_OpenProcessToken;
2469     }
2470 }