]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/windows-nat.c
windows-nat: Remove SO_NAME_MAX_PATH_SIZE limit
[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 {
60c5c021 894 char *rname = realpath (name, NULL);
30512efa 895 if (rname != nullptr)
d0d0ab16 896 {
85b25bd9 897 so->name = rname;
d0d0ab16
CV
898 free (rname);
899 }
900 else
a0e9b532 901 {
30512efa 902 warning (_("dll path for \"%s\" inaccessible"), name);
85b25bd9 903 so->name = so->original_name;
a0e9b532 904 }
d0d0ab16 905 }
de1b3c3d 906 /* Record cygwin1.dll .text start/end. */
85b25bd9
TT
907 size_t len = sizeof ("/cygwin1.dll") - 1;
908 if (so->name.size () >= len
909 && strcasecmp (so->name.c_str () + so->name.size () - len,
910 "/cygwin1.dll") == 0)
de1b3c3d 911 {
de1b3c3d 912 asection *text = NULL;
8e860359 913
a115c6d6 914 gdb_bfd_ref_ptr abfd (gdb_bfd_open (so->name.c_str(), "pei-i386"));
a244bdca 915
192b62ce 916 if (abfd == NULL)
de1b3c3d
PA
917 return so;
918
192b62ce
TT
919 if (bfd_check_format (abfd.get (), bfd_object))
920 text = bfd_get_section_by_name (abfd.get (), ".text");
de1b3c3d
PA
921
922 if (!text)
192b62ce 923 return so;
de1b3c3d 924
7a9dd1b2 925 /* The symbols in a dll are offset by 0x1000, which is the
de1b3c3d 926 offset from 0 of the first byte in an image - because of the
581e13c1 927 file header and the section alignment. */
26f228db
JT
928 windows_process.cygwin_load_start = (CORE_ADDR) (uintptr_t) ((char *)
929 load_addr + 0x1000);
930 windows_process.cygwin_load_end = windows_process.cygwin_load_start +
931 bfd_section_size (text);
de1b3c3d 932 }
10325bc5 933#endif
de1b3c3d
PA
934
935 return so;
8e860359
CF
936}
937
a816ba18 938/* See nat/windows-nat.h. */
1cd9feab 939
a816ba18 940void
20489cca 941windows_per_inferior::handle_load_dll (const char *dll_name, LPVOID base)
24e60978 942{
85b25bd9
TT
943 windows_solib *solib = windows_make_so (dll_name, base);
944 DEBUG_EVENTS ("Loading dll \"%s\" at %s.", solib->name.c_str (),
945 host_address_to_string (solib->load_addr));
3cb8e7f6
CF
946}
947
a816ba18 948/* See nat/windows-nat.h. */
3be75f87 949
a816ba18 950void
20489cca 951windows_per_inferior::handle_unload_dll ()
d3ff4a77 952{
d3653bf6 953 LPVOID lpBaseOfDll = current_event.u.UnloadDll.lpBaseOfDll;
d3ff4a77 954
20489cca
TT
955 auto iter = std::remove_if (windows_process.solibs.begin (),
956 windows_process.solibs.end (),
85b25bd9 957 [&] (windows_solib &lib)
d0e449a1 958 {
85b25bd9 959 if (lib.load_addr == lpBaseOfDll)
d0e449a1 960 {
85b25bd9
TT
961 DEBUG_EVENTS ("Unloading dll \"%s\".", lib.name.c_str ());
962 return true;
d0e449a1 963 }
85b25bd9
TT
964 return false;
965 });
966
20489cca 967 if (iter != windows_process.solibs.end ())
85b25bd9 968 {
20489cca 969 windows_process.solibs.erase (iter, windows_process.solibs.end ());
85b25bd9 970 return;
d0e449a1 971 }
3929abe9 972
ecc13e53
JB
973 /* We did not find any DLL that was previously loaded at this address,
974 so register a complaint. We do not report an error, because we have
975 observed that this may be happening under some circumstances. For
976 instance, running 32bit applications on x64 Windows causes us to receive
977 4 mysterious UNLOAD_DLL_DEBUG_EVENTs during the startup phase (these
978 events are apparently caused by the WOW layer, the interface between
979 32bit and 64bit worlds). */
b98664d3 980 complaint (_("dll starting at %s not found."),
ecc13e53 981 host_address_to_string (lpBaseOfDll));
bf469271
PA
982}
983
581e13c1 984/* Clear list of loaded DLLs. */
3ee6f623 985static void
dc05df57 986windows_clear_solib (void)
450005e7 987{
20489cca 988 windows_process.solibs.clear ();
450005e7 989}
295732ea 990
463888ab 991static void
0b39b52e 992signal_event_command (const char *args, int from_tty)
463888ab
РИ
993{
994 uintptr_t event_id = 0;
995 char *endargs = NULL;
996
997 if (args == NULL)
998 error (_("signal-event requires an argument (integer event id)"));
999
1000 event_id = strtoumax (args, &endargs, 10);
1001
1002 if ((errno == ERANGE) || (event_id == 0) || (event_id > UINTPTR_MAX) ||
1003 ((HANDLE) event_id == INVALID_HANDLE_VALUE))
1004 error (_("Failed to convert `%s' to event id"), args);
1005
1006 SetEvent ((HANDLE) event_id);
1007 CloseHandle ((HANDLE) event_id);
1008}
1009
d41b524f
TT
1010/* See nat/windows-nat.h. */
1011
1012int
20489cca 1013windows_per_inferior::handle_output_debug_string
0578e87f 1014 (struct target_waitstatus *ourstatus)
3cee93ac 1015{
a244bdca 1016 int retval = 0;
3cee93ac 1017
66920317
TT
1018 gdb::unique_xmalloc_ptr<char> s
1019 = (target_read_string
1020 ((CORE_ADDR) (uintptr_t) current_event.u.DebugString.lpDebugStringData,
1021 1024));
1022 if (s == nullptr || !*(s.get ()))
a244bdca 1023 /* nothing to do */;
e83e4e24 1024 else if (!startswith (s.get (), _CYGWIN_SIGNAL_STRING))
3cee93ac 1025 {
10325bc5 1026#ifdef __CYGWIN__
e83e4e24 1027 if (!startswith (s.get (), "cYg"))
10325bc5 1028#endif
040ea00b 1029 {
e83e4e24 1030 char *p = strchr (s.get (), '\0');
040ea00b 1031
e83e4e24 1032 if (p > s.get () && *--p == '\n')
040ea00b 1033 *p = '\0';
e83e4e24 1034 warning (("%s"), s.get ());
040ea00b 1035 }
3cee93ac 1036 }
f20c58f5 1037#ifdef __CYGWIN__
d3a09475 1038 else
3cee93ac 1039 {
e433bca4
JT
1040 /* Got a cygwin signal marker. A cygwin signal marker is
1041 followed by the signal number itself, and (since Cygwin 1.7)
1042 the thread id, and the address of a saved context in the
1043 inferior (That context has an IP which is the return address
1044 in "user" code of the cygwin internal signal handling code,
1045 but is not otherwise usable).
1046
1047 Tell gdb to treat this like the given thread issued a real
1048 signal. */
3cee93ac 1049 char *p;
e83e4e24 1050 int sig = strtol (s.get () + sizeof (_CYGWIN_SIGNAL_STRING) - 1, &p, 0);
0ae534d2 1051 gdb_signal gotasig = gdb_signal_from_host (sig);
e433bca4 1052 LPCVOID x = 0;
c62fa0e2 1053
0714f9bf 1054 if (gotasig)
a244bdca 1055 {
183be222 1056 ourstatus->set_stopped (gotasig);
a244bdca
CF
1057 retval = strtoul (p, &p, 0);
1058 if (!retval)
ab4ee614 1059 retval = current_event.dwThreadId;
e433bca4
JT
1060 else
1061 x = (LPCVOID) (uintptr_t) strtoull (p, NULL, 0);
a244bdca 1062 }
e433bca4
JT
1063
1064 DEBUG_EVENTS ("gdb: cygwin signal %d, thread 0x%x, CONTEXT @ %p",
1065 gotasig, retval, x);
3cee93ac 1066 }
cb832706 1067#endif
3cee93ac 1068
a244bdca 1069 return retval;
3cee93ac 1070}
24e60978 1071
c1748f97
PM
1072static int
1073display_selector (HANDLE thread, DWORD sel)
1074{
1075 LDT_ENTRY info;
46f9f931
HD
1076 BOOL ret;
1077#ifdef __x86_64__
0578e87f 1078 if (windows_process.wow64_process)
46f9f931
HD
1079 ret = Wow64GetThreadSelectorEntry (thread, sel, &info);
1080 else
1081#endif
1082 ret = GetThreadSelectorEntry (thread, sel, &info);
1083 if (ret)
c1748f97
PM
1084 {
1085 int base, limit;
6cb06a8c 1086 gdb_printf ("0x%03x: ", (unsigned) sel);
c1748f97 1087 if (!info.HighWord.Bits.Pres)
baa93fa6 1088 {
0426ad51 1089 gdb_puts ("Segment not present\n");
baa93fa6
CF
1090 return 0;
1091 }
c1748f97
PM
1092 base = (info.HighWord.Bits.BaseHi << 24) +
1093 (info.HighWord.Bits.BaseMid << 16)
1094 + info.BaseLow;
1095 limit = (info.HighWord.Bits.LimitHi << 16) + info.LimitLow;
1096 if (info.HighWord.Bits.Granularity)
caad7706 1097 limit = (limit << 12) | 0xfff;
6cb06a8c 1098 gdb_printf ("base=0x%08x limit=0x%08x", base, limit);
c1748f97 1099 if (info.HighWord.Bits.Default_Big)
0426ad51 1100 gdb_puts(" 32-bit ");
c1748f97 1101 else
0426ad51 1102 gdb_puts(" 16-bit ");
c1748f97
PM
1103 switch ((info.HighWord.Bits.Type & 0xf) >> 1)
1104 {
1105 case 0:
0426ad51 1106 gdb_puts ("Data (Read-Only, Exp-up");
baa93fa6 1107 break;
c1748f97 1108 case 1:
0426ad51 1109 gdb_puts ("Data (Read/Write, Exp-up");
baa93fa6 1110 break;
c1748f97 1111 case 2:
0426ad51 1112 gdb_puts ("Unused segment (");
baa93fa6 1113 break;
c1748f97 1114 case 3:
0426ad51 1115 gdb_puts ("Data (Read/Write, Exp-down");
baa93fa6 1116 break;
c1748f97 1117 case 4:
0426ad51 1118 gdb_puts ("Code (Exec-Only, N.Conf");
baa93fa6 1119 break;
c1748f97 1120 case 5:
0426ad51 1121 gdb_puts ("Code (Exec/Read, N.Conf");
c1748f97
PM
1122 break;
1123 case 6:
0426ad51 1124 gdb_puts ("Code (Exec-Only, Conf");
c1748f97
PM
1125 break;
1126 case 7:
0426ad51 1127 gdb_puts ("Code (Exec/Read, Conf");
c1748f97
PM
1128 break;
1129 default:
6cb06a8c
TT
1130 gdb_printf ("Unknown type 0x%lx",
1131 (unsigned long) info.HighWord.Bits.Type);
c1748f97
PM
1132 }
1133 if ((info.HighWord.Bits.Type & 0x1) == 0)
0426ad51
TT
1134 gdb_puts(", N.Acc");
1135 gdb_puts (")\n");
c1748f97 1136 if ((info.HighWord.Bits.Type & 0x10) == 0)
0426ad51 1137 gdb_puts("System selector ");
36da255e 1138 gdb_printf ("Privilege level = %ld. ",
6cb06a8c 1139 (unsigned long) info.HighWord.Bits.Dpl);
c1748f97 1140 if (info.HighWord.Bits.Granularity)
0426ad51 1141 gdb_puts ("Page granular.\n");
c1748f97 1142 else
0426ad51 1143 gdb_puts ("Byte granular.\n");
c1748f97
PM
1144 return 1;
1145 }
1146 else
1147 {
5572ce1f
PM
1148 DWORD err = GetLastError ();
1149 if (err == ERROR_NOT_SUPPORTED)
6cb06a8c 1150 gdb_printf ("Function not supported\n");
5572ce1f 1151 else
6cb06a8c 1152 gdb_printf ("Invalid selector 0x%x.\n", (unsigned) sel);
c1748f97
PM
1153 return 0;
1154 }
1155}
1156
1157static void
5fed81ff 1158display_selectors (const char * args, int from_tty)
c1748f97 1159{
50838d1b 1160 if (inferior_ptid == null_ptid)
c1748f97 1161 {
0426ad51 1162 gdb_puts ("Impossible to display selectors now.\n");
c1748f97
PM
1163 return;
1164 }
50838d1b
PA
1165
1166 windows_thread_info *current_windows_thread
0578e87f 1167 = windows_process.thread_rec (inferior_ptid, DONT_INVALIDATE_CONTEXT);
50838d1b 1168
c1748f97
PM
1169 if (!args)
1170 {
46f9f931 1171#ifdef __x86_64__
0578e87f 1172 if (windows_process.wow64_process)
46f9f931 1173 {
0426ad51 1174 gdb_puts ("Selector $cs\n");
3c76026d
TT
1175 display_selector (current_windows_thread->h,
1176 current_windows_thread->wow64_context.SegCs);
0426ad51 1177 gdb_puts ("Selector $ds\n");
3c76026d
TT
1178 display_selector (current_windows_thread->h,
1179 current_windows_thread->wow64_context.SegDs);
0426ad51 1180 gdb_puts ("Selector $es\n");
3c76026d
TT
1181 display_selector (current_windows_thread->h,
1182 current_windows_thread->wow64_context.SegEs);
0426ad51 1183 gdb_puts ("Selector $ss\n");
3c76026d
TT
1184 display_selector (current_windows_thread->h,
1185 current_windows_thread->wow64_context.SegSs);
0426ad51 1186 gdb_puts ("Selector $fs\n");
3c76026d
TT
1187 display_selector (current_windows_thread->h,
1188 current_windows_thread->wow64_context.SegFs);
0426ad51 1189 gdb_puts ("Selector $gs\n");
3c76026d
TT
1190 display_selector (current_windows_thread->h,
1191 current_windows_thread->wow64_context.SegGs);
46f9f931
HD
1192 }
1193 else
1194#endif
1195 {
0426ad51 1196 gdb_puts ("Selector $cs\n");
3c76026d
TT
1197 display_selector (current_windows_thread->h,
1198 current_windows_thread->context.SegCs);
0426ad51 1199 gdb_puts ("Selector $ds\n");
3c76026d
TT
1200 display_selector (current_windows_thread->h,
1201 current_windows_thread->context.SegDs);
0426ad51 1202 gdb_puts ("Selector $es\n");
3c76026d
TT
1203 display_selector (current_windows_thread->h,
1204 current_windows_thread->context.SegEs);
0426ad51 1205 gdb_puts ("Selector $ss\n");
3c76026d
TT
1206 display_selector (current_windows_thread->h,
1207 current_windows_thread->context.SegSs);
0426ad51 1208 gdb_puts ("Selector $fs\n");
3c76026d
TT
1209 display_selector (current_windows_thread->h,
1210 current_windows_thread->context.SegFs);
0426ad51 1211 gdb_puts ("Selector $gs\n");
3c76026d
TT
1212 display_selector (current_windows_thread->h,
1213 current_windows_thread->context.SegGs);
46f9f931 1214 }
c1748f97
PM
1215 }
1216 else
1217 {
1218 int sel;
1219 sel = parse_and_eval_long (args);
6cb06a8c 1220 gdb_printf ("Selector \"%s\"\n",args);
3c76026d 1221 display_selector (current_windows_thread->h, sel);
c1748f97
PM
1222 }
1223}
1224
8d30e395 1225/* See nat/windows-nat.h. */
7393af7c 1226
a010605f 1227bool
20489cca 1228windows_per_inferior::handle_access_violation
0578e87f 1229 (const EXCEPTION_RECORD *rec)
a010605f
TT
1230{
1231#ifdef __CYGWIN__
1232 /* See if the access violation happened within the cygwin DLL
1233 itself. Cygwin uses a kind of exception handling to deal with
1234 passed-in invalid addresses. gdb should not treat these as real
1235 SEGVs since they will be silently handled by cygwin. A real SEGV
1236 will (theoretically) be caught by cygwin later in the process and
1237 will be sent as a cygwin-specific-signal. So, ignore SEGVs if
1238 they show up within the text segment of the DLL itself. */
1239 const char *fn;
1240 CORE_ADDR addr = (CORE_ADDR) (uintptr_t) rec->ExceptionAddress;
1241
1242 if ((!cygwin_exceptions && (addr >= cygwin_load_start
1243 && addr < cygwin_load_end))
1244 || (find_pc_partial_function (addr, &fn, NULL, NULL)
1245 && startswith (fn, "KERNEL32!IsBad")))
1246 return true;
1247#endif
1248 return false;
1249}
1250
17617f2d
EZ
1251/* Resume thread specified by ID, or all artificially suspended
1252 threads, if we are continuing execution. KILLED non-zero means we
1253 have killed the inferior, so we should ignore weird errors due to
d08bae3d
TT
1254 threads shutting down. LAST_CALL is true if we expect this to be
1255 the last call to continue the inferior -- we are either mourning it
1256 or detaching. */
4cb763d6 1257BOOL
d08bae3d
TT
1258windows_nat_target::windows_continue (DWORD continue_status, int id,
1259 int killed, bool last_call)
3cee93ac 1260{
0578e87f 1261 windows_process.desired_stop_thread_id = id;
0a4afda3 1262
0578e87f 1263 if (windows_process.matching_pending_stop (debug_events))
d08bae3d
TT
1264 {
1265 /* There's no need to really continue, because there's already
1266 another event pending. However, we do need to inform the
1267 event loop of this. */
1268 serial_event_set (m_wait_event);
1269 return TRUE;
1270 }
6537bb24 1271
20489cca 1272 for (auto &th : windows_process.thread_list)
0a4afda3 1273 if (id == -1 || id == (int) th->tid)
6537bb24 1274 {
46f9f931 1275#ifdef __x86_64__
0578e87f 1276 if (windows_process.wow64_process)
6537bb24 1277 {
296d3d2e 1278 if (th->debug_registers_changed)
46f9f931
HD
1279 {
1280 th->wow64_context.ContextFlags |= CONTEXT_DEBUG_REGISTERS;
20489cca
TT
1281 th->wow64_context.Dr0 = windows_process.dr[0];
1282 th->wow64_context.Dr1 = windows_process.dr[1];
1283 th->wow64_context.Dr2 = windows_process.dr[2];
1284 th->wow64_context.Dr3 = windows_process.dr[3];
46f9f931 1285 th->wow64_context.Dr6 = DR6_CLEAR_VALUE;
20489cca 1286 th->wow64_context.Dr7 = windows_process.dr[7];
296d3d2e 1287 th->debug_registers_changed = false;
46f9f931
HD
1288 }
1289 if (th->wow64_context.ContextFlags)
1290 {
1291 DWORD ec = 0;
1292
1293 if (GetExitCodeThread (th->h, &ec)
1294 && ec == STILL_ACTIVE)
1295 {
1296 BOOL status = Wow64SetThreadContext (th->h,
1297 &th->wow64_context);
1298
1299 if (!killed)
1300 CHECK (status);
1301 }
1302 th->wow64_context.ContextFlags = 0;
1303 }
6537bb24 1304 }
46f9f931
HD
1305 else
1306#endif
6537bb24 1307 {
296d3d2e 1308 if (th->debug_registers_changed)
17617f2d 1309 {
46f9f931 1310 th->context.ContextFlags |= CONTEXT_DEBUG_REGISTERS;
20489cca
TT
1311 th->context.Dr0 = windows_process.dr[0];
1312 th->context.Dr1 = windows_process.dr[1];
1313 th->context.Dr2 = windows_process.dr[2];
1314 th->context.Dr3 = windows_process.dr[3];
46f9f931 1315 th->context.Dr6 = DR6_CLEAR_VALUE;
20489cca 1316 th->context.Dr7 = windows_process.dr[7];
296d3d2e 1317 th->debug_registers_changed = false;
46f9f931
HD
1318 }
1319 if (th->context.ContextFlags)
1320 {
1321 DWORD ec = 0;
1322
1323 if (GetExitCodeThread (th->h, &ec)
1324 && ec == STILL_ACTIVE)
1325 {
1326 BOOL status = SetThreadContext (th->h, &th->context);
17617f2d 1327
46f9f931
HD
1328 if (!killed)
1329 CHECK (status);
1330 }
1331 th->context.ContextFlags = 0;
17617f2d 1332 }
6537bb24 1333 }
98a03287 1334 th->resume ();
6537bb24 1335 }
0a4afda3
TT
1336 else
1337 {
1338 /* When single-stepping a specific thread, other threads must
1339 be suspended. */
1340 th->suspend ();
1341 }
6537bb24 1342
6b09f134 1343 std::optional<unsigned> err;
4cb763d6 1344 do_synchronously ([&] ()
02d04eac 1345 {
4cb763d6
TT
1346 if (!continue_last_debug_event (continue_status, debug_events))
1347 err = (unsigned) GetLastError ();
d08bae3d
TT
1348 /* On the last call, do not block waiting for an event that will
1349 never come. */
1350 return !last_call;
4cb763d6
TT
1351 });
1352
1353 if (err.has_value ())
602971b3
TT
1354 throw_winerror_with_name (_("Failed to resume program execution"
1355 " - ContinueDebugEvent failed"),
1356 *err);
68ffc902 1357
4cb763d6 1358 return TRUE;
3cee93ac
CF
1359}
1360
d6dc8049
CF
1361/* Called in pathological case where Windows fails to send a
1362 CREATE_PROCESS_DEBUG_EVENT after an attach. */
55176502
TT
1363DWORD
1364windows_nat_target::fake_create_process ()
3ade5333 1365{
0578e87f
TT
1366 windows_process.handle
1367 = OpenProcess (PROCESS_ALL_ACCESS, FALSE,
1368 windows_process.current_event.dwProcessId);
1369 if (windows_process.handle != NULL)
20489cca 1370 windows_process.open_process_used = 1;
bf25528d
CF
1371 else
1372 {
02d04eac 1373 unsigned err = (unsigned) GetLastError ();
602971b3 1374 throw_winerror_with_name (_("OpenProcess call failed"), err);
bf25528d
CF
1375 /* We can not debug anything in that case. */
1376 }
55176502 1377 add_thread (ptid_t (windows_process.current_event.dwProcessId, 0,
0578e87f
TT
1378 windows_process.current_event.dwThreadId),
1379 windows_process.current_event.u.CreateThread.hThread,
1380 windows_process.current_event.u.CreateThread.lpThreadLocalBase,
50838d1b 1381 true /* main_thread_p */);
0578e87f 1382 return windows_process.current_event.dwThreadId;
3ade5333
CF
1383}
1384
f6ac5f3d
PA
1385void
1386windows_nat_target::resume (ptid_t ptid, int step, enum gdb_signal sig)
a244bdca 1387{
876d1cd7 1388 windows_thread_info *th;
a244bdca
CF
1389 DWORD continue_status = DBG_CONTINUE;
1390
2dc38344 1391 /* A specific PTID means `step only this thread id'. */
d7e15655 1392 int resume_all = ptid == minus_one_ptid;
2dc38344
PA
1393
1394 /* If we're continuing all threads, it's the current inferior that
1395 should be handled specially. */
1396 if (resume_all)
1397 ptid = inferior_ptid;
a244bdca 1398
a493e3e2 1399 if (sig != GDB_SIGNAL_0)
a244bdca 1400 {
0578e87f
TT
1401 if (windows_process.current_event.dwDebugEventCode
1402 != EXCEPTION_DEBUG_EVENT)
a244bdca 1403 {
4ef367bf 1404 DEBUG_EXCEPT ("Cannot continue with signal %d here.", sig);
a244bdca 1405 }
0578e87f 1406 else if (sig == windows_process.last_sig)
a244bdca
CF
1407 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1408 else
1409#if 0
1410/* This code does not seem to work, because
1411 the kernel does probably not consider changes in the ExceptionRecord
1412 structure when passing the exception to the inferior.
1413 Note that this seems possible in the exception handler itself. */
1414 {
73c13fe6
TT
1415 for (const xlate_exception &x : xlate)
1416 if (x.us == sig)
a244bdca 1417 {
581e13c1 1418 current_event.u.Exception.ExceptionRecord.ExceptionCode
73c13fe6 1419 = x.them;
a244bdca
CF
1420 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1421 break;
1422 }
1423 if (continue_status == DBG_CONTINUE)
1424 {
4ef367bf 1425 DEBUG_EXCEPT ("Cannot continue with signal %d.", sig);
a244bdca
CF
1426 }
1427 }
1428#endif
4ef367bf 1429 DEBUG_EXCEPT ("Can only continue with received signal %d.",
0578e87f 1430 windows_process.last_sig);
a244bdca
CF
1431 }
1432
0578e87f 1433 windows_process.last_sig = GDB_SIGNAL_0;
a244bdca 1434
4ef367bf
TT
1435 DEBUG_EXEC ("pid=%d, tid=0x%x, step=%d, sig=%d",
1436 ptid.pid (), (unsigned) ptid.lwp (), step, sig);
a244bdca 1437
581e13c1 1438 /* Get context for currently selected thread. */
0578e87f 1439 th = windows_process.thread_rec (inferior_ptid, DONT_INVALIDATE_CONTEXT);
a244bdca
CF
1440 if (th)
1441 {
46f9f931 1442#ifdef __x86_64__
0578e87f 1443 if (windows_process.wow64_process)
a244bdca 1444 {
46f9f931
HD
1445 if (step)
1446 {
1447 /* Single step by setting t bit. */
9c742269 1448 regcache *regcache = get_thread_regcache (inferior_thread ());
46f9f931
HD
1449 struct gdbarch *gdbarch = regcache->arch ();
1450 fetch_registers (regcache, gdbarch_ps_regnum (gdbarch));
1451 th->wow64_context.EFlags |= FLAG_TRACE_BIT;
1452 }
a244bdca 1453
46f9f931
HD
1454 if (th->wow64_context.ContextFlags)
1455 {
296d3d2e 1456 if (th->debug_registers_changed)
46f9f931 1457 {
20489cca
TT
1458 th->wow64_context.Dr0 = windows_process.dr[0];
1459 th->wow64_context.Dr1 = windows_process.dr[1];
1460 th->wow64_context.Dr2 = windows_process.dr[2];
1461 th->wow64_context.Dr3 = windows_process.dr[3];
46f9f931 1462 th->wow64_context.Dr6 = DR6_CLEAR_VALUE;
20489cca 1463 th->wow64_context.Dr7 = windows_process.dr[7];
296d3d2e 1464 th->debug_registers_changed = false;
46f9f931
HD
1465 }
1466 CHECK (Wow64SetThreadContext (th->h, &th->wow64_context));
1467 th->wow64_context.ContextFlags = 0;
1468 }
1469 }
1470 else
1471#endif
a244bdca 1472 {
46f9f931 1473 if (step)
a244bdca 1474 {
46f9f931 1475 /* Single step by setting t bit. */
9c742269 1476 regcache *regcache = get_thread_regcache (inferior_thread ());
46f9f931
HD
1477 struct gdbarch *gdbarch = regcache->arch ();
1478 fetch_registers (regcache, gdbarch_ps_regnum (gdbarch));
1479 th->context.EFlags |= FLAG_TRACE_BIT;
1480 }
1481
1482 if (th->context.ContextFlags)
1483 {
296d3d2e 1484 if (th->debug_registers_changed)
46f9f931 1485 {
20489cca
TT
1486 th->context.Dr0 = windows_process.dr[0];
1487 th->context.Dr1 = windows_process.dr[1];
1488 th->context.Dr2 = windows_process.dr[2];
1489 th->context.Dr3 = windows_process.dr[3];
46f9f931 1490 th->context.Dr6 = DR6_CLEAR_VALUE;
20489cca 1491 th->context.Dr7 = windows_process.dr[7];
296d3d2e 1492 th->debug_registers_changed = false;
46f9f931
HD
1493 }
1494 CHECK (SetThreadContext (th->h, &th->context));
1495 th->context.ContextFlags = 0;
a244bdca 1496 }
a244bdca
CF
1497 }
1498 }
1499
1500 /* Allow continuing with the same signal that interrupted us.
581e13c1 1501 Otherwise complain. */
a244bdca 1502
2dc38344 1503 if (resume_all)
17617f2d 1504 windows_continue (continue_status, -1, 0);
2dc38344 1505 else
7c7411bc 1506 windows_continue (continue_status, ptid.lwp (), 0);
a244bdca
CF
1507}
1508
c88afe9c 1509/* Interrupt the inferior. */
695de547 1510
c88afe9c
TT
1511void
1512windows_nat_target::interrupt ()
1513{
1514 DEBUG_EVENTS ("interrupt");
0363df3d 1515#ifdef __x86_64__
0578e87f 1516 if (windows_process.wow64_process)
0363df3d
HD
1517 {
1518 /* Call DbgUiRemoteBreakin of the 32bit ntdll.dll in the target process.
1519 DebugBreakProcess would call the one of the 64bit ntdll.dll, which
1520 can't be correctly handled by gdb. */
20489cca 1521 if (windows_process.wow64_dbgbreak == nullptr)
0363df3d
HD
1522 {
1523 CORE_ADDR addr;
1524 if (!find_minimal_symbol_address ("ntdll!DbgUiRemoteBreakin",
1525 &addr, 0))
20489cca 1526 windows_process.wow64_dbgbreak = (void *) addr;
0363df3d
HD
1527 }
1528
20489cca 1529 if (windows_process.wow64_dbgbreak != nullptr)
0363df3d 1530 {
0578e87f 1531 HANDLE thread = CreateRemoteThread (windows_process.handle, NULL,
0363df3d 1532 0, (LPTHREAD_START_ROUTINE)
20489cca
TT
1533 windows_process.wow64_dbgbreak,
1534 NULL, 0, NULL);
0363df3d 1535 if (thread)
c88afe9c
TT
1536 {
1537 CloseHandle (thread);
1538 return;
1539 }
0363df3d
HD
1540 }
1541 }
1542 else
1543#endif
c88afe9c
TT
1544 if (DebugBreakProcess (windows_process.handle))
1545 return;
1546 warning (_("Could not interrupt program. "
1547 "Press Ctrl-c in the program console."));
1548}
695de547 1549
c88afe9c
TT
1550void
1551windows_nat_target::pass_ctrlc ()
1552{
1553 interrupt ();
695de547
CF
1554}
1555
4cb763d6 1556/* Get the next event from the child. Returns the thread ptid. */
5b6d1e4f 1557
4cb763d6
TT
1558ptid_t
1559windows_nat_target::get_windows_debug_event
1560 (int pid, struct target_waitstatus *ourstatus, target_wait_flags options)
1e37c281 1561{
8a892701 1562 DWORD continue_status, event_code;
e6ad66bd 1563 DWORD thread_id = 0;
1e37c281 1564
0a4afda3
TT
1565 /* If there is a relevant pending stop, report it now. See the
1566 comment by the definition of "pending_stops" for details on why
1567 this is needed. */
6b09f134 1568 std::optional<pending_stop> stop
0578e87f 1569 = windows_process.fetch_pending_stop (debug_events);
d2977bc4 1570 if (stop.has_value ())
0a4afda3 1571 {
d2977bc4
TT
1572 thread_id = stop->thread_id;
1573 *ourstatus = stop->status;
0a4afda3 1574
0578e87f
TT
1575 ptid_t ptid (windows_process.current_event.dwProcessId, thread_id);
1576 windows_thread_info *th
1577 = windows_process.thread_rec (ptid, INVALIDATE_CONTEXT);
e133de49 1578 th->reload_context = true;
0a4afda3 1579
4cb763d6 1580 return ptid;
0a4afda3
TT
1581 }
1582
0578e87f
TT
1583 windows_process.last_sig = GDB_SIGNAL_0;
1584 DEBUG_EVENT *current_event = &windows_process.current_event;
9d3789f7 1585
d08bae3d
TT
1586 if ((options & TARGET_WNOHANG) != 0 && !m_debug_event_pending)
1587 {
1588 ourstatus->set_ignore ();
1589 return minus_one_ptid;
1590 }
1591
4cb763d6 1592 wait_for_debug_event_main_thread (&windows_process.current_event);
1e37c281 1593
1e37c281 1594 continue_status = DBG_CONTINUE;
1e37c281 1595
0578e87f 1596 event_code = windows_process.current_event.dwDebugEventCode;
183be222 1597 ourstatus->set_spurious ();
8a892701
CF
1598
1599 switch (event_code)
1e37c281
JM
1600 {
1601 case CREATE_THREAD_DEBUG_EVENT:
4ef367bf 1602 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
0578e87f
TT
1603 (unsigned) current_event->dwProcessId,
1604 (unsigned) current_event->dwThreadId,
4ef367bf 1605 "CREATE_THREAD_DEBUG_EVENT");
20489cca 1606 if (windows_process.saw_create != 1)
3ade5333 1607 {
0578e87f 1608 inferior *inf = find_inferior_pid (this, current_event->dwProcessId);
20489cca 1609 if (!windows_process.saw_create && inf->attach_flag)
3ade5333 1610 {
d6dc8049
CF
1611 /* Kludge around a Windows bug where first event is a create
1612 thread event. Caused when attached process does not have
581e13c1 1613 a main thread. */
e6ad66bd
JT
1614 thread_id = fake_create_process ();
1615 if (thread_id)
20489cca 1616 windows_process.saw_create++;
3ade5333
CF
1617 }
1618 break;
1619 }
581e13c1 1620 /* Record the existence of this thread. */
0578e87f 1621 thread_id = current_event->dwThreadId;
55176502 1622 add_thread
0578e87f
TT
1623 (ptid_t (current_event->dwProcessId, current_event->dwThreadId, 0),
1624 current_event->u.CreateThread.hThread,
1625 current_event->u.CreateThread.lpThreadLocalBase,
c559d709 1626 false /* main_thread_p */);
711e434b 1627
1e37c281
JM
1628 break;
1629
1630 case EXIT_THREAD_DEBUG_EVENT:
4ef367bf 1631 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
0578e87f
TT
1632 (unsigned) current_event->dwProcessId,
1633 (unsigned) current_event->dwThreadId,
4ef367bf 1634 "EXIT_THREAD_DEBUG_EVENT");
55176502
TT
1635 delete_thread (ptid_t (current_event->dwProcessId,
1636 current_event->dwThreadId, 0),
1637 current_event->u.ExitThread.dwExitCode,
1638 false /* main_thread_p */);
1e37c281
JM
1639 break;
1640
1641 case CREATE_PROCESS_DEBUG_EVENT:
4ef367bf 1642 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
0578e87f
TT
1643 (unsigned) current_event->dwProcessId,
1644 (unsigned) current_event->dwThreadId,
4ef367bf 1645 "CREATE_PROCESS_DEBUG_EVENT");
0578e87f 1646 CloseHandle (current_event->u.CreateProcessInfo.hFile);
20489cca 1647 if (++windows_process.saw_create != 1)
bf25528d 1648 break;
1e37c281 1649
0578e87f 1650 windows_process.handle = current_event->u.CreateProcessInfo.hProcess;
581e13c1 1651 /* Add the main thread. */
55176502 1652 add_thread
0578e87f
TT
1653 (ptid_t (current_event->dwProcessId,
1654 current_event->dwThreadId, 0),
1655 current_event->u.CreateProcessInfo.hThread,
1656 current_event->u.CreateProcessInfo.lpThreadLocalBase,
c559d709 1657 true /* main_thread_p */);
0578e87f 1658 thread_id = current_event->dwThreadId;
1e37c281
JM
1659 break;
1660
1661 case EXIT_PROCESS_DEBUG_EVENT:
4ef367bf 1662 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
0578e87f
TT
1663 (unsigned) current_event->dwProcessId,
1664 (unsigned) current_event->dwThreadId,
4ef367bf 1665 "EXIT_PROCESS_DEBUG_EVENT");
20489cca 1666 if (!windows_process.windows_initialization_done)
16d905e2 1667 {
223ffa71 1668 target_terminal::ours ();
bc1e6c81 1669 target_mourn_inferior (inferior_ptid);
16d905e2 1670 error (_("During startup program exited with code 0x%x."),
0578e87f 1671 (unsigned int) current_event->u.ExitProcess.dwExitCode);
16d905e2 1672 }
20489cca 1673 else if (windows_process.saw_create == 1)
16d905e2 1674 {
55176502
TT
1675 delete_thread (ptid_t (current_event->dwProcessId,
1676 current_event->dwThreadId, 0),
1677 0, true /* main_thread_p */);
0578e87f 1678 DWORD exit_status = current_event->u.ExitProcess.dwExitCode;
559e7e50
EZ
1679 /* If the exit status looks like a fatal exception, but we
1680 don't recognize the exception's code, make the original
1681 exit status value available, to avoid losing
1682 information. */
1683 int exit_signal
1684 = WIFSIGNALED (exit_status) ? WTERMSIG (exit_status) : -1;
1685 if (exit_signal == -1)
183be222 1686 ourstatus->set_exited (exit_status);
559e7e50 1687 else
183be222
SM
1688 ourstatus->set_signalled (gdb_signal_from_host (exit_signal));
1689
0578e87f 1690 thread_id = current_event->dwThreadId;
16d905e2 1691 }
8a892701 1692 break;
1e37c281
JM
1693
1694 case LOAD_DLL_DEBUG_EVENT:
4ef367bf 1695 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
0578e87f
TT
1696 (unsigned) current_event->dwProcessId,
1697 (unsigned) current_event->dwThreadId,
4ef367bf 1698 "LOAD_DLL_DEBUG_EVENT");
0578e87f 1699 CloseHandle (current_event->u.LoadDll.hFile);
20489cca
TT
1700 if (windows_process.saw_create != 1
1701 || ! windows_process.windows_initialization_done)
dfe7f3ac 1702 break;
0578e87f
TT
1703 try
1704 {
1705 windows_process.dll_loaded_event ();
1706 }
1707 catch (const gdb_exception &ex)
1708 {
1709 exception_print (gdb_stderr, ex);
1710 }
183be222 1711 ourstatus->set_loaded ();
0578e87f 1712 thread_id = current_event->dwThreadId;
1e37c281
JM
1713 break;
1714
1715 case UNLOAD_DLL_DEBUG_EVENT:
4ef367bf 1716 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
0578e87f
TT
1717 (unsigned) current_event->dwProcessId,
1718 (unsigned) current_event->dwThreadId,
4ef367bf 1719 "UNLOAD_DLL_DEBUG_EVENT");
20489cca
TT
1720 if (windows_process.saw_create != 1
1721 || ! windows_process.windows_initialization_done)
dfe7f3ac 1722 break;
0578e87f
TT
1723 try
1724 {
1725 windows_process.handle_unload_dll ();
1726 }
1727 catch (const gdb_exception &ex)
1728 {
1729 exception_print (gdb_stderr, ex);
1730 }
183be222 1731 ourstatus->set_loaded ();
0578e87f 1732 thread_id = current_event->dwThreadId;
d3ff4a77 1733 break;
1e37c281
JM
1734
1735 case EXCEPTION_DEBUG_EVENT:
4ef367bf 1736 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
0578e87f
TT
1737 (unsigned) current_event->dwProcessId,
1738 (unsigned) current_event->dwThreadId,
4ef367bf 1739 "EXCEPTION_DEBUG_EVENT");
20489cca 1740 if (windows_process.saw_create != 1)
dfe7f3ac 1741 break;
0578e87f 1742 switch (windows_process.handle_exception (ourstatus, debug_exceptions))
24cdb46e
РИ
1743 {
1744 case HANDLE_EXCEPTION_UNHANDLED:
1745 default:
1746 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1747 break;
1748 case HANDLE_EXCEPTION_HANDLED:
0578e87f 1749 thread_id = current_event->dwThreadId;
24cdb46e
РИ
1750 break;
1751 case HANDLE_EXCEPTION_IGNORED:
1752 continue_status = DBG_CONTINUE;
1753 break;
1754 }
1e37c281
JM
1755 break;
1756
581e13c1 1757 case OUTPUT_DEBUG_STRING_EVENT: /* Message from the kernel. */
4ef367bf 1758 DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
0578e87f
TT
1759 (unsigned) current_event->dwProcessId,
1760 (unsigned) current_event->dwThreadId,
4ef367bf 1761 "OUTPUT_DEBUG_STRING_EVENT");
20489cca 1762 if (windows_process.saw_create != 1)
dfe7f3ac 1763 break;
0578e87f 1764 thread_id = windows_process.handle_output_debug_string (ourstatus);
1e37c281 1765 break;
9d3789f7 1766
1e37c281 1767 default:
20489cca 1768 if (windows_process.saw_create != 1)
dfe7f3ac 1769 break;
6cb06a8c 1770 gdb_printf ("gdb: kernel event for pid=%u tid=0x%x\n",
0578e87f
TT
1771 (unsigned) current_event->dwProcessId,
1772 (unsigned) current_event->dwThreadId);
6cb06a8c 1773 gdb_printf (" unknown event code %u\n",
0578e87f 1774 (unsigned) current_event->dwDebugEventCode);
1e37c281
JM
1775 break;
1776 }
1777
20489cca 1778 if (!thread_id || windows_process.saw_create != 1)
a244bdca 1779 {
0578e87f
TT
1780 CHECK (windows_continue (continue_status,
1781 windows_process.desired_stop_thread_id, 0));
0a4afda3 1782 }
0578e87f
TT
1783 else if (windows_process.desired_stop_thread_id != -1
1784 && windows_process.desired_stop_thread_id != thread_id)
0a4afda3
TT
1785 {
1786 /* Pending stop. See the comment by the definition of
1787 "pending_stops" for details on why this is needed. */
4ef367bf
TT
1788 DEBUG_EVENTS ("get_windows_debug_event - "
1789 "unexpected stop in 0x%x (expecting 0x%x)",
0578e87f 1790 thread_id, windows_process.desired_stop_thread_id);
0a4afda3 1791
0578e87f
TT
1792 if (current_event->dwDebugEventCode == EXCEPTION_DEBUG_EVENT
1793 && ((current_event->u.Exception.ExceptionRecord.ExceptionCode
13302e95 1794 == EXCEPTION_BREAKPOINT)
0578e87f 1795 || (current_event->u.Exception.ExceptionRecord.ExceptionCode
13302e95 1796 == STATUS_WX86_BREAKPOINT))
20489cca 1797 && windows_process.windows_initialization_done)
0a4afda3 1798 {
0578e87f
TT
1799 ptid_t ptid = ptid_t (current_event->dwProcessId, thread_id, 0);
1800 windows_thread_info *th
1801 = windows_process.thread_rec (ptid, INVALIDATE_CONTEXT);
0a4afda3 1802 th->stopped_at_software_breakpoint = true;
7be2bb4f 1803 th->pc_adjusted = false;
0a4afda3 1804 }
0578e87f
TT
1805 windows_process.pending_stops.push_back
1806 ({thread_id, *ourstatus, windows_process.current_event});
0a4afda3 1807 thread_id = 0;
0578e87f
TT
1808 CHECK (windows_continue (continue_status,
1809 windows_process.desired_stop_thread_id, 0));
a244bdca 1810 }
1e37c281 1811
4cb763d6
TT
1812 if (thread_id == 0)
1813 return null_ptid;
1814 return ptid_t (windows_process.current_event.dwProcessId, thread_id, 0);
1e37c281
JM
1815}
1816
2dc38344 1817/* Wait for interesting events to occur in the target process. */
f6ac5f3d
PA
1818ptid_t
1819windows_nat_target::wait (ptid_t ptid, struct target_waitstatus *ourstatus,
b60cea74 1820 target_wait_flags options)
24e60978 1821{
2dc38344 1822 int pid = -1;
39f77062 1823
24e60978
SC
1824 /* We loop when we get a non-standard exception rather than return
1825 with a SPURIOUS because resume can try and step or modify things,
3cee93ac 1826 which needs a current_thread->h. But some of these exceptions mark
24e60978 1827 the birth or death of threads, which mean that the current thread
581e13c1 1828 isn't necessarily what you think it is. */
24e60978
SC
1829
1830 while (1)
450005e7 1831 {
4cb763d6 1832 ptid_t result = get_windows_debug_event (pid, ourstatus, options);
c57918b2 1833
4cb763d6 1834 if (result != null_ptid)
0a4afda3 1835 {
183be222
SM
1836 if (ourstatus->kind () != TARGET_WAITKIND_EXITED
1837 && ourstatus->kind () != TARGET_WAITKIND_SIGNALLED)
0a4afda3 1838 {
0578e87f
TT
1839 windows_thread_info *th
1840 = windows_process.thread_rec (result, INVALIDATE_CONTEXT);
50838d1b
PA
1841
1842 if (th != nullptr)
7be2bb4f 1843 {
50838d1b 1844 th->stopped_at_software_breakpoint = false;
0578e87f
TT
1845 if (windows_process.current_event.dwDebugEventCode
1846 == EXCEPTION_DEBUG_EVENT
1847 && ((windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
50838d1b 1848 == EXCEPTION_BREAKPOINT)
0578e87f 1849 || (windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
50838d1b 1850 == STATUS_WX86_BREAKPOINT))
20489cca 1851 && windows_process.windows_initialization_done)
50838d1b
PA
1852 {
1853 th->stopped_at_software_breakpoint = true;
1854 th->pc_adjusted = false;
1855 }
7be2bb4f 1856 }
0a4afda3
TT
1857 }
1858
1859 return result;
1860 }
450005e7
CF
1861 else
1862 {
1863 int detach = 0;
3cee93ac 1864
98bbd631
AC
1865 if (deprecated_ui_loop_hook != NULL)
1866 detach = deprecated_ui_loop_hook (0);
0714f9bf 1867
450005e7 1868 if (detach)
f6ac5f3d 1869 kill ();
450005e7
CF
1870 }
1871 }
24e60978
SC
1872}
1873
50838d1b
PA
1874void
1875windows_nat_target::do_initial_windows_stuff (DWORD pid, bool attaching)
9d3789f7 1876{
fa4ba8da 1877 int i;
d6b48e9c 1878 struct inferior *inf;
9d3789f7 1879
0578e87f 1880 windows_process.last_sig = GDB_SIGNAL_0;
20489cca
TT
1881 windows_process.open_process_used = 0;
1882 for (i = 0;
1883 i < sizeof (windows_process.dr) / sizeof (windows_process.dr[0]);
1884 i++)
1885 windows_process.dr[i] = 0;
10325bc5 1886#ifdef __CYGWIN__
26f228db
JT
1887 windows_process.cygwin_load_start = 0;
1888 windows_process.cygwin_load_end = 0;
10325bc5 1889#endif
0578e87f
TT
1890 windows_process.current_event.dwProcessId = pid;
1891 memset (&windows_process.current_event, 0,
1892 sizeof (windows_process.current_event));
02980c56 1893 inf = current_inferior ();
c8fbd44a 1894 if (!inf->target_is_pushed (this))
02980c56 1895 inf->push_target (this);
85e8a786 1896 disable_breakpoints_in_shlibs (current_program_space);
dc05df57 1897 windows_clear_solib ();
88056fbb 1898 clear_proceed_status (0);
9d3789f7
CF
1899 init_wait_for_inferior ();
1900
46f9f931 1901#ifdef __x86_64__
0578e87f
TT
1902 windows_process.ignore_first_breakpoint
1903 = !attaching && windows_process.wow64_process;
46f9f931 1904
0578e87f 1905 if (!windows_process.wow64_process)
46f9f931 1906 {
20489cca
TT
1907 windows_process.mappings = amd64_mappings;
1908 windows_process.segment_register_p = amd64_windows_segment_register_p;
46f9f931
HD
1909 }
1910 else
1911#endif
1912 {
20489cca
TT
1913 windows_process.mappings = i386_mappings;
1914 windows_process.segment_register_p = i386_windows_segment_register_p;
46f9f931
HD
1915 }
1916
6c95b8df 1917 inferior_appeared (inf, pid);
181e7f93 1918 inf->attach_flag = attaching;
7f9f62ba 1919
223ffa71
TT
1920 target_terminal::init ();
1921 target_terminal::inferior ();
9d3789f7 1922
20489cca 1923 windows_process.windows_initialization_done = 0;
c72f45d1 1924
50838d1b
PA
1925 ptid_t last_ptid;
1926
9d3789f7
CF
1927 while (1)
1928 {
c72f45d1
PA
1929 struct target_waitstatus status;
1930
50838d1b 1931 last_ptid = this->wait (minus_one_ptid, &status, 0);
c72f45d1
PA
1932
1933 /* Note windows_wait returns TARGET_WAITKIND_SPURIOUS for thread
1934 events. */
183be222
SM
1935 if (status.kind () != TARGET_WAITKIND_LOADED
1936 && status.kind () != TARGET_WAITKIND_SPURIOUS)
9d3789f7 1937 break;
c72f45d1 1938
50838d1b 1939 this->resume (minus_one_ptid, 0, GDB_SIGNAL_0);
9d3789f7 1940 }
eff8332b 1941
9213a6d7 1942 switch_to_thread (this->find_thread (last_ptid));
50838d1b 1943
ea39ad35 1944 /* Now that the inferior has been started and all DLLs have been mapped,
3be75f87
JB
1945 we can iterate over all DLLs and load them in.
1946
1947 We avoid doing it any earlier because, on certain versions of Windows,
1948 LOAD_DLL_DEBUG_EVENTs are sometimes not complete. In particular,
1949 we have seen on Windows 8.1 that the ntdll.dll load event does not
1950 include the DLL name, preventing us from creating an associated SO.
1951 A possible explanation is that ntdll.dll might be mapped before
1952 the SO info gets created by the Windows system -- ntdll.dll is
1953 the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs
1954 do not seem to suffer from that problem.
1955
1956 Rather than try to work around this sort of issue, it is much
1957 simpler to just ignore DLL load/unload events during the startup
1958 phase, and then process them all in one batch now. */
0578e87f 1959 windows_process.add_all_dlls ();
94481b8c 1960
20489cca 1961 windows_process.windows_initialization_done = 1;
9d3789f7
CF
1962 return;
1963}
1964
616a9dc4
CV
1965/* Try to set or remove a user privilege to the current process. Return -1
1966 if that fails, the previous setting of that privilege otherwise.
1967
1968 This code is copied from the Cygwin source code and rearranged to allow
1969 dynamically loading of the needed symbols from advapi32 which is only
581e13c1 1970 available on NT/2K/XP. */
616a9dc4
CV
1971static int
1972set_process_privilege (const char *privilege, BOOL enable)
1973{
616a9dc4
CV
1974 HANDLE token_hdl = NULL;
1975 LUID restore_priv;
1976 TOKEN_PRIVILEGES new_priv, orig_priv;
1977 int ret = -1;
1978 DWORD size;
1979
616a9dc4
CV
1980 if (!OpenProcessToken (GetCurrentProcess (),
1981 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
1982 &token_hdl))
1983 goto out;
1984
418c6cb3 1985 if (!LookupPrivilegeValueA (NULL, privilege, &restore_priv))
616a9dc4
CV
1986 goto out;
1987
1988 new_priv.PrivilegeCount = 1;
1989 new_priv.Privileges[0].Luid = restore_priv;
1990 new_priv.Privileges[0].Attributes = enable ? SE_PRIVILEGE_ENABLED : 0;
1991
1992 if (!AdjustTokenPrivileges (token_hdl, FALSE, &new_priv,
295732ea 1993 sizeof orig_priv, &orig_priv, &size))
616a9dc4
CV
1994 goto out;
1995#if 0
1996 /* Disabled, otherwise every `attach' in an unprivileged user session
1997 would raise the "Failed to get SE_DEBUG_NAME privilege" warning in
581e13c1 1998 windows_attach(). */
616a9dc4 1999 /* AdjustTokenPrivileges returns TRUE even if the privilege could not
581e13c1 2000 be enabled. GetLastError () returns an correct error code, though. */
616a9dc4
CV
2001 if (enable && GetLastError () == ERROR_NOT_ALL_ASSIGNED)
2002 goto out;
2003#endif
2004
2005 ret = orig_priv.Privileges[0].Attributes == SE_PRIVILEGE_ENABLED ? 1 : 0;
2006
2007out:
2008 if (token_hdl)
2009 CloseHandle (token_hdl);
2010
2011 return ret;
2012}
2013
02cc9f49 2014/* Attach to process PID, then initialize for debugging it. */
f6ac5f3d
PA
2015
2016void
2017windows_nat_target::attach (const char *args, int from_tty)
24e60978 2018{
559e75c0 2019 DWORD pid;
24e60978 2020
74164c56 2021 pid = parse_pid_to_attach (args);
24e60978 2022
616a9dc4 2023 if (set_process_privilege (SE_DEBUG_NAME, TRUE) < 0)
390abcd9
TT
2024 warning ("Failed to get SE_DEBUG_NAME privilege\n"
2025 "This can cause attach to fail on Windows NT/2K/XP");
616a9dc4 2026
dc05df57 2027 windows_init_thread_list ();
20489cca 2028 windows_process.saw_create = 0;
24e60978 2029
6b09f134 2030 std::optional<unsigned> err;
4cb763d6 2031 do_synchronously ([&] ()
baa93fa6 2032 {
4cb763d6 2033 BOOL ok = DebugActiveProcess (pid);
baa93fa6 2034
4cb763d6
TT
2035#ifdef __CYGWIN__
2036 if (!ok)
2037 {
2038 /* Try fall back to Cygwin pid. */
2039 pid = cygwin_internal (CW_CYGWIN_PID_TO_WINPID, pid);
2040
2041 if (pid > 0)
2042 ok = DebugActiveProcess (pid);
2043 }
10325bc5 2044#endif
baa93fa6 2045
4cb763d6
TT
2046 if (!ok)
2047 err = (unsigned) GetLastError ();
d08bae3d
TT
2048
2049 return true;
4cb763d6
TT
2050 });
2051
2052 if (err.has_value ())
602971b3
TT
2053 {
2054 std::string msg = string_printf (_("Can't attach to process %u"),
2055 (unsigned) pid);
2056 throw_winerror_with_name (msg.c_str (), *err);
2057 }
24e60978 2058
2b008701 2059 DebugSetProcessKillOnExit (FALSE);
3ade5333 2060
bc521517 2061 target_announce_attach (from_tty, pid);
24e60978 2062
46f9f931
HD
2063#ifdef __x86_64__
2064 HANDLE h = OpenProcess (PROCESS_QUERY_INFORMATION, FALSE, pid);
2065 if (h != NULL)
2066 {
2067 BOOL wow64;
2068 if (IsWow64Process (h, &wow64))
0578e87f 2069 windows_process.wow64_process = wow64;
46f9f931
HD
2070 CloseHandle (h);
2071 }
2072#endif
2073
50838d1b 2074 do_initial_windows_stuff (pid, 1);
223ffa71 2075 target_terminal::ours ();
24e60978
SC
2076}
2077
f6ac5f3d
PA
2078void
2079windows_nat_target::detach (inferior *inf, int from_tty)
24e60978 2080{
d08bae3d 2081 windows_continue (DBG_CONTINUE, -1, 0, true);
96998ce7 2082
6b09f134 2083 std::optional<unsigned> err;
4cb763d6 2084 do_synchronously ([&] ()
02d04eac 2085 {
4cb763d6
TT
2086 if (!DebugActiveProcessStop (windows_process.current_event.dwProcessId))
2087 err = (unsigned) GetLastError ();
2088 else
2089 DebugSetProcessKillOnExit (FALSE);
d08bae3d 2090 return false;
4cb763d6
TT
2091 });
2092
2093 if (err.has_value ())
602971b3
TT
2094 {
2095 std::string msg
2096 = string_printf (_("Can't detach process %u"),
2097 (unsigned) windows_process.current_event.dwProcessId);
2098 throw_winerror_with_name (msg.c_str (), *err);
2099 }
2b008701 2100
eea2d835 2101 target_announce_detach (from_tty);
7f9f62ba 2102
df7e5265 2103 x86_cleanup_dregs ();
50838d1b 2104 switch_to_no_thread ();
b7a08269 2105 detach_inferior (inf);
7f9f62ba 2106
f6ac5f3d 2107 maybe_unpush_target ();
24e60978
SC
2108}
2109
47f7ffdb
JB
2110/* The pid_to_exec_file target_ops method for this platform. */
2111
0e90c441 2112const char *
f6ac5f3d 2113windows_nat_target::pid_to_exec_file (int pid)
47216e51 2114{
fcab5839 2115 return windows_process.pid_to_exec_file (pid);
47216e51
CV
2116}
2117
24e60978
SC
2118/* Print status information about what we're accessing. */
2119
f6ac5f3d
PA
2120void
2121windows_nat_target::files_info ()
24e60978 2122{
181e7f93
PA
2123 struct inferior *inf = current_inferior ();
2124
6cb06a8c
TT
2125 gdb_printf ("\tUsing the running image of %s %s.\n",
2126 inf->attach_flag ? "attached" : "child",
fb6d30e0 2127 target_pid_to_str (ptid_t (inf->pid)).c_str ());
24e60978
SC
2128}
2129
cd44747c
PM
2130/* Modify CreateProcess parameters for use of a new separate console.
2131 Parameters are:
2132 *FLAGS: DWORD parameter for general process creation flags.
2133 *SI: STARTUPINFO structure, for which the console window size and
2134 console buffer size is filled in if GDB is running in a console.
2135 to create the new console.
2136 The size of the used font is not available on all versions of
2137 Windows OS. Furthermore, the current font might not be the default
2138 font, but this is still better than before.
2139 If the windows and buffer sizes are computed,
2140 SI->DWFLAGS is changed so that this information is used
2141 by CreateProcess function. */
2142
2143static void
2144windows_set_console_info (STARTUPINFO *si, DWORD *flags)
2145{
2146 HANDLE hconsole = CreateFile ("CONOUT$", GENERIC_READ | GENERIC_WRITE,
2147 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
2148
2149 if (hconsole != INVALID_HANDLE_VALUE)
2150 {
2151 CONSOLE_SCREEN_BUFFER_INFO sbinfo;
2152 COORD font_size;
2153 CONSOLE_FONT_INFO cfi;
2154
2155 GetCurrentConsoleFont (hconsole, FALSE, &cfi);
2156 font_size = GetConsoleFontSize (hconsole, cfi.nFont);
2157 GetConsoleScreenBufferInfo(hconsole, &sbinfo);
2158 si->dwXSize = sbinfo.srWindow.Right - sbinfo.srWindow.Left + 1;
2159 si->dwYSize = sbinfo.srWindow.Bottom - sbinfo.srWindow.Top + 1;
2160 if (font_size.X)
2161 si->dwXSize *= font_size.X;
2162 else
2163 si->dwXSize *= 8;
2164 if (font_size.Y)
2165 si->dwYSize *= font_size.Y;
2166 else
2167 si->dwYSize *= 12;
2168 si->dwXCountChars = sbinfo.dwSize.X;
2169 si->dwYCountChars = sbinfo.dwSize.Y;
2170 si->dwFlags |= STARTF_USESIZE | STARTF_USECOUNTCHARS;
2171 }
2172 *flags |= CREATE_NEW_CONSOLE;
2173}
2174
c93dbcba
EZ
2175#ifndef __CYGWIN__
2176/* Function called by qsort to sort environment strings. */
2177
2178static int
2179envvar_cmp (const void *a, const void *b)
2180{
2181 const char **p = (const char **) a;
2182 const char **q = (const char **) b;
2183 return strcasecmp (*p, *q);
2184}
2185#endif
2186
b7ff339d
CV
2187#ifdef __CYGWIN__
2188static void
2189clear_win32_environment (char **env)
2190{
2191 int i;
2192 size_t len;
2193 wchar_t *copy = NULL, *equalpos;
2194
2195 for (i = 0; env[i] && *env[i]; i++)
2196 {
2197 len = mbstowcs (NULL, env[i], 0) + 1;
2198 copy = (wchar_t *) xrealloc (copy, len * sizeof (wchar_t));
2199 mbstowcs (copy, env[i], len);
2200 equalpos = wcschr (copy, L'=');
2201 if (equalpos)
dda83cd7 2202 *equalpos = L'\0';
b7ff339d
CV
2203 SetEnvironmentVariableW (copy, NULL);
2204 }
2205 xfree (copy);
2206}
2207#endif
2208
8ba42bc5
EZ
2209#ifndef __CYGWIN__
2210
2211/* Redirection of inferior I/O streams for native MS-Windows programs.
2212 Unlike on Unix, where this is handled by invoking the inferior via
2213 the shell, on MS-Windows we need to emulate the cmd.exe shell.
2214
2215 The official documentation of the cmd.exe redirection features is here:
2216
2217 http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx
2218
2219 (That page talks about Windows XP, but there's no newer
2220 documentation, so we assume later versions of cmd.exe didn't change
2221 anything.)
2222
2223 Caveat: the documentation on that page seems to include a few lies.
2224 For example, it describes strange constructs 1<&2 and 2<&1, which
2225 seem to work only when 1>&2 resp. 2>&1 would make sense, and so I
2226 think the cmd.exe parser of the redirection symbols simply doesn't
2227 care about the < vs > distinction in these cases. Therefore, the
2228 supported features are explicitly documented below.
2229
2230 The emulation below aims at supporting all the valid use cases
2231 supported by cmd.exe, which include:
2232
2233 < FILE redirect standard input from FILE
2234 0< FILE redirect standard input from FILE
2235 <&N redirect standard input from file descriptor N
2236 0<&N redirect standard input from file descriptor N
2237 > FILE redirect standard output to FILE
2238 >> FILE append standard output to FILE
2239 1>> FILE append standard output to FILE
2240 >&N redirect standard output to file descriptor N
2241 1>&N redirect standard output to file descriptor N
2242 >>&N append standard output to file descriptor N
2243 1>>&N append standard output to file descriptor N
2244 2> FILE redirect standard error to FILE
2245 2>> FILE append standard error to FILE
2246 2>&N redirect standard error to file descriptor N
2247 2>>&N append standard error to file descriptor N
2248
2249 Note that using N > 2 in the above construct is supported, but
2250 requires that the corresponding file descriptor be open by some
2251 means elsewhere or outside GDB. Also note that using ">&0" or
2252 "<&2" will generally fail, because the file descriptor redirected
2253 from is normally open in an incompatible mode (e.g., FD 0 is open
2254 for reading only). IOW, use of such tricks is not recommended;
2255 you are on your own.
2256
2257 We do NOT support redirection of file descriptors above 2, as in
2258 "3>SOME-FILE", because MinGW compiled programs don't (supporting
2259 that needs special handling in the startup code that MinGW
2260 doesn't have). Pipes are also not supported.
2261
2262 As for invalid use cases, where the redirection contains some
2263 error, the emulation below will detect that and produce some
2264 error and/or failure. But the behavior in those cases is not
2265 bug-for-bug compatible with what cmd.exe does in those cases.
2266 That's because what cmd.exe does then is not well defined, and
2267 seems to be a side effect of the cmd.exe parsing of the command
2268 line more than anything else. For example, try redirecting to an
2269 invalid file name, as in "> foo:bar".
2270
2271 There are also minor syntactic deviations from what cmd.exe does
2272 in some corner cases. For example, it doesn't support the likes
2273 of "> &foo" to mean redirect to file named literally "&foo"; we
2274 do support that here, because that, too, sounds like some issue
2275 with the cmd.exe parser. Another nicety is that we support
2276 redirection targets that use file names with forward slashes,
2277 something cmd.exe doesn't -- this comes in handy since GDB
2278 file-name completion can be used when typing the command line for
2279 the inferior. */
2280
2281/* Support routines for redirecting standard handles of the inferior. */
2282
2283/* Parse a single redirection spec, open/duplicate the specified
2284 file/fd, and assign the appropriate value to one of the 3 standard
2285 file descriptors. */
2286static int
2287redir_open (const char *redir_string, int *inp, int *out, int *err)
2288{
2289 int *fd, ref_fd = -2;
2290 int mode;
2291 const char *fname = redir_string + 1;
2292 int rc = *redir_string;
2293
2294 switch (rc)
2295 {
2296 case '0':
2297 fname++;
d182e398 2298 [[fallthrough]];
8ba42bc5
EZ
2299 case '<':
2300 fd = inp;
2301 mode = O_RDONLY;
2302 break;
2303 case '1': case '2':
2304 fname++;
d182e398 2305 [[fallthrough]];
8ba42bc5
EZ
2306 case '>':
2307 fd = (rc == '2') ? err : out;
2308 mode = O_WRONLY | O_CREAT;
2309 if (*fname == '>')
2310 {
2311 fname++;
2312 mode |= O_APPEND;
2313 }
2314 else
2315 mode |= O_TRUNC;
2316 break;
2317 default:
2318 return -1;
2319 }
2320
2321 if (*fname == '&' && '0' <= fname[1] && fname[1] <= '9')
2322 {
2323 /* A reference to a file descriptor. */
2324 char *fdtail;
2325 ref_fd = (int) strtol (fname + 1, &fdtail, 10);
2326 if (fdtail > fname + 1 && *fdtail == '\0')
2327 {
2328 /* Don't allow redirection when open modes are incompatible. */
2329 if ((ref_fd == 0 && (fd == out || fd == err))
2330 || ((ref_fd == 1 || ref_fd == 2) && fd == inp))
2331 {
2332 errno = EPERM;
2333 return -1;
2334 }
2335 if (ref_fd == 0)
2336 ref_fd = *inp;
2337 else if (ref_fd == 1)
2338 ref_fd = *out;
2339 else if (ref_fd == 2)
2340 ref_fd = *err;
2341 }
2342 else
2343 {
2344 errno = EBADF;
2345 return -1;
2346 }
2347 }
2348 else
2349 fname++; /* skip the separator space */
2350 /* If the descriptor is already open, close it. This allows
2351 multiple specs of redirections for the same stream, which is
2352 somewhat nonsensical, but still valid and supported by cmd.exe.
2353 (But cmd.exe only opens a single file in this case, the one
2354 specified by the last redirection spec on the command line.) */
2355 if (*fd >= 0)
2356 _close (*fd);
2357 if (ref_fd == -2)
2358 {
2359 *fd = _open (fname, mode, _S_IREAD | _S_IWRITE);
2360 if (*fd < 0)
2361 return -1;
2362 }
2363 else if (ref_fd == -1)
2364 *fd = -1; /* reset to default destination */
2365 else
2366 {
2367 *fd = _dup (ref_fd);
2368 if (*fd < 0)
2369 return -1;
2370 }
2371 /* _open just sets a flag for O_APPEND, which won't be passed to the
2372 inferior, so we need to actually move the file pointer. */
2373 if ((mode & O_APPEND) != 0)
2374 _lseek (*fd, 0L, SEEK_END);
2375 return 0;
2376}
2377
2378/* Canonicalize a single redirection spec and set up the corresponding
2379 file descriptor as specified. */
2380static int
2381redir_set_redirection (const char *s, int *inp, int *out, int *err)
2382{
2383 char buf[__PMAX + 2 + 5]; /* extra space for quotes & redirection string */
2384 char *d = buf;
2385 const char *start = s;
2386 int quote = 0;
2387
2388 *d++ = *s++; /* copy the 1st character, < or > or a digit */
2389 if ((*start == '>' || *start == '1' || *start == '2')
2390 && *s == '>')
2391 {
2392 *d++ = *s++;
2393 if (*s == '>' && *start != '>')
2394 *d++ = *s++;
2395 }
2396 else if (*start == '0' && *s == '<')
2397 *d++ = *s++;
2398 /* cmd.exe recognizes "&N" only immediately after the redirection symbol. */
2399 if (*s != '&')
2400 {
2401 while (isspace (*s)) /* skip whitespace before file name */
2402 s++;
2403 *d++ = ' '; /* separate file name with a single space */
2404 }
2405
2406 /* Copy the file name. */
2407 while (*s)
2408 {
2409 /* Remove quoting characters from the file name in buf[]. */
2410 if (*s == '"') /* could support '..' quoting here */
2411 {
2412 if (!quote)
2413 quote = *s++;
2414 else if (*s == quote)
2415 {
2416 quote = 0;
2417 s++;
2418 }
2419 else
2420 *d++ = *s++;
2421 }
2422 else if (*s == '\\')
2423 {
2424 if (s[1] == '"') /* could support '..' here */
2425 s++;
2426 *d++ = *s++;
2427 }
2428 else if (isspace (*s) && !quote)
2429 break;
2430 else
2431 *d++ = *s++;
2432 if (d - buf >= sizeof (buf) - 1)
2433 {
2434 errno = ENAMETOOLONG;
2435 return 0;
2436 }
2437 }
2438 *d = '\0';
2439
2440 /* Windows doesn't allow redirection characters in file names, so we
2441 can bail out early if they use them, or if there's no target file
2442 name after the redirection symbol. */
2443 if (d[-1] == '>' || d[-1] == '<')
2444 {
2445 errno = ENOENT;
2446 return 0;
2447 }
2448 if (redir_open (buf, inp, out, err) == 0)
2449 return s - start;
2450 return 0;
2451}
2452
2453/* Parse the command line for redirection specs and prepare the file
2454 descriptors for the 3 standard streams accordingly. */
2455static bool
2456redirect_inferior_handles (const char *cmd_orig, char *cmd,
2457 int *inp, int *out, int *err)
2458{
2459 const char *s = cmd_orig;
2460 char *d = cmd;
2461 int quote = 0;
2462 bool retval = false;
2463
2464 while (isspace (*s))
2465 *d++ = *s++;
2466
2467 while (*s)
2468 {
2469 if (*s == '"') /* could also support '..' quoting here */
2470 {
2471 if (!quote)
2472 quote = *s;
2473 else if (*s == quote)
2474 quote = 0;
2475 }
2476 else if (*s == '\\')
2477 {
2478 if (s[1] == '"') /* escaped quote char */
2479 s++;
2480 }
2481 else if (!quote)
2482 {
2483 /* Process a single redirection candidate. */
2484 if (*s == '<' || *s == '>'
2485 || ((*s == '1' || *s == '2') && s[1] == '>')
2486 || (*s == '0' && s[1] == '<'))
2487 {
2488 int skip = redir_set_redirection (s, inp, out, err);
2489
2490 if (skip <= 0)
2491 return false;
2492 retval = true;
2493 s += skip;
2494 }
2495 }
2496 if (*s)
2497 *d++ = *s++;
2498 }
2499 *d = '\0';
2500 return retval;
2501}
2502#endif /* !__CYGWIN__ */
2503
dc05df57 2504/* Start an inferior windows child process and sets inferior_ptid to its pid.
24e60978
SC
2505 EXEC_FILE is the file to run.
2506 ALLARGS is a string containing the arguments to the program.
2507 ENV is the environment vector to pass. Errors reported with error(). */
2508
f6ac5f3d
PA
2509void
2510windows_nat_target::create_inferior (const char *exec_file,
2511 const std::string &origallargs,
2512 char **in_env, int from_tty)
24e60978 2513{
b3c613f2 2514 STARTUPINFO si;
41b4aadc 2515#ifdef __CYGWIN__
7d941aa3
JT
2516 wchar_t real_path[__PMAX];
2517 wchar_t shell[__PMAX]; /* Path to shell */
2518 wchar_t infcwd[__PMAX];
d0d0ab16 2519 const char *sh;
7d941aa3
JT
2520 wchar_t *toexec;
2521 wchar_t *cygallargs;
2522 wchar_t *args;
b7ff339d
CV
2523 char **old_env = NULL;
2524 PWCHAR w32_env;
d0d0ab16 2525 size_t len;
2becadee
CF
2526 int tty;
2527 int ostdin, ostdout, ostderr;
8ba42bc5 2528#else /* !__CYGWIN__ */
b3c613f2 2529 char shell[__PMAX]; /* Path to shell */
5430098f 2530 const char *toexec;
8ba42bc5
EZ
2531 char *args, *allargs_copy;
2532 size_t args_len, allargs_len;
2533 int fd_inp = -1, fd_out = -1, fd_err = -1;
2534 HANDLE tty = INVALID_HANDLE_VALUE;
8ba42bc5 2535 bool redirected = false;
c93dbcba
EZ
2536 char *w32env;
2537 char *temp;
2538 size_t envlen;
2539 int i;
2540 size_t envsize;
2541 char **env;
8ba42bc5 2542#endif /* !__CYGWIN__ */
096c92dd 2543 const char *allargs = origallargs.c_str ();
d0d0ab16 2544 PROCESS_INFORMATION pi;
6b09f134 2545 std::optional<unsigned> ret;
d0d0ab16 2546 DWORD flags = 0;
0b73bf7f 2547 const std::string &inferior_tty = current_inferior ()->tty ();
24e60978
SC
2548
2549 if (!exec_file)
8a3fe4f8 2550 error (_("No executable specified, use `target exec'."));
24e60978 2551
0b73bf7f 2552 const char *inferior_cwd = current_inferior ()->cwd ().c_str ();
d092c5a2 2553 std::string expanded_infcwd;
0b73bf7f
TT
2554 if (*inferior_cwd == '\0')
2555 inferior_cwd = nullptr;
2556 else
d092c5a2
SDJ
2557 {
2558 expanded_infcwd = gdb_tilde_expand (inferior_cwd);
2559 /* Mirror slashes on inferior's cwd. */
2560 std::replace (expanded_infcwd.begin (), expanded_infcwd.end (),
2561 '/', '\\');
2562 inferior_cwd = expanded_infcwd.c_str ();
2563 }
2564
24e60978
SC
2565 memset (&si, 0, sizeof (si));
2566 si.cb = sizeof (si);
2567
d0d0ab16
CV
2568 if (new_group)
2569 flags |= CREATE_NEW_PROCESS_GROUP;
2570
2571 if (new_console)
cd44747c 2572 windows_set_console_info (&si, &flags);
d0d0ab16 2573
10325bc5 2574#ifdef __CYGWIN__
349b409f 2575 if (!useshell)
dfe7f3ac 2576 {
d0d0ab16
CV
2577 flags |= DEBUG_ONLY_THIS_PROCESS;
2578 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, exec_file, real_path,
7d941aa3 2579 __PMAX * sizeof (wchar_t)) < 0)
d0d0ab16 2580 error (_("Error starting executable: %d"), errno);
dfe7f3ac 2581 toexec = real_path;
d0d0ab16
CV
2582 len = mbstowcs (NULL, allargs, 0) + 1;
2583 if (len == (size_t) -1)
2584 error (_("Error starting executable: %d"), errno);
2585 cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
2586 mbstowcs (cygallargs, allargs, len);
dfe7f3ac
CF
2587 }
2588 else
2589 {
974e6844 2590 sh = get_shell ();
b3c613f2 2591 if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, sh, shell, __PMAX) < 0)
24b21115 2592 error (_("Error starting executable via shell: %d"), errno);
d0d0ab16
CV
2593 len = sizeof (L" -c 'exec '") + mbstowcs (NULL, exec_file, 0)
2594 + mbstowcs (NULL, allargs, 0) + 2;
2595 cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
2596 swprintf (cygallargs, len, L" -c 'exec %s %s'", exec_file, allargs);
dfe7f3ac 2597 toexec = shell;
d0d0ab16 2598 flags |= DEBUG_PROCESS;
dfe7f3ac 2599 }
b3c613f2 2600
d092c5a2
SDJ
2601 if (inferior_cwd != NULL
2602 && cygwin_conv_path (CCP_POSIX_TO_WIN_W, inferior_cwd,
2603 infcwd, strlen (inferior_cwd)) < 0)
2604 error (_("Error converting inferior cwd: %d"), errno);
2605
7d941aa3
JT
2606 args = (wchar_t *) alloca ((wcslen (toexec) + wcslen (cygallargs) + 2)
2607 * sizeof (wchar_t));
d0d0ab16
CV
2608 wcscpy (args, toexec);
2609 wcscat (args, L" ");
2610 wcscat (args, cygallargs);
b3c613f2 2611
b7ff339d
CV
2612#ifdef CW_CVT_ENV_TO_WINENV
2613 /* First try to create a direct Win32 copy of the POSIX environment. */
2614 w32_env = (PWCHAR) cygwin_internal (CW_CVT_ENV_TO_WINENV, in_env);
2615 if (w32_env != (PWCHAR) -1)
2616 flags |= CREATE_UNICODE_ENVIRONMENT;
2617 else
2618 /* If that fails, fall back to old method tweaking GDB's environment. */
8ba42bc5 2619#endif /* CW_CVT_ENV_TO_WINENV */
b7ff339d
CV
2620 {
2621 /* Reset all Win32 environment variables to avoid leftover on next run. */
2622 clear_win32_environment (environ);
2623 /* Prepare the environment vars for CreateProcess. */
2624 old_env = environ;
2625 environ = in_env;
2626 cygwin_internal (CW_SYNC_WINENV);
2627 w32_env = NULL;
2628 }
1750a5ef 2629
0b73bf7f 2630 if (inferior_tty.empty ())
2becadee
CF
2631 tty = ostdin = ostdout = ostderr = -1;
2632 else
2633 {
0b73bf7f 2634 tty = open (inferior_tty.c_str (), O_RDWR | O_NOCTTY);
2becadee
CF
2635 if (tty < 0)
2636 {
3d38b301 2637 warning_filename_and_errno (inferior_tty.c_str (), errno);
2becadee
CF
2638 ostdin = ostdout = ostderr = -1;
2639 }
2640 else
2641 {
2642 ostdin = dup (0);
2643 ostdout = dup (1);
2644 ostderr = dup (2);
2645 dup2 (tty, 0);
2646 dup2 (tty, 1);
2647 dup2 (tty, 2);
2648 }
2649 }
d0d0ab16
CV
2650
2651 windows_init_thread_list ();
4cb763d6
TT
2652 do_synchronously ([&] ()
2653 {
2654 if (!create_process (nullptr, args, flags, w32_env,
2655 inferior_cwd != nullptr ? infcwd : nullptr,
2656 disable_randomization,
2657 &si, &pi))
2658 ret = (unsigned) GetLastError ();
d08bae3d 2659 return true;
4cb763d6
TT
2660 });
2661
b7ff339d
CV
2662 if (w32_env)
2663 /* Just free the Win32 environment, if it could be created. */
2664 free (w32_env);
2665 else
2666 {
2667 /* Reset all environment variables to avoid leftover on next run. */
2668 clear_win32_environment (in_env);
2669 /* Restore normal GDB environment variables. */
2670 environ = old_env;
2671 cygwin_internal (CW_SYNC_WINENV);
2672 }
2673
d0d0ab16
CV
2674 if (tty >= 0)
2675 {
6af79d7b 2676 ::close (tty);
d0d0ab16
CV
2677 dup2 (ostdin, 0);
2678 dup2 (ostdout, 1);
2679 dup2 (ostderr, 2);
6af79d7b
JT
2680 ::close (ostdin);
2681 ::close (ostdout);
2682 ::close (ostderr);
d0d0ab16 2683 }
8ba42bc5
EZ
2684#else /* !__CYGWIN__ */
2685 allargs_len = strlen (allargs);
2686 allargs_copy = strcpy ((char *) alloca (allargs_len + 1), allargs);
2687 if (strpbrk (allargs_copy, "<>") != NULL)
2688 {
2689 int e = errno;
2690 errno = 0;
2691 redirected =
2692 redirect_inferior_handles (allargs, allargs_copy,
2693 &fd_inp, &fd_out, &fd_err);
2694 if (errno)
6d91ce9a 2695 warning (_("Error in redirection: %s."), safe_strerror (errno));
8ba42bc5
EZ
2696 else
2697 errno = e;
2698 allargs_len = strlen (allargs_copy);
2699 }
2700 /* If not all the standard streams are redirected by the command
05779d57 2701 line, use INFERIOR_TTY for those which aren't. */
0b73bf7f 2702 if (!inferior_tty.empty ()
8ba42bc5 2703 && !(fd_inp >= 0 && fd_out >= 0 && fd_err >= 0))
41b4aadc
CF
2704 {
2705 SECURITY_ATTRIBUTES sa;
2706 sa.nLength = sizeof(sa);
2707 sa.lpSecurityDescriptor = 0;
2708 sa.bInheritHandle = TRUE;
0b73bf7f 2709 tty = CreateFileA (inferior_tty.c_str (), GENERIC_READ | GENERIC_WRITE,
41b4aadc
CF
2710 0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
2711 if (tty == INVALID_HANDLE_VALUE)
02d04eac
TT
2712 {
2713 unsigned err = (unsigned) GetLastError ();
2714 warning (_("Warning: Failed to open TTY %s, error %#x: %s"),
2715 inferior_tty.c_str (), err, strwinerror (err));
2716 }
8ba42bc5
EZ
2717 }
2718 if (redirected || tty != INVALID_HANDLE_VALUE)
2719 {
2720 if (fd_inp >= 0)
2721 si.hStdInput = (HANDLE) _get_osfhandle (fd_inp);
2722 else if (tty != INVALID_HANDLE_VALUE)
2723 si.hStdInput = tty;
41b4aadc 2724 else
8ba42bc5
EZ
2725 si.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
2726 if (fd_out >= 0)
2727 si.hStdOutput = (HANDLE) _get_osfhandle (fd_out);
2728 else if (tty != INVALID_HANDLE_VALUE)
2729 si.hStdOutput = tty;
2730 else
2731 si.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
2732 if (fd_err >= 0)
2733 si.hStdError = (HANDLE) _get_osfhandle (fd_err);
2734 else if (tty != INVALID_HANDLE_VALUE)
2735 si.hStdError = tty;
2736 else
2737 si.hStdError = GetStdHandle (STD_ERROR_HANDLE);
2738 si.dwFlags |= STARTF_USESTDHANDLES;
41b4aadc 2739 }
2becadee 2740
8ba42bc5
EZ
2741 toexec = exec_file;
2742 /* Build the command line, a space-separated list of tokens where
2743 the first token is the name of the module to be executed.
2744 To avoid ambiguities introduced by spaces in the module name,
2745 we quote it. */
2746 args_len = strlen (toexec) + 2 /* quotes */ + allargs_len + 2;
2747 args = (char *) alloca (args_len);
2748 xsnprintf (args, args_len, "\"%s\" %s", toexec, allargs_copy);
2749
2750 flags |= DEBUG_ONLY_THIS_PROCESS;
2751
c93dbcba
EZ
2752 /* CreateProcess takes the environment list as a null terminated set of
2753 strings (i.e. two nulls terminate the list). */
2754
2755 /* Get total size for env strings. */
2756 for (envlen = 0, i = 0; in_env[i] && *in_env[i]; i++)
2757 envlen += strlen (in_env[i]) + 1;
2758
2759 envsize = sizeof (in_env[0]) * (i + 1);
2760 env = (char **) alloca (envsize);
2761 memcpy (env, in_env, envsize);
2762 /* Windows programs expect the environment block to be sorted. */
2763 qsort (env, i, sizeof (char *), envvar_cmp);
2764
0ae1c716 2765 w32env = (char *) alloca (envlen + 1);
c93dbcba
EZ
2766
2767 /* Copy env strings into new buffer. */
2768 for (temp = w32env, i = 0; env[i] && *env[i]; i++)
2769 {
2770 strcpy (temp, env[i]);
2771 temp += strlen (temp) + 1;
2772 }
2773
2774 /* Final nil string to terminate new env. */
2775 *temp = 0;
2776
dc05df57 2777 windows_init_thread_list ();
4cb763d6
TT
2778 do_synchronously ([&] ()
2779 {
2780 if (!create_process (nullptr, /* image */
2781 args, /* command line */
2782 flags, /* start flags */
2783 w32env, /* environment */
2784 inferior_cwd, /* current directory */
2785 disable_randomization,
2786 &si,
2787 &pi))
2788 ret = (unsigned) GetLastError ();
d08bae3d 2789 return true;
4cb763d6 2790 });
41b4aadc
CF
2791 if (tty != INVALID_HANDLE_VALUE)
2792 CloseHandle (tty);
8ba42bc5
EZ
2793 if (fd_inp >= 0)
2794 _close (fd_inp);
2795 if (fd_out >= 0)
2796 _close (fd_out);
2797 if (fd_err >= 0)
2798 _close (fd_err);
2799#endif /* !__CYGWIN__ */
2becadee 2800
4cb763d6 2801 if (ret.has_value ())
602971b3
TT
2802 {
2803 std::string msg = _("Error creating process ") + std::string (exec_file);
2804 throw_winerror_with_name (msg.c_str (), *ret);
2805 }
24e60978 2806
46f9f931
HD
2807#ifdef __x86_64__
2808 BOOL wow64;
2809 if (IsWow64Process (pi.hProcess, &wow64))
0578e87f 2810 windows_process.wow64_process = wow64;
46f9f931
HD
2811#endif
2812
c1766e7d
PM
2813 CloseHandle (pi.hThread);
2814 CloseHandle (pi.hProcess);
2815
dfe7f3ac 2816 if (useshell && shell[0] != '\0')
20489cca 2817 windows_process.saw_create = -1;
dfe7f3ac 2818 else
20489cca 2819 windows_process.saw_create = 0;
dfe7f3ac 2820
50838d1b 2821 do_initial_windows_stuff (pi.dwProcessId, 0);
d3a09475 2822
17617f2d 2823 /* windows_continue (DBG_CONTINUE, -1, 0); */
24e60978
SC
2824}
2825
f6ac5f3d
PA
2826void
2827windows_nat_target::mourn_inferior ()
24e60978 2828{
d08bae3d 2829 (void) windows_continue (DBG_CONTINUE, -1, 0, true);
df7e5265 2830 x86_cleanup_dregs();
20489cca 2831 if (windows_process.open_process_used)
bf25528d 2832 {
0578e87f 2833 CHECK (CloseHandle (windows_process.handle));
20489cca 2834 windows_process.open_process_used = 0;
bf25528d 2835 }
0578e87f 2836 windows_process.siginfo_er.ExceptionCode = 0;
f6ac5f3d 2837 inf_child_target::mourn_inferior ();
24e60978
SC
2838}
2839
44f38867
PA
2840/* Helper for windows_xfer_partial that handles memory transfers.
2841 Arguments are like target_xfer_partial. */
2842
9b409511 2843static enum target_xfer_status
44f38867 2844windows_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
9b409511 2845 ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
24e60978 2846{
5732a500 2847 SIZE_T done = 0;
44f38867 2848 BOOL success;
9e52adf9 2849 DWORD lasterror = 0;
44f38867
PA
2850
2851 if (writebuf != NULL)
24e60978 2852 {
4ef367bf
TT
2853 DEBUG_MEM ("write target memory, %s bytes at %s",
2854 pulongest (len), core_addr_to_string (memaddr));
0578e87f 2855 success = WriteProcessMemory (windows_process.handle,
44f38867
PA
2856 (LPVOID) (uintptr_t) memaddr, writebuf,
2857 len, &done);
9e52adf9 2858 if (!success)
7126d5c8 2859 lasterror = GetLastError ();
0578e87f 2860 FlushInstructionCache (windows_process.handle,
2c647436 2861 (LPCVOID) (uintptr_t) memaddr, len);
24e60978
SC
2862 }
2863 else
2864 {
4ef367bf
TT
2865 DEBUG_MEM ("read target memory, %s bytes at %s",
2866 pulongest (len), core_addr_to_string (memaddr));
0578e87f 2867 success = ReadProcessMemory (windows_process.handle,
44f38867
PA
2868 (LPCVOID) (uintptr_t) memaddr, readbuf,
2869 len, &done);
9e52adf9 2870 if (!success)
7126d5c8 2871 lasterror = GetLastError ();
24e60978 2872 }
9b409511 2873 *xfered_len = (ULONGEST) done;
9e52adf9 2874 if (!success && lasterror == ERROR_PARTIAL_COPY && done > 0)
9b409511 2875 return TARGET_XFER_OK;
9e52adf9 2876 else
9b409511 2877 return success ? TARGET_XFER_OK : TARGET_XFER_E_IO;
24e60978
SC
2878}
2879
f6ac5f3d
PA
2880void
2881windows_nat_target::kill ()
24e60978 2882{
0578e87f 2883 CHECK (TerminateProcess (windows_process.handle, 0));
3cee93ac 2884
b5edcb45
ILT
2885 for (;;)
2886 {
17617f2d 2887 if (!windows_continue (DBG_CONTINUE, -1, 1))
b5edcb45 2888 break;
4cb763d6 2889 wait_for_debug_event_main_thread (&windows_process.current_event);
0578e87f
TT
2890 if (windows_process.current_event.dwDebugEventCode
2891 == EXIT_PROCESS_DEBUG_EVENT)
b5edcb45
ILT
2892 break;
2893 }
2894
9eee20eb 2895 target_mourn_inferior (inferior_ptid); /* Or just windows_mourn_inferior? */
24e60978
SC
2896}
2897
f6ac5f3d
PA
2898void
2899windows_nat_target::close ()
24e60978 2900{
4ef367bf 2901 DEBUG_EVENTS ("inferior_ptid=%d\n", inferior_ptid.pid ());
d08bae3d 2902 async (false);
24e60978 2903}
1ef980b9 2904
581e13c1 2905/* Convert pid to printable format. */
a068643d 2906std::string
f6ac5f3d 2907windows_nat_target::pid_to_str (ptid_t ptid)
24e60978 2908{
7c7411bc
TT
2909 if (ptid.lwp () != 0)
2910 return string_printf ("Thread %d.0x%lx", ptid.pid (), ptid.lwp ());
2dc38344
PA
2911
2912 return normal_pid_to_str (ptid);
3ee6f623
CF
2913}
2914
9b409511 2915static enum target_xfer_status
dc05df57 2916windows_xfer_shared_libraries (struct target_ops *ops,
9b409511
YQ
2917 enum target_object object, const char *annex,
2918 gdb_byte *readbuf, const gdb_byte *writebuf,
2919 ULONGEST offset, ULONGEST len,
2920 ULONGEST *xfered_len)
3cb8e7f6 2921{
de1b3c3d 2922 if (writebuf)
2ed4b548 2923 return TARGET_XFER_E_IO;
3cb8e7f6 2924
d6ac292e 2925 std::string xml = "<library-list>\n";
20489cca 2926 for (windows_solib &so : windows_process.solibs)
85b25bd9
TT
2927 windows_xfer_shared_library (so.name.c_str (),
2928 (CORE_ADDR) (uintptr_t) so.load_addr,
2929 &so.text_offset,
d6ac292e
SM
2930 current_inferior ()->arch (), xml);
2931 xml += "</library-list>\n";
3cb8e7f6 2932
d6ac292e 2933 ULONGEST len_avail = xml.size ();
de1b3c3d 2934 if (offset >= len_avail)
d6ac292e 2935 len = 0;
49dc7f4b
PM
2936 else
2937 {
2938 if (len > len_avail - offset)
2939 len = len_avail - offset;
d6ac292e 2940 memcpy (readbuf, xml.data () + offset, len);
49dc7f4b 2941 }
3cb8e7f6 2942
9b409511 2943 *xfered_len = (ULONGEST) len;
0837c976 2944 return len != 0 ? TARGET_XFER_OK : TARGET_XFER_EOF;
3cb8e7f6
CF
2945}
2946
7928d571
HD
2947/* Helper for windows_nat_target::xfer_partial that handles signal info. */
2948
2949static enum target_xfer_status
2950windows_xfer_siginfo (gdb_byte *readbuf, ULONGEST offset, ULONGEST len,
2951 ULONGEST *xfered_len)
2952{
0578e87f
TT
2953 char *buf = (char *) &windows_process.siginfo_er;
2954 size_t bufsize = sizeof (windows_process.siginfo_er);
46f9f931
HD
2955
2956#ifdef __x86_64__
2957 EXCEPTION_RECORD32 er32;
0578e87f 2958 if (windows_process.wow64_process)
46f9f931
HD
2959 {
2960 buf = (char *) &er32;
2961 bufsize = sizeof (er32);
2962
0578e87f
TT
2963 er32.ExceptionCode = windows_process.siginfo_er.ExceptionCode;
2964 er32.ExceptionFlags = windows_process.siginfo_er.ExceptionFlags;
2965 er32.ExceptionRecord
2966 = (uintptr_t) windows_process.siginfo_er.ExceptionRecord;
2967 er32.ExceptionAddress
2968 = (uintptr_t) windows_process.siginfo_er.ExceptionAddress;
2969 er32.NumberParameters = windows_process.siginfo_er.NumberParameters;
46f9f931
HD
2970 int i;
2971 for (i = 0; i < EXCEPTION_MAXIMUM_PARAMETERS; i++)
0578e87f
TT
2972 er32.ExceptionInformation[i]
2973 = windows_process.siginfo_er.ExceptionInformation[i];
46f9f931
HD
2974 }
2975#endif
2976
0578e87f 2977 if (windows_process.siginfo_er.ExceptionCode == 0)
7928d571
HD
2978 return TARGET_XFER_E_IO;
2979
2980 if (readbuf == nullptr)
2981 return TARGET_XFER_E_IO;
2982
46f9f931 2983 if (offset > bufsize)
7928d571
HD
2984 return TARGET_XFER_E_IO;
2985
46f9f931
HD
2986 if (offset + len > bufsize)
2987 len = bufsize - offset;
7928d571 2988
46f9f931 2989 memcpy (readbuf, buf + offset, len);
7928d571
HD
2990 *xfered_len = len;
2991
2992 return TARGET_XFER_OK;
2993}
2994
f6ac5f3d
PA
2995enum target_xfer_status
2996windows_nat_target::xfer_partial (enum target_object object,
2997 const char *annex, gdb_byte *readbuf,
2f4f025f
TT
2998 const gdb_byte *writebuf, ULONGEST offset,
2999 ULONGEST len, ULONGEST *xfered_len)
3cb8e7f6 3000{
de1b3c3d 3001 switch (object)
3cb8e7f6 3002 {
de1b3c3d 3003 case TARGET_OBJECT_MEMORY:
9b409511 3004 return windows_xfer_memory (readbuf, writebuf, offset, len, xfered_len);
de1b3c3d
PA
3005
3006 case TARGET_OBJECT_LIBRARIES:
f6ac5f3d 3007 return windows_xfer_shared_libraries (this, object, annex, readbuf,
9b409511 3008 writebuf, offset, len, xfered_len);
3929abe9 3009
7928d571
HD
3010 case TARGET_OBJECT_SIGNAL_INFO:
3011 return windows_xfer_siginfo (readbuf, offset, len, xfered_len);
3012
de1b3c3d 3013 default:
2f4f025f 3014 if (beneath () == NULL)
178d6a63
JB
3015 {
3016 /* This can happen when requesting the transfer of unsupported
3017 objects before a program has been started (and therefore
3018 with the current_target having no target beneath). */
3019 return TARGET_XFER_E_IO;
3020 }
2f4f025f
TT
3021 return beneath ()->xfer_partial (object, annex,
3022 readbuf, writebuf, offset, len,
3023 xfered_len);
3929abe9 3024 }
02c5aecd
CF
3025}
3026
711e434b
PM
3027/* Provide thread local base, i.e. Thread Information Block address.
3028 Returns 1 if ptid is found and sets *ADDR to thread_local_base. */
3029
57810aa7 3030bool
f6ac5f3d 3031windows_nat_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
711e434b 3032{
876d1cd7 3033 windows_thread_info *th;
711e434b 3034
0578e87f 3035 th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
711e434b 3036 if (th == NULL)
57810aa7 3037 return false;
711e434b
PM
3038
3039 if (addr != NULL)
3040 *addr = th->thread_local_base;
3041
57810aa7 3042 return true;
711e434b
PM
3043}
3044
f6ac5f3d 3045ptid_t
c80e29db 3046windows_nat_target::get_ada_task_ptid (long lwp, ULONGEST thread)
1e2f1c5c 3047{
7c7411bc 3048 return ptid_t (inferior_ptid.pid (), lwp, 0);
1e2f1c5c
JB
3049}
3050
24cdb46e
РИ
3051/* Implementation of the to_thread_name method. */
3052
f6ac5f3d
PA
3053const char *
3054windows_nat_target::thread_name (struct thread_info *thr)
24cdb46e 3055{
8bbdbd69
TT
3056 windows_thread_info *th
3057 = windows_process.thread_rec (thr->ptid,
3058 DONT_INVALIDATE_CONTEXT);
3059 return th->thread_name ();
24cdb46e
РИ
3060}
3061
24e60978 3062
6c265988 3063void _initialize_windows_nat ();
24e60978 3064void
6c265988 3065_initialize_windows_nat ()
24e60978 3066{
df7e5265
GB
3067 x86_dr_low.set_control = cygwin_set_dr7;
3068 x86_dr_low.set_addr = cygwin_set_dr;
3069 x86_dr_low.get_addr = cygwin_get_dr;
3070 x86_dr_low.get_status = cygwin_get_dr6;
3071 x86_dr_low.get_control = cygwin_get_dr7;
51a9c8c5 3072
df7e5265
GB
3073 /* x86_dr_low.debug_register_length field is set by
3074 calling x86_set_debug_register_length function
51a9c8c5 3075 in processor windows specific native file. */
fa58ee11 3076
5f8363d9
TT
3077 /* The target is not a global specifically to avoid a C++ "static
3078 initializer fiasco" situation. */
3079 add_inf_child_target (new windows_nat_target);
1ef980b9 3080
d0d0ab16
CV
3081#ifdef __CYGWIN__
3082 cygwin_internal (CW_SET_DOS_FILE_WARNING, 0);
3083#endif
3084
463888ab
РИ
3085 add_com ("signal-event", class_run, signal_event_command, _("\
3086Signal a crashed process with event ID, to allow its debugging.\n\
3087This command is needed in support of setting up GDB as JIT debugger on \
3088MS-Windows. The command should be invoked from the GDB command line using \
3089the '-ex' command-line option. The ID of the event that blocks the \
3090crashed process will be supplied by the Windows JIT debugging mechanism."));
3091
10325bc5 3092#ifdef __CYGWIN__
5bf193a2
AC
3093 add_setshow_boolean_cmd ("shell", class_support, &useshell, _("\
3094Set use of shell to start subprocess."), _("\
3095Show use of shell to start subprocess."), NULL,
3096 NULL,
3097 NULL, /* FIXME: i18n: */
3098 &setlist, &showlist);
3099
581e13c1
MS
3100 add_setshow_boolean_cmd ("cygwin-exceptions", class_support,
3101 &cygwin_exceptions, _("\
09280ddf
CF
3102Break when an exception is detected in the Cygwin DLL itself."), _("\
3103Show whether gdb breaks on exceptions in the Cygwin DLL itself."), NULL,
3104 NULL,
3105 NULL, /* FIXME: i18n: */
3106 &setlist, &showlist);
10325bc5 3107#endif
09280ddf 3108
5bf193a2
AC
3109 add_setshow_boolean_cmd ("new-console", class_support, &new_console, _("\
3110Set creation of new console when creating child process."), _("\
3111Show creation of new console when creating child process."), NULL,
3112 NULL,
3113 NULL, /* FIXME: i18n: */
3114 &setlist, &showlist);
3115
3116 add_setshow_boolean_cmd ("new-group", class_support, &new_group, _("\
3117Set creation of new group when creating child process."), _("\
3118Show creation of new group when creating child process."), NULL,
3119 NULL,
3120 NULL, /* FIXME: i18n: */
3121 &setlist, &showlist);
3122
3123 add_setshow_boolean_cmd ("debugexec", class_support, &debug_exec, _("\
3124Set whether to display execution in child process."), _("\
3125Show whether to display execution in child process."), NULL,
3126 NULL,
3127 NULL, /* FIXME: i18n: */
3128 &setlist, &showlist);
3129
3130 add_setshow_boolean_cmd ("debugevents", class_support, &debug_events, _("\
3131Set whether to display kernel events in child process."), _("\
3132Show whether to display kernel events in child process."), NULL,
3133 NULL,
3134 NULL, /* FIXME: i18n: */
3135 &setlist, &showlist);
3136
3137 add_setshow_boolean_cmd ("debugmemory", class_support, &debug_memory, _("\
3138Set whether to display memory accesses in child process."), _("\
3139Show whether to display memory accesses in child process."), NULL,
3140 NULL,
3141 NULL, /* FIXME: i18n: */
3142 &setlist, &showlist);
3143
3144 add_setshow_boolean_cmd ("debugexceptions", class_support,
3145 &debug_exceptions, _("\
3146Set whether to display kernel exceptions in child process."), _("\
3147Show whether to display kernel exceptions in child process."), NULL,
3148 NULL,
3149 NULL, /* FIXME: i18n: */
3150 &setlist, &showlist);
1ef980b9 3151
711e434b 3152 init_w32_command_list ();
c1748f97
PM
3153
3154 add_cmd ("selector", class_info, display_selectors,
1a966eab 3155 _("Display selectors infos."),
c1748f97 3156 &info_w32_cmdlist);
9e439f00
TT
3157
3158 if (!initialize_loadable ())
3159 {
3160 /* This will probably fail on Windows 9x/Me. Let the user know
3161 that we're missing some functionality. */
3162 warning(_("\
3163cannot automatically find executable file or library to read symbols.\n\
3164Use \"file\" or \"dll\" command to load executable/libraries directly."));
3165 }
24e60978 3166}
3cee93ac 3167
fa4ba8da
PM
3168/* Hardware watchpoint support, adapted from go32-nat.c code. */
3169
3170/* Pass the address ADDR to the inferior in the I'th debug register.
3171 Here we just store the address in dr array, the registers will be
dc05df57 3172 actually set up when windows_continue is called. */
9bb9e8ad 3173static void
fa4ba8da
PM
3174cygwin_set_dr (int i, CORE_ADDR addr)
3175{
3176 if (i < 0 || i > 3)
f34652de 3177 internal_error (_("Invalid register %d in cygwin_set_dr.\n"), i);
20489cca 3178 windows_process.dr[i] = addr;
296d3d2e 3179
20489cca 3180 for (auto &th : windows_process.thread_list)
296d3d2e 3181 th->debug_registers_changed = true;
fa4ba8da
PM
3182}
3183
3184/* Pass the value VAL to the inferior in the DR7 debug control
3185 register. Here we just store the address in D_REGS, the watchpoint
dc05df57 3186 will be actually set up in windows_wait. */
9bb9e8ad
PM
3187static void
3188cygwin_set_dr7 (unsigned long val)
fa4ba8da 3189{
20489cca 3190 windows_process.dr[7] = (CORE_ADDR) val;
296d3d2e 3191
20489cca 3192 for (auto &th : windows_process.thread_list)
296d3d2e 3193 th->debug_registers_changed = true;
fa4ba8da
PM
3194}
3195
7b50312a
PA
3196/* Get the value of debug register I from the inferior. */
3197
3198static CORE_ADDR
3199cygwin_get_dr (int i)
3200{
20489cca 3201 return windows_process.dr[i];
7b50312a
PA
3202}
3203
fa4ba8da
PM
3204/* Get the value of the DR6 debug status register from the inferior.
3205 Here we just return the value stored in dr[6]
3206 by the last call to thread_rec for current_event.dwThreadId id. */
9bb9e8ad 3207static unsigned long
fa4ba8da
PM
3208cygwin_get_dr6 (void)
3209{
20489cca 3210 return (unsigned long) windows_process.dr[6];
fa4ba8da
PM
3211}
3212
7b50312a
PA
3213/* Get the value of the DR7 debug status register from the inferior.
3214 Here we just return the value stored in dr[7] by the last call to
3215 thread_rec for current_event.dwThreadId id. */
3216
3217static unsigned long
3218cygwin_get_dr7 (void)
3219{
20489cca 3220 return (unsigned long) windows_process.dr[7];
7b50312a
PA
3221}
3222
2dc38344 3223/* Determine if the thread referenced by "ptid" is alive
3cee93ac 3224 by "polling" it. If WaitForSingleObject returns WAIT_OBJECT_0
581e13c1 3225 it means that the thread has died. Otherwise it is assumed to be alive. */
f6ac5f3d 3226
57810aa7 3227bool
f6ac5f3d 3228windows_nat_target::thread_alive (ptid_t ptid)
3cee93ac 3229{
7c7411bc 3230 gdb_assert (ptid.lwp () != 0);
39f77062 3231
0578e87f
TT
3232 windows_thread_info *th
3233 = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
3234 return WaitForSingleObject (th->h, 0) != WAIT_OBJECT_0;
3cee93ac
CF
3235}
3236
6c265988 3237void _initialize_check_for_gdb_ini ();
2a3d5645 3238void
6c265988 3239_initialize_check_for_gdb_ini ()
2a3d5645
CF
3240{
3241 char *homedir;
3242 if (inhibit_gdbinit)
3243 return;
3244
3245 homedir = getenv ("HOME");
3246 if (homedir)
3247 {
3248 char *p;
3249 char *oldini = (char *) alloca (strlen (homedir) +
1270fac6 3250 sizeof ("gdb.ini") + 1);
2a3d5645
CF
3251 strcpy (oldini, homedir);
3252 p = strchr (oldini, '\0');
0ba1096a 3253 if (p > oldini && !IS_DIR_SEPARATOR (p[-1]))
2a3d5645
CF
3254 *p++ = '/';
3255 strcpy (p, "gdb.ini");
3256 if (access (oldini, 0) == 0)
3257 {
3258 int len = strlen (oldini);
1270fac6 3259 char *newini = (char *) alloca (len + 2);
08850b56 3260
1270fac6 3261 xsnprintf (newini, len + 2, "%.*s.gdbinit",
08850b56 3262 (int) (len - (sizeof ("gdb.ini") - 1)), oldini);
8a3fe4f8 3263 warning (_("obsolete '%s' found. Rename to '%s'."), oldini, newini);
2a3d5645
CF
3264 }
3265 }
3266}