* remote.c (remote_store_registers): Add 'P' request to set an
[binutils-gdb.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2 Copyright 1988, 1991, 1992, 1993, 1994 Free Software Foundation, Inc.
3
4 This file is part of GDB.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
19
20 /* Remote communication protocol.
21
22 A debug packet whose contents are <data>
23 is encapsulated for transmission in the form:
24
25 $ <data> # CSUM1 CSUM2
26
27 <data> must be ASCII alphanumeric and cannot include characters
28 '$' or '#'
29
30 CSUM1 and CSUM2 are ascii hex representation of an 8-bit
31 checksum of <data>, the most significant nibble is sent first.
32 the hex digits 0-9,a-f are used.
33
34 Receiver responds with:
35
36 + - if CSUM is correct and ready for next packet
37 - - if CSUM is incorrect
38
39 <data> is as follows:
40 All values are encoded in ascii hex digits.
41
42 Request Packet
43
44 read registers g
45 reply XX....X Each byte of register data
46 is described by two hex digits.
47 Registers are in the internal order
48 for GDB, and the bytes in a register
49 are in the same order the machine uses.
50 or ENN for an error.
51
52 write regs GXX..XX Each byte of register data
53 is described by two hex digits.
54 reply OK for success
55 ENN for an error
56
57 write reg Pn...:r... Write register n... with value r...,
58 which contains two hex digits for each
59 byte in the register (target byte
60 order).
61 reply OK for success
62 ENN for an error
63 (not supported by all stubs).
64
65 read mem mAA..AA,LLLL AA..AA is address, LLLL is length.
66 reply XX..XX XX..XX is mem contents
67 Can be fewer bytes than requested
68 if able to read only part of the data.
69 or ENN NN is errno
70
71 write mem MAA..AA,LLLL:XX..XX
72 AA..AA is address,
73 LLLL is number of bytes,
74 XX..XX is data
75 reply OK for success
76 ENN for an error (this includes the case
77 where only part of the data was
78 written).
79
80 cont cAA..AA AA..AA is address to resume
81 If AA..AA is omitted,
82 resume at same address.
83
84 step sAA..AA AA..AA is address to resume
85 If AA..AA is omitted,
86 resume at same address.
87
88 last signal ? Reply the current reason for stopping.
89 This is the same reply as is generated
90 for step or cont : SAA where AA is the
91 signal number.
92
93 There is no immediate reply to step or cont.
94 The reply comes when the machine stops.
95 It is SAA AA is the "signal number"
96
97 or... TAAn...:r...;n:r...;n...:r...;
98 AA = signal number
99 n... = register number
100 r... = register contents
101 or... WAA The process exited, and AA is
102 the exit status. This is only
103 applicable for certains sorts of
104 targets.
105 kill request k
106
107 toggle debug d toggle debug flag (see 386 & 68k stubs)
108 reset r reset -- see sparc stub.
109 reserved <other> On other requests, the stub should
110 ignore the request and send an empty
111 response ($#<checksum>). This way
112 we can extend the protocol and GDB
113 can tell whether the stub it is
114 talking to uses the old or the new.
115 search tAA:PP,MM Search backwards starting at address
116 AA for a match with pattern PP and
117 mask MM. PP and MM are 4 bytes.
118 Not supported by all stubs.
119
120 general query qXXXX Request info about XXXX.
121 general set QXXXX=yyyy Set value of XXXX to yyyy.
122 query sect offs qOffsets Get section offsets. Reply is
123 Text=xxx;Data=yyy;Bss=zzz
124
125 Responses can be run-length encoded to save space. A '*' means that
126 the next two characters are hex digits giving a repeat count which
127 stands for that many repititions of the character preceding the '*'.
128 Note that this means that responses cannot contain '*'. Example:
129 "0*03" means the same as "0000". */
130
131 #include "defs.h"
132 #include <string.h>
133 #include <fcntl.h>
134 #include "frame.h"
135 #include "inferior.h"
136 #include "bfd.h"
137 #include "symfile.h"
138 #include "target.h"
139 #include "wait.h"
140 #include "terminal.h"
141 #include "gdbcmd.h"
142 #include "objfiles.h"
143 #include "gdb-stabs.h"
144
145 #include "dcache.h"
146
147 #if !defined(DONT_USE_REMOTE)
148 #ifdef USG
149 #include <sys/types.h>
150 #endif
151
152 #include <signal.h>
153 #include "serial.h"
154
155 /* Prototypes for local functions */
156
157 static int
158 remote_write_bytes PARAMS ((CORE_ADDR memaddr, unsigned char *myaddr, int len));
159
160 static int
161 remote_read_bytes PARAMS ((CORE_ADDR memaddr, unsigned char *myaddr, int len));
162
163 static void
164 remote_files_info PARAMS ((struct target_ops *ignore));
165
166 static int
167 remote_xfer_memory PARAMS ((CORE_ADDR memaddr, char *myaddr, int len,
168 int should_write, struct target_ops *target));
169
170 static void
171 remote_prepare_to_store PARAMS ((void));
172
173 static void
174 remote_fetch_registers PARAMS ((int regno));
175
176 static void
177 remote_resume PARAMS ((int pid, int step, enum target_signal siggnal));
178
179 static int
180 remote_start_remote PARAMS ((char *dummy));
181
182 static void
183 remote_open PARAMS ((char *name, int from_tty));
184
185 static void
186 remote_close PARAMS ((int quitting));
187
188 static void
189 remote_store_registers PARAMS ((int regno));
190
191 static void
192 getpkt PARAMS ((char *buf, int forever));
193
194 static void
195 putpkt PARAMS ((char *buf));
196
197 static void
198 remote_send PARAMS ((char *buf));
199
200 static int
201 readchar PARAMS ((void));
202
203 static int remote_wait PARAMS ((int pid, struct target_waitstatus *status));
204
205 static int
206 tohex PARAMS ((int nib));
207
208 static int
209 fromhex PARAMS ((int a));
210
211 static void
212 remote_detach PARAMS ((char *args, int from_tty));
213
214 static void
215 remote_interrupt PARAMS ((int signo));
216
217 static void
218 remote_interrupt_twice PARAMS ((int signo));
219
220 static void
221 interrupt_query PARAMS ((void));
222
223 extern struct target_ops remote_ops; /* Forward decl */
224
225 /* This was 5 seconds, which is a long time to sit and wait.
226 Unless this is going though some terminal server or multiplexer or
227 other form of hairy serial connection, I would think 2 seconds would
228 be plenty. */
229 static int timeout = 2;
230
231 #if 0
232 int icache;
233 #endif
234
235 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
236 remote_open knows that we don't have a file open when the program
237 starts. */
238 serial_t remote_desc = NULL;
239
240 /* Having this larger than 400 causes us to be incompatible with m68k-stub.c
241 and i386-stub.c. Normally, no one would notice because it only matters
242 for writing large chunks of memory (e.g. in downloads). Also, this needs
243 to be more than 400 if required to hold the registers (see below, where
244 we round it up based on REGISTER_BYTES). */
245 #define PBUFSIZ 400
246
247 /* Maximum number of bytes to read/write at once. The value here
248 is chosen to fill up a packet (the headers account for the 32). */
249 #define MAXBUFBYTES ((PBUFSIZ-32)/2)
250
251 /* Round up PBUFSIZ to hold all the registers, at least. */
252 #if REGISTER_BYTES > MAXBUFBYTES
253 #undef PBUFSIZ
254 #define PBUFSIZ (REGISTER_BYTES * 2 + 32)
255 #endif
256
257 /* Should we try the 'P' request? If this is set to one when the stub
258 doesn't support 'P', the only consequence is some unnecessary traffic. */
259 static int stub_supports_P = 1;
260
261 \f
262 /* Clean up connection to a remote debugger. */
263
264 /* ARGSUSED */
265 static void
266 remote_close (quitting)
267 int quitting;
268 {
269 if (remote_desc)
270 SERIAL_CLOSE (remote_desc);
271 remote_desc = NULL;
272 }
273
274 /* Query the remote side for the text, data and bss offsets. */
275
276 static void
277 get_offsets ()
278 {
279 unsigned char buf [PBUFSIZ];
280 int nvals;
281 CORE_ADDR text_addr, data_addr, bss_addr;
282 struct section_offsets *offs;
283
284 putpkt ("qOffsets");
285
286 getpkt (buf, 1);
287
288 if (buf[0] == 'E')
289 {
290 warning ("Remote failure reply: %s", buf);
291 return;
292 }
293
294 nvals = sscanf (buf, "Text=%lx;Data=%lx;Bss=%lx", &text_addr, &data_addr,
295 &bss_addr);
296 if (nvals != 3)
297 error ("Malformed response to offset query, %s", buf);
298
299 if (symfile_objfile == NULL)
300 return;
301
302 offs = (struct section_offsets *) alloca (sizeof (struct section_offsets)
303 + symfile_objfile->num_sections
304 * sizeof (offs->offsets));
305 memcpy (offs, symfile_objfile->section_offsets,
306 sizeof (struct section_offsets)
307 + symfile_objfile->num_sections
308 * sizeof (offs->offsets));
309
310 /* FIXME: This code assumes gdb-stabs.h is being used; it's broken
311 for xcoff, dwarf, sdb-coff, etc. But there is no simple
312 canonical representation for this stuff. (Just what does "text"
313 as seen by the stub mean, anyway? I think it means all sections
314 with SEC_CODE set, but we currently have no way to deal with that). */
315
316 ANOFFSET (offs, SECT_OFF_TEXT) = text_addr;
317 ANOFFSET (offs, SECT_OFF_DATA) = data_addr;
318 ANOFFSET (offs, SECT_OFF_BSS) = bss_addr;
319
320 objfile_relocate (symfile_objfile, offs);
321 }
322
323 /* Stub for catch_errors. */
324
325 static int
326 remote_start_remote (dummy)
327 char *dummy;
328 {
329 immediate_quit = 1; /* Allow user to interrupt it */
330
331 /* Ack any packet which the remote side has already sent. */
332
333 SERIAL_WRITE (remote_desc, "+", 1);
334
335 get_offsets (); /* Get text, data & bss offsets */
336
337 putpkt ("?"); /* initiate a query from remote machine */
338 immediate_quit = 0;
339
340 start_remote (); /* Initialize gdb process mechanisms */
341
342 return 1;
343 }
344
345 /* Open a connection to a remote debugger.
346 NAME is the filename used for communication. */
347
348 static DCACHE *remote_dcache;
349
350 static void
351 remote_open (name, from_tty)
352 char *name;
353 int from_tty;
354 {
355 if (name == 0)
356 error (
357 "To open a remote debug connection, you need to specify what serial\n\
358 device is attached to the remote system (e.g. /dev/ttya).");
359
360 target_preopen (from_tty);
361
362 unpush_target (&remote_ops);
363
364 remote_dcache = dcache_init (remote_read_bytes, remote_write_bytes);
365
366 remote_desc = SERIAL_OPEN (name);
367 if (!remote_desc)
368 perror_with_name (name);
369
370 if (baud_rate != -1)
371 {
372 if (SERIAL_SETBAUDRATE (remote_desc, baud_rate))
373 {
374 SERIAL_CLOSE (remote_desc);
375 perror_with_name (name);
376 }
377 }
378
379 SERIAL_RAW (remote_desc);
380
381 /* If there is something sitting in the buffer we might take it as a
382 response to a command, which would be bad. */
383 SERIAL_FLUSH_INPUT (remote_desc);
384
385 if (from_tty)
386 {
387 puts_filtered ("Remote debugging using ");
388 puts_filtered (name);
389 puts_filtered ("\n");
390 }
391 push_target (&remote_ops); /* Switch to using remote target now */
392
393 /* Start out by trying the 'P' request to set registers. We set this each
394 time that we open a new target so that if the user switches from one
395 stub to another, we can (if the target is closed and reopened) cope. */
396 stub_supports_P = 1;
397
398 /* Start the remote connection; if error (0), discard this target.
399 In particular, if the user quits, be sure to discard it
400 (we'd be in an inconsistent state otherwise). */
401 if (!catch_errors (remote_start_remote, (char *)0,
402 "Couldn't establish connection to remote target\n", RETURN_MASK_ALL))
403 pop_target();
404 }
405
406 /* remote_detach()
407 takes a program previously attached to and detaches it.
408 We better not have left any breakpoints
409 in the program or it'll die when it hits one.
410 Close the open connection to the remote debugger.
411 Use this when you want to detach and do something else
412 with your gdb. */
413
414 static void
415 remote_detach (args, from_tty)
416 char *args;
417 int from_tty;
418 {
419 if (args)
420 error ("Argument given to \"detach\" when remotely debugging.");
421
422 pop_target ();
423 if (from_tty)
424 puts_filtered ("Ending remote debugging.\n");
425 }
426
427 /* Convert hex digit A to a number. */
428
429 static int
430 fromhex (a)
431 int a;
432 {
433 if (a >= '0' && a <= '9')
434 return a - '0';
435 else if (a >= 'a' && a <= 'f')
436 return a - 'a' + 10;
437 else
438 error ("Reply contains invalid hex digit");
439 return -1;
440 }
441
442 /* Convert number NIB to a hex digit. */
443
444 static int
445 tohex (nib)
446 int nib;
447 {
448 if (nib < 10)
449 return '0'+nib;
450 else
451 return 'a'+nib-10;
452 }
453 \f
454 /* Tell the remote machine to resume. */
455
456 static void
457 remote_resume (pid, step, siggnal)
458 int pid, step;
459 enum target_signal siggnal;
460 {
461 char buf[PBUFSIZ];
462
463 if (siggnal)
464 {
465 char *name;
466 target_terminal_ours_for_output ();
467 printf_filtered
468 ("Can't send signals to a remote system. %s not sent.\n",
469 target_signal_to_name (siggnal));
470 target_terminal_inferior ();
471 }
472
473 dcache_flush (remote_dcache);
474
475 strcpy (buf, step ? "s": "c");
476
477 putpkt (buf);
478 }
479 \f
480 /* Send ^C to target to halt it. Target will respond, and send us a
481 packet. */
482
483 static void
484 remote_interrupt (signo)
485 int signo;
486 {
487 /* If this doesn't work, try more severe steps. */
488 signal (signo, remote_interrupt_twice);
489
490 if (remote_debug)
491 printf_unfiltered ("remote_interrupt called\n");
492
493 SERIAL_WRITE (remote_desc, "\003", 1); /* Send a ^C */
494 }
495
496 static void (*ofunc)();
497
498 /* The user typed ^C twice. */
499 static void
500 remote_interrupt_twice (signo)
501 int signo;
502 {
503 signal (signo, ofunc);
504
505 interrupt_query ();
506
507 signal (signo, remote_interrupt);
508 }
509
510 /* Ask the user what to do when an interrupt is received. */
511
512 static void
513 interrupt_query ()
514 {
515 target_terminal_ours ();
516
517 if (query ("Interrupted while waiting for the program.\n\
518 Give up (and stop debugging it)? "))
519 {
520 target_mourn_inferior ();
521 return_to_top_level (RETURN_QUIT);
522 }
523
524 target_terminal_inferior ();
525 }
526
527 /* Wait until the remote machine stops, then return,
528 storing status in STATUS just as `wait' would.
529 Returns "pid" (though it's not clear what, if anything, that
530 means in the case of this target). */
531
532 static int
533 remote_wait (pid, status)
534 int pid;
535 struct target_waitstatus *status;
536 {
537 unsigned char buf[PBUFSIZ];
538
539 status->kind = TARGET_WAITKIND_EXITED;
540 status->value.integer = 0;
541
542 while (1)
543 {
544 unsigned char *p;
545
546 ofunc = (void (*)()) signal (SIGINT, remote_interrupt);
547 getpkt ((char *) buf, 1);
548 signal (SIGINT, ofunc);
549
550 if (buf[0] == 'E')
551 warning ("Remote failure reply: %s", buf);
552 else if (buf[0] == 'T')
553 {
554 int i;
555 long regno;
556 char regs[MAX_REGISTER_RAW_SIZE];
557
558 /* Expedited reply, containing Signal, {regno, reg} repeat */
559 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
560 ss = signal number
561 n... = register number
562 r... = register contents
563 */
564
565 p = &buf[3]; /* after Txx */
566
567 while (*p)
568 {
569 unsigned char *p1;
570
571 regno = strtol (p, &p1, 16); /* Read the register number */
572
573 if (p1 == p)
574 warning ("Remote sent badly formed register number: %s\nPacket: '%s'\n",
575 p1, buf);
576
577 p = p1;
578
579 if (*p++ != ':')
580 warning ("Malformed packet (missing colon): %s\nPacket: '%s'\n",
581 p, buf);
582
583 if (regno >= NUM_REGS)
584 warning ("Remote sent bad register number %d: %s\nPacket: '%s'\n",
585 regno, p, buf);
586
587 for (i = 0; i < REGISTER_RAW_SIZE (regno); i++)
588 {
589 if (p[0] == 0 || p[1] == 0)
590 warning ("Remote reply is too short: %s", buf);
591 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
592 p += 2;
593 }
594
595 if (*p++ != ';')
596 warning ("Remote register badly formatted: %s", buf);
597
598 supply_register (regno, regs);
599 }
600 break;
601 }
602 else if (buf[0] == 'W')
603 {
604 /* The remote process exited. */
605 status->kind = TARGET_WAITKIND_EXITED;
606 status->value.integer = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
607 return 0;
608 }
609 else if (buf[0] == 'S')
610 break;
611 else
612 warning ("Invalid remote reply: %s", buf);
613 }
614
615 status->kind = TARGET_WAITKIND_STOPPED;
616 status->value.sig = (enum target_signal)
617 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
618
619 return 0;
620 }
621
622 /* Number of bytes of registers this stub implements. */
623 static int register_bytes_found;
624
625 /* Read the remote registers into the block REGS. */
626 /* Currently we just read all the registers, so we don't use regno. */
627 /* ARGSUSED */
628 static void
629 remote_fetch_registers (regno)
630 int regno;
631 {
632 char buf[PBUFSIZ];
633 int i;
634 char *p;
635 char regs[REGISTER_BYTES];
636
637 sprintf (buf, "g");
638 remote_send (buf);
639
640 /* Unimplemented registers read as all bits zero. */
641 memset (regs, 0, REGISTER_BYTES);
642
643 /* We can get out of synch in various cases. If the first character
644 in the buffer is not a hex character, assume that has happened
645 and try to fetch another packet to read. */
646 while ((buf[0] < '0' || buf[0] > '9')
647 && (buf[0] < 'a' || buf[0] > 'f'))
648 {
649 if (remote_debug)
650 printf_unfiltered ("Bad register packet; fetching a new packet\n");
651 getpkt (buf, 0);
652 }
653
654 /* Reply describes registers byte by byte, each byte encoded as two
655 hex characters. Suck them all up, then supply them to the
656 register cacheing/storage mechanism. */
657
658 p = buf;
659 for (i = 0; i < REGISTER_BYTES; i++)
660 {
661 if (p[0] == 0)
662 break;
663 if (p[1] == 0)
664 {
665 warning ("Remote reply is of odd length: %s", buf);
666 /* Don't change register_bytes_found in this case, and don't
667 print a second warning. */
668 goto supply_them;
669 }
670 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
671 p += 2;
672 }
673
674 if (i != register_bytes_found)
675 {
676 register_bytes_found = i;
677 #ifdef REGISTER_BYTES_OK
678 if (!REGISTER_BYTES_OK (i))
679 warning ("Remote reply is too short: %s", buf);
680 #endif
681 }
682
683 supply_them:
684 for (i = 0; i < NUM_REGS; i++)
685 supply_register (i, &regs[REGISTER_BYTE(i)]);
686 }
687
688 /* Prepare to store registers. Since we may send them all (using a
689 'G' request), we have to read out the ones we don't want to change
690 first. */
691
692 static void
693 remote_prepare_to_store ()
694 {
695 /* Make sure the entire registers array is valid. */
696 read_register_bytes (0, (char *)NULL, REGISTER_BYTES);
697 }
698
699 /* Store register REGNO, or all registers if REGNO == -1, from the contents
700 of REGISTERS. FIXME: ignores errors. */
701
702 static void
703 remote_store_registers (regno)
704 int regno;
705 {
706 char buf[PBUFSIZ];
707 int i;
708 char *p;
709
710 if (regno >= 0 && stub_supports_P)
711 {
712 /* Try storing a single register. */
713 char *regp;
714
715 sprintf (buf, "P%x:", regno);
716 p = buf + strlen (buf);
717 regp = &registers[REGISTER_BYTE (regno)];
718 for (i = 0; i < REGISTER_RAW_SIZE (regno); ++i)
719 {
720 *p++ = tohex ((regp[i] >> 4) & 0xf);
721 *p++ = tohex (regp[i] & 0xf);
722 }
723 *p = '\0';
724 remote_send (buf);
725 if (buf[0] != '\0')
726 {
727 /* The stub understands the 'P' request. We are done. */
728 return;
729 }
730
731 /* The stub does not support the 'P' request. Use 'G' instead,
732 and don't try using 'P' in the future (it will just waste our
733 time). */
734 stub_supports_P = 0;
735 }
736
737 buf[0] = 'G';
738
739 /* Command describes registers byte by byte,
740 each byte encoded as two hex characters. */
741
742 p = buf + 1;
743 /* remote_prepare_to_store insures that register_bytes_found gets set. */
744 for (i = 0; i < register_bytes_found; i++)
745 {
746 *p++ = tohex ((registers[i] >> 4) & 0xf);
747 *p++ = tohex (registers[i] & 0xf);
748 }
749 *p = '\0';
750
751 remote_send (buf);
752 }
753
754 #if 0
755
756 /* Use of the data cache is disabled because it loses for looking at
757 and changing hardware I/O ports and the like. Accepting `volatile'
758 would perhaps be one way to fix it, but a better way which would
759 win for more cases would be to use the executable file for the text
760 segment, like the `icache' code below but done cleanly (in some
761 target-independent place, perhaps in target_xfer_memory, perhaps
762 based on assigning each target a speed or perhaps by some simpler
763 mechanism). */
764
765 /* Read a word from remote address ADDR and return it.
766 This goes through the data cache. */
767
768 static int
769 remote_fetch_word (addr)
770 CORE_ADDR addr;
771 {
772 #if 0
773 if (icache)
774 {
775 extern CORE_ADDR text_start, text_end;
776
777 if (addr >= text_start && addr < text_end)
778 {
779 int buffer;
780 xfer_core_file (addr, &buffer, sizeof (int));
781 return buffer;
782 }
783 }
784 #endif
785 return dcache_fetch (remote_dcache, addr);
786 }
787
788 /* Write a word WORD into remote address ADDR.
789 This goes through the data cache. */
790
791 static void
792 remote_store_word (addr, word)
793 CORE_ADDR addr;
794 int word;
795 {
796 dcache_poke (remote_dcache, addr, word);
797 }
798 #endif /* 0 */
799 \f
800 /* Write memory data directly to the remote machine.
801 This does not inform the data cache; the data cache uses this.
802 MEMADDR is the address in the remote memory space.
803 MYADDR is the address of the buffer in our space.
804 LEN is the number of bytes.
805
806 Returns number of bytes transferred, or 0 for error. */
807
808 static int
809 remote_write_bytes (memaddr, myaddr, len)
810 CORE_ADDR memaddr;
811 unsigned char *myaddr;
812 int len;
813 {
814 char buf[PBUFSIZ];
815 int i;
816 char *p;
817
818 /* FIXME-32x64: Need a version of print_address_numeric which doesn't
819 set use_local (and also puts the result in a buffer like sprintf). */
820 sprintf (buf, "M%lx,%x:", (unsigned long) memaddr, len);
821
822 /* We send target system values byte by byte, in increasing byte addresses,
823 each byte encoded as two hex characters. */
824
825 p = buf + strlen (buf);
826 for (i = 0; i < len; i++)
827 {
828 *p++ = tohex ((myaddr[i] >> 4) & 0xf);
829 *p++ = tohex (myaddr[i] & 0xf);
830 }
831 *p = '\0';
832
833 putpkt (buf);
834 getpkt (buf, 0);
835
836 if (buf[0] == 'E')
837 {
838 /* There is no correspondance between what the remote protocol uses
839 for errors and errno codes. We would like a cleaner way of
840 representing errors (big enough to include errno codes, bfd_error
841 codes, and others). But for now just return EIO. */
842 errno = EIO;
843 return 0;
844 }
845 return len;
846 }
847
848 /* Read memory data directly from the remote machine.
849 This does not use the data cache; the data cache uses this.
850 MEMADDR is the address in the remote memory space.
851 MYADDR is the address of the buffer in our space.
852 LEN is the number of bytes.
853
854 Returns number of bytes transferred, or 0 for error. */
855
856 static int
857 remote_read_bytes (memaddr, myaddr, len)
858 CORE_ADDR memaddr;
859 unsigned char *myaddr;
860 int len;
861 {
862 char buf[PBUFSIZ];
863 int i;
864 char *p;
865
866 if (len > PBUFSIZ / 2 - 1)
867 abort ();
868
869 /* FIXME-32x64: Need a version of print_address_numeric which doesn't
870 set use_local (and also puts the result in a buffer like sprintf). */
871 sprintf (buf, "m%lx,%x", (unsigned long) memaddr, len);
872 putpkt (buf);
873 getpkt (buf, 0);
874
875 if (buf[0] == 'E')
876 {
877 /* There is no correspondance between what the remote protocol uses
878 for errors and errno codes. We would like a cleaner way of
879 representing errors (big enough to include errno codes, bfd_error
880 codes, and others). But for now just return EIO. */
881 errno = EIO;
882 return 0;
883 }
884
885 /* Reply describes memory byte by byte,
886 each byte encoded as two hex characters. */
887
888 p = buf;
889 for (i = 0; i < len; i++)
890 {
891 if (p[0] == 0 || p[1] == 0)
892 /* Reply is short. This means that we were able to read only part
893 of what we wanted to. */
894 break;
895 myaddr[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
896 p += 2;
897 }
898 return i;
899 }
900 \f
901 /* Read or write LEN bytes from inferior memory at MEMADDR, transferring
902 to or from debugger address MYADDR. Write to inferior if SHOULD_WRITE is
903 nonzero. Returns length of data written or read; 0 for error. */
904
905 /* ARGSUSED */
906 static int
907 remote_xfer_memory(memaddr, myaddr, len, should_write, target)
908 CORE_ADDR memaddr;
909 char *myaddr;
910 int len;
911 int should_write;
912 struct target_ops *target; /* ignored */
913 {
914 int xfersize;
915 int bytes_xferred;
916 int total_xferred = 0;
917
918 while (len > 0)
919 {
920 if (len > MAXBUFBYTES)
921 xfersize = MAXBUFBYTES;
922 else
923 xfersize = len;
924
925 if (should_write)
926 bytes_xferred = remote_write_bytes (memaddr,
927 (unsigned char *)myaddr, xfersize);
928 else
929 bytes_xferred = remote_read_bytes (memaddr,
930 (unsigned char *)myaddr, xfersize);
931
932 /* If we get an error, we are done xferring. */
933 if (bytes_xferred == 0)
934 break;
935
936 memaddr += bytes_xferred;
937 myaddr += bytes_xferred;
938 len -= bytes_xferred;
939 total_xferred += bytes_xferred;
940 }
941 return total_xferred;
942 }
943
944 #if 0
945 /* Enable after 4.12. */
946
947 void
948 remote_search (len, data, mask, startaddr, increment, lorange, hirange
949 addr_found, data_found)
950 int len;
951 char *data;
952 char *mask;
953 CORE_ADDR startaddr;
954 int increment;
955 CORE_ADDR lorange;
956 CORE_ADDR hirange;
957 CORE_ADDR *addr_found;
958 char *data_found;
959 {
960 if (increment == -4 && len == 4)
961 {
962 long mask_long, data_long;
963 long data_found_long;
964 CORE_ADDR addr_we_found;
965 char buf[PBUFSIZ];
966 long returned_long[2];
967 char *p;
968
969 mask_long = extract_unsigned_integer (mask, len);
970 data_long = extract_unsigned_integer (data, len);
971 sprintf (buf, "t%x:%x,%x", startaddr, data_long, mask_long);
972 putpkt (buf);
973 getpkt (buf, 0);
974 if (buf[0] == '\0')
975 {
976 /* The stub doesn't support the 't' request. We might want to
977 remember this fact, but on the other hand the stub could be
978 switched on us. Maybe we should remember it only until
979 the next "target remote". */
980 generic_search (len, data, mask, startaddr, increment, lorange,
981 hirange, addr_found, data_found);
982 return;
983 }
984
985 if (buf[0] == 'E')
986 /* There is no correspondance between what the remote protocol uses
987 for errors and errno codes. We would like a cleaner way of
988 representing errors (big enough to include errno codes, bfd_error
989 codes, and others). But for now just use EIO. */
990 memory_error (EIO, startaddr);
991 p = buf;
992 addr_we_found = 0;
993 while (*p != '\0' && *p != ',')
994 addr_we_found = (addr_we_found << 4) + fromhex (*p++);
995 if (*p == '\0')
996 error ("Protocol error: short return for search");
997
998 data_found_long = 0;
999 while (*p != '\0' && *p != ',')
1000 data_found_long = (data_found_long << 4) + fromhex (*p++);
1001 /* Ignore anything after this comma, for future extensions. */
1002
1003 if (addr_we_found < lorange || addr_we_found >= hirange)
1004 {
1005 *addr_found = 0;
1006 return;
1007 }
1008
1009 *addr_found = addr_we_found;
1010 *data_found = store_unsigned_integer (data_we_found, len);
1011 return;
1012 }
1013 generic_search (len, data, mask, startaddr, increment, lorange,
1014 hirange, addr_found, data_found);
1015 }
1016 #endif /* 0 */
1017 \f
1018 static void
1019 remote_files_info (ignore)
1020 struct target_ops *ignore;
1021 {
1022 puts_filtered ("Debugging a target over a serial line.\n");
1023 }
1024 \f
1025 /* Stuff for dealing with the packets which are part of this protocol.
1026 See comment at top of file for details. */
1027
1028 /* Read a single character from the remote end, masking it down to 7 bits. */
1029
1030 static int
1031 readchar ()
1032 {
1033 int ch;
1034
1035 ch = SERIAL_READCHAR (remote_desc, timeout);
1036
1037 if (ch < 0)
1038 return ch;
1039
1040 return ch & 0x7f;
1041 }
1042
1043 /* Send the command in BUF to the remote machine,
1044 and read the reply into BUF.
1045 Report an error if we get an error reply. */
1046
1047 static void
1048 remote_send (buf)
1049 char *buf;
1050 {
1051
1052 putpkt (buf);
1053 getpkt (buf, 0);
1054
1055 if (buf[0] == 'E')
1056 error ("Remote failure reply: %s", buf);
1057 }
1058
1059 /* Send a packet to the remote machine, with error checking.
1060 The data of the packet is in BUF. */
1061
1062 static void
1063 putpkt (buf)
1064 char *buf;
1065 {
1066 int i;
1067 unsigned char csum = 0;
1068 char buf2[PBUFSIZ];
1069 int cnt = strlen (buf);
1070 int ch;
1071 char *p;
1072
1073 /* Copy the packet into buffer BUF2, encapsulating it
1074 and giving it a checksum. */
1075
1076 if (cnt > sizeof(buf2) - 5) /* Prosanity check */
1077 abort();
1078
1079 p = buf2;
1080 *p++ = '$';
1081
1082 for (i = 0; i < cnt; i++)
1083 {
1084 csum += buf[i];
1085 *p++ = buf[i];
1086 }
1087 *p++ = '#';
1088 *p++ = tohex ((csum >> 4) & 0xf);
1089 *p++ = tohex (csum & 0xf);
1090
1091 /* Send it over and over until we get a positive ack. */
1092
1093 while (1)
1094 {
1095 if (remote_debug)
1096 {
1097 *p = '\0';
1098 printf_unfiltered ("Sending packet: %s...", buf2); gdb_flush(gdb_stdout);
1099 }
1100 if (SERIAL_WRITE (remote_desc, buf2, p - buf2))
1101 perror_with_name ("putpkt: write failed");
1102
1103 /* read until either a timeout occurs (-2) or '+' is read */
1104 while (1)
1105 {
1106 ch = readchar ();
1107
1108 switch (ch)
1109 {
1110 case '+':
1111 if (remote_debug)
1112 printf_unfiltered("Ack\n");
1113 return;
1114 case SERIAL_TIMEOUT:
1115 break; /* Retransmit buffer */
1116 case SERIAL_ERROR:
1117 perror_with_name ("putpkt: couldn't read ACK");
1118 case SERIAL_EOF:
1119 error ("putpkt: EOF while trying to read ACK");
1120 default:
1121 if (remote_debug)
1122 printf_unfiltered ("%02X %c ", ch&0xFF, ch);
1123 continue;
1124 }
1125 break; /* Here to retransmit */
1126 }
1127
1128 #if 0
1129 /* This is wrong. If doing a long backtrace, the user should be
1130 able to get out next time we call QUIT, without anything as violent
1131 as interrupt_query. If we want to provide a way out of here
1132 without getting to the next QUIT, it should be based on hitting
1133 ^C twice as in remote_wait. */
1134 if (quit_flag)
1135 {
1136 quit_flag = 0;
1137 interrupt_query ();
1138 }
1139 #endif
1140 }
1141 }
1142
1143 /* Read a packet from the remote machine, with error checking,
1144 and store it in BUF. BUF is expected to be of size PBUFSIZ.
1145 If FOREVER, wait forever rather than timing out; this is used
1146 while the target is executing user code. */
1147
1148 static void
1149 getpkt (retbuf, forever)
1150 char *retbuf;
1151 int forever;
1152 {
1153 char *bp;
1154 unsigned char csum;
1155 int c = 0;
1156 unsigned char c1, c2;
1157 int retries = 0;
1158 char buf[PBUFSIZ];
1159
1160 #define MAX_RETRIES 10
1161
1162 while (1)
1163 {
1164 #if 0
1165 /* This is wrong. If doing a long backtrace, the user should be
1166 able to get out time next we call QUIT, without anything as violent
1167 as interrupt_query. If we want to provide a way out of here
1168 without getting to the next QUIT, it should be based on hitting
1169 ^C twice as in remote_wait. */
1170 if (quit_flag)
1171 {
1172 quit_flag = 0;
1173 interrupt_query ();
1174 }
1175 #endif
1176
1177 /* This can loop forever if the remote side sends us characters
1178 continuously, but if it pauses, we'll get a zero from readchar
1179 because of timeout. Then we'll count that as a retry. */
1180
1181 c = readchar();
1182 if (c > 0 && c != '$')
1183 continue;
1184
1185 if (c == SERIAL_TIMEOUT)
1186 {
1187 if (forever)
1188 continue;
1189 if (++retries >= MAX_RETRIES)
1190 if (remote_debug) puts_filtered ("Timed out.\n");
1191 goto out;
1192 }
1193
1194 if (c == SERIAL_EOF)
1195 error ("Remote connection closed");
1196 if (c == SERIAL_ERROR)
1197 perror_with_name ("Remote communication error");
1198
1199 /* Force csum to be zero here because of possible error retry. */
1200 csum = 0;
1201 bp = buf;
1202
1203 while (1)
1204 {
1205 c = readchar ();
1206 if (c == SERIAL_TIMEOUT)
1207 {
1208 if (remote_debug)
1209 puts_filtered ("Timeout in mid-packet, retrying\n");
1210 goto whole; /* Start a new packet, count retries */
1211 }
1212 if (c == '$')
1213 {
1214 if (remote_debug)
1215 puts_filtered ("Saw new packet start in middle of old one\n");
1216 goto whole; /* Start a new packet, count retries */
1217 }
1218 if (c == '#')
1219 break;
1220 if (bp >= buf+PBUFSIZ-1)
1221 {
1222 *bp = '\0';
1223 puts_filtered ("Remote packet too long: ");
1224 puts_filtered (buf);
1225 puts_filtered ("\n");
1226 goto whole;
1227 }
1228 *bp++ = c;
1229 csum += c;
1230 }
1231 *bp = 0;
1232
1233 c1 = fromhex (readchar ());
1234 c2 = fromhex (readchar ());
1235 if ((csum & 0xff) == (c1 << 4) + c2)
1236 break;
1237 printf_filtered ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=",
1238 (c1 << 4) + c2, csum & 0xff);
1239 puts_filtered (buf);
1240 puts_filtered ("\n");
1241
1242 /* Try the whole thing again. */
1243 whole:
1244 if (++retries < MAX_RETRIES)
1245 {
1246 SERIAL_WRITE (remote_desc, "-", 1);
1247 }
1248 else
1249 {
1250 printf_unfiltered ("Ignoring packet error, continuing...\n");
1251 break;
1252 }
1253 }
1254
1255 /* Deal with run-length encoding. */
1256 {
1257 char *src = buf;
1258 char *dest = retbuf;
1259 int i;
1260 int repeat;
1261 do {
1262 if (*src == '*')
1263 {
1264 if (src[1] == '\0' || src[2] == '\0')
1265 {
1266 if (remote_debug)
1267 puts_filtered ("Packet too short, retrying\n");
1268 goto whole;
1269 }
1270 repeat = (fromhex (src[1]) << 4) + fromhex (src[2]);
1271 for (i = 0; i < repeat; ++i)
1272 {
1273 *dest++ = src[-1];
1274 }
1275 src += 2;
1276 }
1277 else
1278 {
1279 *dest++ = *src;
1280 }
1281 } while (*src++ != '\0');
1282 }
1283
1284 out:
1285 SERIAL_WRITE (remote_desc, "+", 1);
1286
1287 if (remote_debug)
1288 fprintf_unfiltered (gdb_stderr,"Packet received: %s\n", buf);
1289 }
1290 \f
1291 static void
1292 remote_kill ()
1293 {
1294 putpkt ("k");
1295 /* Don't wait for it to die. I'm not really sure it matters whether
1296 we do or not. For the existing stubs, kill is a noop. */
1297 target_mourn_inferior ();
1298 }
1299
1300 static void
1301 remote_mourn ()
1302 {
1303 unpush_target (&remote_ops);
1304 generic_mourn_inferior ();
1305 }
1306 \f
1307 #ifdef REMOTE_BREAKPOINT
1308
1309 /* On some machines, e.g. 68k, we may use a different breakpoint instruction
1310 than other targets. */
1311 static unsigned char break_insn[] = REMOTE_BREAKPOINT;
1312
1313 /* Check that it fits in BREAKPOINT_MAX bytes. */
1314 static unsigned char check_break_insn_size[BREAKPOINT_MAX] = REMOTE_BREAKPOINT;
1315
1316 #else /* No REMOTE_BREAKPOINT. */
1317
1318 /* Same old breakpoint instruction. This code does nothing different
1319 than mem-break.c. */
1320 static unsigned char break_insn[] = BREAKPOINT;
1321
1322 #endif /* No REMOTE_BREAKPOINT. */
1323
1324 /* Insert a breakpoint on targets that don't have any better breakpoint
1325 support. We read the contents of the target location and stash it,
1326 then overwrite it with a breakpoint instruction. ADDR is the target
1327 location in the target machine. CONTENTS_CACHE is a pointer to
1328 memory allocated for saving the target contents. It is guaranteed
1329 by the caller to be long enough to save sizeof BREAKPOINT bytes (this
1330 is accomplished via BREAKPOINT_MAX). */
1331
1332 static int
1333 remote_insert_breakpoint (addr, contents_cache)
1334 CORE_ADDR addr;
1335 char *contents_cache;
1336 {
1337 int val;
1338
1339 val = target_read_memory (addr, contents_cache, sizeof break_insn);
1340
1341 if (val == 0)
1342 val = target_write_memory (addr, (char *)break_insn, sizeof break_insn);
1343
1344 return val;
1345 }
1346
1347 static int
1348 remote_remove_breakpoint (addr, contents_cache)
1349 CORE_ADDR addr;
1350 char *contents_cache;
1351 {
1352 return target_write_memory (addr, contents_cache, sizeof break_insn);
1353 }
1354 \f
1355 /* Define the target subroutine names */
1356
1357 struct target_ops remote_ops = {
1358 "remote", /* to_shortname */
1359 "Remote serial target in gdb-specific protocol", /* to_longname */
1360 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
1361 Specify the serial device it is connected to (e.g. /dev/ttya).", /* to_doc */
1362 remote_open, /* to_open */
1363 remote_close, /* to_close */
1364 NULL, /* to_attach */
1365 remote_detach, /* to_detach */
1366 remote_resume, /* to_resume */
1367 remote_wait, /* to_wait */
1368 remote_fetch_registers, /* to_fetch_registers */
1369 remote_store_registers, /* to_store_registers */
1370 remote_prepare_to_store, /* to_prepare_to_store */
1371 remote_xfer_memory, /* to_xfer_memory */
1372 remote_files_info, /* to_files_info */
1373
1374 remote_insert_breakpoint, /* to_insert_breakpoint */
1375 remote_remove_breakpoint, /* to_remove_breakpoint */
1376
1377 NULL, /* to_terminal_init */
1378 NULL, /* to_terminal_inferior */
1379 NULL, /* to_terminal_ours_for_output */
1380 NULL, /* to_terminal_ours */
1381 NULL, /* to_terminal_info */
1382 remote_kill, /* to_kill */
1383 generic_load, /* to_load */
1384 NULL, /* to_lookup_symbol */
1385 NULL, /* to_create_inferior */
1386 remote_mourn, /* to_mourn_inferior */
1387 0, /* to_can_run */
1388 0, /* to_notice_signals */
1389 process_stratum, /* to_stratum */
1390 NULL, /* to_next */
1391 1, /* to_has_all_memory */
1392 1, /* to_has_memory */
1393 1, /* to_has_stack */
1394 1, /* to_has_registers */
1395 1, /* to_has_execution */
1396 NULL, /* sections */
1397 NULL, /* sections_end */
1398 OPS_MAGIC /* to_magic */
1399 };
1400 #endif /* Use remote. */
1401
1402 void
1403 _initialize_remote ()
1404 {
1405 #if !defined(DONT_USE_REMOTE)
1406 add_target (&remote_ops);
1407 #endif
1408 }