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