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