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