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