Include "gdb_wait.h" instead of "wait.h".
[deliverable/binutils-gdb.git] / gdb / wince.c
1 /* Target-vector operations for controlling Windows CE child processes, for GDB.
2 Copyright 1999, 2000 Free Software Foundation, Inc.
3 Contributed by Cygnus Solutions, A Red Hat Company.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without eve nthe implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA.
21 */
22
23 /* by Christopher Faylor (cgf@cygnus.com) */
24
25 /* We assume we're being built with and will be used for cygwin. */
26
27 #ifdef SHx
28 #undef SH4
29 #define SH4 /* Just to get all of the CONTEXT defines. */
30 #endif
31
32 #include "defs.h"
33 #include "frame.h" /* required by inferior.h */
34 #include "inferior.h"
35 #include "target.h"
36 #include "gdb_wait.h"
37 #include "gdbcore.h"
38 #include "command.h"
39 #include <signal.h>
40 #include <sys/types.h>
41 #include <fcntl.h>
42 #include <stdlib.h>
43
44 #include <windows.h>
45 #include <rapi.h>
46 #include <netdb.h>
47 #include <cygwin/in.h>
48 #include <cygwin/socket.h>
49
50 #include "buildsym.h"
51 #include "symfile.h"
52 #include "objfiles.h"
53 #include "gdb_string.h"
54 #include "gdbthread.h"
55 #include "gdbcmd.h"
56 #include <sys/param.h>
57 #include "wince-stub.h"
58 #include "dcache.h"
59
60 /* The ui's event loop. */
61 extern int (*ui_loop_hook) PARAMS ((int signo));
62
63 /* If we're not using the old Cygwin header file set, define the
64 following which never should have been in the generic Win32 API
65 headers in the first place since they were our own invention... */
66 #ifndef _GNU_H_WINDOWS_H
67 #define FLAG_TRACE_BIT 0x100
68 #ifdef CONTEXT_FLOATING_POINT
69 #define CONTEXT_DEBUGGER0 (CONTEXT_FULL | CONTEXT_FLOATING_POINT)
70 #else
71 #define CONTEXT_DEBUGGER0 (CONTEXT_FULL)
72 #endif
73 #endif
74
75 #ifdef SH4
76 #define CONTEXT_DEBUGGER ((CONTEXT_DEBUGGER0 & ~(CONTEXT_SH4 | CONTEXT_FLOATING_POINT)) | CONTEXT_SH3)
77 #else
78 #define CONTEXT_DEBUGGER CONTEXT_DEBUGGER0
79 #endif
80 /* The string sent by cygwin when it processes a signal.
81 FIXME: This should be in a cygwin include file. */
82 #define CYGWIN_SIGNAL_STRING "cygwin: signal"
83
84 #define CHECK(x) check (x, __FILE__,__LINE__)
85 #define DEBUG_EXEC(x) if (debug_exec) printf x
86 #define DEBUG_EVENTS(x) if (debug_events) printf x
87 #define DEBUG_MEM(x) if (debug_memory) printf x
88 #define DEBUG_EXCEPT(x) if (debug_exceptions) printf x
89
90 static int connection_initialized = 0; /* True if we've initialized a RAPI session. */
91
92 static DCACHE *remote_dcache;
93
94 /* The directory where the stub and executable files are uploaded. */
95 static const char *remote_directory = "\\gdb";
96
97 /* The types automatic upload available. */
98 static enum
99 {
100 UPLOAD_ALWAYS = 0,
101 UPLOAD_NEWER = 1,
102 UPLOAD_NEVER = 2
103 }
104 upload_when = UPLOAD_NEWER;
105
106 /* Valid options for 'set remoteupload'. Note that options
107 must track upload_when enum. */
108 static struct opts
109 {
110 const char *name;
111 int abbrev;
112 }
113 upload_options[3] =
114 {
115 {
116 "always", 1
117 }
118 ,
119 {
120 "newer", 3
121 }
122 ,
123 {
124 "never", 3
125 }
126 };
127
128 static char *remote_upload = NULL; /* Set by set remoteupload */
129 static int remote_add_host = 0;
130
131 /* Forward declaration */
132 extern struct target_ops child_ops;
133
134 static int win32_child_thread_alive PARAMS ((int));
135 void child_kill_inferior PARAMS ((void));
136
137 static int last_sig = 0; /* Set if a signal was received from the
138 debugged process */
139
140 /* Thread information structure used to track information that is
141 not available in gdb's thread structure. */
142 typedef struct thread_info_struct
143 {
144 struct thread_info_struct *next;
145 DWORD id;
146 HANDLE h;
147 char *name;
148 int suspend_count;
149 int stepped; /* True if stepped. */
150 CORE_ADDR step_pc;
151 unsigned long step_instr;
152 unsigned long step_prev;
153 CONTEXT context;
154 }
155 thread_info;
156
157 static thread_info thread_head =
158 {NULL};
159
160 /* The process and thread handles for the above context. */
161
162 static DEBUG_EVENT current_event; /* The current debug event from
163 WaitForDebugEvent */
164 static HANDLE current_process_handle; /* Currently executing process */
165 static thread_info *current_thread; /* Info on currently selected thread */
166 static thread_info *this_thread; /* Info on thread returned by wait_for_debug_event */
167 static DWORD main_thread_id; /* Thread ID of the main thread */
168
169 /* Counts of things. */
170 static int exception_count = 0;
171 static int event_count = 0;
172
173 /* User options. */
174 static int debug_exec = 0; /* show execution */
175 static int debug_events = 0; /* show events from kernel */
176 static int debug_memory = 0; /* show target memory accesses */
177 static int debug_exceptions = 0; /* show target exceptions */
178
179 /* An array of offset mappings into a Win32 Context structure.
180 This is a one-to-one mapping which is indexed by gdb's register
181 numbers. It retrieves an offset into the context structure where
182 the 4 byte register is located.
183 An offset value of -1 indicates that Win32 does not provide this
184 register in it's CONTEXT structure. regptr will return zero for this
185 register.
186
187 This is used by the regptr function. */
188 #define context_offset(x) ((int)&(((PCONTEXT)NULL)->x))
189 static const int mappings[NUM_REGS + 1] =
190 {
191 #ifdef __i386__
192 context_offset (Eax),
193 context_offset (Ecx),
194 context_offset (Edx),
195 context_offset (Ebx),
196 context_offset (Esp),
197 context_offset (Ebp),
198 context_offset (Esi),
199 context_offset (Edi),
200 context_offset (Eip),
201 context_offset (EFlags),
202 context_offset (SegCs),
203 context_offset (SegSs),
204 context_offset (SegDs),
205 context_offset (SegEs),
206 context_offset (SegFs),
207 context_offset (SegGs),
208 context_offset (FloatSave.RegisterArea[0 * 10]),
209 context_offset (FloatSave.RegisterArea[1 * 10]),
210 context_offset (FloatSave.RegisterArea[2 * 10]),
211 context_offset (FloatSave.RegisterArea[3 * 10]),
212 context_offset (FloatSave.RegisterArea[4 * 10]),
213 context_offset (FloatSave.RegisterArea[5 * 10]),
214 context_offset (FloatSave.RegisterArea[6 * 10]),
215 context_offset (FloatSave.RegisterArea[7 * 10]),
216 #elif defined(SHx)
217 context_offset (R0),
218 context_offset (R1),
219 context_offset (R2),
220 context_offset (R3),
221 context_offset (R4),
222 context_offset (R5),
223 context_offset (R6),
224 context_offset (R7),
225 context_offset (R8),
226 context_offset (R9),
227 context_offset (R10),
228 context_offset (R11),
229 context_offset (R12),
230 context_offset (R13),
231 context_offset (R14),
232 context_offset (R15),
233 context_offset (Fir),
234 context_offset (PR), /* Procedure Register */
235 context_offset (GBR), /* Global Base Register */
236 context_offset (MACH), /* Accumulate */
237 context_offset (MACL), /* Multiply */
238 context_offset (Psr),
239 context_offset (Fpul),
240 context_offset (Fpscr),
241 context_offset (FRegs[0]),
242 context_offset (FRegs[1]),
243 context_offset (FRegs[2]),
244 context_offset (FRegs[3]),
245 context_offset (FRegs[4]),
246 context_offset (FRegs[5]),
247 context_offset (FRegs[6]),
248 context_offset (FRegs[7]),
249 context_offset (FRegs[8]),
250 context_offset (FRegs[9]),
251 context_offset (FRegs[10]),
252 context_offset (FRegs[11]),
253 context_offset (FRegs[12]),
254 context_offset (FRegs[13]),
255 context_offset (FRegs[14]),
256 context_offset (FRegs[15]),
257 context_offset (xFRegs[0]),
258 context_offset (xFRegs[1]),
259 context_offset (xFRegs[2]),
260 context_offset (xFRegs[3]),
261 context_offset (xFRegs[4]),
262 context_offset (xFRegs[5]),
263 context_offset (xFRegs[6]),
264 context_offset (xFRegs[7]),
265 context_offset (xFRegs[8]),
266 context_offset (xFRegs[9]),
267 context_offset (xFRegs[10]),
268 context_offset (xFRegs[11]),
269 context_offset (xFRegs[12]),
270 context_offset (xFRegs[13]),
271 context_offset (xFRegs[14]),
272 context_offset (xFRegs[15]),
273 #elif defined(MIPS)
274 context_offset (IntZero),
275 context_offset (IntAt),
276 context_offset (IntV0),
277 context_offset (IntV1),
278 context_offset (IntA0),
279 context_offset (IntA1),
280 context_offset (IntA2),
281 context_offset (IntA3),
282 context_offset (IntT0),
283 context_offset (IntT1),
284 context_offset (IntT2),
285 context_offset (IntT3),
286 context_offset (IntT4),
287 context_offset (IntT5),
288 context_offset (IntT6),
289 context_offset (IntT7),
290 context_offset (IntS0),
291 context_offset (IntS1),
292 context_offset (IntS2),
293 context_offset (IntS3),
294 context_offset (IntS4),
295 context_offset (IntS5),
296 context_offset (IntS6),
297 context_offset (IntS7),
298 context_offset (IntT8),
299 context_offset (IntT9),
300 context_offset (IntK0),
301 context_offset (IntK1),
302 context_offset (IntGp),
303 context_offset (IntSp),
304 context_offset (IntS8),
305 context_offset (IntRa),
306 context_offset (Psr),
307 context_offset (IntLo),
308 context_offset (IntHi),
309 -1, /* bad */
310 -1, /* cause */
311 context_offset (Fir),
312 context_offset (FltF0),
313 context_offset (FltF1),
314 context_offset (FltF2),
315 context_offset (FltF3),
316 context_offset (FltF4),
317 context_offset (FltF5),
318 context_offset (FltF6),
319 context_offset (FltF7),
320 context_offset (FltF8),
321 context_offset (FltF9),
322 context_offset (FltF10),
323 context_offset (FltF11),
324 context_offset (FltF12),
325 context_offset (FltF13),
326 context_offset (FltF14),
327 context_offset (FltF15),
328 context_offset (FltF16),
329 context_offset (FltF17),
330 context_offset (FltF18),
331 context_offset (FltF19),
332 context_offset (FltF20),
333 context_offset (FltF21),
334 context_offset (FltF22),
335 context_offset (FltF23),
336 context_offset (FltF24),
337 context_offset (FltF25),
338 context_offset (FltF26),
339 context_offset (FltF27),
340 context_offset (FltF28),
341 context_offset (FltF29),
342 context_offset (FltF30),
343 context_offset (FltF31),
344 context_offset (Fsr),
345 context_offset (Fir),
346 -1, /* fp */
347 #elif defined(ARM)
348 context_offset (R0),
349 context_offset (R1),
350 context_offset (R2),
351 context_offset (R3),
352 context_offset (R4),
353 context_offset (R5),
354 context_offset (R6),
355 context_offset (R7),
356 context_offset (R8),
357 context_offset (R9),
358 context_offset (R10),
359 context_offset (R11),
360 context_offset (R12),
361 context_offset (Sp),
362 context_offset (Lr),
363 context_offset (Pc),
364 -1,
365 -1,
366 -1,
367 -1,
368 -1,
369 -1,
370 -1,
371 -1,
372 -1,
373 context_offset (Psr),
374 #endif
375 -1
376 };
377
378 /* This vector maps the target's idea of an exception (extracted
379 from the DEBUG_EVENT structure) to GDB's idea. */
380
381 struct xlate_exception
382 {
383 int them;
384 enum target_signal us;
385 };
386
387 static const struct xlate_exception
388 xlate[] =
389 {
390 {EXCEPTION_ACCESS_VIOLATION, TARGET_SIGNAL_SEGV},
391 {STATUS_STACK_OVERFLOW, TARGET_SIGNAL_SEGV},
392 {EXCEPTION_BREAKPOINT, TARGET_SIGNAL_TRAP},
393 {DBG_CONTROL_C, TARGET_SIGNAL_INT},
394 {EXCEPTION_SINGLE_STEP, TARGET_SIGNAL_TRAP},
395 {-1, -1}};
396
397 /******************** Beginning of stub interface ********************/
398
399 /* Stub interface description:
400
401 The Windows CE stub implements a crude RPC. The hand-held device
402 connects to gdb using port 7000. gdb and the stub then communicate
403 using packets where:
404
405 byte 0: command id (e.g. Create Process)
406
407 byte 1-4: DWORD
408
409 byte 1-2: WORD
410
411 byte 1-2: length
412 byte 3-n: arbitrary memory.
413
414 The interface is deterministic, i.e., if the stub expects a DWORD then
415 the gdb server should send a DWORD.
416 */
417
418 /* Note: In the functions below, the `huh' parameter is a string passed from the
419 function containing a descriptive string concerning the current operation.
420 This is used for error reporting.
421
422 The 'what' parameter is a command id as found in wince-stub.h.
423
424 Hopefully, the rest of the parameters are self-explanatory.
425 */
426
427 static int s; /* communication socket */
428
429 /* v-style interface for handling varying argyment list error messages.
430 Displays the error message in a dialog box and exits when user clicks
431 on OK. */
432 static void
433 vstub_error (LPCSTR fmt, va_list * args)
434 {
435 char buf[4096];
436 vsprintf (buf, fmt, args);
437 s = -1;
438 error ("%s", buf);
439 }
440
441 /* The standard way to display an error message and exit. */
442 static void
443 stub_error (LPCSTR fmt,...)
444 {
445 va_list args;
446 va_start (args, fmt);
447 vstub_error (fmt, args);
448 }
449
450 /* Standard "oh well" can't communicate error. Someday this might attempt
451 synchronization. */
452 static void
453 attempt_resync (LPCSTR huh, int s)
454 {
455 stub_error ("lost synchronization with target attempting %s", huh);
456 }
457
458 /* Read arbitrary stuff from a socket. */
459 static int
460 sockread (LPCSTR huh, int s, void *str, size_t n)
461 {
462 for (;;)
463 {
464 if (recv (s, str, n, 0) == n)
465 return n;
466 attempt_resync (huh, s);
467 }
468 }
469
470 /* Write arbitrary stuff to a socket. */
471 static int
472 sockwrite (LPCSTR huh, const void *str, size_t n)
473 {
474 for (;;)
475 {
476 if (send (s, str, n, 0) == n)
477 return n;
478 attempt_resync (huh, s);
479 }
480 }
481
482 /* Output an id/dword to the host */
483 static void
484 putdword (LPCSTR huh, gdb_wince_id what, DWORD n)
485 {
486 if (sockwrite (huh, &what, sizeof (what)) != sizeof (what))
487 stub_error ("error writing record id to host for %s", huh);
488 if (sockwrite (huh, &n, sizeof (n)) != sizeof (n))
489 stub_error ("error writing %s to host.", huh);
490 }
491
492 /* Output an id/word to the host */
493 static void
494 putword (LPCSTR huh, gdb_wince_id what, WORD n)
495 {
496 if (sockwrite (huh, &what, sizeof (what)) != sizeof (what))
497 stub_error ("error writing record id to host for %s", huh);
498 if (sockwrite (huh, &n, sizeof (n)) != sizeof (n))
499 stub_error ("error writing %s host.", huh);
500 }
501
502 /* Convenience define for outputting a "gdb_wince_len" type. */
503 #define putlen(huh, what, n) putword((huh), (what), (gdb_wince_len) (n))
504
505 /* Put an arbitrary block of memory to the gdb host. This comes in
506 two chunks an id/dword representing the length and the stream of memory
507 itself. */
508 static void
509 putmemory (LPCSTR huh, gdb_wince_id what, const void *mem, gdb_wince_len len)
510 {
511 putlen (huh, what, len);
512 if (((short) len > 0) && sockwrite (huh, mem, len) != len)
513 stub_error ("error writing %s to host.", huh);
514 }
515
516 /* Output the result of an operation to the host. If res != 0, sends a block of
517 memory starting at mem of len bytes. If res == 0, sends -GetLastError () and
518 avoids sending the mem. */
519 static DWORD
520 getdword (LPCSTR huh, gdb_wince_id what_this)
521 {
522 DWORD n;
523 gdb_wince_id what;
524 do
525 if (sockread (huh, s, &what, sizeof (what)) != sizeof (what))
526 stub_error ("error getting record type from host - %s.", huh);
527 while (what_this != what);
528
529 if (sockread (huh, s, &n, sizeof (n)) != sizeof (n))
530 stub_error ("error getting %s from host.", huh);
531
532 return n;
533 }
534
535 /* Get a an ID (possibly) and a WORD from the host gdb.
536 Don't bother with the id if the main loop has already
537 read it. */
538 static WORD
539 getword (LPCSTR huh, gdb_wince_id what_this)
540 {
541 WORD n;
542 gdb_wince_id what;
543 do
544 if (sockread (huh, s, &what, sizeof (what)) != sizeof (what))
545 stub_error ("error getting record type from host - %s.", huh);
546 while (what_this != what);
547
548 if (sockread (huh, s, &n, sizeof (n)) != sizeof (n))
549 stub_error ("error getting %s from host.", huh);
550
551 return n;
552 }
553
554 /* Handy defines for getting/putting various types of values. */
555 #define gethandle(huh, what) (HANDLE) getdword ((huh), (what))
556 #define getpvoid(huh, what) (LPVOID) getdword ((huh), (what))
557 #define getlen(huh, what) (gdb_wince_len) getword ((huh), (what))
558 #define puthandle(huh, what, h) putdword ((huh), (what), (DWORD) (h))
559 #define putpvoid(huh, what, p) putdword ((huh), (what), (DWORD) (p))
560
561 /* Retrieve the result of an operation from the stub. If nbytes < 0) then nbytes
562 is actually an error and nothing else follows. Use SetLastError to remember this.
563 if nbytes > 0, retrieve a block of *nbytes into buf.
564 */
565 int
566 getresult (LPCSTR huh, gdb_wince_id what, LPVOID buf, gdb_wince_len * nbytes)
567 {
568 gdb_wince_len dummy;
569 if (nbytes == NULL)
570 nbytes = &dummy;
571
572 *nbytes = getlen (huh, what);
573
574 if ((short) *nbytes < 0)
575 {
576 SetLastError (-(short) *nbytes);
577 return 0;
578 }
579
580 if ((gdb_wince_len) sockread (huh, s, buf, *nbytes) != *nbytes)
581 stub_error ("couldn't read information from wince stub - %s", huh);
582
583 return 1;
584 }
585
586 /* Convert "narrow" string to "wide". Manipulates a buffer ring of 8
587 buffers which hold the translated string. This is an arbitrary limit
588 but it is approximately double the current needs of this module.
589 */
590 LPWSTR
591 towide (const char *s, gdb_wince_len * out_len)
592 {
593 static int n = -1;
594 static LPWSTR outs[8] =
595 {NULL /*, NULL, etc. */ };
596 gdb_wince_len dummy;
597
598 if (!out_len)
599 out_len = &dummy;
600
601 /* First determine the length required to hold the converted string. */
602 *out_len = sizeof (WCHAR) * MultiByteToWideChar (CP_ACP, 0, s, -1, NULL, 0);
603 if (!*out_len)
604 return NULL; /* The conversion failed */
605
606 if (++n >= (sizeof (outs) / sizeof (outs[0])))
607 n = 0; /* wrap */
608
609 /* Allocate space for the converted string, reusing any previously allocated
610 space, if applicable. Note that if outs[n] is NULL, realloc will act as
611 a malloc (under cygwin, at least).
612 */
613 outs[n] = (LPWSTR) realloc (outs[n], *out_len);
614 memset (outs[n], 0, *out_len);
615 (void) MultiByteToWideChar (CP_ACP, 0, s, -1, outs[n], *out_len);
616 return outs[n];
617 }
618
619 /******************** Emulation routines start here. ********************
620
621 The functions below are modelled after their Win32 counterparts. They are named
622 similarly to Win32 and take exactly the same arguments except where otherwise noted.
623 They communicate with the stub on the hand-held device by sending their arguments
624 over the socket and waiting for results from the socket.
625
626 There is one universal change. In cases where a length is expected to be returned
627 in a DWORD, we use a gdb_wince_len type instead. Currently this is an unsigned short
628 which is smaller than the standard Win32 DWORD. This is done to minimize unnecessary
629 traffic since the connection to Windows CE can be slow. To change this, modify the
630 typedef in wince-stub.h and change the putlen/getlen macros in this file and in
631 the stub.
632 */
633 static int
634 create_process (LPSTR exec_file, LPSTR args, DWORD flags, PROCESS_INFORMATION * pi)
635 {
636 gdb_wince_len len;
637 LPWSTR buf;
638
639 buf = towide (exec_file, &len);
640 putmemory ("CreateProcess exec_file", GDB_CREATEPROCESS, buf, len);
641 buf = towide (args, &len);
642 putmemory ("CreateProcess args", GDB_CREATEPROCESS, buf, len);
643 putdword ("CreateProcess flags", GDB_CREATEPROCESS, flags);
644 return getresult ("CreateProcess result", GDB_CREATEPROCESS, pi, NULL);
645 }
646
647 /* Emulate TerminateProcess. Don't bother with the second argument since CE
648 ignores it.
649 */
650 static int
651 terminate_process (HANDLE h)
652 {
653 gdb_wince_result res;
654 if (s < 0)
655 return 1;
656 puthandle ("TerminateProcess handle", GDB_TERMINATEPROCESS, h);
657 return getresult ("TerminateProcess result", GDB_TERMINATEPROCESS, &res, NULL);
658 }
659
660 static int
661 wait_for_debug_event (DEBUG_EVENT * ev, DWORD ms)
662 {
663 if (s < 0)
664 return 1;
665 putdword ("WaitForDebugEvent ms", GDB_WAITFORDEBUGEVENT, ms);
666 return getresult ("WaitForDebugEvent event", GDB_WAITFORDEBUGEVENT, ev, NULL);
667 }
668
669 static int
670 get_thread_context (HANDLE h, CONTEXT * c)
671 {
672 if (s < 0)
673 return 1;
674 puthandle ("GetThreadContext handle", GDB_GETTHREADCONTEXT, h);
675 putdword ("GetThreadContext flags", GDB_GETTHREADCONTEXT, c->ContextFlags);
676 return getresult ("GetThreadContext context", GDB_GETTHREADCONTEXT, c, NULL);
677 }
678
679 static int
680 set_thread_context (HANDLE h, CONTEXT * c)
681 {
682 gdb_wince_result res;
683 if (s < 0)
684 return 1;
685 puthandle ("SetThreadContext handle", GDB_SETTHREADCONTEXT, h);
686 putmemory ("SetThreadContext context", GDB_SETTHREADCONTEXT, c, sizeof (*c));
687 return getresult ("SetThreadContext context", GDB_SETTHREADCONTEXT, &res, NULL);
688 }
689
690 static int
691 read_process_memory (HANDLE h, LPCVOID where, LPVOID buf, gdb_wince_len len, gdb_wince_len * nbytes)
692 {
693 if (s < 0)
694 return 1;
695 puthandle ("ReadProcessMemory handle", GDB_READPROCESSMEMORY, h);
696 putpvoid ("ReadProcessMemory location", GDB_READPROCESSMEMORY, where);
697 putlen ("ReadProcessMemory size", GDB_READPROCESSMEMORY, len);
698
699 return getresult ("ReadProcessMemory buf", GDB_READPROCESSMEMORY, buf, nbytes);
700 }
701
702 static int
703 write_process_memory (HANDLE h, LPCVOID where, LPCVOID buf, gdb_wince_len len, gdb_wince_len * nbytes)
704 {
705 if (s < 0)
706 return 1;
707 puthandle ("WriteProcessMemory handle", GDB_WRITEPROCESSMEMORY, h);
708 putpvoid ("WriteProcessMemory location", GDB_WRITEPROCESSMEMORY, where);
709 putmemory ("WriteProcProcessMemory buf", GDB_WRITEPROCESSMEMORY, buf, len);
710
711 return getresult ("WriteProcessMemory result", GDB_WRITEPROCESSMEMORY, nbytes, NULL);
712 }
713
714 static int
715 remote_read_bytes (CORE_ADDR memaddr, char *myaddr, int len)
716 {
717 gdb_wince_len nbytes;
718 if (!read_process_memory (current_process_handle, (LPCVOID) memaddr,
719 (LPVOID) myaddr, len, &nbytes))
720 return -1;
721 return nbytes;
722 }
723
724 static int
725 remote_write_bytes (CORE_ADDR memaddr, char *myaddr, int len)
726 {
727 gdb_wince_len nbytes;
728 if (!write_process_memory (current_process_handle, (LPCVOID) memaddr,
729 (LPCVOID) myaddr, len, &nbytes))
730 return -1;
731 return nbytes;
732 }
733
734 /* This is not a standard Win32 function. It instructs the stub to return TRUE
735 if the thread referenced by HANDLE h is alive.
736 */
737 static int
738 thread_alive (HANDLE h)
739 {
740 gdb_wince_result res;
741 if (s < 0)
742 return 1;
743 puthandle ("ThreadAlive handle", GDB_THREADALIVE, h);
744 return getresult ("ThreadAlive result", GDB_THREADALIVE, &res, NULL);
745 }
746
747 static int
748 suspend_thread (HANDLE h)
749 {
750 if (s < 0)
751 return 1;
752 puthandle ("SuspendThread handle", GDB_SUSPENDTHREAD, h);
753 return (int) getdword ("SuspendThread result", GDB_SUSPENDTHREAD);
754 }
755
756 static int
757 resume_thread (HANDLE h)
758 {
759 if (s < 0)
760 return 1;
761 puthandle ("ResumeThread handle", GDB_RESUMETHREAD, h);
762 return (int) getdword ("SuspendThread result", GDB_RESUMETHREAD);
763 }
764
765 static int
766 continue_debug_event (DWORD pid, DWORD tid, DWORD status)
767 {
768 gdb_wince_result res;
769 if (s < 0)
770 return 0;
771 putdword ("ContinueDebugEvent pid", GDB_CONTINUEDEBUGEVENT, pid);
772 putdword ("ContinueDebugEvent tid", GDB_CONTINUEDEBUGEVENT, tid);
773 putdword ("ContinueDebugEvent status", GDB_CONTINUEDEBUGEVENT, status);
774 return getresult ("ContinueDebugEvent result", GDB_CONTINUEDEBUGEVENT, &res, NULL);
775 }
776
777 static int
778 close_handle (HANDLE h)
779 {
780 gdb_wince_result res;
781 if (s < 0)
782 return 1;
783 puthandle ("CloseHandle handle", GDB_CLOSEHANDLE, h);
784 return (int) getresult ("CloseHandle result", GDB_CLOSEHANDLE, &res, NULL);
785 }
786
787 /* This is not a standard Win32 interface. This function tells the stub
788 to terminate.
789 */
790 static void
791 stop_stub ()
792 {
793 if (s < 0)
794 return;
795 (void) putdword ("Stopping gdb stub", GDB_STOPSTUB, 0);
796 s = -1;
797 }
798
799 /******************** End of emulation routines. ********************/
800 /******************** End of stub interface ********************/
801
802 /* Find a thread record given a thread id.
803 If get_context then also retrieve the context for this
804 thread. */
805 static thread_info *
806 thread_rec (DWORD id, int get_context)
807 {
808 thread_info *th;
809
810 for (th = &thread_head; (th = th->next) != NULL;)
811 if (th->id == id)
812 {
813 if (!th->suspend_count && get_context)
814 {
815 if (get_context > 0 && th != this_thread)
816 th->suspend_count = suspend_thread (th->h) + 1;
817 else if (get_context < 0)
818 th->suspend_count = -1;
819
820 th->context.ContextFlags = CONTEXT_DEBUGGER;
821 get_thread_context (th->h, &th->context);
822 }
823 return th;
824 }
825
826 return NULL;
827 }
828
829 /* Add a thread to the thread list */
830 static thread_info *
831 child_add_thread (DWORD id, HANDLE h)
832 {
833 thread_info *th;
834
835 if ((th = thread_rec (id, FALSE)))
836 return th;
837
838 th = (thread_info *) xmalloc (sizeof (*th));
839 memset (th, 0, sizeof (*th));
840 th->id = id;
841 th->h = h;
842 th->next = thread_head.next;
843 thread_head.next = th;
844 add_thread (id);
845 return th;
846 }
847
848 /* Clear out any old thread list and reintialize it to a
849 pristine state. */
850 static void
851 child_init_thread_list ()
852 {
853 thread_info *th = &thread_head;
854
855 DEBUG_EVENTS (("gdb: child_init_thread_list\n"));
856 init_thread_list ();
857 while (th->next != NULL)
858 {
859 thread_info *here = th->next;
860 th->next = here->next;
861 (void) close_handle (here->h);
862 free (here);
863 }
864 }
865
866 /* Delete a thread from the list of threads */
867 static void
868 child_delete_thread (DWORD id)
869 {
870 thread_info *th;
871
872 if (info_verbose)
873 printf_unfiltered ("[Deleting %s]\n", target_pid_to_str (id));
874 delete_thread (id);
875
876 for (th = &thread_head;
877 th->next != NULL && th->next->id != id;
878 th = th->next)
879 continue;
880
881 if (th->next != NULL)
882 {
883 thread_info *here = th->next;
884 th->next = here->next;
885 close_handle (here->h);
886 free (here);
887 }
888 }
889
890 static void
891 check (BOOL ok, const char *file, int line)
892 {
893 if (!ok)
894 printf_filtered ("error return %s:%d was %d\n", file, line, GetLastError ());
895 }
896
897 /* Return a pointer into a CONTEXT field indexed by gdb register number.
898 Return a pointer to an address pointing to zero if there is no
899 corresponding CONTEXT field for the given register number.
900 */
901 static ULONG *
902 regptr (LPCONTEXT c, int r)
903 {
904 static ULONG zero = 0;
905 ULONG *p;
906 if (mappings[r] < 0)
907 p = &zero;
908 else
909 p = (ULONG *) (((char *) c) + mappings[r]);
910 return p;
911 }
912
913 static void
914 do_child_fetch_inferior_registers (int r)
915 {
916 if (r >= 0)
917 {
918 supply_register (r, (char *) regptr (&current_thread->context, r));
919 }
920 else
921 {
922 for (r = 0; r < NUM_REGS; r++)
923 do_child_fetch_inferior_registers (r);
924 }
925 }
926
927 static void
928 child_fetch_inferior_registers (int r)
929 {
930 current_thread = thread_rec (inferior_pid, TRUE);
931 do_child_fetch_inferior_registers (r);
932 }
933
934 static void
935 do_child_store_inferior_registers (int r)
936 {
937 if (r >= 0)
938 read_register_gen (r, ((char *) &current_thread->context) + mappings[r]);
939 else
940 {
941 for (r = 0; r < NUM_REGS; r++)
942 do_child_store_inferior_registers (r);
943 }
944 }
945
946 /* Store a new register value into the current thread context */
947 static void
948 child_store_inferior_registers (int r)
949 {
950 current_thread = thread_rec (inferior_pid, TRUE);
951 do_child_store_inferior_registers (r);
952 }
953
954 /* Wait for child to do something. Return pid of child, or -1 in case
955 of error; store status through argument pointer OURSTATUS. */
956
957 static int
958 handle_load_dll (PTR dummy)
959 {
960 LOAD_DLL_DEBUG_INFO *event = &current_event.u.LoadDll;
961 char dll_buf[MAX_PATH + 1];
962 char *p, *bufp, *imgp, *dll_name, *dll_basename;
963 int len;
964
965 dll_buf[0] = dll_buf[sizeof (dll_buf) - 1] = '\0';
966 if (!event->lpImageName)
967 return 1;
968
969 len = 0;
970 for (bufp = dll_buf, imgp = event->lpImageName;
971 bufp < dll_buf + sizeof (dll_buf);
972 bufp += 16, imgp += 16)
973 {
974 gdb_wince_len nbytes = 0;
975 (void) read_process_memory (current_process_handle,
976 imgp, bufp, 16, &nbytes);
977
978 if (!nbytes && bufp == dll_buf)
979 return 1; /* couldn't read it */
980 for (p = bufp; p < bufp + nbytes; p++)
981 {
982 len++;
983 if (*p == '\0')
984 goto out;
985 if (event->fUnicode)
986 p++;
987 }
988 if (!nbytes)
989 break;
990 }
991
992 out:
993 if (!len)
994 return 1;
995 dll_buf[len] = '\0';
996 dll_name = alloca (len);
997
998 if (!dll_name)
999 return 1;
1000
1001 if (!event->fUnicode)
1002 memcpy (dll_name, dll_buf, len);
1003 else
1004 WideCharToMultiByte (CP_ACP, 0, (LPCWSTR) dll_buf, len,
1005 dll_name, len, 0, 0);
1006
1007 while ((p = strchr (dll_name, '\\')))
1008 *p = '/';
1009
1010 /* FIXME!! It would be nice to define one symbol which pointed to the
1011 front of the dll if we can't find any symbols. */
1012
1013 if (!(dll_basename = strrchr (dll_name, '/')))
1014 dll_basename = dll_name;
1015 else
1016 dll_basename++;
1017
1018 /* The symbols in a dll are offset by 0x1000, which is the
1019 the offset from 0 of the first byte in an image - because
1020 of the file header and the section alignment.
1021
1022 FIXME: Is this the real reason that we need the 0x1000 ? */
1023
1024 printf_unfiltered ("%x:%s", event->lpBaseOfDll, dll_name);
1025 #if 0 /* FIXME: Need to use RAPI stuff to read the file someday. */
1026 {
1027 struct section_addr_info section_addrs;
1028 memset (&section_addrs, 0, sizeof (section_addrs));
1029 section_addrs.text_addr = (int) event->lpBaseOfDll + 0x1000;
1030 symbol_file_add (dll_name, 0, &section_addrs, 0, OBJF_SHARED);
1031 }
1032 #endif
1033 printf_unfiltered ("\n");
1034
1035 return 1;
1036 }
1037
1038 /* Handle DEBUG_STRING output from child process.
1039 Cygwin prepends its messages with a "cygwin:". Interpret this as
1040 a Cygwin signal. Otherwise just print the string as a warning. */
1041 static void
1042 handle_output_debug_string (struct target_waitstatus *ourstatus)
1043 {
1044 char p[256];
1045 char s[255];
1046 char *q;
1047 gdb_wince_len nbytes_read;
1048 gdb_wince_len nbytes = current_event.u.DebugString.nDebugStringLength;
1049
1050 if (nbytes > 255)
1051 nbytes = 255;
1052
1053 memset (p, 0, sizeof (p));
1054 if (!read_process_memory (current_process_handle,
1055 current_event.u.DebugString.lpDebugStringData,
1056 &p, nbytes, &nbytes_read)
1057 || !*p)
1058 return;
1059
1060 memset (s, 0, sizeof (s));
1061 WideCharToMultiByte (CP_ACP, 0, (LPCWSTR) p, (int) nbytes_read, s,
1062 sizeof (s) - 1, NULL, NULL);
1063 q = strchr (s, '\n');
1064 if (q != NULL)
1065 {
1066 *q = '\0';
1067 if (*--q = '\r')
1068 *q = '\0';
1069 }
1070
1071 warning (s);
1072 return;
1073 }
1074
1075 /* Handle target exceptions. */
1076 static int
1077 handle_exception (struct target_waitstatus *ourstatus)
1078 {
1079 thread_info *th;
1080
1081 if (current_event.u.Exception.dwFirstChance)
1082 return 0;
1083
1084 ourstatus->kind = TARGET_WAITKIND_STOPPED;
1085
1086 /* Record the context of the current thread */
1087 th = thread_rec (current_event.dwThreadId, -1);
1088
1089 switch (current_event.u.Exception.ExceptionRecord.ExceptionCode)
1090 {
1091 case EXCEPTION_ACCESS_VIOLATION:
1092 DEBUG_EXCEPT (("gdb: Target exception ACCESS_VIOLATION at 0x%08x\n",
1093 (unsigned) current_event.u.Exception.ExceptionRecord.ExceptionAddress));
1094 ourstatus->value.sig = TARGET_SIGNAL_SEGV;
1095 break;
1096 case STATUS_STACK_OVERFLOW:
1097 DEBUG_EXCEPT (("gdb: Target exception STACK_OVERFLOW at 0x%08x\n",
1098 (unsigned) current_event.u.Exception.ExceptionRecord.ExceptionAddress));
1099 ourstatus->value.sig = TARGET_SIGNAL_SEGV;
1100 break;
1101 case EXCEPTION_BREAKPOINT:
1102 DEBUG_EXCEPT (("gdb: Target exception BREAKPOINT at 0x%08x\n",
1103 (unsigned) current_event.u.Exception.ExceptionRecord.ExceptionAddress));
1104 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
1105 break;
1106 case DBG_CONTROL_C:
1107 DEBUG_EXCEPT (("gdb: Target exception CONTROL_C at 0x%08x\n",
1108 (unsigned) current_event.u.Exception.ExceptionRecord.ExceptionAddress));
1109 ourstatus->value.sig = TARGET_SIGNAL_INT;
1110 /* User typed CTRL-C. Continue with this status */
1111 last_sig = SIGINT; /* FIXME - should check pass state */
1112 break;
1113 case EXCEPTION_SINGLE_STEP:
1114 DEBUG_EXCEPT (("gdb: Target exception SINGLE_STEP at 0x%08x\n",
1115 (unsigned) current_event.u.Exception.ExceptionRecord.ExceptionAddress));
1116 ourstatus->value.sig = TARGET_SIGNAL_TRAP;
1117 break;
1118 default:
1119 /* This may be a structured exception handling exception. In
1120 that case, we want to let the program try to handle it, and
1121 only break if we see the exception a second time. */
1122
1123 printf_unfiltered ("gdb: unknown target exception 0x%08x at 0x%08x\n",
1124 current_event.u.Exception.ExceptionRecord.ExceptionCode,
1125 current_event.u.Exception.ExceptionRecord.ExceptionAddress);
1126 ourstatus->value.sig = TARGET_SIGNAL_UNKNOWN;
1127 break;
1128 }
1129 exception_count++;
1130 return 1;
1131 }
1132
1133 /* Resume all artificially suspended threads if we are continuing
1134 execution */
1135 static BOOL
1136 child_continue (DWORD continue_status, int id)
1137 {
1138 int i;
1139 thread_info *th;
1140 BOOL res;
1141
1142 DEBUG_EVENTS (("ContinueDebugEvent (cpid=%d, ctid=%d, DBG_CONTINUE);\n",
1143 (unsigned) current_event.dwProcessId, (unsigned) current_event.dwThreadId));
1144 res = continue_debug_event (current_event.dwProcessId,
1145 current_event.dwThreadId,
1146 continue_status);
1147 if (res)
1148 for (th = &thread_head; (th = th->next) != NULL;)
1149 if (((id == -1) || (id == th->id)) && th->suspend_count)
1150 {
1151 for (i = 0; i < th->suspend_count; i++)
1152 (void) resume_thread (th->h);
1153 th->suspend_count = 0;
1154 }
1155
1156 return res;
1157 }
1158
1159 /* Get the next event from the child. Return 1 if the event requires
1160 handling by WFI (or whatever).
1161 */
1162 static int
1163 get_child_debug_event (int pid, struct target_waitstatus *ourstatus, DWORD * event_code, int *retval)
1164 {
1165 BOOL debug_event;
1166 DWORD continue_status;
1167 int breakout = 1;
1168
1169 if (!(debug_event = wait_for_debug_event (&current_event, 1000)))
1170 {
1171 breakout = *retval = *event_code = 0;
1172 goto out;
1173 }
1174
1175 this_thread = thread_rec (current_event.dwThreadId, FALSE);
1176 event_count++;
1177 continue_status = DBG_CONTINUE;
1178 *retval = 0;
1179 switch (*event_code = current_event.dwDebugEventCode)
1180 {
1181 case CREATE_THREAD_DEBUG_EVENT:
1182 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%x code=%s)\n",
1183 (unsigned) current_event.dwProcessId,
1184 (unsigned) current_event.dwThreadId,
1185 "CREATE_THREAD_DEBUG_EVENT"));
1186 /* Record the existence of this thread */
1187 child_add_thread (current_event.dwThreadId,
1188 current_event.u.CreateThread.hThread);
1189 if (info_verbose)
1190 printf_unfiltered ("[New %s]\n",
1191 target_pid_to_str (current_event.dwThreadId));
1192 break;
1193
1194 case EXIT_THREAD_DEBUG_EVENT:
1195 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
1196 (unsigned) current_event.dwProcessId,
1197 (unsigned) current_event.dwThreadId,
1198 "EXIT_THREAD_DEBUG_EVENT"));
1199 child_delete_thread (current_event.dwThreadId);
1200 break;
1201
1202 case CREATE_PROCESS_DEBUG_EVENT:
1203 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
1204 (unsigned) current_event.dwProcessId,
1205 (unsigned) current_event.dwThreadId,
1206 "CREATE_PROCESS_DEBUG_EVENT"));
1207 current_process_handle = current_event.u.CreateProcessInfo.hProcess;
1208
1209 main_thread_id = inferior_pid = current_event.dwThreadId;
1210 /* Add the main thread */
1211 current_thread = child_add_thread (inferior_pid,
1212 current_event.u.CreateProcessInfo.hThread);
1213 break;
1214
1215 case EXIT_PROCESS_DEBUG_EVENT:
1216 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
1217 (unsigned) current_event.dwProcessId,
1218 (unsigned) current_event.dwThreadId,
1219 "EXIT_PROCESS_DEBUG_EVENT"));
1220 ourstatus->kind = TARGET_WAITKIND_EXITED;
1221 ourstatus->value.integer = current_event.u.ExitProcess.dwExitCode;
1222 close_handle (current_process_handle);
1223 *retval = current_event.dwProcessId;
1224 goto out;
1225
1226 case LOAD_DLL_DEBUG_EVENT:
1227 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
1228 (unsigned) current_event.dwProcessId,
1229 (unsigned) current_event.dwThreadId,
1230 "LOAD_DLL_DEBUG_EVENT"));
1231 catch_errors (handle_load_dll, NULL, (char *) "", RETURN_MASK_ALL);
1232 registers_changed (); /* mark all regs invalid */
1233 break;
1234
1235 case UNLOAD_DLL_DEBUG_EVENT:
1236 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
1237 (unsigned) current_event.dwProcessId,
1238 (unsigned) current_event.dwThreadId,
1239 "UNLOAD_DLL_DEBUG_EVENT"));
1240 break; /* FIXME: don't know what to do here */
1241
1242 case EXCEPTION_DEBUG_EVENT:
1243 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
1244 (unsigned) current_event.dwProcessId,
1245 (unsigned) current_event.dwThreadId,
1246 "EXCEPTION_DEBUG_EVENT"));
1247 if (handle_exception (ourstatus))
1248 {
1249 char buf[32];
1250 *retval = current_event.dwThreadId;
1251 remote_read_bytes (read_pc (), buf, sizeof (buf));
1252 dcache_xfer_memory (remote_dcache, read_pc (), buf, sizeof (buf), 0);
1253 goto out;
1254 }
1255 continue_status = DBG_EXCEPTION_NOT_HANDLED;
1256 break;
1257
1258 case OUTPUT_DEBUG_STRING_EVENT: /* message from the kernel */
1259 DEBUG_EVENTS (("gdb: kernel event for pid=%d tid=%d code=%s)\n",
1260 (unsigned) current_event.dwProcessId,
1261 (unsigned) current_event.dwThreadId,
1262 "OUTPUT_DEBUG_STRING_EVENT"));
1263 handle_output_debug_string (ourstatus);
1264 break;
1265 default:
1266 printf_unfiltered ("gdb: kernel event for pid=%d tid=%d\n",
1267 current_event.dwProcessId,
1268 current_event.dwThreadId);
1269 printf_unfiltered (" unknown event code %d\n",
1270 current_event.dwDebugEventCode);
1271 break;
1272 }
1273
1274 breakout = 0;
1275 CHECK (child_continue (continue_status, -1));
1276
1277 out:
1278 return breakout;
1279 }
1280
1281 /* Wait for interesting events to occur in the target process. */
1282 static int
1283 child_wait (int pid, struct target_waitstatus *ourstatus)
1284 {
1285 DWORD event_code;
1286 int retval;
1287
1288 /* We loop when we get a non-standard exception rather than return
1289 with a SPURIOUS because resume can try and step or modify things,
1290 which needs a current_thread->h. But some of these exceptions mark
1291 the birth or death of threads, which mean that the current thread
1292 isn't necessarily what you think it is. */
1293
1294 while (1)
1295 if (get_child_debug_event (pid, ourstatus, &event_code, &retval))
1296 return retval;
1297 else
1298 {
1299 int detach = 0;
1300
1301 if (ui_loop_hook != NULL)
1302 detach = ui_loop_hook (0);
1303
1304 if (detach)
1305 child_kill_inferior ();
1306 }
1307 }
1308
1309 /* Print status information about what we're accessing. */
1310
1311 static void
1312 child_files_info (ignore)
1313 struct target_ops *ignore;
1314 {
1315 printf_unfiltered ("\tUsing the running image of child %s.\n",
1316 target_pid_to_str (inferior_pid));
1317 }
1318
1319 /* ARGSUSED */
1320 static void
1321 child_open (arg, from_tty)
1322 char *arg;
1323 int from_tty;
1324 {
1325 error ("Use the \"run\" command to start a child process.");
1326 }
1327
1328 #define FACTOR (0x19db1ded53ea710LL)
1329 #define NSPERSEC 10000000
1330
1331 /* Convert a Win32 time to "UNIX" format. */
1332 long
1333 to_time_t (FILETIME * ptr)
1334 {
1335 /* A file time is the number of 100ns since jan 1 1601
1336 stuffed into two long words.
1337 A time_t is the number of seconds since jan 1 1970. */
1338
1339 long rem;
1340 long long x = ((long long) ptr->dwHighDateTime << 32) + ((unsigned) ptr->dwLowDateTime);
1341 x -= FACTOR; /* number of 100ns between 1601 and 1970 */
1342 rem = x % ((long long) NSPERSEC);
1343 rem += (NSPERSEC / 2);
1344 x /= (long long) NSPERSEC; /* number of 100ns in a second */
1345 x += (long long) (rem / NSPERSEC);
1346 return x;
1347 }
1348
1349 /* Upload a file to the remote device depending on the user's
1350 'set remoteupload' specification. */
1351 char *
1352 upload_to_device (const char *to, const char *from)
1353 {
1354 HANDLE h;
1355 const char *dir = remote_directory ? : "\\gdb";
1356 int len;
1357 static char *remotefile = NULL;
1358 LPWSTR wstr;
1359 char *p;
1360 DWORD err;
1361 const char *in_to = to;
1362 FILETIME ctime, atime, wtime;
1363 struct stat st;
1364 int fd;
1365
1366 /* Look for a path separator and only use trailing part. */
1367 while ((p = strpbrk (to, "/\\")) != NULL)
1368 to = p + 1;
1369
1370 if (!*to)
1371 error ("no filename found to upload - %s.", in_to);
1372
1373 len = strlen (dir) + strlen (to) + 2;
1374 remotefile = (char *) realloc (remotefile, len);
1375 strcpy (remotefile, dir);
1376 strcat (remotefile, "\\");
1377 strcat (remotefile, to);
1378
1379 if (upload_when == UPLOAD_NEVER)
1380 return remotefile; /* Don't bother uploading. */
1381
1382 /* Open the source. */
1383 if ((fd = openp (getenv ("PATH"), TRUE, (char *) from, O_RDONLY, 0, NULL)) < 0)
1384 error ("couldn't open %s", from);
1385
1386 /* Get the time for later comparison. */
1387 if (fstat (fd, &st))
1388 st.st_mtime = (time_t) - 1;
1389
1390 /* Always attempt to create the directory on the remote system. */
1391 wstr = towide (dir, NULL);
1392 (void) CeCreateDirectory (wstr, NULL);
1393
1394 /* Attempt to open the remote file, creating it if it doesn't exist. */
1395 wstr = towide (remotefile, NULL);
1396 h = CeCreateFile (wstr, GENERIC_READ | GENERIC_WRITE, 0, NULL,
1397 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1398
1399 /* Some kind of problem? */
1400 err = CeGetLastError ();
1401 if (h == NULL)
1402 error ("error creating file to \"%s\". Windows error %d.",
1403 remotefile, err);
1404
1405 /* See if we need to upload the file. */
1406 if (upload_when == UPLOAD_ALWAYS ||
1407 err != ERROR_ALREADY_EXISTS ||
1408 !CeGetFileTime (h, &ctime, &atime, &wtime) ||
1409 to_time_t (&wtime) < st.st_mtime)
1410 {
1411 DWORD nbytes;
1412 char buf[4096];
1413 int n;
1414
1415 /* Upload the file. */
1416 while ((n = read (fd, buf, sizeof (buf))) > 0)
1417 if (!CeWriteFile (h, buf, (DWORD) n, &nbytes, NULL))
1418 error ("error writing to remote device - %d.",
1419 CeGetLastError ());
1420 }
1421
1422 close (fd);
1423 CeCloseHandle (h);
1424
1425 return remotefile;
1426 }
1427
1428 /* Initialize the connection to the remote device. */
1429 static void
1430 wince_initialize ()
1431 {
1432 int tmp;
1433 char args[256];
1434 char *hostname;
1435 struct sockaddr_in sin;
1436 char *stub_file_name;
1437 int s0;
1438 PROCESS_INFORMATION pi;
1439
1440 if (!connection_initialized)
1441 switch (CeRapiInit ())
1442 {
1443 case 0:
1444 connection_initialized = 1;
1445 break;
1446 default:
1447 CeRapiUninit ();
1448 error ("Can't initialize connection to remote device.\n");
1449 break;
1450 }
1451
1452 /* Upload the stub to the handheld device. */
1453 stub_file_name = upload_to_device ("wince-stub.exe", WINCE_STUB);
1454 strcpy (args, stub_file_name);
1455
1456 if (remote_add_host)
1457 {
1458 strcat (args, " ");
1459 hostname = strchr (args, '\0');
1460 if (gethostname (hostname, sizeof (args) - strlen (args)))
1461 error ("couldn't get hostname of this system.");
1462 }
1463
1464 /* Get a socket. */
1465 if ((s0 = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1466 stub_error ("Couldn't connect to host system.");
1467
1468 /* Allow rapid reuse of the port. */
1469 tmp = 1;
1470 (void) setsockopt (s0, SOL_SOCKET, SO_REUSEADDR, (char *) &tmp, sizeof (tmp));
1471
1472
1473 /* Set up the information for connecting to the host gdb process. */
1474 memset (&sin, 0, sizeof (sin));
1475 sin.sin_family = AF_INET;
1476 sin.sin_port = htons (7000); /* FIXME: This should be configurable */
1477
1478 if (bind (s0, (struct sockaddr *) &sin, sizeof (sin)))
1479 error ("couldn't bind socket");
1480
1481 if (listen (s0, 1))
1482 error ("Couldn't open socket for listening.\n");
1483
1484 /* Start up the stub on the remote device. */
1485 if (!CeCreateProcess (towide (stub_file_name, NULL), towide (args, NULL),
1486 NULL, NULL, 0, 0, NULL, NULL, NULL, &pi))
1487 error ("Unable to start remote stub '%s'. Windows CE error %d.",
1488 stub_file_name, CeGetLastError ());
1489
1490 /* Wait for a connection */
1491
1492 if ((s = accept (s0, NULL, NULL)) < 0)
1493 error ("couldn't set up server for connection.");
1494
1495 close (s0);
1496 }
1497
1498 /* Start an inferior win32 child process and sets inferior_pid to its pid.
1499 EXEC_FILE is the file to run.
1500 ALLARGS is a string containing the arguments to the program.
1501 ENV is the environment vector to pass. Errors reported with error(). */
1502 static void
1503 child_create_inferior (char *exec_file, char *args, char **env)
1504 {
1505 PROCESS_INFORMATION pi;
1506 struct target_waitstatus dummy;
1507 int ret;
1508 DWORD flags, event_code;
1509 char *exec_and_args;
1510
1511 if (!exec_file)
1512 error ("No executable specified, use `target exec'.\n");
1513
1514 flags = DEBUG_PROCESS;
1515
1516 wince_initialize (); /* Make sure we've got a connection. */
1517 if (!remote_dcache)
1518 remote_dcache = dcache_init (remote_read_bytes, remote_write_bytes);
1519 else
1520 dcache_flush (remote_dcache);
1521
1522 exec_file = upload_to_device (exec_file, exec_file);
1523
1524 while (*args == ' ')
1525 args++;
1526
1527 /* Allocate space for "command<sp>args" */
1528 if (*args == '\0')
1529 {
1530 exec_and_args = alloca (strlen (exec_file) + 1);
1531 strcpy (exec_and_args, exec_file);
1532 }
1533 else
1534 {
1535 exec_and_args = alloca (strlen (exec_file + strlen (args) + 2));
1536 sprintf (exec_and_args, "%s %s", exec_file, args);
1537 }
1538
1539 memset (&pi, 0, sizeof (pi));
1540 /* Execute the process */
1541 if (!create_process (exec_file, exec_and_args, flags, &pi))
1542 error ("Error creating process %s, (error %d)\n", exec_file, GetLastError ());
1543
1544 exception_count = 0;
1545 event_count = 0;
1546
1547 current_process_handle = pi.hProcess;
1548 current_event.dwProcessId = pi.dwProcessId;
1549 memset (&current_event, 0, sizeof (current_event));
1550 inferior_pid = current_event.dwThreadId = pi.dwThreadId;
1551 push_target (&child_ops);
1552 child_init_thread_list ();
1553 child_add_thread (pi.dwThreadId, pi.hThread);
1554 init_wait_for_inferior ();
1555 clear_proceed_status ();
1556 target_terminal_init ();
1557 target_terminal_inferior ();
1558
1559
1560 /* Run until process and threads are loaded */
1561 do
1562 get_child_debug_event (inferior_pid, &dummy, &event_code, &ret);
1563 while (event_code != CREATE_PROCESS_DEBUG_EVENT);
1564
1565 proceed ((CORE_ADDR) -1, TARGET_SIGNAL_0, 0);
1566 }
1567
1568 /* Chile has gone bye-bye. */
1569 static void
1570 child_mourn_inferior ()
1571 {
1572 (void) child_continue (DBG_CONTINUE, -1);
1573 unpush_target (&child_ops);
1574 stop_stub ();
1575 CeRapiUninit ();
1576 connection_initialized = 0;
1577 generic_mourn_inferior ();
1578 }
1579
1580 /* Move memory from child to/from gdb. */
1581 int
1582 child_xfer_memory (CORE_ADDR memaddr, char *our, int len,
1583 int write, struct target_ops *target)
1584 {
1585 if (len <= 0)
1586 return 0;
1587 return dcache_xfer_memory (remote_dcache, memaddr, our, len, write);
1588 }
1589
1590 /* Terminate the process and wait for child to tell us it has completed. */
1591 void
1592 child_kill_inferior (void)
1593 {
1594 CHECK (terminate_process (current_process_handle));
1595
1596 for (;;)
1597 {
1598 if (!child_continue (DBG_CONTINUE, -1))
1599 break;
1600 if (!wait_for_debug_event (&current_event, INFINITE))
1601 break;
1602 if (current_event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
1603 break;
1604 }
1605
1606 CHECK (close_handle (current_process_handle));
1607 close_handle (current_thread->h);
1608 target_mourn_inferior (); /* or just child_mourn_inferior? */
1609 }
1610
1611 #ifdef MIPS
1612 static void
1613 undoSStep (thread_info * th)
1614 {
1615 if (th->stepped)
1616 {
1617 memory_remove_breakpoint (th->step_pc, (void *) &th->step_prev);
1618 th->stepped = 0;
1619 }
1620 }
1621
1622 void
1623 wince_software_single_step (unsigned int ignore, int insert_breakpoints_p)
1624 {
1625 unsigned long pc;
1626 thread_info *th = current_thread; /* Info on currently selected thread */
1627 CORE_ADDR mips_next_pc (CORE_ADDR pc);
1628
1629 if (!insert_breakpoints_p)
1630 {
1631 undoSStep (th);
1632 return;
1633 }
1634
1635 th->stepped = 1;
1636 pc = read_register (PC_REGNUM);
1637 th->step_pc = mips_next_pc (pc);
1638 th->step_prev = 0;
1639 memory_insert_breakpoint (th->step_pc, (void *) &th->step_prev);
1640 }
1641 #elif SHx
1642 /* Hitachi SH architecture instruction encoding masks */
1643
1644 #define COND_BR_MASK 0xff00
1645 #define UCOND_DBR_MASK 0xe000
1646 #define UCOND_RBR_MASK 0xf0df
1647 #define TRAPA_MASK 0xff00
1648
1649 #define COND_DISP 0x00ff
1650 #define UCOND_DISP 0x0fff
1651 #define UCOND_REG 0x0f00
1652
1653 /* Hitachi SH instruction opcodes */
1654
1655 #define BF_INSTR 0x8b00
1656 #define BT_INSTR 0x8900
1657 #define BRA_INSTR 0xa000
1658 #define BSR_INSTR 0xb000
1659 #define JMP_INSTR 0x402b
1660 #define JSR_INSTR 0x400b
1661 #define RTS_INSTR 0x000b
1662 #define RTE_INSTR 0x002b
1663 #define TRAPA_INSTR 0xc300
1664 #define SSTEP_INSTR 0xc3ff
1665
1666
1667 #define T_BIT_MASK 0x0001
1668
1669 /* Undo the effect of a previous doSStep. If we single stepped,
1670 restore the old instruction. */
1671
1672 static void
1673 undoSStep (thread_info * th)
1674 {
1675 if (th->stepped)
1676 {
1677 gdb_wince_len done;
1678 write_process_memory (current_process_handle, (LPVOID) th->step_pc,
1679 (LPVOID) & th->step_instr, sizeof (short), &done);
1680 if (done != sizeof (short))
1681 error ("error unsetting single step.");
1682 th->stepped = 0;
1683 }
1684 }
1685
1686 /* Single step (in a painstaking fashion) by inspecting the current
1687 instruction and setting a breakpoint on the "next" instruction
1688 which would be executed. This code hails from sh-stub.c.
1689 */
1690 void
1691 wince_software_single_step (unsigned int ignore, int insert_breakpoints_p)
1692 {
1693 thread_info *th = current_thread; /* Info on currently selected thread */
1694
1695 if (!insert_breakpoints_p)
1696 undoSStep (th);
1697 else
1698 {
1699 short *instrMem;
1700 int displacement;
1701 int reg;
1702 unsigned short opcode;
1703 gdb_wince_len done;
1704 LPCONTEXT c = &th->context;
1705
1706 instrMem = (short *) c->Fir;
1707
1708 read_process_memory (current_process_handle, (LPCVOID) c->Fir, &opcode,
1709 sizeof (opcode), &done);
1710 if (done != sizeof (opcode))
1711 error ("couldn't retrieve opcode");
1712 th->stepped = 1;
1713
1714 if ((opcode & COND_BR_MASK) == BT_INSTR)
1715 {
1716 if (c->Psr & T_BIT_MASK)
1717 {
1718 displacement = (opcode & COND_DISP) << 1;
1719 if (displacement & 0x80)
1720 displacement |= 0xffffff00;
1721 /*
1722 * Remember PC points to second instr.
1723 * after PC of branch ... so add 4
1724 */
1725 instrMem = (short *) (c->Fir + displacement + 4);
1726 }
1727 else
1728 instrMem += 1;
1729 }
1730 else if ((opcode & COND_BR_MASK) == BF_INSTR)
1731 {
1732 if (c->Psr & T_BIT_MASK)
1733 instrMem += 1;
1734 else
1735 {
1736 displacement = (opcode & COND_DISP) << 1;
1737 if (displacement & 0x80)
1738 displacement |= 0xffffff00;
1739 /*
1740 * Remember PC points to second instr.
1741 * after PC of branch ... so add 4
1742 */
1743 instrMem = (short *) (c->Fir + displacement + 4);
1744 }
1745 }
1746 else if ((opcode & UCOND_DBR_MASK) == BRA_INSTR)
1747 {
1748 displacement = (opcode & UCOND_DISP) << 1;
1749 if (displacement & 0x0800)
1750 displacement |= 0xfffff000;
1751
1752 /*
1753 * Remember PC points to second instr.
1754 * after PC of branch ... so add 4
1755 */
1756 instrMem = (short *) (c->Fir + displacement + 4);
1757 }
1758 else if ((opcode & UCOND_RBR_MASK) == JSR_INSTR)
1759 {
1760 reg = (char) ((opcode & UCOND_REG) >> 8);
1761
1762 instrMem = (short *) *regptr (c, reg);
1763 }
1764 else if (opcode == RTS_INSTR)
1765 instrMem = (short *) c->PR;
1766 else if (opcode == RTE_INSTR)
1767 instrMem = (short *) *regptr (c, 15);
1768 else if ((opcode & TRAPA_MASK) == TRAPA_INSTR)
1769 instrMem = (short *) ((opcode & ~TRAPA_MASK) << 2);
1770 else
1771 instrMem += 1;
1772
1773 th->step_pc = (CORE_ADDR) instrMem;
1774
1775 read_process_memory (current_process_handle, (LPVOID) instrMem,
1776 (LPVOID) & th->step_instr, sizeof (short), &done);
1777 opcode = SSTEP_INSTR;
1778 write_process_memory (current_process_handle, (LPVOID) instrMem,
1779 (LPVOID) & opcode, sizeof (short), &done);
1780 }
1781 }
1782 #elif defined (ARM)
1783 /* Single step (in a painstaking fashion) by inspecting the current
1784 instruction and setting a breakpoint on the "next" instruction
1785 which would be executed. This code hails from sh-stub.c.
1786 */
1787 static void
1788 undoSStep (thread_info * th)
1789 {
1790 if (th->stepped)
1791 {
1792 memory_remove_breakpoint (th->step_pc, (void *) &th->step_prev);
1793 th->stepped = 0;
1794 }
1795 }
1796
1797 void
1798 wince_software_single_step (unsigned int ignore, int insert_breakpoints_p)
1799 {
1800 unsigned long pc;
1801 thread_info *th = current_thread; /* Info on currently selected thread */
1802 CORE_ADDR mips_next_pc (CORE_ADDR pc);
1803
1804 if (!insert_breakpoints_p)
1805 {
1806 undoSStep (th);
1807 return;
1808 }
1809
1810 th->stepped = 1;
1811 pc = read_register (PC_REGNUM);
1812 th->step_pc = arm_get_next_pc (pc);
1813 th->step_prev = 0;
1814 memory_insert_breakpoint (th->step_pc, (void *) &th->step_prev);
1815 }
1816 #endif
1817
1818 /* Resume the child after an exception. */
1819 void
1820 child_resume (int pid, int step, enum target_signal sig)
1821 {
1822 thread_info *th;
1823 DWORD continue_status = last_sig > 0 && last_sig < NSIG ?
1824 DBG_EXCEPTION_NOT_HANDLED : DBG_CONTINUE;
1825
1826 DEBUG_EXEC (("gdb: child_resume (pid=%d, step=%d, sig=%d);\n",
1827 pid, step, sig));
1828
1829 /* Get context for currently selected thread */
1830 th = thread_rec (current_event.dwThreadId, FALSE);
1831
1832 if (th->context.ContextFlags)
1833 {
1834 CHECK (set_thread_context (th->h, &th->context));
1835 th->context.ContextFlags = 0;
1836 }
1837
1838 dcache_flush (remote_dcache);
1839
1840 /* Allow continuing with the same signal that interrupted us.
1841 Otherwise complain. */
1842 if (sig && sig != last_sig)
1843 fprintf_unfiltered (gdb_stderr, "Can't send signals to the child. signal %d\n", sig);
1844
1845 last_sig = 0;
1846 child_continue (continue_status, pid);
1847 }
1848
1849 static void
1850 child_prepare_to_store ()
1851 {
1852 /* Do nothing, since we can store individual regs */
1853 }
1854
1855 static int
1856 child_can_run ()
1857 {
1858 return 1;
1859 }
1860
1861 static void
1862 child_close ()
1863 {
1864 DEBUG_EVENTS (("gdb: child_close, inferior_pid=%d\n", inferior_pid));
1865 }
1866
1867 /* Explicitly upload file to remotedir */
1868
1869 static void
1870 child_load (char *file, int from_tty)
1871 {
1872 upload_to_device (file, file);
1873 }
1874
1875 struct target_ops child_ops;
1876
1877 static void
1878 init_child_ops (void)
1879 {
1880 memset (&child_ops, 0, sizeof (child_ops));
1881 child_ops.to_shortname = (char *) "child";
1882 child_ops.to_longname = (char *) "Windows CE process";
1883 child_ops.to_doc = (char *) "Windows CE process (started by the \"run\" command).";
1884 child_ops.to_open = child_open;
1885 child_ops.to_close = child_close;
1886 child_ops.to_resume = child_resume;
1887 child_ops.to_wait = child_wait;
1888 child_ops.to_fetch_registers = child_fetch_inferior_registers;
1889 child_ops.to_store_registers = child_store_inferior_registers;
1890 child_ops.to_prepare_to_store = child_prepare_to_store;
1891 child_ops.to_xfer_memory = child_xfer_memory;
1892 child_ops.to_files_info = child_files_info;
1893 child_ops.to_insert_breakpoint = memory_insert_breakpoint;
1894 child_ops.to_remove_breakpoint = memory_remove_breakpoint;
1895 child_ops.to_terminal_init = terminal_init_inferior;
1896 child_ops.to_terminal_inferior = terminal_inferior;
1897 child_ops.to_terminal_ours_for_output = terminal_ours_for_output;
1898 child_ops.to_terminal_ours = terminal_ours;
1899 child_ops.to_terminal_info = child_terminal_info;
1900 child_ops.to_kill = child_kill_inferior;
1901 child_ops.to_load = child_load;
1902 child_ops.to_create_inferior = child_create_inferior;
1903 child_ops.to_mourn_inferior = child_mourn_inferior;
1904 child_ops.to_can_run = child_can_run;
1905 child_ops.to_thread_alive = win32_child_thread_alive;
1906 child_ops.to_stratum = process_stratum;
1907 child_ops.to_has_all_memory = 1;
1908 child_ops.to_has_memory = 1;
1909 child_ops.to_has_stack = 1;
1910 child_ops.to_has_registers = 1;
1911 child_ops.to_has_execution = 1;
1912 child_ops.to_sections = 0;
1913 child_ops.to_sections_end = 0;
1914 child_ops.to_magic = OPS_MAGIC;
1915 }
1916
1917
1918 /* Handle 'set remoteupload' parameter. */
1919
1920 #define replace_upload(what) \
1921 upload_when = UPLOAD_NEWER; \
1922 remote_upload = realloc (remote_upload, strlen (upload_options[upload_when].name)); \
1923 strcpy (remote_upload, upload_options[upload_when].name);
1924
1925 static void
1926 set_upload_type (char *ignore, int from_tty)
1927 {
1928 int i, len;
1929 char *bad_option;
1930
1931 if (!remote_upload || !remote_upload[0])
1932 {
1933 replace_upload (UPLOAD_NEWER);
1934 if (from_tty)
1935 printf_unfiltered ("Upload upload_options are: always, newer, never.\n");
1936 return;
1937 }
1938
1939 len = strlen (remote_upload);
1940 for (i = 0; i < (sizeof (upload_options) / sizeof (upload_options[0])); i++)
1941 if (len >= upload_options[i].abbrev &&
1942 strncasecmp (remote_upload, upload_options[i].name, len) == 0)
1943 {
1944 remote_upload = (char *) upload_options[i].name;
1945 upload_when = i;
1946 return;
1947 }
1948
1949 bad_option = remote_upload;
1950 replace_upload (UPLOAD_NEWER);
1951 error ("Unknown upload type: %s.", bad_option);
1952 }
1953
1954 void
1955 _initialize_inftarg ()
1956 {
1957 struct cmd_list_element *set;
1958 init_child_ops ();
1959
1960 add_show_from_set
1961 (add_set_cmd ((char *) "remotedirectory", no_class,
1962 var_string_noescape, (char *) &remote_directory,
1963 (char *) "Set directory for remote upload.\n",
1964 &setlist),
1965 &showlist);
1966 remote_directory = xstrdup (remote_directory);
1967
1968 set = add_set_cmd ((char *) "remoteupload", no_class,
1969 var_string_noescape, (char *) &remote_upload,
1970 (char *) "Set how to upload executables to remote device.\n",
1971 &setlist);
1972 add_show_from_set (set, &showlist);
1973 set->function.cfunc = set_upload_type;
1974 set_upload_type (NULL, 0);
1975 set_dcache_state (1);
1976
1977 add_show_from_set
1978 (add_set_cmd ((char *) "debugexec", class_support, var_boolean,
1979 (char *) &debug_exec,
1980 (char *) "Set whether to display execution in child process.",
1981 &setlist),
1982 &showlist);
1983
1984 add_show_from_set
1985 (add_set_cmd ((char *) "remoteaddhost", class_support, var_boolean,
1986 (char *) &remote_add_host,
1987 (char *) "Set whether to add this host to remote stub arguments for\n
1988 debugging over a network.", &setlist),
1989 &showlist);
1990
1991 add_show_from_set
1992 (add_set_cmd ((char *) "debugevents", class_support, var_boolean,
1993 (char *) &debug_events,
1994 (char *) "Set whether to display kernel events in child process.",
1995 &setlist),
1996 &showlist);
1997
1998 add_show_from_set
1999 (add_set_cmd ((char *) "debugmemory", class_support, var_boolean,
2000 (char *) &debug_memory,
2001 (char *) "Set whether to display memory accesses in child process.",
2002 &setlist),
2003 &showlist);
2004
2005 add_show_from_set
2006 (add_set_cmd ((char *) "debugexceptions", class_support, var_boolean,
2007 (char *) &debug_exceptions,
2008 (char *) "Set whether to display kernel exceptions in child process.",
2009 &setlist),
2010 &showlist);
2011
2012 add_target (&child_ops);
2013 }
2014
2015 /* Determine if the thread referenced by "pid" is alive
2016 by "polling" it. If WaitForSingleObject returns WAIT_OBJECT_0
2017 it means that the pid has died. Otherwise it is assumed to be alive. */
2018 static int
2019 win32_child_thread_alive (int pid)
2020 {
2021 return thread_alive (thread_rec (pid, FALSE)->h);
2022 }
2023
2024 /* Convert pid to printable format. */
2025 char *
2026 cygwin_pid_to_str (int pid)
2027 {
2028 static char buf[80];
2029 if (pid == current_event.dwProcessId)
2030 sprintf (buf, "process %d", pid);
2031 else
2032 sprintf (buf, "thread %d.0x%x", (unsigned) current_event.dwProcessId, pid);
2033 return buf;
2034 }
This page took 0.068692 seconds and 5 git commands to generate.