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