Fix Cygwin gdb build
[deliverable/binutils-gdb.git] / gdbserver / win32-low.cc
CommitLineData
b80864fb 1/* Low level interface to Windows debugging, for gdbserver.
b811d2c2 2 Copyright (C) 2006-2020 Free Software Foundation, Inc.
b80864fb
DJ
3
4 Contributed by Leo Zayas. Based on "win32-nat.c" from GDB.
5
6 This file is part of GDB.
7
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
a9762ec7 10 the Free Software Foundation; either version 3 of the License, or
b80864fb
DJ
11 (at your option) any later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
a9762ec7 19 along with this program. If not, see <http://www.gnu.org/licenses/>. */
b80864fb
DJ
20
21#include "server.h"
22#include "regcache.h"
59a016f0 23#include "gdb/fileio.h"
ed50f18f
PA
24#include "mem-break.h"
25#include "win32-low.h"
623b6bdf 26#include "gdbthread.h"
799cdc37 27#include "dll.h"
533b0600 28#include "hostio.h"
b80864fb 29#include <windows.h>
ed50f18f 30#include <winnt.h>
b80864fb 31#include <imagehlp.h>
255e7678 32#include <tlhelp32.h>
b80864fb 33#include <psapi.h>
b80864fb 34#include <process.h>
268a13a5
TT
35#include "gdbsupport/gdb_tilde_expand.h"
36#include "gdbsupport/common-inferior.h"
559e7e50 37#include "gdbsupport/gdb_wait.h"
b80864fb 38
4834dad0
TT
39using namespace windows_nat;
40
b80864fb
DJ
41#ifndef USE_WIN32API
42#include <sys/cygwin.h>
43#endif
44
10357975
PA
45#define OUTMSG(X) do { printf X; fflush (stderr); } while (0)
46
47#define OUTMSG2(X) \
48 do \
49 { \
50 if (debug_threads) \
51 { \
52 printf X; \
53 fflush (stderr); \
54 } \
55 } while (0)
ed50f18f
PA
56
57#ifndef _T
58#define _T(x) TEXT (x)
59#endif
60
61#ifndef COUNTOF
62#define COUNTOF(STR) (sizeof (STR) / sizeof ((STR)[0]))
b80864fb
DJ
63#endif
64
bf914831
PA
65#ifdef _WIN32_WCE
66# define GETPROCADDRESS(DLL, PROC) \
67 ((winapi_ ## PROC) GetProcAddress (DLL, TEXT (#PROC)))
68#else
69# define GETPROCADDRESS(DLL, PROC) \
70 ((winapi_ ## PROC) GetProcAddress (DLL, #PROC))
71#endif
72
b80864fb
DJ
73int using_threads = 1;
74
75/* Globals. */
d97903b2 76static int attaching = 0;
b80864fb 77
4210d83e
PA
78/* A status that hasn't been reported to the core yet, and so
79 win32_wait should return it next, instead of fetching the next
80 debug event off the win32 API. */
81static struct target_waitstatus cached_status;
82
4d5d1aaa
PA
83/* Non zero if an interrupt request is to be satisfied by suspending
84 all threads. */
85static int soft_interrupt_requested = 0;
86
87/* Non zero if the inferior is stopped in a simulated breakpoint done
88 by suspending all the threads. */
89static int faked_breakpoint = 0;
90
3aee8918
PA
91const struct target_desc *win32_tdesc;
92
ed50f18f 93#define NUM_REGS (the_low_target.num_regs)
b80864fb 94
7a9a7487
MG
95typedef BOOL (WINAPI *winapi_DebugActiveProcessStop) (DWORD dwProcessId);
96typedef BOOL (WINAPI *winapi_DebugSetProcessKillOnExit) (BOOL KillOnExit);
97typedef BOOL (WINAPI *winapi_DebugBreakProcess) (HANDLE);
98typedef BOOL (WINAPI *winapi_GenerateConsoleCtrlEvent) (DWORD, DWORD);
b80864fb 99
379a5e2d 100#ifndef _WIN32_WCE
f25b3fc3 101static void win32_add_all_dlls (void);
379a5e2d 102#endif
34b34921 103
b80864fb
DJ
104/* Get the thread ID from the current selected inferior (the current
105 thread). */
95954743 106static ptid_t
0bfdf32f 107current_thread_ptid (void)
b80864fb 108{
80894984 109 return current_ptid;
95954743
PA
110}
111
112/* The current debug event from WaitForDebugEvent. */
113static ptid_t
114debug_event_ptid (DEBUG_EVENT *event)
115{
fd79271b 116 return ptid_t (event->dwProcessId, event->dwThreadId, 0);
b80864fb
DJ
117}
118
9c6c8194
PA
119/* Get the thread context of the thread associated with TH. */
120
121static void
e56f8ccb 122win32_get_thread_context (windows_thread_info *th)
9c6c8194
PA
123{
124 memset (&th->context, 0, sizeof (CONTEXT));
a2abc7de 125 (*the_low_target.get_thread_context) (th);
9c6c8194
PA
126#ifdef _WIN32_WCE
127 memcpy (&th->base_context, &th->context, sizeof (CONTEXT));
128#endif
129}
130
131/* Set the thread context of the thread associated with TH. */
132
133static void
e56f8ccb 134win32_set_thread_context (windows_thread_info *th)
9c6c8194
PA
135{
136#ifdef _WIN32_WCE
137 /* Calling SuspendThread on a thread that is running kernel code
138 will report that the suspending was successful, but in fact, that
139 will often not be true. In those cases, the context returned by
140 GetThreadContext will not be correct by the time the thread
141 stops, hence we can't set that context back into the thread when
30baf67b 142 resuming - it will most likely crash the inferior.
9c6c8194
PA
143 Unfortunately, there is no way to know when the thread will
144 really stop. To work around it, we'll only write the context
145 back to the thread when either the user or GDB explicitly change
146 it between stopping and resuming. */
147 if (memcmp (&th->context, &th->base_context, sizeof (CONTEXT)) != 0)
148#endif
a2abc7de 149 SetThreadContext (th->h, &th->context);
9c6c8194
PA
150}
151
a2abc7de
PA
152/* Set the thread context of the thread associated with TH. */
153
154static void
e56f8ccb 155win32_prepare_to_resume (windows_thread_info *th)
b80864fb 156{
a2abc7de
PA
157 if (the_low_target.prepare_to_resume != NULL)
158 (*the_low_target.prepare_to_resume) (th);
159}
b80864fb 160
a2abc7de 161/* See win32-low.h. */
b80864fb 162
a2abc7de 163void
e56f8ccb 164win32_require_context (windows_thread_info *th)
a2abc7de
PA
165{
166 if (th->context.ContextFlags == 0)
b80864fb 167 {
98a03287 168 th->suspend ();
9c6c8194 169 win32_get_thread_context (th);
b80864fb 170 }
a2abc7de
PA
171}
172
28688adf
TT
173/* See nat/windows-nat.h. */
174
175windows_thread_info *
176windows_nat::thread_rec (ptid_t ptid, thread_disposition_type disposition)
a2abc7de 177{
8dc7b443 178 thread_info *thread = find_thread_ptid (ptid);
a2abc7de
PA
179 if (thread == NULL)
180 return NULL;
181
e56f8ccb 182 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread);
28688adf 183 if (disposition != DONT_INVALIDATE_CONTEXT)
a2abc7de 184 win32_require_context (th);
b80864fb
DJ
185 return th;
186}
187
188/* Add a thread to the thread list. */
e56f8ccb 189static windows_thread_info *
711e434b 190child_add_thread (DWORD pid, DWORD tid, HANDLE h, void *tlb)
b80864fb 191{
e56f8ccb 192 windows_thread_info *th;
fd79271b 193 ptid_t ptid = ptid_t (pid, tid, 0);
b80864fb 194
28688adf 195 if ((th = thread_rec (ptid, DONT_INVALIDATE_CONTEXT)))
b80864fb
DJ
196 return th;
197
e9534bd2 198 th = new windows_thread_info (tid, h, (CORE_ADDR) (uintptr_t) tlb);
b80864fb 199
95954743 200 add_thread (ptid, th);
b80864fb 201
34b34921
PA
202 if (the_low_target.thread_added != NULL)
203 (*the_low_target.thread_added) (th);
b80864fb
DJ
204
205 return th;
206}
207
208/* Delete a thread from the list of threads. */
209static void
9c80ecd6 210delete_thread_info (thread_info *thread)
b80864fb 211{
e56f8ccb 212 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread);
b80864fb 213
c3de4d92 214 remove_thread (thread);
e9534bd2 215 delete th;
b80864fb
DJ
216}
217
218/* Delete a thread from the list of threads. */
219static void
95954743 220child_delete_thread (DWORD pid, DWORD tid)
b80864fb 221{
b80864fb 222 /* If the last thread is exiting, just return. */
9c80ecd6 223 if (all_threads.size () == 1)
b80864fb
DJ
224 return;
225
8dc7b443 226 thread_info *thread = find_thread_ptid (ptid_t (pid, tid));
b80864fb
DJ
227 if (thread == NULL)
228 return;
229
230 delete_thread_info (thread);
231}
232
aa5ca48f
DE
233/* These watchpoint related wrapper functions simply pass on the function call
234 if the low target has registered a corresponding function. */
235
a2b2297a
TBA
236bool
237win32_process_target::supports_z_point_type (char z_type)
802e8e6d 238{
523d4f80
TT
239 return (z_type == Z_PACKET_SW_BP
240 || (the_low_target.supports_z_point_type != NULL
241 && the_low_target.supports_z_point_type (z_type)));
802e8e6d
PA
242}
243
7e0bde70
TBA
244int
245win32_process_target::insert_point (enum raw_bkpt_type type, CORE_ADDR addr,
246 int size, raw_breakpoint *bp)
aa5ca48f 247{
523d4f80
TT
248 if (type == raw_bkpt_type_sw)
249 return insert_memory_breakpoint (bp);
250 else if (the_low_target.insert_point != NULL)
802e8e6d 251 return the_low_target.insert_point (type, addr, size, bp);
aa5ca48f
DE
252 else
253 /* Unsupported (see target.h). */
254 return 1;
255}
256
7e0bde70
TBA
257int
258win32_process_target::remove_point (enum raw_bkpt_type type, CORE_ADDR addr,
259 int size, raw_breakpoint *bp)
aa5ca48f 260{
523d4f80
TT
261 if (type == raw_bkpt_type_sw)
262 return remove_memory_breakpoint (bp);
263 else if (the_low_target.remove_point != NULL)
802e8e6d 264 return the_low_target.remove_point (type, addr, size, bp);
aa5ca48f
DE
265 else
266 /* Unsupported (see target.h). */
267 return 1;
268}
269
6eeb5c55
TBA
270bool
271win32_process_target::stopped_by_watchpoint ()
aa5ca48f
DE
272{
273 if (the_low_target.stopped_by_watchpoint != NULL)
274 return the_low_target.stopped_by_watchpoint ();
275 else
6eeb5c55 276 return false;
aa5ca48f
DE
277}
278
6eeb5c55
TBA
279CORE_ADDR
280win32_process_target::stopped_data_address ()
aa5ca48f
DE
281{
282 if (the_low_target.stopped_data_address != NULL)
283 return the_low_target.stopped_data_address ();
284 else
285 return 0;
286}
287
288
b80864fb
DJ
289/* Transfer memory from/to the debugged process. */
290static int
291child_xfer_memory (CORE_ADDR memaddr, char *our, int len,
5b6d1e4f 292 int write, process_stratum_target *target)
b80864fb 293{
cee83bcb
PM
294 BOOL success;
295 SIZE_T done = 0;
296 DWORD lasterror = 0;
e8f0053d 297 uintptr_t addr = (uintptr_t) memaddr;
b80864fb
DJ
298
299 if (write)
300 {
cee83bcb
PM
301 success = WriteProcessMemory (current_process_handle, (LPVOID) addr,
302 (LPCVOID) our, len, &done);
303 if (!success)
304 lasterror = GetLastError ();
b80864fb
DJ
305 FlushInstructionCache (current_process_handle, (LPCVOID) addr, len);
306 }
307 else
308 {
cee83bcb
PM
309 success = ReadProcessMemory (current_process_handle, (LPCVOID) addr,
310 (LPVOID) our, len, &done);
311 if (!success)
312 lasterror = GetLastError ();
b80864fb 313 }
cee83bcb
PM
314 if (!success && lasterror == ERROR_PARTIAL_COPY && done > 0)
315 return done;
316 else
317 return success ? done : -1;
b80864fb
DJ
318}
319
ed50f18f 320/* Clear out any old thread list and reinitialize it to a pristine
b80864fb
DJ
321 state. */
322static void
323child_init_thread_list (void)
324{
f0045347 325 for_each_thread (delete_thread_info);
b80864fb
DJ
326}
327
f25b3fc3
JB
328/* Zero during the child initialization phase, and nonzero otherwise. */
329
330static int child_initialization_done = 0;
331
b80864fb 332static void
95954743 333do_initial_child_stuff (HANDLE proch, DWORD pid, int attached)
b80864fb 334{
3aee8918
PA
335 struct process_info *proc;
336
a493e3e2 337 last_sig = GDB_SIGNAL_0;
b80864fb 338
5ac588cf
PA
339 current_process_handle = proch;
340 current_process_id = pid;
341 main_thread_id = 0;
342
343 soft_interrupt_requested = 0;
344 faked_breakpoint = 0;
345
b80864fb
DJ
346 memset (&current_event, 0, sizeof (current_event));
347
3aee8918
PA
348 proc = add_process (pid, attached);
349 proc->tdesc = win32_tdesc;
b80864fb 350 child_init_thread_list ();
f25b3fc3 351 child_initialization_done = 0;
ed50f18f
PA
352
353 if (the_low_target.initial_stuff != NULL)
354 (*the_low_target.initial_stuff) ();
4210d83e
PA
355
356 cached_status.kind = TARGET_WAITKIND_IGNORE;
357
358 /* Flush all currently pending debug events (thread and dll list) up
359 to the initial breakpoint. */
360 while (1)
361 {
362 struct target_waitstatus status;
363
52405d85 364 the_target->wait (minus_one_ptid, &status, 0);
4210d83e
PA
365
366 /* Note win32_wait doesn't return thread events. */
367 if (status.kind != TARGET_WAITKIND_LOADED)
368 {
369 cached_status = status;
370 break;
371 }
372
373 {
374 struct thread_resume resume;
375
376 resume.thread = minus_one_ptid;
377 resume.kind = resume_continue;
378 resume.sig = 0;
379
52405d85 380 the_target->resume (&resume, 1);
4210d83e
PA
381 }
382 }
379a5e2d
JB
383
384#ifndef _WIN32_WCE
f25b3fc3
JB
385 /* Now that the inferior has been started and all DLLs have been mapped,
386 we can iterate over all DLLs and load them in.
387
388 We avoid doing it any earlier because, on certain versions of Windows,
389 LOAD_DLL_DEBUG_EVENTs are sometimes not complete. In particular,
390 we have seen on Windows 8.1 that the ntdll.dll load event does not
391 include the DLL name, preventing us from creating an associated SO.
392 A possible explanation is that ntdll.dll might be mapped before
393 the SO info gets created by the Windows system -- ntdll.dll is
394 the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs
395 do not seem to suffer from that problem.
396
397 Rather than try to work around this sort of issue, it is much
398 simpler to just ignore DLL load/unload events during the startup
399 phase, and then process them all in one batch now. */
400 win32_add_all_dlls ();
379a5e2d 401#endif
f25b3fc3
JB
402
403 child_initialization_done = 1;
b80864fb
DJ
404}
405
406/* Resume all artificially suspended threads if we are continuing
407 execution. */
2bee2b6c
SM
408static void
409continue_one_thread (thread_info *thread, int thread_id)
b80864fb 410{
e56f8ccb 411 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread);
b80864fb 412
a2abc7de 413 if (thread_id == -1 || thread_id == th->tid)
b80864fb 414 {
a2abc7de 415 win32_prepare_to_resume (th);
34b34921 416
a2abc7de 417 if (th->suspended)
c436e841 418 {
a2abc7de
PA
419 if (th->context.ContextFlags)
420 {
421 win32_set_thread_context (th);
422 th->context.ContextFlags = 0;
423 }
424
98a03287 425 th->resume ();
c436e841 426 }
b80864fb 427 }
b80864fb
DJ
428}
429
430static BOOL
431child_continue (DWORD continue_status, int thread_id)
432{
360ad8b3
TT
433 desired_stop_thread_id = thread_id;
434 if (matching_pending_stop (debug_threads))
435 return TRUE;
436
4d5d1aaa
PA
437 /* The inferior will only continue after the ContinueDebugEvent
438 call. */
2bee2b6c
SM
439 for_each_thread ([&] (thread_info *thread)
440 {
441 continue_one_thread (thread, thread_id);
442 });
4d5d1aaa 443 faked_breakpoint = 0;
b80864fb 444
e758e19c 445 return continue_last_debug_event (continue_status, debug_threads);
b80864fb
DJ
446}
447
b80864fb
DJ
448/* Fetch register(s) from the current thread context. */
449static void
442ea881 450child_fetch_inferior_registers (struct regcache *regcache, int r)
b80864fb
DJ
451{
452 int regno;
28688adf
TT
453 windows_thread_info *th = thread_rec (current_thread_ptid (),
454 INVALIDATE_CONTEXT);
4463ce24 455 if (r == -1 || r > NUM_REGS)
442ea881 456 child_fetch_inferior_registers (regcache, NUM_REGS);
b80864fb
DJ
457 else
458 for (regno = 0; regno < r; regno++)
442ea881 459 (*the_low_target.fetch_inferior_register) (regcache, th, regno);
b80864fb
DJ
460}
461
462/* Store a new register value into the current thread context. We don't
463 change the program's context until later, when we resume it. */
464static void
442ea881 465child_store_inferior_registers (struct regcache *regcache, int r)
b80864fb
DJ
466{
467 int regno;
28688adf
TT
468 windows_thread_info *th = thread_rec (current_thread_ptid (),
469 INVALIDATE_CONTEXT);
b80864fb 470 if (r == -1 || r == 0 || r > NUM_REGS)
442ea881 471 child_store_inferior_registers (regcache, NUM_REGS);
b80864fb
DJ
472 else
473 for (regno = 0; regno < r; regno++)
442ea881 474 (*the_low_target.store_inferior_register) (regcache, th, regno);
b80864fb
DJ
475}
476
ed50f18f
PA
477/* Map the Windows error number in ERROR to a locale-dependent error
478 message string and return a pointer to it. Typically, the values
479 for ERROR come from GetLastError.
480
481 The string pointed to shall not be modified by the application,
482 but may be overwritten by a subsequent call to strwinerror
483
484 The strwinerror function does not change the current setting
485 of GetLastError. */
486
487char *
488strwinerror (DWORD error)
489{
490 static char buf[1024];
491 TCHAR *msgbuf;
492 DWORD lasterr = GetLastError ();
493 DWORD chars = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
494 | FORMAT_MESSAGE_ALLOCATE_BUFFER,
495 NULL,
496 error,
497 0, /* Default language */
c3de4d92 498 (LPTSTR) &msgbuf,
ed50f18f
PA
499 0,
500 NULL);
501 if (chars != 0)
502 {
503 /* If there is an \r\n appended, zap it. */
504 if (chars >= 2
505 && msgbuf[chars - 2] == '\r'
506 && msgbuf[chars - 1] == '\n')
507 {
508 chars -= 2;
509 msgbuf[chars] = 0;
510 }
511
512 if (chars > ((COUNTOF (buf)) - 1))
513 {
514 chars = COUNTOF (buf) - 1;
515 msgbuf [chars] = 0;
516 }
517
518#ifdef UNICODE
519 wcstombs (buf, msgbuf, chars + 1);
520#else
521 strncpy (buf, msgbuf, chars + 1);
522#endif
523 LocalFree (msgbuf);
524 }
525 else
dfe07582 526 sprintf (buf, "unknown win32 error (%u)", (unsigned) error);
ed50f18f
PA
527
528 SetLastError (lasterr);
529 return buf;
530}
531
aec18585
PA
532static BOOL
533create_process (const char *program, char *args,
534 DWORD flags, PROCESS_INFORMATION *pi)
535{
bc3b087d 536 const char *inferior_cwd = get_inferior_cwd ();
aec18585 537 BOOL ret;
a9b34532
EZ
538 size_t argslen, proglen;
539
540 proglen = strlen (program) + 1;
541 argslen = strlen (args) + proglen;
aec18585
PA
542
543#ifdef _WIN32_WCE
bc3b087d 544 wchar_t *p, *wprogram, *wargs, *wcwd = NULL;
aec18585 545
a9b34532
EZ
546 wprogram = (wchar_t *) alloca (proglen * sizeof (wchar_t));
547 mbstowcs (wprogram, program, proglen);
aec18585
PA
548
549 for (p = wprogram; *p; ++p)
550 if (L'/' == *p)
551 *p = L'\\';
552
aec18585 553 wargs = alloca ((argslen + 1) * sizeof (wchar_t));
a9b34532
EZ
554 wcscpy (wargs, wprogram);
555 wcscat (wargs, L" ");
556 mbstowcs (wargs + proglen, args, argslen + 1 - proglen);
aec18585 557
bc3b087d
SDJ
558 if (inferior_cwd != NULL)
559 {
906994d9 560 std::string expanded_infcwd = gdb_tilde_expand (inferior_cwd);
bc3b087d
SDJ
561 std::replace (expanded_infcwd.begin (), expanded_infcwd.end (),
562 '/', '\\');
563 wcwd = alloca ((expanded_infcwd.size () + 1) * sizeof (wchar_t));
564 if (mbstowcs (wcwd, expanded_infcwd.c_str (),
565 expanded_infcwd.size () + 1) == NULL)
566 {
567 error (_("\
568Could not convert the expanded inferior cwd to wide-char."));
569 }
570 }
571
aec18585 572 ret = CreateProcessW (wprogram, /* image name */
1b3f6016
PA
573 wargs, /* command line */
574 NULL, /* security, not supported */
575 NULL, /* thread, not supported */
576 FALSE, /* inherit handles, not supported */
577 flags, /* start flags */
578 NULL, /* environment, not supported */
bc3b087d 579 wcwd, /* current directory */
1b3f6016
PA
580 NULL, /* start info, not supported */
581 pi); /* proc info */
aec18585
PA
582#else
583 STARTUPINFOA si = { sizeof (STARTUPINFOA) };
a9b34532
EZ
584 char *program_and_args = (char *) alloca (argslen + 1);
585
586 strcpy (program_and_args, program);
587 strcat (program_and_args, " ");
588 strcat (program_and_args, args);
589 ret = CreateProcessA (program, /* image name */
590 program_and_args, /* command line */
591 NULL, /* security */
592 NULL, /* thread */
593 TRUE, /* inherit handles */
594 flags, /* start flags */
595 NULL, /* environment */
906994d9
JB
596 /* current directory */
597 (inferior_cwd == NULL
598 ? NULL
599 : gdb_tilde_expand (inferior_cwd).c_str()),
a9b34532
EZ
600 &si, /* start info */
601 pi); /* proc info */
aec18585
PA
602#endif
603
604 return ret;
605}
606
b80864fb 607/* Start a new process.
2090129c
SDJ
608 PROGRAM is the program name.
609 PROGRAM_ARGS is the vector containing the inferior's args.
b80864fb
DJ
610 Returns the new PID on success, -1 on failure. Registers the new
611 process with the process list. */
15295543
TBA
612int
613win32_process_target::create_inferior (const char *program,
614 const std::vector<char *> &program_args)
b80864fb 615{
6341380d 616 client_state &cs = get_client_state ();
b80864fb 617#ifndef USE_WIN32API
d8d2a3ee 618 char real_path[PATH_MAX];
b80864fb
DJ
619 char *orig_path, *new_path, *path_ptr;
620#endif
b80864fb
DJ
621 BOOL ret;
622 DWORD flags;
ed50f18f 623 PROCESS_INFORMATION pi;
aec18585 624 DWORD err;
2090129c
SDJ
625 std::string str_program_args = stringify_argv (program_args);
626 char *args = (char *) str_program_args.c_str ();
b80864fb 627
d97903b2
PA
628 /* win32_wait needs to know we're not attaching. */
629 attaching = 0;
630
b80864fb
DJ
631 if (!program)
632 error ("No executable specified, specify executable to debug.\n");
633
b80864fb
DJ
634 flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS;
635
636#ifndef USE_WIN32API
637 orig_path = NULL;
638 path_ptr = getenv ("PATH");
639 if (path_ptr)
640 {
81239425 641 int size = cygwin_conv_path_list (CCP_POSIX_TO_WIN_A, path_ptr, NULL, 0);
0ae534d2
JT
642 orig_path = (char *) alloca (strlen (path_ptr) + 1);
643 new_path = (char *) alloca (size);
b80864fb 644 strcpy (orig_path, path_ptr);
81239425 645 cygwin_conv_path_list (CCP_POSIX_TO_WIN_A, path_ptr, new_path, size);
b80864fb 646 setenv ("PATH", new_path, 1);
81239425 647 }
d8d2a3ee 648 cygwin_conv_path (CCP_POSIX_TO_WIN_A, program, real_path, PATH_MAX);
b80864fb
DJ
649 program = real_path;
650#endif
651
a9b34532 652 OUTMSG2 (("Command line is \"%s %s\"\n", program, args));
b80864fb 653
ed50f18f 654#ifdef CREATE_NEW_PROCESS_GROUP
b80864fb 655 flags |= CREATE_NEW_PROCESS_GROUP;
ed50f18f 656#endif
b80864fb 657
aec18585
PA
658 ret = create_process (program, args, flags, &pi);
659 err = GetLastError ();
660 if (!ret && err == ERROR_FILE_NOT_FOUND)
661 {
c3de4d92 662 char *exename = (char *) alloca (strlen (program) + 5);
aec18585
PA
663 strcat (strcpy (exename, program), ".exe");
664 ret = create_process (exename, args, flags, &pi);
665 err = GetLastError ();
666 }
b80864fb
DJ
667
668#ifndef USE_WIN32API
669 if (orig_path)
670 setenv ("PATH", orig_path, 1);
671#endif
672
673 if (!ret)
674 {
a9b34532 675 error ("Error creating process \"%s %s\", (error %d): %s\n",
ed50f18f 676 program, args, (int) err, strwinerror (err));
b80864fb
DJ
677 }
678 else
679 {
a9b34532 680 OUTMSG2 (("Process created: %s %s\n", program, (char *) args));
b80864fb
DJ
681 }
682
ed50f18f
PA
683#ifndef _WIN32_WCE
684 /* On Windows CE this handle can't be closed. The OS reuses
685 it in the debug events, while the 9x/NT versions of Windows
686 probably use a DuplicateHandle'd one. */
b80864fb 687 CloseHandle (pi.hThread);
ed50f18f 688#endif
b80864fb 689
95954743 690 do_initial_child_stuff (pi.hProcess, pi.dwProcessId, 0);
b80864fb 691
7dbac825
JB
692 /* Wait till we are at 1st instruction in program, return new pid
693 (assuming success). */
6532e7e3 694 cs.last_ptid = wait (ptid_t (current_process_id), &cs.last_status, 0);
7dbac825 695
052793ad
HD
696 /* Necessary for handle_v_kill. */
697 signal_pid = current_process_id;
698
b80864fb
DJ
699 return current_process_id;
700}
701
702/* Attach to a running process.
703 PID is the process ID to attach to, specified by the user
704 or a higher layer. */
ef03dad8
TBA
705int
706win32_process_target::attach (unsigned long pid)
b80864fb 707{
5ca906e6 708 HANDLE h;
bf914831 709 winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit = NULL;
5ca906e6 710 DWORD err;
ed50f18f
PA
711#ifdef _WIN32_WCE
712 HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
713#else
714 HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
715#endif
bf914831 716 DebugSetProcessKillOnExit = GETPROCADDRESS (dll, DebugSetProcessKillOnExit);
b80864fb 717
5ca906e6
PA
718 h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
719 if (h != NULL)
1d5315fe 720 {
5ca906e6
PA
721 if (DebugActiveProcess (pid))
722 {
723 if (DebugSetProcessKillOnExit != NULL)
724 DebugSetProcessKillOnExit (FALSE);
725
d97903b2 726 /* win32_wait needs to know we're attaching. */
1b3f6016 727 attaching = 1;
95954743 728 do_initial_child_stuff (h, pid, 1);
5ca906e6
PA
729 return 0;
730 }
731
732 CloseHandle (h);
b80864fb
DJ
733 }
734
5ca906e6
PA
735 err = GetLastError ();
736 error ("Attach to process failed (error %d): %s\n",
737 (int) err, strwinerror (err));
b80864fb
DJ
738}
739
d41b524f
TT
740/* See nat/windows-nat.h. */
741
742int
743windows_nat::handle_output_debug_string (struct target_waitstatus *ourstatus)
bce7165d
PA
744{
745#define READ_BUFFER_LEN 1024
746 CORE_ADDR addr;
747 char s[READ_BUFFER_LEN + 1] = { 0 };
748 DWORD nbytes = current_event.u.DebugString.nDebugStringLength;
749
750 if (nbytes == 0)
d41b524f 751 return 0;
bce7165d
PA
752
753 if (nbytes > READ_BUFFER_LEN)
754 nbytes = READ_BUFFER_LEN;
755
756 addr = (CORE_ADDR) (size_t) current_event.u.DebugString.lpDebugStringData;
757
758 if (current_event.u.DebugString.fUnicode)
759 {
760 /* The event tells us how many bytes, not chars, even
1b3f6016 761 in Unicode. */
bce7165d
PA
762 WCHAR buffer[(READ_BUFFER_LEN + 1) / sizeof (WCHAR)] = { 0 };
763 if (read_inferior_memory (addr, (unsigned char *) buffer, nbytes) != 0)
d41b524f 764 return 0;
bce7165d
PA
765 wcstombs (s, buffer, (nbytes + 1) / sizeof (WCHAR));
766 }
767 else
768 {
769 if (read_inferior_memory (addr, (unsigned char *) s, nbytes) != 0)
d41b524f 770 return 0;
bce7165d
PA
771 }
772
61012eef 773 if (!startswith (s, "cYg"))
45e2715e
PA
774 {
775 if (!server_waiting)
776 {
777 OUTMSG2(("%s", s));
d41b524f 778 return 0;
45e2715e
PA
779 }
780
781 monitor_output (s);
782 }
bce7165d 783#undef READ_BUFFER_LEN
d41b524f
TT
784
785 return 0;
bce7165d
PA
786}
787
5ac588cf
PA
788static void
789win32_clear_inferiors (void)
790{
791 if (current_process_handle != NULL)
792 CloseHandle (current_process_handle);
793
f0045347 794 for_each_thread (delete_thread_info);
7928d571 795 siginfo_er.ExceptionCode = 0;
5ac588cf
PA
796 clear_inferiors ();
797}
798
a780ef4f
PA
799/* Implementation of target_ops::kill. */
800
c6885a57
TBA
801int
802win32_process_target::kill (process_info *process)
b80864fb
DJ
803{
804 TerminateProcess (current_process_handle, 0);
805 for (;;)
806 {
807 if (!child_continue (DBG_CONTINUE, -1))
808 break;
2c1d95e8 809 if (!wait_for_debug_event (&current_event, INFINITE))
b80864fb
DJ
810 break;
811 if (current_event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
812 break;
bce7165d 813 else if (current_event.dwDebugEventCode == OUTPUT_DEBUG_STRING_EVENT)
d41b524f 814 handle_output_debug_string (nullptr);
b80864fb 815 }
ed50f18f 816
5ac588cf 817 win32_clear_inferiors ();
95954743 818
95954743
PA
819 remove_process (process);
820 return 0;
b80864fb
DJ
821}
822
ef2ddb33
PA
823/* Implementation of target_ops::detach. */
824
9061c9cf
TBA
825int
826win32_process_target::detach (process_info *process)
b80864fb 827{
bf914831
PA
828 winapi_DebugActiveProcessStop DebugActiveProcessStop = NULL;
829 winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit = NULL;
ed50f18f
PA
830#ifdef _WIN32_WCE
831 HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
832#else
833 HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
834#endif
bf914831
PA
835 DebugActiveProcessStop = GETPROCADDRESS (dll, DebugActiveProcessStop);
836 DebugSetProcessKillOnExit = GETPROCADDRESS (dll, DebugSetProcessKillOnExit);
b80864fb 837
444d6139
PA
838 if (DebugSetProcessKillOnExit == NULL
839 || DebugActiveProcessStop == NULL)
840 return -1;
b80864fb 841
444d6139
PA
842 {
843 struct thread_resume resume;
95954743 844 resume.thread = minus_one_ptid;
bd99dc85 845 resume.kind = resume_continue;
444d6139 846 resume.sig = 0;
0e4d7e35 847 this->resume (&resume, 1);
444d6139
PA
848 }
849
850 if (!DebugActiveProcessStop (current_process_id))
5ac588cf
PA
851 return -1;
852
444d6139 853 DebugSetProcessKillOnExit (FALSE);
95954743 854 remove_process (process);
444d6139 855
5ac588cf 856 win32_clear_inferiors ();
444d6139
PA
857 return 0;
858}
859
8adb37b9
TBA
860void
861win32_process_target::mourn (struct process_info *process)
505106cd
PA
862{
863 remove_process (process);
864}
865
ef2ddb33
PA
866/* Implementation of target_ops::join. */
867
95a49a39
TBA
868void
869win32_process_target::join (int pid)
444d6139 870{
d105de22 871 HANDLE h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
5ac588cf
PA
872 if (h != NULL)
873 {
874 WaitForSingleObject (h, INFINITE);
875 CloseHandle (h);
876 }
b80864fb
DJ
877}
878
13d3d99b
TBA
879/* Return true iff the thread with thread ID TID is alive. */
880bool
881win32_process_target::thread_alive (ptid_t ptid)
b80864fb 882{
b80864fb
DJ
883 /* Our thread list is reliable; don't bother to poll target
884 threads. */
8dc7b443 885 return find_thread_ptid (ptid) != NULL;
b80864fb
DJ
886}
887
888/* Resume the inferior process. RESUME_INFO describes how we want
889 to resume. */
0e4d7e35
TBA
890void
891win32_process_target::resume (thread_resume *resume_info, size_t n)
b80864fb
DJ
892{
893 DWORD tid;
2ea28649 894 enum gdb_signal sig;
b80864fb 895 int step;
e56f8ccb 896 windows_thread_info *th;
b80864fb 897 DWORD continue_status = DBG_CONTINUE;
95954743 898 ptid_t ptid;
b80864fb
DJ
899
900 /* This handles the very limited set of resume packets that GDB can
901 currently produce. */
902
d7e15655 903 if (n == 1 && resume_info[0].thread == minus_one_ptid)
b80864fb 904 tid = -1;
2bd7c093 905 else if (n > 1)
b80864fb
DJ
906 tid = -1;
907 else
908 /* Yes, we're ignoring resume_info[0].thread. It'd be tricky to make
909 the Windows resume code do the right thing for thread switching. */
910 tid = current_event.dwThreadId;
911
d7e15655 912 if (resume_info[0].thread != minus_one_ptid)
b80864fb 913 {
ce7715e2 914 sig = gdb_signal_from_host (resume_info[0].sig);
bd99dc85 915 step = resume_info[0].kind == resume_step;
b80864fb
DJ
916 }
917 else
918 {
ce7715e2 919 sig = GDB_SIGNAL_0;
b80864fb
DJ
920 step = 0;
921 }
922
a493e3e2 923 if (sig != GDB_SIGNAL_0)
b80864fb
DJ
924 {
925 if (current_event.dwDebugEventCode != EXCEPTION_DEBUG_EVENT)
926 {
ce7715e2
PA
927 OUTMSG (("Cannot continue with signal %s here.\n",
928 gdb_signal_to_string (sig)));
b80864fb
DJ
929 }
930 else if (sig == last_sig)
931 continue_status = DBG_EXCEPTION_NOT_HANDLED;
932 else
ce7715e2
PA
933 OUTMSG (("Can only continue with received signal %s.\n",
934 gdb_signal_to_string (last_sig)));
b80864fb
DJ
935 }
936
a493e3e2 937 last_sig = GDB_SIGNAL_0;
b80864fb
DJ
938
939 /* Get context for the currently selected thread. */
95954743 940 ptid = debug_event_ptid (&current_event);
28688adf 941 th = thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
b80864fb
DJ
942 if (th)
943 {
a2abc7de
PA
944 win32_prepare_to_resume (th);
945
b80864fb
DJ
946 if (th->context.ContextFlags)
947 {
b80864fb
DJ
948 /* Move register values from the inferior into the thread
949 context structure. */
950 regcache_invalidate ();
951
952 if (step)
ed50f18f
PA
953 {
954 if (the_low_target.single_step != NULL)
955 (*the_low_target.single_step) (th);
956 else
957 error ("Single stepping is not supported "
958 "in this configuration.\n");
959 }
34b34921 960
9c6c8194 961 win32_set_thread_context (th);
b80864fb
DJ
962 th->context.ContextFlags = 0;
963 }
964 }
965
966 /* Allow continuing with the same signal that interrupted us.
967 Otherwise complain. */
968
969 child_continue (continue_status, tid);
970}
971
255e7678
DJ
972static void
973win32_add_one_solib (const char *name, CORE_ADDR load_addr)
974{
975 char buf[MAX_PATH + 1];
976 char buf2[MAX_PATH + 1];
977
978#ifdef _WIN32_WCE
979 WIN32_FIND_DATA w32_fd;
980 WCHAR wname[MAX_PATH + 1];
981 mbstowcs (wname, name, MAX_PATH);
982 HANDLE h = FindFirstFile (wname, &w32_fd);
983#else
984 WIN32_FIND_DATAA w32_fd;
985 HANDLE h = FindFirstFileA (name, &w32_fd);
986#endif
987
850a0f76
JB
988 /* The symbols in a dll are offset by 0x1000, which is the
989 offset from 0 of the first byte in an image - because
990 of the file header and the section alignment. */
991 load_addr += 0x1000;
992
255e7678
DJ
993 if (h == INVALID_HANDLE_VALUE)
994 strcpy (buf, name);
995 else
996 {
997 FindClose (h);
998 strcpy (buf, name);
999#ifndef _WIN32_WCE
1000 {
1001 char cwd[MAX_PATH + 1];
1002 char *p;
1003 if (GetCurrentDirectoryA (MAX_PATH + 1, cwd))
1004 {
1005 p = strrchr (buf, '\\');
1006 if (p)
1007 p[1] = '\0';
1008 SetCurrentDirectoryA (buf);
1009 GetFullPathNameA (w32_fd.cFileName, MAX_PATH, buf, &p);
1010 SetCurrentDirectoryA (cwd);
1011 }
1012 }
1013#endif
1014 }
1015
cf6e3471
PA
1016#ifndef _WIN32_WCE
1017 if (strcasecmp (buf, "ntdll.dll") == 0)
1018 {
1019 GetSystemDirectoryA (buf, sizeof (buf));
1020 strcat (buf, "\\ntdll.dll");
1021 }
1022#endif
1023
255e7678 1024#ifdef __CYGWIN__
81239425 1025 cygwin_conv_path (CCP_WIN_A_TO_POSIX, buf, buf2, sizeof (buf2));
255e7678
DJ
1026#else
1027 strcpy (buf2, buf);
1028#endif
1029
1030 loaded_dll (buf2, load_addr);
1031}
1032
255e7678
DJ
1033typedef BOOL (WINAPI *winapi_EnumProcessModules) (HANDLE, HMODULE *,
1034 DWORD, LPDWORD);
1035typedef BOOL (WINAPI *winapi_GetModuleInformation) (HANDLE, HMODULE,
1036 LPMODULEINFO, DWORD);
1037typedef DWORD (WINAPI *winapi_GetModuleFileNameExA) (HANDLE, HMODULE,
1038 LPSTR, DWORD);
1039
1040static winapi_EnumProcessModules win32_EnumProcessModules;
1041static winapi_GetModuleInformation win32_GetModuleInformation;
1042static winapi_GetModuleFileNameExA win32_GetModuleFileNameExA;
1043
1044static BOOL
1045load_psapi (void)
1046{
1047 static int psapi_loaded = 0;
1048 static HMODULE dll = NULL;
1049
1050 if (!psapi_loaded)
1051 {
1052 psapi_loaded = 1;
1053 dll = LoadLibrary (TEXT("psapi.dll"));
1054 if (!dll)
1055 return FALSE;
1056 win32_EnumProcessModules =
1057 GETPROCADDRESS (dll, EnumProcessModules);
1058 win32_GetModuleInformation =
1059 GETPROCADDRESS (dll, GetModuleInformation);
1060 win32_GetModuleFileNameExA =
1061 GETPROCADDRESS (dll, GetModuleFileNameExA);
1062 }
1063
1064 return (win32_EnumProcessModules != NULL
1065 && win32_GetModuleInformation != NULL
1066 && win32_GetModuleFileNameExA != NULL);
1067}
1068
379a5e2d 1069#ifndef _WIN32_WCE
649ebbca 1070
f25b3fc3
JB
1071/* Iterate over all DLLs currently mapped by our inferior, and
1072 add them to our list of solibs. */
379a5e2d
JB
1073
1074static void
f25b3fc3 1075win32_add_all_dlls (void)
379a5e2d 1076{
379a5e2d
JB
1077 size_t i;
1078 HMODULE dh_buf[1];
1079 HMODULE *DllHandle = dh_buf;
1080 DWORD cbNeeded;
1081 BOOL ok;
1082
379a5e2d
JB
1083 if (!load_psapi ())
1084 return;
1085
1086 cbNeeded = 0;
1087 ok = (*win32_EnumProcessModules) (current_process_handle,
1088 DllHandle,
1089 sizeof (HMODULE),
1090 &cbNeeded);
1091
1092 if (!ok || !cbNeeded)
1093 return;
1094
1095 DllHandle = (HMODULE *) alloca (cbNeeded);
1096 if (!DllHandle)
1097 return;
1098
1099 ok = (*win32_EnumProcessModules) (current_process_handle,
1100 DllHandle,
1101 cbNeeded,
1102 &cbNeeded);
1103 if (!ok)
1104 return;
1105
f25b3fc3 1106 for (i = 1; i < ((size_t) cbNeeded / sizeof (HMODULE)); i++)
379a5e2d
JB
1107 {
1108 MODULEINFO mi;
1109 char dll_name[MAX_PATH];
1110
1111 if (!(*win32_GetModuleInformation) (current_process_handle,
1112 DllHandle[i],
1113 &mi,
1114 sizeof (mi)))
1115 continue;
1116 if ((*win32_GetModuleFileNameExA) (current_process_handle,
1117 DllHandle[i],
1118 dll_name,
1119 MAX_PATH) == 0)
1120 continue;
850a0f76 1121 win32_add_one_solib (dll_name, (CORE_ADDR) (uintptr_t) mi.lpBaseOfDll);
379a5e2d
JB
1122 }
1123}
1124#endif
1125
255e7678
DJ
1126typedef HANDLE (WINAPI *winapi_CreateToolhelp32Snapshot) (DWORD, DWORD);
1127typedef BOOL (WINAPI *winapi_Module32First) (HANDLE, LPMODULEENTRY32);
1128typedef BOOL (WINAPI *winapi_Module32Next) (HANDLE, LPMODULEENTRY32);
1129
a816ba18 1130/* See nat/windows-nat.h. */
255e7678 1131
a816ba18
TT
1132void
1133windows_nat::handle_load_dll ()
255e7678
DJ
1134{
1135 LOAD_DLL_DEBUG_INFO *event = &current_event.u.LoadDll;
9d8679cc 1136 const char *dll_name;
255e7678 1137
d763de10
JB
1138 dll_name = get_image_name (current_process_handle,
1139 event->lpImageName, event->fUnicode);
255e7678
DJ
1140 if (!dll_name)
1141 return;
1142
850a0f76 1143 win32_add_one_solib (dll_name, (CORE_ADDR) (uintptr_t) event->lpBaseOfDll);
255e7678
DJ
1144}
1145
a816ba18 1146/* See nat/windows-nat.h. */
f25b3fc3 1147
a816ba18
TT
1148void
1149windows_nat::handle_unload_dll ()
255e7678
DJ
1150{
1151 CORE_ADDR load_addr =
e8f0053d 1152 (CORE_ADDR) (uintptr_t) current_event.u.UnloadDll.lpBaseOfDll;
850a0f76
JB
1153
1154 /* The symbols in a dll are offset by 0x1000, which is the
1155 offset from 0 of the first byte in an image - because
1156 of the file header and the section alignment. */
255e7678
DJ
1157 load_addr += 0x1000;
1158 unloaded_dll (NULL, load_addr);
1159}
1160
34b34921 1161static void
9c80ecd6 1162suspend_one_thread (thread_info *thread)
4d5d1aaa 1163{
e56f8ccb 1164 windows_thread_info *th = (windows_thread_info *) thread_target_data (thread);
4d5d1aaa 1165
98a03287 1166 th->suspend ();
4d5d1aaa
PA
1167}
1168
1169static void
1170fake_breakpoint_event (void)
b80864fb 1171{
4d5d1aaa 1172 OUTMSG2(("fake_breakpoint_event\n"));
b80864fb 1173
4d5d1aaa
PA
1174 faked_breakpoint = 1;
1175
1176 memset (&current_event, 0, sizeof (current_event));
1177 current_event.dwThreadId = main_thread_id;
1178 current_event.dwDebugEventCode = EXCEPTION_DEBUG_EVENT;
1179 current_event.u.Exception.ExceptionRecord.ExceptionCode
1180 = EXCEPTION_BREAKPOINT;
1181
f0045347 1182 for_each_thread (suspend_one_thread);
4d5d1aaa
PA
1183}
1184
b65d95c5
DJ
1185#ifdef _WIN32_WCE
1186static int
1187auto_delete_breakpoint (CORE_ADDR stop_pc)
1188{
1189 return 1;
1190}
1191#endif
1192
8d30e395
TT
1193/* See nat/windows-nat.h. */
1194
1195bool
1196windows_nat::handle_ms_vc_exception (const EXCEPTION_RECORD *rec)
1197{
1198 return false;
1199}
1200
a010605f
TT
1201/* See nat/windows-nat.h. */
1202
1203bool
1204windows_nat::handle_access_violation (const EXCEPTION_RECORD *rec)
1205{
1206 return false;
1207}
1208
523d4f80
TT
1209/* A helper function that will, if needed, set
1210 'stopped_at_software_breakpoint' on the thread and adjust the
1211 PC. */
1212
1213static void
1214maybe_adjust_pc ()
1215{
1216 struct regcache *regcache = get_thread_regcache (current_thread, 1);
1217 child_fetch_inferior_registers (regcache, -1);
1218
1219 windows_thread_info *th = thread_rec (current_thread_ptid (),
1220 DONT_INVALIDATE_CONTEXT);
1221 th->stopped_at_software_breakpoint = false;
1222
1223 if (current_event.dwDebugEventCode == EXCEPTION_DEBUG_EVENT
1224 && (current_event.u.Exception.ExceptionRecord.ExceptionCode
1225 == EXCEPTION_BREAKPOINT)
1226 && child_initialization_done)
1227 {
1228 th->stopped_at_software_breakpoint = true;
1229 CORE_ADDR pc = regcache_read_pc (regcache);
1230 CORE_ADDR sw_breakpoint_pc = pc - the_low_target.decr_pc_after_break;
1231 regcache_write_pc (regcache, sw_breakpoint_pc);
1232 }
1233}
1234
4d5d1aaa
PA
1235/* Get the next event from the child. */
1236
1237static int
8d30e395
TT
1238get_child_debug_event (DWORD *continue_status,
1239 struct target_waitstatus *ourstatus)
4d5d1aaa 1240{
95954743
PA
1241 ptid_t ptid;
1242
a493e3e2 1243 last_sig = GDB_SIGNAL_0;
b80864fb 1244 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
8d30e395 1245 *continue_status = DBG_CONTINUE;
b80864fb 1246
4d5d1aaa
PA
1247 /* Check if GDB sent us an interrupt request. */
1248 check_remote_input_interrupt_request ();
1249
1250 if (soft_interrupt_requested)
1251 {
1252 soft_interrupt_requested = 0;
1253 fake_breakpoint_event ();
1254 goto gotevent;
1255 }
1256
d97903b2
PA
1257#ifndef _WIN32_WCE
1258 attaching = 0;
1259#else
1260 if (attaching)
1261 {
1262 /* WinCE doesn't set an initial breakpoint automatically. To
1b3f6016
PA
1263 stop the inferior, we flush all currently pending debug
1264 events -- the thread list and the dll list are always
1265 reported immediatelly without delay, then, we suspend all
1266 threads and pretend we saw a trap at the current PC of the
1267 main thread.
1268
1269 Contrary to desktop Windows, Windows CE *does* report the dll
1270 names on LOAD_DLL_DEBUG_EVENTs resulting from a
1271 DebugActiveProcess call. This limits the way we can detect
1272 if all the dlls have already been reported. If we get a real
1273 debug event before leaving attaching, the worst that will
1274 happen is the user will see a spurious breakpoint. */
d97903b2
PA
1275
1276 current_event.dwDebugEventCode = 0;
2c1d95e8 1277 if (!wait_for_debug_event (&current_event, 0))
1b3f6016
PA
1278 {
1279 OUTMSG2(("no attach events left\n"));
1280 fake_breakpoint_event ();
1281 attaching = 0;
1282 }
d97903b2 1283 else
1b3f6016 1284 OUTMSG2(("got attach event\n"));
d97903b2
PA
1285 }
1286 else
1287#endif
1288 {
360ad8b3
TT
1289 gdb::optional<pending_stop> stop = fetch_pending_stop (debug_threads);
1290 if (stop.has_value ())
1291 {
1292 *ourstatus = stop->status;
1293 current_event = stop->event;
1294 ptid = debug_event_ptid (&current_event);
1295 current_thread = find_thread_ptid (ptid);
1296 return 1;
1297 }
1298
30baf67b 1299 /* Keep the wait time low enough for comfortable remote
1b3f6016
PA
1300 interruption, but high enough so gdbserver doesn't become a
1301 bottleneck. */
2c1d95e8 1302 if (!wait_for_debug_event (&current_event, 250))
912cf4ba
PA
1303 {
1304 DWORD e = GetLastError();
1305
1306 if (e == ERROR_PIPE_NOT_CONNECTED)
1307 {
1308 /* This will happen if the loader fails to succesfully
1309 load the application, e.g., if the main executable
1310 tries to pull in a non-existing export from a
1311 DLL. */
1312 ourstatus->kind = TARGET_WAITKIND_EXITED;
1313 ourstatus->value.integer = 1;
1314 return 1;
1315 }
1316
1317 return 0;
1318 }
d97903b2 1319 }
4d5d1aaa
PA
1320
1321 gotevent:
b80864fb 1322
34b34921 1323 switch (current_event.dwDebugEventCode)
b80864fb
DJ
1324 {
1325 case CREATE_THREAD_DEBUG_EVENT:
1326 OUTMSG2 (("gdbserver: kernel event CREATE_THREAD_DEBUG_EVENT "
dfe07582 1327 "for pid=%u tid=%x)\n",
b80864fb
DJ
1328 (unsigned) current_event.dwProcessId,
1329 (unsigned) current_event.dwThreadId));
1330
1331 /* Record the existence of this thread. */
95954743
PA
1332 child_add_thread (current_event.dwProcessId,
1333 current_event.dwThreadId,
711e434b
PM
1334 current_event.u.CreateThread.hThread,
1335 current_event.u.CreateThread.lpThreadLocalBase);
b80864fb
DJ
1336 break;
1337
1338 case EXIT_THREAD_DEBUG_EVENT:
1339 OUTMSG2 (("gdbserver: kernel event EXIT_THREAD_DEBUG_EVENT "
dfe07582 1340 "for pid=%u tid=%x\n",
b80864fb
DJ
1341 (unsigned) current_event.dwProcessId,
1342 (unsigned) current_event.dwThreadId));
95954743
PA
1343 child_delete_thread (current_event.dwProcessId,
1344 current_event.dwThreadId);
aeeb81d1 1345
9c80ecd6 1346 current_thread = get_first_thread ();
aeeb81d1 1347 return 1;
b80864fb
DJ
1348
1349 case CREATE_PROCESS_DEBUG_EVENT:
1350 OUTMSG2 (("gdbserver: kernel event CREATE_PROCESS_DEBUG_EVENT "
dfe07582 1351 "for pid=%u tid=%x\n",
b80864fb
DJ
1352 (unsigned) current_event.dwProcessId,
1353 (unsigned) current_event.dwThreadId));
1354 CloseHandle (current_event.u.CreateProcessInfo.hFile);
1355
1356 current_process_handle = current_event.u.CreateProcessInfo.hProcess;
1357 main_thread_id = current_event.dwThreadId;
1358
b80864fb 1359 /* Add the main thread. */
95954743
PA
1360 child_add_thread (current_event.dwProcessId,
1361 main_thread_id,
711e434b
PM
1362 current_event.u.CreateProcessInfo.hThread,
1363 current_event.u.CreateProcessInfo.lpThreadLocalBase);
b80864fb 1364
ed50f18f 1365#ifdef _WIN32_WCE
d97903b2
PA
1366 if (!attaching)
1367 {
1368 /* Windows CE doesn't set the initial breakpoint
1369 automatically like the desktop versions of Windows do.
1370 We add it explicitly here. It will be removed as soon as
1371 it is hit. */
1372 set_breakpoint_at ((CORE_ADDR) (long) current_event.u
1373 .CreateProcessInfo.lpStartAddress,
b65d95c5 1374 auto_delete_breakpoint);
d97903b2 1375 }
ed50f18f 1376#endif
b80864fb
DJ
1377 break;
1378
1379 case EXIT_PROCESS_DEBUG_EVENT:
1380 OUTMSG2 (("gdbserver: kernel event EXIT_PROCESS_DEBUG_EVENT "
dfe07582 1381 "for pid=%u tid=%x\n",
b80864fb
DJ
1382 (unsigned) current_event.dwProcessId,
1383 (unsigned) current_event.dwThreadId));
559e7e50
EZ
1384 {
1385 DWORD exit_status = current_event.u.ExitProcess.dwExitCode;
1386 /* If the exit status looks like a fatal exception, but we
1387 don't recognize the exception's code, make the original
1388 exit status value available, to avoid losing information. */
1389 int exit_signal
1390 = WIFSIGNALED (exit_status) ? WTERMSIG (exit_status) : -1;
1391 if (exit_signal == -1)
1392 {
1393 ourstatus->kind = TARGET_WAITKIND_EXITED;
1394 ourstatus->value.integer = exit_status;
1395 }
1396 else
1397 {
1398 ourstatus->kind = TARGET_WAITKIND_SIGNALLED;
1399 ourstatus->value.sig = gdb_signal_from_host (exit_signal);
1400 }
1401 }
360ad8b3 1402 child_continue (DBG_CONTINUE, desired_stop_thread_id);
b80864fb 1403 CloseHandle (current_process_handle);
9d606399 1404 current_process_handle = NULL;
b80864fb
DJ
1405 break;
1406
1407 case LOAD_DLL_DEBUG_EVENT:
1408 OUTMSG2 (("gdbserver: kernel event LOAD_DLL_DEBUG_EVENT "
dfe07582 1409 "for pid=%u tid=%x\n",
b80864fb
DJ
1410 (unsigned) current_event.dwProcessId,
1411 (unsigned) current_event.dwThreadId));
1412 CloseHandle (current_event.u.LoadDll.hFile);
f25b3fc3
JB
1413 if (! child_initialization_done)
1414 break;
255e7678 1415 handle_load_dll ();
b80864fb
DJ
1416
1417 ourstatus->kind = TARGET_WAITKIND_LOADED;
a493e3e2 1418 ourstatus->value.sig = GDB_SIGNAL_TRAP;
b80864fb
DJ
1419 break;
1420
1421 case UNLOAD_DLL_DEBUG_EVENT:
1422 OUTMSG2 (("gdbserver: kernel event UNLOAD_DLL_DEBUG_EVENT "
dfe07582 1423 "for pid=%u tid=%x\n",
b80864fb
DJ
1424 (unsigned) current_event.dwProcessId,
1425 (unsigned) current_event.dwThreadId));
f25b3fc3
JB
1426 if (! child_initialization_done)
1427 break;
255e7678
DJ
1428 handle_unload_dll ();
1429 ourstatus->kind = TARGET_WAITKIND_LOADED;
a493e3e2 1430 ourstatus->value.sig = GDB_SIGNAL_TRAP;
b80864fb
DJ
1431 break;
1432
1433 case EXCEPTION_DEBUG_EVENT:
1434 OUTMSG2 (("gdbserver: kernel event EXCEPTION_DEBUG_EVENT "
dfe07582 1435 "for pid=%u tid=%x\n",
b80864fb
DJ
1436 (unsigned) current_event.dwProcessId,
1437 (unsigned) current_event.dwThreadId));
8d30e395
TT
1438 if (handle_exception (ourstatus, debug_threads)
1439 == HANDLE_EXCEPTION_UNHANDLED)
1440 *continue_status = DBG_EXCEPTION_NOT_HANDLED;
b80864fb
DJ
1441 break;
1442
1443 case OUTPUT_DEBUG_STRING_EVENT:
1444 /* A message from the kernel (or Cygwin). */
1445 OUTMSG2 (("gdbserver: kernel event OUTPUT_DEBUG_STRING_EVENT "
dfe07582 1446 "for pid=%u tid=%x\n",
b80864fb
DJ
1447 (unsigned) current_event.dwProcessId,
1448 (unsigned) current_event.dwThreadId));
d41b524f 1449 handle_output_debug_string (nullptr);
b80864fb
DJ
1450 break;
1451
1452 default:
1453 OUTMSG2 (("gdbserver: kernel event unknown "
dfe07582 1454 "for pid=%u tid=%x code=%x\n",
b80864fb
DJ
1455 (unsigned) current_event.dwProcessId,
1456 (unsigned) current_event.dwThreadId,
dfe07582 1457 (unsigned) current_event.dwDebugEventCode));
b80864fb
DJ
1458 break;
1459 }
1460
aeeb81d1 1461 ptid = debug_event_ptid (&current_event);
360ad8b3
TT
1462
1463 if (desired_stop_thread_id != -1 && desired_stop_thread_id != ptid.lwp ())
1464 {
1465 /* Pending stop. See the comment by the definition of
1466 "pending_stops" for details on why this is needed. */
1467 OUTMSG2 (("get_windows_debug_event - "
e2275c6e 1468 "unexpected stop in 0x%lx (expecting 0x%x)\n",
360ad8b3
TT
1469 ptid.lwp (), desired_stop_thread_id));
1470 maybe_adjust_pc ();
1471 pending_stops.push_back ({(DWORD) ptid.lwp (), *ourstatus, current_event});
1472 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
1473 }
1474 else
1475 current_thread = find_thread_ptid (ptid);
1476
4d5d1aaa 1477 return 1;
b80864fb
DJ
1478}
1479
1480/* Wait for the inferior process to change state.
1481 STATUS will be filled in with a response code to send to GDB.
1482 Returns the signal which caused the process to stop. */
6532e7e3
TBA
1483ptid_t
1484win32_process_target::wait (ptid_t ptid, target_waitstatus *ourstatus,
1485 int options)
b80864fb 1486{
4210d83e
PA
1487 if (cached_status.kind != TARGET_WAITKIND_IGNORE)
1488 {
1489 /* The core always does a wait after creating the inferior, and
1490 do_initial_child_stuff already ran the inferior to the
1491 initial breakpoint (or an exit, if creating the process
1492 fails). Report it now. */
1493 *ourstatus = cached_status;
1494 cached_status.kind = TARGET_WAITKIND_IGNORE;
1495 return debug_event_ptid (&current_event);
1496 }
1497
b80864fb
DJ
1498 while (1)
1499 {
8d30e395
TT
1500 DWORD continue_status;
1501 if (!get_child_debug_event (&continue_status, ourstatus))
4d5d1aaa 1502 continue;
b80864fb 1503
5b1c542e 1504 switch (ourstatus->kind)
b80864fb 1505 {
34b34921 1506 case TARGET_WAITKIND_EXITED:
b80864fb 1507 OUTMSG2 (("Child exited with retcode = %x\n",
5b1c542e 1508 ourstatus->value.integer));
5ac588cf 1509 win32_clear_inferiors ();
f2907e49 1510 return ptid_t (current_event.dwProcessId);
34b34921 1511 case TARGET_WAITKIND_STOPPED:
559e7e50 1512 case TARGET_WAITKIND_SIGNALLED:
1b3f6016 1513 case TARGET_WAITKIND_LOADED:
523d4f80
TT
1514 {
1515 OUTMSG2 (("Child Stopped with signal = %d \n",
1516 ourstatus->value.sig));
1517 maybe_adjust_pc ();
1518 return debug_event_ptid (&current_event);
1519 }
1b3f6016 1520 default:
5b1c542e 1521 OUTMSG (("Ignoring unknown internal event, %d\n", ourstatus->kind));
1b3f6016
PA
1522 /* fall-through */
1523 case TARGET_WAITKIND_SPURIOUS:
34b34921 1524 /* do nothing, just continue */
360ad8b3 1525 child_continue (continue_status, desired_stop_thread_id);
34b34921 1526 break;
b80864fb 1527 }
b80864fb
DJ
1528 }
1529}
1530
1531/* Fetch registers from the inferior process.
1532 If REGNO is -1, fetch all registers; otherwise, fetch at least REGNO. */
a5a4d4cd
TBA
1533void
1534win32_process_target::fetch_registers (regcache *regcache, int regno)
b80864fb 1535{
442ea881 1536 child_fetch_inferior_registers (regcache, regno);
b80864fb
DJ
1537}
1538
1539/* Store registers to the inferior process.
1540 If REGNO is -1, store all registers; otherwise, store at least REGNO. */
a5a4d4cd
TBA
1541void
1542win32_process_target::store_registers (regcache *regcache, int regno)
b80864fb 1543{
442ea881 1544 child_store_inferior_registers (regcache, regno);
b80864fb
DJ
1545}
1546
1547/* Read memory from the inferior process. This should generally be
1548 called through read_inferior_memory, which handles breakpoint shadowing.
1549 Read LEN bytes at MEMADDR into a buffer at MYADDR. */
e2558df3
TBA
1550int
1551win32_process_target::read_memory (CORE_ADDR memaddr, unsigned char *myaddr,
1552 int len)
b80864fb 1553{
ed50f18f 1554 return child_xfer_memory (memaddr, (char *) myaddr, len, 0, 0) != len;
b80864fb
DJ
1555}
1556
1557/* Write memory to the inferior process. This should generally be
1558 called through write_inferior_memory, which handles breakpoint shadowing.
1559 Write LEN bytes from the buffer at MYADDR to MEMADDR.
1560 Returns 0 on success and errno on failure. */
e2558df3
TBA
1561int
1562win32_process_target::write_memory (CORE_ADDR memaddr,
1563 const unsigned char *myaddr, int len)
b80864fb
DJ
1564{
1565 return child_xfer_memory (memaddr, (char *) myaddr, len, 1, 0) != len;
1566}
1567
7390519e 1568/* Send an interrupt request to the inferior process. */
eb497a2a
TBA
1569void
1570win32_process_target::request_interrupt ()
7390519e
PA
1571{
1572 winapi_DebugBreakProcess DebugBreakProcess;
1573 winapi_GenerateConsoleCtrlEvent GenerateConsoleCtrlEvent;
1574
1575#ifdef _WIN32_WCE
1576 HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
1577#else
1578 HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
1579#endif
1580
1581 GenerateConsoleCtrlEvent = GETPROCADDRESS (dll, GenerateConsoleCtrlEvent);
1582
1583 if (GenerateConsoleCtrlEvent != NULL
1584 && GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, current_process_id))
1585 return;
1586
1587 /* GenerateConsoleCtrlEvent can fail if process id being debugged is
1588 not a process group id.
1589 Fallback to XP/Vista 'DebugBreakProcess', which generates a
1590 breakpoint exception in the interior process. */
1591
1592 DebugBreakProcess = GETPROCADDRESS (dll, DebugBreakProcess);
1593
1594 if (DebugBreakProcess != NULL
1595 && DebugBreakProcess (current_process_handle))
1596 return;
1597
4d5d1aaa
PA
1598 /* Last resort, suspend all threads manually. */
1599 soft_interrupt_requested = 1;
7390519e
PA
1600}
1601
22aa6223
TBA
1602bool
1603win32_process_target::supports_hardware_single_step ()
1604{
1605 return true;
1606}
1607
59a016f0
PA
1608#ifdef _WIN32_WCE
1609int
1610win32_error_to_fileio_error (DWORD err)
1611{
1612 switch (err)
1613 {
1614 case ERROR_BAD_PATHNAME:
1615 case ERROR_FILE_NOT_FOUND:
1616 case ERROR_INVALID_NAME:
1617 case ERROR_PATH_NOT_FOUND:
1618 return FILEIO_ENOENT;
1619 case ERROR_CRC:
1620 case ERROR_IO_DEVICE:
1621 case ERROR_OPEN_FAILED:
1622 return FILEIO_EIO;
1623 case ERROR_INVALID_HANDLE:
1624 return FILEIO_EBADF;
1625 case ERROR_ACCESS_DENIED:
1626 case ERROR_SHARING_VIOLATION:
1627 return FILEIO_EACCES;
1628 case ERROR_NOACCESS:
1629 return FILEIO_EFAULT;
1630 case ERROR_BUSY:
1631 return FILEIO_EBUSY;
1632 case ERROR_ALREADY_EXISTS:
1633 case ERROR_FILE_EXISTS:
1634 return FILEIO_EEXIST;
1635 case ERROR_BAD_DEVICE:
1636 return FILEIO_ENODEV;
1637 case ERROR_DIRECTORY:
1638 return FILEIO_ENOTDIR;
1639 case ERROR_FILENAME_EXCED_RANGE:
1640 case ERROR_INVALID_DATA:
1641 case ERROR_INVALID_PARAMETER:
1642 case ERROR_NEGATIVE_SEEK:
1643 return FILEIO_EINVAL;
1644 case ERROR_TOO_MANY_OPEN_FILES:
1645 return FILEIO_EMFILE;
1646 case ERROR_HANDLE_DISK_FULL:
1647 case ERROR_DISK_FULL:
1648 return FILEIO_ENOSPC;
1649 case ERROR_WRITE_PROTECT:
1650 return FILEIO_EROFS;
1651 case ERROR_NOT_SUPPORTED:
1652 return FILEIO_ENOSYS;
1653 }
1654
1655 return FILEIO_EUNKNOWN;
1656}
1657
ea06bbaa
TBA
1658void
1659win32_process_target::hostio_last_error (char *buf)
59a016f0
PA
1660{
1661 DWORD winerr = GetLastError ();
1662 int fileio_err = win32_error_to_fileio_error (winerr);
1663 sprintf (buf, "F-1,%x", fileio_err);
1664}
1665#endif
1666
d7abedf7
TBA
1667bool
1668win32_process_target::supports_qxfer_siginfo ()
1669{
1670 return true;
1671}
1672
7928d571
HD
1673/* Write Windows signal info. */
1674
d7abedf7
TBA
1675int
1676win32_process_target::qxfer_siginfo (const char *annex,
1677 unsigned char *readbuf,
1678 unsigned const char *writebuf,
1679 CORE_ADDR offset, int len)
7928d571
HD
1680{
1681 if (siginfo_er.ExceptionCode == 0)
1682 return -1;
1683
1684 if (readbuf == nullptr)
1685 return -1;
1686
1687 if (offset > sizeof (siginfo_er))
1688 return -1;
1689
1690 if (offset + len > sizeof (siginfo_er))
1691 len = sizeof (siginfo_er) - offset;
1692
1693 memcpy (readbuf, (char *) &siginfo_er + offset, len);
1694
1695 return len;
1696}
1697
4e2e869c
TBA
1698bool
1699win32_process_target::supports_get_tib_address ()
1700{
1701 return true;
1702}
1703
711e434b
PM
1704/* Write Windows OS Thread Information Block address. */
1705
4e2e869c
TBA
1706int
1707win32_process_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
711e434b 1708{
e56f8ccb 1709 windows_thread_info *th;
28688adf 1710 th = thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
711e434b
PM
1711 if (th == NULL)
1712 return 0;
1713 if (addr != NULL)
1714 *addr = th->thread_local_base;
1715 return 1;
1716}
1717
fb78e89c
AT
1718/* Implementation of the target_ops method "sw_breakpoint_from_kind". */
1719
d367006f
TBA
1720const gdb_byte *
1721win32_process_target::sw_breakpoint_from_kind (int kind, int *size)
fb78e89c
AT
1722{
1723 *size = the_low_target.breakpoint_len;
1724 return the_low_target.breakpoint;
1725}
1726
523d4f80
TT
1727bool
1728win32_process_target::stopped_by_sw_breakpoint ()
1729{
1730 windows_thread_info *th = thread_rec (current_thread_ptid (),
1731 DONT_INVALIDATE_CONTEXT);
1732 return th == nullptr ? false : th->stopped_at_software_breakpoint;
1733}
1734
1735bool
1736win32_process_target::supports_stopped_by_sw_breakpoint ()
1737{
1738 return true;
1739}
1740
d6225aff
TT
1741CORE_ADDR
1742win32_process_target::read_pc (struct regcache *regcache)
1743{
1744 return (*the_low_target.get_pc) (regcache);
1745}
1746
1747void
1748win32_process_target::write_pc (struct regcache *regcache, CORE_ADDR pc)
1749{
1750 return (*the_low_target.set_pc) (regcache, pc);
1751}
1752
5ef9273d
TBA
1753/* The win32 target ops object. */
1754
1755static win32_process_target the_win32_target;
1756
b80864fb
DJ
1757/* Initialize the Win32 backend. */
1758void
1759initialize_low (void)
1760{
52405d85 1761 set_target_ops (&the_win32_target);
d05b4ac3 1762 the_low_target.arch_setup ();
b80864fb 1763}
This page took 1.223439 seconds and 4 git commands to generate.