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