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