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