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