import gdb-1999-12-06 snapshot
[external/binutils.git] / gdb / win32-nat.c
1 /* Target-vector operations for controlling win32 child processes, for GDB.
2    Copyright 1995, 1996, 1997, 1998 Free Software Foundation, Inc.
3    Contributed by Cygnus Support.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without eve nthe implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 59 Temple Place - Suite 330,
20    Boston, MA 02111-1307, USA.
21  */
22
23 /* by Steve Chamberlain, sac@cygnus.com */
24
25 /* We assume we're being built with and will be used for cygwin.  */
26
27 #include "defs.h"
28 #include "frame.h"              /* required by inferior.h */
29 #include "inferior.h"
30 #include "target.h"
31 #include "wait.h"
32 #include "gdbcore.h"
33 #include "command.h"
34 #include <signal.h>
35 #include <sys/types.h>
36 #include <fcntl.h>
37 #include <stdlib.h>
38
39 #ifdef _MSC_VER
40 #include "windefs.h"
41 #else /* other WIN32 compiler */
42 #include <windows.h>
43 #include <imagehlp.h>
44 #endif
45
46 #include "buildsym.h"
47 #include "symfile.h"
48 #include "objfiles.h"
49 #include "gdb_string.h"
50 #include "gdbthread.h"
51 #include "gdbcmd.h"
52 #include <sys/param.h>
53 #include <unistd.h>
54
55 /* The ui's event loop. */
56 extern int (*ui_loop_hook) PARAMS ((int signo));
57
58 /* If we're not using the old Cygwin header file set, define the
59    following which never should have been in the generic Win32 API
60    headers in the first place since they were our own invention... */
61 #ifndef _GNU_H_WINDOWS_H
62 #define FLAG_TRACE_BIT 0x100
63 #define CONTEXT_DEBUGGER (CONTEXT_FULL | CONTEXT_FLOATING_POINT)
64 #endif
65
66 /* The string sent by cygwin when it processes a signal.
67    FIXME: This should be in a cygwin include file. */
68 #define CYGWIN_SIGNAL_STRING "cygwin: signal"
69
70 #define CHECK(x)        check (x, __FILE__,__LINE__)
71 #define DEBUG_EXEC(x)   if (debug_exec)         printf x
72 #define DEBUG_EVENTS(x) if (debug_events)       printf x
73 #define DEBUG_MEM(x)    if (debug_memory)       printf x
74 #define DEBUG_EXCEPT(x) if (debug_exceptions)   printf x
75
76 /* Forward declaration */
77 extern struct target_ops child_ops;
78
79 static void child_stop PARAMS ((void));
80 static int win32_child_thread_alive PARAMS ((int));
81 void child_kill_inferior PARAMS ((void));
82
83 /* Thread information structure used to track information that is
84    not available in gdb's thread structure. */
85 typedef struct thread_info_struct
86   {
87     struct thread_info_struct *next;
88     DWORD id;
89     HANDLE h;
90     char *name;
91     int suspend_count;
92     CONTEXT context;
93     STACKFRAME sf;
94   } thread_info;
95
96 static thread_info thread_head = {NULL};
97
98 /* The saved state for a continue after breaking back to gdb. */
99 static DWORD continue_status;
100
101 /* The process and thread handles for the above context. */
102
103 static DEBUG_EVENT current_event;       /* The current debug event from
104                                            WaitForDebugEvent */
105 static HANDLE current_process_handle;   /* Currently executing process */
106 static thread_info *current_thread;     /* Info on currently selected thread */
107 static DWORD main_thread_id;    /* Thread ID of the main thread */
108
109 /* Counts of things. */
110 static int exception_count = 0;
111 static int event_count = 0;
112
113 /* User options. */
114 static int new_console = 0;
115 static int new_group = 1;
116 static int debug_exec = 0;      /* show execution */
117 static int debug_events = 0;    /* show events from kernel */
118 static int debug_memory = 0;    /* show target memory accesses */
119 static int debug_exceptions = 0;        /* show target exceptions */
120
121 /* This vector maps GDB's idea of a register's number into an address
122    in the win32 exception context vector.
123
124    It also contains the bit mask needed to load the register in question.
125
126    One day we could read a reg, we could inspect the context we
127    already have loaded, if it doesn't have the bit set that we need,
128    we read that set of registers in using GetThreadContext.  If the
129    context already contains what we need, we just unpack it. Then to
130    write a register, first we have to ensure that the context contains
131    the other regs of the group, and then we copy the info in and set
132    out bit. */
133
134 #define context_offset(x) ((int)&(((CONTEXT *)NULL)->x))
135 static const int mappings[] =
136 {
137   context_offset (Eax),
138   context_offset (Ecx),
139   context_offset (Edx),
140   context_offset (Ebx),
141   context_offset (Esp),
142   context_offset (Ebp),
143   context_offset (Esi),
144   context_offset (Edi),
145   context_offset (Eip),
146   context_offset (EFlags),
147   context_offset (SegCs),
148   context_offset (SegSs),
149   context_offset (SegDs),
150   context_offset (SegEs),
151   context_offset (SegFs),
152   context_offset (SegGs),
153   context_offset (FloatSave.RegisterArea[0 * 10]),
154   context_offset (FloatSave.RegisterArea[1 * 10]),
155   context_offset (FloatSave.RegisterArea[2 * 10]),
156   context_offset (FloatSave.RegisterArea[3 * 10]),
157   context_offset (FloatSave.RegisterArea[4 * 10]),
158   context_offset (FloatSave.RegisterArea[5 * 10]),
159   context_offset (FloatSave.RegisterArea[6 * 10]),
160   context_offset (FloatSave.RegisterArea[7 * 10]),
161   context_offset (FloatSave.ControlWord),
162   context_offset (FloatSave.StatusWord),
163   context_offset (FloatSave.TagWord),
164   context_offset (FloatSave.ErrorSelector),
165   context_offset (FloatSave.ErrorOffset),
166   context_offset (FloatSave.DataSelector),
167   context_offset (FloatSave.DataOffset),
168 };
169
170 /* This vector maps the target's idea of an exception (extracted
171    from the DEBUG_EVENT structure) to GDB's idea. */
172
173 struct xlate_exception
174   {
175     int them;
176     enum target_signal us;
177   };
178
179 static const struct xlate_exception
180   xlate[] =
181 {
182   {EXCEPTION_ACCESS_VIOLATION, TARGET_SIGNAL_SEGV},
183   {STATUS_STACK_OVERFLOW, TARGET_SIGNAL_SEGV},
184   {EXCEPTION_BREAKPOINT, TARGET_SIGNAL_TRAP},
185   {DBG_CONTROL_C, TARGET_SIGNAL_INT},
186   {EXCEPTION_SINGLE_STEP, TARGET_SIGNAL_TRAP},
187   {-1, -1}};
188
189 /* Find a thread record given a thread id.
190    If get_context then also retrieve the context for this
191    thread. */
192 static thread_info *
193 thread_rec (DWORD id, int get_context)
194 {
195   thread_info *th;
196
197   for (th = &thread_head; (th = th->next) != NULL;)
198     if (th->id == id)
199       {
200         if (!th->suspend_count && get_context)
201           {
202             if (get_context > 0)
203               th->suspend_count = SuspendThread (th->h) + 1;
204             else if (get_context < 0)
205               th->suspend_count = -1;
206
207             th->context.ContextFlags = CONTEXT_DEBUGGER;
208             GetThreadContext (th->h, &th->context);
209           }
210         return th;
211       }
212
213   return NULL;
214 }
215
216 /* Add a thread to the thread list */
217 static thread_info *
218 child_add_thread (DWORD id, HANDLE h)
219 {
220   thread_info *th;
221
222   if ((th = thread_rec (id, FALSE)))
223     return th;
224
225   th = (thread_info *) xmalloc (sizeof (*th));
226   memset (th, 0, sizeof (*th));
227   th->id = id;
228   th->h = h;
229   th->next = thread_head.next;
230   thread_head.next = th;
231   add_thread (id);
232   return th;
233 }
234
235 /* Clear out any old thread list and reintialize it to a
236    pristine state. */
237 static void
238 child_init_thread_list ()
239 {
240   thread_info *th = &thread_head;
241
242   DEBUG_EVENTS (("gdb: child_init_thread_list\n"));
243   init_thread_list ();
244   while (th->next != NULL)
245     {
246       thread_info *here = th->next;
247       th->next = here->next;
248       (void) CloseHandle (here->h);
249       free (here);
250     }
251 }
252
253 /* Delete a thread from the list of threads */
254 static void
255 child_delete_thread (DWORD id)
256 {
257   thread_info *th;
258
259   if (info_verbose)
260     printf_unfiltered ("[Deleting %s]\n", target_pid_to_str (id));
261   delete_thread (id);
262
263   for (th = &thread_head;
264        th->next != NULL && th->next->id != id;
265        th = th->next)
266     continue;
267
268   if (th->next != NULL)
269     {
270       thread_info *here = th->next;
271       th->next = here->next;
272       CloseHandle (here->h);
273       free (here);
274     }
275 }
276
277 static void
278 check (BOOL ok, const char *file, int line)
279 {
280   if (!ok)
281     printf_filtered ("error return %s:%d was %d\n", file, line, GetLastError ());
282 }
283
284 static void
285 do_child_fetch_inferior_registers (int r)
286 {
287   char *context_offset = ((char *) &current_thread->context) + mappings[r];
288   long l;
289   if (r == FCS_REGNUM)
290     {
291       l = *((long *)context_offset) & 0xffff;
292       supply_register (r, (char *) &l);
293     }
294   else if (r == FOP_REGNUM)
295     {
296       l = (*((long *)context_offset) >> 16) & ((1 << 11) - 1);
297       supply_register (r, (char *) &l);
298     }
299   else if (r >= 0)
300     supply_register (r, ((char *) &current_thread->context) + mappings[r]);
301   else
302     {
303       for (r = 0; r < NUM_REGS; r++)
304         do_child_fetch_inferior_registers (r);
305     }
306 }
307
308 static void
309 child_fetch_inferior_registers (int r)
310 {
311   current_thread = thread_rec (inferior_pid, TRUE);
312   do_child_fetch_inferior_registers (r);
313 }
314
315 static void
316 do_child_store_inferior_registers (int r)
317 {
318   if (r >= 0)
319     read_register_gen (r, ((char *) &current_thread->context) + mappings[r]);
320   else
321     {
322       for (r = 0; r < NUM_REGS; r++)
323         do_child_store_inferior_registers (r);
324     }
325 }
326
327 /* Store a new register value into the current thread context */
328 static void
329 child_store_inferior_registers (int r)
330 {
331   current_thread = thread_rec (inferior_pid, TRUE);
332   do_child_store_inferior_registers (r);
333 }
334
335 #include <psapi.h>
336 static int psapi_loaded = 0;
337 static HMODULE psapi_module_handle = NULL;
338 static BOOL  WINAPI (*psapi_EnumProcessModules)(HANDLE, HMODULE*, DWORD, LPDWORD)= NULL;
339 static BOOL  WINAPI (*psapi_GetModuleInformation) (HANDLE, HMODULE, LPMODULEINFO, DWORD)= NULL;
340 static DWORD WINAPI (*psapi_GetModuleFileNameExA) (HANDLE, HMODULE, LPSTR, DWORD)= NULL;
341
342 int psapi_get_dll_name (DWORD BaseAddress, char *dll_name_ret)
343 {
344   DWORD len;
345   MODULEINFO mi;
346   int i;
347   HMODULE dh_buf [ 1 ];
348   HMODULE* DllHandle = dh_buf;
349   DWORD cbNeeded;
350   BOOL ok;
351
352   if (!psapi_loaded ||
353        psapi_EnumProcessModules   == NULL ||
354        psapi_GetModuleInformation == NULL ||
355        psapi_GetModuleFileNameExA == NULL)
356     {
357       if (psapi_loaded)goto failed;
358       psapi_loaded = 1;
359       psapi_module_handle = LoadLibrary ("psapi.dll");
360       if (!psapi_module_handle)
361         {
362           /* printf_unfiltered ("error loading psapi.dll: %u", GetLastError ());*/
363           goto failed;
364         }
365       psapi_EnumProcessModules   = GetProcAddress (psapi_module_handle, "EnumProcessModules" );
366       psapi_GetModuleInformation = GetProcAddress (psapi_module_handle, "GetModuleInformation");
367       psapi_GetModuleFileNameExA = (void *) GetProcAddress (psapi_module_handle,
368                                                             "GetModuleFileNameExA");
369       if (psapi_EnumProcessModules   == NULL ||
370            psapi_GetModuleInformation == NULL ||
371            psapi_GetModuleFileNameExA == NULL)
372         goto failed;
373     }
374
375   cbNeeded = 0;
376   ok = (*psapi_EnumProcessModules) (current_process_handle,
377                                      DllHandle,
378                                      sizeof (HMODULE),
379                                      &cbNeeded);
380
381   if (!ok || !cbNeeded)
382     goto failed;
383
384   DllHandle = (HMODULE*) alloca (cbNeeded);
385   if (!DllHandle)
386     goto failed;
387
388   ok = (*psapi_EnumProcessModules) (current_process_handle,
389                                      DllHandle,
390                                      cbNeeded,
391                                      &cbNeeded);
392   if (!ok)
393     goto failed;
394
395   for (i = 0; i < cbNeeded / sizeof (HMODULE); i++)
396     {
397       if (!(*psapi_GetModuleInformation) (current_process_handle,
398                                              DllHandle [i],
399                                              &mi,
400                                              sizeof (mi)))
401         error ("Can't get module info");
402
403       len = (*psapi_GetModuleFileNameExA) (current_process_handle,
404                                             DllHandle [i],
405                                             dll_name_ret,
406                                             MAX_PATH);
407       if (len == 0)
408         error ("Error getting dll name: %u\n", GetLastError ()); 
409
410       if ((DWORD) (mi.lpBaseOfDll) == BaseAddress)
411         return 1;
412     }
413
414 failed:
415   dll_name_ret[0] = '\0';
416   return 0;
417 }
418
419 /* Wait for child to do something.  Return pid of child, or -1 in case
420    of error; store status through argument pointer OURSTATUS.  */
421
422 static int
423 handle_load_dll (PTR dummy)
424 {
425   LOAD_DLL_DEBUG_INFO *event = &current_event.u.LoadDll;
426   DWORD dll_name_ptr;
427   DWORD done;
428   char dll_buf[MAX_PATH + 1];
429   char *p, *dll_name = NULL;
430   struct objfile *objfile;
431   MEMORY_BASIC_INFORMATION minfo;
432   struct section_addr_info section_addrs;
433
434   memset (&section_addrs, 0, sizeof (section_addrs));
435   dll_buf[0] = dll_buf[sizeof (dll_buf) - 1] = '\0';
436
437   if (!psapi_get_dll_name ((DWORD) (event->lpBaseOfDll), dll_buf))
438     dll_buf[0] = dll_buf[sizeof(dll_buf) - 1] = '\0';
439
440   dll_name = dll_buf;
441
442   /* Attempt to read the name of the dll that was detected.
443      This is documented to work only when actively debugging
444      a program.  It will not work for attached processes. */
445   if (dll_name == NULL || *dll_name == '\0')
446     {
447       int size = event->fUnicode ? sizeof (WCHAR) : sizeof (char);
448       int len = 0;
449       char b[2];
450
451       ReadProcessMemory (current_process_handle,
452                          (LPCVOID) event->lpImageName,
453                          (char *) &dll_name_ptr,
454                          sizeof (dll_name_ptr), &done);
455
456       /* See if we could read the address of a string, and that the
457          address isn't null. */
458
459       if (done != sizeof (dll_name_ptr) || !dll_name_ptr)
460         return 1;
461
462       do
463         {
464           ReadProcessMemory (current_process_handle,
465                              (LPCVOID) (dll_name_ptr + len * size),
466                              &b,
467                              size,
468                              &done);
469           len++;
470         }
471       while ((b[0] != 0 || b[size - 1] != 0) && done == size);
472
473       dll_name = alloca (len);
474
475       if (event->fUnicode)
476         {
477           WCHAR *unicode_dll_name = (WCHAR *) alloca (len * sizeof (WCHAR));
478           ReadProcessMemory (current_process_handle,
479                              (LPCVOID) dll_name_ptr,
480                              unicode_dll_name,
481                              len * sizeof (WCHAR),
482                              &done);
483
484           WideCharToMultiByte (CP_ACP, 0,
485                                unicode_dll_name, len,
486                                dll_name, len, 0, 0);
487         }
488       else
489         {
490           ReadProcessMemory (current_process_handle,
491                              (LPCVOID) dll_name_ptr,
492                              dll_name,
493                              len,
494                              &done);
495         }
496     }
497
498   if (!dll_name)
499     return 1;
500
501   while ((p = strchr (dll_name, '\\')))
502     *p = '/';
503
504   /* The symbols in a dll are offset by 0x1000, which is the
505      the offset from 0 of the first byte in an image - because
506      of the file header and the section alignment.
507
508      FIXME: Is this the real reason that we need the 0x1000 ? */
509
510   printf_unfiltered ("%x:%s", event->lpBaseOfDll, dll_name);
511   section_addrs.text_addr = (int) event->lpBaseOfDll + 0x1000;
512   symbol_file_add (dll_name, 0, &section_addrs, 0, OBJF_SHARED);
513   printf_unfiltered ("\n");
514
515   return 1;
516 }
517
518 /* Handle DEBUG_STRING output from child process.
519    Cygwin prepends its messages with a "cygwin:".  Interpret this as
520    a Cygwin signal.  Otherwise just print the string as a warning. */
521 static int
522 handle_output_debug_string (struct target_waitstatus *ourstatus)
523 {
524   char *s;
525   int gotasig = FALSE;
526
527   if (!target_read_string
528     ((CORE_ADDR) current_event.u.DebugString.lpDebugStringData, &s, 1024, 0)
529       || !s || !*s)
530     return gotasig;
531
532   if (strncmp (s, CYGWIN_SIGNAL_STRING, sizeof (CYGWIN_SIGNAL_STRING) - 1))
533     {
534       if (strncmp (s, "cYg", 3))
535         warning (s);
536     }
537     {
538       char *p;
539       int sig = strtol (s + sizeof (CYGWIN_SIGNAL_STRING) - 1, &p, 0);
540       gotasig = target_signal_from_host (sig);
541       ourstatus->value.sig = gotasig;
542       if (gotasig)
543         ourstatus->kind = TARGET_WAITKIND_STOPPED;
544     }
545
546   free (s);
547   return gotasig;
548 }
549
550 static int
551 handle_exception (struct target_waitstatus *ourstatus)
552 {
553   int i;
554   int done = 0;
555   thread_info *th;
556
557   ourstatus->kind = TARGET_WAITKIND_STOPPED;
558
559   /* Record the context of the current thread */
560   th = thread_rec (current_event.dwThreadId, -1);
561
562   switch (current_event.u.Exception.ExceptionRecord.ExceptionCode)
563     {
564     case EXCEPTION_ACCESS_VIOLATION:
565       DEBUG_EXCEPT (("gdb: Target exception ACCESS_VIOLATION at 0x%08x\n",
566                current_event.u.Exception.ExceptionRecord.ExceptionAddress));
567       ourstatus->value.sig = TARGET_SIGNAL_SEGV;
568       continue_status = DBG_EXCEPTION_NOT_HANDLED;
569       break;
570     case STATUS_STACK_OVERFLOW:
571       DEBUG_EXCEPT (("gdb: Target exception STACK_OVERFLOW at 0x%08x\n",
572                current_event.u.Exception.ExceptionRecord.ExceptionAddress));
573       ourstatus->value.sig = TARGET_SIGNAL_SEGV;
574       continue_status = DBG_EXCEPTION_NOT_HANDLED;
575       break;
576     case EXCEPTION_BREAKPOINT:
577       DEBUG_EXCEPT (("gdb: Target exception BREAKPOINT at 0x%08x\n",
578                current_event.u.Exception.ExceptionRecord.ExceptionAddress));
579       ourstatus->value.sig = TARGET_SIGNAL_TRAP;
580       break;
581     case DBG_CONTROL_C:
582       DEBUG_EXCEPT (("gdb: Target exception CONTROL_C at 0x%08x\n",
583                current_event.u.Exception.ExceptionRecord.ExceptionAddress));
584       ourstatus->value.sig = TARGET_SIGNAL_INT;
585       continue_status = DBG_EXCEPTION_NOT_HANDLED;
586       break;
587     case EXCEPTION_SINGLE_STEP:
588       DEBUG_EXCEPT (("gdb: Target exception SINGLE_STEP at 0x%08x\n",
589                current_event.u.Exception.ExceptionRecord.ExceptionAddress));
590       ourstatus->value.sig = TARGET_SIGNAL_TRAP;
591       break;
592     default:
593       /* This may be a structured exception handling exception.  In
594          that case, we want to let the program try to handle it, and
595          only break if we see the exception a second time.  */
596       if (current_event.u.Exception.dwFirstChance)
597         return 0;
598
599       printf_unfiltered ("gdb: unknown target exception 0x%08x at 0x%08x\n",
600                     current_event.u.Exception.ExceptionRecord.ExceptionCode,
601                 current_event.u.Exception.ExceptionRecord.ExceptionAddress);
602       ourstatus->value.sig = TARGET_SIGNAL_UNKNOWN;
603       continue_status = DBG_EXCEPTION_NOT_HANDLED;
604       break;
605     }
606   exception_count++;
607   return 1;
608 }
609
610 /* Resume all artificially suspended threads if we are continuing
611    execution */
612 static BOOL
613 child_continue (int id)
614 {
615   int i;
616   thread_info *th;
617   BOOL res;
618
619   DEBUG_EVENTS (("ContinueDebugEvent (cpid=%d, ctid=%d, DBG_CONTINUE);\n",
620                  current_event.dwProcessId, current_event.dwThreadId));
621   res = ContinueDebugEvent (current_event.dwProcessId,
622                             current_event.dwThreadId,
623                             continue_status);
624   continue_status = 0;
625   if (res)
626     for (th = &thread_head; (th = th->next) != NULL;)
627       if (((id == -1) || (id == th->id)) && th->suspend_count)
628         {
629           for (i = 0; i < th->suspend_count; i++)
630             (void) ResumeThread (th->h);
631           th->suspend_count = 0;
632         }
633
634   return res;
635 }
636
637 static int
638 get_child_debug_event (int pid, struct target_waitstatus *ourstatus,
639                        DWORD *event_code, int *retval)
640 {
641   BOOL debug_event;
642   int breakout = 1;
643
644   if (!(debug_event = WaitForDebugEvent (&current_event, 20)))
645     {
646       breakout = *retval = *event_code = 0;
647       goto out;
648     }
649
650   event_count++;
651   continue_status = DBG_CONTINUE;
652   *retval = 0;
653
654   switch (*event_code = current_event.dwDebugEventCode)
655     {
656     case CREATE_THREAD_DEBUG_EVENT:
657       DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%x code=%s)\n",
658                     (unsigned) current_event.dwProcessId,
659                     (unsigned) current_event.dwThreadId,
660                     "CREATE_THREAD_DEBUG_EVENT"));
661       /* Record the existence of this thread */
662       child_add_thread (current_event.dwThreadId,
663                         current_event.u.CreateThread.hThread);
664       if (info_verbose)
665         printf_unfiltered ("[New %s]\n",
666                       target_pid_to_str (current_event.dwThreadId));
667       break;
668
669     case EXIT_THREAD_DEBUG_EVENT:
670       DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
671                     (unsigned) current_event.dwProcessId,
672                     (unsigned) current_event.dwThreadId,
673                     "EXIT_THREAD_DEBUG_EVENT"));
674       child_delete_thread (current_event.dwThreadId);
675       break;
676
677     case CREATE_PROCESS_DEBUG_EVENT:
678       DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
679                     (unsigned) current_event.dwProcessId,
680                     (unsigned) current_event.dwThreadId,
681                     "CREATE_PROCESS_DEBUG_EVENT"));
682       current_process_handle = current_event.u.CreateProcessInfo.hProcess;
683
684       main_thread_id = inferior_pid = current_event.dwThreadId;
685       /* Add the main thread */
686       current_thread = child_add_thread (inferior_pid,
687                          current_event.u.CreateProcessInfo.hThread);
688       break;
689
690     case EXIT_PROCESS_DEBUG_EVENT:
691       DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
692                     (unsigned) current_event.dwProcessId,
693                     (unsigned) current_event.dwThreadId,
694                     "EXIT_PROCESS_DEBUG_EVENT"));
695       ourstatus->kind = TARGET_WAITKIND_EXITED;
696       ourstatus->value.integer = current_event.u.ExitProcess.dwExitCode;
697       CloseHandle (current_process_handle);
698       *retval = current_event.dwProcessId;
699       goto out;
700
701     case LOAD_DLL_DEBUG_EVENT:
702       DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
703                     (unsigned) current_event.dwProcessId,
704                     (unsigned) current_event.dwThreadId,
705                     "LOAD_DLL_DEBUG_EVENT"));
706       catch_errors (handle_load_dll, NULL, "", RETURN_MASK_ALL);
707       registers_changed ();     /* mark all regs invalid */
708       break;
709
710     case UNLOAD_DLL_DEBUG_EVENT:
711       DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
712                     (unsigned) current_event.dwProcessId,
713                     (unsigned) current_event.dwThreadId,
714                     "UNLOAD_DLL_DEBUG_EVENT"));
715       break;            /* FIXME: don't know what to do here */
716
717     case EXCEPTION_DEBUG_EVENT:
718       DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
719                     (unsigned) current_event.dwProcessId,
720                     (unsigned) current_event.dwThreadId,
721                     "EXCEPTION_DEBUG_EVENT"));
722       if (handle_exception (ourstatus)) /* sets continue_status */
723         {
724           *retval = current_event.dwThreadId;
725           goto out;
726         }
727       break;
728
729     case OUTPUT_DEBUG_STRING_EVENT:
730       DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
731                     (unsigned) current_event.dwProcessId,
732                     (unsigned) current_event.dwThreadId,
733                     "OUTPUT_DEBUG_STRING_EVENT"));
734       if (handle_output_debug_string (ourstatus))
735         {
736           *retval = main_thread_id;
737           goto out;
738         }
739       break;
740     default:
741       printf_unfiltered ("gdb: kernel event for pid=%d tid=%d\n",
742                          current_event.dwProcessId,
743                          current_event.dwThreadId);
744       printf_unfiltered ("                 unknown event code %d\n",
745                          current_event.dwDebugEventCode);
746       break;
747     }
748
749   breakout = 0;
750   CHECK (child_continue (-1));
751   continue_status = 0;
752
753 out:
754   return breakout;
755 }
756
757
758 /* Wait for interesting events to occur in the target process. */
759 static int
760 child_wait (int pid, struct target_waitstatus *ourstatus)
761 {
762   DWORD event_code;
763   int retval;
764
765   /* We loop when we get a non-standard exception rather than return
766      with a SPURIOUS because resume can try and step or modify things,
767      which needs a current_thread->h.  But some of these exceptions mark
768      the birth or death of threads, which mean that the current thread
769      isn't necessarily what you think it is. */
770
771   while (1)
772     {
773       if (continue_status != 0)
774         CHECK (child_continue (-1));
775       if (get_child_debug_event (pid, ourstatus, &event_code, &retval))
776         return retval;
777       else
778         {
779           int detach = 0;
780
781           if (ui_loop_hook != NULL)
782             detach = ui_loop_hook (0);
783
784           if (detach)
785             child_kill_inferior ();
786         }
787     }
788 }
789
790 /* Attach to process PID, then initialize for debugging it.  */
791
792 static void
793 child_attach (args, from_tty)
794      char *args;
795      int from_tty;
796 {
797   BOOL ok;
798
799   if (!args)
800     error_no_arg ("process-id to attach");
801
802   current_event.dwProcessId = strtoul (args, 0, 0);
803
804   ok = DebugActiveProcess (current_event.dwProcessId);
805
806   if (!ok)
807     error ("Can't attach to process.");
808
809   exception_count = 0;
810   event_count = 0;
811
812   if (from_tty)
813     {
814       char *exec_file = (char *) get_exec_file (0);
815
816       if (exec_file)
817         printf_unfiltered ("Attaching to program `%s', %s\n", exec_file,
818                            target_pid_to_str (current_event.dwProcessId));
819       else
820         printf_unfiltered ("Attaching to %s\n",
821                            target_pid_to_str (current_event.dwProcessId));
822
823       gdb_flush (gdb_stdout);
824     }
825
826   push_target (&child_ops);
827 }
828
829 static void
830 child_detach (args, from_tty)
831      char *args;
832      int from_tty;
833 {
834   if (from_tty)
835     {
836       char *exec_file = get_exec_file (0);
837       if (exec_file == 0)
838         exec_file = "";
839       printf_unfiltered ("Detaching from program: %s %s\n", exec_file,
840                          target_pid_to_str (inferior_pid));
841       gdb_flush (gdb_stdout);
842     }
843   inferior_pid = 0;
844   unpush_target (&child_ops);
845 }
846
847 /* Print status information about what we're accessing.  */
848
849 static void
850 child_files_info (ignore)
851      struct target_ops *ignore;
852 {
853   printf_unfiltered ("\tUsing the running image of %s %s.\n",
854       attach_flag ? "attached" : "child", target_pid_to_str (inferior_pid));
855 }
856
857 /* ARGSUSED */
858 static void
859 child_open (arg, from_tty)
860      char *arg;
861      int from_tty;
862 {
863   error ("Use the \"run\" command to start a Unix child process.");
864 }
865
866 /* Start an inferior win32 child process and sets inferior_pid to its pid.
867    EXEC_FILE is the file to run.
868    ALLARGS is a string containing the arguments to the program.
869    ENV is the environment vector to pass.  Errors reported with error().  */
870
871 static void
872 child_create_inferior (exec_file, allargs, env)
873      char *exec_file;
874      char *allargs;
875      char **env;
876 {
877   char real_path[MAXPATHLEN];
878   char *winenv;
879   char *temp;
880   int envlen;
881   int i;
882   STARTUPINFO si;
883   PROCESS_INFORMATION pi;
884   struct target_waitstatus dummy;
885   BOOL ret;
886   DWORD flags;
887   char *args;
888   DWORD event_code;
889
890   if (!exec_file)
891     {
892       error ("No executable specified, use `target exec'.\n");
893     }
894
895   memset (&si, 0, sizeof (si));
896   si.cb = sizeof (si);
897
898   cygwin32_conv_to_win32_path (exec_file, real_path);
899
900   flags = DEBUG_ONLY_THIS_PROCESS;
901
902   if (new_group)
903     flags |= CREATE_NEW_PROCESS_GROUP;
904
905   if (new_console)
906     flags |= CREATE_NEW_CONSOLE;
907
908   args = alloca (strlen (real_path) + strlen (allargs) + 2);
909
910   strcpy (args, real_path);
911
912   strcat (args, " ");
913   strcat (args, allargs);
914
915   /* Prepare the environment vars for CreateProcess.  */
916   {
917     /* This code use to assume all env vars were file names and would
918        translate them all to win32 style.  That obviously doesn't work in the
919        general case.  The current rule is that we only translate PATH.
920        We need to handle PATH because we're about to call CreateProcess and
921        it uses PATH to find DLL's.  Fortunately PATH has a well-defined value
922        in both posix and win32 environments.  cygwin.dll will change it back
923        to posix style if necessary.  */
924
925     static const char *conv_path_names[] =
926     {
927       "PATH=",
928       0
929     };
930
931     /* CreateProcess takes the environment list as a null terminated set of
932        strings (i.e. two nulls terminate the list).  */
933
934     /* Get total size for env strings.  */
935     for (envlen = 0, i = 0; env[i] && *env[i]; i++)
936       {
937         int j, len;
938
939         for (j = 0; conv_path_names[j]; j++)
940           {
941             len = strlen (conv_path_names[j]);
942             if (strncmp (conv_path_names[j], env[i], len) == 0)
943               {
944                 if (cygwin32_posix_path_list_p (env[i] + len))
945                   envlen += len
946                     + cygwin32_posix_to_win32_path_list_buf_size (env[i] + len);
947                 else
948                   envlen += strlen (env[i]) + 1;
949                 break;
950               }
951           }
952         if (conv_path_names[j] == NULL)
953           envlen += strlen (env[i]) + 1;
954       }
955
956     winenv = alloca (envlen + 1);
957
958     /* Copy env strings into new buffer.  */
959     for (temp = winenv, i = 0; env[i] && *env[i]; i++)
960       {
961         int j, len;
962
963         for (j = 0; conv_path_names[j]; j++)
964           {
965             len = strlen (conv_path_names[j]);
966             if (strncmp (conv_path_names[j], env[i], len) == 0)
967               {
968                 if (cygwin32_posix_path_list_p (env[i] + len))
969                   {
970                     memcpy (temp, env[i], len);
971                     cygwin32_posix_to_win32_path_list (env[i] + len, temp + len);
972                   }
973                 else
974                   strcpy (temp, env[i]);
975                 break;
976               }
977           }
978         if (conv_path_names[j] == NULL)
979           strcpy (temp, env[i]);
980
981         temp += strlen (temp) + 1;
982       }
983
984     /* Final nil string to terminate new env.  */
985     *temp = 0;
986   }
987
988   ret = CreateProcess (0,
989                        args,    /* command line */
990                        NULL,    /* Security */
991                        NULL,    /* thread */
992                        TRUE,    /* inherit handles */
993                        flags,   /* start flags */
994                        winenv,
995                        NULL,    /* current directory */
996                        &si,
997                        &pi);
998   if (!ret)
999     error ("Error creating process %s, (error %d)\n", exec_file, GetLastError ());
1000
1001   exception_count = 0;
1002   event_count = 0;
1003
1004   current_process_handle = pi.hProcess;
1005   current_event.dwProcessId = pi.dwProcessId;
1006   memset (&current_event, 0, sizeof (current_event));
1007   inferior_pid = current_event.dwThreadId = pi.dwThreadId;
1008   push_target (&child_ops);
1009   child_init_thread_list ();
1010   init_wait_for_inferior ();
1011   clear_proceed_status ();
1012   target_terminal_init ();
1013   target_terminal_inferior ();
1014
1015   /* Run until process and threads are loaded */
1016   do
1017     get_child_debug_event (inferior_pid, &dummy, &event_code, &ret);
1018   while (event_code != EXCEPTION_DEBUG_EVENT);
1019
1020   proceed ((CORE_ADDR) - 1, TARGET_SIGNAL_0, 0);
1021 }
1022
1023 static void
1024 child_mourn_inferior ()
1025 {
1026   continue_status = DBG_CONTINUE;
1027   (void) child_continue (-1);
1028   unpush_target (&child_ops);
1029   generic_mourn_inferior ();
1030 }
1031
1032 /* Send a SIGINT to the process group.  This acts just like the user typed a
1033    ^C on the controlling terminal. */
1034
1035 static void
1036 child_stop ()
1037 {
1038   DEBUG_EVENTS (("gdb: GenerateConsoleCtrlEvent (CTRLC_EVENT, 0)\n"));
1039   CHECK (GenerateConsoleCtrlEvent (CTRL_C_EVENT, current_event.dwProcessId));
1040   registers_changed ();         /* refresh register state */
1041 }
1042
1043 int
1044 child_xfer_memory (CORE_ADDR memaddr, char *our, int len,
1045                    int write, struct target_ops *target)
1046 {
1047   DWORD done;
1048   if (write)
1049     {
1050       DEBUG_MEM (("gdb: write target memory, %d bytes at 0x%08x\n",
1051                   len, memaddr));
1052       WriteProcessMemory (current_process_handle, (LPVOID) memaddr, our,
1053                           len, &done);
1054       FlushInstructionCache (current_process_handle, (LPCVOID) memaddr, len);
1055     }
1056   else
1057     {
1058       DEBUG_MEM (("gdb: read target memory, %d bytes at 0x%08x\n",
1059                   len, memaddr));
1060       ReadProcessMemory (current_process_handle, (LPCVOID) memaddr, our, len,
1061                          &done);
1062     }
1063   return done;
1064 }
1065
1066 void
1067 child_kill_inferior (void)
1068 {
1069   CHECK (TerminateProcess (current_process_handle, 0));
1070
1071   for (;;)
1072     {
1073       continue_status = DBG_CONTINUE;
1074       if (!child_continue (-1))
1075         break;
1076       if (!WaitForDebugEvent (&current_event, INFINITE))
1077         break;
1078       if (current_event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
1079         break;
1080     }
1081
1082   CHECK (CloseHandle (current_process_handle));
1083
1084   /* this may fail in an attached process so don't check. */
1085   (void) CloseHandle (current_thread->h);
1086   target_mourn_inferior ();     /* or just child_mourn_inferior? */
1087 }
1088
1089 void
1090 child_resume (int pid, int step, enum target_signal sig)
1091 {
1092   int i;
1093   thread_info *th;
1094
1095   DEBUG_EXEC (("gdb: child_resume (pid=%d, step=%d, sig=%d);\n",
1096                pid, step, sig));
1097
1098   /* Get context for currently selected thread */
1099   th = thread_rec (current_event.dwThreadId, FALSE);
1100   if (step)
1101     {
1102 #ifdef i386
1103       /* Single step by setting t bit */
1104       child_fetch_inferior_registers (PS_REGNUM);
1105       th->context.EFlags |= FLAG_TRACE_BIT;
1106 #endif
1107     }
1108
1109   if (th->context.ContextFlags)
1110     {
1111       CHECK (SetThreadContext (th->h, &th->context));
1112       th->context.ContextFlags = 0;
1113     }
1114
1115   /* Allow continuing with the same signal that interrupted us.
1116      Otherwise complain. */
1117
1118   child_continue (pid);
1119 }
1120
1121 static void
1122 child_prepare_to_store ()
1123 {
1124   /* Do nothing, since we can store individual regs */
1125 }
1126
1127 static int
1128 child_can_run ()
1129 {
1130   return 1;
1131 }
1132
1133 static void
1134 child_close ()
1135 {
1136   DEBUG_EVENTS (("gdb: child_close, inferior_pid=%d\n", inferior_pid));
1137 }
1138
1139 struct target_ops child_ops;
1140
1141 static void
1142 init_child_ops (void)
1143 {
1144   child_ops.to_shortname = "child";
1145   child_ops.to_longname = "Win32 child process";
1146   child_ops.to_doc = "Win32 child process (started by the \"run\" command).";
1147   child_ops.to_open = child_open;
1148   child_ops.to_close = child_close;
1149   child_ops.to_attach = child_attach;
1150   child_ops.to_detach = child_detach;
1151   child_ops.to_resume = child_resume;
1152   child_ops.to_wait = child_wait;
1153   child_ops.to_fetch_registers = child_fetch_inferior_registers;
1154   child_ops.to_store_registers = child_store_inferior_registers;
1155   child_ops.to_prepare_to_store = child_prepare_to_store;
1156   child_ops.to_xfer_memory = child_xfer_memory;
1157   child_ops.to_files_info = child_files_info;
1158   child_ops.to_insert_breakpoint = memory_insert_breakpoint;
1159   child_ops.to_remove_breakpoint = memory_remove_breakpoint;
1160   child_ops.to_terminal_init = terminal_init_inferior;
1161   child_ops.to_terminal_inferior = terminal_inferior;
1162   child_ops.to_terminal_ours_for_output = terminal_ours_for_output;
1163   child_ops.to_terminal_ours = terminal_ours;
1164   child_ops.to_terminal_info = child_terminal_info;
1165   child_ops.to_kill = child_kill_inferior;
1166   child_ops.to_load = 0;
1167   child_ops.to_lookup_symbol = 0;
1168   child_ops.to_create_inferior = child_create_inferior;
1169   child_ops.to_mourn_inferior = child_mourn_inferior;
1170   child_ops.to_can_run = child_can_run;
1171   child_ops.to_notice_signals = 0;
1172   child_ops.to_thread_alive = win32_child_thread_alive;
1173   child_ops.to_stop = child_stop;
1174   child_ops.to_stratum = process_stratum;
1175   child_ops.DONT_USE = 0;
1176   child_ops.to_has_all_memory = 1;
1177   child_ops.to_has_memory = 1;
1178   child_ops.to_has_stack = 1;
1179   child_ops.to_has_registers = 1;
1180   child_ops.to_has_execution = 1;
1181   child_ops.to_sections = 0;
1182   child_ops.to_sections_end = 0;
1183   child_ops.to_magic = OPS_MAGIC;
1184 }
1185
1186 void
1187 _initialize_inftarg ()
1188 {
1189   struct cmd_list_element *c;
1190   init_child_ops ();
1191
1192   add_show_from_set
1193     (add_set_cmd ("new-console", class_support, var_boolean,
1194                   (char *) &new_console,
1195                   "Set creation of new console when creating child process.",
1196                   &setlist),
1197      &showlist);
1198
1199   add_show_from_set
1200     (add_set_cmd ("new-group", class_support, var_boolean,
1201                   (char *) &new_group,
1202                   "Set creation of new group when creating child process.",
1203                   &setlist),
1204      &showlist);
1205
1206   add_show_from_set
1207     (add_set_cmd ("debugexec", class_support, var_boolean,
1208                   (char *) &debug_exec,
1209                   "Set whether to display execution in child process.",
1210                   &setlist),
1211      &showlist);
1212
1213   add_show_from_set
1214     (add_set_cmd ("debugevents", class_support, var_boolean,
1215                   (char *) &debug_events,
1216                   "Set whether to display kernel events in child process.",
1217                   &setlist),
1218      &showlist);
1219
1220   add_show_from_set
1221     (add_set_cmd ("debugmemory", class_support, var_boolean,
1222                   (char *) &debug_memory,
1223                   "Set whether to display memory accesses in child process.",
1224                   &setlist),
1225      &showlist);
1226
1227   add_show_from_set
1228     (add_set_cmd ("debugexceptions", class_support, var_boolean,
1229                   (char *) &debug_exceptions,
1230                "Set whether to display kernel exceptions in child process.",
1231                   &setlist),
1232      &showlist);
1233
1234   add_target (&child_ops);
1235 }
1236
1237 /* Determine if the thread referenced by "pid" is alive
1238    by "polling" it.  If WaitForSingleObject returns WAIT_OBJECT_0
1239    it means that the pid has died.  Otherwise it is assumed to be alive. */
1240 static int
1241 win32_child_thread_alive (int pid)
1242 {
1243   return WaitForSingleObject (thread_rec (pid, FALSE)->h, 0) == WAIT_OBJECT_0 ?
1244     FALSE : TRUE;
1245 }
1246
1247 /* Convert pid to printable format. */
1248 char *
1249 cygwin_pid_to_str (int pid)
1250 {
1251   static char buf[80];
1252   if (pid == current_event.dwProcessId)
1253     sprintf (buf, "process %d", pid);
1254   else
1255     sprintf (buf, "thread %d.0x%x", current_event.dwProcessId, pid);
1256   return buf;
1257 }
1258 #ifdef NOTYET
1259 CORE_ADDR
1260 win32_read_fp ()
1261 {
1262   STACKFRAME *sf = current_thread->sf;
1263   
1264   memset (&sf, 0, sizeof(sf));
1265   sf->AddrPC.Offset = current_thread->context.Eip;
1266   sf->AddrPC.Mode = AddrModeFlat;
1267   sf->AddrStack.Offset = current_thread->context.Esp;
1268   sf->AddrStack.Mode = AddrModeFlat;
1269   sf->AddrFrame.Offset = current_thread->context.Ebp;
1270   if (!StackWalk (IMAGE_FILE_MACHINE_I386, current_process_handle,
1271                   current->thread->h, sf, NULL, NULL,
1272                   SymFunctionTableAccess, SymGetModuleBase, NULL))
1273     return NULL;
1274   return (CORE_ADDR) sf.AddrFrame.Offset;
1275 }
1276
1277 CORE_ADDR
1278 child_frame_chain(struct frame_info *thisframe)
1279 {
1280   STACKFRAME *sf = current->thread->sf;
1281 #if 0
1282   sf.AddrPC.Offset = thisframe->pc;
1283   sf.AddrPC.Mode = AddrModeFlat;
1284   sf.AddrStack.Offset = thisframe->;
1285   sf.AddrStack.Mode = AddrModeFlat;
1286   sf.AddrFrame.Offset = cx->Ebp;
1287 #endif
1288   if (!StackWalk (IMAGE_FILE_MACHINE_I386, current_process_handle,
1289                   current->thread->h, &sf, NULL, NULL,
1290                   SymFunctionTableAccess, SymGetModuleBase, NULL))
1291     return NULL;
1292   return (CORE_ADDR) sf->AddrFrame.Offset;
1293 }
1294 #endif