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