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