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