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