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