windows-nat: Don't change current_event.dwThreadId in handle_output_debug_string()
[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         }
854     }
855 #endif
856
857   if (s)
858     xfree (s);
859   return retval;
860 }
861
862 static int
863 display_selector (HANDLE thread, DWORD sel)
864 {
865   LDT_ENTRY info;
866   if (GetThreadSelectorEntry (thread, sel, &info))
867     {
868       int base, limit;
869       printf_filtered ("0x%03x: ", (unsigned) sel);
870       if (!info.HighWord.Bits.Pres)
871         {
872           puts_filtered ("Segment not present\n");
873           return 0;
874         }
875       base = (info.HighWord.Bits.BaseHi << 24) +
876              (info.HighWord.Bits.BaseMid << 16)
877              + info.BaseLow;
878       limit = (info.HighWord.Bits.LimitHi << 16) + info.LimitLow;
879       if (info.HighWord.Bits.Granularity)
880         limit = (limit << 12) | 0xfff;
881       printf_filtered ("base=0x%08x limit=0x%08x", base, limit);
882       if (info.HighWord.Bits.Default_Big)
883         puts_filtered(" 32-bit ");
884       else
885         puts_filtered(" 16-bit ");
886       switch ((info.HighWord.Bits.Type & 0xf) >> 1)
887         {
888         case 0:
889           puts_filtered ("Data (Read-Only, Exp-up");
890           break;
891         case 1:
892           puts_filtered ("Data (Read/Write, Exp-up");
893           break;
894         case 2:
895           puts_filtered ("Unused segment (");
896           break;
897         case 3:
898           puts_filtered ("Data (Read/Write, Exp-down");
899           break;
900         case 4:
901           puts_filtered ("Code (Exec-Only, N.Conf");
902           break;
903         case 5:
904           puts_filtered ("Code (Exec/Read, N.Conf");
905           break;
906         case 6:
907           puts_filtered ("Code (Exec-Only, Conf");
908           break;
909         case 7:
910           puts_filtered ("Code (Exec/Read, Conf");
911           break;
912         default:
913           printf_filtered ("Unknown type 0x%x",info.HighWord.Bits.Type);
914         }
915       if ((info.HighWord.Bits.Type & 0x1) == 0)
916         puts_filtered(", N.Acc");
917       puts_filtered (")\n");
918       if ((info.HighWord.Bits.Type & 0x10) == 0)
919         puts_filtered("System selector ");
920       printf_filtered ("Priviledge level = %d. ", info.HighWord.Bits.Dpl);
921       if (info.HighWord.Bits.Granularity)
922         puts_filtered ("Page granular.\n");
923       else
924         puts_filtered ("Byte granular.\n");
925       return 1;
926     }
927   else
928     {
929       DWORD err = GetLastError ();
930       if (err == ERROR_NOT_SUPPORTED)
931         printf_filtered ("Function not supported\n");
932       else
933         printf_filtered ("Invalid selector 0x%x.\n", (unsigned) sel);
934       return 0;
935     }
936 }
937
938 static void
939 display_selectors (char * args, int from_tty)
940 {
941   if (!current_thread)
942     {
943       puts_filtered ("Impossible to display selectors now.\n");
944       return;
945     }
946   if (!args)
947     {
948
949       puts_filtered ("Selector $cs\n");
950       display_selector (current_thread->h,
951         current_thread->context.SegCs);
952       puts_filtered ("Selector $ds\n");
953       display_selector (current_thread->h,
954         current_thread->context.SegDs);
955       puts_filtered ("Selector $es\n");
956       display_selector (current_thread->h,
957         current_thread->context.SegEs);
958       puts_filtered ("Selector $ss\n");
959       display_selector (current_thread->h,
960         current_thread->context.SegSs);
961       puts_filtered ("Selector $fs\n");
962       display_selector (current_thread->h,
963         current_thread->context.SegFs);
964       puts_filtered ("Selector $gs\n");
965       display_selector (current_thread->h,
966         current_thread->context.SegGs);
967     }
968   else
969     {
970       int sel;
971       sel = parse_and_eval_long (args);
972       printf_filtered ("Selector \"%s\"\n",args);
973       display_selector (current_thread->h, sel);
974     }
975 }
976
977 #define DEBUG_EXCEPTION_SIMPLE(x)       if (debug_exceptions) \
978   printf_unfiltered ("gdb: Target exception %s at %s\n", x, \
979     host_address_to_string (\
980       current_event.u.Exception.ExceptionRecord.ExceptionAddress))
981
982 static int
983 handle_exception (struct target_waitstatus *ourstatus)
984 {
985   windows_thread_info *th;
986   DWORD code = current_event.u.Exception.ExceptionRecord.ExceptionCode;
987
988   ourstatus->kind = TARGET_WAITKIND_STOPPED;
989
990   /* Record the context of the current thread.  */
991   th = thread_rec (current_event.dwThreadId, -1);
992
993   switch (code)
994     {
995     case EXCEPTION_ACCESS_VIOLATION:
996       DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ACCESS_VIOLATION");
997       ourstatus->value.sig = GDB_SIGNAL_SEGV;
998 #ifdef __CYGWIN__
999       {
1000         /* See if the access violation happened within the cygwin DLL
1001            itself.  Cygwin uses a kind of exception handling to deal
1002            with passed-in invalid addresses.  gdb should not treat
1003            these as real SEGVs since they will be silently handled by
1004            cygwin.  A real SEGV will (theoretically) be caught by
1005            cygwin later in the process and will be sent as a
1006            cygwin-specific-signal.  So, ignore SEGVs if they show up
1007            within the text segment of the DLL itself.  */
1008         const char *fn;
1009         CORE_ADDR addr = (CORE_ADDR) (uintptr_t)
1010           current_event.u.Exception.ExceptionRecord.ExceptionAddress;
1011
1012         if ((!cygwin_exceptions && (addr >= cygwin_load_start
1013                                     && addr < cygwin_load_end))
1014             || (find_pc_partial_function (addr, &fn, NULL, NULL)
1015                 && startswith (fn, "KERNEL32!IsBad")))
1016           return 0;
1017       }
1018 #endif
1019       break;
1020     case STATUS_STACK_OVERFLOW:
1021       DEBUG_EXCEPTION_SIMPLE ("STATUS_STACK_OVERFLOW");
1022       ourstatus->value.sig = GDB_SIGNAL_SEGV;
1023       break;
1024     case STATUS_FLOAT_DENORMAL_OPERAND:
1025       DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DENORMAL_OPERAND");
1026       ourstatus->value.sig = GDB_SIGNAL_FPE;
1027       break;
1028     case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
1029       DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ARRAY_BOUNDS_EXCEEDED");
1030       ourstatus->value.sig = GDB_SIGNAL_FPE;
1031       break;
1032     case STATUS_FLOAT_INEXACT_RESULT:
1033       DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INEXACT_RESULT");
1034       ourstatus->value.sig = GDB_SIGNAL_FPE;
1035       break;
1036     case STATUS_FLOAT_INVALID_OPERATION:
1037       DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_INVALID_OPERATION");
1038       ourstatus->value.sig = GDB_SIGNAL_FPE;
1039       break;
1040     case STATUS_FLOAT_OVERFLOW:
1041       DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_OVERFLOW");
1042       ourstatus->value.sig = GDB_SIGNAL_FPE;
1043       break;
1044     case STATUS_FLOAT_STACK_CHECK:
1045       DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_STACK_CHECK");
1046       ourstatus->value.sig = GDB_SIGNAL_FPE;
1047       break;
1048     case STATUS_FLOAT_UNDERFLOW:
1049       DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_UNDERFLOW");
1050       ourstatus->value.sig = GDB_SIGNAL_FPE;
1051       break;
1052     case STATUS_FLOAT_DIVIDE_BY_ZERO:
1053       DEBUG_EXCEPTION_SIMPLE ("STATUS_FLOAT_DIVIDE_BY_ZERO");
1054       ourstatus->value.sig = GDB_SIGNAL_FPE;
1055       break;
1056     case STATUS_INTEGER_DIVIDE_BY_ZERO:
1057       DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_DIVIDE_BY_ZERO");
1058       ourstatus->value.sig = GDB_SIGNAL_FPE;
1059       break;
1060     case STATUS_INTEGER_OVERFLOW:
1061       DEBUG_EXCEPTION_SIMPLE ("STATUS_INTEGER_OVERFLOW");
1062       ourstatus->value.sig = GDB_SIGNAL_FPE;
1063       break;
1064     case EXCEPTION_BREAKPOINT:
1065       DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_BREAKPOINT");
1066       ourstatus->value.sig = GDB_SIGNAL_TRAP;
1067       break;
1068     case DBG_CONTROL_C:
1069       DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_C");
1070       ourstatus->value.sig = GDB_SIGNAL_INT;
1071       break;
1072     case DBG_CONTROL_BREAK:
1073       DEBUG_EXCEPTION_SIMPLE ("DBG_CONTROL_BREAK");
1074       ourstatus->value.sig = GDB_SIGNAL_INT;
1075       break;
1076     case EXCEPTION_SINGLE_STEP:
1077       DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_SINGLE_STEP");
1078       ourstatus->value.sig = GDB_SIGNAL_TRAP;
1079       break;
1080     case EXCEPTION_ILLEGAL_INSTRUCTION:
1081       DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_ILLEGAL_INSTRUCTION");
1082       ourstatus->value.sig = GDB_SIGNAL_ILL;
1083       break;
1084     case EXCEPTION_PRIV_INSTRUCTION:
1085       DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_PRIV_INSTRUCTION");
1086       ourstatus->value.sig = GDB_SIGNAL_ILL;
1087       break;
1088     case EXCEPTION_NONCONTINUABLE_EXCEPTION:
1089       DEBUG_EXCEPTION_SIMPLE ("EXCEPTION_NONCONTINUABLE_EXCEPTION");
1090       ourstatus->value.sig = GDB_SIGNAL_ILL;
1091       break;
1092     default:
1093       /* Treat unhandled first chance exceptions specially.  */
1094       if (current_event.u.Exception.dwFirstChance)
1095         return -1;
1096       printf_unfiltered ("gdb: unknown target exception 0x%08x at %s\n",
1097         (unsigned) current_event.u.Exception.ExceptionRecord.ExceptionCode,
1098         host_address_to_string (
1099           current_event.u.Exception.ExceptionRecord.ExceptionAddress));
1100       ourstatus->value.sig = GDB_SIGNAL_UNKNOWN;
1101       break;
1102     }
1103   exception_count++;
1104   last_sig = ourstatus->value.sig;
1105   return 1;
1106 }
1107
1108 /* Resume thread specified by ID, or all artificially suspended
1109    threads, if we are continuing execution.  KILLED non-zero means we
1110    have killed the inferior, so we should ignore weird errors due to
1111    threads shutting down.  */
1112 static BOOL
1113 windows_continue (DWORD continue_status, int id, int killed)
1114 {
1115   int i;
1116   windows_thread_info *th;
1117   BOOL res;
1118
1119   DEBUG_EVENTS (("ContinueDebugEvent (cpid=%d, ctid=0x%x, %s);\n",
1120                   (unsigned) current_event.dwProcessId,
1121                   (unsigned) current_event.dwThreadId,
1122                   continue_status == DBG_CONTINUE ?
1123                   "DBG_CONTINUE" : "DBG_EXCEPTION_NOT_HANDLED"));
1124
1125   for (th = &thread_head; (th = th->next) != NULL;)
1126     if ((id == -1 || id == (int) th->id)
1127         && th->suspended)
1128       {
1129         if (debug_registers_changed)
1130           {
1131             th->context.ContextFlags |= CONTEXT_DEBUG_REGISTERS;
1132             th->context.Dr0 = dr[0];
1133             th->context.Dr1 = dr[1];
1134             th->context.Dr2 = dr[2];
1135             th->context.Dr3 = dr[3];
1136             th->context.Dr6 = DR6_CLEAR_VALUE;
1137             th->context.Dr7 = dr[7];
1138           }
1139         if (th->context.ContextFlags)
1140           {
1141             DWORD ec = 0;
1142
1143             if (GetExitCodeThread (th->h, &ec)
1144                 && ec == STILL_ACTIVE)
1145               {
1146                 BOOL status = SetThreadContext (th->h, &th->context);
1147
1148                 if (!killed)
1149                   CHECK (status);
1150               }
1151             th->context.ContextFlags = 0;
1152           }
1153         if (th->suspended > 0)
1154           (void) ResumeThread (th->h);
1155         th->suspended = 0;
1156       }
1157
1158   res = ContinueDebugEvent (current_event.dwProcessId,
1159                             current_event.dwThreadId,
1160                             continue_status);
1161
1162   if (!res)
1163     error (_("Failed to resume program execution"
1164              " (ContinueDebugEvent failed, error %u)"),
1165            (unsigned int) GetLastError ());
1166
1167   debug_registers_changed = 0;
1168   return res;
1169 }
1170
1171 /* Called in pathological case where Windows fails to send a
1172    CREATE_PROCESS_DEBUG_EVENT after an attach.  */
1173 static DWORD
1174 fake_create_process (void)
1175 {
1176   current_process_handle = OpenProcess (PROCESS_ALL_ACCESS, FALSE,
1177                                         current_event.dwProcessId);
1178   if (current_process_handle != NULL)
1179     open_process_used = 1;
1180   else
1181     {
1182       error (_("OpenProcess call failed, GetLastError = %u"),
1183        (unsigned) GetLastError ());
1184       /*  We can not debug anything in that case.  */
1185     }
1186   main_thread_id = current_event.dwThreadId;
1187   current_thread = windows_add_thread (
1188                      ptid_build (current_event.dwProcessId, 0,
1189                                  current_event.dwThreadId),
1190                      current_event.u.CreateThread.hThread,
1191                      current_event.u.CreateThread.lpThreadLocalBase);
1192   return main_thread_id;
1193 }
1194
1195 static void
1196 windows_resume (struct target_ops *ops,
1197                 ptid_t ptid, int step, enum gdb_signal sig)
1198 {
1199   windows_thread_info *th;
1200   DWORD continue_status = DBG_CONTINUE;
1201
1202   /* A specific PTID means `step only this thread id'.  */
1203   int resume_all = ptid_equal (ptid, minus_one_ptid);
1204
1205   /* If we're continuing all threads, it's the current inferior that
1206      should be handled specially.  */
1207   if (resume_all)
1208     ptid = inferior_ptid;
1209
1210   if (sig != GDB_SIGNAL_0)
1211     {
1212       if (current_event.dwDebugEventCode != EXCEPTION_DEBUG_EVENT)
1213         {
1214           DEBUG_EXCEPT(("Cannot continue with signal %d here.\n",sig));
1215         }
1216       else if (sig == last_sig)
1217         continue_status = DBG_EXCEPTION_NOT_HANDLED;
1218       else
1219 #if 0
1220 /* This code does not seem to work, because
1221   the kernel does probably not consider changes in the ExceptionRecord
1222   structure when passing the exception to the inferior.
1223   Note that this seems possible in the exception handler itself.  */
1224         {
1225           int i;
1226           for (i = 0; xlate[i].them != -1; i++)
1227             if (xlate[i].us == sig)
1228               {
1229                 current_event.u.Exception.ExceptionRecord.ExceptionCode
1230                   = xlate[i].them;
1231                 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1232                 break;
1233               }
1234           if (continue_status == DBG_CONTINUE)
1235             {
1236               DEBUG_EXCEPT(("Cannot continue with signal %d.\n",sig));
1237             }
1238         }
1239 #endif
1240         DEBUG_EXCEPT(("Can only continue with received signal %d.\n",
1241           last_sig));
1242     }
1243
1244   last_sig = GDB_SIGNAL_0;
1245
1246   DEBUG_EXEC (("gdb: windows_resume (pid=%d, tid=%ld, step=%d, sig=%d);\n",
1247                ptid_get_pid (ptid), ptid_get_tid (ptid), step, sig));
1248
1249   /* Get context for currently selected thread.  */
1250   th = thread_rec (ptid_get_tid (inferior_ptid), FALSE);
1251   if (th)
1252     {
1253       if (step)
1254         {
1255           /* Single step by setting t bit.  */
1256           struct regcache *regcache = get_current_regcache ();
1257           struct gdbarch *gdbarch = get_regcache_arch (regcache);
1258           windows_fetch_inferior_registers (ops, regcache,
1259                                             gdbarch_ps_regnum (gdbarch));
1260           th->context.EFlags |= FLAG_TRACE_BIT;
1261         }
1262
1263       if (th->context.ContextFlags)
1264         {
1265           if (debug_registers_changed)
1266             {
1267               th->context.Dr0 = dr[0];
1268               th->context.Dr1 = dr[1];
1269               th->context.Dr2 = dr[2];
1270               th->context.Dr3 = dr[3];
1271               th->context.Dr6 = DR6_CLEAR_VALUE;
1272               th->context.Dr7 = dr[7];
1273             }
1274           CHECK (SetThreadContext (th->h, &th->context));
1275           th->context.ContextFlags = 0;
1276         }
1277     }
1278
1279   /* Allow continuing with the same signal that interrupted us.
1280      Otherwise complain.  */
1281
1282   if (resume_all)
1283     windows_continue (continue_status, -1, 0);
1284   else
1285     windows_continue (continue_status, ptid_get_tid (ptid), 0);
1286 }
1287
1288 /* Ctrl-C handler used when the inferior is not run in the same console.  The
1289    handler is in charge of interrupting the inferior using DebugBreakProcess.
1290    Note that this function is not available prior to Windows XP.  In this case
1291    we emit a warning.  */
1292 static BOOL WINAPI
1293 ctrl_c_handler (DWORD event_type)
1294 {
1295   const int attach_flag = current_inferior ()->attach_flag;
1296
1297   /* Only handle Ctrl-C and Ctrl-Break events.  Ignore others.  */
1298   if (event_type != CTRL_C_EVENT && event_type != CTRL_BREAK_EVENT)
1299     return FALSE;
1300
1301   /* If the inferior and the debugger share the same console, do nothing as
1302      the inferior has also received the Ctrl-C event.  */
1303   if (!new_console && !attach_flag)
1304     return TRUE;
1305
1306   if (!DebugBreakProcess (current_process_handle))
1307     warning (_("Could not interrupt program.  "
1308                "Press Ctrl-c in the program console."));
1309
1310   /* Return true to tell that Ctrl-C has been handled.  */
1311   return TRUE;
1312 }
1313
1314 /* Get the next event from the child.  Returns a non-zero thread id if the event
1315    requires handling by WFI (or whatever).  */
1316 static int
1317 get_windows_debug_event (struct target_ops *ops,
1318                          int pid, struct target_waitstatus *ourstatus)
1319 {
1320   BOOL debug_event;
1321   DWORD continue_status, event_code;
1322   windows_thread_info *th;
1323   static windows_thread_info dummy_thread_info;
1324   DWORD thread_id = 0;
1325
1326   last_sig = GDB_SIGNAL_0;
1327
1328   if (!(debug_event = WaitForDebugEvent (&current_event, 1000)))
1329     goto out;
1330
1331   event_count++;
1332   continue_status = DBG_CONTINUE;
1333
1334   event_code = current_event.dwDebugEventCode;
1335   ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
1336   th = NULL;
1337   have_saved_context = 0;
1338
1339   switch (event_code)
1340     {
1341     case CREATE_THREAD_DEBUG_EVENT:
1342       DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1343                      (unsigned) current_event.dwProcessId,
1344                      (unsigned) current_event.dwThreadId,
1345                      "CREATE_THREAD_DEBUG_EVENT"));
1346       if (saw_create != 1)
1347         {
1348           struct inferior *inf;
1349           inf = find_inferior_pid (current_event.dwProcessId);
1350           if (!saw_create && inf->attach_flag)
1351             {
1352               /* Kludge around a Windows bug where first event is a create
1353                  thread event.  Caused when attached process does not have
1354                  a main thread.  */
1355               thread_id = fake_create_process ();
1356               if (thread_id)
1357                 saw_create++;
1358             }
1359           break;
1360         }
1361       /* Record the existence of this thread.  */
1362       thread_id = current_event.dwThreadId;
1363       th = windows_add_thread (ptid_build (current_event.dwProcessId, 0,
1364                                          current_event.dwThreadId),
1365                              current_event.u.CreateThread.hThread,
1366                              current_event.u.CreateThread.lpThreadLocalBase);
1367
1368       break;
1369
1370     case EXIT_THREAD_DEBUG_EVENT:
1371       DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1372                      (unsigned) current_event.dwProcessId,
1373                      (unsigned) current_event.dwThreadId,
1374                      "EXIT_THREAD_DEBUG_EVENT"));
1375
1376       if (current_event.dwThreadId != main_thread_id)
1377         {
1378           windows_delete_thread (ptid_build (current_event.dwProcessId, 0,
1379                                              current_event.dwThreadId),
1380                                  current_event.u.ExitThread.dwExitCode);
1381           th = &dummy_thread_info;
1382         }
1383       break;
1384
1385     case CREATE_PROCESS_DEBUG_EVENT:
1386       DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1387                      (unsigned) current_event.dwProcessId,
1388                      (unsigned) current_event.dwThreadId,
1389                      "CREATE_PROCESS_DEBUG_EVENT"));
1390       CloseHandle (current_event.u.CreateProcessInfo.hFile);
1391       if (++saw_create != 1)
1392         break;
1393
1394       current_process_handle = current_event.u.CreateProcessInfo.hProcess;
1395       if (main_thread_id)
1396         windows_delete_thread (ptid_build (current_event.dwProcessId, 0,
1397                                            main_thread_id),
1398                                0);
1399       main_thread_id = current_event.dwThreadId;
1400       /* Add the main thread.  */
1401       th = windows_add_thread (ptid_build (current_event.dwProcessId, 0,
1402                                            current_event.dwThreadId),
1403              current_event.u.CreateProcessInfo.hThread,
1404              current_event.u.CreateProcessInfo.lpThreadLocalBase);
1405       thread_id = current_event.dwThreadId;
1406       break;
1407
1408     case EXIT_PROCESS_DEBUG_EVENT:
1409       DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1410                      (unsigned) current_event.dwProcessId,
1411                      (unsigned) current_event.dwThreadId,
1412                      "EXIT_PROCESS_DEBUG_EVENT"));
1413       if (!windows_initialization_done)
1414         {
1415           target_terminal_ours ();
1416           target_mourn_inferior ();
1417           error (_("During startup program exited with code 0x%x."),
1418                  (unsigned int) current_event.u.ExitProcess.dwExitCode);
1419         }
1420       else if (saw_create == 1)
1421         {
1422           ourstatus->kind = TARGET_WAITKIND_EXITED;
1423           ourstatus->value.integer = current_event.u.ExitProcess.dwExitCode;
1424           thread_id = main_thread_id;
1425         }
1426       break;
1427
1428     case LOAD_DLL_DEBUG_EVENT:
1429       DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1430                      (unsigned) current_event.dwProcessId,
1431                      (unsigned) current_event.dwThreadId,
1432                      "LOAD_DLL_DEBUG_EVENT"));
1433       CloseHandle (current_event.u.LoadDll.hFile);
1434       if (saw_create != 1 || ! windows_initialization_done)
1435         break;
1436       catch_errors (handle_load_dll, NULL, (char *) "", RETURN_MASK_ALL);
1437       ourstatus->kind = TARGET_WAITKIND_LOADED;
1438       ourstatus->value.integer = 0;
1439       thread_id = main_thread_id;
1440       break;
1441
1442     case UNLOAD_DLL_DEBUG_EVENT:
1443       DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1444                      (unsigned) current_event.dwProcessId,
1445                      (unsigned) current_event.dwThreadId,
1446                      "UNLOAD_DLL_DEBUG_EVENT"));
1447       if (saw_create != 1 || ! windows_initialization_done)
1448         break;
1449       catch_errors (handle_unload_dll, NULL, (char *) "", RETURN_MASK_ALL);
1450       ourstatus->kind = TARGET_WAITKIND_LOADED;
1451       ourstatus->value.integer = 0;
1452       thread_id = main_thread_id;
1453       break;
1454
1455     case EXCEPTION_DEBUG_EVENT:
1456       DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1457                      (unsigned) current_event.dwProcessId,
1458                      (unsigned) current_event.dwThreadId,
1459                      "EXCEPTION_DEBUG_EVENT"));
1460       if (saw_create != 1)
1461         break;
1462       switch (handle_exception (ourstatus))
1463         {
1464         case 0:
1465           continue_status = DBG_EXCEPTION_NOT_HANDLED;
1466           break;
1467         case 1:
1468           thread_id = current_event.dwThreadId;
1469           break;
1470         case -1:
1471           last_sig = 1;
1472           continue_status = -1;
1473           break;
1474         }
1475       break;
1476
1477     case OUTPUT_DEBUG_STRING_EVENT:     /* Message from the kernel.  */
1478       DEBUG_EVENTS (("gdb: kernel event for pid=%u tid=0x%x code=%s)\n",
1479                      (unsigned) current_event.dwProcessId,
1480                      (unsigned) current_event.dwThreadId,
1481                      "OUTPUT_DEBUG_STRING_EVENT"));
1482       if (saw_create != 1)
1483         break;
1484       thread_id = handle_output_debug_string (ourstatus);
1485       break;
1486
1487     default:
1488       if (saw_create != 1)
1489         break;
1490       printf_unfiltered ("gdb: kernel event for pid=%u tid=0x%x\n",
1491                          (unsigned) current_event.dwProcessId,
1492                          (unsigned) current_event.dwThreadId);
1493       printf_unfiltered ("                 unknown event code %u\n",
1494                          (unsigned) current_event.dwDebugEventCode);
1495       break;
1496     }
1497
1498   if (!thread_id || saw_create != 1)
1499     {
1500       if (continue_status == -1)
1501         windows_resume (ops, minus_one_ptid, 0, 1);
1502       else
1503         CHECK (windows_continue (continue_status, -1, 0));
1504     }
1505   else
1506     {
1507       inferior_ptid = ptid_build (current_event.dwProcessId, 0,
1508                                   thread_id);
1509       current_thread = th;
1510       if (!current_thread)
1511         current_thread = thread_rec (thread_id, TRUE);
1512     }
1513
1514 out:
1515   return thread_id;
1516 }
1517
1518 /* Wait for interesting events to occur in the target process.  */
1519 static ptid_t
1520 windows_wait (struct target_ops *ops,
1521               ptid_t ptid, struct target_waitstatus *ourstatus, int options)
1522 {
1523   int pid = -1;
1524
1525   target_terminal_ours ();
1526
1527   /* We loop when we get a non-standard exception rather than return
1528      with a SPURIOUS because resume can try and step or modify things,
1529      which needs a current_thread->h.  But some of these exceptions mark
1530      the birth or death of threads, which mean that the current thread
1531      isn't necessarily what you think it is.  */
1532
1533   while (1)
1534     {
1535       int retval;
1536
1537       /* If the user presses Ctrl-c while the debugger is waiting
1538          for an event, he expects the debugger to interrupt his program
1539          and to get the prompt back.  There are two possible situations:
1540
1541            - The debugger and the program do not share the console, in
1542              which case the Ctrl-c event only reached the debugger.
1543              In that case, the ctrl_c handler will take care of interrupting
1544              the inferior.  Note that this case is working starting with
1545              Windows XP.  For Windows 2000, Ctrl-C should be pressed in the
1546              inferior console.
1547
1548            - The debugger and the program share the same console, in which
1549              case both debugger and inferior will receive the Ctrl-c event.
1550              In that case the ctrl_c handler will ignore the event, as the
1551              Ctrl-c event generated inside the inferior will trigger the
1552              expected debug event.
1553
1554              FIXME: brobecker/2008-05-20: If the inferior receives the
1555              signal first and the delay until GDB receives that signal
1556              is sufficiently long, GDB can sometimes receive the SIGINT
1557              after we have unblocked the CTRL+C handler.  This would
1558              lead to the debugger stopping prematurely while handling
1559              the new-thread event that comes with the handling of the SIGINT
1560              inside the inferior, and then stop again immediately when
1561              the user tries to resume the execution in the inferior.
1562              This is a classic race that we should try to fix one day.  */
1563       SetConsoleCtrlHandler (&ctrl_c_handler, TRUE);
1564       retval = get_windows_debug_event (ops, pid, ourstatus);
1565       SetConsoleCtrlHandler (&ctrl_c_handler, FALSE);
1566
1567       if (retval)
1568         return ptid_build (current_event.dwProcessId, 0, retval);
1569       else
1570         {
1571           int detach = 0;
1572
1573           if (deprecated_ui_loop_hook != NULL)
1574             detach = deprecated_ui_loop_hook (0);
1575
1576           if (detach)
1577             windows_kill_inferior (ops);
1578         }
1579     }
1580 }
1581
1582 /* Iterate over all DLLs currently mapped by our inferior, and
1583    add them to our list of solibs.  */
1584
1585 static void
1586 windows_add_all_dlls (void)
1587 {
1588   struct so_list *so;
1589   HMODULE dummy_hmodule;
1590   DWORD cb_needed;
1591   HMODULE *hmodules;
1592   int i;
1593
1594   if (EnumProcessModules (current_process_handle, &dummy_hmodule,
1595                           sizeof (HMODULE), &cb_needed) == 0)
1596     return;
1597
1598   if (cb_needed < 1)
1599     return;
1600
1601   hmodules = (HMODULE *) alloca (cb_needed);
1602   if (EnumProcessModules (current_process_handle, hmodules,
1603                           cb_needed, &cb_needed) == 0)
1604     return;
1605
1606   for (i = 1; i < (int) (cb_needed / sizeof (HMODULE)); i++)
1607     {
1608       MODULEINFO mi;
1609 #ifdef __USEWIDE
1610       wchar_t dll_name[__PMAX];
1611       char name[__PMAX];
1612 #else
1613       char dll_name[__PMAX];
1614       char *name;
1615 #endif
1616       if (GetModuleInformation (current_process_handle, hmodules[i],
1617                                 &mi, sizeof (mi)) == 0)
1618         continue;
1619       if (GetModuleFileNameEx (current_process_handle, hmodules[i],
1620                                dll_name, sizeof (dll_name)) == 0)
1621         continue;
1622 #ifdef __USEWIDE
1623       wcstombs (name, dll_name, __PMAX);
1624 #else
1625       name = dll_name;
1626 #endif
1627
1628       solib_end->next = windows_make_so (name, mi.lpBaseOfDll);
1629       solib_end = solib_end->next;
1630     }
1631 }
1632
1633 static void
1634 do_initial_windows_stuff (struct target_ops *ops, DWORD pid, int attaching)
1635 {
1636   extern int stop_after_trap;
1637   int i;
1638   struct inferior *inf;
1639   struct thread_info *tp;
1640
1641   last_sig = GDB_SIGNAL_0;
1642   event_count = 0;
1643   exception_count = 0;
1644   open_process_used = 0;
1645   debug_registers_changed = 0;
1646   debug_registers_used = 0;
1647   for (i = 0; i < sizeof (dr) / sizeof (dr[0]); i++)
1648     dr[i] = 0;
1649 #ifdef __CYGWIN__
1650   cygwin_load_start = cygwin_load_end = 0;
1651 #endif
1652   current_event.dwProcessId = pid;
1653   memset (&current_event, 0, sizeof (current_event));
1654   if (!target_is_pushed (ops))
1655     push_target (ops);
1656   disable_breakpoints_in_shlibs ();
1657   windows_clear_solib ();
1658   clear_proceed_status (0);
1659   init_wait_for_inferior ();
1660
1661   inf = current_inferior ();
1662   inferior_appeared (inf, pid);
1663   inf->attach_flag = attaching;
1664
1665   /* Make the new process the current inferior, so terminal handling
1666      can rely on it.  When attaching, we don't know about any thread
1667      id here, but that's OK --- nothing should be referencing the
1668      current thread until we report an event out of windows_wait.  */
1669   inferior_ptid = pid_to_ptid (pid);
1670
1671   target_terminal_init ();
1672   target_terminal_inferior ();
1673
1674   windows_initialization_done = 0;
1675   inf->control.stop_soon = STOP_QUIETLY;
1676   while (1)
1677     {
1678       stop_after_trap = 1;
1679       wait_for_inferior ();
1680       tp = inferior_thread ();
1681       if (tp->suspend.stop_signal != GDB_SIGNAL_TRAP)
1682         resume (tp->suspend.stop_signal);
1683       else
1684         break;
1685     }
1686
1687   /* Now that the inferior has been started and all DLLs have been mapped,
1688      we can iterate over all DLLs and load them in.
1689
1690      We avoid doing it any earlier because, on certain versions of Windows,
1691      LOAD_DLL_DEBUG_EVENTs are sometimes not complete.  In particular,
1692      we have seen on Windows 8.1 that the ntdll.dll load event does not
1693      include the DLL name, preventing us from creating an associated SO.
1694      A possible explanation is that ntdll.dll might be mapped before
1695      the SO info gets created by the Windows system -- ntdll.dll is
1696      the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs
1697      do not seem to suffer from that problem.
1698
1699      Rather than try to work around this sort of issue, it is much
1700      simpler to just ignore DLL load/unload events during the startup
1701      phase, and then process them all in one batch now.  */
1702   windows_add_all_dlls ();
1703
1704   windows_initialization_done = 1;
1705   inf->control.stop_soon = NO_STOP_QUIETLY;
1706   stop_after_trap = 0;
1707   return;
1708 }
1709
1710 /* Try to set or remove a user privilege to the current process.  Return -1
1711    if that fails, the previous setting of that privilege otherwise.
1712
1713    This code is copied from the Cygwin source code and rearranged to allow
1714    dynamically loading of the needed symbols from advapi32 which is only
1715    available on NT/2K/XP.  */
1716 static int
1717 set_process_privilege (const char *privilege, BOOL enable)
1718 {
1719   HANDLE token_hdl = NULL;
1720   LUID restore_priv;
1721   TOKEN_PRIVILEGES new_priv, orig_priv;
1722   int ret = -1;
1723   DWORD size;
1724
1725   if (!OpenProcessToken (GetCurrentProcess (),
1726                          TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
1727                          &token_hdl))
1728     goto out;
1729
1730   if (!LookupPrivilegeValueA (NULL, privilege, &restore_priv))
1731     goto out;
1732
1733   new_priv.PrivilegeCount = 1;
1734   new_priv.Privileges[0].Luid = restore_priv;
1735   new_priv.Privileges[0].Attributes = enable ? SE_PRIVILEGE_ENABLED : 0;
1736
1737   if (!AdjustTokenPrivileges (token_hdl, FALSE, &new_priv,
1738                               sizeof orig_priv, &orig_priv, &size))
1739     goto out;
1740 #if 0
1741   /* Disabled, otherwise every `attach' in an unprivileged user session
1742      would raise the "Failed to get SE_DEBUG_NAME privilege" warning in
1743      windows_attach().  */
1744   /* AdjustTokenPrivileges returns TRUE even if the privilege could not
1745      be enabled.  GetLastError () returns an correct error code, though.  */
1746   if (enable && GetLastError () == ERROR_NOT_ALL_ASSIGNED)
1747     goto out;
1748 #endif
1749
1750   ret = orig_priv.Privileges[0].Attributes == SE_PRIVILEGE_ENABLED ? 1 : 0;
1751
1752 out:
1753   if (token_hdl)
1754     CloseHandle (token_hdl);
1755
1756   return ret;
1757 }
1758
1759 /* Attach to process PID, then initialize for debugging it.  */
1760 static void
1761 windows_attach (struct target_ops *ops, const char *args, int from_tty)
1762 {
1763   BOOL ok;
1764   DWORD pid;
1765
1766   pid = parse_pid_to_attach (args);
1767
1768   if (set_process_privilege (SE_DEBUG_NAME, TRUE) < 0)
1769     {
1770       printf_unfiltered ("Warning: Failed to get SE_DEBUG_NAME privilege\n");
1771       printf_unfiltered ("This can cause attach to "
1772                          "fail on Windows NT/2K/XP\n");
1773     }
1774
1775   windows_init_thread_list ();
1776   ok = DebugActiveProcess (pid);
1777   saw_create = 0;
1778
1779 #ifdef __CYGWIN__
1780   if (!ok)
1781     {
1782       /* Try fall back to Cygwin pid.  */
1783       pid = cygwin_internal (CW_CYGWIN_PID_TO_WINPID, pid);
1784
1785       if (pid > 0)
1786         ok = DebugActiveProcess (pid);
1787   }
1788 #endif
1789
1790   if (!ok)
1791     error (_("Can't attach to process."));
1792
1793   DebugSetProcessKillOnExit (FALSE);
1794
1795   if (from_tty)
1796     {
1797       char *exec_file = (char *) get_exec_file (0);
1798
1799       if (exec_file)
1800         printf_unfiltered ("Attaching to program `%s', %s\n", exec_file,
1801                            target_pid_to_str (pid_to_ptid (pid)));
1802       else
1803         printf_unfiltered ("Attaching to %s\n",
1804                            target_pid_to_str (pid_to_ptid (pid)));
1805
1806       gdb_flush (gdb_stdout);
1807     }
1808
1809   do_initial_windows_stuff (ops, pid, 1);
1810   target_terminal_ours ();
1811 }
1812
1813 static void
1814 windows_detach (struct target_ops *ops, const char *args, int from_tty)
1815 {
1816   int detached = 1;
1817
1818   ptid_t ptid = {-1};
1819   windows_resume (ops, ptid, 0, GDB_SIGNAL_0);
1820
1821   if (!DebugActiveProcessStop (current_event.dwProcessId))
1822     {
1823       error (_("Can't detach process %u (error %u)"),
1824              (unsigned) current_event.dwProcessId, (unsigned) GetLastError ());
1825       detached = 0;
1826     }
1827   DebugSetProcessKillOnExit (FALSE);
1828
1829   if (detached && from_tty)
1830     {
1831       char *exec_file = get_exec_file (0);
1832       if (exec_file == 0)
1833         exec_file = "";
1834       printf_unfiltered ("Detaching from program: %s, Pid %u\n", exec_file,
1835                          (unsigned) current_event.dwProcessId);
1836       gdb_flush (gdb_stdout);
1837     }
1838
1839   x86_cleanup_dregs ();
1840   inferior_ptid = null_ptid;
1841   detach_inferior (current_event.dwProcessId);
1842
1843   inf_child_maybe_unpush_target (ops);
1844 }
1845
1846 /* Try to determine the executable filename.
1847
1848    EXE_NAME_RET is a pointer to a buffer whose size is EXE_NAME_MAX_LEN.
1849
1850    Upon success, the filename is stored inside EXE_NAME_RET, and
1851    this function returns nonzero.
1852
1853    Otherwise, this function returns zero and the contents of
1854    EXE_NAME_RET is undefined.  */
1855
1856 static int
1857 windows_get_exec_module_filename (char *exe_name_ret, size_t exe_name_max_len)
1858 {
1859   DWORD len;
1860   HMODULE dh_buf;
1861   DWORD cbNeeded;
1862
1863   cbNeeded = 0;
1864   if (!EnumProcessModules (current_process_handle, &dh_buf,
1865                            sizeof (HMODULE), &cbNeeded) || !cbNeeded)
1866     return 0;
1867
1868   /* We know the executable is always first in the list of modules,
1869      which we just fetched.  So no need to fetch more.  */
1870
1871 #ifdef __CYGWIN__
1872   {
1873     /* Cygwin prefers that the path be in /x/y/z format, so extract
1874        the filename into a temporary buffer first, and then convert it
1875        to POSIX format into the destination buffer.  */
1876     cygwin_buf_t *pathbuf = alloca (exe_name_max_len * sizeof (cygwin_buf_t));
1877
1878     len = GetModuleFileNameEx (current_process_handle,
1879                                dh_buf, pathbuf, exe_name_max_len);
1880     if (len == 0)
1881       error (_("Error getting executable filename: %u."),
1882              (unsigned) GetLastError ());
1883     if (cygwin_conv_path (CCP_WIN_W_TO_POSIX, pathbuf, exe_name_ret,
1884                           exe_name_max_len) < 0)
1885       error (_("Error converting executable filename to POSIX: %d."), errno);
1886   }
1887 #else
1888   len = GetModuleFileNameEx (current_process_handle,
1889                              dh_buf, exe_name_ret, exe_name_max_len);
1890   if (len == 0)
1891     error (_("Error getting executable filename: %u."),
1892            (unsigned) GetLastError ());
1893 #endif
1894
1895     return 1;   /* success */
1896 }
1897
1898 /* The pid_to_exec_file target_ops method for this platform.  */
1899
1900 static char *
1901 windows_pid_to_exec_file (struct target_ops *self, int pid)
1902 {
1903   static char path[__PMAX];
1904 #ifdef __CYGWIN__
1905   /* Try to find exe name as symlink target of /proc/<pid>/exe.  */
1906   int nchars;
1907   char procexe[sizeof ("/proc/4294967295/exe")];
1908
1909   xsnprintf (procexe, sizeof (procexe), "/proc/%u/exe", pid);
1910   nchars = readlink (procexe, path, sizeof(path));
1911   if (nchars > 0 && nchars < sizeof (path))
1912     {
1913       path[nchars] = '\0';      /* Got it */
1914       return path;
1915     }
1916 #endif
1917
1918   /* If we get here then either Cygwin is hosed, this isn't a Cygwin version
1919      of gdb, or we're trying to debug a non-Cygwin windows executable.  */
1920   if (!windows_get_exec_module_filename (path, sizeof (path)))
1921     path[0] = '\0';
1922
1923   return path;
1924 }
1925
1926 /* Print status information about what we're accessing.  */
1927
1928 static void
1929 windows_files_info (struct target_ops *ignore)
1930 {
1931   struct inferior *inf = current_inferior ();
1932
1933   printf_unfiltered ("\tUsing the running image of %s %s.\n",
1934                      inf->attach_flag ? "attached" : "child",
1935                      target_pid_to_str (inferior_ptid));
1936 }
1937
1938 /* Modify CreateProcess parameters for use of a new separate console.
1939    Parameters are:
1940    *FLAGS: DWORD parameter for general process creation flags.
1941    *SI: STARTUPINFO structure, for which the console window size and
1942    console buffer size is filled in if GDB is running in a console.
1943    to create the new console.
1944    The size of the used font is not available on all versions of
1945    Windows OS.  Furthermore, the current font might not be the default
1946    font, but this is still better than before.
1947    If the windows and buffer sizes are computed,
1948    SI->DWFLAGS is changed so that this information is used
1949    by CreateProcess function.  */
1950
1951 static void
1952 windows_set_console_info (STARTUPINFO *si, DWORD *flags)
1953 {
1954   HANDLE hconsole = CreateFile ("CONOUT$", GENERIC_READ | GENERIC_WRITE,
1955                                 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
1956
1957   if (hconsole != INVALID_HANDLE_VALUE)
1958     {
1959       CONSOLE_SCREEN_BUFFER_INFO sbinfo;
1960       COORD font_size;
1961       CONSOLE_FONT_INFO cfi;
1962
1963       GetCurrentConsoleFont (hconsole, FALSE, &cfi);
1964       font_size = GetConsoleFontSize (hconsole, cfi.nFont);
1965       GetConsoleScreenBufferInfo(hconsole, &sbinfo);
1966       si->dwXSize = sbinfo.srWindow.Right - sbinfo.srWindow.Left + 1;
1967       si->dwYSize = sbinfo.srWindow.Bottom - sbinfo.srWindow.Top + 1;
1968       if (font_size.X)
1969         si->dwXSize *= font_size.X;
1970       else
1971         si->dwXSize *= 8;
1972       if (font_size.Y)
1973         si->dwYSize *= font_size.Y;
1974       else
1975         si->dwYSize *= 12;
1976       si->dwXCountChars = sbinfo.dwSize.X;
1977       si->dwYCountChars = sbinfo.dwSize.Y;
1978       si->dwFlags |= STARTF_USESIZE | STARTF_USECOUNTCHARS;
1979     }
1980   *flags |= CREATE_NEW_CONSOLE;
1981 }
1982
1983 #ifndef __CYGWIN__
1984 /* Function called by qsort to sort environment strings.  */
1985
1986 static int
1987 envvar_cmp (const void *a, const void *b)
1988 {
1989   const char **p = (const char **) a;
1990   const char **q = (const char **) b;
1991   return strcasecmp (*p, *q);
1992 }
1993 #endif
1994
1995 #ifdef __CYGWIN__
1996 static void
1997 clear_win32_environment (char **env)
1998 {
1999   int i;
2000   size_t len;
2001   wchar_t *copy = NULL, *equalpos;
2002
2003   for (i = 0; env[i] && *env[i]; i++)
2004     {
2005       len = mbstowcs (NULL, env[i], 0) + 1;
2006       copy = (wchar_t *) xrealloc (copy, len * sizeof (wchar_t));
2007       mbstowcs (copy, env[i], len);
2008       equalpos = wcschr (copy, L'=');
2009       if (equalpos)
2010         *equalpos = L'\0';
2011       SetEnvironmentVariableW (copy, NULL);
2012     }
2013   xfree (copy);
2014 }
2015 #endif
2016
2017 /* Start an inferior windows child process and sets inferior_ptid to its pid.
2018    EXEC_FILE is the file to run.
2019    ALLARGS is a string containing the arguments to the program.
2020    ENV is the environment vector to pass.  Errors reported with error().  */
2021
2022 static void
2023 windows_create_inferior (struct target_ops *ops, char *exec_file,
2024                        char *allargs, char **in_env, int from_tty)
2025 {
2026   STARTUPINFO si;
2027 #ifdef __CYGWIN__
2028   cygwin_buf_t real_path[__PMAX];
2029   cygwin_buf_t shell[__PMAX]; /* Path to shell */
2030   const char *sh;
2031   cygwin_buf_t *toexec;
2032   cygwin_buf_t *cygallargs;
2033   cygwin_buf_t *args;
2034   char **old_env = NULL;
2035   PWCHAR w32_env;
2036   size_t len;
2037   int tty;
2038   int ostdin, ostdout, ostderr;
2039 #else
2040   char real_path[__PMAX];
2041   char shell[__PMAX]; /* Path to shell */
2042   char *toexec;
2043   char *args;
2044   size_t args_len;
2045   HANDLE tty;
2046   char *w32env;
2047   char *temp;
2048   size_t envlen;
2049   int i;
2050   size_t envsize;
2051   char **env;
2052 #endif
2053   PROCESS_INFORMATION pi;
2054   BOOL ret;
2055   DWORD flags = 0;
2056   const char *inferior_io_terminal = get_inferior_io_terminal ();
2057
2058   if (!exec_file)
2059     error (_("No executable specified, use `target exec'."));
2060
2061   memset (&si, 0, sizeof (si));
2062   si.cb = sizeof (si);
2063
2064   if (new_group)
2065     flags |= CREATE_NEW_PROCESS_GROUP;
2066
2067   if (new_console)
2068     windows_set_console_info (&si, &flags);
2069
2070 #ifdef __CYGWIN__
2071   if (!useshell)
2072     {
2073       flags |= DEBUG_ONLY_THIS_PROCESS;
2074       if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, exec_file, real_path,
2075                             __PMAX * sizeof (cygwin_buf_t)) < 0)
2076         error (_("Error starting executable: %d"), errno);
2077       toexec = real_path;
2078 #ifdef __USEWIDE
2079       len = mbstowcs (NULL, allargs, 0) + 1;
2080       if (len == (size_t) -1)
2081         error (_("Error starting executable: %d"), errno);
2082       cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
2083       mbstowcs (cygallargs, allargs, len);
2084 #else
2085       cygallargs = allargs;
2086 #endif
2087     }
2088   else
2089     {
2090       sh = getenv ("SHELL");
2091       if (!sh)
2092         sh = "/bin/sh";
2093       if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, sh, shell, __PMAX) < 0)
2094         error (_("Error starting executable via shell: %d"), errno);
2095 #ifdef __USEWIDE
2096       len = sizeof (L" -c 'exec  '") + mbstowcs (NULL, exec_file, 0)
2097             + mbstowcs (NULL, allargs, 0) + 2;
2098       cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
2099       swprintf (cygallargs, len, L" -c 'exec %s %s'", exec_file, allargs);
2100 #else
2101       len = (sizeof (" -c 'exec  '") + strlen (exec_file)
2102              + strlen (allargs) + 2);
2103       cygallargs = (char *) alloca (len);
2104       xsnprintf (cygallargs, len, " -c 'exec %s %s'", exec_file, allargs);
2105 #endif
2106       toexec = shell;
2107       flags |= DEBUG_PROCESS;
2108     }
2109
2110 #ifdef __USEWIDE
2111   args = (cygwin_buf_t *) alloca ((wcslen (toexec) + wcslen (cygallargs) + 2)
2112                                   * sizeof (wchar_t));
2113   wcscpy (args, toexec);
2114   wcscat (args, L" ");
2115   wcscat (args, cygallargs);
2116 #else
2117   args = (cygwin_buf_t *) alloca (strlen (toexec) + strlen (cygallargs) + 2);
2118   strcpy (args, toexec);
2119   strcat (args, " ");
2120   strcat (args, cygallargs);
2121 #endif
2122
2123 #ifdef CW_CVT_ENV_TO_WINENV
2124   /* First try to create a direct Win32 copy of the POSIX environment. */
2125   w32_env = (PWCHAR) cygwin_internal (CW_CVT_ENV_TO_WINENV, in_env);
2126   if (w32_env != (PWCHAR) -1)
2127     flags |= CREATE_UNICODE_ENVIRONMENT;
2128   else
2129     /* If that fails, fall back to old method tweaking GDB's environment. */
2130 #endif
2131     {
2132       /* Reset all Win32 environment variables to avoid leftover on next run. */
2133       clear_win32_environment (environ);
2134       /* Prepare the environment vars for CreateProcess.  */
2135       old_env = environ;
2136       environ = in_env;
2137       cygwin_internal (CW_SYNC_WINENV);
2138       w32_env = NULL;
2139     }
2140
2141   if (!inferior_io_terminal)
2142     tty = ostdin = ostdout = ostderr = -1;
2143   else
2144     {
2145       tty = open (inferior_io_terminal, O_RDWR | O_NOCTTY);
2146       if (tty < 0)
2147         {
2148           print_sys_errmsg (inferior_io_terminal, errno);
2149           ostdin = ostdout = ostderr = -1;
2150         }
2151       else
2152         {
2153           ostdin = dup (0);
2154           ostdout = dup (1);
2155           ostderr = dup (2);
2156           dup2 (tty, 0);
2157           dup2 (tty, 1);
2158           dup2 (tty, 2);
2159         }
2160     }
2161
2162   windows_init_thread_list ();
2163   ret = CreateProcess (0,
2164                        args,    /* command line */
2165                        NULL,    /* Security */
2166                        NULL,    /* thread */
2167                        TRUE,    /* inherit handles */
2168                        flags,   /* start flags */
2169                        w32_env, /* environment */
2170                        NULL,    /* current directory */
2171                        &si,
2172                        &pi);
2173   if (w32_env)
2174     /* Just free the Win32 environment, if it could be created. */
2175     free (w32_env);
2176   else
2177     {
2178       /* Reset all environment variables to avoid leftover on next run. */
2179       clear_win32_environment (in_env);
2180       /* Restore normal GDB environment variables.  */
2181       environ = old_env;
2182       cygwin_internal (CW_SYNC_WINENV);
2183     }
2184
2185   if (tty >= 0)
2186     {
2187       close (tty);
2188       dup2 (ostdin, 0);
2189       dup2 (ostdout, 1);
2190       dup2 (ostderr, 2);
2191       close (ostdin);
2192       close (ostdout);
2193       close (ostderr);
2194     }
2195 #else
2196   toexec = exec_file;
2197   /* Build the command line, a space-separated list of tokens where
2198      the first token is the name of the module to be executed.
2199      To avoid ambiguities introduced by spaces in the module name,
2200      we quote it.  */
2201   args_len = strlen (toexec) + 2 /* quotes */ + strlen (allargs) + 2;
2202   args = alloca (args_len);
2203   xsnprintf (args, args_len, "\"%s\" %s", toexec, allargs);
2204
2205   flags |= DEBUG_ONLY_THIS_PROCESS;
2206
2207   if (!inferior_io_terminal)
2208     tty = INVALID_HANDLE_VALUE;
2209   else
2210     {
2211       SECURITY_ATTRIBUTES sa;
2212       sa.nLength = sizeof(sa);
2213       sa.lpSecurityDescriptor = 0;
2214       sa.bInheritHandle = TRUE;
2215       tty = CreateFileA (inferior_io_terminal, GENERIC_READ | GENERIC_WRITE,
2216                          0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
2217       if (tty == INVALID_HANDLE_VALUE)
2218         warning (_("Warning: Failed to open TTY %s, error %#x."),
2219                  inferior_io_terminal, (unsigned) GetLastError ());
2220       else
2221         {
2222           si.hStdInput = tty;
2223           si.hStdOutput = tty;
2224           si.hStdError = tty;
2225           si.dwFlags |= STARTF_USESTDHANDLES;
2226         }
2227     }
2228
2229   /* CreateProcess takes the environment list as a null terminated set of
2230      strings (i.e. two nulls terminate the list).  */
2231
2232   /* Get total size for env strings.  */
2233   for (envlen = 0, i = 0; in_env[i] && *in_env[i]; i++)
2234     envlen += strlen (in_env[i]) + 1;
2235
2236   envsize = sizeof (in_env[0]) * (i + 1);
2237   env = (char **) alloca (envsize);
2238   memcpy (env, in_env, envsize);
2239   /* Windows programs expect the environment block to be sorted.  */
2240   qsort (env, i, sizeof (char *), envvar_cmp);
2241
2242   w32env = alloca (envlen + 1);
2243
2244   /* Copy env strings into new buffer.  */
2245   for (temp = w32env, i = 0; env[i] && *env[i]; i++)
2246     {
2247       strcpy (temp, env[i]);
2248       temp += strlen (temp) + 1;
2249     }
2250
2251   /* Final nil string to terminate new env.  */
2252   *temp = 0;
2253
2254   windows_init_thread_list ();
2255   ret = CreateProcessA (0,
2256                         args,   /* command line */
2257                         NULL,   /* Security */
2258                         NULL,   /* thread */
2259                         TRUE,   /* inherit handles */
2260                         flags,  /* start flags */
2261                         w32env, /* environment */
2262                         NULL,   /* current directory */
2263                         &si,
2264                         &pi);
2265   if (tty != INVALID_HANDLE_VALUE)
2266     CloseHandle (tty);
2267 #endif
2268
2269   if (!ret)
2270     error (_("Error creating process %s, (error %u)."),
2271            exec_file, (unsigned) GetLastError ());
2272
2273   CloseHandle (pi.hThread);
2274   CloseHandle (pi.hProcess);
2275
2276   if (useshell && shell[0] != '\0')
2277     saw_create = -1;
2278   else
2279     saw_create = 0;
2280
2281   do_initial_windows_stuff (ops, pi.dwProcessId, 0);
2282
2283   /* windows_continue (DBG_CONTINUE, -1, 0); */
2284 }
2285
2286 static void
2287 windows_mourn_inferior (struct target_ops *ops)
2288 {
2289   (void) windows_continue (DBG_CONTINUE, -1, 0);
2290   x86_cleanup_dregs();
2291   if (open_process_used)
2292     {
2293       CHECK (CloseHandle (current_process_handle));
2294       open_process_used = 0;
2295     }
2296   inf_child_mourn_inferior (ops);
2297 }
2298
2299 /* Send a SIGINT to the process group.  This acts just like the user typed a
2300    ^C on the controlling terminal.  */
2301
2302 static void
2303 windows_stop (struct target_ops *self, ptid_t ptid)
2304 {
2305   DEBUG_EVENTS (("gdb: GenerateConsoleCtrlEvent (CTRLC_EVENT, 0)\n"));
2306   CHECK (GenerateConsoleCtrlEvent (CTRL_C_EVENT, current_event.dwProcessId));
2307   registers_changed ();         /* refresh register state */
2308 }
2309
2310 /* Helper for windows_xfer_partial that handles memory transfers.
2311    Arguments are like target_xfer_partial.  */
2312
2313 static enum target_xfer_status
2314 windows_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
2315                      ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
2316 {
2317   SIZE_T done = 0;
2318   BOOL success;
2319   DWORD lasterror = 0;
2320
2321   if (writebuf != NULL)
2322     {
2323       DEBUG_MEM (("gdb: write target memory, %s bytes at %s\n",
2324                   pulongest (len), core_addr_to_string (memaddr)));
2325       success = WriteProcessMemory (current_process_handle,
2326                                     (LPVOID) (uintptr_t) memaddr, writebuf,
2327                                     len, &done);
2328       if (!success)
2329         lasterror = GetLastError ();
2330       FlushInstructionCache (current_process_handle,
2331                              (LPCVOID) (uintptr_t) memaddr, len);
2332     }
2333   else
2334     {
2335       DEBUG_MEM (("gdb: read target memory, %s bytes at %s\n",
2336                   pulongest (len), core_addr_to_string (memaddr)));
2337       success = ReadProcessMemory (current_process_handle,
2338                                    (LPCVOID) (uintptr_t) memaddr, readbuf,
2339                                    len, &done);
2340       if (!success)
2341         lasterror = GetLastError ();
2342     }
2343   *xfered_len = (ULONGEST) done;
2344   if (!success && lasterror == ERROR_PARTIAL_COPY && done > 0)
2345     return TARGET_XFER_OK;
2346   else
2347     return success ? TARGET_XFER_OK : TARGET_XFER_E_IO;
2348 }
2349
2350 static void
2351 windows_kill_inferior (struct target_ops *ops)
2352 {
2353   CHECK (TerminateProcess (current_process_handle, 0));
2354
2355   for (;;)
2356     {
2357       if (!windows_continue (DBG_CONTINUE, -1, 1))
2358         break;
2359       if (!WaitForDebugEvent (&current_event, INFINITE))
2360         break;
2361       if (current_event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
2362         break;
2363     }
2364
2365   target_mourn_inferior ();     /* Or just windows_mourn_inferior?  */
2366 }
2367
2368 static void
2369 windows_close (struct target_ops *self)
2370 {
2371   DEBUG_EVENTS (("gdb: windows_close, inferior_ptid=%d\n",
2372                 ptid_get_pid (inferior_ptid)));
2373 }
2374
2375 /* Convert pid to printable format.  */
2376 static char *
2377 windows_pid_to_str (struct target_ops *ops, ptid_t ptid)
2378 {
2379   static char buf[80];
2380
2381   if (ptid_get_tid (ptid) != 0)
2382     {
2383       snprintf (buf, sizeof (buf), "Thread %d.0x%lx",
2384                 ptid_get_pid (ptid), ptid_get_tid (ptid));
2385       return buf;
2386     }
2387
2388   return normal_pid_to_str (ptid);
2389 }
2390
2391 static enum target_xfer_status
2392 windows_xfer_shared_libraries (struct target_ops *ops,
2393                                enum target_object object, const char *annex,
2394                                gdb_byte *readbuf, const gdb_byte *writebuf,
2395                                ULONGEST offset, ULONGEST len,
2396                                ULONGEST *xfered_len)
2397 {
2398   struct obstack obstack;
2399   const char *buf;
2400   LONGEST len_avail;
2401   struct so_list *so;
2402
2403   if (writebuf)
2404     return TARGET_XFER_E_IO;
2405
2406   obstack_init (&obstack);
2407   obstack_grow_str (&obstack, "<library-list>\n");
2408   for (so = solib_start.next; so; so = so->next)
2409     windows_xfer_shared_library (so->so_name, (CORE_ADDR)
2410                                  (uintptr_t) so->lm_info->load_addr,
2411                                  target_gdbarch (), &obstack);
2412   obstack_grow_str0 (&obstack, "</library-list>\n");
2413
2414   buf = obstack_finish (&obstack);
2415   len_avail = strlen (buf);
2416   if (offset >= len_avail)
2417     len= 0;
2418   else
2419     {
2420       if (len > len_avail - offset)
2421         len = len_avail - offset;
2422       memcpy (readbuf, buf + offset, len);
2423     }
2424
2425   obstack_free (&obstack, NULL);
2426   *xfered_len = (ULONGEST) len;
2427   return len != 0 ? TARGET_XFER_OK : TARGET_XFER_EOF;
2428 }
2429
2430 static enum target_xfer_status
2431 windows_xfer_partial (struct target_ops *ops, enum target_object object,
2432                       const char *annex, gdb_byte *readbuf,
2433                       const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
2434                       ULONGEST *xfered_len)
2435 {
2436   switch (object)
2437     {
2438     case TARGET_OBJECT_MEMORY:
2439       return windows_xfer_memory (readbuf, writebuf, offset, len, xfered_len);
2440
2441     case TARGET_OBJECT_LIBRARIES:
2442       return windows_xfer_shared_libraries (ops, object, annex, readbuf,
2443                                             writebuf, offset, len, xfered_len);
2444
2445     default:
2446       return ops->beneath->to_xfer_partial (ops->beneath, object, annex,
2447                                             readbuf, writebuf, offset, len,
2448                                             xfered_len);
2449     }
2450 }
2451
2452 /* Provide thread local base, i.e. Thread Information Block address.
2453    Returns 1 if ptid is found and sets *ADDR to thread_local_base.  */
2454
2455 static int
2456 windows_get_tib_address (struct target_ops *self,
2457                          ptid_t ptid, CORE_ADDR *addr)
2458 {
2459   windows_thread_info *th;
2460
2461   th = thread_rec (ptid_get_tid (ptid), 0);
2462   if (th == NULL)
2463     return 0;
2464
2465   if (addr != NULL)
2466     *addr = th->thread_local_base;
2467
2468   return 1;
2469 }
2470
2471 static ptid_t
2472 windows_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
2473 {
2474   return ptid_build (ptid_get_pid (inferior_ptid), 0, lwp);
2475 }
2476
2477 static struct target_ops *
2478 windows_target (void)
2479 {
2480   struct target_ops *t = inf_child_target ();
2481
2482   t->to_close = windows_close;
2483   t->to_attach = windows_attach;
2484   t->to_attach_no_wait = 1;
2485   t->to_detach = windows_detach;
2486   t->to_resume = windows_resume;
2487   t->to_wait = windows_wait;
2488   t->to_fetch_registers = windows_fetch_inferior_registers;
2489   t->to_store_registers = windows_store_inferior_registers;
2490   t->to_xfer_partial = windows_xfer_partial;
2491   t->to_files_info = windows_files_info;
2492   t->to_kill = windows_kill_inferior;
2493   t->to_create_inferior = windows_create_inferior;
2494   t->to_mourn_inferior = windows_mourn_inferior;
2495   t->to_thread_alive = windows_thread_alive;
2496   t->to_pid_to_str = windows_pid_to_str;
2497   t->to_stop = windows_stop;
2498   t->to_pid_to_exec_file = windows_pid_to_exec_file;
2499   t->to_get_ada_task_ptid = windows_get_ada_task_ptid;
2500   t->to_get_tib_address = windows_get_tib_address;
2501
2502   return t;
2503 }
2504
2505 static void
2506 set_windows_aliases (char *argv0)
2507 {
2508   add_info_alias ("dll", "sharedlibrary", 1);
2509 }
2510
2511 /* -Wmissing-prototypes */
2512 extern initialize_file_ftype _initialize_windows_nat;
2513
2514 void
2515 _initialize_windows_nat (void)
2516 {
2517   struct target_ops *t;
2518
2519   t = windows_target ();
2520
2521   x86_use_watchpoints (t);
2522
2523   x86_dr_low.set_control = cygwin_set_dr7;
2524   x86_dr_low.set_addr = cygwin_set_dr;
2525   x86_dr_low.get_addr = cygwin_get_dr;
2526   x86_dr_low.get_status = cygwin_get_dr6;
2527   x86_dr_low.get_control = cygwin_get_dr7;
2528
2529   /* x86_dr_low.debug_register_length field is set by
2530      calling x86_set_debug_register_length function
2531      in processor windows specific native file.  */
2532
2533   add_target (t);
2534
2535 #ifdef __CYGWIN__
2536   cygwin_internal (CW_SET_DOS_FILE_WARNING, 0);
2537 #endif
2538
2539 #ifdef __CYGWIN__
2540   add_setshow_boolean_cmd ("shell", class_support, &useshell, _("\
2541 Set use of shell to start subprocess."), _("\
2542 Show use of shell to start subprocess."), NULL,
2543                            NULL,
2544                            NULL, /* FIXME: i18n: */
2545                            &setlist, &showlist);
2546
2547   add_setshow_boolean_cmd ("cygwin-exceptions", class_support,
2548                            &cygwin_exceptions, _("\
2549 Break when an exception is detected in the Cygwin DLL itself."), _("\
2550 Show whether gdb breaks on exceptions in the Cygwin DLL itself."), NULL,
2551                            NULL,
2552                            NULL, /* FIXME: i18n: */
2553                            &setlist, &showlist);
2554 #endif
2555
2556   add_setshow_boolean_cmd ("new-console", class_support, &new_console, _("\
2557 Set creation of new console when creating child process."), _("\
2558 Show creation of new console when creating child process."), NULL,
2559                            NULL,
2560                            NULL, /* FIXME: i18n: */
2561                            &setlist, &showlist);
2562
2563   add_setshow_boolean_cmd ("new-group", class_support, &new_group, _("\
2564 Set creation of new group when creating child process."), _("\
2565 Show creation of new group when creating child process."), NULL,
2566                            NULL,
2567                            NULL, /* FIXME: i18n: */
2568                            &setlist, &showlist);
2569
2570   add_setshow_boolean_cmd ("debugexec", class_support, &debug_exec, _("\
2571 Set whether to display execution in child process."), _("\
2572 Show whether to display execution in child process."), NULL,
2573                            NULL,
2574                            NULL, /* FIXME: i18n: */
2575                            &setlist, &showlist);
2576
2577   add_setshow_boolean_cmd ("debugevents", class_support, &debug_events, _("\
2578 Set whether to display kernel events in child process."), _("\
2579 Show whether to display kernel events in child process."), NULL,
2580                            NULL,
2581                            NULL, /* FIXME: i18n: */
2582                            &setlist, &showlist);
2583
2584   add_setshow_boolean_cmd ("debugmemory", class_support, &debug_memory, _("\
2585 Set whether to display memory accesses in child process."), _("\
2586 Show whether to display memory accesses in child process."), NULL,
2587                            NULL,
2588                            NULL, /* FIXME: i18n: */
2589                            &setlist, &showlist);
2590
2591   add_setshow_boolean_cmd ("debugexceptions", class_support,
2592                            &debug_exceptions, _("\
2593 Set whether to display kernel exceptions in child process."), _("\
2594 Show whether to display kernel exceptions in child process."), NULL,
2595                            NULL,
2596                            NULL, /* FIXME: i18n: */
2597                            &setlist, &showlist);
2598
2599   init_w32_command_list ();
2600
2601   add_cmd ("selector", class_info, display_selectors,
2602            _("Display selectors infos."),
2603            &info_w32_cmdlist);
2604   deprecated_init_ui_hook = set_windows_aliases;
2605 }
2606
2607 /* Hardware watchpoint support, adapted from go32-nat.c code.  */
2608
2609 /* Pass the address ADDR to the inferior in the I'th debug register.
2610    Here we just store the address in dr array, the registers will be
2611    actually set up when windows_continue is called.  */
2612 static void
2613 cygwin_set_dr (int i, CORE_ADDR addr)
2614 {
2615   if (i < 0 || i > 3)
2616     internal_error (__FILE__, __LINE__,
2617                     _("Invalid register %d in cygwin_set_dr.\n"), i);
2618   dr[i] = addr;
2619   debug_registers_changed = 1;
2620   debug_registers_used = 1;
2621 }
2622
2623 /* Pass the value VAL to the inferior in the DR7 debug control
2624    register.  Here we just store the address in D_REGS, the watchpoint
2625    will be actually set up in windows_wait.  */
2626 static void
2627 cygwin_set_dr7 (unsigned long val)
2628 {
2629   dr[7] = (CORE_ADDR) val;
2630   debug_registers_changed = 1;
2631   debug_registers_used = 1;
2632 }
2633
2634 /* Get the value of debug register I from the inferior.  */
2635
2636 static CORE_ADDR
2637 cygwin_get_dr (int i)
2638 {
2639   return dr[i];
2640 }
2641
2642 /* Get the value of the DR6 debug status register from the inferior.
2643    Here we just return the value stored in dr[6]
2644    by the last call to thread_rec for current_event.dwThreadId id.  */
2645 static unsigned long
2646 cygwin_get_dr6 (void)
2647 {
2648   return (unsigned long) dr[6];
2649 }
2650
2651 /* Get the value of the DR7 debug status register from the inferior.
2652    Here we just return the value stored in dr[7] by the last call to
2653    thread_rec for current_event.dwThreadId id.  */
2654
2655 static unsigned long
2656 cygwin_get_dr7 (void)
2657 {
2658   return (unsigned long) dr[7];
2659 }
2660
2661 /* Determine if the thread referenced by "ptid" is alive
2662    by "polling" it.  If WaitForSingleObject returns WAIT_OBJECT_0
2663    it means that the thread has died.  Otherwise it is assumed to be alive.  */
2664 static int
2665 windows_thread_alive (struct target_ops *ops, ptid_t ptid)
2666 {
2667   int tid;
2668
2669   gdb_assert (ptid_get_tid (ptid) != 0);
2670   tid = ptid_get_tid (ptid);
2671
2672   return WaitForSingleObject (thread_rec (tid, FALSE)->h, 0) == WAIT_OBJECT_0
2673     ? FALSE : TRUE;
2674 }
2675
2676 /* -Wmissing-prototypes */
2677 extern initialize_file_ftype _initialize_check_for_gdb_ini;
2678
2679 void
2680 _initialize_check_for_gdb_ini (void)
2681 {
2682   char *homedir;
2683   if (inhibit_gdbinit)
2684     return;
2685
2686   homedir = getenv ("HOME");
2687   if (homedir)
2688     {
2689       char *p;
2690       char *oldini = (char *) alloca (strlen (homedir) +
2691                                       sizeof ("/gdb.ini"));
2692       strcpy (oldini, homedir);
2693       p = strchr (oldini, '\0');
2694       if (p > oldini && !IS_DIR_SEPARATOR (p[-1]))
2695         *p++ = '/';
2696       strcpy (p, "gdb.ini");
2697       if (access (oldini, 0) == 0)
2698         {
2699           int len = strlen (oldini);
2700           char *newini = alloca (len + 1);
2701
2702           xsnprintf (newini, len + 1, "%.*s.gdbinit",
2703                      (int) (len - (sizeof ("gdb.ini") - 1)), oldini);
2704           warning (_("obsolete '%s' found. Rename to '%s'."), oldini, newini);
2705         }
2706     }
2707 }
2708
2709 /* Define dummy functions which always return error for the rare cases where
2710    these functions could not be found.  */
2711 static BOOL WINAPI
2712 bad_DebugActiveProcessStop (DWORD w)
2713 {
2714   return FALSE;
2715 }
2716 static BOOL WINAPI
2717 bad_DebugBreakProcess (HANDLE w)
2718 {
2719   return FALSE;
2720 }
2721 static BOOL WINAPI
2722 bad_DebugSetProcessKillOnExit (BOOL w)
2723 {
2724   return FALSE;
2725 }
2726 static BOOL WINAPI
2727 bad_EnumProcessModules (HANDLE w, HMODULE *x, DWORD y, LPDWORD z)
2728 {
2729   return FALSE;
2730 }
2731
2732 #ifdef __USEWIDE
2733 static DWORD WINAPI
2734 bad_GetModuleFileNameExW (HANDLE w, HMODULE x, LPWSTR y, DWORD z)
2735 {
2736   return 0;
2737 }
2738 #else
2739 static DWORD WINAPI
2740 bad_GetModuleFileNameExA (HANDLE w, HMODULE x, LPSTR y, DWORD z)
2741 {
2742   return 0;
2743 }
2744 #endif
2745
2746 static BOOL WINAPI
2747 bad_GetModuleInformation (HANDLE w, HMODULE x, LPMODULEINFO y, DWORD z)
2748 {
2749   return FALSE;
2750 }
2751
2752 static BOOL WINAPI
2753 bad_OpenProcessToken (HANDLE w, DWORD x, PHANDLE y)
2754 {
2755   return FALSE;
2756 }
2757
2758 static BOOL WINAPI
2759 bad_GetCurrentConsoleFont (HANDLE w, BOOL bMaxWindow, CONSOLE_FONT_INFO *f)
2760 {
2761   f->nFont = 0;
2762   return 1;
2763 }
2764 static COORD WINAPI
2765 bad_GetConsoleFontSize (HANDLE w, DWORD nFont)
2766 {
2767   COORD size;
2768   size.X = 8;
2769   size.Y = 12;
2770   return size;
2771 }
2772  
2773 /* -Wmissing-prototypes */
2774 extern initialize_file_ftype _initialize_loadable;
2775
2776 /* Load any functions which may not be available in ancient versions
2777    of Windows.  */
2778
2779 void
2780 _initialize_loadable (void)
2781 {
2782   HMODULE hm = NULL;
2783
2784   hm = LoadLibrary ("kernel32.dll");
2785   if (hm)
2786     {
2787       DebugActiveProcessStop = (void *)
2788         GetProcAddress (hm, "DebugActiveProcessStop");
2789       DebugBreakProcess = (void *)
2790         GetProcAddress (hm, "DebugBreakProcess");
2791       DebugSetProcessKillOnExit = (void *)
2792         GetProcAddress (hm, "DebugSetProcessKillOnExit");
2793       GetConsoleFontSize = (void *) 
2794         GetProcAddress (hm, "GetConsoleFontSize");
2795       GetCurrentConsoleFont = (void *) 
2796         GetProcAddress (hm, "GetCurrentConsoleFont");
2797     }
2798
2799   /* Set variables to dummy versions of these processes if the function
2800      wasn't found in kernel32.dll.  */
2801   if (!DebugBreakProcess)
2802     DebugBreakProcess = bad_DebugBreakProcess;
2803   if (!DebugActiveProcessStop || !DebugSetProcessKillOnExit)
2804     {
2805       DebugActiveProcessStop = bad_DebugActiveProcessStop;
2806       DebugSetProcessKillOnExit = bad_DebugSetProcessKillOnExit;
2807     }
2808   if (!GetConsoleFontSize)
2809     GetConsoleFontSize = bad_GetConsoleFontSize;
2810   if (!GetCurrentConsoleFont)
2811     GetCurrentConsoleFont = bad_GetCurrentConsoleFont;
2812
2813   /* Load optional functions used for retrieving filename information
2814      associated with the currently debugged process or its dlls.  */
2815   hm = LoadLibrary ("psapi.dll");
2816   if (hm)
2817     {
2818       EnumProcessModules = (void *)
2819         GetProcAddress (hm, "EnumProcessModules");
2820       GetModuleInformation = (void *)
2821         GetProcAddress (hm, "GetModuleInformation");
2822       GetModuleFileNameEx = (void *)
2823         GetProcAddress (hm, GetModuleFileNameEx_name);
2824     }
2825
2826   if (!EnumProcessModules || !GetModuleInformation || !GetModuleFileNameEx)
2827     {
2828       /* Set variables to dummy versions of these processes if the function
2829          wasn't found in psapi.dll.  */
2830       EnumProcessModules = bad_EnumProcessModules;
2831       GetModuleInformation = bad_GetModuleInformation;
2832       GetModuleFileNameEx = bad_GetModuleFileNameEx;
2833       /* This will probably fail on Windows 9x/Me.  Let the user know
2834          that we're missing some functionality.  */
2835       warning(_("\
2836 cannot automatically find executable file or library to read symbols.\n\
2837 Use \"file\" or \"dll\" command to load executable/libraries directly."));
2838     }
2839
2840   hm = LoadLibrary ("advapi32.dll");
2841   if (hm)
2842     {
2843       OpenProcessToken = (void *) GetProcAddress (hm, "OpenProcessToken");
2844       LookupPrivilegeValueA = (void *)
2845         GetProcAddress (hm, "LookupPrivilegeValueA");
2846       AdjustTokenPrivileges = (void *)
2847         GetProcAddress (hm, "AdjustTokenPrivileges");
2848       /* Only need to set one of these since if OpenProcessToken fails nothing
2849          else is needed.  */
2850       if (!OpenProcessToken || !LookupPrivilegeValueA
2851           || !AdjustTokenPrivileges)
2852         OpenProcessToken = bad_OpenProcessToken;
2853     }
2854 }