* win32-low.c (win32_add_one_solib): If the dll name is
[deliverable/binutils-gdb.git] / gdb / gdbserver / win32-low.c
1 /* Low level interface to Windows debugging, for gdbserver.
2 Copyright (C) 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
3
4 Contributed by Leo Zayas. Based on "win32-nat.c" from GDB.
5
6 This file is part of GDB.
7
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or
11 (at your option) any later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20
21 #include "server.h"
22 #include "regcache.h"
23 #include "gdb/signals.h"
24 #include "gdb/fileio.h"
25 #include "mem-break.h"
26 #include "win32-low.h"
27
28 #include <windows.h>
29 #include <winnt.h>
30 #include <imagehlp.h>
31 #include <tlhelp32.h>
32 #include <psapi.h>
33 #include <sys/param.h>
34 #include <malloc.h>
35 #include <process.h>
36
37 #ifndef USE_WIN32API
38 #include <sys/cygwin.h>
39 #endif
40
41 #define LOG 0
42
43 #define OUTMSG(X) do { printf X; fflush (stdout); } while (0)
44 #if LOG
45 #define OUTMSG2(X) do { printf X; fflush (stdout); } while (0)
46 #else
47 #define OUTMSG2(X) do ; while (0)
48 #endif
49
50 #ifndef _T
51 #define _T(x) TEXT (x)
52 #endif
53
54 #ifndef COUNTOF
55 #define COUNTOF(STR) (sizeof (STR) / sizeof ((STR)[0]))
56 #endif
57
58 #ifdef _WIN32_WCE
59 # define GETPROCADDRESS(DLL, PROC) \
60 ((winapi_ ## PROC) GetProcAddress (DLL, TEXT (#PROC)))
61 #else
62 # define GETPROCADDRESS(DLL, PROC) \
63 ((winapi_ ## PROC) GetProcAddress (DLL, #PROC))
64 #endif
65
66 int using_threads = 1;
67
68 /* Globals. */
69 static int attaching = 0;
70 static HANDLE current_process_handle = NULL;
71 static DWORD current_process_id = 0;
72 static DWORD main_thread_id = 0;
73 static enum target_signal last_sig = TARGET_SIGNAL_0;
74
75 /* The current debug event from WaitForDebugEvent. */
76 static DEBUG_EVENT current_event;
77
78 /* Non zero if an interrupt request is to be satisfied by suspending
79 all threads. */
80 static int soft_interrupt_requested = 0;
81
82 /* Non zero if the inferior is stopped in a simulated breakpoint done
83 by suspending all the threads. */
84 static int faked_breakpoint = 0;
85
86 #define NUM_REGS (the_low_target.num_regs)
87
88 typedef BOOL WINAPI (*winapi_DebugActiveProcessStop) (DWORD dwProcessId);
89 typedef BOOL WINAPI (*winapi_DebugSetProcessKillOnExit) (BOOL KillOnExit);
90 typedef BOOL WINAPI (*winapi_DebugBreakProcess) (HANDLE);
91 typedef BOOL WINAPI (*winapi_GenerateConsoleCtrlEvent) (DWORD, DWORD);
92
93 static void win32_resume (struct thread_resume *resume_info, size_t n);
94
95 /* Get the thread ID from the current selected inferior (the current
96 thread). */
97 static ptid_t
98 current_inferior_ptid (void)
99 {
100 return ((struct inferior_list_entry*) current_inferior)->id;
101 }
102
103 /* The current debug event from WaitForDebugEvent. */
104 static ptid_t
105 debug_event_ptid (DEBUG_EVENT *event)
106 {
107 return ptid_build (event->dwProcessId, event->dwThreadId, 0);
108 }
109
110 /* Get the thread context of the thread associated with TH. */
111
112 static void
113 win32_get_thread_context (win32_thread_info *th)
114 {
115 memset (&th->context, 0, sizeof (CONTEXT));
116 (*the_low_target.get_thread_context) (th, &current_event);
117 #ifdef _WIN32_WCE
118 memcpy (&th->base_context, &th->context, sizeof (CONTEXT));
119 #endif
120 }
121
122 /* Set the thread context of the thread associated with TH. */
123
124 static void
125 win32_set_thread_context (win32_thread_info *th)
126 {
127 #ifdef _WIN32_WCE
128 /* Calling SuspendThread on a thread that is running kernel code
129 will report that the suspending was successful, but in fact, that
130 will often not be true. In those cases, the context returned by
131 GetThreadContext will not be correct by the time the thread
132 stops, hence we can't set that context back into the thread when
133 resuming - it will most likelly crash the inferior.
134 Unfortunately, there is no way to know when the thread will
135 really stop. To work around it, we'll only write the context
136 back to the thread when either the user or GDB explicitly change
137 it between stopping and resuming. */
138 if (memcmp (&th->context, &th->base_context, sizeof (CONTEXT)) != 0)
139 #endif
140 (*the_low_target.set_thread_context) (th, &current_event);
141 }
142
143 /* Find a thread record given a thread id. If GET_CONTEXT is set then
144 also retrieve the context for this thread. */
145 static win32_thread_info *
146 thread_rec (ptid_t ptid, int get_context)
147 {
148 struct thread_info *thread;
149 win32_thread_info *th;
150
151 thread = (struct thread_info *) find_inferior_id (&all_threads, ptid);
152 if (thread == NULL)
153 return NULL;
154
155 th = inferior_target_data (thread);
156 if (get_context && th->context.ContextFlags == 0)
157 {
158 if (!th->suspended)
159 {
160 if (SuspendThread (th->h) == (DWORD) -1)
161 {
162 DWORD err = GetLastError ();
163 OUTMSG (("warning: SuspendThread failed in thread_rec, "
164 "(error %d): %s\n", (int) err, strwinerror (err)));
165 }
166 else
167 th->suspended = 1;
168 }
169
170 win32_get_thread_context (th);
171 }
172
173 return th;
174 }
175
176 /* Add a thread to the thread list. */
177 static win32_thread_info *
178 child_add_thread (DWORD pid, DWORD tid, HANDLE h)
179 {
180 win32_thread_info *th;
181 ptid_t ptid = ptid_build (pid, tid, 0);
182
183 if ((th = thread_rec (ptid, FALSE)))
184 return th;
185
186 th = xcalloc (1, sizeof (*th));
187 th->tid = tid;
188 th->h = h;
189
190 add_thread (ptid, th);
191 set_inferior_regcache_data ((struct thread_info *)
192 find_inferior_id (&all_threads, ptid),
193 new_register_cache ());
194
195 if (the_low_target.thread_added != NULL)
196 (*the_low_target.thread_added) (th);
197
198 return th;
199 }
200
201 /* Delete a thread from the list of threads. */
202 static void
203 delete_thread_info (struct inferior_list_entry *thread)
204 {
205 win32_thread_info *th = inferior_target_data ((struct thread_info *) thread);
206
207 remove_thread ((struct thread_info *) thread);
208 CloseHandle (th->h);
209 free (th);
210 }
211
212 /* Delete a thread from the list of threads. */
213 static void
214 child_delete_thread (DWORD pid, DWORD tid)
215 {
216 struct inferior_list_entry *thread;
217 ptid_t ptid;
218
219 /* If the last thread is exiting, just return. */
220 if (all_threads.head == all_threads.tail)
221 return;
222
223 ptid = ptid_build (pid, tid, 0);
224 thread = find_inferior_id (&all_threads, ptid);
225 if (thread == NULL)
226 return;
227
228 delete_thread_info (thread);
229 }
230
231 /* These watchpoint related wrapper functions simply pass on the function call
232 if the low target has registered a corresponding function. */
233
234 static int
235 win32_insert_point (char type, CORE_ADDR addr, int len)
236 {
237 if (the_low_target.insert_point != NULL)
238 return the_low_target.insert_point (type, addr, len);
239 else
240 /* Unsupported (see target.h). */
241 return 1;
242 }
243
244 static int
245 win32_remove_point (char type, CORE_ADDR addr, int len)
246 {
247 if (the_low_target.remove_point != NULL)
248 return the_low_target.remove_point (type, addr, len);
249 else
250 /* Unsupported (see target.h). */
251 return 1;
252 }
253
254 static int
255 win32_stopped_by_watchpoint (void)
256 {
257 if (the_low_target.stopped_by_watchpoint != NULL)
258 return the_low_target.stopped_by_watchpoint ();
259 else
260 return 0;
261 }
262
263 static CORE_ADDR
264 win32_stopped_data_address (void)
265 {
266 if (the_low_target.stopped_data_address != NULL)
267 return the_low_target.stopped_data_address ();
268 else
269 return 0;
270 }
271
272
273 /* Transfer memory from/to the debugged process. */
274 static int
275 child_xfer_memory (CORE_ADDR memaddr, char *our, int len,
276 int write, struct target_ops *target)
277 {
278 SIZE_T done;
279 long addr = (long) memaddr;
280
281 if (write)
282 {
283 WriteProcessMemory (current_process_handle, (LPVOID) addr,
284 (LPCVOID) our, len, &done);
285 FlushInstructionCache (current_process_handle, (LPCVOID) addr, len);
286 }
287 else
288 {
289 ReadProcessMemory (current_process_handle, (LPCVOID) addr, (LPVOID) our,
290 len, &done);
291 }
292 return done;
293 }
294
295 /* Clear out any old thread list and reinitialize it to a pristine
296 state. */
297 static void
298 child_init_thread_list (void)
299 {
300 for_each_inferior (&all_threads, delete_thread_info);
301 }
302
303 static void
304 do_initial_child_stuff (HANDLE proch, DWORD pid, int attached)
305 {
306 last_sig = TARGET_SIGNAL_0;
307
308 current_process_handle = proch;
309 current_process_id = pid;
310 main_thread_id = 0;
311
312 soft_interrupt_requested = 0;
313 faked_breakpoint = 0;
314
315 memset (&current_event, 0, sizeof (current_event));
316
317 add_process (pid, attached);
318 child_init_thread_list ();
319
320 if (the_low_target.initial_stuff != NULL)
321 (*the_low_target.initial_stuff) ();
322 }
323
324 /* Resume all artificially suspended threads if we are continuing
325 execution. */
326 static int
327 continue_one_thread (struct inferior_list_entry *this_thread, void *id_ptr)
328 {
329 struct thread_info *thread = (struct thread_info *) this_thread;
330 int thread_id = * (int *) id_ptr;
331 win32_thread_info *th = inferior_target_data (thread);
332
333 if ((thread_id == -1 || thread_id == th->tid)
334 && th->suspended)
335 {
336 if (th->context.ContextFlags)
337 {
338 win32_set_thread_context (th);
339 th->context.ContextFlags = 0;
340 }
341
342 if (ResumeThread (th->h) == (DWORD) -1)
343 {
344 DWORD err = GetLastError ();
345 OUTMSG (("warning: ResumeThread failed in continue_one_thread, "
346 "(error %d): %s\n", (int) err, strwinerror (err)));
347 }
348 th->suspended = 0;
349 }
350
351 return 0;
352 }
353
354 static BOOL
355 child_continue (DWORD continue_status, int thread_id)
356 {
357 /* The inferior will only continue after the ContinueDebugEvent
358 call. */
359 find_inferior (&all_threads, continue_one_thread, &thread_id);
360 faked_breakpoint = 0;
361
362 if (!ContinueDebugEvent (current_event.dwProcessId,
363 current_event.dwThreadId,
364 continue_status))
365 return FALSE;
366
367 return TRUE;
368 }
369
370 /* Fetch register(s) from the current thread context. */
371 static void
372 child_fetch_inferior_registers (int r)
373 {
374 int regno;
375 win32_thread_info *th = thread_rec (current_inferior_ptid (), TRUE);
376 if (r == -1 || r > NUM_REGS)
377 child_fetch_inferior_registers (NUM_REGS);
378 else
379 for (regno = 0; regno < r; regno++)
380 (*the_low_target.fetch_inferior_register) (th, regno);
381 }
382
383 /* Store a new register value into the current thread context. We don't
384 change the program's context until later, when we resume it. */
385 static void
386 child_store_inferior_registers (int r)
387 {
388 int regno;
389 win32_thread_info *th = thread_rec (current_inferior_ptid (), TRUE);
390 if (r == -1 || r == 0 || r > NUM_REGS)
391 child_store_inferior_registers (NUM_REGS);
392 else
393 for (regno = 0; regno < r; regno++)
394 (*the_low_target.store_inferior_register) (th, regno);
395 }
396
397 /* Map the Windows error number in ERROR to a locale-dependent error
398 message string and return a pointer to it. Typically, the values
399 for ERROR come from GetLastError.
400
401 The string pointed to shall not be modified by the application,
402 but may be overwritten by a subsequent call to strwinerror
403
404 The strwinerror function does not change the current setting
405 of GetLastError. */
406
407 char *
408 strwinerror (DWORD error)
409 {
410 static char buf[1024];
411 TCHAR *msgbuf;
412 DWORD lasterr = GetLastError ();
413 DWORD chars = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
414 | FORMAT_MESSAGE_ALLOCATE_BUFFER,
415 NULL,
416 error,
417 0, /* Default language */
418 (LPVOID)&msgbuf,
419 0,
420 NULL);
421 if (chars != 0)
422 {
423 /* If there is an \r\n appended, zap it. */
424 if (chars >= 2
425 && msgbuf[chars - 2] == '\r'
426 && msgbuf[chars - 1] == '\n')
427 {
428 chars -= 2;
429 msgbuf[chars] = 0;
430 }
431
432 if (chars > ((COUNTOF (buf)) - 1))
433 {
434 chars = COUNTOF (buf) - 1;
435 msgbuf [chars] = 0;
436 }
437
438 #ifdef UNICODE
439 wcstombs (buf, msgbuf, chars + 1);
440 #else
441 strncpy (buf, msgbuf, chars + 1);
442 #endif
443 LocalFree (msgbuf);
444 }
445 else
446 sprintf (buf, "unknown win32 error (%ld)", error);
447
448 SetLastError (lasterr);
449 return buf;
450 }
451
452 static BOOL
453 create_process (const char *program, char *args,
454 DWORD flags, PROCESS_INFORMATION *pi)
455 {
456 BOOL ret;
457
458 #ifdef _WIN32_WCE
459 wchar_t *p, *wprogram, *wargs;
460 size_t argslen;
461
462 wprogram = alloca ((strlen (program) + 1) * sizeof (wchar_t));
463 mbstowcs (wprogram, program, strlen (program) + 1);
464
465 for (p = wprogram; *p; ++p)
466 if (L'/' == *p)
467 *p = L'\\';
468
469 argslen = strlen (args);
470 wargs = alloca ((argslen + 1) * sizeof (wchar_t));
471 mbstowcs (wargs, args, argslen + 1);
472
473 ret = CreateProcessW (wprogram, /* image name */
474 wargs, /* command line */
475 NULL, /* security, not supported */
476 NULL, /* thread, not supported */
477 FALSE, /* inherit handles, not supported */
478 flags, /* start flags */
479 NULL, /* environment, not supported */
480 NULL, /* current directory, not supported */
481 NULL, /* start info, not supported */
482 pi); /* proc info */
483 #else
484 STARTUPINFOA si = { sizeof (STARTUPINFOA) };
485
486 ret = CreateProcessA (program, /* image name */
487 args, /* command line */
488 NULL, /* security */
489 NULL, /* thread */
490 TRUE, /* inherit handles */
491 flags, /* start flags */
492 NULL, /* environment */
493 NULL, /* current directory */
494 &si, /* start info */
495 pi); /* proc info */
496 #endif
497
498 return ret;
499 }
500
501 /* Start a new process.
502 PROGRAM is a path to the program to execute.
503 ARGS is a standard NULL-terminated array of arguments,
504 to be passed to the inferior as ``argv''.
505 Returns the new PID on success, -1 on failure. Registers the new
506 process with the process list. */
507 static int
508 win32_create_inferior (char *program, char **program_args)
509 {
510 #ifndef USE_WIN32API
511 char real_path[MAXPATHLEN];
512 char *orig_path, *new_path, *path_ptr;
513 #endif
514 BOOL ret;
515 DWORD flags;
516 char *args;
517 int argslen;
518 int argc;
519 PROCESS_INFORMATION pi;
520 DWORD err;
521
522 /* win32_wait needs to know we're not attaching. */
523 attaching = 0;
524
525 if (!program)
526 error ("No executable specified, specify executable to debug.\n");
527
528 flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS;
529
530 #ifndef USE_WIN32API
531 orig_path = NULL;
532 path_ptr = getenv ("PATH");
533 if (path_ptr)
534 {
535 orig_path = alloca (strlen (path_ptr) + 1);
536 new_path = alloca (cygwin_posix_to_win32_path_list_buf_size (path_ptr));
537 strcpy (orig_path, path_ptr);
538 cygwin_posix_to_win32_path_list (path_ptr, new_path);
539 setenv ("PATH", new_path, 1);
540 }
541 cygwin_conv_to_win32_path (program, real_path);
542 program = real_path;
543 #endif
544
545 argslen = 1;
546 for (argc = 1; program_args[argc]; argc++)
547 argslen += strlen (program_args[argc]) + 1;
548 args = alloca (argslen);
549 args[0] = '\0';
550 for (argc = 1; program_args[argc]; argc++)
551 {
552 /* FIXME: Can we do better about quoting? How does Cygwin
553 handle this? */
554 strcat (args, " ");
555 strcat (args, program_args[argc]);
556 }
557 OUTMSG2 (("Command line is \"%s\"\n", args));
558
559 #ifdef CREATE_NEW_PROCESS_GROUP
560 flags |= CREATE_NEW_PROCESS_GROUP;
561 #endif
562
563 ret = create_process (program, args, flags, &pi);
564 err = GetLastError ();
565 if (!ret && err == ERROR_FILE_NOT_FOUND)
566 {
567 char *exename = alloca (strlen (program) + 5);
568 strcat (strcpy (exename, program), ".exe");
569 ret = create_process (exename, args, flags, &pi);
570 err = GetLastError ();
571 }
572
573 #ifndef USE_WIN32API
574 if (orig_path)
575 setenv ("PATH", orig_path, 1);
576 #endif
577
578 if (!ret)
579 {
580 error ("Error creating process \"%s%s\", (error %d): %s\n",
581 program, args, (int) err, strwinerror (err));
582 }
583 else
584 {
585 OUTMSG2 (("Process created: %s\n", (char *) args));
586 }
587
588 #ifndef _WIN32_WCE
589 /* On Windows CE this handle can't be closed. The OS reuses
590 it in the debug events, while the 9x/NT versions of Windows
591 probably use a DuplicateHandle'd one. */
592 CloseHandle (pi.hThread);
593 #endif
594
595 do_initial_child_stuff (pi.hProcess, pi.dwProcessId, 0);
596
597 return current_process_id;
598 }
599
600 /* Attach to a running process.
601 PID is the process ID to attach to, specified by the user
602 or a higher layer. */
603 static int
604 win32_attach (unsigned long pid)
605 {
606 HANDLE h;
607 winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit = NULL;
608 DWORD err;
609 #ifdef _WIN32_WCE
610 HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
611 #else
612 HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
613 #endif
614 DebugSetProcessKillOnExit = GETPROCADDRESS (dll, DebugSetProcessKillOnExit);
615
616 h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
617 if (h != NULL)
618 {
619 if (DebugActiveProcess (pid))
620 {
621 if (DebugSetProcessKillOnExit != NULL)
622 DebugSetProcessKillOnExit (FALSE);
623
624 /* win32_wait needs to know we're attaching. */
625 attaching = 1;
626 do_initial_child_stuff (h, pid, 1);
627 return 0;
628 }
629
630 CloseHandle (h);
631 }
632
633 err = GetLastError ();
634 error ("Attach to process failed (error %d): %s\n",
635 (int) err, strwinerror (err));
636 }
637
638 /* Handle OUTPUT_DEBUG_STRING_EVENT from child process. */
639 static void
640 handle_output_debug_string (struct target_waitstatus *ourstatus)
641 {
642 #define READ_BUFFER_LEN 1024
643 CORE_ADDR addr;
644 char s[READ_BUFFER_LEN + 1] = { 0 };
645 DWORD nbytes = current_event.u.DebugString.nDebugStringLength;
646
647 if (nbytes == 0)
648 return;
649
650 if (nbytes > READ_BUFFER_LEN)
651 nbytes = READ_BUFFER_LEN;
652
653 addr = (CORE_ADDR) (size_t) current_event.u.DebugString.lpDebugStringData;
654
655 if (current_event.u.DebugString.fUnicode)
656 {
657 /* The event tells us how many bytes, not chars, even
658 in Unicode. */
659 WCHAR buffer[(READ_BUFFER_LEN + 1) / sizeof (WCHAR)] = { 0 };
660 if (read_inferior_memory (addr, (unsigned char *) buffer, nbytes) != 0)
661 return;
662 wcstombs (s, buffer, (nbytes + 1) / sizeof (WCHAR));
663 }
664 else
665 {
666 if (read_inferior_memory (addr, (unsigned char *) s, nbytes) != 0)
667 return;
668 }
669
670 if (strncmp (s, "cYg", 3) != 0)
671 {
672 if (!server_waiting)
673 {
674 OUTMSG2(("%s", s));
675 return;
676 }
677
678 monitor_output (s);
679 }
680 #undef READ_BUFFER_LEN
681 }
682
683 static void
684 win32_clear_inferiors (void)
685 {
686 if (current_process_handle != NULL)
687 CloseHandle (current_process_handle);
688
689 for_each_inferior (&all_threads, delete_thread_info);
690 clear_inferiors ();
691 }
692
693 /* Kill all inferiors. */
694 static int
695 win32_kill (int pid)
696 {
697 struct process_info *process;
698
699 if (current_process_handle == NULL)
700 return -1;
701
702 TerminateProcess (current_process_handle, 0);
703 for (;;)
704 {
705 if (!child_continue (DBG_CONTINUE, -1))
706 break;
707 if (!WaitForDebugEvent (&current_event, INFINITE))
708 break;
709 if (current_event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
710 break;
711 else if (current_event.dwDebugEventCode == OUTPUT_DEBUG_STRING_EVENT)
712 {
713 struct target_waitstatus our_status = { 0 };
714 handle_output_debug_string (&our_status);
715 }
716 }
717
718 win32_clear_inferiors ();
719
720 process = find_process_pid (pid);
721 remove_process (process);
722 return 0;
723 }
724
725 /* Detach from inferior PID. */
726 static int
727 win32_detach (int pid)
728 {
729 struct process_info *process;
730 winapi_DebugActiveProcessStop DebugActiveProcessStop = NULL;
731 winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit = NULL;
732 #ifdef _WIN32_WCE
733 HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
734 #else
735 HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
736 #endif
737 DebugActiveProcessStop = GETPROCADDRESS (dll, DebugActiveProcessStop);
738 DebugSetProcessKillOnExit = GETPROCADDRESS (dll, DebugSetProcessKillOnExit);
739
740 if (DebugSetProcessKillOnExit == NULL
741 || DebugActiveProcessStop == NULL)
742 return -1;
743
744 {
745 struct thread_resume resume;
746 resume.thread = minus_one_ptid;
747 resume.kind = resume_continue;
748 resume.sig = 0;
749 win32_resume (&resume, 1);
750 }
751
752 if (!DebugActiveProcessStop (current_process_id))
753 return -1;
754
755 DebugSetProcessKillOnExit (FALSE);
756 process = find_process_pid (pid);
757 remove_process (process);
758
759 win32_clear_inferiors ();
760 return 0;
761 }
762
763 /* Wait for inferiors to end. */
764 static void
765 win32_join (int pid)
766 {
767 HANDLE h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
768 if (h != NULL)
769 {
770 WaitForSingleObject (h, INFINITE);
771 CloseHandle (h);
772 }
773 }
774
775 /* Return 1 iff the thread with thread ID TID is alive. */
776 static int
777 win32_thread_alive (ptid_t ptid)
778 {
779 int res;
780
781 /* Our thread list is reliable; don't bother to poll target
782 threads. */
783 if (find_inferior_id (&all_threads, ptid) != NULL)
784 res = 1;
785 else
786 res = 0;
787 return res;
788 }
789
790 /* Resume the inferior process. RESUME_INFO describes how we want
791 to resume. */
792 static void
793 win32_resume (struct thread_resume *resume_info, size_t n)
794 {
795 DWORD tid;
796 enum target_signal sig;
797 int step;
798 win32_thread_info *th;
799 DWORD continue_status = DBG_CONTINUE;
800 ptid_t ptid;
801
802 /* This handles the very limited set of resume packets that GDB can
803 currently produce. */
804
805 if (n == 1 && ptid_equal (resume_info[0].thread, minus_one_ptid))
806 tid = -1;
807 else if (n > 1)
808 tid = -1;
809 else
810 /* Yes, we're ignoring resume_info[0].thread. It'd be tricky to make
811 the Windows resume code do the right thing for thread switching. */
812 tid = current_event.dwThreadId;
813
814 if (!ptid_equal (resume_info[0].thread, minus_one_ptid))
815 {
816 sig = resume_info[0].sig;
817 step = resume_info[0].kind == resume_step;
818 }
819 else
820 {
821 sig = 0;
822 step = 0;
823 }
824
825 if (sig != TARGET_SIGNAL_0)
826 {
827 if (current_event.dwDebugEventCode != EXCEPTION_DEBUG_EVENT)
828 {
829 OUTMSG (("Cannot continue with signal %d here.\n", sig));
830 }
831 else if (sig == last_sig)
832 continue_status = DBG_EXCEPTION_NOT_HANDLED;
833 else
834 OUTMSG (("Can only continue with recieved signal %d.\n", last_sig));
835 }
836
837 last_sig = TARGET_SIGNAL_0;
838
839 /* Get context for the currently selected thread. */
840 ptid = debug_event_ptid (&current_event);
841 th = thread_rec (ptid, FALSE);
842 if (th)
843 {
844 if (th->context.ContextFlags)
845 {
846 /* Move register values from the inferior into the thread
847 context structure. */
848 regcache_invalidate ();
849
850 if (step)
851 {
852 if (the_low_target.single_step != NULL)
853 (*the_low_target.single_step) (th);
854 else
855 error ("Single stepping is not supported "
856 "in this configuration.\n");
857 }
858
859 win32_set_thread_context (th);
860 th->context.ContextFlags = 0;
861 }
862 }
863
864 /* Allow continuing with the same signal that interrupted us.
865 Otherwise complain. */
866
867 child_continue (continue_status, tid);
868 }
869
870 static void
871 win32_add_one_solib (const char *name, CORE_ADDR load_addr)
872 {
873 char buf[MAX_PATH + 1];
874 char buf2[MAX_PATH + 1];
875
876 #ifdef _WIN32_WCE
877 WIN32_FIND_DATA w32_fd;
878 WCHAR wname[MAX_PATH + 1];
879 mbstowcs (wname, name, MAX_PATH);
880 HANDLE h = FindFirstFile (wname, &w32_fd);
881 #else
882 WIN32_FIND_DATAA w32_fd;
883 HANDLE h = FindFirstFileA (name, &w32_fd);
884 #endif
885
886 if (h == INVALID_HANDLE_VALUE)
887 strcpy (buf, name);
888 else
889 {
890 FindClose (h);
891 strcpy (buf, name);
892 #ifndef _WIN32_WCE
893 {
894 char cwd[MAX_PATH + 1];
895 char *p;
896 if (GetCurrentDirectoryA (MAX_PATH + 1, cwd))
897 {
898 p = strrchr (buf, '\\');
899 if (p)
900 p[1] = '\0';
901 SetCurrentDirectoryA (buf);
902 GetFullPathNameA (w32_fd.cFileName, MAX_PATH, buf, &p);
903 SetCurrentDirectoryA (cwd);
904 }
905 }
906 #endif
907 }
908
909 #ifndef _WIN32_WCE
910 if (strcasecmp (buf, "ntdll.dll") == 0)
911 {
912 GetSystemDirectoryA (buf, sizeof (buf));
913 strcat (buf, "\\ntdll.dll");
914 }
915 #endif
916
917 #ifdef __CYGWIN__
918 cygwin_conv_to_posix_path (buf, buf2);
919 #else
920 strcpy (buf2, buf);
921 #endif
922
923 loaded_dll (buf2, load_addr);
924 }
925
926 static char *
927 get_image_name (HANDLE h, void *address, int unicode)
928 {
929 static char buf[(2 * MAX_PATH) + 1];
930 DWORD size = unicode ? sizeof (WCHAR) : sizeof (char);
931 char *address_ptr;
932 int len = 0;
933 char b[2];
934 DWORD done;
935
936 /* Attempt to read the name of the dll that was detected.
937 This is documented to work only when actively debugging
938 a program. It will not work for attached processes. */
939 if (address == NULL)
940 return NULL;
941
942 #ifdef _WIN32_WCE
943 /* Windows CE reports the address of the image name,
944 instead of an address of a pointer into the image name. */
945 address_ptr = address;
946 #else
947 /* See if we could read the address of a string, and that the
948 address isn't null. */
949 if (!ReadProcessMemory (h, address, &address_ptr,
950 sizeof (address_ptr), &done)
951 || done != sizeof (address_ptr)
952 || !address_ptr)
953 return NULL;
954 #endif
955
956 /* Find the length of the string */
957 while (ReadProcessMemory (h, address_ptr + len++ * size, &b, size, &done)
958 && (b[0] != 0 || b[size - 1] != 0) && done == size)
959 continue;
960
961 if (!unicode)
962 ReadProcessMemory (h, address_ptr, buf, len, &done);
963 else
964 {
965 WCHAR *unicode_address = (WCHAR *) alloca (len * sizeof (WCHAR));
966 ReadProcessMemory (h, address_ptr, unicode_address, len * sizeof (WCHAR),
967 &done);
968
969 WideCharToMultiByte (CP_ACP, 0, unicode_address, len, buf, len, 0, 0);
970 }
971
972 return buf;
973 }
974
975 typedef BOOL (WINAPI *winapi_EnumProcessModules) (HANDLE, HMODULE *,
976 DWORD, LPDWORD);
977 typedef BOOL (WINAPI *winapi_GetModuleInformation) (HANDLE, HMODULE,
978 LPMODULEINFO, DWORD);
979 typedef DWORD (WINAPI *winapi_GetModuleFileNameExA) (HANDLE, HMODULE,
980 LPSTR, DWORD);
981
982 static winapi_EnumProcessModules win32_EnumProcessModules;
983 static winapi_GetModuleInformation win32_GetModuleInformation;
984 static winapi_GetModuleFileNameExA win32_GetModuleFileNameExA;
985
986 static BOOL
987 load_psapi (void)
988 {
989 static int psapi_loaded = 0;
990 static HMODULE dll = NULL;
991
992 if (!psapi_loaded)
993 {
994 psapi_loaded = 1;
995 dll = LoadLibrary (TEXT("psapi.dll"));
996 if (!dll)
997 return FALSE;
998 win32_EnumProcessModules =
999 GETPROCADDRESS (dll, EnumProcessModules);
1000 win32_GetModuleInformation =
1001 GETPROCADDRESS (dll, GetModuleInformation);
1002 win32_GetModuleFileNameExA =
1003 GETPROCADDRESS (dll, GetModuleFileNameExA);
1004 }
1005
1006 return (win32_EnumProcessModules != NULL
1007 && win32_GetModuleInformation != NULL
1008 && win32_GetModuleFileNameExA != NULL);
1009 }
1010
1011 static int
1012 psapi_get_dll_name (DWORD BaseAddress, char *dll_name_ret)
1013 {
1014 DWORD len;
1015 MODULEINFO mi;
1016 size_t i;
1017 HMODULE dh_buf[1];
1018 HMODULE *DllHandle = dh_buf;
1019 DWORD cbNeeded;
1020 BOOL ok;
1021
1022 if (!load_psapi ())
1023 goto failed;
1024
1025 cbNeeded = 0;
1026 ok = (*win32_EnumProcessModules) (current_process_handle,
1027 DllHandle,
1028 sizeof (HMODULE),
1029 &cbNeeded);
1030
1031 if (!ok || !cbNeeded)
1032 goto failed;
1033
1034 DllHandle = (HMODULE *) alloca (cbNeeded);
1035 if (!DllHandle)
1036 goto failed;
1037
1038 ok = (*win32_EnumProcessModules) (current_process_handle,
1039 DllHandle,
1040 cbNeeded,
1041 &cbNeeded);
1042 if (!ok)
1043 goto failed;
1044
1045 for (i = 0; i < ((size_t) cbNeeded / sizeof (HMODULE)); i++)
1046 {
1047 if (!(*win32_GetModuleInformation) (current_process_handle,
1048 DllHandle[i],
1049 &mi,
1050 sizeof (mi)))
1051 {
1052 DWORD err = GetLastError ();
1053 error ("Can't get module info: (error %d): %s\n",
1054 (int) err, strwinerror (err));
1055 }
1056
1057 if ((DWORD) (mi.lpBaseOfDll) == BaseAddress)
1058 {
1059 len = (*win32_GetModuleFileNameExA) (current_process_handle,
1060 DllHandle[i],
1061 dll_name_ret,
1062 MAX_PATH);
1063 if (len == 0)
1064 {
1065 DWORD err = GetLastError ();
1066 error ("Error getting dll name: (error %d): %s\n",
1067 (int) err, strwinerror (err));
1068 }
1069 return 1;
1070 }
1071 }
1072
1073 failed:
1074 dll_name_ret[0] = '\0';
1075 return 0;
1076 }
1077
1078 typedef HANDLE (WINAPI *winapi_CreateToolhelp32Snapshot) (DWORD, DWORD);
1079 typedef BOOL (WINAPI *winapi_Module32First) (HANDLE, LPMODULEENTRY32);
1080 typedef BOOL (WINAPI *winapi_Module32Next) (HANDLE, LPMODULEENTRY32);
1081
1082 static winapi_CreateToolhelp32Snapshot win32_CreateToolhelp32Snapshot;
1083 static winapi_Module32First win32_Module32First;
1084 static winapi_Module32Next win32_Module32Next;
1085 #ifdef _WIN32_WCE
1086 typedef BOOL (WINAPI *winapi_CloseToolhelp32Snapshot) (HANDLE);
1087 static winapi_CloseToolhelp32Snapshot win32_CloseToolhelp32Snapshot;
1088 #endif
1089
1090 static BOOL
1091 load_toolhelp (void)
1092 {
1093 static int toolhelp_loaded = 0;
1094 static HMODULE dll = NULL;
1095
1096 if (!toolhelp_loaded)
1097 {
1098 toolhelp_loaded = 1;
1099 #ifndef _WIN32_WCE
1100 dll = GetModuleHandle (_T("KERNEL32.DLL"));
1101 #else
1102 dll = LoadLibrary (L"TOOLHELP.DLL");
1103 #endif
1104 if (!dll)
1105 return FALSE;
1106
1107 win32_CreateToolhelp32Snapshot =
1108 GETPROCADDRESS (dll, CreateToolhelp32Snapshot);
1109 win32_Module32First = GETPROCADDRESS (dll, Module32First);
1110 win32_Module32Next = GETPROCADDRESS (dll, Module32Next);
1111 #ifdef _WIN32_WCE
1112 win32_CloseToolhelp32Snapshot =
1113 GETPROCADDRESS (dll, CloseToolhelp32Snapshot);
1114 #endif
1115 }
1116
1117 return (win32_CreateToolhelp32Snapshot != NULL
1118 && win32_Module32First != NULL
1119 && win32_Module32Next != NULL
1120 #ifdef _WIN32_WCE
1121 && win32_CloseToolhelp32Snapshot != NULL
1122 #endif
1123 );
1124 }
1125
1126 static int
1127 toolhelp_get_dll_name (DWORD BaseAddress, char *dll_name_ret)
1128 {
1129 HANDLE snapshot_module;
1130 MODULEENTRY32 modEntry = { sizeof (MODULEENTRY32) };
1131 int found = 0;
1132
1133 if (!load_toolhelp ())
1134 return 0;
1135
1136 snapshot_module = win32_CreateToolhelp32Snapshot (TH32CS_SNAPMODULE,
1137 current_event.dwProcessId);
1138 if (snapshot_module == INVALID_HANDLE_VALUE)
1139 return 0;
1140
1141 /* Ignore the first module, which is the exe. */
1142 if (win32_Module32First (snapshot_module, &modEntry))
1143 while (win32_Module32Next (snapshot_module, &modEntry))
1144 if ((DWORD) modEntry.modBaseAddr == BaseAddress)
1145 {
1146 #ifdef UNICODE
1147 wcstombs (dll_name_ret, modEntry.szExePath, MAX_PATH + 1);
1148 #else
1149 strcpy (dll_name_ret, modEntry.szExePath);
1150 #endif
1151 found = 1;
1152 break;
1153 }
1154
1155 #ifdef _WIN32_WCE
1156 win32_CloseToolhelp32Snapshot (snapshot_module);
1157 #else
1158 CloseHandle (snapshot_module);
1159 #endif
1160 return found;
1161 }
1162
1163 static void
1164 handle_load_dll (void)
1165 {
1166 LOAD_DLL_DEBUG_INFO *event = &current_event.u.LoadDll;
1167 char dll_buf[MAX_PATH + 1];
1168 char *dll_name = NULL;
1169 DWORD load_addr;
1170
1171 dll_buf[0] = dll_buf[sizeof (dll_buf) - 1] = '\0';
1172
1173 /* Windows does not report the image name of the dlls in the debug
1174 event on attaches. We resort to iterating over the list of
1175 loaded dlls looking for a match by image base. */
1176 if (!psapi_get_dll_name ((DWORD) event->lpBaseOfDll, dll_buf))
1177 {
1178 if (!server_waiting)
1179 /* On some versions of Windows and Windows CE, we can't create
1180 toolhelp snapshots while the inferior is stopped in a
1181 LOAD_DLL_DEBUG_EVENT due to a dll load, but we can while
1182 Windows is reporting the already loaded dlls. */
1183 toolhelp_get_dll_name ((DWORD) event->lpBaseOfDll, dll_buf);
1184 }
1185
1186 dll_name = dll_buf;
1187
1188 if (*dll_name == '\0')
1189 dll_name = get_image_name (current_process_handle,
1190 event->lpImageName, event->fUnicode);
1191 if (!dll_name)
1192 return;
1193
1194 /* The symbols in a dll are offset by 0x1000, which is the
1195 the offset from 0 of the first byte in an image - because
1196 of the file header and the section alignment. */
1197
1198 load_addr = (DWORD) event->lpBaseOfDll + 0x1000;
1199 win32_add_one_solib (dll_name, load_addr);
1200 }
1201
1202 static void
1203 handle_unload_dll (void)
1204 {
1205 CORE_ADDR load_addr =
1206 (CORE_ADDR) (DWORD) current_event.u.UnloadDll.lpBaseOfDll;
1207 load_addr += 0x1000;
1208 unloaded_dll (NULL, load_addr);
1209 }
1210
1211 static void
1212 handle_exception (struct target_waitstatus *ourstatus)
1213 {
1214 DWORD code = current_event.u.Exception.ExceptionRecord.ExceptionCode;
1215
1216 ourstatus->kind = TARGET_WAITKIND_STOPPED;
1217
1218 switch (code)
1219 {
1220 case EXCEPTION_ACCESS_VIOLATION:
1221 OUTMSG2 (("EXCEPTION_ACCESS_VIOLATION"));
1222 ourstatus->value.sig = TARGET_SIGNAL_SEGV;
1223 break;
1224 case STATUS_STACK_OVERFLOW:
1225 OUTMSG2 (("STATUS_STACK_OVERFLOW"));
1226 ourstatus->value.sig = TARGET_SIGNAL_SEGV;
1227 break;
1228 case STATUS_FLOAT_DENORMAL_OPERAND:
1229 OUTMSG2 (("STATUS_FLOAT_DENORMAL_OPERAND"));
1230 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1231 break;
1232 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
1233 OUTMSG2 (("EXCEPTION_ARRAY_BOUNDS_EXCEEDED"));
1234 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1235 break;
1236 case STATUS_FLOAT_INEXACT_RESULT:
1237 OUTMSG2 (("STATUS_FLOAT_INEXACT_RESULT"));
1238 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1239 break;
1240 case STATUS_FLOAT_INVALID_OPERATION:
1241 OUTMSG2 (("STATUS_FLOAT_INVALID_OPERATION"));
1242 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1243 break;
1244 case STATUS_FLOAT_OVERFLOW:
1245 OUTMSG2 (("STATUS_FLOAT_OVERFLOW"));
1246 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1247 break;
1248 case STATUS_FLOAT_STACK_CHECK:
1249 OUTMSG2 (("STATUS_FLOAT_STACK_CHECK"));
1250 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1251 break;
1252 case STATUS_FLOAT_UNDERFLOW:
1253 OUTMSG2 (("STATUS_FLOAT_UNDERFLOW"));
1254 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1255 break;
1256 case STATUS_FLOAT_DIVIDE_BY_ZERO:
1257 OUTMSG2 (("STATUS_FLOAT_DIVIDE_BY_ZERO"));
1258 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1259 break;
1260 case STATUS_INTEGER_DIVIDE_BY_ZERO:
1261 OUTMSG2 (("STATUS_INTEGER_DIVIDE_BY_ZERO"));
1262 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1263 break;
1264 case STATUS_INTEGER_OVERFLOW:
1265 OUTMSG2 (("STATUS_INTEGER_OVERFLOW"));
1266 ourstatus->value.sig = TARGET_SIGNAL_FPE;
1267 break;
1268 case EXCEPTION_BREAKPOINT:
1269 OUTMSG2 (("EXCEPTION_BREAKPOINT"));
1270 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
1271 #ifdef _WIN32_WCE
1272 /* Remove the initial breakpoint. */
1273 check_breakpoints ((CORE_ADDR) (long) current_event
1274 .u.Exception.ExceptionRecord.ExceptionAddress);
1275 #endif
1276 break;
1277 case DBG_CONTROL_C:
1278 OUTMSG2 (("DBG_CONTROL_C"));
1279 ourstatus->value.sig = TARGET_SIGNAL_INT;
1280 break;
1281 case DBG_CONTROL_BREAK:
1282 OUTMSG2 (("DBG_CONTROL_BREAK"));
1283 ourstatus->value.sig = TARGET_SIGNAL_INT;
1284 break;
1285 case EXCEPTION_SINGLE_STEP:
1286 OUTMSG2 (("EXCEPTION_SINGLE_STEP"));
1287 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
1288 break;
1289 case EXCEPTION_ILLEGAL_INSTRUCTION:
1290 OUTMSG2 (("EXCEPTION_ILLEGAL_INSTRUCTION"));
1291 ourstatus->value.sig = TARGET_SIGNAL_ILL;
1292 break;
1293 case EXCEPTION_PRIV_INSTRUCTION:
1294 OUTMSG2 (("EXCEPTION_PRIV_INSTRUCTION"));
1295 ourstatus->value.sig = TARGET_SIGNAL_ILL;
1296 break;
1297 case EXCEPTION_NONCONTINUABLE_EXCEPTION:
1298 OUTMSG2 (("EXCEPTION_NONCONTINUABLE_EXCEPTION"));
1299 ourstatus->value.sig = TARGET_SIGNAL_ILL;
1300 break;
1301 default:
1302 if (current_event.u.Exception.dwFirstChance)
1303 {
1304 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
1305 return;
1306 }
1307 OUTMSG2 (("gdbserver: unknown target exception 0x%08lx at 0x%08lx",
1308 current_event.u.Exception.ExceptionRecord.ExceptionCode,
1309 (DWORD) current_event.u.Exception.ExceptionRecord.
1310 ExceptionAddress));
1311 ourstatus->value.sig = TARGET_SIGNAL_UNKNOWN;
1312 break;
1313 }
1314 OUTMSG2 (("\n"));
1315 last_sig = ourstatus->value.sig;
1316 }
1317
1318
1319 static void
1320 suspend_one_thread (struct inferior_list_entry *entry)
1321 {
1322 struct thread_info *thread = (struct thread_info *) entry;
1323 win32_thread_info *th = inferior_target_data (thread);
1324
1325 if (!th->suspended)
1326 {
1327 if (SuspendThread (th->h) == (DWORD) -1)
1328 {
1329 DWORD err = GetLastError ();
1330 OUTMSG (("warning: SuspendThread failed in suspend_one_thread, "
1331 "(error %d): %s\n", (int) err, strwinerror (err)));
1332 }
1333 else
1334 th->suspended = 1;
1335 }
1336 }
1337
1338 static void
1339 fake_breakpoint_event (void)
1340 {
1341 OUTMSG2(("fake_breakpoint_event\n"));
1342
1343 faked_breakpoint = 1;
1344
1345 memset (&current_event, 0, sizeof (current_event));
1346 current_event.dwThreadId = main_thread_id;
1347 current_event.dwDebugEventCode = EXCEPTION_DEBUG_EVENT;
1348 current_event.u.Exception.ExceptionRecord.ExceptionCode
1349 = EXCEPTION_BREAKPOINT;
1350
1351 for_each_inferior (&all_threads, suspend_one_thread);
1352 }
1353
1354 #ifdef _WIN32_WCE
1355 static int
1356 auto_delete_breakpoint (CORE_ADDR stop_pc)
1357 {
1358 return 1;
1359 }
1360 #endif
1361
1362 /* Get the next event from the child. */
1363
1364 static int
1365 get_child_debug_event (struct target_waitstatus *ourstatus)
1366 {
1367 ptid_t ptid;
1368
1369 last_sig = TARGET_SIGNAL_0;
1370 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
1371
1372 /* Check if GDB sent us an interrupt request. */
1373 check_remote_input_interrupt_request ();
1374
1375 if (soft_interrupt_requested)
1376 {
1377 soft_interrupt_requested = 0;
1378 fake_breakpoint_event ();
1379 goto gotevent;
1380 }
1381
1382 #ifndef _WIN32_WCE
1383 attaching = 0;
1384 #else
1385 if (attaching)
1386 {
1387 /* WinCE doesn't set an initial breakpoint automatically. To
1388 stop the inferior, we flush all currently pending debug
1389 events -- the thread list and the dll list are always
1390 reported immediatelly without delay, then, we suspend all
1391 threads and pretend we saw a trap at the current PC of the
1392 main thread.
1393
1394 Contrary to desktop Windows, Windows CE *does* report the dll
1395 names on LOAD_DLL_DEBUG_EVENTs resulting from a
1396 DebugActiveProcess call. This limits the way we can detect
1397 if all the dlls have already been reported. If we get a real
1398 debug event before leaving attaching, the worst that will
1399 happen is the user will see a spurious breakpoint. */
1400
1401 current_event.dwDebugEventCode = 0;
1402 if (!WaitForDebugEvent (&current_event, 0))
1403 {
1404 OUTMSG2(("no attach events left\n"));
1405 fake_breakpoint_event ();
1406 attaching = 0;
1407 }
1408 else
1409 OUTMSG2(("got attach event\n"));
1410 }
1411 else
1412 #endif
1413 {
1414 /* Keep the wait time low enough for confortable remote
1415 interruption, but high enough so gdbserver doesn't become a
1416 bottleneck. */
1417 if (!WaitForDebugEvent (&current_event, 250))
1418 {
1419 DWORD e = GetLastError();
1420
1421 if (e == ERROR_PIPE_NOT_CONNECTED)
1422 {
1423 /* This will happen if the loader fails to succesfully
1424 load the application, e.g., if the main executable
1425 tries to pull in a non-existing export from a
1426 DLL. */
1427 ourstatus->kind = TARGET_WAITKIND_EXITED;
1428 ourstatus->value.integer = 1;
1429 return 1;
1430 }
1431
1432 return 0;
1433 }
1434 }
1435
1436 gotevent:
1437
1438 ptid = debug_event_ptid (&current_event);
1439 current_inferior =
1440 (struct thread_info *) find_inferior_id (&all_threads, ptid);
1441
1442 switch (current_event.dwDebugEventCode)
1443 {
1444 case CREATE_THREAD_DEBUG_EVENT:
1445 OUTMSG2 (("gdbserver: kernel event CREATE_THREAD_DEBUG_EVENT "
1446 "for pid=%d tid=%x)\n",
1447 (unsigned) current_event.dwProcessId,
1448 (unsigned) current_event.dwThreadId));
1449
1450 /* Record the existence of this thread. */
1451 child_add_thread (current_event.dwProcessId,
1452 current_event.dwThreadId,
1453 current_event.u.CreateThread.hThread);
1454 break;
1455
1456 case EXIT_THREAD_DEBUG_EVENT:
1457 OUTMSG2 (("gdbserver: kernel event EXIT_THREAD_DEBUG_EVENT "
1458 "for pid=%d tid=%x\n",
1459 (unsigned) current_event.dwProcessId,
1460 (unsigned) current_event.dwThreadId));
1461 child_delete_thread (current_event.dwProcessId,
1462 current_event.dwThreadId);
1463 break;
1464
1465 case CREATE_PROCESS_DEBUG_EVENT:
1466 OUTMSG2 (("gdbserver: kernel event CREATE_PROCESS_DEBUG_EVENT "
1467 "for pid=%d tid=%x\n",
1468 (unsigned) current_event.dwProcessId,
1469 (unsigned) current_event.dwThreadId));
1470 CloseHandle (current_event.u.CreateProcessInfo.hFile);
1471
1472 current_process_handle = current_event.u.CreateProcessInfo.hProcess;
1473 main_thread_id = current_event.dwThreadId;
1474
1475 ourstatus->kind = TARGET_WAITKIND_EXECD;
1476 ourstatus->value.execd_pathname = "Main executable";
1477
1478 /* Add the main thread. */
1479 child_add_thread (current_event.dwProcessId,
1480 main_thread_id,
1481 current_event.u.CreateProcessInfo.hThread);
1482
1483 ourstatus->value.related_pid = debug_event_ptid (&current_event);
1484 #ifdef _WIN32_WCE
1485 if (!attaching)
1486 {
1487 /* Windows CE doesn't set the initial breakpoint
1488 automatically like the desktop versions of Windows do.
1489 We add it explicitly here. It will be removed as soon as
1490 it is hit. */
1491 set_breakpoint_at ((CORE_ADDR) (long) current_event.u
1492 .CreateProcessInfo.lpStartAddress,
1493 auto_delete_breakpoint);
1494 }
1495 #endif
1496 break;
1497
1498 case EXIT_PROCESS_DEBUG_EVENT:
1499 OUTMSG2 (("gdbserver: kernel event EXIT_PROCESS_DEBUG_EVENT "
1500 "for pid=%d tid=%x\n",
1501 (unsigned) current_event.dwProcessId,
1502 (unsigned) current_event.dwThreadId));
1503 ourstatus->kind = TARGET_WAITKIND_EXITED;
1504 ourstatus->value.integer = current_event.u.ExitProcess.dwExitCode;
1505 child_continue (DBG_CONTINUE, -1);
1506 CloseHandle (current_process_handle);
1507 current_process_handle = NULL;
1508 break;
1509
1510 case LOAD_DLL_DEBUG_EVENT:
1511 OUTMSG2 (("gdbserver: kernel event LOAD_DLL_DEBUG_EVENT "
1512 "for pid=%d tid=%x\n",
1513 (unsigned) current_event.dwProcessId,
1514 (unsigned) current_event.dwThreadId));
1515 CloseHandle (current_event.u.LoadDll.hFile);
1516 handle_load_dll ();
1517
1518 ourstatus->kind = TARGET_WAITKIND_LOADED;
1519 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
1520 break;
1521
1522 case UNLOAD_DLL_DEBUG_EVENT:
1523 OUTMSG2 (("gdbserver: kernel event UNLOAD_DLL_DEBUG_EVENT "
1524 "for pid=%d tid=%x\n",
1525 (unsigned) current_event.dwProcessId,
1526 (unsigned) current_event.dwThreadId));
1527 handle_unload_dll ();
1528 ourstatus->kind = TARGET_WAITKIND_LOADED;
1529 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
1530 break;
1531
1532 case EXCEPTION_DEBUG_EVENT:
1533 OUTMSG2 (("gdbserver: kernel event EXCEPTION_DEBUG_EVENT "
1534 "for pid=%d tid=%x\n",
1535 (unsigned) current_event.dwProcessId,
1536 (unsigned) current_event.dwThreadId));
1537 handle_exception (ourstatus);
1538 break;
1539
1540 case OUTPUT_DEBUG_STRING_EVENT:
1541 /* A message from the kernel (or Cygwin). */
1542 OUTMSG2 (("gdbserver: kernel event OUTPUT_DEBUG_STRING_EVENT "
1543 "for pid=%d tid=%x\n",
1544 (unsigned) current_event.dwProcessId,
1545 (unsigned) current_event.dwThreadId));
1546 handle_output_debug_string (ourstatus);
1547 break;
1548
1549 default:
1550 OUTMSG2 (("gdbserver: kernel event unknown "
1551 "for pid=%d tid=%x code=%ld\n",
1552 (unsigned) current_event.dwProcessId,
1553 (unsigned) current_event.dwThreadId,
1554 current_event.dwDebugEventCode));
1555 break;
1556 }
1557
1558 current_inferior =
1559 (struct thread_info *) find_inferior_id (&all_threads, ptid);
1560 return 1;
1561 }
1562
1563 /* Wait for the inferior process to change state.
1564 STATUS will be filled in with a response code to send to GDB.
1565 Returns the signal which caused the process to stop. */
1566 static ptid_t
1567 win32_wait (ptid_t ptid, struct target_waitstatus *ourstatus, int options)
1568 {
1569 struct process_info *process;
1570
1571 while (1)
1572 {
1573 if (!get_child_debug_event (ourstatus))
1574 continue;
1575
1576 switch (ourstatus->kind)
1577 {
1578 case TARGET_WAITKIND_EXITED:
1579 OUTMSG2 (("Child exited with retcode = %x\n",
1580 ourstatus->value.integer));
1581
1582 process = find_process_pid (current_process_id);
1583 remove_process (process);
1584 win32_clear_inferiors ();
1585 return pid_to_ptid (current_event.dwProcessId);
1586 case TARGET_WAITKIND_STOPPED:
1587 case TARGET_WAITKIND_LOADED:
1588 OUTMSG2 (("Child Stopped with signal = %d \n",
1589 our_status.value.sig));
1590
1591 child_fetch_inferior_registers (-1);
1592
1593 if (ourstatus->kind == TARGET_WAITKIND_LOADED
1594 && !server_waiting)
1595 {
1596 /* When gdb connects, we want to be stopped at the
1597 initial breakpoint, not in some dll load event. */
1598 child_continue (DBG_CONTINUE, -1);
1599 break;
1600 }
1601
1602 /* We don't expose _LOADED events to gdbserver core. See
1603 the `dlls_changed' global. */
1604 if (ourstatus->kind == TARGET_WAITKIND_LOADED)
1605 ourstatus->kind = TARGET_WAITKIND_STOPPED;
1606
1607 return debug_event_ptid (&current_event);
1608 default:
1609 OUTMSG (("Ignoring unknown internal event, %d\n", ourstatus->kind));
1610 /* fall-through */
1611 case TARGET_WAITKIND_SPURIOUS:
1612 case TARGET_WAITKIND_EXECD:
1613 /* do nothing, just continue */
1614 child_continue (DBG_CONTINUE, -1);
1615 break;
1616 }
1617 }
1618 }
1619
1620 /* Fetch registers from the inferior process.
1621 If REGNO is -1, fetch all registers; otherwise, fetch at least REGNO. */
1622 static void
1623 win32_fetch_inferior_registers (int regno)
1624 {
1625 child_fetch_inferior_registers (regno);
1626 }
1627
1628 /* Store registers to the inferior process.
1629 If REGNO is -1, store all registers; otherwise, store at least REGNO. */
1630 static void
1631 win32_store_inferior_registers (int regno)
1632 {
1633 child_store_inferior_registers (regno);
1634 }
1635
1636 /* Read memory from the inferior process. This should generally be
1637 called through read_inferior_memory, which handles breakpoint shadowing.
1638 Read LEN bytes at MEMADDR into a buffer at MYADDR. */
1639 static int
1640 win32_read_inferior_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
1641 {
1642 return child_xfer_memory (memaddr, (char *) myaddr, len, 0, 0) != len;
1643 }
1644
1645 /* Write memory to the inferior process. This should generally be
1646 called through write_inferior_memory, which handles breakpoint shadowing.
1647 Write LEN bytes from the buffer at MYADDR to MEMADDR.
1648 Returns 0 on success and errno on failure. */
1649 static int
1650 win32_write_inferior_memory (CORE_ADDR memaddr, const unsigned char *myaddr,
1651 int len)
1652 {
1653 return child_xfer_memory (memaddr, (char *) myaddr, len, 1, 0) != len;
1654 }
1655
1656 /* Send an interrupt request to the inferior process. */
1657 static void
1658 win32_request_interrupt (void)
1659 {
1660 winapi_DebugBreakProcess DebugBreakProcess;
1661 winapi_GenerateConsoleCtrlEvent GenerateConsoleCtrlEvent;
1662
1663 #ifdef _WIN32_WCE
1664 HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
1665 #else
1666 HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
1667 #endif
1668
1669 GenerateConsoleCtrlEvent = GETPROCADDRESS (dll, GenerateConsoleCtrlEvent);
1670
1671 if (GenerateConsoleCtrlEvent != NULL
1672 && GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, current_process_id))
1673 return;
1674
1675 /* GenerateConsoleCtrlEvent can fail if process id being debugged is
1676 not a process group id.
1677 Fallback to XP/Vista 'DebugBreakProcess', which generates a
1678 breakpoint exception in the interior process. */
1679
1680 DebugBreakProcess = GETPROCADDRESS (dll, DebugBreakProcess);
1681
1682 if (DebugBreakProcess != NULL
1683 && DebugBreakProcess (current_process_handle))
1684 return;
1685
1686 /* Last resort, suspend all threads manually. */
1687 soft_interrupt_requested = 1;
1688 }
1689
1690 #ifdef _WIN32_WCE
1691 int
1692 win32_error_to_fileio_error (DWORD err)
1693 {
1694 switch (err)
1695 {
1696 case ERROR_BAD_PATHNAME:
1697 case ERROR_FILE_NOT_FOUND:
1698 case ERROR_INVALID_NAME:
1699 case ERROR_PATH_NOT_FOUND:
1700 return FILEIO_ENOENT;
1701 case ERROR_CRC:
1702 case ERROR_IO_DEVICE:
1703 case ERROR_OPEN_FAILED:
1704 return FILEIO_EIO;
1705 case ERROR_INVALID_HANDLE:
1706 return FILEIO_EBADF;
1707 case ERROR_ACCESS_DENIED:
1708 case ERROR_SHARING_VIOLATION:
1709 return FILEIO_EACCES;
1710 case ERROR_NOACCESS:
1711 return FILEIO_EFAULT;
1712 case ERROR_BUSY:
1713 return FILEIO_EBUSY;
1714 case ERROR_ALREADY_EXISTS:
1715 case ERROR_FILE_EXISTS:
1716 return FILEIO_EEXIST;
1717 case ERROR_BAD_DEVICE:
1718 return FILEIO_ENODEV;
1719 case ERROR_DIRECTORY:
1720 return FILEIO_ENOTDIR;
1721 case ERROR_FILENAME_EXCED_RANGE:
1722 case ERROR_INVALID_DATA:
1723 case ERROR_INVALID_PARAMETER:
1724 case ERROR_NEGATIVE_SEEK:
1725 return FILEIO_EINVAL;
1726 case ERROR_TOO_MANY_OPEN_FILES:
1727 return FILEIO_EMFILE;
1728 case ERROR_HANDLE_DISK_FULL:
1729 case ERROR_DISK_FULL:
1730 return FILEIO_ENOSPC;
1731 case ERROR_WRITE_PROTECT:
1732 return FILEIO_EROFS;
1733 case ERROR_NOT_SUPPORTED:
1734 return FILEIO_ENOSYS;
1735 }
1736
1737 return FILEIO_EUNKNOWN;
1738 }
1739
1740 static void
1741 wince_hostio_last_error (char *buf)
1742 {
1743 DWORD winerr = GetLastError ();
1744 int fileio_err = win32_error_to_fileio_error (winerr);
1745 sprintf (buf, "F-1,%x", fileio_err);
1746 }
1747 #endif
1748
1749 static struct target_ops win32_target_ops = {
1750 win32_create_inferior,
1751 win32_attach,
1752 win32_kill,
1753 win32_detach,
1754 win32_join,
1755 win32_thread_alive,
1756 win32_resume,
1757 win32_wait,
1758 win32_fetch_inferior_registers,
1759 win32_store_inferior_registers,
1760 win32_read_inferior_memory,
1761 win32_write_inferior_memory,
1762 NULL,
1763 win32_request_interrupt,
1764 NULL,
1765 win32_insert_point,
1766 win32_remove_point,
1767 win32_stopped_by_watchpoint,
1768 win32_stopped_data_address,
1769 NULL,
1770 NULL,
1771 NULL,
1772 #ifdef _WIN32_WCE
1773 wince_hostio_last_error,
1774 #else
1775 hostio_last_error_from_errno,
1776 #endif
1777 };
1778
1779 /* Initialize the Win32 backend. */
1780 void
1781 initialize_low (void)
1782 {
1783 set_target_ops (&win32_target_ops);
1784 if (the_low_target.breakpoint != NULL)
1785 set_breakpoint_data (the_low_target.breakpoint,
1786 the_low_target.breakpoint_len);
1787 the_low_target.arch_setup ();
1788 }
This page took 0.063378 seconds and 5 git commands to generate.