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