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