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