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