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