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