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