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