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