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