* config/i386/mingw.mh, config/i386/mingw.mt: New files.
[deliverable/binutils-gdb.git] / gdb / windows-nat.c
1 /* Target-vector operations for controlling win32 child processes, for GDB.
2
3 Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 2005, 2006, 2007 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 #ifdef __CYGWIN__
42 #include <sys/cygwin.h>
43 #endif
44 #include <signal.h>
45
46 #include "buildsym.h"
47 #include "symfile.h"
48 #include "objfiles.h"
49 #include "gdb_obstack.h"
50 #include "gdb_string.h"
51 #include "gdbthread.h"
52 #include "gdbcmd.h"
53 #include <sys/param.h>
54 #include <unistd.h>
55 #include "exec.h"
56 #include "solist.h"
57 #include "solib.h"
58 #include "xml-support.h"
59
60 #include "i386-tdep.h"
61 #include "i387-tdep.h"
62
63 #include "i386-cygwin-tdep.h"
64
65 static struct target_ops win32_ops;
66
67 #ifdef __CYGWIN__
68 /* The starting and ending address of the cygwin1.dll text segment. */
69 static bfd_vma cygwin_load_start;
70 static bfd_vma cygwin_load_end;
71 #endif
72
73 static int have_saved_context; /* True if we've saved context from a cygwin signal. */
74 static CONTEXT saved_context; /* Containes the saved context from a cygwin signal. */
75
76 /* If we're not using the old Cygwin header file set, define the
77 following which never should have been in the generic Win32 API
78 headers in the first place since they were our own invention... */
79 #ifndef _GNU_H_WINDOWS_H
80 enum
81 {
82 FLAG_TRACE_BIT = 0x100,
83 CONTEXT_DEBUGGER = (CONTEXT_FULL | CONTEXT_FLOATING_POINT)
84 };
85 #endif
86 #include <psapi.h>
87
88 #define CONTEXT_DEBUGGER_DR CONTEXT_DEBUGGER | CONTEXT_DEBUG_REGISTERS \
89 | CONTEXT_EXTENDED_REGISTERS
90
91 static unsigned dr[8];
92 static int debug_registers_changed;
93 static int debug_registers_used;
94
95 /* The string sent by cygwin when it processes a signal.
96 FIXME: This should be in a cygwin include file. */
97 #ifndef _CYGWIN_SIGNAL_STRING
98 #define _CYGWIN_SIGNAL_STRING "cYgSiGw00f"
99 #endif
100
101 #define CHECK(x) check (x, __FILE__,__LINE__)
102 #define DEBUG_EXEC(x) if (debug_exec) printf_unfiltered x
103 #define DEBUG_EVENTS(x) if (debug_events) printf_unfiltered x
104 #define DEBUG_MEM(x) if (debug_memory) printf_unfiltered x
105 #define DEBUG_EXCEPT(x) if (debug_exceptions) printf_unfiltered x
106
107 static void win32_stop (void);
108 static int win32_win32_thread_alive (ptid_t);
109 static void win32_kill_inferior (void);
110
111 static enum target_signal last_sig = TARGET_SIGNAL_0;
112 /* Set if a signal was received from the debugged process */
113
114 /* Thread information structure used to track information that is
115 not available in gdb's thread structure. */
116 typedef struct thread_info_struct
117 {
118 struct thread_info_struct *next;
119 DWORD id;
120 HANDLE h;
121 char *name;
122 int suspend_count;
123 int reload_context;
124 CONTEXT context;
125 STACKFRAME sf;
126 }
127 thread_info;
128
129 static thread_info thread_head;
130
131 /* The process and thread handles for the above context. */
132
133 static DEBUG_EVENT current_event; /* The current debug event from
134 WaitForDebugEvent */
135 static HANDLE current_process_handle; /* Currently executing process */
136 static thread_info *current_thread; /* Info on currently selected thread */
137 static DWORD main_thread_id; /* Thread ID of the main thread */
138
139 /* Counts of things. */
140 static int exception_count = 0;
141 static int event_count = 0;
142 static int saw_create;
143
144 /* User options. */
145 static int new_console = 0;
146 #ifdef __CYGWIN__
147 static int cygwin_exceptions = 0;
148 #endif
149 static int new_group = 1;
150 static int debug_exec = 0; /* show execution */
151 static int debug_events = 0; /* show events from kernel */
152 static int debug_memory = 0; /* show target memory accesses */
153 static int debug_exceptions = 0; /* show target exceptions */
154 static int useshell = 0; /* use shell for subprocesses */
155
156 /* This vector maps GDB's idea of a register's number into an address
157 in the win32 exception context vector.
158
159 It also contains the bit mask needed to load the register in question.
160
161 One day we could read a reg, we could inspect the context we
162 already have loaded, if it doesn't have the bit set that we need,
163 we read that set of registers in using GetThreadContext. If the
164 context already contains what we need, we just unpack it. Then to
165 write a register, first we have to ensure that the context contains
166 the other regs of the group, and then we copy the info in and set
167 out bit. */
168
169 #define context_offset(x) ((int)&(((CONTEXT *)NULL)->x))
170 static const int mappings[] =
171 {
172 context_offset (Eax),
173 context_offset (Ecx),
174 context_offset (Edx),
175 context_offset (Ebx),
176 context_offset (Esp),
177 context_offset (Ebp),
178 context_offset (Esi),
179 context_offset (Edi),
180 context_offset (Eip),
181 context_offset (EFlags),
182 context_offset (SegCs),
183 context_offset (SegSs),
184 context_offset (SegDs),
185 context_offset (SegEs),
186 context_offset (SegFs),
187 context_offset (SegGs),
188 context_offset (FloatSave.RegisterArea[0 * 10]),
189 context_offset (FloatSave.RegisterArea[1 * 10]),
190 context_offset (FloatSave.RegisterArea[2 * 10]),
191 context_offset (FloatSave.RegisterArea[3 * 10]),
192 context_offset (FloatSave.RegisterArea[4 * 10]),
193 context_offset (FloatSave.RegisterArea[5 * 10]),
194 context_offset (FloatSave.RegisterArea[6 * 10]),
195 context_offset (FloatSave.RegisterArea[7 * 10]),
196 context_offset (FloatSave.ControlWord),
197 context_offset (FloatSave.StatusWord),
198 context_offset (FloatSave.TagWord),
199 context_offset (FloatSave.ErrorSelector),
200 context_offset (FloatSave.ErrorOffset),
201 context_offset (FloatSave.DataSelector),
202 context_offset (FloatSave.DataOffset),
203 context_offset (FloatSave.ErrorSelector)
204 /* XMM0-7 */ ,
205 context_offset (ExtendedRegisters[10*16]),
206 context_offset (ExtendedRegisters[11*16]),
207 context_offset (ExtendedRegisters[12*16]),
208 context_offset (ExtendedRegisters[13*16]),
209 context_offset (ExtendedRegisters[14*16]),
210 context_offset (ExtendedRegisters[15*16]),
211 context_offset (ExtendedRegisters[16*16]),
212 context_offset (ExtendedRegisters[17*16]),
213 /* MXCSR */
214 context_offset (ExtendedRegisters[24])
215 };
216
217 #undef context_offset
218
219 /* This vector maps the target's idea of an exception (extracted
220 from the DEBUG_EVENT structure) to GDB's idea. */
221
222 struct xlate_exception
223 {
224 int them;
225 enum target_signal us;
226 };
227
228 static const struct xlate_exception
229 xlate[] =
230 {
231 {EXCEPTION_ACCESS_VIOLATION, TARGET_SIGNAL_SEGV},
232 {STATUS_STACK_OVERFLOW, TARGET_SIGNAL_SEGV},
233 {EXCEPTION_BREAKPOINT, TARGET_SIGNAL_TRAP},
234 {DBG_CONTROL_C, TARGET_SIGNAL_INT},
235 {EXCEPTION_SINGLE_STEP, TARGET_SIGNAL_TRAP},
236 {STATUS_FLOAT_DIVIDE_BY_ZERO, TARGET_SIGNAL_FPE},
237 {-1, -1}};
238
239 static void
240 check (BOOL ok, const char *file, int line)
241 {
242 if (!ok)
243 printf_filtered ("error return %s:%d was %lu\n", file, line,
244 GetLastError ());
245 }
246
247 /* Find a thread record given a thread id.
248 If get_context then also retrieve the context for this
249 thread. */
250 static thread_info *
251 thread_rec (DWORD id, int get_context)
252 {
253 thread_info *th;
254
255 for (th = &thread_head; (th = th->next) != NULL;)
256 if (th->id == id)
257 {
258 if (!th->suspend_count && get_context)
259 {
260 if (get_context > 0 && id != current_event.dwThreadId)
261 th->suspend_count = SuspendThread (th->h) + 1;
262 else if (get_context < 0)
263 th->suspend_count = -1;
264 th->reload_context = 1;
265 }
266 return th;
267 }
268
269 return NULL;
270 }
271
272 /* Add a thread to the thread list */
273 static thread_info *
274 win32_add_thread (DWORD id, HANDLE h)
275 {
276 thread_info *th;
277
278 if ((th = thread_rec (id, FALSE)))
279 return th;
280
281 th = XZALLOC (thread_info);
282 th->id = id;
283 th->h = h;
284 th->next = thread_head.next;
285 thread_head.next = th;
286 add_thread (pid_to_ptid (id));
287 /* Set the debug registers for the new thread in they are used. */
288 if (debug_registers_used)
289 {
290 /* Only change the value of the debug registers. */
291 th->context.ContextFlags = CONTEXT_DEBUG_REGISTERS;
292 CHECK (GetThreadContext (th->h, &th->context));
293 th->context.Dr0 = dr[0];
294 th->context.Dr1 = dr[1];
295 th->context.Dr2 = dr[2];
296 th->context.Dr3 = dr[3];
297 /* th->context.Dr6 = dr[6];
298 FIXME: should we set dr6 also ?? */
299 th->context.Dr7 = dr[7];
300 CHECK (SetThreadContext (th->h, &th->context));
301 th->context.ContextFlags = 0;
302 }
303 return th;
304 }
305
306 /* Clear out any old thread list and reintialize it to a
307 pristine state. */
308 static void
309 win32_init_thread_list (void)
310 {
311 thread_info *th = &thread_head;
312
313 DEBUG_EVENTS (("gdb: win32_init_thread_list\n"));
314 init_thread_list ();
315 while (th->next != NULL)
316 {
317 thread_info *here = th->next;
318 th->next = here->next;
319 (void) CloseHandle (here->h);
320 xfree (here);
321 }
322 thread_head.next = NULL;
323 }
324
325 /* Delete a thread from the list of threads */
326 static void
327 win32_delete_thread (DWORD id)
328 {
329 thread_info *th;
330
331 if (info_verbose)
332 printf_unfiltered ("[Deleting %s]\n", target_pid_to_str (pid_to_ptid (id)));
333 delete_thread (pid_to_ptid (id));
334
335 for (th = &thread_head;
336 th->next != NULL && th->next->id != id;
337 th = th->next)
338 continue;
339
340 if (th->next != NULL)
341 {
342 thread_info *here = th->next;
343 th->next = here->next;
344 CloseHandle (here->h);
345 xfree (here);
346 }
347 }
348
349 static void
350 do_win32_fetch_inferior_registers (struct regcache *regcache, int r)
351 {
352 char *context_offset = ((char *) &current_thread->context) + mappings[r];
353 long l;
354
355 if (!current_thread)
356 return; /* Windows sometimes uses a non-existent thread id in its
357 events */
358
359 if (current_thread->reload_context)
360 {
361 #ifdef __COPY_CONTEXT_SIZE
362 if (have_saved_context)
363 {
364 /* Lie about where the program actually is stopped since cygwin has informed us that
365 we should consider the signal to have occurred at another location which is stored
366 in "saved_context. */
367 memcpy (&current_thread->context, &saved_context, __COPY_CONTEXT_SIZE);
368 have_saved_context = 0;
369 }
370 else
371 #endif
372 {
373 thread_info *th = current_thread;
374 th->context.ContextFlags = CONTEXT_DEBUGGER_DR;
375 GetThreadContext (th->h, &th->context);
376 /* Copy dr values from that thread. */
377 dr[0] = th->context.Dr0;
378 dr[1] = th->context.Dr1;
379 dr[2] = th->context.Dr2;
380 dr[3] = th->context.Dr3;
381 dr[6] = th->context.Dr6;
382 dr[7] = th->context.Dr7;
383 }
384 current_thread->reload_context = 0;
385 }
386
387 #define I387_ST0_REGNUM I386_ST0_REGNUM
388
389 if (r == I387_FISEG_REGNUM)
390 {
391 l = *((long *) context_offset) & 0xffff;
392 regcache_raw_supply (regcache, r, (char *) &l);
393 }
394 else if (r == I387_FOP_REGNUM)
395 {
396 l = (*((long *) context_offset) >> 16) & ((1 << 11) - 1);
397 regcache_raw_supply (regcache, r, (char *) &l);
398 }
399 else if (r >= 0)
400 regcache_raw_supply (regcache, r, context_offset);
401 else
402 {
403 for (r = 0; r < gdbarch_num_regs (current_gdbarch); r++)
404 do_win32_fetch_inferior_registers (regcache, r);
405 }
406
407 #undef I387_ST0_REGNUM
408 }
409
410 static void
411 win32_fetch_inferior_registers (struct regcache *regcache, int r)
412 {
413 current_thread = thread_rec (PIDGET (inferior_ptid), TRUE);
414 /* Check if current_thread exists. Windows sometimes uses a non-existent
415 thread id in its events */
416 if (current_thread)
417 do_win32_fetch_inferior_registers (regcache, r);
418 }
419
420 static void
421 do_win32_store_inferior_registers (const struct regcache *regcache, int r)
422 {
423 if (!current_thread)
424 /* Windows sometimes uses a non-existent thread id in its events */;
425 else if (r >= 0)
426 regcache_raw_collect (regcache, r,
427 ((char *) &current_thread->context) + mappings[r]);
428 else
429 {
430 for (r = 0; r < gdbarch_num_regs (current_gdbarch); r++)
431 do_win32_store_inferior_registers (regcache, r);
432 }
433 }
434
435 /* Store a new register value into the current thread context */
436 static void
437 win32_store_inferior_registers (struct regcache *regcache, int r)
438 {
439 current_thread = thread_rec (PIDGET (inferior_ptid), TRUE);
440 /* Check if current_thread exists. Windows sometimes uses a non-existent
441 thread id in its events */
442 if (current_thread)
443 do_win32_store_inferior_registers (regcache, r);
444 }
445
446 static int psapi_loaded = 0;
447 static HMODULE psapi_module_handle = NULL;
448 static BOOL WINAPI (*psapi_EnumProcessModules) (HANDLE, HMODULE *, DWORD, LPDWORD) = NULL;
449 static BOOL WINAPI (*psapi_GetModuleInformation) (HANDLE, HMODULE, LPMODULEINFO, DWORD) = NULL;
450 static DWORD WINAPI (*psapi_GetModuleFileNameExA) (HANDLE, HMODULE, LPSTR, DWORD) = NULL;
451
452 static int
453 psapi_get_dll_name (DWORD BaseAddress, char *dll_name_ret)
454 {
455 DWORD len;
456 MODULEINFO mi;
457 int i;
458 HMODULE dh_buf[1];
459 HMODULE *DllHandle = dh_buf;
460 DWORD cbNeeded;
461 BOOL ok;
462
463 if (!psapi_loaded ||
464 psapi_EnumProcessModules == NULL ||
465 psapi_GetModuleInformation == NULL ||
466 psapi_GetModuleFileNameExA == NULL)
467 {
468 if (psapi_loaded)
469 goto failed;
470 psapi_loaded = 1;
471 psapi_module_handle = LoadLibrary ("psapi.dll");
472 if (!psapi_module_handle)
473 {
474 /* printf_unfiltered ("error loading psapi.dll: %u", GetLastError ()); */
475 goto failed;
476 }
477 psapi_EnumProcessModules = GetProcAddress (psapi_module_handle, "EnumProcessModules");
478 psapi_GetModuleInformation = GetProcAddress (psapi_module_handle, "GetModuleInformation");
479 psapi_GetModuleFileNameExA = (void *) GetProcAddress (psapi_module_handle,
480 "GetModuleFileNameExA");
481 if (psapi_EnumProcessModules == NULL ||
482 psapi_GetModuleInformation == NULL ||
483 psapi_GetModuleFileNameExA == NULL)
484 goto failed;
485 }
486
487 cbNeeded = 0;
488 ok = (*psapi_EnumProcessModules) (current_process_handle,
489 DllHandle,
490 sizeof (HMODULE),
491 &cbNeeded);
492
493 if (!ok || !cbNeeded)
494 goto failed;
495
496 DllHandle = (HMODULE *) alloca (cbNeeded);
497 if (!DllHandle)
498 goto failed;
499
500 ok = (*psapi_EnumProcessModules) (current_process_handle,
501 DllHandle,
502 cbNeeded,
503 &cbNeeded);
504 if (!ok)
505 goto failed;
506
507 for (i = 0; i < (int) (cbNeeded / sizeof (HMODULE)); i++)
508 {
509 if (!(*psapi_GetModuleInformation) (current_process_handle,
510 DllHandle[i],
511 &mi,
512 sizeof (mi)))
513 error (_("Can't get module info"));
514
515 len = (*psapi_GetModuleFileNameExA) (current_process_handle,
516 DllHandle[i],
517 dll_name_ret,
518 MAX_PATH);
519 if (len == 0)
520 error (_("Error getting dll name: %u."), (unsigned) GetLastError ());
521
522 if ((DWORD) (mi.lpBaseOfDll) == BaseAddress)
523 return 1;
524 }
525
526 failed:
527 dll_name_ret[0] = '\0';
528 return 0;
529 }
530
531 /* Encapsulate the information required in a call to
532 symbol_file_add_args */
533 struct safe_symbol_file_add_args
534 {
535 char *name;
536 int from_tty;
537 struct section_addr_info *addrs;
538 int mainline;
539 int flags;
540 struct ui_file *err, *out;
541 struct objfile *ret;
542 };
543
544 /* Maintain a linked list of "so" information. */
545 struct lm_info
546 {
547 DWORD load_addr;
548 };
549
550 static struct so_list solib_start, *solib_end;
551
552 /* Call symbol_file_add with stderr redirected. We don't care if there
553 are errors. */
554 static int
555 safe_symbol_file_add_stub (void *argv)
556 {
557 #define p ((struct safe_symbol_file_add_args *) argv)
558 struct so_list *so = &solib_start;
559
560 p->ret = symbol_file_add (p->name, p->from_tty, p->addrs, p->mainline, p->flags);
561 return !!p->ret;
562 #undef p
563 }
564
565 /* Restore gdb's stderr after calling symbol_file_add */
566 static void
567 safe_symbol_file_add_cleanup (void *p)
568 {
569 #define sp ((struct safe_symbol_file_add_args *)p)
570 gdb_flush (gdb_stderr);
571 gdb_flush (gdb_stdout);
572 ui_file_delete (gdb_stderr);
573 ui_file_delete (gdb_stdout);
574 gdb_stderr = sp->err;
575 gdb_stdout = sp->out;
576 #undef sp
577 }
578
579 /* symbol_file_add wrapper that prevents errors from being displayed. */
580 static struct objfile *
581 safe_symbol_file_add (char *name, int from_tty,
582 struct section_addr_info *addrs,
583 int mainline, int flags)
584 {
585 struct safe_symbol_file_add_args p;
586 struct cleanup *cleanup;
587
588 cleanup = make_cleanup (safe_symbol_file_add_cleanup, &p);
589
590 p.err = gdb_stderr;
591 p.out = gdb_stdout;
592 gdb_flush (gdb_stderr);
593 gdb_flush (gdb_stdout);
594 gdb_stderr = ui_file_new ();
595 gdb_stdout = ui_file_new ();
596 p.name = name;
597 p.from_tty = from_tty;
598 p.addrs = addrs;
599 p.mainline = mainline;
600 p.flags = flags;
601 catch_errors (safe_symbol_file_add_stub, &p, "", RETURN_MASK_ERROR);
602
603 do_cleanups (cleanup);
604 return p.ret;
605 }
606
607 static struct so_list *
608 win32_make_so (const char *name, DWORD load_addr)
609 {
610 struct so_list *so;
611 char buf[MAX_PATH + 1];
612 char cwd[MAX_PATH + 1];
613 char *p;
614 WIN32_FIND_DATA w32_fd;
615 HANDLE h = FindFirstFile(name, &w32_fd);
616 MEMORY_BASIC_INFORMATION m;
617
618 if (h == INVALID_HANDLE_VALUE)
619 strcpy (buf, name);
620 else
621 {
622 FindClose (h);
623 strcpy (buf, name);
624 if (GetCurrentDirectory (MAX_PATH + 1, cwd))
625 {
626 p = strrchr (buf, '\\');
627 if (p)
628 p[1] = '\0';
629 SetCurrentDirectory (buf);
630 GetFullPathName (w32_fd.cFileName, MAX_PATH, buf, &p);
631 SetCurrentDirectory (cwd);
632 }
633 }
634
635 if (strcasecmp (buf, "ntdll.dll") == 0)
636 {
637 GetSystemDirectory (buf, sizeof (buf));
638 strcat (buf, "\\ntdll.dll");
639 }
640 so = XZALLOC (struct so_list);
641 so->lm_info = (struct lm_info *) xmalloc (sizeof (struct lm_info));
642 so->lm_info->load_addr = load_addr;
643 strcpy (so->so_original_name, name);
644 #ifndef __CYGWIN__
645 strcpy (so->so_name, buf);
646 #else
647 cygwin_conv_to_posix_path (buf, so->so_name);
648 /* Record cygwin1.dll .text start/end. */
649 p = strchr (so->so_name, '\0') - (sizeof ("/cygwin1.dll") - 1);
650 if (p >= so->so_name && strcasecmp (p, "/cygwin1.dll") == 0)
651 {
652 bfd *abfd;
653 asection *text = NULL;
654 CORE_ADDR text_vma;
655
656 abfd = bfd_openr (name, "pei-i386");
657
658 if (!abfd)
659 return so;
660
661 if (bfd_check_format (abfd, bfd_object))
662 text = bfd_get_section_by_name (abfd, ".text");
663
664 if (!text)
665 {
666 bfd_close (abfd);
667 return so;
668 }
669
670 /* The symbols in a dll are offset by 0x1000, which is the the
671 offset from 0 of the first byte in an image - because of the
672 file header and the section alignment. */
673 cygwin_load_start = load_addr + 0x1000;
674 cygwin_load_end = cygwin_load_start + bfd_section_size (abfd, text);
675
676 bfd_close (abfd);
677 }
678 #endif
679
680 return so;
681 }
682
683 static char *
684 get_image_name (HANDLE h, void *address, int unicode)
685 {
686 static char buf[(2 * MAX_PATH) + 1];
687 DWORD size = unicode ? sizeof (WCHAR) : sizeof (char);
688 char *address_ptr;
689 int len = 0;
690 char b[2];
691 DWORD done;
692
693 /* Attempt to read the name of the dll that was detected.
694 This is documented to work only when actively debugging
695 a program. It will not work for attached processes. */
696 if (address == NULL)
697 return NULL;
698
699 /* See if we could read the address of a string, and that the
700 address isn't null. */
701 if (!ReadProcessMemory (h, address, &address_ptr, sizeof (address_ptr), &done)
702 || done != sizeof (address_ptr) || !address_ptr)
703 return NULL;
704
705 /* Find the length of the string */
706 while (ReadProcessMemory (h, address_ptr + len++ * size, &b, size, &done)
707 && (b[0] != 0 || b[size - 1] != 0) && done == size)
708 continue;
709
710 if (!unicode)
711 ReadProcessMemory (h, address_ptr, buf, len, &done);
712 else
713 {
714 WCHAR *unicode_address = (WCHAR *) alloca (len * sizeof (WCHAR));
715 ReadProcessMemory (h, address_ptr, unicode_address, len * sizeof (WCHAR),
716 &done);
717
718 WideCharToMultiByte (CP_ACP, 0, unicode_address, len, buf, len, 0, 0);
719 }
720
721 return buf;
722 }
723
724 /* Wait for child to do something. Return pid of child, or -1 in case
725 of error; store status through argument pointer OURSTATUS. */
726 static int
727 handle_load_dll (void *dummy)
728 {
729 LOAD_DLL_DEBUG_INFO *event = &current_event.u.LoadDll;
730 char dll_buf[MAX_PATH + 1];
731 char *dll_name = NULL;
732
733 dll_buf[0] = dll_buf[sizeof (dll_buf) - 1] = '\0';
734
735 if (!psapi_get_dll_name ((DWORD) (event->lpBaseOfDll), dll_buf))
736 dll_buf[0] = dll_buf[sizeof (dll_buf) - 1] = '\0';
737
738 dll_name = dll_buf;
739
740 if (*dll_name == '\0')
741 dll_name = get_image_name (current_process_handle,
742 event->lpImageName, event->fUnicode);
743 if (!dll_name)
744 return 1;
745
746 solib_end->next = win32_make_so (dll_name, (DWORD) event->lpBaseOfDll);
747 solib_end = solib_end->next;
748
749 return 1;
750 }
751
752 static void
753 win32_free_so (struct so_list *so)
754 {
755 if (so->lm_info)
756 xfree (so->lm_info);
757 xfree (so);
758 }
759
760 static int
761 handle_unload_dll (void *dummy)
762 {
763 DWORD lpBaseOfDll = (DWORD) current_event.u.UnloadDll.lpBaseOfDll;
764 struct so_list *so;
765
766 for (so = &solib_start; so->next != NULL; so = so->next)
767 if (so->next->lm_info->load_addr == lpBaseOfDll)
768 {
769 struct so_list *sodel = so->next;
770 so->next = sodel->next;
771 if (!so->next)
772 solib_end = so;
773 win32_free_so (sodel);
774 solib_add (NULL, 0, NULL, auto_solib_add);
775 return 1;
776 }
777
778 error (_("Error: dll starting at 0x%lx not found."), (DWORD) lpBaseOfDll);
779
780 return 0;
781 }
782
783 /* Clear list of loaded DLLs. */
784 static void
785 win32_clear_solib (void)
786 {
787 solib_start.next = NULL;
788 solib_end = &solib_start;
789 }
790
791 /* Load DLL symbol info. */
792 void
793 dll_symbol_command (char *args, int from_tty)
794 {
795 int n;
796 dont_repeat ();
797
798 if (args == NULL)
799 error (_("dll-symbols requires a file name"));
800
801 n = strlen (args);
802 if (n > 4 && strcasecmp (args + n - 4, ".dll") != 0)
803 {
804 char *newargs = (char *) alloca (n + 4 + 1);
805 strcpy (newargs, args);
806 strcat (newargs, ".dll");
807 args = newargs;
808 }
809
810 safe_symbol_file_add (args, from_tty, NULL, 0, OBJF_SHARED | OBJF_USERLOADED);
811 }
812
813 /* Handle DEBUG_STRING output from child process.
814 Cygwin prepends its messages with a "cygwin:". Interpret this as
815 a Cygwin signal. Otherwise just print the string as a warning. */
816 static int
817 handle_output_debug_string (struct target_waitstatus *ourstatus)
818 {
819 char *s = NULL;
820 int retval = 0;
821
822 if (!target_read_string
823 ((CORE_ADDR) current_event.u.DebugString.lpDebugStringData, &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 0x%08lx\n", x, \
990 (DWORD) 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 bfd_vma addr = (bfd_vma) 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 0x%08lx\n",
1102 current_event.u.Exception.ExceptionRecord.ExceptionCode,
1103 (DWORD) 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 win32_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 res = ContinueDebugEvent (current_event.dwProcessId,
1126 current_event.dwThreadId,
1127 continue_status);
1128 if (res)
1129 for (th = &thread_head; (th = th->next) != NULL;)
1130 if (((id == -1) || (id == (int) th->id)) && th->suspend_count)
1131 {
1132
1133 for (i = 0; i < th->suspend_count; i++)
1134 (void) ResumeThread (th->h);
1135 th->suspend_count = 0;
1136 if (debug_registers_changed)
1137 {
1138 /* Only change the value of the debug registers */
1139 th->context.ContextFlags = CONTEXT_DEBUG_REGISTERS;
1140 th->context.Dr0 = dr[0];
1141 th->context.Dr1 = dr[1];
1142 th->context.Dr2 = dr[2];
1143 th->context.Dr3 = dr[3];
1144 /* th->context.Dr6 = dr[6];
1145 FIXME: should we set dr6 also ?? */
1146 th->context.Dr7 = dr[7];
1147 CHECK (SetThreadContext (th->h, &th->context));
1148 th->context.ContextFlags = 0;
1149 }
1150 }
1151
1152 debug_registers_changed = 0;
1153 return res;
1154 }
1155
1156 /* Called in pathological case where Windows fails to send a
1157 CREATE_PROCESS_DEBUG_EVENT after an attach. */
1158 static DWORD
1159 fake_create_process (void)
1160 {
1161 current_process_handle = OpenProcess (PROCESS_ALL_ACCESS, FALSE,
1162 current_event.dwProcessId);
1163 main_thread_id = current_event.dwThreadId;
1164 current_thread = win32_add_thread (main_thread_id,
1165 current_event.u.CreateThread.hThread);
1166 return main_thread_id;
1167 }
1168
1169 static void
1170 win32_resume (ptid_t ptid, int step, enum target_signal sig)
1171 {
1172 thread_info *th;
1173 DWORD continue_status = DBG_CONTINUE;
1174
1175 int pid = PIDGET (ptid);
1176
1177 if (sig != TARGET_SIGNAL_0)
1178 {
1179 if (current_event.dwDebugEventCode != EXCEPTION_DEBUG_EVENT)
1180 {
1181 DEBUG_EXCEPT(("Cannot continue with signal %d here.\n",sig));
1182 }
1183 else if (sig == last_sig)
1184 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1185 else
1186 #if 0
1187 /* This code does not seem to work, because
1188 the kernel does probably not consider changes in the ExceptionRecord
1189 structure when passing the exception to the inferior.
1190 Note that this seems possible in the exception handler itself. */
1191 {
1192 int i;
1193 for (i = 0; xlate[i].them != -1; i++)
1194 if (xlate[i].us == sig)
1195 {
1196 current_event.u.Exception.ExceptionRecord.ExceptionCode =
1197 xlate[i].them;
1198 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1199 break;
1200 }
1201 if (continue_status == DBG_CONTINUE)
1202 {
1203 DEBUG_EXCEPT(("Cannot continue with signal %d.\n",sig));
1204 }
1205 }
1206 #endif
1207 DEBUG_EXCEPT(("Can only continue with recieved signal %d.\n",
1208 last_sig));
1209 }
1210
1211 last_sig = TARGET_SIGNAL_0;
1212
1213 DEBUG_EXEC (("gdb: win32_resume (pid=%d, step=%d, sig=%d);\n",
1214 pid, step, sig));
1215
1216 /* Get context for currently selected thread */
1217 th = thread_rec (current_event.dwThreadId, FALSE);
1218 if (th)
1219 {
1220 if (step)
1221 {
1222 /* Single step by setting t bit */
1223 win32_fetch_inferior_registers (get_current_regcache (),
1224 gdbarch_ps_regnum (current_gdbarch));
1225 th->context.EFlags |= FLAG_TRACE_BIT;
1226 }
1227
1228 if (th->context.ContextFlags)
1229 {
1230 if (debug_registers_changed)
1231 {
1232 th->context.Dr0 = dr[0];
1233 th->context.Dr1 = dr[1];
1234 th->context.Dr2 = dr[2];
1235 th->context.Dr3 = dr[3];
1236 /* th->context.Dr6 = dr[6];
1237 FIXME: should we set dr6 also ?? */
1238 th->context.Dr7 = dr[7];
1239 }
1240 CHECK (SetThreadContext (th->h, &th->context));
1241 th->context.ContextFlags = 0;
1242 }
1243 }
1244
1245 /* Allow continuing with the same signal that interrupted us.
1246 Otherwise complain. */
1247
1248 win32_continue (continue_status, pid);
1249 }
1250
1251 /* Get the next event from the child. Return 1 if the event requires
1252 handling by WFI (or whatever).
1253 */
1254 static int
1255 get_win32_debug_event (int pid, struct target_waitstatus *ourstatus)
1256 {
1257 BOOL debug_event;
1258 DWORD continue_status, event_code;
1259 thread_info *th;
1260 static thread_info dummy_thread_info;
1261 int retval = 0;
1262 ptid_t ptid = {-1};
1263
1264 last_sig = TARGET_SIGNAL_0;
1265
1266 if (!(debug_event = WaitForDebugEvent (&current_event, 1000)))
1267 goto out;
1268
1269 event_count++;
1270 continue_status = DBG_CONTINUE;
1271
1272 event_code = current_event.dwDebugEventCode;
1273 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
1274 th = NULL;
1275 have_saved_context = 0;
1276
1277 switch (event_code)
1278 {
1279 case CREATE_THREAD_DEBUG_EVENT:
1280 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%x code=%s)\n",
1281 (unsigned) current_event.dwProcessId,
1282 (unsigned) current_event.dwThreadId,
1283 "CREATE_THREAD_DEBUG_EVENT"));
1284 if (saw_create != 1)
1285 {
1286 if (!saw_create && attach_flag)
1287 {
1288 /* Kludge around a Windows bug where first event is a create
1289 thread event. Caused when attached process does not have
1290 a main thread. */
1291 retval = ourstatus->value.related_pid = fake_create_process ();
1292 saw_create++;
1293 }
1294 break;
1295 }
1296 /* Record the existence of this thread */
1297 th = win32_add_thread (current_event.dwThreadId,
1298 current_event.u.CreateThread.hThread);
1299 if (info_verbose)
1300 printf_unfiltered ("[New %s]\n",
1301 target_pid_to_str (
1302 pid_to_ptid (current_event.dwThreadId)));
1303 retval = current_event.dwThreadId;
1304 break;
1305
1306 case EXIT_THREAD_DEBUG_EVENT:
1307 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
1308 (unsigned) current_event.dwProcessId,
1309 (unsigned) current_event.dwThreadId,
1310 "EXIT_THREAD_DEBUG_EVENT"));
1311 if (current_event.dwThreadId != main_thread_id)
1312 {
1313 win32_delete_thread (current_event.dwThreadId);
1314 th = &dummy_thread_info;
1315 }
1316 break;
1317
1318 case CREATE_PROCESS_DEBUG_EVENT:
1319 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
1320 (unsigned) current_event.dwProcessId,
1321 (unsigned) current_event.dwThreadId,
1322 "CREATE_PROCESS_DEBUG_EVENT"));
1323 CloseHandle (current_event.u.CreateProcessInfo.hFile);
1324 if (++saw_create != 1)
1325 {
1326 CloseHandle (current_event.u.CreateProcessInfo.hProcess);
1327 break;
1328 }
1329
1330 current_process_handle = current_event.u.CreateProcessInfo.hProcess;
1331 if (main_thread_id)
1332 win32_delete_thread (main_thread_id);
1333 main_thread_id = current_event.dwThreadId;
1334 /* Add the main thread */
1335 th = win32_add_thread (main_thread_id,
1336 current_event.u.CreateProcessInfo.hThread);
1337 retval = ourstatus->value.related_pid = current_event.dwThreadId;
1338 break;
1339
1340 case EXIT_PROCESS_DEBUG_EVENT:
1341 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
1342 (unsigned) current_event.dwProcessId,
1343 (unsigned) current_event.dwThreadId,
1344 "EXIT_PROCESS_DEBUG_EVENT"));
1345 if (saw_create != 1)
1346 break;
1347 ourstatus->kind = TARGET_WAITKIND_EXITED;
1348 ourstatus->value.integer = current_event.u.ExitProcess.dwExitCode;
1349 CloseHandle (current_process_handle);
1350 retval = main_thread_id;
1351 break;
1352
1353 case LOAD_DLL_DEBUG_EVENT:
1354 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
1355 (unsigned) current_event.dwProcessId,
1356 (unsigned) current_event.dwThreadId,
1357 "LOAD_DLL_DEBUG_EVENT"));
1358 CloseHandle (current_event.u.LoadDll.hFile);
1359 if (saw_create != 1)
1360 break;
1361 catch_errors (handle_load_dll, NULL, (char *) "", RETURN_MASK_ALL);
1362 ourstatus->kind = TARGET_WAITKIND_LOADED;
1363 ourstatus->value.integer = 0;
1364 retval = main_thread_id;
1365 break;
1366
1367 case UNLOAD_DLL_DEBUG_EVENT:
1368 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
1369 (unsigned) current_event.dwProcessId,
1370 (unsigned) current_event.dwThreadId,
1371 "UNLOAD_DLL_DEBUG_EVENT"));
1372 if (saw_create != 1)
1373 break;
1374 catch_errors (handle_unload_dll, NULL, (char *) "", RETURN_MASK_ALL);
1375 ourstatus->kind = TARGET_WAITKIND_LOADED;
1376 ourstatus->value.integer = 0;
1377 retval = main_thread_id;
1378 break;
1379
1380 case EXCEPTION_DEBUG_EVENT:
1381 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
1382 (unsigned) current_event.dwProcessId,
1383 (unsigned) current_event.dwThreadId,
1384 "EXCEPTION_DEBUG_EVENT"));
1385 if (saw_create != 1)
1386 break;
1387 switch (handle_exception (ourstatus))
1388 {
1389 case 0:
1390 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1391 break;
1392 case 1:
1393 retval = current_event.dwThreadId;
1394 break;
1395 case -1:
1396 last_sig = 1;
1397 continue_status = -1;
1398 break;
1399 }
1400 break;
1401
1402 case OUTPUT_DEBUG_STRING_EVENT: /* message from the kernel */
1403 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
1404 (unsigned) current_event.dwProcessId,
1405 (unsigned) current_event.dwThreadId,
1406 "OUTPUT_DEBUG_STRING_EVENT"));
1407 if (saw_create != 1)
1408 break;
1409 retval = handle_output_debug_string (ourstatus);
1410 break;
1411
1412 default:
1413 if (saw_create != 1)
1414 break;
1415 printf_unfiltered ("gdb: kernel event for pid=%ld tid=%ld\n",
1416 (DWORD) current_event.dwProcessId,
1417 (DWORD) current_event.dwThreadId);
1418 printf_unfiltered (" unknown event code %ld\n",
1419 current_event.dwDebugEventCode);
1420 break;
1421 }
1422
1423 if (!retval || saw_create != 1)
1424 {
1425 if (continue_status == -1)
1426 win32_resume (ptid, 0, 1);
1427 else
1428 CHECK (win32_continue (continue_status, -1));
1429 }
1430 else
1431 {
1432 inferior_ptid = pid_to_ptid (retval);
1433 current_thread = th ?: thread_rec (current_event.dwThreadId, TRUE);
1434 }
1435
1436 out:
1437 return retval;
1438 }
1439
1440 /* Wait for interesting events to occur in the target process. */
1441 static ptid_t
1442 win32_wait (ptid_t ptid, struct target_waitstatus *ourstatus)
1443 {
1444 int pid = PIDGET (ptid);
1445
1446 target_terminal_ours ();
1447
1448 /* We loop when we get a non-standard exception rather than return
1449 with a SPURIOUS because resume can try and step or modify things,
1450 which needs a current_thread->h. But some of these exceptions mark
1451 the birth or death of threads, which mean that the current thread
1452 isn't necessarily what you think it is. */
1453
1454 while (1)
1455 {
1456 int retval = get_win32_debug_event (pid, ourstatus);
1457 if (retval)
1458 return pid_to_ptid (retval);
1459 else
1460 {
1461 int detach = 0;
1462
1463 if (deprecated_ui_loop_hook != NULL)
1464 detach = deprecated_ui_loop_hook (0);
1465
1466 if (detach)
1467 win32_kill_inferior ();
1468 }
1469 }
1470 }
1471
1472 static void
1473 do_initial_win32_stuff (DWORD pid)
1474 {
1475 extern int stop_after_trap;
1476 int i;
1477
1478 last_sig = TARGET_SIGNAL_0;
1479 event_count = 0;
1480 exception_count = 0;
1481 debug_registers_changed = 0;
1482 debug_registers_used = 0;
1483 for (i = 0; i < sizeof (dr) / sizeof (dr[0]); i++)
1484 dr[i] = 0;
1485 #ifdef __CYGWIN__
1486 cygwin_load_start = cygwin_load_end = 0;
1487 #endif
1488 current_event.dwProcessId = pid;
1489 memset (&current_event, 0, sizeof (current_event));
1490 push_target (&win32_ops);
1491 disable_breakpoints_in_shlibs ();
1492 win32_clear_solib ();
1493 clear_proceed_status ();
1494 init_wait_for_inferior ();
1495
1496 terminal_init_inferior_with_pgrp (pid);
1497 target_terminal_inferior ();
1498
1499 while (1)
1500 {
1501 stop_after_trap = 1;
1502 wait_for_inferior ();
1503 if (stop_signal != TARGET_SIGNAL_TRAP)
1504 resume (0, stop_signal);
1505 else
1506 break;
1507 }
1508 stop_after_trap = 0;
1509 return;
1510 }
1511
1512 /* Since Windows XP, detaching from a process is supported by Windows.
1513 The following code tries loading the appropriate functions dynamically.
1514 If loading these functions succeeds use them to actually detach from
1515 the inferior process, otherwise behave as usual, pretending that
1516 detach has worked. */
1517 static BOOL WINAPI (*DebugSetProcessKillOnExit)(BOOL);
1518 static BOOL WINAPI (*DebugActiveProcessStop)(DWORD);
1519
1520 static int
1521 has_detach_ability (void)
1522 {
1523 static HMODULE kernel32 = NULL;
1524
1525 if (!kernel32)
1526 kernel32 = LoadLibrary ("kernel32.dll");
1527 if (kernel32)
1528 {
1529 if (!DebugSetProcessKillOnExit)
1530 DebugSetProcessKillOnExit = GetProcAddress (kernel32,
1531 "DebugSetProcessKillOnExit");
1532 if (!DebugActiveProcessStop)
1533 DebugActiveProcessStop = GetProcAddress (kernel32,
1534 "DebugActiveProcessStop");
1535 if (DebugSetProcessKillOnExit && DebugActiveProcessStop)
1536 return 1;
1537 }
1538 return 0;
1539 }
1540
1541 /* Try to set or remove a user privilege to the current process. Return -1
1542 if that fails, the previous setting of that privilege otherwise.
1543
1544 This code is copied from the Cygwin source code and rearranged to allow
1545 dynamically loading of the needed symbols from advapi32 which is only
1546 available on NT/2K/XP. */
1547 static int
1548 set_process_privilege (const char *privilege, BOOL enable)
1549 {
1550 static HMODULE advapi32 = NULL;
1551 static BOOL WINAPI (*OpenProcessToken)(HANDLE, DWORD, PHANDLE);
1552 static BOOL WINAPI (*LookupPrivilegeValue)(LPCSTR, LPCSTR, PLUID);
1553 static BOOL WINAPI (*AdjustTokenPrivileges)(HANDLE, BOOL, PTOKEN_PRIVILEGES,
1554 DWORD, PTOKEN_PRIVILEGES, PDWORD);
1555
1556 HANDLE token_hdl = NULL;
1557 LUID restore_priv;
1558 TOKEN_PRIVILEGES new_priv, orig_priv;
1559 int ret = -1;
1560 DWORD size;
1561
1562 if (GetVersion () >= 0x80000000) /* No security availbale on 9x/Me */
1563 return 0;
1564
1565 if (!advapi32)
1566 {
1567 if (!(advapi32 = LoadLibrary ("advapi32.dll")))
1568 goto out;
1569 if (!OpenProcessToken)
1570 OpenProcessToken = GetProcAddress (advapi32, "OpenProcessToken");
1571 if (!LookupPrivilegeValue)
1572 LookupPrivilegeValue = GetProcAddress (advapi32,
1573 "LookupPrivilegeValueA");
1574 if (!AdjustTokenPrivileges)
1575 AdjustTokenPrivileges = GetProcAddress (advapi32,
1576 "AdjustTokenPrivileges");
1577 if (!OpenProcessToken || !LookupPrivilegeValue || !AdjustTokenPrivileges)
1578 {
1579 advapi32 = NULL;
1580 goto out;
1581 }
1582 }
1583
1584 if (!OpenProcessToken (GetCurrentProcess (),
1585 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
1586 &token_hdl))
1587 goto out;
1588
1589 if (!LookupPrivilegeValue (NULL, privilege, &restore_priv))
1590 goto out;
1591
1592 new_priv.PrivilegeCount = 1;
1593 new_priv.Privileges[0].Luid = restore_priv;
1594 new_priv.Privileges[0].Attributes = enable ? SE_PRIVILEGE_ENABLED : 0;
1595
1596 if (!AdjustTokenPrivileges (token_hdl, FALSE, &new_priv,
1597 sizeof orig_priv, &orig_priv, &size))
1598 goto out;
1599 #if 0
1600 /* Disabled, otherwise every `attach' in an unprivileged user session
1601 would raise the "Failed to get SE_DEBUG_NAME privilege" warning in
1602 win32_attach(). */
1603 /* AdjustTokenPrivileges returns TRUE even if the privilege could not
1604 be enabled. GetLastError () returns an correct error code, though. */
1605 if (enable && GetLastError () == ERROR_NOT_ALL_ASSIGNED)
1606 goto out;
1607 #endif
1608
1609 ret = orig_priv.Privileges[0].Attributes == SE_PRIVILEGE_ENABLED ? 1 : 0;
1610
1611 out:
1612 if (token_hdl)
1613 CloseHandle (token_hdl);
1614
1615 return ret;
1616 }
1617
1618 /* Attach to process PID, then initialize for debugging it. */
1619 static void
1620 win32_attach (char *args, int from_tty)
1621 {
1622 BOOL ok;
1623 DWORD pid;
1624
1625 if (!args)
1626 error_no_arg (_("process-id to attach"));
1627
1628 if (set_process_privilege (SE_DEBUG_NAME, TRUE) < 0)
1629 {
1630 printf_unfiltered ("Warning: Failed to get SE_DEBUG_NAME privilege\n");
1631 printf_unfiltered ("This can cause attach to fail on Windows NT/2K/XP\n");
1632 }
1633
1634 pid = strtoul (args, 0, 0); /* Windows pid */
1635
1636 win32_init_thread_list ();
1637 ok = DebugActiveProcess (pid);
1638 saw_create = 0;
1639
1640 #ifdef __CYGWIN__
1641 if (!ok)
1642 {
1643 /* Try fall back to Cygwin pid */
1644 pid = cygwin_internal (CW_CYGWIN_PID_TO_WINPID, pid);
1645
1646 if (pid > 0)
1647 ok = DebugActiveProcess (pid);
1648 }
1649 #endif
1650
1651 if (!ok)
1652 error (_("Can't attach to process."));
1653
1654 if (has_detach_ability ())
1655 DebugSetProcessKillOnExit (FALSE);
1656
1657 attach_flag = 1;
1658
1659 if (from_tty)
1660 {
1661 char *exec_file = (char *) get_exec_file (0);
1662
1663 if (exec_file)
1664 printf_unfiltered ("Attaching to program `%s', %s\n", exec_file,
1665 target_pid_to_str (pid_to_ptid (pid)));
1666 else
1667 printf_unfiltered ("Attaching to %s\n",
1668 target_pid_to_str (pid_to_ptid (pid)));
1669
1670 gdb_flush (gdb_stdout);
1671 }
1672
1673 do_initial_win32_stuff (pid);
1674 target_terminal_ours ();
1675 }
1676
1677 static void
1678 win32_detach (char *args, int from_tty)
1679 {
1680 int detached = 1;
1681
1682 if (has_detach_ability ())
1683 {
1684 ptid_t ptid = {-1};
1685 win32_resume (ptid, 0, TARGET_SIGNAL_0);
1686
1687 if (!DebugActiveProcessStop (current_event.dwProcessId))
1688 {
1689 error (_("Can't detach process %lu (error %lu)"),
1690 current_event.dwProcessId, GetLastError ());
1691 detached = 0;
1692 }
1693 DebugSetProcessKillOnExit (FALSE);
1694 }
1695 if (detached && from_tty)
1696 {
1697 char *exec_file = get_exec_file (0);
1698 if (exec_file == 0)
1699 exec_file = "";
1700 printf_unfiltered ("Detaching from program: %s, Pid %lu\n", exec_file,
1701 current_event.dwProcessId);
1702 gdb_flush (gdb_stdout);
1703 }
1704 inferior_ptid = null_ptid;
1705 unpush_target (&win32_ops);
1706 }
1707
1708 static char *
1709 win32_pid_to_exec_file (int pid)
1710 {
1711 /* Try to find the process path using the Cygwin internal process list
1712 pid isn't a valid pid, unfortunately. Use current_event.dwProcessId
1713 instead. */
1714
1715 static char path[MAX_PATH + 1];
1716 char *path_ptr = NULL;
1717
1718 #ifdef __CYGWIN__
1719 /* TODO: Also find native Windows processes using CW_GETPINFO_FULL. */
1720 int cpid;
1721 struct external_pinfo *pinfo;
1722
1723 cygwin_internal (CW_LOCK_PINFO, 1000);
1724 for (cpid = 0;
1725 (pinfo = (struct external_pinfo *)
1726 cygwin_internal (CW_GETPINFO, cpid | CW_NEXTPID));
1727 cpid = pinfo->pid)
1728 {
1729 if (pinfo->dwProcessId == current_event.dwProcessId) /* Got it */
1730 {
1731 cygwin_conv_to_full_posix_path (pinfo->progname, path);
1732 path_ptr = path;
1733 break;
1734 }
1735 }
1736 cygwin_internal (CW_UNLOCK_PINFO);
1737 #endif
1738
1739 return path_ptr;
1740 }
1741
1742 /* Print status information about what we're accessing. */
1743
1744 static void
1745 win32_files_info (struct target_ops *ignore)
1746 {
1747 printf_unfiltered ("\tUsing the running image of %s %s.\n",
1748 attach_flag ? "attached" : "child", target_pid_to_str (inferior_ptid));
1749 }
1750
1751 static void
1752 win32_open (char *arg, int from_tty)
1753 {
1754 error (_("Use the \"run\" command to start a Unix child process."));
1755 }
1756
1757 /* Start an inferior win32 child process and sets inferior_ptid to its pid.
1758 EXEC_FILE is the file to run.
1759 ALLARGS is a string containing the arguments to the program.
1760 ENV is the environment vector to pass. Errors reported with error(). */
1761
1762 static void
1763 win32_create_inferior (char *exec_file, char *allargs, char **in_env,
1764 int from_tty)
1765 {
1766 STARTUPINFO si;
1767 PROCESS_INFORMATION pi;
1768 BOOL ret;
1769 DWORD flags;
1770 char *args;
1771 char real_path[MAXPATHLEN];
1772 char *toexec;
1773 char shell[MAX_PATH + 1]; /* Path to shell */
1774 const char *sh;
1775 int tty;
1776 int ostdin, ostdout, ostderr;
1777 const char *inferior_io_terminal = get_inferior_io_terminal ();
1778
1779 if (!exec_file)
1780 error (_("No executable specified, use `target exec'."));
1781
1782 memset (&si, 0, sizeof (si));
1783 si.cb = sizeof (si);
1784
1785 #ifdef __CYGWIN__
1786 if (!useshell)
1787 {
1788 flags = DEBUG_ONLY_THIS_PROCESS;
1789 cygwin_conv_to_win32_path (exec_file, real_path);
1790 toexec = real_path;
1791 }
1792 else
1793 {
1794 char *newallargs;
1795 sh = getenv ("SHELL");
1796 if (!sh)
1797 sh = "/bin/sh";
1798 cygwin_conv_to_win32_path (sh, shell);
1799 newallargs = alloca (sizeof (" -c 'exec '") + strlen (exec_file)
1800 + strlen (allargs) + 2);
1801 sprintf (newallargs, " -c 'exec %s %s'", exec_file, allargs);
1802 allargs = newallargs;
1803 toexec = shell;
1804 flags = DEBUG_PROCESS;
1805 }
1806 #else
1807 toexec = exec_file;
1808 flags = DEBUG_ONLY_THIS_PROCESS;
1809 #endif
1810
1811 if (new_group)
1812 flags |= CREATE_NEW_PROCESS_GROUP;
1813
1814 if (new_console)
1815 flags |= CREATE_NEW_CONSOLE;
1816
1817 attach_flag = 0;
1818
1819 args = alloca (strlen (toexec) + strlen (allargs) + 2);
1820 strcpy (args, toexec);
1821 strcat (args, " ");
1822 strcat (args, allargs);
1823
1824 #ifdef __CYGWIN__
1825 /* Prepare the environment vars for CreateProcess. */
1826 cygwin_internal (CW_SYNC_WINENV);
1827
1828 if (!inferior_io_terminal)
1829 tty = ostdin = ostdout = ostderr = -1;
1830 else
1831 {
1832 tty = open (inferior_io_terminal, O_RDWR | O_NOCTTY);
1833 if (tty < 0)
1834 {
1835 print_sys_errmsg (inferior_io_terminal, errno);
1836 ostdin = ostdout = ostderr = -1;
1837 }
1838 else
1839 {
1840 ostdin = dup (0);
1841 ostdout = dup (1);
1842 ostderr = dup (2);
1843 dup2 (tty, 0);
1844 dup2 (tty, 1);
1845 dup2 (tty, 2);
1846 }
1847 }
1848 #endif
1849
1850 win32_init_thread_list ();
1851 ret = CreateProcess (0,
1852 args, /* command line */
1853 NULL, /* Security */
1854 NULL, /* thread */
1855 TRUE, /* inherit handles */
1856 flags, /* start flags */
1857 NULL, /* environment */
1858 NULL, /* current directory */
1859 &si,
1860 &pi);
1861
1862 #ifdef __CYGWIN__
1863 if (tty >= 0)
1864 {
1865 close (tty);
1866 dup2 (ostdin, 0);
1867 dup2 (ostdout, 1);
1868 dup2 (ostderr, 2);
1869 close (ostdin);
1870 close (ostdout);
1871 close (ostderr);
1872 }
1873 #endif
1874
1875 if (!ret)
1876 error (_("Error creating process %s, (error %d)."),
1877 exec_file, (unsigned) GetLastError ());
1878
1879 CloseHandle (pi.hThread);
1880 CloseHandle (pi.hProcess);
1881
1882 if (useshell && shell[0] != '\0')
1883 saw_create = -1;
1884 else
1885 saw_create = 0;
1886
1887 do_initial_win32_stuff (pi.dwProcessId);
1888
1889 /* win32_continue (DBG_CONTINUE, -1); */
1890 }
1891
1892 static void
1893 win32_mourn_inferior (void)
1894 {
1895 (void) win32_continue (DBG_CONTINUE, -1);
1896 i386_cleanup_dregs();
1897 unpush_target (&win32_ops);
1898 generic_mourn_inferior ();
1899 }
1900
1901 /* Send a SIGINT to the process group. This acts just like the user typed a
1902 ^C on the controlling terminal. */
1903
1904 static void
1905 win32_stop (void)
1906 {
1907 DEBUG_EVENTS (("gdb: GenerateConsoleCtrlEvent (CTRLC_EVENT, 0)\n"));
1908 CHECK (GenerateConsoleCtrlEvent (CTRL_C_EVENT, current_event.dwProcessId));
1909 registers_changed (); /* refresh register state */
1910 }
1911
1912 static int
1913 win32_xfer_memory (CORE_ADDR memaddr, gdb_byte *our, int len,
1914 int write, struct mem_attrib *mem,
1915 struct target_ops *target)
1916 {
1917 DWORD done = 0;
1918 if (write)
1919 {
1920 DEBUG_MEM (("gdb: write target memory, %d bytes at 0x%08lx\n",
1921 len, (DWORD) memaddr));
1922 if (!WriteProcessMemory (current_process_handle, (LPVOID) memaddr, our,
1923 len, &done))
1924 done = 0;
1925 FlushInstructionCache (current_process_handle, (LPCVOID) memaddr, len);
1926 }
1927 else
1928 {
1929 DEBUG_MEM (("gdb: read target memory, %d bytes at 0x%08lx\n",
1930 len, (DWORD) memaddr));
1931 if (!ReadProcessMemory (current_process_handle, (LPCVOID) memaddr, our,
1932 len, &done))
1933 done = 0;
1934 }
1935 return done;
1936 }
1937
1938 static void
1939 win32_kill_inferior (void)
1940 {
1941 CHECK (TerminateProcess (current_process_handle, 0));
1942
1943 for (;;)
1944 {
1945 if (!win32_continue (DBG_CONTINUE, -1))
1946 break;
1947 if (!WaitForDebugEvent (&current_event, INFINITE))
1948 break;
1949 if (current_event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
1950 break;
1951 }
1952
1953 CHECK (CloseHandle (current_process_handle));
1954
1955 /* this may fail in an attached process so don't check. */
1956 if (current_thread && current_thread->h)
1957 (void) CloseHandle (current_thread->h);
1958 target_mourn_inferior (); /* or just win32_mourn_inferior? */
1959 }
1960
1961 static void
1962 win32_prepare_to_store (struct regcache *regcache)
1963 {
1964 /* Do nothing, since we can store individual regs */
1965 }
1966
1967 static int
1968 win32_can_run (void)
1969 {
1970 return 1;
1971 }
1972
1973 static void
1974 win32_close (int x)
1975 {
1976 DEBUG_EVENTS (("gdb: win32_close, inferior_ptid=%d\n",
1977 PIDGET (inferior_ptid)));
1978 }
1979
1980 /* Convert pid to printable format. */
1981 static char *
1982 win32_pid_to_str (ptid_t ptid)
1983 {
1984 static char buf[80];
1985 int pid = PIDGET (ptid);
1986
1987 if ((DWORD) pid == current_event.dwProcessId)
1988 sprintf (buf, "process %d", pid);
1989 else
1990 sprintf (buf, "thread %ld.0x%x", current_event.dwProcessId, pid);
1991 return buf;
1992 }
1993
1994 static LONGEST
1995 win32_xfer_shared_libraries (struct target_ops *ops,
1996 enum target_object object, const char *annex,
1997 gdb_byte *readbuf, const gdb_byte *writebuf,
1998 ULONGEST offset, LONGEST len)
1999 {
2000 struct obstack obstack;
2001 const char *buf;
2002 LONGEST len_avail;
2003 struct so_list *so;
2004
2005 if (writebuf)
2006 return -1;
2007
2008 obstack_init (&obstack);
2009 obstack_grow_str (&obstack, "<library-list>\n");
2010 for (so = solib_start.next; so; so = so->next)
2011 win32_xfer_shared_library (so->so_name, so->lm_info->load_addr, &obstack);
2012 obstack_grow_str0 (&obstack, "</library-list>\n");
2013
2014 buf = obstack_finish (&obstack);
2015 len_avail = strlen (buf);
2016 if (offset >= len_avail)
2017 return 0;
2018
2019 if (len > len_avail - offset)
2020 len = len_avail - offset;
2021 memcpy (readbuf, buf + offset, len);
2022
2023 obstack_free (&obstack, NULL);
2024 return len;
2025 }
2026
2027 static LONGEST
2028 win32_xfer_partial (struct target_ops *ops, enum target_object object,
2029 const char *annex, gdb_byte *readbuf,
2030 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
2031 {
2032 switch (object)
2033 {
2034 case TARGET_OBJECT_MEMORY:
2035 if (readbuf)
2036 return (*ops->deprecated_xfer_memory) (offset, readbuf,
2037 len, 0/*write*/, NULL, ops);
2038 if (writebuf)
2039 return (*ops->deprecated_xfer_memory) (offset, (gdb_byte *) writebuf,
2040 len, 1/*write*/, NULL, ops);
2041 return -1;
2042
2043 case TARGET_OBJECT_LIBRARIES:
2044 return win32_xfer_shared_libraries (ops, object, annex, readbuf,
2045 writebuf, offset, len);
2046
2047 default:
2048 if (ops->beneath != NULL)
2049 return ops->beneath->to_xfer_partial (ops->beneath, object, annex,
2050 readbuf, writebuf, offset, len);
2051 return -1;
2052 }
2053 }
2054
2055 static void
2056 init_win32_ops (void)
2057 {
2058 win32_ops.to_shortname = "child";
2059 win32_ops.to_longname = "Win32 child process";
2060 win32_ops.to_doc = "Win32 child process (started by the \"run\" command).";
2061 win32_ops.to_open = win32_open;
2062 win32_ops.to_close = win32_close;
2063 win32_ops.to_attach = win32_attach;
2064 win32_ops.to_detach = win32_detach;
2065 win32_ops.to_resume = win32_resume;
2066 win32_ops.to_wait = win32_wait;
2067 win32_ops.to_fetch_registers = win32_fetch_inferior_registers;
2068 win32_ops.to_store_registers = win32_store_inferior_registers;
2069 win32_ops.to_prepare_to_store = win32_prepare_to_store;
2070 win32_ops.deprecated_xfer_memory = win32_xfer_memory;
2071 win32_ops.to_xfer_partial = win32_xfer_partial;
2072 win32_ops.to_files_info = win32_files_info;
2073 win32_ops.to_insert_breakpoint = memory_insert_breakpoint;
2074 win32_ops.to_remove_breakpoint = memory_remove_breakpoint;
2075 win32_ops.to_terminal_init = terminal_init_inferior;
2076 win32_ops.to_terminal_inferior = terminal_inferior;
2077 win32_ops.to_terminal_ours_for_output = terminal_ours_for_output;
2078 win32_ops.to_terminal_ours = terminal_ours;
2079 win32_ops.to_terminal_save_ours = terminal_save_ours;
2080 win32_ops.to_terminal_info = child_terminal_info;
2081 win32_ops.to_kill = win32_kill_inferior;
2082 win32_ops.to_create_inferior = win32_create_inferior;
2083 win32_ops.to_mourn_inferior = win32_mourn_inferior;
2084 win32_ops.to_can_run = win32_can_run;
2085 win32_ops.to_thread_alive = win32_win32_thread_alive;
2086 win32_ops.to_pid_to_str = win32_pid_to_str;
2087 win32_ops.to_stop = win32_stop;
2088 win32_ops.to_stratum = process_stratum;
2089 win32_ops.to_has_all_memory = 1;
2090 win32_ops.to_has_memory = 1;
2091 win32_ops.to_has_stack = 1;
2092 win32_ops.to_has_registers = 1;
2093 win32_ops.to_has_execution = 1;
2094 win32_ops.to_magic = OPS_MAGIC;
2095 win32_ops.to_pid_to_exec_file = win32_pid_to_exec_file;
2096 }
2097
2098 static void
2099 set_win32_aliases (char *argv0)
2100 {
2101 add_info_alias ("dll", "sharedlibrary", 1);
2102 }
2103
2104 void
2105 _initialize_win32_nat (void)
2106 {
2107 struct cmd_list_element *c;
2108
2109 init_win32_ops ();
2110
2111 c = add_com ("dll-symbols", class_files, dll_symbol_command,
2112 _("Load dll library symbols from FILE."));
2113 set_cmd_completer (c, filename_completer);
2114
2115 add_com_alias ("sharedlibrary", "dll-symbols", class_alias, 1);
2116
2117 #ifdef __CYGWIN__
2118 add_setshow_boolean_cmd ("shell", class_support, &useshell, _("\
2119 Set use of shell to start subprocess."), _("\
2120 Show use of shell to start subprocess."), NULL,
2121 NULL,
2122 NULL, /* FIXME: i18n: */
2123 &setlist, &showlist);
2124
2125 add_setshow_boolean_cmd ("cygwin-exceptions", class_support, &cygwin_exceptions, _("\
2126 Break when an exception is detected in the Cygwin DLL itself."), _("\
2127 Show whether gdb breaks on exceptions in the Cygwin DLL itself."), NULL,
2128 NULL,
2129 NULL, /* FIXME: i18n: */
2130 &setlist, &showlist);
2131 #endif
2132
2133 add_setshow_boolean_cmd ("new-console", class_support, &new_console, _("\
2134 Set creation of new console when creating child process."), _("\
2135 Show creation of new console when creating child process."), NULL,
2136 NULL,
2137 NULL, /* FIXME: i18n: */
2138 &setlist, &showlist);
2139
2140 add_setshow_boolean_cmd ("new-group", class_support, &new_group, _("\
2141 Set creation of new group when creating child process."), _("\
2142 Show creation of new group when creating child process."), NULL,
2143 NULL,
2144 NULL, /* FIXME: i18n: */
2145 &setlist, &showlist);
2146
2147 add_setshow_boolean_cmd ("debugexec", class_support, &debug_exec, _("\
2148 Set whether to display execution in child process."), _("\
2149 Show whether to display execution in child process."), NULL,
2150 NULL,
2151 NULL, /* FIXME: i18n: */
2152 &setlist, &showlist);
2153
2154 add_setshow_boolean_cmd ("debugevents", class_support, &debug_events, _("\
2155 Set whether to display kernel events in child process."), _("\
2156 Show whether to display kernel events in child process."), NULL,
2157 NULL,
2158 NULL, /* FIXME: i18n: */
2159 &setlist, &showlist);
2160
2161 add_setshow_boolean_cmd ("debugmemory", class_support, &debug_memory, _("\
2162 Set whether to display memory accesses in child process."), _("\
2163 Show whether to display memory accesses in child process."), NULL,
2164 NULL,
2165 NULL, /* FIXME: i18n: */
2166 &setlist, &showlist);
2167
2168 add_setshow_boolean_cmd ("debugexceptions", class_support,
2169 &debug_exceptions, _("\
2170 Set whether to display kernel exceptions in child process."), _("\
2171 Show whether to display kernel exceptions in child process."), NULL,
2172 NULL,
2173 NULL, /* FIXME: i18n: */
2174 &setlist, &showlist);
2175
2176 add_prefix_cmd ("w32", class_info, info_w32_command,
2177 _("Print information specific to Win32 debugging."),
2178 &info_w32_cmdlist, "info w32 ", 0, &infolist);
2179
2180 add_cmd ("selector", class_info, display_selectors,
2181 _("Display selectors infos."),
2182 &info_w32_cmdlist);
2183 add_target (&win32_ops);
2184 deprecated_init_ui_hook = set_win32_aliases;
2185 }
2186
2187 /* Hardware watchpoint support, adapted from go32-nat.c code. */
2188
2189 /* Pass the address ADDR to the inferior in the I'th debug register.
2190 Here we just store the address in dr array, the registers will be
2191 actually set up when win32_continue is called. */
2192 void
2193 cygwin_set_dr (int i, CORE_ADDR addr)
2194 {
2195 if (i < 0 || i > 3)
2196 internal_error (__FILE__, __LINE__,
2197 _("Invalid register %d in cygwin_set_dr.\n"), i);
2198 dr[i] = (unsigned) addr;
2199 debug_registers_changed = 1;
2200 debug_registers_used = 1;
2201 }
2202
2203 /* Pass the value VAL to the inferior in the DR7 debug control
2204 register. Here we just store the address in D_REGS, the watchpoint
2205 will be actually set up in win32_wait. */
2206 void
2207 cygwin_set_dr7 (unsigned val)
2208 {
2209 dr[7] = val;
2210 debug_registers_changed = 1;
2211 debug_registers_used = 1;
2212 }
2213
2214 /* Get the value of the DR6 debug status register from the inferior.
2215 Here we just return the value stored in dr[6]
2216 by the last call to thread_rec for current_event.dwThreadId id. */
2217 unsigned
2218 cygwin_get_dr6 (void)
2219 {
2220 return dr[6];
2221 }
2222
2223 /* Determine if the thread referenced by "pid" is alive
2224 by "polling" it. If WaitForSingleObject returns WAIT_OBJECT_0
2225 it means that the pid has died. Otherwise it is assumed to be alive. */
2226 static int
2227 win32_win32_thread_alive (ptid_t ptid)
2228 {
2229 int pid = PIDGET (ptid);
2230
2231 return WaitForSingleObject (thread_rec (pid, FALSE)->h, 0) == WAIT_OBJECT_0 ?
2232 FALSE : TRUE;
2233 }
2234
2235 void
2236 _initialize_check_for_gdb_ini (void)
2237 {
2238 char *homedir;
2239 if (inhibit_gdbinit)
2240 return;
2241
2242 homedir = getenv ("HOME");
2243 if (homedir)
2244 {
2245 char *p;
2246 char *oldini = (char *) alloca (strlen (homedir) +
2247 sizeof ("/gdb.ini"));
2248 strcpy (oldini, homedir);
2249 p = strchr (oldini, '\0');
2250 if (p > oldini && p[-1] != '/')
2251 *p++ = '/';
2252 strcpy (p, "gdb.ini");
2253 if (access (oldini, 0) == 0)
2254 {
2255 int len = strlen (oldini);
2256 char *newini = alloca (len + 1);
2257 sprintf (newini, "%.*s.gdbinit",
2258 (int) (len - (sizeof ("gdb.ini") - 1)), oldini);
2259 warning (_("obsolete '%s' found. Rename to '%s'."), oldini, newini);
2260 }
2261 }
2262 }
This page took 0.079485 seconds and 4 git commands to generate.