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