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