Thu Jun 4 08:25:38 1998 Michael Snyder <msnyder@cleaver.cygnus.com>
[platform/upstream/binutils.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2    Copyright 1988, 1991, 1992, 1993, 1994, 1995, 1996, 1997 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    Most values are encoded in ascii hex digits.  Signal numbers are according
42    to the numbering in target.h.
43
44         Request         Packet
45
46         set thread      Hct...          Set thread for subsequent operations.
47                                         c = 'c' for thread used in step and 
48                                         continue; t... can be -1 for all
49                                         threads.
50                                         c = 'g' for thread used in other
51                                         operations.  If zero, pick a thread,
52                                         any thread.
53         reply           OK              for success
54                         ENN             for an error.
55
56         read registers  g
57         reply           XX....X         Each byte of register data
58                                         is described by two hex digits.
59                                         Registers are in the internal order
60                                         for GDB, and the bytes in a register
61                                         are in the same order the machine uses.
62                         or ENN          for an error.
63
64         write regs      GXX..XX         Each byte of register data
65                                         is described by two hex digits.
66         reply           OK              for success
67                         ENN             for an error
68
69         write reg       Pn...=r...      Write register n... with value r...,
70                                         which contains two hex digits for each
71                                         byte in the register (target byte
72                                         order).
73         reply           OK              for success
74                         ENN             for an error
75         (not supported by all stubs).
76
77         read mem        mAA..AA,LLLL    AA..AA is address, LLLL is length.
78         reply           XX..XX          XX..XX is mem contents
79                                         Can be fewer bytes than requested
80                                         if able to read only part of the data.
81                         or ENN          NN is errno
82
83         write mem       MAA..AA,LLLL:XX..XX
84                                         AA..AA is address,
85                                         LLLL is number of bytes,
86                                         XX..XX is data
87         reply           OK              for success
88                         ENN             for an error (this includes the case
89                                         where only part of the data was
90                                         written).
91
92         continue        cAA..AA         AA..AA is address to resume
93                                         If AA..AA is omitted,
94                                         resume at same address.
95
96         step            sAA..AA         AA..AA is address to resume
97                                         If AA..AA is omitted,
98                                         resume at same address.
99
100         continue with   Csig;AA..AA     Continue with signal sig (hex signal
101         signal                          number).  If ;AA..AA is omitted, resume
102                                         at same address.
103
104         step with       Ssig;AA..AA     Like 'C' but step not continue.
105         signal
106
107         last signal     ?               Reply the current reason for stopping.
108                                         This is the same reply as is generated
109                                         for step or cont : SAA where AA is the
110                                         signal number.
111
112         detach          D               Reply OK.
113
114         There is no immediate reply to step or cont.
115         The reply comes when the machine stops.
116         It is           SAA             AA is the signal number.
117
118         or...           TAAn...:r...;n...:r...;n...:r...;
119                                         AA = signal number
120                                         n... = register number (hex)
121                                           r... = register contents
122                                         n... = `thread'
123                                           r... = thread process ID.  This is
124                                                  a hex integer.
125                                         n... = other string not starting 
126                                             with valid hex digit.
127                                           gdb should ignore this n,r pair
128                                           and go on to the next.  This way
129                                           we can extend the protocol.
130         or...           WAA             The process exited, and AA is
131                                         the exit status.  This is only
132                                         applicable for certains sorts of
133                                         targets.
134         or...           XAA             The process terminated with signal
135                                         AA.
136         or...           OXX..XX XX..XX  is hex encoding of ASCII data. This
137                                         can happen at any time while the program is
138                                         running and the debugger should
139                                         continue to wait for 'W', 'T', etc.
140
141         thread alive    TXX             Find out if the thread XX is alive.
142         reply           OK              thread is still alive
143                         ENN             thread is dead
144         
145         remote restart  RXX             Restart the remote server
146
147         extended ops    !               Use the extended remote protocol.
148                                         Sticky -- only needs to be set once.
149
150         kill request    k
151
152         toggle debug    d               toggle debug flag (see 386 & 68k stubs)
153         reset           r               reset -- see sparc stub.
154         reserved        <other>         On other requests, the stub should
155                                         ignore the request and send an empty
156                                         response ($#<checksum>).  This way
157                                         we can extend the protocol and GDB
158                                         can tell whether the stub it is
159                                         talking to uses the old or the new.
160         search          tAA:PP,MM       Search backwards starting at address
161                                         AA for a match with pattern PP and
162                                         mask MM.  PP and MM are 4 bytes.
163                                         Not supported by all stubs.
164
165         general query   qXXXX           Request info about XXXX.
166         general set     QXXXX=yyyy      Set value of XXXX to yyyy.
167         query sect offs qOffsets        Get section offsets.  Reply is
168                                         Text=xxx;Data=yyy;Bss=zzz
169
170         Responses can be run-length encoded to save space.  A '*' means that
171         the next character is an ASCII encoding giving a repeat count which
172         stands for that many repititions of the character preceding the '*'.
173         The encoding is n+29, yielding a printable character where n >=3 
174         (which is where rle starts to win).  Don't use an n > 126.
175
176         So 
177         "0* " means the same as "0000".  */
178
179 #include "defs.h"
180 #include "gdb_string.h"
181 #include <fcntl.h>
182 #include "frame.h"
183 #include "inferior.h"
184 #include "bfd.h"
185 #include "symfile.h"
186 #include "target.h"
187 #include "wait.h"
188 /*#include "terminal.h"*/
189 #include "gdbcmd.h"
190 #include "objfiles.h"
191 #include "gdb-stabs.h"
192 #include "gdbthread.h"
193
194 #include "dcache.h"
195
196 #ifdef USG
197 #include <sys/types.h>
198 #endif
199
200 #include <signal.h>
201 #include "serial.h"
202
203 /* Prototypes for local functions */
204
205 static int remote_write_bytes PARAMS ((CORE_ADDR memaddr,
206                                        char *myaddr, int len));
207
208 static int remote_read_bytes PARAMS ((CORE_ADDR memaddr,
209                                       char *myaddr, int len));
210
211 static void remote_files_info PARAMS ((struct target_ops *ignore));
212
213 static int remote_xfer_memory PARAMS ((CORE_ADDR memaddr, char *myaddr,
214                                        int len, int should_write,
215                                        struct target_ops *target));
216
217 static void remote_prepare_to_store PARAMS ((void));
218
219 static void remote_fetch_registers PARAMS ((int regno));
220
221 static void remote_resume PARAMS ((int pid, int step,
222                                    enum target_signal siggnal));
223
224 static int remote_start_remote PARAMS ((char *dummy));
225
226 static void remote_open PARAMS ((char *name, int from_tty));
227
228 static void extended_remote_open PARAMS ((char *name, int from_tty));
229
230 static void remote_open_1 PARAMS ((char *, int, struct target_ops *, int extended_p));
231
232 static void remote_close PARAMS ((int quitting));
233
234 static void remote_store_registers PARAMS ((int regno));
235
236 static void remote_mourn PARAMS ((void));
237
238 static void extended_remote_restart PARAMS ((void));
239
240 static void extended_remote_mourn PARAMS ((void));
241
242 static void extended_remote_create_inferior PARAMS ((char *, char *, char **));
243
244 static void remote_mourn_1 PARAMS ((struct target_ops *));
245
246 static void remote_send PARAMS ((char *buf));
247
248 static int readchar PARAMS ((int timeout));
249
250 static int remote_wait PARAMS ((int pid, struct target_waitstatus *status));
251
252 static void remote_kill PARAMS ((void));
253
254 static int tohex PARAMS ((int nib));
255
256 static void remote_detach PARAMS ((char *args, int from_tty));
257
258 static void remote_interrupt PARAMS ((int signo));
259
260 static void remote_interrupt_twice PARAMS ((int signo));
261
262 static void interrupt_query PARAMS ((void));
263
264 static void set_thread PARAMS ((int, int));
265
266 static int remote_thread_alive PARAMS ((int));
267
268 static void get_offsets PARAMS ((void));
269
270 static int read_frame PARAMS ((char *));
271
272 static int remote_insert_breakpoint PARAMS ((CORE_ADDR, char *));
273
274 static int remote_remove_breakpoint PARAMS ((CORE_ADDR, char *));
275
276 static int hexnumlen PARAMS ((ULONGEST num));
277
278 /* exported functions */
279
280 extern int fromhex PARAMS ((int a));
281 extern void getpkt PARAMS ((char *buf, int forever));
282 extern int putpkt PARAMS ((char *buf));
283
284 /* Define the target subroutine names */
285
286 static struct target_ops remote_ops ;
287
288 static void init_remote_ops(void)
289 {
290   remote_ops.to_shortname =   "remote";         
291   remote_ops.to_longname =   "Remote serial target in gdb-specific protocol";
292   remote_ops.to_doc =   "Use a remote computer via a serial line; using a gdb-specific protocol.\n\
293 Specify the serial device it is connected to (e.g. /dev/ttya)." ;  
294   remote_ops.to_open =   remote_open;           
295   remote_ops.to_close =   remote_close;         
296   remote_ops.to_attach =   NULL;                
297   remote_ops.to_detach =   remote_detach;       
298   remote_ops.to_resume =   remote_resume;       
299   remote_ops.to_wait  =   remote_wait;          
300   remote_ops.to_fetch_registers  =   remote_fetch_registers;
301   remote_ops.to_store_registers  =   remote_store_registers;
302   remote_ops.to_prepare_to_store =   remote_prepare_to_store;
303   remote_ops.to_xfer_memory  =   remote_xfer_memory;    
304   remote_ops.to_files_info  =   remote_files_info;      
305   remote_ops.to_insert_breakpoint =   remote_insert_breakpoint;
306   remote_ops.to_remove_breakpoint =   remote_remove_breakpoint;
307   remote_ops.to_terminal_init  =   NULL;                
308   remote_ops.to_terminal_inferior =   NULL;             
309   remote_ops.to_terminal_ours_for_output =   NULL;
310   remote_ops.to_terminal_ours  =   NULL;        
311   remote_ops.to_terminal_info  =   NULL;        
312   remote_ops.to_kill  =   remote_kill;          
313   remote_ops.to_load  =   generic_load;         
314   remote_ops.to_lookup_symbol =   NULL;         
315   remote_ops.to_create_inferior =   NULL;       
316   remote_ops.to_mourn_inferior =   remote_mourn;
317   remote_ops.to_can_run  =   0;                 
318   remote_ops.to_notice_signals =   0;           
319   remote_ops.to_thread_alive  =   remote_thread_alive;
320   remote_ops.to_stop  =   0;            
321   remote_ops.to_stratum =   process_stratum;
322   remote_ops.DONT_USE =   NULL;         
323   remote_ops.to_has_all_memory =   1;   
324   remote_ops.to_has_memory =   1;       
325   remote_ops.to_has_stack =   1;        
326   remote_ops.to_has_registers =   1;    
327   remote_ops.to_has_execution =   1;    
328   remote_ops.to_sections =   NULL;      
329   remote_ops.to_sections_end =   NULL;  
330   remote_ops.to_magic =   OPS_MAGIC ;   
331 } /* init_remote_ops */
332
333 static struct target_ops extended_remote_ops ;
334
335 static void init_extended_remote_ops(void) 
336 {
337   extended_remote_ops.to_shortname =   "extended-remote";       
338   extended_remote_ops.to_longname =   "Extended remote serial target in gdb-specific protocol";
339   extended_remote_ops.to_doc =   "Use a remote computer via a serial line; using a gdb-specific protocol.\n\
340 Specify the serial device it is connected to (e.g. /dev/ttya).",
341     extended_remote_ops.to_open =   extended_remote_open;       
342   extended_remote_ops.to_close =   remote_close;        
343   extended_remote_ops.to_attach =   NULL;               
344   extended_remote_ops.to_detach =   remote_detach;      
345   extended_remote_ops.to_resume =   remote_resume;      
346   extended_remote_ops.to_wait  =   remote_wait;         
347   extended_remote_ops.to_fetch_registers  =   remote_fetch_registers;
348   extended_remote_ops.to_store_registers  =   remote_store_registers;   
349   extended_remote_ops.to_prepare_to_store =   remote_prepare_to_store;
350   extended_remote_ops.to_xfer_memory  =   remote_xfer_memory;   
351   extended_remote_ops.to_files_info  =   remote_files_info;     
352   extended_remote_ops.to_insert_breakpoint =   remote_insert_breakpoint;
353   extended_remote_ops.to_remove_breakpoint =   remote_remove_breakpoint;
354   extended_remote_ops.to_terminal_init  =   NULL;               
355   extended_remote_ops.to_terminal_inferior =   NULL;            
356   extended_remote_ops.to_terminal_ours_for_output =   NULL;
357   extended_remote_ops.to_terminal_ours  =   NULL;       
358   extended_remote_ops.to_terminal_info  =   NULL;       
359   extended_remote_ops.to_kill  =   remote_kill;         
360   extended_remote_ops.to_load  =   generic_load;        
361   extended_remote_ops.to_lookup_symbol =   NULL;        
362   extended_remote_ops.to_create_inferior =   extended_remote_create_inferior;
363   extended_remote_ops.to_mourn_inferior =   extended_remote_mourn;
364   extended_remote_ops.to_can_run  =   0;                        
365   extended_remote_ops.to_notice_signals =   0;                  
366   extended_remote_ops.to_thread_alive  =   remote_thread_alive;
367   extended_remote_ops.to_stop  =   0;                   
368   extended_remote_ops.to_stratum =   process_stratum;
369   extended_remote_ops.DONT_USE =   NULL;        
370   extended_remote_ops.to_has_all_memory =   1;  
371   extended_remote_ops.to_has_memory =   1;      
372   extended_remote_ops.to_has_stack =   1;       
373   extended_remote_ops.to_has_registers =   1;   
374   extended_remote_ops.to_has_execution =   1;   
375   extended_remote_ops.to_sections =   NULL;     
376   extended_remote_ops.to_sections_end =   NULL;
377   extended_remote_ops.to_magic =   OPS_MAGIC ;
378
379
380
381 /* This was 5 seconds, which is a long time to sit and wait.
382    Unless this is going though some terminal server or multiplexer or
383    other form of hairy serial connection, I would think 2 seconds would
384    be plenty.  */
385
386 /* Changed to allow option to set timeout value.
387    was static int remote_timeout = 2; */
388 extern int remote_timeout;
389
390 /* This variable chooses whether to send a ^C or a break when the user
391    requests program interruption.  Although ^C is usually what remote
392    systems expect, and that is the default here, sometimes a break is
393    preferable instead.  */
394
395 static int remote_break;
396
397 /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
398    remote_open knows that we don't have a file open when the program
399    starts.  */
400 static serial_t remote_desc = NULL;
401
402 /* Having this larger than 400 causes us to be incompatible with m68k-stub.c
403    and i386-stub.c.  Normally, no one would notice because it only matters
404    for writing large chunks of memory (e.g. in downloads).  Also, this needs
405    to be more than 400 if required to hold the registers (see below, where
406    we round it up based on REGISTER_BYTES).  */
407 #define PBUFSIZ 400
408
409 /* Maximum number of bytes to read/write at once.  The value here
410    is chosen to fill up a packet (the headers account for the 32).  */
411 #define MAXBUFBYTES ((PBUFSIZ-32)/2)
412
413 /* Round up PBUFSIZ to hold all the registers, at least.  */
414 /* The blank line after the #if seems to be required to work around a
415    bug in HP's PA compiler.  */
416 #if REGISTER_BYTES > MAXBUFBYTES
417
418 #undef PBUFSIZ
419 #define PBUFSIZ (REGISTER_BYTES * 2 + 32)
420 #endif
421
422 /* This variable sets the number of bytes to be written to the target
423    in a single packet.  Normally PBUFSIZ is satisfactory, but some
424    targets need smaller values (perhaps because the receiving end
425    is slow).  */
426
427 static int remote_write_size = PBUFSIZ;
428
429 /* This is the size (in chars) of the first response to the `g' command.  This
430    is used to limit the size of the memory read and write commands to prevent
431    stub buffers from overflowing.  The size does not include headers and
432    trailers, it is only the payload size. */
433
434 static int remote_register_buf_size = 0;
435
436 /* Should we try the 'P' request?  If this is set to one when the stub
437    doesn't support 'P', the only consequence is some unnecessary traffic.  */
438 static int stub_supports_P = 1;
439
440 /* These are pointers to hook functions that may be set in order to
441    modify resume/wait behavior for a particular architecture.  */
442
443 void (*target_resume_hook) PARAMS ((void));
444 void (*target_wait_loop_hook) PARAMS ((void));
445
446 \f
447 /* These are the threads which we last sent to the remote system.  -1 for all
448    or -2 for not sent yet.  */
449 int general_thread;
450 int cont_thread;
451
452 static void
453 set_thread (th, gen)
454      int th;
455      int gen;
456 {
457   char buf[PBUFSIZ];
458   int state = gen ? general_thread : cont_thread;
459   if (state == th)
460     return;
461   buf[0] = 'H';
462   buf[1] = gen ? 'g' : 'c';
463   if (th == 42000)
464     {
465       buf[2] = '0';
466       buf[3] = '\0';
467     }
468   else if (th < 0)
469     sprintf (&buf[2], "-%x", -th);
470   else
471     sprintf (&buf[2], "%x", th);
472   putpkt (buf);
473   getpkt (buf, 0);
474   if (gen)
475     general_thread = th;
476   else
477     cont_thread = th;
478 }
479 \f
480 /*  Return nonzero if the thread TH is still alive on the remote system.  */
481
482 static int
483 remote_thread_alive (th)
484      int th;
485 {
486   char buf[PBUFSIZ];
487
488   buf[0] = 'T';
489   if (th < 0)
490     sprintf (&buf[1], "-%x", -th);
491   else
492     sprintf (&buf[1], "%x", th);
493   putpkt (buf);
494   getpkt (buf, 0);
495   return (buf[0] == 'O' && buf[1] == 'K');
496 }
497
498 /*  Restart the remote side; this is an extended protocol operation.  */
499
500 static void
501 extended_remote_restart ()
502 {
503   char buf[PBUFSIZ];
504
505   /* Send the restart command; for reasons I don't understand the
506      remote side really expects a number after the "R".  */
507   buf[0] = 'R';
508   sprintf (&buf[1], "%x", 0);
509   putpkt (buf);
510
511   /* Now query for status so this looks just like we restarted
512      gdbserver from scratch.  */
513   putpkt ("?");
514   getpkt (buf, 0);
515 }
516 \f
517 /* Clean up connection to a remote debugger.  */
518
519 /* ARGSUSED */
520 static void
521 remote_close (quitting)
522      int quitting;
523 {
524   if (remote_desc)
525     SERIAL_CLOSE (remote_desc);
526   remote_desc = NULL;
527 }
528
529 /* Query the remote side for the text, data and bss offsets. */
530
531 static void
532 get_offsets ()
533 {
534   char buf[PBUFSIZ], *ptr;
535   int lose;
536   CORE_ADDR text_addr, data_addr, bss_addr;
537   struct section_offsets *offs;
538
539   putpkt ("qOffsets");
540
541   getpkt (buf, 0);
542
543   if (buf[0] == '\000')
544     return;                     /* Return silently.  Stub doesn't support this
545                                    command. */
546   if (buf[0] == 'E')
547     {
548       warning ("Remote failure reply: %s", buf);
549       return;
550     }
551
552   /* Pick up each field in turn.  This used to be done with scanf, but
553      scanf will make trouble if CORE_ADDR size doesn't match
554      conversion directives correctly.  The following code will work
555      with any size of CORE_ADDR.  */
556   text_addr = data_addr = bss_addr = 0;
557   ptr = buf;
558   lose = 0;
559
560   if (strncmp (ptr, "Text=", 5) == 0)
561     {
562       ptr += 5;
563       /* Don't use strtol, could lose on big values.  */
564       while (*ptr && *ptr != ';')
565         text_addr = (text_addr << 4) + fromhex (*ptr++);
566     }
567   else
568     lose = 1;
569
570   if (!lose && strncmp (ptr, ";Data=", 6) == 0)
571     {
572       ptr += 6;
573       while (*ptr && *ptr != ';')
574         data_addr = (data_addr << 4) + fromhex (*ptr++);
575     }
576   else
577     lose = 1;
578
579   if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
580     {
581       ptr += 5;
582       while (*ptr && *ptr != ';')
583         bss_addr = (bss_addr << 4) + fromhex (*ptr++);
584     }
585   else
586     lose = 1;
587
588   if (lose)
589     error ("Malformed response to offset query, %s", buf);
590
591   if (symfile_objfile == NULL)
592     return;
593
594   offs = (struct section_offsets *) alloca (sizeof (struct section_offsets)
595                                             + symfile_objfile->num_sections
596                                             * sizeof (offs->offsets));
597   memcpy (offs, symfile_objfile->section_offsets,
598           sizeof (struct section_offsets)
599           + symfile_objfile->num_sections
600           * sizeof (offs->offsets));
601
602   ANOFFSET (offs, SECT_OFF_TEXT) = text_addr;
603
604   /* This is a temporary kludge to force data and bss to use the same offsets
605      because that's what nlmconv does now.  The real solution requires changes
606      to the stub and remote.c that I don't have time to do right now.  */
607
608   ANOFFSET (offs, SECT_OFF_DATA) = data_addr;
609   ANOFFSET (offs, SECT_OFF_BSS) = data_addr;
610
611   objfile_relocate (symfile_objfile, offs);
612 }
613
614 /* Stub for catch_errors.  */
615
616 static int
617 remote_start_remote (dummy)
618      char *dummy;
619 {
620   immediate_quit = 1;           /* Allow user to interrupt it */
621
622   /* Ack any packet which the remote side has already sent.  */
623   SERIAL_WRITE (remote_desc, "+", 1);
624
625   /* Let the stub know that we want it to return the thread.  */
626   set_thread (-1, 0);
627
628   get_offsets ();               /* Get text, data & bss offsets */
629
630   putpkt ("?");                 /* initiate a query from remote machine */
631   immediate_quit = 0;
632
633   start_remote ();              /* Initialize gdb process mechanisms */
634   return 1;
635 }
636
637 /* Open a connection to a remote debugger.
638    NAME is the filename used for communication.  */
639
640 static void
641 remote_open (name, from_tty)
642      char *name;
643      int from_tty;
644 {
645   remote_open_1 (name, from_tty, &remote_ops, 0);
646 }
647
648 /* Open a connection to a remote debugger using the extended
649    remote gdb protocol.  NAME is the filename used for communication.  */
650
651 static void
652 extended_remote_open (name, from_tty)
653      char *name;
654      int from_tty;
655 {
656   remote_open_1 (name, from_tty, &extended_remote_ops, 1/*extended_p*/);
657 }
658
659 /* Generic code for opening a connection to a remote target.  */
660 static DCACHE *remote_dcache;
661
662 static void
663 remote_open_1 (name, from_tty, target, extended_p)
664      char *name;
665      int from_tty;
666      struct target_ops *target;
667      int extended_p;
668 {
669   if (name == 0)
670     error ("To open a remote debug connection, you need to specify what serial\n\
671 device is attached to the remote system (e.g. /dev/ttya).");
672
673   target_preopen (from_tty);
674
675   unpush_target (target);
676
677   remote_dcache = dcache_init (remote_read_bytes, remote_write_bytes);
678
679   remote_desc = SERIAL_OPEN (name);
680   if (!remote_desc)
681     perror_with_name (name);
682
683   if (baud_rate != -1)
684     {
685       if (SERIAL_SETBAUDRATE (remote_desc, baud_rate))
686         {
687           SERIAL_CLOSE (remote_desc);
688           perror_with_name (name);
689         }
690     }
691
692
693   SERIAL_RAW (remote_desc);
694
695   /* If there is something sitting in the buffer we might take it as a
696      response to a command, which would be bad.  */
697   SERIAL_FLUSH_INPUT (remote_desc);
698
699   if (from_tty)
700     {
701       puts_filtered ("Remote debugging using ");
702       puts_filtered (name);
703       puts_filtered ("\n");
704     }
705   push_target (target); /* Switch to using remote target now */
706
707   /* Start out by trying the 'P' request to set registers.  We set this each
708      time that we open a new target so that if the user switches from one
709      stub to another, we can (if the target is closed and reopened) cope.  */
710   stub_supports_P = 1;
711
712   general_thread = -2;
713   cont_thread = -2;
714
715   /* Without this, some commands which require an active target (such as kill)
716      won't work.  This variable serves (at least) double duty as both the pid
717      of the target process (if it has such), and as a flag indicating that a
718      target is active.  These functions should be split out into seperate
719      variables, especially since GDB will someday have a notion of debugging
720      several processes.  */
721
722   inferior_pid = 42000;
723   /* Start the remote connection; if error (0), discard this target.
724      In particular, if the user quits, be sure to discard it
725      (we'd be in an inconsistent state otherwise).  */
726   if (!catch_errors (remote_start_remote, (char *)0, 
727                      "Couldn't establish connection to remote target\n", RETURN_MASK_ALL))
728     {
729       pop_target();
730       return;
731     }
732
733   if (extended_p)
734     {
735       /* tell the remote that we're using the extended protocol.  */
736       char buf[PBUFSIZ];
737       putpkt ("!");
738       getpkt (buf, 0);
739     }
740 }
741
742 /* This takes a program previously attached to and detaches it.  After
743    this is done, GDB can be used to debug some other program.  We
744    better not have left any breakpoints in the target program or it'll
745    die when it hits one.  */
746
747 static void
748 remote_detach (args, from_tty)
749      char *args;
750      int from_tty;
751 {
752   char buf[PBUFSIZ];
753
754   if (args)
755     error ("Argument given to \"detach\" when remotely debugging.");
756
757   /* Tell the remote target to detach.  */
758   strcpy (buf, "D");
759   remote_send (buf);
760
761   pop_target ();
762   if (from_tty)
763     puts_filtered ("Ending remote debugging.\n");
764 }
765
766 /* Convert hex digit A to a number.  */
767
768 int
769 fromhex (a)
770      int a;
771 {
772   if (a >= '0' && a <= '9')
773     return a - '0';
774   else if (a >= 'a' && a <= 'f')
775     return a - 'a' + 10;
776   else if (a >= 'A' && a <= 'F')
777     return a - 'A' + 10;
778   else 
779     error ("Reply contains invalid hex digit %d", a);
780 }
781
782 /* Convert number NIB to a hex digit.  */
783
784 static int
785 tohex (nib)
786      int nib;
787 {
788   if (nib < 10)
789     return '0'+nib;
790   else
791     return 'a'+nib-10;
792 }
793 \f
794 /* Tell the remote machine to resume.  */
795
796 static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
797 int last_sent_step;
798
799 static void
800 remote_resume (pid, step, siggnal)
801      int pid, step;
802      enum target_signal siggnal;
803 {
804   char buf[PBUFSIZ];
805
806   if (pid == -1)
807     set_thread (inferior_pid, 0);
808   else
809     set_thread (pid, 0);
810
811   dcache_flush (remote_dcache);
812
813   last_sent_signal = siggnal;
814   last_sent_step = step;
815
816   /* A hook for when we need to do something at the last moment before
817      resumption.  */
818   if (target_resume_hook)
819     (*target_resume_hook) ();
820
821   if (siggnal != TARGET_SIGNAL_0)
822     {
823       buf[0] = step ? 'S' : 'C';
824       buf[1] = tohex (((int)siggnal >> 4) & 0xf);
825       buf[2] = tohex ((int)siggnal & 0xf);
826       buf[3] = '\0';
827     }
828   else
829     strcpy (buf, step ? "s": "c");
830
831   putpkt (buf);
832 }
833 \f
834 /* Send ^C to target to halt it.  Target will respond, and send us a
835    packet.  */
836
837 static void
838 remote_interrupt (signo)
839      int signo;
840 {
841   /* If this doesn't work, try more severe steps.  */
842   signal (signo, remote_interrupt_twice);
843   
844   if (remote_debug)
845     printf_unfiltered ("remote_interrupt called\n");
846
847   /* Send a break or a ^C, depending on user preference.  */
848   if (remote_break)
849     SERIAL_SEND_BREAK (remote_desc);
850   else
851     SERIAL_WRITE (remote_desc, "\003", 1);
852 }
853
854 static void (*ofunc)();
855
856 /* The user typed ^C twice.  */
857 static void
858 remote_interrupt_twice (signo)
859      int signo;
860 {
861   signal (signo, ofunc);
862   
863   interrupt_query ();
864
865   signal (signo, remote_interrupt);
866 }
867
868 /* Ask the user what to do when an interrupt is received.  */
869
870 static void
871 interrupt_query ()
872 {
873   target_terminal_ours ();
874
875   if (query ("Interrupted while waiting for the program.\n\
876 Give up (and stop debugging it)? "))
877     {
878       target_mourn_inferior ();
879       return_to_top_level (RETURN_QUIT);
880     }
881
882   target_terminal_inferior ();
883 }
884
885 /* If nonzero, ignore the next kill.  */
886 int kill_kludge;
887
888 void
889 remote_console_output (msg)
890      char *msg;
891 {
892   char *p;
893
894   for (p = msg; *p; p +=2) 
895     {
896       char tb[2];
897       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
898       tb[0] = c;
899       tb[1] = 0;
900       if (target_output_hook)
901         target_output_hook (tb);
902       else 
903         fputs_filtered (tb, gdb_stdout);
904     }
905 }
906
907 /* Wait until the remote machine stops, then return,
908    storing status in STATUS just as `wait' would.
909    Returns "pid" (though it's not clear what, if anything, that
910    means in the case of this target).  */
911
912 static int
913 remote_wait (pid, status)
914      int pid;
915      struct target_waitstatus *status;
916 {
917   unsigned char buf[PBUFSIZ];
918   int thread_num = -1;
919
920   status->kind = TARGET_WAITKIND_EXITED;
921   status->value.integer = 0;
922
923   while (1)
924     {
925       unsigned char *p;
926
927       ofunc = (void (*)()) signal (SIGINT, remote_interrupt);
928       getpkt ((char *) buf, 1);
929       signal (SIGINT, ofunc);
930
931       /* This is a hook for when we need to do something (perhaps the
932          collection of trace data) every time the target stops.  */
933       if (target_wait_loop_hook)
934         (*target_wait_loop_hook) ();
935
936       switch (buf[0])
937         {
938         case 'E':               /* Error of some sort */
939           warning ("Remote failure reply: %s", buf);
940           continue;
941         case 'T':               /* Status with PC, SP, FP, ... */
942           {
943             int i;
944             long regno;
945             char regs[MAX_REGISTER_RAW_SIZE];
946
947             /* Expedited reply, containing Signal, {regno, reg} repeat */
948             /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
949                 ss = signal number
950                 n... = register number
951                 r... = register contents
952                 */
953             p = &buf[3];        /* after Txx */
954
955             while (*p)
956               {
957                 unsigned char *p1;
958                 char *p_temp;
959
960                 regno = strtol ((const char *) p, &p_temp, 16); /* Read the register number */
961                 p1 = (unsigned char *)p_temp;
962
963                 if (p1 == p)
964                   {
965                     p1 = (unsigned char *) strchr ((const char *) p, ':');
966                     if (p1 == NULL)
967                       warning ("Malformed packet (missing colon): %s\n\
968 Packet: '%s'\n",
969                                p, buf);
970                     if (strncmp ((const char *) p, "thread", p1 - p) == 0)
971                       {
972                         thread_num = strtol ((const char *) ++p1, &p_temp, 16);
973                         p = (unsigned char *)p_temp;
974                       }
975                   }
976                 else
977                   {
978                     p = p1;
979
980                     if (*p++ != ':')
981                       warning ("Malformed packet (missing colon): %s\n\
982 Packet: '%s'\n",
983                                p, buf);
984
985                     if (regno >= NUM_REGS)
986                       warning ("Remote sent bad register number %ld: %s\n\
987 Packet: '%s'\n",
988                                regno, p, buf);
989
990                     for (i = 0; i < REGISTER_RAW_SIZE (regno); i++)
991                       {
992                         if (p[0] == 0 || p[1] == 0)
993                           warning ("Remote reply is too short: %s", buf);
994                         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
995                         p += 2;
996                       }
997                     supply_register (regno, regs);
998                   }
999
1000                 if (*p++ != ';')
1001                   warning ("Remote register badly formatted: %s", buf);
1002               }
1003           }
1004           /* fall through */
1005         case 'S':               /* Old style status, just signal only */
1006           status->kind = TARGET_WAITKIND_STOPPED;
1007           status->value.sig = (enum target_signal)
1008             (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
1009
1010           goto got_status;
1011         case 'W':               /* Target exited */
1012           {
1013             /* The remote process exited.  */
1014             status->kind = TARGET_WAITKIND_EXITED;
1015             status->value.integer = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
1016             goto got_status;
1017           }
1018         case 'X':
1019           status->kind = TARGET_WAITKIND_SIGNALLED;
1020           status->value.sig = (enum target_signal)
1021             (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
1022           kill_kludge = 1;
1023
1024           goto got_status;
1025         case 'O':               /* Console output */
1026           remote_console_output (buf + 1);
1027           continue;
1028         case '\0':
1029           if (last_sent_signal != TARGET_SIGNAL_0)
1030             {
1031               /* Zero length reply means that we tried 'S' or 'C' and
1032                  the remote system doesn't support it.  */
1033               target_terminal_ours_for_output ();
1034               printf_filtered
1035                 ("Can't send signals to this remote system.  %s not sent.\n",
1036                  target_signal_to_name (last_sent_signal));
1037               last_sent_signal = TARGET_SIGNAL_0;
1038               target_terminal_inferior ();
1039
1040               strcpy ((char *) buf, last_sent_step ? "s" : "c");
1041               putpkt ((char *) buf);
1042               continue;
1043             }
1044           /* else fallthrough */
1045         default:
1046           warning ("Invalid remote reply: %s", buf);
1047           continue;
1048         }
1049     }
1050  got_status:
1051   if (thread_num != -1)
1052     {
1053       /* Initial thread value can only be acquired via wait, so deal with
1054          this marker which is used before the first thread value is
1055          acquired.  */
1056       if (inferior_pid == 42000)
1057         {
1058           inferior_pid = thread_num;
1059           add_thread (inferior_pid);
1060         }
1061       return thread_num;
1062     }
1063   return inferior_pid;
1064 }
1065
1066 /* Number of bytes of registers this stub implements.  */
1067 static int register_bytes_found;
1068
1069 /* Read the remote registers into the block REGS.  */
1070 /* Currently we just read all the registers, so we don't use regno.  */
1071 /* ARGSUSED */
1072 static void
1073 remote_fetch_registers (regno)
1074      int regno;
1075 {
1076   char buf[PBUFSIZ];
1077   int i;
1078   char *p;
1079   char regs[REGISTER_BYTES];
1080
1081   set_thread (inferior_pid, 1);
1082
1083   sprintf (buf, "g");
1084   remote_send (buf);
1085
1086   if (remote_register_buf_size == 0)
1087     remote_register_buf_size = strlen (buf);
1088
1089   /* Unimplemented registers read as all bits zero.  */
1090   memset (regs, 0, REGISTER_BYTES);
1091
1092   /* We can get out of synch in various cases.  If the first character
1093      in the buffer is not a hex character, assume that has happened
1094      and try to fetch another packet to read.  */
1095   while ((buf[0] < '0' || buf[0] > '9')
1096          && (buf[0] < 'a' || buf[0] > 'f'))
1097     {
1098       if (remote_debug)
1099         printf_unfiltered ("Bad register packet; fetching a new packet\n");
1100       getpkt (buf, 0);
1101     }
1102
1103   /* Reply describes registers byte by byte, each byte encoded as two
1104      hex characters.  Suck them all up, then supply them to the
1105      register cacheing/storage mechanism.  */
1106
1107   p = buf;
1108   for (i = 0; i < REGISTER_BYTES; i++)
1109     {
1110       if (p[0] == 0)
1111         break;
1112       if (p[1] == 0)
1113         {
1114           warning ("Remote reply is of odd length: %s", buf);
1115           /* Don't change register_bytes_found in this case, and don't
1116              print a second warning.  */
1117           goto supply_them;
1118         }
1119       regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
1120       p += 2;
1121     }
1122
1123   if (i != register_bytes_found)
1124     {
1125       register_bytes_found = i;
1126 #ifdef REGISTER_BYTES_OK
1127       if (!REGISTER_BYTES_OK (i))
1128         warning ("Remote reply is too short: %s", buf);
1129 #endif
1130     }
1131
1132  supply_them:
1133   for (i = 0; i < NUM_REGS; i++)
1134     supply_register (i, &regs[REGISTER_BYTE(i)]);
1135 }
1136
1137 /* Prepare to store registers.  Since we may send them all (using a
1138    'G' request), we have to read out the ones we don't want to change
1139    first.  */
1140
1141 static void 
1142 remote_prepare_to_store ()
1143 {
1144   /* Make sure the entire registers array is valid.  */
1145   read_register_bytes (0, (char *)NULL, REGISTER_BYTES);
1146 }
1147
1148 /* Store register REGNO, or all registers if REGNO == -1, from the contents
1149    of REGISTERS.  FIXME: ignores errors.  */
1150
1151 static void
1152 remote_store_registers (regno)
1153      int regno;
1154 {
1155   char buf[PBUFSIZ];
1156   int i;
1157   char *p;
1158
1159   set_thread (inferior_pid, 1);
1160
1161   if (regno >= 0 && stub_supports_P)
1162     {
1163       /* Try storing a single register.  */
1164       char *regp;
1165
1166       sprintf (buf, "P%x=", regno);
1167       p = buf + strlen (buf);
1168       regp = &registers[REGISTER_BYTE (regno)];
1169       for (i = 0; i < REGISTER_RAW_SIZE (regno); ++i)
1170         {
1171           *p++ = tohex ((regp[i] >> 4) & 0xf);
1172           *p++ = tohex (regp[i] & 0xf);
1173         }
1174       *p = '\0';
1175       remote_send (buf);
1176       if (buf[0] != '\0')
1177         {
1178           /* The stub understands the 'P' request.  We are done.  */
1179           return;
1180         }
1181
1182       /* The stub does not support the 'P' request.  Use 'G' instead,
1183          and don't try using 'P' in the future (it will just waste our
1184          time).  */
1185       stub_supports_P = 0;
1186     }
1187
1188   buf[0] = 'G';
1189
1190   /* Command describes registers byte by byte,
1191      each byte encoded as two hex characters.  */
1192
1193   p = buf + 1;
1194   /* remote_prepare_to_store insures that register_bytes_found gets set.  */
1195   for (i = 0; i < register_bytes_found; i++)
1196     {
1197       *p++ = tohex ((registers[i] >> 4) & 0xf);
1198       *p++ = tohex (registers[i] & 0xf);
1199     }
1200   *p = '\0';
1201
1202   remote_send (buf);
1203 }
1204
1205 /* 
1206    Use of the data cache *used* to be disabled because it loses for looking at
1207    and changing hardware I/O ports and the like.  Accepting `volatile'
1208    would perhaps be one way to fix it.  Another idea would be to use the
1209    executable file for the text segment (for all SEC_CODE sections?
1210    For all SEC_READONLY sections?).  This has problems if you want to
1211    actually see what the memory contains (e.g. self-modifying code,
1212    clobbered memory, user downloaded the wrong thing).  
1213
1214    Because it speeds so much up, it's now enabled, if you're playing
1215    with registers you turn it of (set remotecache 0)
1216 */
1217
1218 /* Read a word from remote address ADDR and return it.
1219    This goes through the data cache.  */
1220
1221 #if 0   /* unused? */
1222 static int
1223 remote_fetch_word (addr)
1224      CORE_ADDR addr;
1225 {
1226   return dcache_fetch (remote_dcache, addr);
1227 }
1228
1229 /* Write a word WORD into remote address ADDR.
1230    This goes through the data cache.  */
1231
1232 static void
1233 remote_store_word (addr, word)
1234      CORE_ADDR addr;
1235      int word;
1236 {
1237   dcache_poke (remote_dcache, addr, word);
1238 }
1239 #endif  /* 0 (unused?) */
1240
1241 \f
1242
1243 /* Return the number of hex digits in num.  */
1244
1245 static int
1246 hexnumlen (num)
1247      ULONGEST num;
1248 {
1249   int i;
1250
1251   for (i = 0; num != 0; i++)
1252     num >>= 4;
1253
1254   return max (i, 1);
1255 }
1256
1257 /* Write memory data directly to the remote machine.
1258    This does not inform the data cache; the data cache uses this.
1259    MEMADDR is the address in the remote memory space.
1260    MYADDR is the address of the buffer in our space.
1261    LEN is the number of bytes.
1262
1263    Returns number of bytes transferred, or 0 for error.  */
1264
1265 static int
1266 remote_write_bytes (memaddr, myaddr, len)
1267      CORE_ADDR memaddr;
1268      char *myaddr;
1269      int len;
1270 {
1271   int max_buf_size;             /* Max size of packet output buffer */
1272   int origlen;
1273
1274   /* Chop the transfer down if necessary */
1275
1276   max_buf_size = min (remote_write_size, PBUFSIZ);
1277   if (remote_register_buf_size != 0)
1278     max_buf_size = min (max_buf_size, remote_register_buf_size);
1279
1280   /* Subtract header overhead from max payload size -  $M<memaddr>,<len>:#nn */
1281   max_buf_size -= 2 + hexnumlen (memaddr + len - 1) + 1 + hexnumlen (len) + 4;
1282
1283   origlen = len;
1284   while (len > 0)
1285     {
1286       char buf[PBUFSIZ];
1287       char *p;
1288       int todo;
1289       int i;
1290
1291       todo = min (len, max_buf_size / 2); /* num bytes that will fit */
1292
1293       /* FIXME-32x64: Need a version of print_address_numeric which puts the
1294          result in a buffer like sprintf.  */
1295       sprintf (buf, "M%lx,%x:", (unsigned long) memaddr, todo);
1296
1297       /* We send target system values byte by byte, in increasing byte addresses,
1298          each byte encoded as two hex characters.  */
1299
1300       p = buf + strlen (buf);
1301       for (i = 0; i < todo; i++)
1302         {
1303           *p++ = tohex ((myaddr[i] >> 4) & 0xf);
1304           *p++ = tohex (myaddr[i] & 0xf);
1305         }
1306       *p = '\0';
1307
1308       putpkt (buf);
1309       getpkt (buf, 0);
1310
1311       if (buf[0] == 'E')
1312         {
1313           /* There is no correspondance between what the remote protocol uses
1314              for errors and errno codes.  We would like a cleaner way of
1315              representing errors (big enough to include errno codes, bfd_error
1316              codes, and others).  But for now just return EIO.  */
1317           errno = EIO;
1318           return 0;
1319         }
1320       myaddr += todo;
1321       memaddr += todo;
1322       len -= todo;
1323     }
1324   return origlen;
1325 }
1326
1327 /* Read memory data directly from the remote machine.
1328    This does not use the data cache; the data cache uses this.
1329    MEMADDR is the address in the remote memory space.
1330    MYADDR is the address of the buffer in our space.
1331    LEN is the number of bytes.
1332
1333    Returns number of bytes transferred, or 0 for error.  */
1334
1335 static int
1336 remote_read_bytes (memaddr, myaddr, len)
1337      CORE_ADDR memaddr;
1338      char *myaddr;
1339      int len;
1340 {
1341   int max_buf_size;             /* Max size of packet output buffer */
1342   int origlen;
1343
1344   /* Chop the transfer down if necessary */
1345
1346   max_buf_size = min (remote_write_size, PBUFSIZ);
1347   if (remote_register_buf_size != 0)
1348     max_buf_size = min (max_buf_size, remote_register_buf_size);
1349
1350   origlen = len;
1351   while (len > 0)
1352     {
1353       char buf[PBUFSIZ];
1354       char *p;
1355       int todo;
1356       int i;
1357
1358       todo = min (len, max_buf_size / 2); /* num bytes that will fit */
1359
1360       /* FIXME-32x64: Need a version of print_address_numeric which puts the
1361          result in a buffer like sprintf.  */
1362       sprintf (buf, "m%lx,%x", (unsigned long) memaddr, todo);
1363       putpkt (buf);
1364       getpkt (buf, 0);
1365
1366       if (buf[0] == 'E')
1367         {
1368           /* There is no correspondance between what the remote protocol uses
1369              for errors and errno codes.  We would like a cleaner way of
1370              representing errors (big enough to include errno codes, bfd_error
1371              codes, and others).  But for now just return EIO.  */
1372           errno = EIO;
1373           return 0;
1374         }
1375
1376   /* Reply describes memory byte by byte,
1377      each byte encoded as two hex characters.  */
1378
1379       p = buf;
1380       for (i = 0; i < todo; i++)
1381         {
1382           if (p[0] == 0 || p[1] == 0)
1383             /* Reply is short.  This means that we were able to read only part
1384                of what we wanted to.  */
1385             return i + (origlen - len);
1386           myaddr[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
1387           p += 2;
1388         }
1389       myaddr += todo;
1390       memaddr += todo;
1391       len -= todo;
1392     }
1393   return origlen;
1394 }
1395 \f
1396 /* Read or write LEN bytes from inferior memory at MEMADDR, transferring
1397    to or from debugger address MYADDR.  Write to inferior if SHOULD_WRITE is
1398    nonzero.  Returns length of data written or read; 0 for error.  */
1399
1400 /* ARGSUSED */
1401 static int
1402 remote_xfer_memory(memaddr, myaddr, len, should_write, target)
1403      CORE_ADDR memaddr;
1404      char *myaddr;
1405      int len;
1406      int should_write;
1407      struct target_ops *target;                 /* ignored */
1408 {
1409 #ifdef REMOTE_TRANSLATE_XFER_ADDRESS
1410   CORE_ADDR targaddr;
1411   int targlen;
1412   REMOTE_TRANSLATE_XFER_ADDRESS (memaddr, len, targaddr, targlen);
1413   if (targlen == 0)
1414     return 0;
1415   memaddr = targaddr;
1416   len = targlen;
1417 #endif
1418
1419   return dcache_xfer_memory (remote_dcache, memaddr, myaddr, len, should_write);
1420 }
1421
1422    
1423 #if 0
1424 /* Enable after 4.12.  */
1425
1426 void
1427 remote_search (len, data, mask, startaddr, increment, lorange, hirange
1428                addr_found, data_found)
1429      int len;
1430      char *data;
1431      char *mask;
1432      CORE_ADDR startaddr;
1433      int increment;
1434      CORE_ADDR lorange;
1435      CORE_ADDR hirange;
1436      CORE_ADDR *addr_found;
1437      char *data_found;
1438 {
1439   if (increment == -4 && len == 4)
1440     {
1441       long mask_long, data_long;
1442       long data_found_long;
1443       CORE_ADDR addr_we_found;
1444       char buf[PBUFSIZ];
1445       long returned_long[2];
1446       char *p;
1447
1448       mask_long = extract_unsigned_integer (mask, len);
1449       data_long = extract_unsigned_integer (data, len);
1450       sprintf (buf, "t%x:%x,%x", startaddr, data_long, mask_long);
1451       putpkt (buf);
1452       getpkt (buf, 0);
1453       if (buf[0] == '\0')
1454         {
1455           /* The stub doesn't support the 't' request.  We might want to
1456              remember this fact, but on the other hand the stub could be
1457              switched on us.  Maybe we should remember it only until
1458              the next "target remote".  */
1459           generic_search (len, data, mask, startaddr, increment, lorange,
1460                           hirange, addr_found, data_found);
1461           return;
1462         }
1463
1464       if (buf[0] == 'E')
1465         /* There is no correspondance between what the remote protocol uses
1466            for errors and errno codes.  We would like a cleaner way of
1467            representing errors (big enough to include errno codes, bfd_error
1468            codes, and others).  But for now just use EIO.  */
1469         memory_error (EIO, startaddr);
1470       p = buf;
1471       addr_we_found = 0;
1472       while (*p != '\0' && *p != ',')
1473         addr_we_found = (addr_we_found << 4) + fromhex (*p++);
1474       if (*p == '\0')
1475         error ("Protocol error: short return for search");
1476
1477       data_found_long = 0;
1478       while (*p != '\0' && *p != ',')
1479         data_found_long = (data_found_long << 4) + fromhex (*p++);
1480       /* Ignore anything after this comma, for future extensions.  */
1481
1482       if (addr_we_found < lorange || addr_we_found >= hirange)
1483         {
1484           *addr_found = 0;
1485           return;
1486         }
1487
1488       *addr_found = addr_we_found;
1489       *data_found = store_unsigned_integer (data_we_found, len);
1490       return;
1491     }
1492   generic_search (len, data, mask, startaddr, increment, lorange,
1493                   hirange, addr_found, data_found);
1494 }
1495 #endif /* 0 */
1496 \f
1497 static void
1498 remote_files_info (ignore)
1499      struct target_ops *ignore;
1500 {
1501   puts_filtered ("Debugging a target over a serial line.\n");
1502 }
1503 \f
1504 /* Stuff for dealing with the packets which are part of this protocol.
1505    See comment at top of file for details.  */
1506
1507 /* Read a single character from the remote end, masking it down to 7 bits. */
1508
1509 static int
1510 readchar (timeout)
1511      int timeout;
1512 {
1513   int ch;
1514
1515   ch = SERIAL_READCHAR (remote_desc, timeout);
1516
1517   switch (ch)
1518     {
1519     case SERIAL_EOF:
1520       error ("Remote connection closed");
1521     case SERIAL_ERROR:
1522       perror_with_name ("Remote communication error");
1523     case SERIAL_TIMEOUT:
1524       return ch;
1525     default:
1526       return ch & 0x7f;
1527     }
1528 }
1529
1530 /* Send the command in BUF to the remote machine,
1531    and read the reply into BUF.
1532    Report an error if we get an error reply.  */
1533
1534 static void
1535 remote_send (buf)
1536      char *buf;
1537 {
1538   putpkt (buf);
1539   getpkt (buf, 0);
1540
1541   if (buf[0] == 'E')
1542     error ("Remote failure reply: %s", buf);
1543 }
1544
1545 /* Send a packet to the remote machine, with error checking.
1546    The data of the packet is in BUF.  */
1547
1548 int
1549 putpkt (buf)
1550      char *buf;
1551 {
1552   int i;
1553   unsigned char csum = 0;
1554   char buf2[PBUFSIZ];
1555   int cnt = strlen (buf);
1556   int ch;
1557   int tcount = 0;
1558   char *p;
1559
1560   /* Copy the packet into buffer BUF2, encapsulating it
1561      and giving it a checksum.  */
1562
1563   if (cnt > (int) sizeof (buf2) - 5)            /* Prosanity check */
1564     abort();
1565
1566   p = buf2;
1567   *p++ = '$';
1568
1569   for (i = 0; i < cnt; i++)
1570     {
1571       csum += buf[i];
1572       *p++ = buf[i];
1573     }
1574   *p++ = '#';
1575   *p++ = tohex ((csum >> 4) & 0xf);
1576   *p++ = tohex (csum & 0xf);
1577
1578   /* Send it over and over until we get a positive ack.  */
1579
1580   while (1)
1581     {
1582       int started_error_output = 0;
1583
1584       if (remote_debug)
1585         {
1586           *p = '\0';
1587           printf_unfiltered ("Sending packet: %s...", buf2);
1588           gdb_flush(gdb_stdout);
1589         }
1590       if (SERIAL_WRITE (remote_desc, buf2, p - buf2))
1591         perror_with_name ("putpkt: write failed");
1592
1593       /* read until either a timeout occurs (-2) or '+' is read */
1594       while (1)
1595         {
1596           ch = readchar (remote_timeout);
1597
1598           if (remote_debug)
1599             {
1600               switch (ch)
1601                 {
1602                 case '+':
1603                 case SERIAL_TIMEOUT:
1604                 case '$':
1605                   if (started_error_output)
1606                     {
1607                       putchar_unfiltered ('\n');
1608                       started_error_output = 0;
1609                     }
1610                 }
1611             }
1612
1613           switch (ch)
1614             {
1615             case '+':
1616               if (remote_debug)
1617                 printf_unfiltered("Ack\n");
1618               return 1;
1619             case SERIAL_TIMEOUT:
1620               tcount ++;
1621               if (tcount > 3)
1622                 return 0;
1623               break;            /* Retransmit buffer */
1624             case '$':
1625               {
1626                 char junkbuf[PBUFSIZ];
1627
1628               /* It's probably an old response, and we're out of sync.  Just
1629                  gobble up the packet and ignore it.  */
1630                 getpkt (junkbuf, 0);
1631                 continue;               /* Now, go look for + */
1632               }
1633             default:
1634               if (remote_debug)
1635                 {
1636                   if (!started_error_output)
1637                     {
1638                       started_error_output = 1;
1639                       printf_unfiltered ("putpkt: Junk: ");
1640                     }
1641                   putchar_unfiltered (ch & 0177);
1642                 }
1643               continue;
1644             }
1645           break;                /* Here to retransmit */
1646         }
1647
1648 #if 0
1649       /* This is wrong.  If doing a long backtrace, the user should be
1650          able to get out next time we call QUIT, without anything as violent
1651          as interrupt_query.  If we want to provide a way out of here
1652          without getting to the next QUIT, it should be based on hitting
1653          ^C twice as in remote_wait.  */
1654       if (quit_flag)
1655         {
1656           quit_flag = 0;
1657           interrupt_query ();
1658         }
1659 #endif
1660     }
1661 }
1662
1663 /* Come here after finding the start of the frame.  Collect the rest into BUF,
1664    verifying the checksum, length, and handling run-length compression.
1665    Returns 0 on any error, 1 on success.  */
1666
1667 static int
1668 read_frame (buf)
1669      char *buf;
1670 {
1671   unsigned char csum;
1672   char *bp;
1673   int c;
1674
1675   csum = 0;
1676   bp = buf;
1677
1678   while (1)
1679     {
1680       c = readchar (remote_timeout);
1681
1682       switch (c)
1683         {
1684         case SERIAL_TIMEOUT:
1685           if (remote_debug)
1686             puts_filtered ("Timeout in mid-packet, retrying\n");
1687           return 0;
1688         case '$':
1689           if (remote_debug)
1690             puts_filtered ("Saw new packet start in middle of old one\n");
1691           return 0;             /* Start a new packet, count retries */
1692         case '#':
1693           {
1694             unsigned char pktcsum;
1695
1696             *bp = '\000';
1697
1698             pktcsum = fromhex (readchar (remote_timeout)) << 4;
1699             pktcsum |= fromhex (readchar (remote_timeout));
1700
1701             if (csum == pktcsum)
1702               return 1;
1703
1704             if (remote_debug) 
1705               {
1706                 printf_filtered ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=",
1707                                  pktcsum, csum);
1708                 puts_filtered (buf);
1709                 puts_filtered ("\n");
1710               }
1711             return 0;
1712           }
1713         case '*':               /* Run length encoding */
1714           csum += c;
1715           c = readchar (remote_timeout);
1716           csum += c;
1717           c = c - ' ' + 3;      /* Compute repeat count */
1718
1719
1720           if (c > 0 && c < 255 && bp + c - 1 < buf + PBUFSIZ - 1)
1721             {
1722               memset (bp, *(bp - 1), c);
1723               bp += c;
1724               continue;
1725             }
1726
1727           *bp = '\0';
1728           printf_filtered ("Repeat count %d too large for buffer: ", c);
1729           puts_filtered (buf);
1730           puts_filtered ("\n");
1731           return 0;
1732
1733         default:
1734           if (bp < buf + PBUFSIZ - 1)
1735             {
1736               *bp++ = c;
1737               csum += c;
1738               continue;
1739             }
1740
1741           *bp = '\0';
1742           puts_filtered ("Remote packet too long: ");
1743           puts_filtered (buf);
1744           puts_filtered ("\n");
1745
1746           return 0;
1747         }
1748     }
1749 }
1750
1751 /* Read a packet from the remote machine, with error checking,
1752    and store it in BUF.  BUF is expected to be of size PBUFSIZ.
1753    If FOREVER, wait forever rather than timing out; this is used
1754    while the target is executing user code.  */
1755
1756 void
1757 getpkt (buf, forever)
1758      char *buf;
1759      int forever;
1760 {
1761   int c;
1762   int tries;
1763   int timeout;
1764   int val;
1765
1766   strcpy (buf,"timeout");
1767
1768   if (forever)
1769     {
1770 #ifdef MAINTENANCE_CMDS
1771       timeout = watchdog > 0 ? watchdog : -1;
1772 #else
1773       timeout = -1;
1774 #endif
1775     }
1776
1777   else
1778     timeout = remote_timeout;
1779
1780 #define MAX_TRIES 3
1781
1782   for (tries = 1; tries <= MAX_TRIES; tries++)
1783     {
1784       /* This can loop forever if the remote side sends us characters
1785          continuously, but if it pauses, we'll get a zero from readchar
1786          because of timeout.  Then we'll count that as a retry.  */
1787
1788       /* Note that we will only wait forever prior to the start of a packet.
1789          After that, we expect characters to arrive at a brisk pace.  They
1790          should show up within remote_timeout intervals.  */
1791
1792       do
1793         {
1794           c = readchar (timeout);
1795
1796           if (c == SERIAL_TIMEOUT)
1797             {
1798 #ifdef MAINTENANCE_CMDS
1799               if (forever)      /* Watchdog went off.  Kill the target. */
1800                 {
1801                   target_mourn_inferior ();
1802                   error ("Watchdog has expired.  Target detached.\n");
1803                 }
1804 #endif
1805               if (remote_debug)
1806                 puts_filtered ("Timed out.\n");
1807               goto retry;
1808             }
1809         }
1810       while (c != '$');
1811
1812       /* We've found the start of a packet, now collect the data.  */
1813
1814       val = read_frame (buf);
1815
1816       if (val == 1)
1817         {
1818           if (remote_debug)
1819             fprintf_unfiltered (gdb_stdout, "Packet received: %s\n", buf);
1820           SERIAL_WRITE (remote_desc, "+", 1);
1821           return;
1822         }
1823
1824       /* Try the whole thing again.  */
1825     retry:
1826       SERIAL_WRITE (remote_desc, "-", 1);
1827     }
1828
1829   /* We have tried hard enough, and just can't receive the packet.  Give up. */
1830
1831   printf_unfiltered ("Ignoring packet error, continuing...\n");
1832   SERIAL_WRITE (remote_desc, "+", 1);
1833 }
1834 \f
1835 static void
1836 remote_kill ()
1837 {
1838   /* For some mysterious reason, wait_for_inferior calls kill instead of
1839      mourn after it gets TARGET_WAITKIND_SIGNALLED.  Work around it.  */
1840   if (kill_kludge)
1841     {
1842       kill_kludge = 0;
1843       target_mourn_inferior ();
1844       return;
1845     }
1846
1847   /* Use catch_errors so the user can quit from gdb even when we aren't on
1848      speaking terms with the remote system.  */
1849   catch_errors (putpkt, "k", "", RETURN_MASK_ERROR);
1850
1851   /* Don't wait for it to die.  I'm not really sure it matters whether
1852      we do or not.  For the existing stubs, kill is a noop.  */
1853   target_mourn_inferior ();
1854 }
1855
1856 static void
1857 remote_mourn ()
1858 {
1859   remote_mourn_1 (&remote_ops);
1860 }
1861
1862 static void
1863 extended_remote_mourn ()
1864 {
1865   /* We do _not_ want to mourn the target like this; this will
1866      remove the extended remote target  from the target stack,
1867      and the next time the user says "run" it'll fail. 
1868
1869      FIXME: What is the right thing to do here?  */
1870 #if 0
1871   remote_mourn_1 (&extended_remote_ops);
1872 #endif
1873 }
1874
1875 /* Worker function for remote_mourn.  */
1876 static void
1877 remote_mourn_1 (target)
1878      struct target_ops *target;
1879 {
1880   unpush_target (target);
1881   generic_mourn_inferior ();
1882 }
1883
1884 /* In the extended protocol we want to be able to do things like
1885    "run" and have them basically work as expected.  So we need
1886    a special create_inferior function. 
1887
1888    FIXME: One day add support for changing the exec file
1889    we're debugging, arguments and an environment.  */
1890
1891 static void
1892 extended_remote_create_inferior (exec_file, args, env)
1893      char *exec_file;
1894      char *args;
1895      char **env;
1896 {
1897   /* Rip out the breakpoints; we'll reinsert them after restarting
1898      the remote server.  */
1899   remove_breakpoints ();
1900
1901   /* Now restart the remote server.  */
1902   extended_remote_restart ();
1903
1904   /* Now put the breakpoints back in.  This way we're safe if the
1905      restart function works via a unix fork on the remote side.  */
1906   insert_breakpoints ();
1907
1908   /* Clean up from the last time we were running.  */
1909   clear_proceed_status ();
1910
1911   /* Let the remote process run.  */
1912   proceed (-1, TARGET_SIGNAL_0, 0);
1913 }
1914
1915 \f
1916 /* On some machines, e.g. 68k, we may use a different breakpoint instruction
1917    than other targets; in those use REMOTE_BREAKPOINT instead of just
1918    BREAKPOINT.  Also, bi-endian targets may define LITTLE_REMOTE_BREAKPOINT
1919    and BIG_REMOTE_BREAKPOINT.  If none of these are defined, we just call
1920    the standard routines that are in mem-break.c.  */
1921
1922 /* FIXME, these ought to be done in a more dynamic fashion.  For instance,
1923    the choice of breakpoint instruction affects target program design and
1924    vice versa, and by making it user-tweakable, the special code here
1925    goes away and we need fewer special GDB configurations.  */
1926
1927 #if defined (LITTLE_REMOTE_BREAKPOINT) && defined (BIG_REMOTE_BREAKPOINT) && !defined(REMOTE_BREAKPOINT)
1928 #define REMOTE_BREAKPOINT
1929 #endif
1930
1931 #ifdef REMOTE_BREAKPOINT
1932
1933 /* If the target isn't bi-endian, just pretend it is.  */
1934 #if !defined (LITTLE_REMOTE_BREAKPOINT) && !defined (BIG_REMOTE_BREAKPOINT)
1935 #define LITTLE_REMOTE_BREAKPOINT REMOTE_BREAKPOINT
1936 #define BIG_REMOTE_BREAKPOINT REMOTE_BREAKPOINT
1937 #endif
1938
1939 static unsigned char big_break_insn[] = BIG_REMOTE_BREAKPOINT;
1940 static unsigned char little_break_insn[] = LITTLE_REMOTE_BREAKPOINT;
1941
1942 #endif /* REMOTE_BREAKPOINT */
1943
1944 /* Insert a breakpoint on targets that don't have any better breakpoint
1945    support.  We read the contents of the target location and stash it,
1946    then overwrite it with a breakpoint instruction.  ADDR is the target
1947    location in the target machine.  CONTENTS_CACHE is a pointer to 
1948    memory allocated for saving the target contents.  It is guaranteed
1949    by the caller to be long enough to save sizeof BREAKPOINT bytes (this
1950    is accomplished via BREAKPOINT_MAX).  */
1951
1952 static int
1953 remote_insert_breakpoint (addr, contents_cache)
1954      CORE_ADDR addr;
1955      char *contents_cache;
1956 {
1957 #ifdef REMOTE_BREAKPOINT
1958   int val;
1959
1960   val = target_read_memory (addr, contents_cache, sizeof big_break_insn);
1961
1962   if (val == 0)
1963     {
1964       if (TARGET_BYTE_ORDER == BIG_ENDIAN)
1965         val = target_write_memory (addr, (char *) big_break_insn,
1966                                    sizeof big_break_insn);
1967       else
1968         val = target_write_memory (addr, (char *) little_break_insn,
1969                                    sizeof little_break_insn);
1970     }
1971
1972   return val;
1973 #else
1974   return memory_insert_breakpoint (addr, contents_cache);
1975 #endif /* REMOTE_BREAKPOINT */
1976 }
1977
1978 static int
1979 remote_remove_breakpoint (addr, contents_cache)
1980      CORE_ADDR addr;
1981      char *contents_cache;
1982 {
1983 #ifdef REMOTE_BREAKPOINT
1984   return target_write_memory (addr, contents_cache, sizeof big_break_insn);
1985 #else
1986   return memory_remove_breakpoint (addr, contents_cache);
1987 #endif /* REMOTE_BREAKPOINT */
1988 }
1989
1990 /* Some targets are only capable of doing downloads, and afterwards they switch
1991    to the remote serial protocol.  This function provides a clean way to get
1992    from the download target to the remote target.  It's basically just a
1993    wrapper so that we don't have to expose any of the internal workings of
1994    remote.c.
1995
1996    Prior to calling this routine, you should shutdown the current target code,
1997    else you will get the "A program is being debugged already..." message.
1998    Usually a call to pop_target() suffices.
1999 */
2000
2001 void
2002 push_remote_target (name, from_tty)
2003      char *name;
2004      int from_tty;
2005 {
2006   printf_filtered ("Switching to remote protocol\n");
2007   remote_open (name, from_tty);
2008 }
2009
2010 /* Other targets want to use the entire remote serial module but with
2011    certain remote_ops overridden. */
2012
2013 void
2014 open_remote_target (name, from_tty, target, extended_p)
2015      char *name;
2016      int from_tty;
2017      struct target_ops *target;
2018      int extended_p;
2019 {
2020   printf_filtered ("Selecting the %sremote protocol\n",
2021                    (extended_p ? "extended-" : ""));
2022   remote_open_1 (name, from_tty, target, extended_p);
2023 }
2024
2025 /* Remote target communications for serial-line targets in custom GDB protocol
2026    Copyright 1988, 1991, 1992, 1993, 1994, 1995, 1996, 1997 Free Software Foundation, Inc.
2027
2028 This file is part of GDB.
2029
2030 This program is free software; you can redistribute it and/or modify
2031 it under the terms of the GNU General Public License as published by
2032 the Free Software Foundation; either version 2 of the License, or
2033 (at your option) any later version.
2034
2035 This program is distributed in the hope that it will be useful,
2036 but WITHOUT ANY WARRANTY; without even the implied warranty of
2037 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
2038 GNU General Public License for more details.
2039
2040 You should have received a copy of the GNU General Public License
2041 along with this program; if not, write to the Free Software
2042 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
2043
2044 /* Remote communication protocol.
2045
2046    A debug packet whose contents are <data>
2047    is encapsulated for transmission in the form:
2048
2049         $ <data> # CSUM1 CSUM2
2050
2051         <data> must be ASCII alphanumeric and cannot include characters
2052         '$' or '#'.  If <data> starts with two characters followed by
2053         ':', then the existing stubs interpret this as a sequence number.
2054
2055         CSUM1 and CSUM2 are ascii hex representation of an 8-bit 
2056         checksum of <data>, the most significant nibble is sent first.
2057         the hex digits 0-9,a-f are used.
2058
2059    Receiver responds with:
2060
2061         +       - if CSUM is correct and ready for next packet
2062         -       - if CSUM is incorrect
2063
2064    <data> is as follows:
2065    Most values are encoded in ascii hex digits.  Signal numbers are according
2066    to the numbering in target.h.
2067
2068         Request         Packet
2069
2070         set thread      Hct...          Set thread for subsequent operations.
2071                                         c = 'c' for thread used in step and 
2072                                         continue; t... can be -1 for all
2073                                         threads.
2074                                         c = 'g' for thread used in other
2075                                         operations.  If zero, pick a thread,
2076                                         any thread.
2077         reply           OK              for success
2078                         ENN             for an error.
2079
2080         read registers  g
2081         reply           XX....X         Each byte of register data
2082                                         is described by two hex digits.
2083                                         Registers are in the internal order
2084                                         for GDB, and the bytes in a register
2085                                         are in the same order the machine uses.
2086                         or ENN          for an error.
2087
2088         write regs      GXX..XX         Each byte of register data
2089                                         is described by two hex digits.
2090         reply           OK              for success
2091                         ENN             for an error
2092
2093         write reg       Pn...=r...      Write register n... with value r...,
2094                                         which contains two hex digits for each
2095                                         byte in the register (target byte
2096                                         order).
2097         reply           OK              for success
2098                         ENN             for an error
2099         (not supported by all stubs).
2100
2101         read mem        mAA..AA,LLLL    AA..AA is address, LLLL is length.
2102         reply           XX..XX          XX..XX is mem contents
2103                                         Can be fewer bytes than requested
2104                                         if able to read only part of the data.
2105                         or ENN          NN is errno
2106
2107         write mem       MAA..AA,LLLL:XX..XX
2108                                         AA..AA is address,
2109                                         LLLL is number of bytes,
2110                                         XX..XX is data
2111         reply           OK              for success
2112                         ENN             for an error (this includes the case
2113                                         where only part of the data was
2114                                         written).
2115
2116         continue        cAA..AA         AA..AA is address to resume
2117                                         If AA..AA is omitted,
2118                                         resume at same address.
2119
2120         step            sAA..AA         AA..AA is address to resume
2121                                         If AA..AA is omitted,
2122                                         resume at same address.
2123
2124         continue with   Csig;AA..AA     Continue with signal sig (hex signal
2125         signal                          number).  If ;AA..AA is omitted, resume
2126                                         at same address.
2127
2128         step with       Ssig;AA..AA     Like 'C' but step not continue.
2129         signal
2130
2131         last signal     ?               Reply the current reason for stopping.
2132                                         This is the same reply as is generated
2133                                         for step or cont : SAA where AA is the
2134                                         signal number.
2135
2136         detach          D               Reply OK.
2137
2138         There is no immediate reply to step or cont.
2139         The reply comes when the machine stops.
2140         It is           SAA             AA is the signal number.
2141
2142         or...           TAAn...:r...;n...:r...;n...:r...;
2143                                         AA = signal number
2144                                         n... = register number (hex)
2145                                           r... = register contents
2146                                         n... = `thread'
2147                                           r... = thread process ID.  This is
2148                                                  a hex integer.
2149                                         n... = other string not starting 
2150                                             with valid hex digit.
2151                                           gdb should ignore this n,r pair
2152                                           and go on to the next.  This way
2153                                           we can extend the protocol.
2154         or...           WAA             The process exited, and AA is
2155                                         the exit status.  This is only
2156                                         applicable for certains sorts of
2157                                         targets.
2158         or...           XAA             The process terminated with signal
2159                                         AA.
2160         or...           OXX..XX XX..XX  is hex encoding of ASCII data. This
2161                                         can happen at any time while the program is
2162                                         running and the debugger should
2163                                         continue to wait for 'W', 'T', etc.
2164
2165         thread alive    TXX             Find out if the thread XX is alive.
2166         reply           OK              thread is still alive
2167                         ENN             thread is dead
2168         
2169         remote restart  RXX             Restart the remote server
2170
2171         extended ops    !               Use the extended remote protocol.
2172                                         Sticky -- only needs to be set once.
2173
2174         kill request    k
2175
2176         toggle debug    d               toggle debug flag (see 386 & 68k stubs)
2177         reset           r               reset -- see sparc stub.
2178         reserved        <other>         On other requests, the stub should
2179                                         ignore the request and send an empty
2180                                         response ($#<checksum>).  This way
2181                                         we can extend the protocol and GDB
2182                                         can tell whether the stub it is
2183                                         talking to uses the old or the new.
2184         search          tAA:PP,MM       Search backwards starting at address
2185                                         AA for a match with pattern PP and
2186                                         mask MM.  PP and MM are 4 bytes.
2187                                         Not supported by all stubs.
2188
2189         general query   qXXXX           Request info about XXXX.
2190         general set     QXXXX=yyyy      Set value of XXXX to yyyy.
2191         query sect offs qOffsets        Get section offsets.  Reply is
2192                                         Text=xxx;Data=yyy;Bss=zzz
2193
2194         Responses can be run-length encoded to save space.  A '*' means that
2195         the next character is an ASCII encoding giving a repeat count which
2196         stands for that many repititions of the character preceding the '*'.
2197         The encoding is n+29, yielding a printable character where n >=3 
2198         (which is where rle starts to win).  Don't use an n > 126.
2199
2200         So 
2201         "0* " means the same as "0000".  */
2202
2203 #include "defs.h"
2204 #include "gdb_string.h"
2205 #include <fcntl.h>
2206 #include "frame.h"
2207 #include "inferior.h"
2208 #include "bfd.h"
2209 #include "symfile.h"
2210 #include "target.h"
2211 #include "wait.h"
2212 /*#include "terminal.h"*/
2213 #include "gdbcmd.h"
2214 #include "objfiles.h"
2215 #include "gdb-stabs.h"
2216 #include "gdbthread.h"
2217
2218 #include "dcache.h"
2219
2220 #ifdef USG
2221 #include <sys/types.h>
2222 #endif
2223
2224 #include <signal.h>
2225 #include "serial.h"
2226
2227 /* Prototypes for local functions */
2228
2229 static int remote_write_bytes PARAMS ((CORE_ADDR memaddr,
2230                                        char *myaddr, int len));
2231
2232 static int remote_read_bytes PARAMS ((CORE_ADDR memaddr,
2233                                       char *myaddr, int len));
2234
2235 static void remote_files_info PARAMS ((struct target_ops *ignore));
2236
2237 static int remote_xfer_memory PARAMS ((CORE_ADDR memaddr, char *myaddr,
2238                                        int len, int should_write,
2239                                        struct target_ops *target));
2240
2241 static void remote_prepare_to_store PARAMS ((void));
2242
2243 static void remote_fetch_registers PARAMS ((int regno));
2244
2245 static void remote_resume PARAMS ((int pid, int step,
2246                                    enum target_signal siggnal));
2247
2248 static int remote_start_remote PARAMS ((char *dummy));
2249
2250 static void remote_open PARAMS ((char *name, int from_tty));
2251
2252 static void extended_remote_open PARAMS ((char *name, int from_tty));
2253
2254 static void remote_open_1 PARAMS ((char *, int, struct target_ops *, int extended_p));
2255
2256 static void remote_close PARAMS ((int quitting));
2257
2258 static void remote_store_registers PARAMS ((int regno));
2259
2260 static void remote_mourn PARAMS ((void));
2261
2262 static void extended_remote_restart PARAMS ((void));
2263
2264 static void extended_remote_mourn PARAMS ((void));
2265
2266 static void extended_remote_create_inferior PARAMS ((char *, char *, char **));
2267
2268 static void remote_mourn_1 PARAMS ((struct target_ops *));
2269
2270 static void remote_send PARAMS ((char *buf));
2271
2272 static int readchar PARAMS ((int timeout));
2273
2274 static int remote_wait PARAMS ((int pid, struct target_waitstatus *status));
2275
2276 static void remote_kill PARAMS ((void));
2277
2278 static int tohex PARAMS ((int nib));
2279
2280 static void remote_detach PARAMS ((char *args, int from_tty));
2281
2282 static void remote_interrupt PARAMS ((int signo));
2283
2284 static void remote_interrupt_twice PARAMS ((int signo));
2285
2286 static void interrupt_query PARAMS ((void));
2287
2288 static void set_thread PARAMS ((int, int));
2289
2290 static int remote_thread_alive PARAMS ((int));
2291
2292 static void get_offsets PARAMS ((void));
2293
2294 static int read_frame PARAMS ((char *));
2295
2296 static int remote_insert_breakpoint PARAMS ((CORE_ADDR, char *));
2297
2298 static int remote_remove_breakpoint PARAMS ((CORE_ADDR, char *));
2299
2300 static int hexnumlen PARAMS ((ULONGEST num));
2301
2302 /* exported functions */
2303
2304 extern int fromhex PARAMS ((int a));
2305 extern void getpkt PARAMS ((char *buf, int forever));
2306 extern int putpkt PARAMS ((char *buf));
2307
2308 /* Define the target subroutine names */
2309
2310 static struct target_ops remote_ops ;
2311
2312 static void init_remote_ops(void)
2313 {
2314   remote_ops.to_shortname =   "remote";         
2315   remote_ops.to_longname =   "Remote serial target in gdb-specific protocol";
2316   remote_ops.to_doc =   "Use a remote computer via a serial line; using a gdb-specific protocol.\n\
2317 Specify the serial device it is connected to (e.g. /dev/ttya)." ;  
2318   remote_ops.to_open =   remote_open;           
2319   remote_ops.to_close =   remote_close;         
2320   remote_ops.to_attach =   NULL;                
2321   remote_ops.to_detach =   remote_detach;       
2322   remote_ops.to_resume =   remote_resume;       
2323   remote_ops.to_wait  =   remote_wait;          
2324   remote_ops.to_fetch_registers  =   remote_fetch_registers;
2325   remote_ops.to_store_registers  =   remote_store_registers;
2326   remote_ops.to_prepare_to_store =   remote_prepare_to_store;
2327   remote_ops.to_xfer_memory  =   remote_xfer_memory;    
2328   remote_ops.to_files_info  =   remote_files_info;      
2329   remote_ops.to_insert_breakpoint =   remote_insert_breakpoint;
2330   remote_ops.to_remove_breakpoint =   remote_remove_breakpoint;
2331   remote_ops.to_terminal_init  =   NULL;                
2332   remote_ops.to_terminal_inferior =   NULL;             
2333   remote_ops.to_terminal_ours_for_output =   NULL;
2334   remote_ops.to_terminal_ours  =   NULL;        
2335   remote_ops.to_terminal_info  =   NULL;        
2336   remote_ops.to_kill  =   remote_kill;          
2337   remote_ops.to_load  =   generic_load;         
2338   remote_ops.to_lookup_symbol =   NULL;         
2339   remote_ops.to_create_inferior =   NULL;       
2340   remote_ops.to_mourn_inferior =   remote_mourn;
2341   remote_ops.to_can_run  =   0;                 
2342   remote_ops.to_notice_signals =   0;           
2343   remote_ops.to_thread_alive  =   remote_thread_alive;
2344   remote_ops.to_stop  =   0;            
2345   remote_ops.to_stratum =   process_stratum;
2346   remote_ops.DONT_USE =   NULL;         
2347   remote_ops.to_has_all_memory =   1;   
2348   remote_ops.to_has_memory =   1;       
2349   remote_ops.to_has_stack =   1;        
2350   remote_ops.to_has_registers =   1;    
2351   remote_ops.to_has_execution =   1;    
2352   remote_ops.to_sections =   NULL;      
2353   remote_ops.to_sections_end =   NULL;  
2354   remote_ops.to_magic =   OPS_MAGIC ;   
2355 } /* init_remote_ops */
2356
2357 static struct target_ops extended_remote_ops ;
2358
2359 static void init_extended_remote_ops(void) 
2360 {
2361   extended_remote_ops.to_shortname =   "extended-remote";       
2362   extended_remote_ops.to_longname =   "Extended remote serial target in gdb-specific protocol";
2363   extended_remote_ops.to_doc =   "Use a remote computer via a serial line; using a gdb-specific protocol.\n\
2364 Specify the serial device it is connected to (e.g. /dev/ttya).",
2365     extended_remote_ops.to_open =   extended_remote_open;       
2366   extended_remote_ops.to_close =   remote_close;        
2367   extended_remote_ops.to_attach =   NULL;               
2368   extended_remote_ops.to_detach =   remote_detach;      
2369   extended_remote_ops.to_resume =   remote_resume;      
2370   extended_remote_ops.to_wait  =   remote_wait;         
2371   extended_remote_ops.to_fetch_registers  =   remote_fetch_registers;
2372   extended_remote_ops.to_store_registers  =   remote_store_registers;   
2373   extended_remote_ops.to_prepare_to_store =   remote_prepare_to_store;
2374   extended_remote_ops.to_xfer_memory  =   remote_xfer_memory;   
2375   extended_remote_ops.to_files_info  =   remote_files_info;     
2376   extended_remote_ops.to_insert_breakpoint =   remote_insert_breakpoint;
2377   extended_remote_ops.to_remove_breakpoint =   remote_remove_breakpoint;
2378   extended_remote_ops.to_terminal_init  =   NULL;               
2379   extended_remote_ops.to_terminal_inferior =   NULL;            
2380   extended_remote_ops.to_terminal_ours_for_output =   NULL;
2381   extended_remote_ops.to_terminal_ours  =   NULL;       
2382   extended_remote_ops.to_terminal_info  =   NULL;       
2383   extended_remote_ops.to_kill  =   remote_kill;         
2384   extended_remote_ops.to_load  =   generic_load;        
2385   extended_remote_ops.to_lookup_symbol =   NULL;        
2386   extended_remote_ops.to_create_inferior =   extended_remote_create_inferior;
2387   extended_remote_ops.to_mourn_inferior =   extended_remote_mourn;
2388   extended_remote_ops.to_can_run  =   0;                        
2389   extended_remote_ops.to_notice_signals =   0;                  
2390   extended_remote_ops.to_thread_alive  =   remote_thread_alive;
2391   extended_remote_ops.to_stop  =   0;                   
2392   extended_remote_ops.to_stratum =   process_stratum;
2393   extended_remote_ops.DONT_USE =   NULL;        
2394   extended_remote_ops.to_has_all_memory =   1;  
2395   extended_remote_ops.to_has_memory =   1;      
2396   extended_remote_ops.to_has_stack =   1;       
2397   extended_remote_ops.to_has_registers =   1;   
2398   extended_remote_ops.to_has_execution =   1;   
2399   extended_remote_ops.to_sections =   NULL;     
2400   extended_remote_ops.to_sections_end =   NULL;
2401   extended_remote_ops.to_magic =   OPS_MAGIC ;
2402
2403
2404
2405 /* This was 5 seconds, which is a long time to sit and wait.
2406    Unless this is going though some terminal server or multiplexer or
2407    other form of hairy serial connection, I would think 2 seconds would
2408    be plenty.  */
2409
2410 /* Changed to allow option to set timeout value.
2411    was static int remote_timeout = 2; */
2412 extern int remote_timeout;
2413
2414 /* This variable chooses whether to send a ^C or a break when the user
2415    requests program interruption.  Although ^C is usually what remote
2416    systems expect, and that is the default here, sometimes a break is
2417    preferable instead.  */
2418
2419 static int remote_break;
2420
2421 /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
2422    remote_open knows that we don't have a file open when the program
2423    starts.  */
2424 static serial_t remote_desc = NULL;
2425
2426 /* Having this larger than 400 causes us to be incompatible with m68k-stub.c
2427    and i386-stub.c.  Normally, no one would notice because it only matters
2428    for writing large chunks of memory (e.g. in downloads).  Also, this needs
2429    to be more than 400 if required to hold the registers (see below, where
2430    we round it up based on REGISTER_BYTES).  */
2431 #define PBUFSIZ 400
2432
2433 /* Maximum number of bytes to read/write at once.  The value here
2434    is chosen to fill up a packet (the headers account for the 32).  */
2435 #define MAXBUFBYTES ((PBUFSIZ-32)/2)
2436
2437 /* Round up PBUFSIZ to hold all the registers, at least.  */
2438 /* The blank line after the #if seems to be required to work around a
2439    bug in HP's PA compiler.  */
2440 #if REGISTER_BYTES > MAXBUFBYTES
2441
2442 #undef PBUFSIZ
2443 #define PBUFSIZ (REGISTER_BYTES * 2 + 32)
2444 #endif
2445
2446 /* This variable sets the number of bytes to be written to the target
2447    in a single packet.  Normally PBUFSIZ is satisfactory, but some
2448    targets need smaller values (perhaps because the receiving end
2449    is slow).  */
2450
2451 static int remote_write_size = PBUFSIZ;
2452
2453 /* This is the size (in chars) of the first response to the `g' command.  This
2454    is used to limit the size of the memory read and write commands to prevent
2455    stub buffers from overflowing.  The size does not include headers and
2456    trailers, it is only the payload size. */
2457
2458 static int remote_register_buf_size = 0;
2459
2460 /* Should we try the 'P' request?  If this is set to one when the stub
2461    doesn't support 'P', the only consequence is some unnecessary traffic.  */
2462 static int stub_supports_P = 1;
2463
2464 /* These are pointers to hook functions that may be set in order to
2465    modify resume/wait behavior for a particular architecture.  */
2466
2467 void (*target_resume_hook) PARAMS ((void));
2468 void (*target_wait_loop_hook) PARAMS ((void));
2469
2470 \f
2471 /* These are the threads which we last sent to the remote system.  -1 for all
2472    or -2 for not sent yet.  */
2473 int general_thread;
2474 int cont_thread;
2475
2476 static void
2477 set_thread (th, gen)
2478      int th;
2479      int gen;
2480 {
2481   char buf[PBUFSIZ];
2482   int state = gen ? general_thread : cont_thread;
2483   if (state == th)
2484     return;
2485   buf[0] = 'H';
2486   buf[1] = gen ? 'g' : 'c';
2487   if (th == 42000)
2488     {
2489       buf[2] = '0';
2490       buf[3] = '\0';
2491     }
2492   else if (th < 0)
2493     sprintf (&buf[2], "-%x", -th);
2494   else
2495     sprintf (&buf[2], "%x", th);
2496   putpkt (buf);
2497   getpkt (buf, 0);
2498   if (gen)
2499     general_thread = th;
2500   else
2501     cont_thread = th;
2502 }
2503 \f
2504 /*  Return nonzero if the thread TH is still alive on the remote system.  */
2505
2506 static int
2507 remote_thread_alive (th)
2508      int th;
2509 {
2510   char buf[PBUFSIZ];
2511
2512   buf[0] = 'T';
2513   if (th < 0)
2514     sprintf (&buf[1], "-%x", -th);
2515   else
2516     sprintf (&buf[1], "%x", th);
2517   putpkt (buf);
2518   getpkt (buf, 0);
2519   return (buf[0] == 'O' && buf[1] == 'K');
2520 }
2521
2522 /*  Restart the remote side; this is an extended protocol operation.  */
2523
2524 static void
2525 extended_remote_restart ()
2526 {
2527   char buf[PBUFSIZ];
2528
2529   /* Send the restart command; for reasons I don't understand the
2530      remote side really expects a number after the "R".  */
2531   buf[0] = 'R';
2532   sprintf (&buf[1], "%x", 0);
2533   putpkt (buf);
2534
2535   /* Now query for status so this looks just like we restarted
2536      gdbserver from scratch.  */
2537   putpkt ("?");
2538   getpkt (buf, 0);
2539 }
2540 \f
2541 /* Clean up connection to a remote debugger.  */
2542
2543 /* ARGSUSED */
2544 static void
2545 remote_close (quitting)
2546      int quitting;
2547 {
2548   if (remote_desc)
2549     SERIAL_CLOSE (remote_desc);
2550   remote_desc = NULL;
2551 }
2552
2553 /* Query the remote side for the text, data and bss offsets. */
2554
2555 static void
2556 get_offsets ()
2557 {
2558   char buf[PBUFSIZ], *ptr;
2559   int lose;
2560   CORE_ADDR text_addr, data_addr, bss_addr;
2561   struct section_offsets *offs;
2562
2563   putpkt ("qOffsets");
2564
2565   getpkt (buf, 0);
2566
2567   if (buf[0] == '\000')
2568     return;                     /* Return silently.  Stub doesn't support this
2569                                    command. */
2570   if (buf[0] == 'E')
2571     {
2572       warning ("Remote failure reply: %s", buf);
2573       return;
2574     }
2575
2576   /* Pick up each field in turn.  This used to be done with scanf, but
2577      scanf will make trouble if CORE_ADDR size doesn't match
2578      conversion directives correctly.  The following code will work
2579      with any size of CORE_ADDR.  */
2580   text_addr = data_addr = bss_addr = 0;
2581   ptr = buf;
2582   lose = 0;
2583
2584   if (strncmp (ptr, "Text=", 5) == 0)
2585     {
2586       ptr += 5;
2587       /* Don't use strtol, could lose on big values.  */
2588       while (*ptr && *ptr != ';')
2589         text_addr = (text_addr << 4) + fromhex (*ptr++);
2590     }
2591   else
2592     lose = 1;
2593
2594   if (!lose && strncmp (ptr, ";Data=", 6) == 0)
2595     {
2596       ptr += 6;
2597       while (*ptr && *ptr != ';')
2598         data_addr = (data_addr << 4) + fromhex (*ptr++);
2599     }
2600   else
2601     lose = 1;
2602
2603   if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
2604     {
2605       ptr += 5;
2606       while (*ptr && *ptr != ';')
2607         bss_addr = (bss_addr << 4) + fromhex (*ptr++);
2608     }
2609   else
2610     lose = 1;
2611
2612   if (lose)
2613     error ("Malformed response to offset query, %s", buf);
2614
2615   if (symfile_objfile == NULL)
2616     return;
2617
2618   offs = (struct section_offsets *) alloca (sizeof (struct section_offsets)
2619                                             + symfile_objfile->num_sections
2620                                             * sizeof (offs->offsets));
2621   memcpy (offs, symfile_objfile->section_offsets,
2622           sizeof (struct section_offsets)
2623           + symfile_objfile->num_sections
2624           * sizeof (offs->offsets));
2625
2626   ANOFFSET (offs, SECT_OFF_TEXT) = text_addr;
2627
2628   /* This is a temporary kludge to force data and bss to use the same offsets
2629      because that's what nlmconv does now.  The real solution requires changes
2630      to the stub and remote.c that I don't have time to do right now.  */
2631
2632   ANOFFSET (offs, SECT_OFF_DATA) = data_addr;
2633   ANOFFSET (offs, SECT_OFF_BSS) = data_addr;
2634
2635   objfile_relocate (symfile_objfile, offs);
2636 }
2637
2638 /* Stub for catch_errors.  */
2639
2640 static int
2641 remote_start_remote (dummy)
2642      char *dummy;
2643 {
2644   immediate_quit = 1;           /* Allow user to interrupt it */
2645
2646   /* Ack any packet which the remote side has already sent.  */
2647   SERIAL_WRITE (remote_desc, "+", 1);
2648
2649   /* Let the stub know that we want it to return the thread.  */
2650   set_thread (-1, 0);
2651
2652   get_offsets ();               /* Get text, data & bss offsets */
2653
2654   putpkt ("?");                 /* initiate a query from remote machine */
2655   immediate_quit = 0;
2656
2657   start_remote ();              /* Initialize gdb process mechanisms */
2658   return 1;
2659 }
2660
2661 /* Open a connection to a remote debugger.
2662    NAME is the filename used for communication.  */
2663
2664 static void
2665 remote_open (name, from_tty)
2666      char *name;
2667      int from_tty;
2668 {
2669   remote_open_1 (name, from_tty, &remote_ops, 0);
2670 }
2671
2672 /* Open a connection to a remote debugger using the extended
2673    remote gdb protocol.  NAME is the filename used for communication.  */
2674
2675 static void
2676 extended_remote_open (name, from_tty)
2677      char *name;
2678      int from_tty;
2679 {
2680   remote_open_1 (name, from_tty, &extended_remote_ops, 1/*extended_p*/);
2681 }
2682
2683 /* Generic code for opening a connection to a remote target.  */
2684 static DCACHE *remote_dcache;
2685
2686 static void
2687 remote_open_1 (name, from_tty, target, extended_p)
2688      char *name;
2689      int from_tty;
2690      struct target_ops *target;
2691      int extended_p;
2692 {
2693   if (name == 0)
2694     error ("To open a remote debug connection, you need to specify what serial\n\
2695 device is attached to the remote system (e.g. /dev/ttya).");
2696
2697   target_preopen (from_tty);
2698
2699   unpush_target (target);
2700
2701   remote_dcache = dcache_init (remote_read_bytes, remote_write_bytes);
2702
2703   remote_desc = SERIAL_OPEN (name);
2704   if (!remote_desc)
2705     perror_with_name (name);
2706
2707   if (baud_rate != -1)
2708     {
2709       if (SERIAL_SETBAUDRATE (remote_desc, baud_rate))
2710         {
2711           SERIAL_CLOSE (remote_desc);
2712           perror_with_name (name);
2713         }
2714     }
2715
2716
2717   SERIAL_RAW (remote_desc);
2718
2719   /* If there is something sitting in the buffer we might take it as a
2720      response to a command, which would be bad.  */
2721   SERIAL_FLUSH_INPUT (remote_desc);
2722
2723   if (from_tty)
2724     {
2725       puts_filtered ("Remote debugging using ");
2726       puts_filtered (name);
2727       puts_filtered ("\n");
2728     }
2729   push_target (target); /* Switch to using remote target now */
2730
2731   /* Start out by trying the 'P' request to set registers.  We set this each
2732      time that we open a new target so that if the user switches from one
2733      stub to another, we can (if the target is closed and reopened) cope.  */
2734   stub_supports_P = 1;
2735
2736   general_thread = -2;
2737   cont_thread = -2;
2738
2739   /* Without this, some commands which require an active target (such as kill)
2740      won't work.  This variable serves (at least) double duty as both the pid
2741      of the target process (if it has such), and as a flag indicating that a
2742      target is active.  These functions should be split out into seperate
2743      variables, especially since GDB will someday have a notion of debugging
2744      several processes.  */
2745
2746   inferior_pid = 42000;
2747   /* Start the remote connection; if error (0), discard this target.
2748      In particular, if the user quits, be sure to discard it
2749      (we'd be in an inconsistent state otherwise).  */
2750   if (!catch_errors (remote_start_remote, (char *)0, 
2751                      "Couldn't establish connection to remote target\n", RETURN_MASK_ALL))
2752     {
2753       pop_target();
2754       return;
2755     }
2756
2757   if (extended_p)
2758     {
2759       /* tell the remote that we're using the extended protocol.  */
2760       char buf[PBUFSIZ];
2761       putpkt ("!");
2762       getpkt (buf, 0);
2763     }
2764 }
2765
2766 /* This takes a program previously attached to and detaches it.  After
2767    this is done, GDB can be used to debug some other program.  We
2768    better not have left any breakpoints in the target program or it'll
2769    die when it hits one.  */
2770
2771 static void
2772 remote_detach (args, from_tty)
2773      char *args;
2774      int from_tty;
2775 {
2776   char buf[PBUFSIZ];
2777
2778   if (args)
2779     error ("Argument given to \"detach\" when remotely debugging.");
2780
2781   /* Tell the remote target to detach.  */
2782   strcpy (buf, "D");
2783   remote_send (buf);
2784
2785   pop_target ();
2786   if (from_tty)
2787     puts_filtered ("Ending remote debugging.\n");
2788 }
2789
2790 /* Convert hex digit A to a number.  */
2791
2792 int
2793 fromhex (a)
2794      int a;
2795 {
2796   if (a >= '0' && a <= '9')
2797     return a - '0';
2798   else if (a >= 'a' && a <= 'f')
2799     return a - 'a' + 10;
2800   else if (a >= 'A' && a <= 'F')
2801     return a - 'A' + 10;
2802   else 
2803     error ("Reply contains invalid hex digit %d", a);
2804 }
2805
2806 /* Convert number NIB to a hex digit.  */
2807
2808 static int
2809 tohex (nib)
2810      int nib;
2811 {
2812   if (nib < 10)
2813     return '0'+nib;
2814   else
2815     return 'a'+nib-10;
2816 }
2817 \f
2818 /* Tell the remote machine to resume.  */
2819
2820 static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
2821 int last_sent_step;
2822
2823 static void
2824 remote_resume (pid, step, siggnal)
2825      int pid, step;
2826      enum target_signal siggnal;
2827 {
2828   char buf[PBUFSIZ];
2829
2830   if (pid == -1)
2831     set_thread (inferior_pid, 0);
2832   else
2833     set_thread (pid, 0);
2834
2835   dcache_flush (remote_dcache);
2836
2837   last_sent_signal = siggnal;
2838   last_sent_step = step;
2839
2840   /* A hook for when we need to do something at the last moment before
2841      resumption.  */
2842   if (target_resume_hook)
2843     (*target_resume_hook) ();
2844
2845   if (siggnal != TARGET_SIGNAL_0)
2846     {
2847       buf[0] = step ? 'S' : 'C';
2848       buf[1] = tohex (((int)siggnal >> 4) & 0xf);
2849       buf[2] = tohex ((int)siggnal & 0xf);
2850       buf[3] = '\0';
2851     }
2852   else
2853     strcpy (buf, step ? "s": "c");
2854
2855   putpkt (buf);
2856 }
2857 \f
2858 /* Send ^C to target to halt it.  Target will respond, and send us a
2859    packet.  */
2860
2861 static void
2862 remote_interrupt (signo)
2863      int signo;
2864 {
2865   /* If this doesn't work, try more severe steps.  */
2866   signal (signo, remote_interrupt_twice);
2867   
2868   if (remote_debug)
2869     printf_unfiltered ("remote_interrupt called\n");
2870
2871   /* Send a break or a ^C, depending on user preference.  */
2872   if (remote_break)
2873     SERIAL_SEND_BREAK (remote_desc);
2874   else
2875     SERIAL_WRITE (remote_desc, "\003", 1);
2876 }
2877
2878 static void (*ofunc)();
2879
2880 /* The user typed ^C twice.  */
2881 static void
2882 remote_interrupt_twice (signo)
2883      int signo;
2884 {
2885   signal (signo, ofunc);
2886   
2887   interrupt_query ();
2888
2889   signal (signo, remote_interrupt);
2890 }
2891
2892 /* Ask the user what to do when an interrupt is received.  */
2893
2894 static void
2895 interrupt_query ()
2896 {
2897   target_terminal_ours ();
2898
2899   if (query ("Interrupted while waiting for the program.\n\
2900 Give up (and stop debugging it)? "))
2901     {
2902       target_mourn_inferior ();
2903       return_to_top_level (RETURN_QUIT);
2904     }
2905
2906   target_terminal_inferior ();
2907 }
2908
2909 /* If nonzero, ignore the next kill.  */
2910 int kill_kludge;
2911
2912 void
2913 remote_console_output (msg)
2914      char *msg;
2915 {
2916   char *p;
2917
2918   for (p = msg; *p; p +=2) 
2919     {
2920       char tb[2];
2921       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
2922       tb[0] = c;
2923       tb[1] = 0;
2924       if (target_output_hook)
2925         target_output_hook (tb);
2926       else 
2927         fputs_filtered (tb, gdb_stdout);
2928     }
2929 }
2930
2931 /* Wait until the remote machine stops, then return,
2932    storing status in STATUS just as `wait' would.
2933    Returns "pid" (though it's not clear what, if anything, that
2934    means in the case of this target).  */
2935
2936 static int
2937 remote_wait (pid, status)
2938      int pid;
2939      struct target_waitstatus *status;
2940 {
2941   unsigned char buf[PBUFSIZ];
2942   int thread_num = -1;
2943
2944   status->kind = TARGET_WAITKIND_EXITED;
2945   status->value.integer = 0;
2946
2947   while (1)
2948     {
2949       unsigned char *p;
2950
2951       ofunc = (void (*)()) signal (SIGINT, remote_interrupt);
2952       getpkt ((char *) buf, 1);
2953       signal (SIGINT, ofunc);
2954
2955       /* This is a hook for when we need to do something (perhaps the
2956          collection of trace data) every time the target stops.  */
2957       if (target_wait_loop_hook)
2958         (*target_wait_loop_hook) ();
2959
2960       switch (buf[0])
2961         {
2962         case 'E':               /* Error of some sort */
2963           warning ("Remote failure reply: %s", buf);
2964           continue;
2965         case 'T':               /* Status with PC, SP, FP, ... */
2966           {
2967             int i;
2968             long regno;
2969             char regs[MAX_REGISTER_RAW_SIZE];
2970
2971             /* Expedited reply, containing Signal, {regno, reg} repeat */
2972             /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
2973                 ss = signal number
2974                 n... = register number
2975                 r... = register contents
2976                 */
2977             p = &buf[3];        /* after Txx */
2978
2979             while (*p)
2980               {
2981                 unsigned char *p1;
2982                 char *p_temp;
2983
2984                 regno = strtol ((const char *) p, &p_temp, 16); /* Read the register number */
2985                 p1 = (unsigned char *)p_temp;
2986
2987                 if (p1 == p)
2988                   {
2989                     p1 = (unsigned char *) strchr ((const char *) p, ':');
2990                     if (p1 == NULL)
2991                       warning ("Malformed packet (missing colon): %s\n\
2992 Packet: '%s'\n",
2993                                p, buf);
2994                     if (strncmp ((const char *) p, "thread", p1 - p) == 0)
2995                       {
2996                         thread_num = strtol ((const char *) ++p1, &p_temp, 16);
2997                         p = (unsigned char *)p_temp;
2998                       }
2999                   }
3000                 else
3001                   {
3002                     p = p1;
3003
3004                     if (*p++ != ':')
3005                       warning ("Malformed packet (missing colon): %s\n\
3006 Packet: '%s'\n",
3007                                p, buf);
3008
3009                     if (regno >= NUM_REGS)
3010                       warning ("Remote sent bad register number %ld: %s\n\
3011 Packet: '%s'\n",
3012                                regno, p, buf);
3013
3014                     for (i = 0; i < REGISTER_RAW_SIZE (regno); i++)
3015                       {
3016                         if (p[0] == 0 || p[1] == 0)
3017                           warning ("Remote reply is too short: %s", buf);
3018                         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
3019                         p += 2;
3020                       }
3021                     supply_register (regno, regs);
3022                   }
3023
3024                 if (*p++ != ';')
3025                   warning ("Remote register badly formatted: %s", buf);
3026               }
3027           }
3028           /* fall through */
3029         case 'S':               /* Old style status, just signal only */
3030           status->kind = TARGET_WAITKIND_STOPPED;
3031           status->value.sig = (enum target_signal)
3032             (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3033
3034           goto got_status;
3035         case 'W':               /* Target exited */
3036           {
3037             /* The remote process exited.  */
3038             status->kind = TARGET_WAITKIND_EXITED;
3039             status->value.integer = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
3040             goto got_status;
3041           }
3042         case 'X':
3043           status->kind = TARGET_WAITKIND_SIGNALLED;
3044           status->value.sig = (enum target_signal)
3045             (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3046           kill_kludge = 1;
3047
3048           goto got_status;
3049         case 'O':               /* Console output */
3050           remote_console_output (buf + 1);
3051           continue;
3052         case '\0':
3053           if (last_sent_signal != TARGET_SIGNAL_0)
3054             {
3055               /* Zero length reply means that we tried 'S' or 'C' and
3056                  the remote system doesn't support it.  */
3057               target_terminal_ours_for_output ();
3058               printf_filtered
3059                 ("Can't send signals to this remote system.  %s not sent.\n",
3060                  target_signal_to_name (last_sent_signal));
3061               last_sent_signal = TARGET_SIGNAL_0;
3062               target_terminal_inferior ();
3063
3064               strcpy ((char *) buf, last_sent_step ? "s" : "c");
3065               putpkt ((char *) buf);
3066               continue;
3067             }
3068           /* else fallthrough */
3069         default:
3070           warning ("Invalid remote reply: %s", buf);
3071           continue;
3072         }
3073     }
3074  got_status:
3075   if (thread_num != -1)
3076     {
3077       /* Initial thread value can only be acquired via wait, so deal with
3078          this marker which is used before the first thread value is
3079          acquired.  */
3080       if (inferior_pid == 42000)
3081         {
3082           inferior_pid = thread_num;
3083           add_thread (inferior_pid);
3084         }
3085       return thread_num;
3086     }
3087   return inferior_pid;
3088 }
3089
3090 /* Number of bytes of registers this stub implements.  */
3091 static int register_bytes_found;
3092
3093 /* Read the remote registers into the block REGS.  */
3094 /* Currently we just read all the registers, so we don't use regno.  */
3095 /* ARGSUSED */
3096 static void
3097 remote_fetch_registers (regno)
3098      int regno;
3099 {
3100   char buf[PBUFSIZ];
3101   int i;
3102   char *p;
3103   char regs[REGISTER_BYTES];
3104
3105   set_thread (inferior_pid, 1);
3106
3107   sprintf (buf, "g");
3108   remote_send (buf);
3109
3110   if (remote_register_buf_size == 0)
3111     remote_register_buf_size = strlen (buf);
3112
3113   /* Unimplemented registers read as all bits zero.  */
3114   memset (regs, 0, REGISTER_BYTES);
3115
3116   /* We can get out of synch in various cases.  If the first character
3117      in the buffer is not a hex character, assume that has happened
3118      and try to fetch another packet to read.  */
3119   while ((buf[0] < '0' || buf[0] > '9')
3120          && (buf[0] < 'a' || buf[0] > 'f'))
3121     {
3122       if (remote_debug)
3123         printf_unfiltered ("Bad register packet; fetching a new packet\n");
3124       getpkt (buf, 0);
3125     }
3126
3127   /* Reply describes registers byte by byte, each byte encoded as two
3128      hex characters.  Suck them all up, then supply them to the
3129      register cacheing/storage mechanism.  */
3130
3131   p = buf;
3132   for (i = 0; i < REGISTER_BYTES; i++)
3133     {
3134       if (p[0] == 0)
3135         break;
3136       if (p[1] == 0)
3137         {
3138           warning ("Remote reply is of odd length: %s", buf);
3139           /* Don't change register_bytes_found in this case, and don't
3140              print a second warning.  */
3141           goto supply_them;
3142         }
3143       regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
3144       p += 2;
3145     }
3146
3147   if (i != register_bytes_found)
3148     {
3149       register_bytes_found = i;
3150 #ifdef REGISTER_BYTES_OK
3151       if (!REGISTER_BYTES_OK (i))
3152         warning ("Remote reply is too short: %s", buf);
3153 #endif
3154     }
3155
3156  supply_them:
3157   for (i = 0; i < NUM_REGS; i++)
3158     supply_register (i, &regs[REGISTER_BYTE(i)]);
3159 }
3160
3161 /* Prepare to store registers.  Since we may send them all (using a
3162    'G' request), we have to read out the ones we don't want to change
3163    first.  */
3164
3165 static void 
3166 remote_prepare_to_store ()
3167 {
3168   /* Make sure the entire registers array is valid.  */
3169   read_register_bytes (0, (char *)NULL, REGISTER_BYTES);
3170 }
3171
3172 /* Store register REGNO, or all registers if REGNO == -1, from the contents
3173    of REGISTERS.  FIXME: ignores errors.  */
3174
3175 static void
3176 remote_store_registers (regno)
3177      int regno;
3178 {
3179   char buf[PBUFSIZ];
3180   int i;
3181   char *p;
3182
3183   set_thread (inferior_pid, 1);
3184
3185   if (regno >= 0 && stub_supports_P)
3186     {
3187       /* Try storing a single register.  */
3188       char *regp;
3189
3190       sprintf (buf, "P%x=", regno);
3191       p = buf + strlen (buf);
3192       regp = &registers[REGISTER_BYTE (regno)];
3193       for (i = 0; i < REGISTER_RAW_SIZE (regno); ++i)
3194         {
3195           *p++ = tohex ((regp[i] >> 4) & 0xf);
3196           *p++ = tohex (regp[i] & 0xf);
3197         }
3198       *p = '\0';
3199       remote_send (buf);
3200       if (buf[0] != '\0')
3201         {
3202           /* The stub understands the 'P' request.  We are done.  */
3203           return;
3204         }
3205
3206       /* The stub does not support the 'P' request.  Use 'G' instead,
3207          and don't try using 'P' in the future (it will just waste our
3208          time).  */
3209       stub_supports_P = 0;
3210     }
3211
3212   buf[0] = 'G';
3213
3214   /* Command describes registers byte by byte,
3215      each byte encoded as two hex characters.  */
3216
3217   p = buf + 1;
3218   /* remote_prepare_to_store insures that register_bytes_found gets set.  */
3219   for (i = 0; i < register_bytes_found; i++)
3220     {
3221       *p++ = tohex ((registers[i] >> 4) & 0xf);
3222       *p++ = tohex (registers[i] & 0xf);
3223     }
3224   *p = '\0';
3225
3226   remote_send (buf);
3227 }
3228
3229 /* 
3230    Use of the data cache *used* to be disabled because it loses for looking at
3231    and changing hardware I/O ports and the like.  Accepting `volatile'
3232    would perhaps be one way to fix it.  Another idea would be to use the
3233    executable file for the text segment (for all SEC_CODE sections?
3234    For all SEC_READONLY sections?).  This has problems if you want to
3235    actually see what the memory contains (e.g. self-modifying code,
3236    clobbered memory, user downloaded the wrong thing).  
3237
3238    Because it speeds so much up, it's now enabled, if you're playing
3239    with registers you turn it of (set remotecache 0)
3240 */
3241
3242 /* Read a word from remote address ADDR and return it.
3243    This goes through the data cache.  */
3244
3245 #if 0   /* unused? */
3246 static int
3247 remote_fetch_word (addr)
3248      CORE_ADDR addr;
3249 {
3250   return dcache_fetch (remote_dcache, addr);
3251 }
3252
3253 /* Write a word WORD into remote address ADDR.
3254    This goes through the data cache.  */
3255
3256 static void
3257 remote_store_word (addr, word)
3258      CORE_ADDR addr;
3259      int word;
3260 {
3261   dcache_poke (remote_dcache, addr, word);
3262 }
3263 #endif  /* 0 (unused?) */
3264
3265 \f
3266
3267 /* Return the number of hex digits in num.  */
3268
3269 static int
3270 hexnumlen (num)
3271      ULONGEST num;
3272 {
3273   int i;
3274
3275   for (i = 0; num != 0; i++)
3276     num >>= 4;
3277
3278   return max (i, 1);
3279 }
3280
3281 /* Write memory data directly to the remote machine.
3282    This does not inform the data cache; the data cache uses this.
3283    MEMADDR is the address in the remote memory space.
3284    MYADDR is the address of the buffer in our space.
3285    LEN is the number of bytes.
3286
3287    Returns number of bytes transferred, or 0 for error.  */
3288
3289 static int
3290 remote_write_bytes (memaddr, myaddr, len)
3291      CORE_ADDR memaddr;
3292      char *myaddr;
3293      int len;
3294 {
3295   int max_buf_size;             /* Max size of packet output buffer */
3296   int origlen;
3297
3298   /* Chop the transfer down if necessary */
3299
3300   max_buf_size = min (remote_write_size, PBUFSIZ);
3301   if (remote_register_buf_size != 0)
3302     max_buf_size = min (max_buf_size, remote_register_buf_size);
3303
3304   /* Subtract header overhead from max payload size -  $M<memaddr>,<len>:#nn */
3305   max_buf_size -= 2 + hexnumlen (memaddr + len - 1) + 1 + hexnumlen (len) + 4;
3306
3307   origlen = len;
3308   while (len > 0)
3309     {
3310       char buf[PBUFSIZ];
3311       char *p;
3312       int todo;
3313       int i;
3314
3315       todo = min (len, max_buf_size / 2); /* num bytes that will fit */
3316
3317       /* FIXME-32x64: Need a version of print_address_numeric which puts the
3318          result in a buffer like sprintf.  */
3319       sprintf (buf, "M%lx,%x:", (unsigned long) memaddr, todo);
3320
3321       /* We send target system values byte by byte, in increasing byte addresses,
3322          each byte encoded as two hex characters.  */
3323
3324       p = buf + strlen (buf);
3325       for (i = 0; i < todo; i++)
3326         {
3327           *p++ = tohex ((myaddr[i] >> 4) & 0xf);
3328           *p++ = tohex (myaddr[i] & 0xf);
3329         }
3330       *p = '\0';
3331
3332       putpkt (buf);
3333       getpkt (buf, 0);
3334
3335       if (buf[0] == 'E')
3336         {
3337           /* There is no correspondance between what the remote protocol uses
3338              for errors and errno codes.  We would like a cleaner way of
3339              representing errors (big enough to include errno codes, bfd_error
3340              codes, and others).  But for now just return EIO.  */
3341           errno = EIO;
3342           return 0;
3343         }
3344       myaddr += todo;
3345       memaddr += todo;
3346       len -= todo;
3347     }
3348   return origlen;
3349 }
3350
3351 /* Read memory data directly from the remote machine.
3352    This does not use the data cache; the data cache uses this.
3353    MEMADDR is the address in the remote memory space.
3354    MYADDR is the address of the buffer in our space.
3355    LEN is the number of bytes.
3356
3357    Returns number of bytes transferred, or 0 for error.  */
3358
3359 static int
3360 remote_read_bytes (memaddr, myaddr, len)
3361      CORE_ADDR memaddr;
3362      char *myaddr;
3363      int len;
3364 {
3365   int max_buf_size;             /* Max size of packet output buffer */
3366   int origlen;
3367
3368   /* Chop the transfer down if necessary */
3369
3370   max_buf_size = min (remote_write_size, PBUFSIZ);
3371   if (remote_register_buf_size != 0)
3372     max_buf_size = min (max_buf_size, remote_register_buf_size);
3373
3374   origlen = len;
3375   while (len > 0)
3376     {
3377       char buf[PBUFSIZ];
3378       char *p;
3379       int todo;
3380       int i;
3381
3382       todo = min (len, max_buf_size / 2); /* num bytes that will fit */
3383
3384       /* FIXME-32x64: Need a version of print_address_numeric which puts the
3385          result in a buffer like sprintf.  */
3386       sprintf (buf, "m%lx,%x", (unsigned long) memaddr, todo);
3387       putpkt (buf);
3388       getpkt (buf, 0);
3389
3390       if (buf[0] == 'E')
3391         {
3392           /* There is no correspondance between what the remote protocol uses
3393              for errors and errno codes.  We would like a cleaner way of
3394              representing errors (big enough to include errno codes, bfd_error
3395              codes, and others).  But for now just return EIO.  */
3396           errno = EIO;
3397           return 0;
3398         }
3399
3400   /* Reply describes memory byte by byte,
3401      each byte encoded as two hex characters.  */
3402
3403       p = buf;
3404       for (i = 0; i < todo; i++)
3405         {
3406           if (p[0] == 0 || p[1] == 0)
3407             /* Reply is short.  This means that we were able to read only part
3408                of what we wanted to.  */
3409             return i + (origlen - len);
3410           myaddr[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
3411           p += 2;
3412         }
3413       myaddr += todo;
3414       memaddr += todo;
3415       len -= todo;
3416     }
3417   return origlen;
3418 }
3419 \f
3420 /* Read or write LEN bytes from inferior memory at MEMADDR, transferring
3421    to or from debugger address MYADDR.  Write to inferior if SHOULD_WRITE is
3422    nonzero.  Returns length of data written or read; 0 for error.  */
3423
3424 /* ARGSUSED */
3425 static int
3426 remote_xfer_memory(memaddr, myaddr, len, should_write, target)
3427      CORE_ADDR memaddr;
3428      char *myaddr;
3429      int len;
3430      int should_write;
3431      struct target_ops *target;                 /* ignored */
3432 {
3433 #ifdef REMOTE_TRANSLATE_XFER_ADDRESS
3434   CORE_ADDR targaddr;
3435   int targlen;
3436   REMOTE_TRANSLATE_XFER_ADDRESS (memaddr, len, targaddr, targlen);
3437   if (targlen == 0)
3438     return 0;
3439   memaddr = targaddr;
3440   len = targlen;
3441 #endif
3442
3443   return dcache_xfer_memory (remote_dcache, memaddr, myaddr, len, should_write);
3444 }
3445
3446    
3447 #if 0
3448 /* Enable after 4.12.  */
3449
3450 void
3451 remote_search (len, data, mask, startaddr, increment, lorange, hirange
3452                addr_found, data_found)
3453      int len;
3454      char *data;
3455      char *mask;
3456      CORE_ADDR startaddr;
3457      int increment;
3458      CORE_ADDR lorange;
3459      CORE_ADDR hirange;
3460      CORE_ADDR *addr_found;
3461      char *data_found;
3462 {
3463   if (increment == -4 && len == 4)
3464     {
3465       long mask_long, data_long;
3466       long data_found_long;
3467       CORE_ADDR addr_we_found;
3468       char buf[PBUFSIZ];
3469       long returned_long[2];
3470       char *p;
3471
3472       mask_long = extract_unsigned_integer (mask, len);
3473       data_long = extract_unsigned_integer (data, len);
3474       sprintf (buf, "t%x:%x,%x", startaddr, data_long, mask_long);
3475       putpkt (buf);
3476       getpkt (buf, 0);
3477       if (buf[0] == '\0')
3478         {
3479           /* The stub doesn't support the 't' request.  We might want to
3480              remember this fact, but on the other hand the stub could be
3481              switched on us.  Maybe we should remember it only until
3482              the next "target remote".  */
3483           generic_search (len, data, mask, startaddr, increment, lorange,
3484                           hirange, addr_found, data_found);
3485           return;
3486         }
3487
3488       if (buf[0] == 'E')
3489         /* There is no correspondance between what the remote protocol uses
3490            for errors and errno codes.  We would like a cleaner way of
3491            representing errors (big enough to include errno codes, bfd_error
3492            codes, and others).  But for now just use EIO.  */
3493         memory_error (EIO, startaddr);
3494       p = buf;
3495       addr_we_found = 0;
3496       while (*p != '\0' && *p != ',')
3497         addr_we_found = (addr_we_found << 4) + fromhex (*p++);
3498       if (*p == '\0')
3499         error ("Protocol error: short return for search");
3500
3501       data_found_long = 0;
3502       while (*p != '\0' && *p != ',')
3503         data_found_long = (data_found_long << 4) + fromhex (*p++);
3504       /* Ignore anything after this comma, for future extensions.  */
3505
3506       if (addr_we_found < lorange || addr_we_found >= hirange)
3507         {
3508           *addr_found = 0;
3509           return;
3510         }
3511
3512       *addr_found = addr_we_found;
3513       *data_found = store_unsigned_integer (data_we_found, len);
3514       return;
3515     }
3516   generic_search (len, data, mask, startaddr, increment, lorange,
3517                   hirange, addr_found, data_found);
3518 }
3519 #endif /* 0 */
3520 \f
3521 static void
3522 remote_files_info (ignore)
3523      struct target_ops *ignore;
3524 {
3525   puts_filtered ("Debugging a target over a serial line.\n");
3526 }
3527 \f
3528 /* Stuff for dealing with the packets which are part of this protocol.
3529    See comment at top of file for details.  */
3530
3531 /* Read a single character from the remote end, masking it down to 7 bits. */
3532
3533 static int
3534 readchar (timeout)
3535      int timeout;
3536 {
3537   int ch;
3538
3539   ch = SERIAL_READCHAR (remote_desc, timeout);
3540
3541   switch (ch)
3542     {
3543     case SERIAL_EOF:
3544       error ("Remote connection closed");
3545     case SERIAL_ERROR:
3546       perror_with_name ("Remote communication error");
3547     case SERIAL_TIMEOUT:
3548       return ch;
3549     default:
3550       return ch & 0x7f;
3551     }
3552 }
3553
3554 /* Send the command in BUF to the remote machine,
3555    and read the reply into BUF.
3556    Report an error if we get an error reply.  */
3557
3558 static void
3559 remote_send (buf)
3560      char *buf;
3561 {
3562   putpkt (buf);
3563   getpkt (buf, 0);
3564
3565   if (buf[0] == 'E')
3566     error ("Remote failure reply: %s", buf);
3567 }
3568
3569 /* Send a packet to the remote machine, with error checking.
3570    The data of the packet is in BUF.  */
3571
3572 int
3573 putpkt (buf)
3574      char *buf;
3575 {
3576   int i;
3577   unsigned char csum = 0;
3578   char buf2[PBUFSIZ];
3579   int cnt = strlen (buf);
3580   int ch;
3581   int tcount = 0;
3582   char *p;
3583
3584   /* Copy the packet into buffer BUF2, encapsulating it
3585      and giving it a checksum.  */
3586
3587   if (cnt > (int) sizeof (buf2) - 5)            /* Prosanity check */
3588     abort();
3589
3590   p = buf2;
3591   *p++ = '$';
3592
3593   for (i = 0; i < cnt; i++)
3594     {
3595       csum += buf[i];
3596       *p++ = buf[i];
3597     }
3598   *p++ = '#';
3599   *p++ = tohex ((csum >> 4) & 0xf);
3600   *p++ = tohex (csum & 0xf);
3601
3602   /* Send it over and over until we get a positive ack.  */
3603
3604   while (1)
3605     {
3606       int started_error_output = 0;
3607
3608       if (remote_debug)
3609         {
3610           *p = '\0';
3611           printf_unfiltered ("Sending packet: %s...", buf2);
3612           gdb_flush(gdb_stdout);
3613         }
3614       if (SERIAL_WRITE (remote_desc, buf2, p - buf2))
3615         perror_with_name ("putpkt: write failed");
3616
3617       /* read until either a timeout occurs (-2) or '+' is read */
3618       while (1)
3619         {
3620           ch = readchar (remote_timeout);
3621
3622           if (remote_debug)
3623             {
3624               switch (ch)
3625                 {
3626                 case '+':
3627                 case SERIAL_TIMEOUT:
3628                 case '$':
3629                   if (started_error_output)
3630                     {
3631                       putchar_unfiltered ('\n');
3632                       started_error_output = 0;
3633                     }
3634                 }
3635             }
3636
3637           switch (ch)
3638             {
3639             case '+':
3640               if (remote_debug)
3641                 printf_unfiltered("Ack\n");
3642               return 1;
3643             case SERIAL_TIMEOUT:
3644               tcount ++;
3645               if (tcount > 3)
3646                 return 0;
3647               break;            /* Retransmit buffer */
3648             case '$':
3649               {
3650                 char junkbuf[PBUFSIZ];
3651
3652               /* It's probably an old response, and we're out of sync.  Just
3653                  gobble up the packet and ignore it.  */
3654                 getpkt (junkbuf, 0);
3655                 continue;               /* Now, go look for + */
3656               }
3657             default:
3658               if (remote_debug)
3659                 {
3660                   if (!started_error_output)
3661                     {
3662                       started_error_output = 1;
3663                       printf_unfiltered ("putpkt: Junk: ");
3664                     }
3665                   putchar_unfiltered (ch & 0177);
3666                 }
3667               continue;
3668             }
3669           break;                /* Here to retransmit */
3670         }
3671
3672 #if 0
3673       /* This is wrong.  If doing a long backtrace, the user should be
3674          able to get out next time we call QUIT, without anything as violent
3675          as interrupt_query.  If we want to provide a way out of here
3676          without getting to the next QUIT, it should be based on hitting
3677          ^C twice as in remote_wait.  */
3678       if (quit_flag)
3679         {
3680           quit_flag = 0;
3681           interrupt_query ();
3682         }
3683 #endif
3684     }
3685 }
3686
3687 /* Come here after finding the start of the frame.  Collect the rest into BUF,
3688    verifying the checksum, length, and handling run-length compression.
3689    Returns 0 on any error, 1 on success.  */
3690
3691 static int
3692 read_frame (buf)
3693      char *buf;
3694 {
3695   unsigned char csum;
3696   char *bp;
3697   int c;
3698
3699   csum = 0;
3700   bp = buf;
3701
3702   while (1)
3703     {
3704       c = readchar (remote_timeout);
3705
3706       switch (c)
3707         {
3708         case SERIAL_TIMEOUT:
3709           if (remote_debug)
3710             puts_filtered ("Timeout in mid-packet, retrying\n");
3711           return 0;
3712         case '$':
3713           if (remote_debug)
3714             puts_filtered ("Saw new packet start in middle of old one\n");
3715           return 0;             /* Start a new packet, count retries */
3716         case '#':
3717           {
3718             unsigned char pktcsum;
3719
3720             *bp = '\000';
3721
3722             pktcsum = fromhex (readchar (remote_timeout)) << 4;
3723             pktcsum |= fromhex (readchar (remote_timeout));
3724
3725             if (csum == pktcsum)
3726               return 1;
3727
3728             if (remote_debug) 
3729               {
3730                 printf_filtered ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=",
3731                                  pktcsum, csum);
3732                 puts_filtered (buf);
3733                 puts_filtered ("\n");
3734               }
3735             return 0;
3736           }
3737         case '*':               /* Run length encoding */
3738           csum += c;
3739           c = readchar (remote_timeout);
3740           csum += c;
3741           c = c - ' ' + 3;      /* Compute repeat count */
3742
3743
3744           if (c > 0 && c < 255 && bp + c - 1 < buf + PBUFSIZ - 1)
3745             {
3746               memset (bp, *(bp - 1), c);
3747               bp += c;
3748               continue;
3749             }
3750
3751           *bp = '\0';
3752           printf_filtered ("Repeat count %d too large for buffer: ", c);
3753           puts_filtered (buf);
3754           puts_filtered ("\n");
3755           return 0;
3756
3757         default:
3758           if (bp < buf + PBUFSIZ - 1)
3759             {
3760               *bp++ = c;
3761               csum += c;
3762               continue;
3763             }
3764
3765           *bp = '\0';
3766           puts_filtered ("Remote packet too long: ");
3767           puts_filtered (buf);
3768           puts_filtered ("\n");
3769
3770           return 0;
3771         }
3772     }
3773 }
3774
3775 /* Read a packet from the remote machine, with error checking,
3776    and store it in BUF.  BUF is expected to be of size PBUFSIZ.
3777    If FOREVER, wait forever rather than timing out; this is used
3778    while the target is executing user code.  */
3779
3780 void
3781 getpkt (buf, forever)
3782      char *buf;
3783      int forever;
3784 {
3785   int c;
3786   int tries;
3787   int timeout;
3788   int val;
3789
3790   strcpy (buf,"timeout");
3791
3792   if (forever)
3793     {
3794 #ifdef MAINTENANCE_CMDS
3795       timeout = watchdog > 0 ? watchdog : -1;
3796 #else
3797       timeout = -1;
3798 #endif
3799     }
3800
3801   else
3802     timeout = remote_timeout;
3803
3804 #define MAX_TRIES 3
3805
3806   for (tries = 1; tries <= MAX_TRIES; tries++)
3807     {
3808       /* This can loop forever if the remote side sends us characters
3809          continuously, but if it pauses, we'll get a zero from readchar
3810          because of timeout.  Then we'll count that as a retry.  */
3811
3812       /* Note that we will only wait forever prior to the start of a packet.
3813          After that, we expect characters to arrive at a brisk pace.  They
3814          should show up within remote_timeout intervals.  */
3815
3816       do
3817         {
3818           c = readchar (timeout);
3819
3820           if (c == SERIAL_TIMEOUT)
3821             {
3822 #ifdef MAINTENANCE_CMDS
3823               if (forever)      /* Watchdog went off.  Kill the target. */
3824                 {
3825                   target_mourn_inferior ();
3826                   error ("Watchdog has expired.  Target detached.\n");
3827                 }
3828 #endif
3829               if (remote_debug)
3830                 puts_filtered ("Timed out.\n");
3831               goto retry;
3832             }
3833         }
3834       while (c != '$');
3835
3836       /* We've found the start of a packet, now collect the data.  */
3837
3838       val = read_frame (buf);
3839
3840       if (val == 1)
3841         {
3842           if (remote_debug)
3843             fprintf_unfiltered (gdb_stdout, "Packet received: %s\n", buf);
3844           SERIAL_WRITE (remote_desc, "+", 1);
3845           return;
3846         }
3847
3848       /* Try the whole thing again.  */
3849     retry:
3850       SERIAL_WRITE (remote_desc, "-", 1);
3851     }
3852
3853   /* We have tried hard enough, and just can't receive the packet.  Give up. */
3854
3855   printf_unfiltered ("Ignoring packet error, continuing...\n");
3856   SERIAL_WRITE (remote_desc, "+", 1);
3857 }
3858 \f
3859 static void
3860 remote_kill ()
3861 {
3862   /* For some mysterious reason, wait_for_inferior calls kill instead of
3863      mourn after it gets TARGET_WAITKIND_SIGNALLED.  Work around it.  */
3864   if (kill_kludge)
3865     {
3866       kill_kludge = 0;
3867       target_mourn_inferior ();
3868       return;
3869     }
3870
3871   /* Use catch_errors so the user can quit from gdb even when we aren't on
3872      speaking terms with the remote system.  */
3873   catch_errors (putpkt, "k", "", RETURN_MASK_ERROR);
3874
3875   /* Don't wait for it to die.  I'm not really sure it matters whether
3876      we do or not.  For the existing stubs, kill is a noop.  */
3877   target_mourn_inferior ();
3878 }
3879
3880 static void
3881 remote_mourn ()
3882 {
3883   remote_mourn_1 (&remote_ops);
3884 }
3885
3886 static void
3887 extended_remote_mourn ()
3888 {
3889   /* We do _not_ want to mourn the target like this; this will
3890      remove the extended remote target  from the target stack,
3891      and the next time the user says "run" it'll fail. 
3892
3893      FIXME: What is the right thing to do here?  */
3894 #if 0
3895   remote_mourn_1 (&extended_remote_ops);
3896 #endif
3897 }
3898
3899 /* Worker function for remote_mourn.  */
3900 static void
3901 remote_mourn_1 (target)
3902      struct target_ops *target;
3903 {
3904   unpush_target (target);
3905   generic_mourn_inferior ();
3906 }
3907
3908 /* In the extended protocol we want to be able to do things like
3909    "run" and have them basically work as expected.  So we need
3910    a special create_inferior function. 
3911
3912    FIXME: One day add support for changing the exec file
3913    we're debugging, arguments and an environment.  */
3914
3915 static void
3916 extended_remote_create_inferior (exec_file, args, env)
3917      char *exec_file;
3918      char *args;
3919      char **env;
3920 {
3921   /* Rip out the breakpoints; we'll reinsert them after restarting
3922      the remote server.  */
3923   remove_breakpoints ();
3924
3925   /* Now restart the remote server.  */
3926   extended_remote_restart ();
3927
3928   /* Now put the breakpoints back in.  This way we're safe if the
3929      restart function works via a unix fork on the remote side.  */
3930   insert_breakpoints ();
3931
3932   /* Clean up from the last time we were running.  */
3933   clear_proceed_status ();
3934
3935   /* Let the remote process run.  */
3936   proceed (-1, TARGET_SIGNAL_0, 0);
3937 }
3938
3939 \f
3940 /* On some machines, e.g. 68k, we may use a different breakpoint instruction
3941    than other targets; in those use REMOTE_BREAKPOINT instead of just
3942    BREAKPOINT.  Also, bi-endian targets may define LITTLE_REMOTE_BREAKPOINT
3943    and BIG_REMOTE_BREAKPOINT.  If none of these are defined, we just call
3944    the standard routines that are in mem-break.c.  */
3945
3946 /* FIXME, these ought to be done in a more dynamic fashion.  For instance,
3947    the choice of breakpoint instruction affects target program design and
3948    vice versa, and by making it user-tweakable, the special code here
3949    goes away and we need fewer special GDB configurations.  */
3950
3951 #if defined (LITTLE_REMOTE_BREAKPOINT) && defined (BIG_REMOTE_BREAKPOINT) && !defined(REMOTE_BREAKPOINT)
3952 #define REMOTE_BREAKPOINT
3953 #endif
3954
3955 #ifdef REMOTE_BREAKPOINT
3956
3957 /* If the target isn't bi-endian, just pretend it is.  */
3958 #if !defined (LITTLE_REMOTE_BREAKPOINT) && !defined (BIG_REMOTE_BREAKPOINT)
3959 #define LITTLE_REMOTE_BREAKPOINT REMOTE_BREAKPOINT
3960 #define BIG_REMOTE_BREAKPOINT REMOTE_BREAKPOINT
3961 #endif
3962
3963 static unsigned char big_break_insn[] = BIG_REMOTE_BREAKPOINT;
3964 static unsigned char little_break_insn[] = LITTLE_REMOTE_BREAKPOINT;
3965
3966 #endif /* REMOTE_BREAKPOINT */
3967
3968 /* Insert a breakpoint on targets that don't have any better breakpoint
3969    support.  We read the contents of the target location and stash it,
3970    then overwrite it with a breakpoint instruction.  ADDR is the target
3971    location in the target machine.  CONTENTS_CACHE is a pointer to 
3972    memory allocated for saving the target contents.  It is guaranteed
3973    by the caller to be long enough to save sizeof BREAKPOINT bytes (this
3974    is accomplished via BREAKPOINT_MAX).  */
3975
3976 static int
3977 remote_insert_breakpoint (addr, contents_cache)
3978      CORE_ADDR addr;
3979      char *contents_cache;
3980 {
3981 #ifdef REMOTE_BREAKPOINT
3982   int val;
3983
3984   val = target_read_memory (addr, contents_cache, sizeof big_break_insn);
3985
3986   if (val == 0)
3987     {
3988       if (TARGET_BYTE_ORDER == BIG_ENDIAN)
3989         val = target_write_memory (addr, (char *) big_break_insn,
3990                                    sizeof big_break_insn);
3991       else
3992         val = target_write_memory (addr, (char *) little_break_insn,
3993                                    sizeof little_break_insn);
3994     }
3995
3996   return val;
3997 #else
3998   return memory_insert_breakpoint (addr, contents_cache);
3999 #endif /* REMOTE_BREAKPOINT */
4000 }
4001
4002 static int
4003 remote_remove_breakpoint (addr, contents_cache)
4004      CORE_ADDR addr;
4005      char *contents_cache;
4006 {
4007 #ifdef REMOTE_BREAKPOINT
4008   return target_write_memory (addr, contents_cache, sizeof big_break_insn);
4009 #else
4010   return memory_remove_breakpoint (addr, contents_cache);
4011 #endif /* REMOTE_BREAKPOINT */
4012 }
4013
4014 /* Some targets are only capable of doing downloads, and afterwards they switch
4015    to the remote serial protocol.  This function provides a clean way to get
4016    from the download target to the remote target.  It's basically just a
4017    wrapper so that we don't have to expose any of the internal workings of
4018    remote.c.
4019
4020    Prior to calling this routine, you should shutdown the current target code,
4021    else you will get the "A program is being debugged already..." message.
4022    Usually a call to pop_target() suffices.
4023 */
4024
4025 void
4026 push_remote_target (name, from_tty)
4027      char *name;
4028      int from_tty;
4029 {
4030   printf_filtered ("Switching to remote protocol\n");
4031   remote_open (name, from_tty);
4032 }
4033
4034 /* Other targets want to use the entire remote serial module but with
4035    certain remote_ops overridden. */
4036
4037 void
4038 open_remote_target (name, from_tty, target, extended_p)
4039      char *name;
4040      int from_tty;
4041      struct target_ops *target;
4042      int extended_p;
4043 {
4044   printf_filtered ("Selecting the %sremote protocol\n",
4045                    (extended_p ? "extended-" : ""));
4046   remote_open_1 (name, from_tty, target, extended_p);
4047 }
4048
4049 /* Table used by the crc32 function to calcuate the checksum. */
4050 static unsigned long crc32_table[256] = {0, 0};
4051
4052 static unsigned long
4053 crc32 (buf, len, crc)
4054      unsigned char *buf;
4055      int len;
4056      unsigned int crc;
4057 {
4058   if (! crc32_table[1])
4059     {
4060       /* Initialize the CRC table and the decoding table. */
4061       int i, j;
4062       unsigned int c;
4063
4064       for (i = 0; i < 256; i++)
4065         {
4066           for (c = i << 24, j = 8; j > 0; --j)
4067             c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
4068           crc32_table[i] = c;
4069         }
4070     }
4071
4072   while (len--)
4073     {
4074       crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
4075       buf++;
4076     }
4077   return crc;
4078 }
4079
4080 /* compare-sections command
4081
4082    With no arguments, compares each loadable section in the exec bfd
4083    with the same memory range on the target, and reports mismatches.
4084    Useful for verifying the image on the target against the exec file.
4085    Depends on the target understanding the new "qCRC:" request.  */
4086
4087 static void
4088 remote_compare_command (args, from_tty)
4089      char *args;
4090      int from_tty;
4091 {
4092   asection *s;
4093   unsigned long host_crc, target_crc;
4094   extern bfd *exec_bfd;
4095   struct cleanup *old_chain;
4096   char *tmp, *sectdata, *sectname, buf[PBUFSIZ];
4097   bfd_size_type size;
4098   bfd_vma lma;
4099   int matched = 0;
4100
4101   if (!exec_bfd)
4102     error ("command cannot be used without an exec file");
4103   if (!current_target.to_shortname ||
4104       strcmp (current_target.to_shortname, "remote") != 0)
4105     error ("command can only be used with remote target");
4106
4107   for (s = exec_bfd->sections; s; s = s->next) 
4108     {
4109       if (!(s->flags & SEC_LOAD))
4110         continue;       /* skip non-loadable section */
4111
4112       size = bfd_get_section_size_before_reloc (s);
4113       if (size == 0)
4114         continue;       /* skip zero-length section */
4115
4116       sectname = (char *) bfd_get_section_name (exec_bfd, s);
4117       if (args && strcmp (args, sectname) != 0)
4118         continue;       /* not the section selected by user */
4119
4120       matched = 1;      /* do this section */
4121       lma = s->lma;
4122       /* FIXME: assumes lma can fit into long */
4123       sprintf (buf, "qCRC:%lx,%lx", (long) lma, (long) size);
4124       putpkt (buf);
4125
4126       /* be clever; compute the host_crc before waiting for target reply */
4127       sectdata = xmalloc (size);
4128       old_chain = make_cleanup (free, sectdata);
4129       bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
4130       host_crc = crc32 ((unsigned char *) sectdata, size, 0xffffffff);
4131
4132       getpkt (buf, 0);
4133       if (buf[0] == 'E')
4134         error ("target memory fault, section %s, range 0x%08x -- 0x%08x",
4135                sectname, lma, lma + size);
4136       if (buf[0] != 'C')
4137         error ("remote target does not support this operation");
4138
4139       for (target_crc = 0, tmp = &buf[1]; *tmp; tmp++)
4140         target_crc = target_crc * 16 + fromhex (*tmp);
4141
4142       printf_filtered ("Section %s, range 0x%08x -- 0x%08x: ",
4143                        sectname, lma, lma + size);
4144       if (host_crc == target_crc)
4145         printf_filtered ("matched.\n");
4146       else
4147         printf_filtered ("MIS-MATCHED!\n");
4148
4149       do_cleanups (old_chain);
4150     }
4151   if (args && !matched)
4152     printf_filtered ("No loaded section named '%s'.\n", args);
4153 }
4154
4155
4156 void
4157 _initialize_remote ()
4158 {
4159   init_remote_ops() ;
4160   init_extended_remote_ops() ;
4161   add_target (&remote_ops);
4162   add_target (&extended_remote_ops);
4163
4164 /* Remote target communications for serial-line targets in custom GDB protocol
4165    Copyright 1988, 1991, 1992, 1993, 1994, 1995, 1996, 1997 Free Software Foundation, Inc.
4166
4167 This file is part of GDB.
4168
4169 This program is free software; you can redistribute it and/or modify
4170 it under the terms of the GNU General Public License as published by
4171 the Free Software Foundation; either version 2 of the License, or
4172 (at your option) any later version.
4173
4174 This program is distributed in the hope that it will be useful,
4175 but WITHOUT ANY WARRANTY; without even the implied warranty of
4176 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
4177 GNU General Public License for more details.
4178
4179 You should have received a copy of the GNU General Public License
4180 along with this program; if not, write to the Free Software
4181 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
4182
4183 /* Remote communication protocol.
4184
4185    A debug packet whose contents are <data>
4186    is encapsulated for transmission in the form:
4187
4188         $ <data> # CSUM1 CSUM2
4189
4190         <data> must be ASCII alphanumeric and cannot include characters
4191         '$' or '#'.  If <data> starts with two characters followed by
4192         ':', then the existing stubs interpret this as a sequence number.
4193
4194         CSUM1 and CSUM2 are ascii hex representation of an 8-bit 
4195         checksum of <data>, the most significant nibble is sent first.
4196         the hex digits 0-9,a-f are used.
4197
4198    Receiver responds with:
4199
4200         +       - if CSUM is correct and ready for next packet
4201         -       - if CSUM is incorrect
4202
4203    <data> is as follows:
4204    Most values are encoded in ascii hex digits.  Signal numbers are according
4205    to the numbering in target.h.
4206
4207         Request         Packet
4208
4209         set thread      Hct...          Set thread for subsequent operations.
4210                                         c = 'c' for thread used in step and 
4211                                         continue; t... can be -1 for all
4212                                         threads.
4213                                         c = 'g' for thread used in other
4214                                         operations.  If zero, pick a thread,
4215                                         any thread.
4216         reply           OK              for success
4217                         ENN             for an error.
4218
4219         read registers  g
4220         reply           XX....X         Each byte of register data
4221                                         is described by two hex digits.
4222                                         Registers are in the internal order
4223                                         for GDB, and the bytes in a register
4224                                         are in the same order the machine uses.
4225                         or ENN          for an error.
4226
4227         write regs      GXX..XX         Each byte of register data
4228                                         is described by two hex digits.
4229         reply           OK              for success
4230                         ENN             for an error
4231
4232         write reg       Pn...=r...      Write register n... with value r...,
4233                                         which contains two hex digits for each
4234                                         byte in the register (target byte
4235                                         order).
4236         reply           OK              for success
4237                         ENN             for an error
4238         (not supported by all stubs).
4239
4240         read mem        mAA..AA,LLLL    AA..AA is address, LLLL is length.
4241         reply           XX..XX          XX..XX is mem contents
4242                                         Can be fewer bytes than requested
4243                                         if able to read only part of the data.
4244                         or ENN          NN is errno
4245
4246         write mem       MAA..AA,LLLL:XX..XX
4247                                         AA..AA is address,
4248                                         LLLL is number of bytes,
4249                                         XX..XX is data
4250         reply           OK              for success
4251                         ENN             for an error (this includes the case
4252                                         where only part of the data was
4253                                         written).
4254
4255         continue        cAA..AA         AA..AA is address to resume
4256                                         If AA..AA is omitted,
4257                                         resume at same address.
4258
4259         step            sAA..AA         AA..AA is address to resume
4260                                         If AA..AA is omitted,
4261                                         resume at same address.
4262
4263         continue with   Csig;AA..AA     Continue with signal sig (hex signal
4264         signal                          number).  If ;AA..AA is omitted, resume
4265                                         at same address.
4266
4267         step with       Ssig;AA..AA     Like 'C' but step not continue.
4268         signal
4269
4270         last signal     ?               Reply the current reason for stopping.
4271                                         This is the same reply as is generated
4272                                         for step or cont : SAA where AA is the
4273                                         signal number.
4274
4275         detach          D               Reply OK.
4276
4277         There is no immediate reply to step or cont.
4278         The reply comes when the machine stops.
4279         It is           SAA             AA is the signal number.
4280
4281         or...           TAAn...:r...;n...:r...;n...:r...;
4282                                         AA = signal number
4283                                         n... = register number (hex)
4284                                           r... = register contents
4285                                         n... = `thread'
4286                                           r... = thread process ID.  This is
4287                                                  a hex integer.
4288                                         n... = other string not starting 
4289                                             with valid hex digit.
4290                                           gdb should ignore this n,r pair
4291                                           and go on to the next.  This way
4292                                           we can extend the protocol.
4293         or...           WAA             The process exited, and AA is
4294                                         the exit status.  This is only
4295                                         applicable for certains sorts of
4296                                         targets.
4297         or...           XAA             The process terminated with signal
4298                                         AA.
4299         or...           OXX..XX XX..XX  is hex encoding of ASCII data. This
4300                                         can happen at any time while the program is
4301                                         running and the debugger should
4302                                         continue to wait for 'W', 'T', etc.
4303
4304         thread alive    TXX             Find out if the thread XX is alive.
4305         reply           OK              thread is still alive
4306                         ENN             thread is dead
4307         
4308         remote restart  RXX             Restart the remote server
4309
4310         extended ops    !               Use the extended remote protocol.
4311                                         Sticky -- only needs to be set once.
4312
4313         kill request    k
4314
4315         toggle debug    d               toggle debug flag (see 386 & 68k stubs)
4316         reset           r               reset -- see sparc stub.
4317         reserved        <other>         On other requests, the stub should
4318                                         ignore the request and send an empty
4319                                         response ($#<checksum>).  This way
4320                                         we can extend the protocol and GDB
4321                                         can tell whether the stub it is
4322                                         talking to uses the old or the new.
4323         search          tAA:PP,MM       Search backwards starting at address
4324                                         AA for a match with pattern PP and
4325                                         mask MM.  PP and MM are 4 bytes.
4326                                         Not supported by all stubs.
4327
4328         general query   qXXXX           Request info about XXXX.
4329         general set     QXXXX=yyyy      Set value of XXXX to yyyy.
4330         query sect offs qOffsets        Get section offsets.  Reply is
4331                                         Text=xxx;Data=yyy;Bss=zzz
4332
4333         Responses can be run-length encoded to save space.  A '*' means that
4334         the next character is an ASCII encoding giving a repeat count which
4335         stands for that many repititions of the character preceding the '*'.
4336         The encoding is n+29, yielding a printable character where n >=3 
4337         (which is where rle starts to win).  Don't use an n > 126.
4338
4339         So 
4340         "0* " means the same as "0000".  */
4341
4342 #include "defs.h"
4343 #include "gdb_string.h"
4344 #include <fcntl.h>
4345 #include "frame.h"
4346 #include "inferior.h"
4347 #include "bfd.h"
4348 #include "symfile.h"
4349 #include "target.h"
4350 #include "wait.h"
4351 /*#include "terminal.h"*/
4352 #include "gdbcmd.h"
4353 #include "objfiles.h"
4354 #include "gdb-stabs.h"
4355 #include "gdbthread.h"
4356
4357 #include "dcache.h"
4358
4359 #ifdef USG
4360 #include <sys/types.h>
4361 #endif
4362
4363 #include <signal.h>
4364 #include "serial.h"
4365
4366 /* Prototypes for local functions */
4367
4368 static int remote_write_bytes PARAMS ((CORE_ADDR memaddr,
4369                                        char *myaddr, int len));
4370
4371 static int remote_read_bytes PARAMS ((CORE_ADDR memaddr,
4372                                       char *myaddr, int len));
4373
4374 static void remote_files_info PARAMS ((struct target_ops *ignore));
4375
4376 static int remote_xfer_memory PARAMS ((CORE_ADDR memaddr, char *myaddr,
4377                                        int len, int should_write,
4378                                        struct target_ops *target));
4379
4380 static void remote_prepare_to_store PARAMS ((void));
4381
4382 static void remote_fetch_registers PARAMS ((int regno));
4383
4384 static void remote_resume PARAMS ((int pid, int step,
4385                                    enum target_signal siggnal));
4386
4387 static int remote_start_remote PARAMS ((char *dummy));
4388
4389 static void remote_open PARAMS ((char *name, int from_tty));
4390
4391 static void extended_remote_open PARAMS ((char *name, int from_tty));
4392
4393 static void remote_open_1 PARAMS ((char *, int, struct target_ops *, int extended_p));
4394
4395 static void remote_close PARAMS ((int quitting));
4396
4397 static void remote_store_registers PARAMS ((int regno));
4398
4399 static void remote_mourn PARAMS ((void));
4400
4401 static void extended_remote_restart PARAMS ((void));
4402
4403 static void extended_remote_mourn PARAMS ((void));
4404
4405 static void extended_remote_create_inferior PARAMS ((char *, char *, char **));
4406
4407 static void remote_mourn_1 PARAMS ((struct target_ops *));
4408
4409 static void remote_send PARAMS ((char *buf));
4410
4411 static int readchar PARAMS ((int timeout));
4412
4413 static int remote_wait PARAMS ((int pid, struct target_waitstatus *status));
4414
4415 static void remote_kill PARAMS ((void));
4416
4417 static int tohex PARAMS ((int nib));
4418
4419 static void remote_detach PARAMS ((char *args, int from_tty));
4420
4421 static void remote_interrupt PARAMS ((int signo));
4422
4423 static void remote_interrupt_twice PARAMS ((int signo));
4424
4425 static void interrupt_query PARAMS ((void));
4426
4427 static void set_thread PARAMS ((int, int));
4428
4429 static int remote_thread_alive PARAMS ((int));
4430
4431 static void get_offsets PARAMS ((void));
4432
4433 static int read_frame PARAMS ((char *));
4434
4435 static int remote_insert_breakpoint PARAMS ((CORE_ADDR, char *));
4436
4437 static int remote_remove_breakpoint PARAMS ((CORE_ADDR, char *));
4438
4439 static int hexnumlen PARAMS ((ULONGEST num));
4440
4441 /* exported functions */
4442
4443 extern int fromhex PARAMS ((int a));
4444 extern void getpkt PARAMS ((char *buf, int forever));
4445 extern int putpkt PARAMS ((char *buf));
4446
4447 /* Define the target subroutine names */
4448
4449 static struct target_ops remote_ops ;
4450
4451 static void init_remote_ops(void)
4452 {
4453   remote_ops.to_shortname =   "remote";         
4454   remote_ops.to_longname =   "Remote serial target in gdb-specific protocol";
4455   remote_ops.to_doc =   "Use a remote computer via a serial line; using a gdb-specific protocol.\n\
4456 Specify the serial device it is connected to (e.g. /dev/ttya)." ;  
4457   remote_ops.to_open =   remote_open;           
4458   remote_ops.to_close =   remote_close;         
4459   remote_ops.to_attach =   NULL;                
4460   remote_ops.to_detach =   remote_detach;       
4461   remote_ops.to_resume =   remote_resume;       
4462   remote_ops.to_wait  =   remote_wait;          
4463   remote_ops.to_fetch_registers  =   remote_fetch_registers;
4464   remote_ops.to_store_registers  =   remote_store_registers;
4465   remote_ops.to_prepare_to_store =   remote_prepare_to_store;
4466   remote_ops.to_xfer_memory  =   remote_xfer_memory;    
4467   remote_ops.to_files_info  =   remote_files_info;      
4468   remote_ops.to_insert_breakpoint =   remote_insert_breakpoint;
4469   remote_ops.to_remove_breakpoint =   remote_remove_breakpoint;
4470   remote_ops.to_terminal_init  =   NULL;                
4471   remote_ops.to_terminal_inferior =   NULL;             
4472   remote_ops.to_terminal_ours_for_output =   NULL;
4473   remote_ops.to_terminal_ours  =   NULL;        
4474   remote_ops.to_terminal_info  =   NULL;        
4475   remote_ops.to_kill  =   remote_kill;          
4476   remote_ops.to_load  =   generic_load;         
4477   remote_ops.to_lookup_symbol =   NULL;         
4478   remote_ops.to_create_inferior =   NULL;       
4479   remote_ops.to_mourn_inferior =   remote_mourn;
4480   remote_ops.to_can_run  =   0;                 
4481   remote_ops.to_notice_signals =   0;           
4482   remote_ops.to_thread_alive  =   remote_thread_alive;
4483   remote_ops.to_stop  =   0;            
4484   remote_ops.to_stratum =   process_stratum;
4485   remote_ops.DONT_USE =   NULL;         
4486   remote_ops.to_has_all_memory =   1;   
4487   remote_ops.to_has_memory =   1;       
4488   remote_ops.to_has_stack =   1;        
4489   remote_ops.to_has_registers =   1;    
4490   remote_ops.to_has_execution =   1;    
4491   remote_ops.to_sections =   NULL;      
4492   remote_ops.to_sections_end =   NULL;  
4493   remote_ops.to_magic =   OPS_MAGIC ;   
4494 } /* init_remote_ops */
4495
4496 static struct target_ops extended_remote_ops ;
4497
4498 static void init_extended_remote_ops(void) 
4499 {
4500   extended_remote_ops.to_shortname =   "extended-remote";       
4501   extended_remote_ops.to_longname =   "Extended remote serial target in gdb-specific protocol";
4502   extended_remote_ops.to_doc =   "Use a remote computer via a serial line; using a gdb-specific protocol.\n\
4503 Specify the serial device it is connected to (e.g. /dev/ttya).",
4504     extended_remote_ops.to_open =   extended_remote_open;       
4505   extended_remote_ops.to_close =   remote_close;        
4506   extended_remote_ops.to_attach =   NULL;               
4507   extended_remote_ops.to_detach =   remote_detach;      
4508   extended_remote_ops.to_resume =   remote_resume;      
4509   extended_remote_ops.to_wait  =   remote_wait;         
4510   extended_remote_ops.to_fetch_registers  =   remote_fetch_registers;
4511   extended_remote_ops.to_store_registers  =   remote_store_registers;   
4512   extended_remote_ops.to_prepare_to_store =   remote_prepare_to_store;
4513   extended_remote_ops.to_xfer_memory  =   remote_xfer_memory;   
4514   extended_remote_ops.to_files_info  =   remote_files_info;     
4515   extended_remote_ops.to_insert_breakpoint =   remote_insert_breakpoint;
4516   extended_remote_ops.to_remove_breakpoint =   remote_remove_breakpoint;
4517   extended_remote_ops.to_terminal_init  =   NULL;               
4518   extended_remote_ops.to_terminal_inferior =   NULL;            
4519   extended_remote_ops.to_terminal_ours_for_output =   NULL;
4520   extended_remote_ops.to_terminal_ours  =   NULL;       
4521   extended_remote_ops.to_terminal_info  =   NULL;       
4522   extended_remote_ops.to_kill  =   remote_kill;         
4523   extended_remote_ops.to_load  =   generic_load;        
4524   extended_remote_ops.to_lookup_symbol =   NULL;        
4525   extended_remote_ops.to_create_inferior =   extended_remote_create_inferior;
4526   extended_remote_ops.to_mourn_inferior =   extended_remote_mourn;
4527   extended_remote_ops.to_can_run  =   0;                        
4528   extended_remote_ops.to_notice_signals =   0;                  
4529   extended_remote_ops.to_thread_alive  =   remote_thread_alive;
4530   extended_remote_ops.to_stop  =   0;                   
4531   extended_remote_ops.to_stratum =   process_stratum;
4532   extended_remote_ops.DONT_USE =   NULL;        
4533   extended_remote_ops.to_has_all_memory =   1;  
4534   extended_remote_ops.to_has_memory =   1;      
4535   extended_remote_ops.to_has_stack =   1;       
4536   extended_remote_ops.to_has_registers =   1;   
4537   extended_remote_ops.to_has_execution =   1;   
4538   extended_remote_ops.to_sections =   NULL;     
4539   extended_remote_ops.to_sections_end =   NULL;
4540   extended_remote_ops.to_magic =   OPS_MAGIC ;
4541
4542
4543
4544 /* This was 5 seconds, which is a long time to sit and wait.
4545    Unless this is going though some terminal server or multiplexer or
4546    other form of hairy serial connection, I would think 2 seconds would
4547    be plenty.  */
4548
4549 /* Changed to allow option to set timeout value.
4550    was static int remote_timeout = 2; */
4551 extern int remote_timeout;
4552
4553 /* This variable chooses whether to send a ^C or a break when the user
4554    requests program interruption.  Although ^C is usually what remote
4555    systems expect, and that is the default here, sometimes a break is
4556    preferable instead.  */
4557
4558 static int remote_break;
4559
4560 /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
4561    remote_open knows that we don't have a file open when the program
4562    starts.  */
4563 static serial_t remote_desc = NULL;
4564
4565 /* Having this larger than 400 causes us to be incompatible with m68k-stub.c
4566    and i386-stub.c.  Normally, no one would notice because it only matters
4567    for writing large chunks of memory (e.g. in downloads).  Also, this needs
4568    to be more than 400 if required to hold the registers (see below, where
4569    we round it up based on REGISTER_BYTES).  */
4570 #define PBUFSIZ 400
4571
4572 /* Maximum number of bytes to read/write at once.  The value here
4573    is chosen to fill up a packet (the headers account for the 32).  */
4574 #define MAXBUFBYTES ((PBUFSIZ-32)/2)
4575
4576 /* Round up PBUFSIZ to hold all the registers, at least.  */
4577 /* The blank line after the #if seems to be required to work around a
4578    bug in HP's PA compiler.  */
4579 #if REGISTER_BYTES > MAXBUFBYTES
4580
4581 #undef PBUFSIZ
4582 #define PBUFSIZ (REGISTER_BYTES * 2 + 32)
4583 #endif
4584
4585 /* This variable sets the number of bytes to be written to the target
4586    in a single packet.  Normally PBUFSIZ is satisfactory, but some
4587    targets need smaller values (perhaps because the receiving end
4588    is slow).  */
4589
4590 static int remote_write_size = PBUFSIZ;
4591
4592 /* This is the size (in chars) of the first response to the `g' command.  This
4593    is used to limit the size of the memory read and write commands to prevent
4594    stub buffers from overflowing.  The size does not include headers and
4595    trailers, it is only the payload size. */
4596
4597 static int remote_register_buf_size = 0;
4598
4599 /* Should we try the 'P' request?  If this is set to one when the stub
4600    doesn't support 'P', the only consequence is some unnecessary traffic.  */
4601 static int stub_supports_P = 1;
4602
4603 /* These are pointers to hook functions that may be set in order to
4604    modify resume/wait behavior for a particular architecture.  */
4605
4606 void (*target_resume_hook) PARAMS ((void));
4607 void (*target_wait_loop_hook) PARAMS ((void));
4608
4609 \f
4610 /* These are the threads which we last sent to the remote system.  -1 for all
4611    or -2 for not sent yet.  */
4612 int general_thread;
4613 int cont_thread;
4614
4615 static void
4616 set_thread (th, gen)
4617      int th;
4618      int gen;
4619 {
4620   char buf[PBUFSIZ];
4621   int state = gen ? general_thread : cont_thread;
4622   if (state == th)
4623     return;
4624   buf[0] = 'H';
4625   buf[1] = gen ? 'g' : 'c';
4626   if (th == 42000)
4627     {
4628       buf[2] = '0';
4629       buf[3] = '\0';
4630     }
4631   else if (th < 0)
4632     sprintf (&buf[2], "-%x", -th);
4633   else
4634     sprintf (&buf[2], "%x", th);
4635   putpkt (buf);
4636   getpkt (buf, 0);
4637   if (gen)
4638     general_thread = th;
4639   else
4640     cont_thread = th;
4641 }
4642 \f
4643 /*  Return nonzero if the thread TH is still alive on the remote system.  */
4644
4645 static int
4646 remote_thread_alive (th)
4647      int th;
4648 {
4649   char buf[PBUFSIZ];
4650
4651   buf[0] = 'T';
4652   if (th < 0)
4653     sprintf (&buf[1], "-%x", -th);
4654   else
4655     sprintf (&buf[1], "%x", th);
4656   putpkt (buf);
4657   getpkt (buf, 0);
4658   return (buf[0] == 'O' && buf[1] == 'K');
4659 }
4660
4661 /*  Restart the remote side; this is an extended protocol operation.  */
4662
4663 static void
4664 extended_remote_restart ()
4665 {
4666   char buf[PBUFSIZ];
4667
4668   /* Send the restart command; for reasons I don't understand the
4669      remote side really expects a number after the "R".  */
4670   buf[0] = 'R';
4671   sprintf (&buf[1], "%x", 0);
4672   putpkt (buf);
4673
4674   /* Now query for status so this looks just like we restarted
4675      gdbserver from scratch.  */
4676   putpkt ("?");
4677   getpkt (buf, 0);
4678 }
4679 \f
4680 /* Clean up connection to a remote debugger.  */
4681
4682 /* ARGSUSED */
4683 static void
4684 remote_close (quitting)
4685      int quitting;
4686 {
4687   if (remote_desc)
4688     SERIAL_CLOSE (remote_desc);
4689   remote_desc = NULL;
4690 }
4691
4692 /* Query the remote side for the text, data and bss offsets. */
4693
4694 static void
4695 get_offsets ()
4696 {
4697   char buf[PBUFSIZ], *ptr;
4698   int lose;
4699   CORE_ADDR text_addr, data_addr, bss_addr;
4700   struct section_offsets *offs;
4701
4702   putpkt ("qOffsets");
4703
4704   getpkt (buf, 0);
4705
4706   if (buf[0] == '\000')
4707     return;                     /* Return silently.  Stub doesn't support this
4708                                    command. */
4709   if (buf[0] == 'E')
4710     {
4711       warning ("Remote failure reply: %s", buf);
4712       return;
4713     }
4714
4715   /* Pick up each field in turn.  This used to be done with scanf, but
4716      scanf will make trouble if CORE_ADDR size doesn't match
4717      conversion directives correctly.  The following code will work
4718      with any size of CORE_ADDR.  */
4719   text_addr = data_addr = bss_addr = 0;
4720   ptr = buf;
4721   lose = 0;
4722
4723   if (strncmp (ptr, "Text=", 5) == 0)
4724     {
4725       ptr += 5;
4726       /* Don't use strtol, could lose on big values.  */
4727       while (*ptr && *ptr != ';')
4728         text_addr = (text_addr << 4) + fromhex (*ptr++);
4729     }
4730   else
4731     lose = 1;
4732
4733   if (!lose && strncmp (ptr, ";Data=", 6) == 0)
4734     {
4735       ptr += 6;
4736       while (*ptr && *ptr != ';')
4737         data_addr = (data_addr << 4) + fromhex (*ptr++);
4738     }
4739   else
4740     lose = 1;
4741
4742   if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
4743     {
4744       ptr += 5;
4745       while (*ptr && *ptr != ';')
4746         bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4747     }
4748   else
4749     lose = 1;
4750
4751   if (lose)
4752     error ("Malformed response to offset query, %s", buf);
4753
4754   if (symfile_objfile == NULL)
4755     return;
4756
4757   offs = (struct section_offsets *) alloca (sizeof (struct section_offsets)
4758                                             + symfile_objfile->num_sections
4759                                             * sizeof (offs->offsets));
4760   memcpy (offs, symfile_objfile->section_offsets,
4761           sizeof (struct section_offsets)
4762           + symfile_objfile->num_sections
4763           * sizeof (offs->offsets));
4764
4765   ANOFFSET (offs, SECT_OFF_TEXT) = text_addr;
4766
4767   /* This is a temporary kludge to force data and bss to use the same offsets
4768      because that's what nlmconv does now.  The real solution requires changes
4769      to the stub and remote.c that I don't have time to do right now.  */
4770
4771   ANOFFSET (offs, SECT_OFF_DATA) = data_addr;
4772   ANOFFSET (offs, SECT_OFF_BSS) = data_addr;
4773
4774   objfile_relocate (symfile_objfile, offs);
4775 }
4776
4777 /* Stub for catch_errors.  */
4778
4779 static int
4780 remote_start_remote (dummy)
4781      char *dummy;
4782 {
4783   immediate_quit = 1;           /* Allow user to interrupt it */
4784
4785   /* Ack any packet which the remote side has already sent.  */
4786   SERIAL_WRITE (remote_desc, "+", 1);
4787
4788   /* Let the stub know that we want it to return the thread.  */
4789   set_thread (-1, 0);
4790
4791   get_offsets ();               /* Get text, data & bss offsets */
4792
4793   putpkt ("?");                 /* initiate a query from remote machine */
4794   immediate_quit = 0;
4795
4796   start_remote ();              /* Initialize gdb process mechanisms */
4797   return 1;
4798 }
4799
4800 /* Open a connection to a remote debugger.
4801    NAME is the filename used for communication.  */
4802
4803 static void
4804 remote_open (name, from_tty)
4805      char *name;
4806      int from_tty;
4807 {
4808   remote_open_1 (name, from_tty, &remote_ops, 0);
4809 }
4810
4811 /* Open a connection to a remote debugger using the extended
4812    remote gdb protocol.  NAME is the filename used for communication.  */
4813
4814 static void
4815 extended_remote_open (name, from_tty)
4816      char *name;
4817      int from_tty;
4818 {
4819   remote_open_1 (name, from_tty, &extended_remote_ops, 1/*extended_p*/);
4820 }
4821
4822 /* Generic code for opening a connection to a remote target.  */
4823 static DCACHE *remote_dcache;
4824
4825 static void
4826 remote_open_1 (name, from_tty, target, extended_p)
4827      char *name;
4828      int from_tty;
4829      struct target_ops *target;
4830      int extended_p;
4831 {
4832   if (name == 0)
4833     error ("To open a remote debug connection, you need to specify what serial\n\
4834 device is attached to the remote system (e.g. /dev/ttya).");
4835
4836   target_preopen (from_tty);
4837
4838   unpush_target (target);
4839
4840   remote_dcache = dcache_init (remote_read_bytes, remote_write_bytes);
4841
4842   remote_desc = SERIAL_OPEN (name);
4843   if (!remote_desc)
4844     perror_with_name (name);
4845
4846   if (baud_rate != -1)
4847     {
4848       if (SERIAL_SETBAUDRATE (remote_desc, baud_rate))
4849         {
4850           SERIAL_CLOSE (remote_desc);
4851           perror_with_name (name);
4852         }
4853     }
4854
4855
4856   SERIAL_RAW (remote_desc);
4857
4858   /* If there is something sitting in the buffer we might take it as a
4859      response to a command, which would be bad.  */
4860   SERIAL_FLUSH_INPUT (remote_desc);
4861
4862   if (from_tty)
4863     {
4864       puts_filtered ("Remote debugging using ");
4865       puts_filtered (name);
4866       puts_filtered ("\n");
4867     }
4868   push_target (target); /* Switch to using remote target now */
4869
4870   /* Start out by trying the 'P' request to set registers.  We set this each
4871      time that we open a new target so that if the user switches from one
4872      stub to another, we can (if the target is closed and reopened) cope.  */
4873   stub_supports_P = 1;
4874
4875   general_thread = -2;
4876   cont_thread = -2;
4877
4878   /* Without this, some commands which require an active target (such as kill)
4879      won't work.  This variable serves (at least) double duty as both the pid
4880      of the target process (if it has such), and as a flag indicating that a
4881      target is active.  These functions should be split out into seperate
4882      variables, especially since GDB will someday have a notion of debugging
4883      several processes.  */
4884
4885   inferior_pid = 42000;
4886   /* Start the remote connection; if error (0), discard this target.
4887      In particular, if the user quits, be sure to discard it
4888      (we'd be in an inconsistent state otherwise).  */
4889   if (!catch_errors (remote_start_remote, (char *)0, 
4890                      "Couldn't establish connection to remote target\n", RETURN_MASK_ALL))
4891     {
4892       pop_target();
4893       return;
4894     }
4895
4896   if (extended_p)
4897     {
4898       /* tell the remote that we're using the extended protocol.  */
4899       char buf[PBUFSIZ];
4900       putpkt ("!");
4901       getpkt (buf, 0);
4902     }
4903 }
4904
4905 /* This takes a program previously attached to and detaches it.  After
4906    this is done, GDB can be used to debug some other program.  We
4907    better not have left any breakpoints in the target program or it'll
4908    die when it hits one.  */
4909
4910 static void
4911 remote_detach (args, from_tty)
4912      char *args;
4913      int from_tty;
4914 {
4915   char buf[PBUFSIZ];
4916
4917   if (args)
4918     error ("Argument given to \"detach\" when remotely debugging.");
4919
4920   /* Tell the remote target to detach.  */
4921   strcpy (buf, "D");
4922   remote_send (buf);
4923
4924   pop_target ();
4925   if (from_tty)
4926     puts_filtered ("Ending remote debugging.\n");
4927 }
4928
4929 /* Convert hex digit A to a number.  */
4930
4931 int
4932 fromhex (a)
4933      int a;
4934 {
4935   if (a >= '0' && a <= '9')
4936     return a - '0';
4937   else if (a >= 'a' && a <= 'f')
4938     return a - 'a' + 10;
4939   else if (a >= 'A' && a <= 'F')
4940     return a - 'A' + 10;
4941   else 
4942     error ("Reply contains invalid hex digit %d", a);
4943 }
4944
4945 /* Convert number NIB to a hex digit.  */
4946
4947 static int
4948 tohex (nib)
4949      int nib;
4950 {
4951   if (nib < 10)
4952     return '0'+nib;
4953   else
4954     return 'a'+nib-10;
4955 }
4956 \f
4957 /* Tell the remote machine to resume.  */
4958
4959 static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
4960 int last_sent_step;
4961
4962 static void
4963 remote_resume (pid, step, siggnal)
4964      int pid, step;
4965      enum target_signal siggnal;
4966 {
4967   char buf[PBUFSIZ];
4968
4969   if (pid == -1)
4970     set_thread (inferior_pid, 0);
4971   else
4972     set_thread (pid, 0);
4973
4974   dcache_flush (remote_dcache);
4975
4976   last_sent_signal = siggnal;
4977   last_sent_step = step;
4978
4979   /* A hook for when we need to do something at the last moment before
4980      resumption.  */
4981   if (target_resume_hook)
4982     (*target_resume_hook) ();
4983
4984   if (siggnal != TARGET_SIGNAL_0)
4985     {
4986       buf[0] = step ? 'S' : 'C';
4987       buf[1] = tohex (((int)siggnal >> 4) & 0xf);
4988       buf[2] = tohex ((int)siggnal & 0xf);
4989       buf[3] = '\0';
4990     }
4991   else
4992     strcpy (buf, step ? "s": "c");
4993
4994   putpkt (buf);
4995 }
4996 \f
4997 /* Send ^C to target to halt it.  Target will respond, and send us a
4998    packet.  */
4999
5000 static void
5001 remote_interrupt (signo)
5002      int signo;
5003 {
5004   /* If this doesn't work, try more severe steps.  */
5005   signal (signo, remote_interrupt_twice);
5006   
5007   if (remote_debug)
5008     printf_unfiltered ("remote_interrupt called\n");
5009
5010   /* Send a break or a ^C, depending on user preference.  */
5011   if (remote_break)
5012     SERIAL_SEND_BREAK (remote_desc);
5013   else
5014     SERIAL_WRITE (remote_desc, "\003", 1);
5015 }
5016
5017 static void (*ofunc)();
5018
5019 /* The user typed ^C twice.  */
5020 static void
5021 remote_interrupt_twice (signo)
5022      int signo;
5023 {
5024   signal (signo, ofunc);
5025   
5026   interrupt_query ();
5027
5028   signal (signo, remote_interrupt);
5029 }
5030
5031 /* Ask the user what to do when an interrupt is received.  */
5032
5033 static void
5034 interrupt_query ()
5035 {
5036   target_terminal_ours ();
5037
5038   if (query ("Interrupted while waiting for the program.\n\
5039 Give up (and stop debugging it)? "))
5040     {
5041       target_mourn_inferior ();
5042       return_to_top_level (RETURN_QUIT);
5043     }
5044
5045   target_terminal_inferior ();
5046 }
5047
5048 /* If nonzero, ignore the next kill.  */
5049 int kill_kludge;
5050
5051 void
5052 remote_console_output (msg)
5053      char *msg;
5054 {
5055   char *p;
5056
5057   for (p = msg; *p; p +=2) 
5058     {
5059       char tb[2];
5060       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5061       tb[0] = c;
5062       tb[1] = 0;
5063       if (target_output_hook)
5064         target_output_hook (tb);
5065       else 
5066         fputs_filtered (tb, gdb_stdout);
5067     }
5068 }
5069
5070 /* Wait until the remote machine stops, then return,
5071    storing status in STATUS just as `wait' would.
5072    Returns "pid" (though it's not clear what, if anything, that
5073    means in the case of this target).  */
5074
5075 static int
5076 remote_wait (pid, status)
5077      int pid;
5078      struct target_waitstatus *status;
5079 {
5080   unsigned char buf[PBUFSIZ];
5081   int thread_num = -1;
5082
5083   status->kind = TARGET_WAITKIND_EXITED;
5084   status->value.integer = 0;
5085
5086   while (1)
5087     {
5088       unsigned char *p;
5089
5090       ofunc = (void (*)()) signal (SIGINT, remote_interrupt);
5091       getpkt ((char *) buf, 1);
5092       signal (SIGINT, ofunc);
5093
5094       /* This is a hook for when we need to do something (perhaps the
5095          collection of trace data) every time the target stops.  */
5096       if (target_wait_loop_hook)
5097         (*target_wait_loop_hook) ();
5098
5099       switch (buf[0])
5100         {
5101         case 'E':               /* Error of some sort */
5102           warning ("Remote failure reply: %s", buf);
5103           continue;
5104         case 'T':               /* Status with PC, SP, FP, ... */
5105           {
5106             int i;
5107             long regno;
5108             char regs[MAX_REGISTER_RAW_SIZE];
5109
5110             /* Expedited reply, containing Signal, {regno, reg} repeat */
5111             /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
5112                 ss = signal number
5113                 n... = register number
5114                 r... = register contents
5115                 */
5116             p = &buf[3];        /* after Txx */
5117
5118             while (*p)
5119               {
5120                 unsigned char *p1;
5121                 char *p_temp;
5122
5123                 regno = strtol ((const char *) p, &p_temp, 16); /* Read the register number */
5124                 p1 = (unsigned char *)p_temp;
5125
5126                 if (p1 == p)
5127                   {
5128                     p1 = (unsigned char *) strchr ((const char *) p, ':');
5129                     if (p1 == NULL)
5130                       warning ("Malformed packet (missing colon): %s\n\
5131 Packet: '%s'\n",
5132                                p, buf);
5133                     if (strncmp ((const char *) p, "thread", p1 - p) == 0)
5134                       {
5135                         thread_num = strtol ((const char *) ++p1, &p_temp, 16);
5136                         p = (unsigned char *)p_temp;
5137                       }
5138                   }
5139                 else
5140                   {
5141                     p = p1;
5142
5143                     if (*p++ != ':')
5144                       warning ("Malformed packet (missing colon): %s\n\
5145 Packet: '%s'\n",
5146                                p, buf);
5147
5148                     if (regno >= NUM_REGS)
5149                       warning ("Remote sent bad register number %ld: %s\n\
5150 Packet: '%s'\n",
5151                                regno, p, buf);
5152
5153                     for (i = 0; i < REGISTER_RAW_SIZE (regno); i++)
5154                       {
5155                         if (p[0] == 0 || p[1] == 0)
5156                           warning ("Remote reply is too short: %s", buf);
5157                         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
5158                         p += 2;
5159                       }
5160                     supply_register (regno, regs);
5161                   }
5162
5163                 if (*p++ != ';')
5164                   warning ("Remote register badly formatted: %s", buf);
5165               }
5166           }
5167           /* fall through */
5168         case 'S':               /* Old style status, just signal only */
5169           status->kind = TARGET_WAITKIND_STOPPED;
5170           status->value.sig = (enum target_signal)
5171             (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
5172
5173           goto got_status;
5174         case 'W':               /* Target exited */
5175           {
5176             /* The remote process exited.  */
5177             status->kind = TARGET_WAITKIND_EXITED;
5178             status->value.integer = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
5179             goto got_status;
5180           }
5181         case 'X':
5182           status->kind = TARGET_WAITKIND_SIGNALLED;
5183           status->value.sig = (enum target_signal)
5184             (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
5185           kill_kludge = 1;
5186
5187           goto got_status;
5188         case 'O':               /* Console output */
5189           remote_console_output (buf + 1);
5190           continue;
5191         case '\0':
5192           if (last_sent_signal != TARGET_SIGNAL_0)
5193             {
5194               /* Zero length reply means that we tried 'S' or 'C' and
5195                  the remote system doesn't support it.  */
5196               target_terminal_ours_for_output ();
5197               printf_filtered
5198                 ("Can't send signals to this remote system.  %s not sent.\n",
5199                  target_signal_to_name (last_sent_signal));
5200               last_sent_signal = TARGET_SIGNAL_0;
5201               target_terminal_inferior ();
5202
5203               strcpy ((char *) buf, last_sent_step ? "s" : "c");
5204               putpkt ((char *) buf);
5205               continue;
5206             }
5207           /* else fallthrough */
5208         default:
5209           warning ("Invalid remote reply: %s", buf);
5210           continue;
5211         }
5212     }
5213  got_status:
5214   if (thread_num != -1)
5215     {
5216       /* Initial thread value can only be acquired via wait, so deal with
5217          this marker which is used before the first thread value is
5218          acquired.  */
5219       if (inferior_pid == 42000)
5220         {
5221           inferior_pid = thread_num;
5222           add_thread (inferior_pid);
5223         }
5224       return thread_num;
5225     }
5226   return inferior_pid;
5227 }
5228
5229 /* Number of bytes of registers this stub implements.  */
5230 static int register_bytes_found;
5231
5232 /* Read the remote registers into the block REGS.  */
5233 /* Currently we just read all the registers, so we don't use regno.  */
5234 /* ARGSUSED */
5235 static void
5236 remote_fetch_registers (regno)
5237      int regno;
5238 {
5239   char buf[PBUFSIZ];
5240   int i;
5241   char *p;
5242   char regs[REGISTER_BYTES];
5243
5244   set_thread (inferior_pid, 1);
5245
5246   sprintf (buf, "g");
5247   remote_send (buf);
5248
5249   if (remote_register_buf_size == 0)
5250     remote_register_buf_size = strlen (buf);
5251
5252   /* Unimplemented registers read as all bits zero.  */
5253   memset (regs, 0, REGISTER_BYTES);
5254
5255   /* We can get out of synch in various cases.  If the first character
5256      in the buffer is not a hex character, assume that has happened
5257      and try to fetch another packet to read.  */
5258   while ((buf[0] < '0' || buf[0] > '9')
5259          && (buf[0] < 'a' || buf[0] > 'f'))
5260     {
5261       if (remote_debug)
5262         printf_unfiltered ("Bad register packet; fetching a new packet\n");
5263       getpkt (buf, 0);
5264     }
5265
5266   /* Reply describes registers byte by byte, each byte encoded as two
5267      hex characters.  Suck them all up, then supply them to the
5268      register cacheing/storage mechanism.  */
5269
5270   p = buf;
5271   for (i = 0; i < REGISTER_BYTES; i++)
5272     {
5273       if (p[0] == 0)
5274         break;
5275       if (p[1] == 0)
5276         {
5277           warning ("Remote reply is of odd length: %s", buf);
5278           /* Don't change register_bytes_found in this case, and don't
5279              print a second warning.  */
5280           goto supply_them;
5281         }
5282       regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
5283       p += 2;
5284     }
5285
5286   if (i != register_bytes_found)
5287     {
5288       register_bytes_found = i;
5289 #ifdef REGISTER_BYTES_OK
5290       if (!REGISTER_BYTES_OK (i))
5291         warning ("Remote reply is too short: %s", buf);
5292 #endif
5293     }
5294
5295  supply_them:
5296   for (i = 0; i < NUM_REGS; i++)
5297     supply_register (i, &regs[REGISTER_BYTE(i)]);
5298 }
5299
5300 /* Prepare to store registers.  Since we may send them all (using a
5301    'G' request), we have to read out the ones we don't want to change
5302    first.  */
5303
5304 static void 
5305 remote_prepare_to_store ()
5306 {
5307   /* Make sure the entire registers array is valid.  */
5308   read_register_bytes (0, (char *)NULL, REGISTER_BYTES);
5309 }
5310
5311 /* Store register REGNO, or all registers if REGNO == -1, from the contents
5312    of REGISTERS.  FIXME: ignores errors.  */
5313
5314 static void
5315 remote_store_registers (regno)
5316      int regno;
5317 {
5318   char buf[PBUFSIZ];
5319   int i;
5320   char *p;
5321
5322   set_thread (inferior_pid, 1);
5323
5324   if (regno >= 0 && stub_supports_P)
5325     {
5326       /* Try storing a single register.  */
5327       char *regp;
5328
5329       sprintf (buf, "P%x=", regno);
5330       p = buf + strlen (buf);
5331       regp = &registers[REGISTER_BYTE (regno)];
5332       for (i = 0; i < REGISTER_RAW_SIZE (regno); ++i)
5333         {
5334           *p++ = tohex ((regp[i] >> 4) & 0xf);
5335           *p++ = tohex (regp[i] & 0xf);
5336         }
5337       *p = '\0';
5338       remote_send (buf);
5339       if (buf[0] != '\0')
5340         {
5341           /* The stub understands the 'P' request.  We are done.  */
5342           return;
5343         }
5344
5345       /* The stub does not support the 'P' request.  Use 'G' instead,
5346          and don't try using 'P' in the future (it will just waste our
5347          time).  */
5348       stub_supports_P = 0;
5349     }
5350
5351   buf[0] = 'G';
5352
5353   /* Command describes registers byte by byte,
5354      each byte encoded as two hex characters.  */
5355
5356   p = buf + 1;
5357   /* remote_prepare_to_store insures that register_bytes_found gets set.  */
5358   for (i = 0; i < register_bytes_found; i++)
5359     {
5360       *p++ = tohex ((registers[i] >> 4) & 0xf);
5361       *p++ = tohex (registers[i] & 0xf);
5362     }
5363   *p = '\0';
5364
5365   remote_send (buf);
5366 }
5367
5368 /* 
5369    Use of the data cache *used* to be disabled because it loses for looking at
5370    and changing hardware I/O ports and the like.  Accepting `volatile'
5371    would perhaps be one way to fix it.  Another idea would be to use the
5372    executable file for the text segment (for all SEC_CODE sections?
5373    For all SEC_READONLY sections?).  This has problems if you want to
5374    actually see what the memory contains (e.g. self-modifying code,
5375    clobbered memory, user downloaded the wrong thing).  
5376
5377    Because it speeds so much up, it's now enabled, if you're playing
5378    with registers you turn it of (set remotecache 0)
5379 */
5380
5381 /* Read a word from remote address ADDR and return it.
5382    This goes through the data cache.  */
5383
5384 #if 0   /* unused? */
5385 static int
5386 remote_fetch_word (addr)
5387      CORE_ADDR addr;
5388 {
5389   return dcache_fetch (remote_dcache, addr);
5390 }
5391
5392 /* Write a word WORD into remote address ADDR.
5393    This goes through the data cache.  */
5394
5395 static void
5396 remote_store_word (addr, word)
5397      CORE_ADDR addr;
5398      int word;
5399 {
5400   dcache_poke (remote_dcache, addr, word);
5401 }
5402 #endif  /* 0 (unused?) */
5403
5404 \f
5405
5406 /* Return the number of hex digits in num.  */
5407
5408 static int
5409 hexnumlen (num)
5410      ULONGEST num;
5411 {
5412   int i;
5413
5414   for (i = 0; num != 0; i++)
5415     num >>= 4;
5416
5417   return max (i, 1);
5418 }
5419
5420 /* Write memory data directly to the remote machine.
5421    This does not inform the data cache; the data cache uses this.
5422    MEMADDR is the address in the remote memory space.
5423    MYADDR is the address of the buffer in our space.
5424    LEN is the number of bytes.
5425
5426    Returns number of bytes transferred, or 0 for error.  */
5427
5428 static int
5429 remote_write_bytes (memaddr, myaddr, len)
5430      CORE_ADDR memaddr;
5431      char *myaddr;
5432      int len;
5433 {
5434   int max_buf_size;             /* Max size of packet output buffer */
5435   int origlen;
5436
5437   /* Chop the transfer down if necessary */
5438
5439   max_buf_size = min (remote_write_size, PBUFSIZ);
5440   if (remote_register_buf_size != 0)
5441     max_buf_size = min (max_buf_size, remote_register_buf_size);
5442
5443   /* Subtract header overhead from max payload size -  $M<memaddr>,<len>:#nn */
5444   max_buf_size -= 2 + hexnumlen (memaddr + len - 1) + 1 + hexnumlen (len) + 4;
5445
5446   origlen = len;
5447   while (len > 0)
5448     {
5449       char buf[PBUFSIZ];
5450       char *p;
5451       int todo;
5452       int i;
5453
5454       todo = min (len, max_buf_size / 2); /* num bytes that will fit */
5455
5456       /* FIXME-32x64: Need a version of print_address_numeric which puts the
5457          result in a buffer like sprintf.  */
5458       sprintf (buf, "M%lx,%x:", (unsigned long) memaddr, todo);
5459
5460       /* We send target system values byte by byte, in increasing byte addresses,
5461          each byte encoded as two hex characters.  */
5462
5463       p = buf + strlen (buf);
5464       for (i = 0; i < todo; i++)
5465         {
5466           *p++ = tohex ((myaddr[i] >> 4) & 0xf);
5467           *p++ = tohex (myaddr[i] & 0xf);
5468         }
5469       *p = '\0';
5470
5471       putpkt (buf);
5472       getpkt (buf, 0);
5473
5474       if (buf[0] == 'E')
5475         {
5476           /* There is no correspondance between what the remote protocol uses
5477              for errors and errno codes.  We would like a cleaner way of
5478              representing errors (big enough to include errno codes, bfd_error
5479              codes, and others).  But for now just return EIO.  */
5480           errno = EIO;
5481           return 0;
5482         }
5483       myaddr += todo;
5484       memaddr += todo;
5485       len -= todo;
5486     }
5487   return origlen;
5488 }
5489
5490 /* Read memory data directly from the remote machine.
5491    This does not use the data cache; the data cache uses this.
5492    MEMADDR is the address in the remote memory space.
5493    MYADDR is the address of the buffer in our space.
5494    LEN is the number of bytes.
5495
5496    Returns number of bytes transferred, or 0 for error.  */
5497
5498 static int
5499 remote_read_bytes (memaddr, myaddr, len)
5500      CORE_ADDR memaddr;
5501      char *myaddr;
5502      int len;
5503 {
5504   int max_buf_size;             /* Max size of packet output buffer */
5505   int origlen;
5506
5507   /* Chop the transfer down if necessary */
5508
5509   max_buf_size = min (remote_write_size, PBUFSIZ);
5510   if (remote_register_buf_size != 0)
5511     max_buf_size = min (max_buf_size, remote_register_buf_size);
5512
5513   origlen = len;
5514   while (len > 0)
5515     {
5516       char buf[PBUFSIZ];
5517       char *p;
5518       int todo;
5519       int i;
5520
5521       todo = min (len, max_buf_size / 2); /* num bytes that will fit */
5522
5523       /* FIXME-32x64: Need a version of print_address_numeric which puts the
5524          result in a buffer like sprintf.  */
5525       sprintf (buf, "m%lx,%x", (unsigned long) memaddr, todo);
5526       putpkt (buf);
5527       getpkt (buf, 0);
5528
5529       if (buf[0] == 'E')
5530         {
5531           /* There is no correspondance between what the remote protocol uses
5532              for errors and errno codes.  We would like a cleaner way of
5533              representing errors (big enough to include errno codes, bfd_error
5534              codes, and others).  But for now just return EIO.  */
5535           errno = EIO;
5536           return 0;
5537         }
5538
5539   /* Reply describes memory byte by byte,
5540      each byte encoded as two hex characters.  */
5541
5542       p = buf;
5543       for (i = 0; i < todo; i++)
5544         {
5545           if (p[0] == 0 || p[1] == 0)
5546             /* Reply is short.  This means that we were able to read only part
5547                of what we wanted to.  */
5548             return i + (origlen - len);
5549           myaddr[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
5550           p += 2;
5551         }
5552       myaddr += todo;
5553       memaddr += todo;
5554       len -= todo;
5555     }
5556   return origlen;
5557 }
5558 \f
5559 /* Read or write LEN bytes from inferior memory at MEMADDR, transferring
5560    to or from debugger address MYADDR.  Write to inferior if SHOULD_WRITE is
5561    nonzero.  Returns length of data written or read; 0 for error.  */
5562
5563 /* ARGSUSED */
5564 static int
5565 remote_xfer_memory(memaddr, myaddr, len, should_write, target)
5566      CORE_ADDR memaddr;
5567      char *myaddr;
5568      int len;
5569      int should_write;
5570      struct target_ops *target;                 /* ignored */
5571 {
5572 #ifdef REMOTE_TRANSLATE_XFER_ADDRESS
5573   CORE_ADDR targaddr;
5574   int targlen;
5575   REMOTE_TRANSLATE_XFER_ADDRESS (memaddr, len, targaddr, targlen);
5576   if (targlen == 0)
5577     return 0;
5578   memaddr = targaddr;
5579   len = targlen;
5580 #endif
5581
5582   return dcache_xfer_memory (remote_dcache, memaddr, myaddr, len, should_write);
5583 }
5584
5585    
5586 #if 0
5587 /* Enable after 4.12.  */
5588
5589 void
5590 remote_search (len, data, mask, startaddr, increment, lorange, hirange
5591                addr_found, data_found)
5592      int len;
5593      char *data;
5594      char *mask;
5595      CORE_ADDR startaddr;
5596      int increment;
5597      CORE_ADDR lorange;
5598      CORE_ADDR hirange;
5599      CORE_ADDR *addr_found;
5600      char *data_found;
5601 {
5602   if (increment == -4 && len == 4)
5603     {
5604       long mask_long, data_long;
5605       long data_found_long;
5606       CORE_ADDR addr_we_found;
5607       char buf[PBUFSIZ];
5608       long returned_long[2];
5609       char *p;
5610
5611       mask_long = extract_unsigned_integer (mask, len);
5612       data_long = extract_unsigned_integer (data, len);
5613       sprintf (buf, "t%x:%x,%x", startaddr, data_long, mask_long);
5614       putpkt (buf);
5615       getpkt (buf, 0);
5616       if (buf[0] == '\0')
5617         {
5618           /* The stub doesn't support the 't' request.  We might want to
5619              remember this fact, but on the other hand the stub could be
5620              switched on us.  Maybe we should remember it only until
5621              the next "target remote".  */
5622           generic_search (len, data, mask, startaddr, increment, lorange,
5623                           hirange, addr_found, data_found);
5624           return;
5625         }
5626
5627       if (buf[0] == 'E')
5628         /* There is no correspondance between what the remote protocol uses
5629            for errors and errno codes.  We would like a cleaner way of
5630            representing errors (big enough to include errno codes, bfd_error
5631            codes, and others).  But for now just use EIO.  */
5632         memory_error (EIO, startaddr);
5633       p = buf;
5634       addr_we_found = 0;
5635       while (*p != '\0' && *p != ',')
5636         addr_we_found = (addr_we_found << 4) + fromhex (*p++);
5637       if (*p == '\0')
5638         error ("Protocol error: short return for search");
5639
5640       data_found_long = 0;
5641       while (*p != '\0' && *p != ',')
5642         data_found_long = (data_found_long << 4) + fromhex (*p++);
5643       /* Ignore anything after this comma, for future extensions.  */
5644
5645       if (addr_we_found < lorange || addr_we_found >= hirange)
5646         {
5647           *addr_found = 0;
5648           return;
5649         }
5650
5651       *addr_found = addr_we_found;
5652       *data_found = store_unsigned_integer (data_we_found, len);
5653       return;
5654     }
5655   generic_search (len, data, mask, startaddr, increment, lorange,
5656                   hirange, addr_found, data_found);
5657 }
5658 #endif /* 0 */
5659 \f
5660 static void
5661 remote_files_info (ignore)
5662      struct target_ops *ignore;
5663 {
5664   puts_filtered ("Debugging a target over a serial line.\n");
5665 }
5666 \f
5667 /* Stuff for dealing with the packets which are part of this protocol.
5668    See comment at top of file for details.  */
5669
5670 /* Read a single character from the remote end, masking it down to 7 bits. */
5671
5672 static int
5673 readchar (timeout)
5674      int timeout;
5675 {
5676   int ch;
5677
5678   ch = SERIAL_READCHAR (remote_desc, timeout);
5679
5680   switch (ch)
5681     {
5682     case SERIAL_EOF:
5683       error ("Remote connection closed");
5684     case SERIAL_ERROR:
5685       perror_with_name ("Remote communication error");
5686     case SERIAL_TIMEOUT:
5687       return ch;
5688     default:
5689       return ch & 0x7f;
5690     }
5691 }
5692
5693 /* Send the command in BUF to the remote machine,
5694    and read the reply into BUF.
5695    Report an error if we get an error reply.  */
5696
5697 static void
5698 remote_send (buf)
5699      char *buf;
5700 {
5701   putpkt (buf);
5702   getpkt (buf, 0);
5703
5704   if (buf[0] == 'E')
5705     error ("Remote failure reply: %s", buf);
5706 }
5707
5708 /* Send a packet to the remote machine, with error checking.
5709    The data of the packet is in BUF.  */
5710
5711 int
5712 putpkt (buf)
5713      char *buf;
5714 {
5715   int i;
5716   unsigned char csum = 0;
5717   char buf2[PBUFSIZ];
5718   int cnt = strlen (buf);
5719   int ch;
5720   int tcount = 0;
5721   char *p;
5722
5723   /* Copy the packet into buffer BUF2, encapsulating it
5724      and giving it a checksum.  */
5725
5726   if (cnt > (int) sizeof (buf2) - 5)            /* Prosanity check */
5727     abort();
5728
5729   p = buf2;
5730   *p++ = '$';
5731
5732   for (i = 0; i < cnt; i++)
5733     {
5734       csum += buf[i];
5735       *p++ = buf[i];
5736     }
5737   *p++ = '#';
5738   *p++ = tohex ((csum >> 4) & 0xf);
5739   *p++ = tohex (csum & 0xf);
5740
5741   /* Send it over and over until we get a positive ack.  */
5742
5743   while (1)
5744     {
5745       int started_error_output = 0;
5746
5747       if (remote_debug)
5748         {
5749           *p = '\0';
5750           printf_unfiltered ("Sending packet: %s...", buf2);
5751           gdb_flush(gdb_stdout);
5752         }
5753       if (SERIAL_WRITE (remote_desc, buf2, p - buf2))
5754         perror_with_name ("putpkt: write failed");
5755
5756       /* read until either a timeout occurs (-2) or '+' is read */
5757       while (1)
5758         {
5759           ch = readchar (remote_timeout);
5760
5761           if (remote_debug)
5762             {
5763               switch (ch)
5764                 {
5765                 case '+':
5766                 case SERIAL_TIMEOUT:
5767                 case '$':
5768                   if (started_error_output)
5769                     {
5770                       putchar_unfiltered ('\n');
5771                       started_error_output = 0;
5772                     }
5773                 }
5774             }
5775
5776           switch (ch)
5777             {
5778             case '+':
5779               if (remote_debug)
5780                 printf_unfiltered("Ack\n");
5781               return 1;
5782             case SERIAL_TIMEOUT:
5783               tcount ++;
5784               if (tcount > 3)
5785                 return 0;
5786               break;            /* Retransmit buffer */
5787             case '$':
5788               {
5789                 char junkbuf[PBUFSIZ];
5790
5791               /* It's probably an old response, and we're out of sync.  Just
5792                  gobble up the packet and ignore it.  */
5793                 getpkt (junkbuf, 0);
5794                 continue;               /* Now, go look for + */
5795               }
5796             default:
5797               if (remote_debug)
5798                 {
5799                   if (!started_error_output)
5800                     {
5801                       started_error_output = 1;
5802                       printf_unfiltered ("putpkt: Junk: ");
5803                     }
5804                   putchar_unfiltered (ch & 0177);
5805                 }
5806               continue;
5807             }
5808           break;                /* Here to retransmit */
5809         }
5810
5811 #if 0
5812       /* This is wrong.  If doing a long backtrace, the user should be
5813          able to get out next time we call QUIT, without anything as violent
5814          as interrupt_query.  If we want to provide a way out of here
5815          without getting to the next QUIT, it should be based on hitting
5816          ^C twice as in remote_wait.  */
5817       if (quit_flag)
5818         {
5819           quit_flag = 0;
5820           interrupt_query ();
5821         }
5822 #endif
5823     }
5824 }
5825
5826 /* Come here after finding the start of the frame.  Collect the rest into BUF,
5827    verifying the checksum, length, and handling run-length compression.
5828    Returns 0 on any error, 1 on success.  */
5829
5830 static int
5831 read_frame (buf)
5832      char *buf;
5833 {
5834   unsigned char csum;
5835   char *bp;
5836   int c;
5837
5838   csum = 0;
5839   bp = buf;
5840
5841   while (1)
5842     {
5843       c = readchar (remote_timeout);
5844
5845       switch (c)
5846         {
5847         case SERIAL_TIMEOUT:
5848           if (remote_debug)
5849             puts_filtered ("Timeout in mid-packet, retrying\n");
5850           return 0;
5851         case '$':
5852           if (remote_debug)
5853             puts_filtered ("Saw new packet start in middle of old one\n");
5854           return 0;             /* Start a new packet, count retries */
5855         case '#':
5856           {
5857             unsigned char pktcsum;
5858
5859             *bp = '\000';
5860
5861             pktcsum = fromhex (readchar (remote_timeout)) << 4;
5862             pktcsum |= fromhex (readchar (remote_timeout));
5863
5864             if (csum == pktcsum)
5865               return 1;
5866
5867             if (remote_debug) 
5868               {
5869                 printf_filtered ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=",
5870                                  pktcsum, csum);
5871                 puts_filtered (buf);
5872                 puts_filtered ("\n");
5873               }
5874             return 0;
5875           }
5876         case '*':               /* Run length encoding */
5877           csum += c;
5878           c = readchar (remote_timeout);
5879           csum += c;
5880           c = c - ' ' + 3;      /* Compute repeat count */
5881
5882
5883           if (c > 0 && c < 255 && bp + c - 1 < buf + PBUFSIZ - 1)
5884             {
5885               memset (bp, *(bp - 1), c);
5886               bp += c;
5887               continue;
5888             }
5889
5890           *bp = '\0';
5891           printf_filtered ("Repeat count %d too large for buffer: ", c);
5892           puts_filtered (buf);
5893           puts_filtered ("\n");
5894           return 0;
5895
5896         default:
5897           if (bp < buf + PBUFSIZ - 1)
5898             {
5899               *bp++ = c;
5900               csum += c;
5901               continue;
5902             }
5903
5904           *bp = '\0';
5905           puts_filtered ("Remote packet too long: ");
5906           puts_filtered (buf);
5907           puts_filtered ("\n");
5908
5909           return 0;
5910         }
5911     }
5912 }
5913
5914 /* Read a packet from the remote machine, with error checking,
5915    and store it in BUF.  BUF is expected to be of size PBUFSIZ.
5916    If FOREVER, wait forever rather than timing out; this is used
5917    while the target is executing user code.  */
5918
5919 void
5920 getpkt (buf, forever)
5921      char *buf;
5922      int forever;
5923 {
5924   int c;
5925   int tries;
5926   int timeout;
5927   int val;
5928
5929   strcpy (buf,"timeout");
5930
5931   if (forever)
5932     {
5933 #ifdef MAINTENANCE_CMDS
5934       timeout = watchdog > 0 ? watchdog : -1;
5935 #else
5936       timeout = -1;
5937 #endif
5938     }
5939
5940   else
5941     timeout = remote_timeout;
5942
5943 #define MAX_TRIES 3
5944
5945   for (tries = 1; tries <= MAX_TRIES; tries++)
5946     {
5947       /* This can loop forever if the remote side sends us characters
5948          continuously, but if it pauses, we'll get a zero from readchar
5949          because of timeout.  Then we'll count that as a retry.  */
5950
5951       /* Note that we will only wait forever prior to the start of a packet.
5952          After that, we expect characters to arrive at a brisk pace.  They
5953          should show up within remote_timeout intervals.  */
5954
5955       do
5956         {
5957           c = readchar (timeout);
5958
5959           if (c == SERIAL_TIMEOUT)
5960             {
5961 #ifdef MAINTENANCE_CMDS
5962               if (forever)      /* Watchdog went off.  Kill the target. */
5963                 {
5964                   target_mourn_inferior ();
5965                   error ("Watchdog has expired.  Target detached.\n");
5966                 }
5967 #endif
5968               if (remote_debug)
5969                 puts_filtered ("Timed out.\n");
5970               goto retry;
5971             }
5972         }
5973       while (c != '$');
5974
5975       /* We've found the start of a packet, now collect the data.  */
5976
5977       val = read_frame (buf);
5978
5979       if (val == 1)
5980         {
5981           if (remote_debug)
5982             fprintf_unfiltered (gdb_stdout, "Packet received: %s\n", buf);
5983           SERIAL_WRITE (remote_desc, "+", 1);
5984           return;
5985         }
5986
5987       /* Try the whole thing again.  */
5988     retry:
5989       SERIAL_WRITE (remote_desc, "-", 1);
5990     }
5991
5992   /* We have tried hard enough, and just can't receive the packet.  Give up. */
5993
5994   printf_unfiltered ("Ignoring packet error, continuing...\n");
5995   SERIAL_WRITE (remote_desc, "+", 1);
5996 }
5997 \f
5998 static void
5999 remote_kill ()
6000 {
6001   /* For some mysterious reason, wait_for_inferior calls kill instead of
6002      mourn after it gets TARGET_WAITKIND_SIGNALLED.  Work around it.  */
6003   if (kill_kludge)
6004     {
6005       kill_kludge = 0;
6006       target_mourn_inferior ();
6007       return;
6008     }
6009
6010   /* Use catch_errors so the user can quit from gdb even when we aren't on
6011      speaking terms with the remote system.  */
6012   catch_errors (putpkt, "k", "", RETURN_MASK_ERROR);
6013
6014   /* Don't wait for it to die.  I'm not really sure it matters whether
6015      we do or not.  For the existing stubs, kill is a noop.  */
6016   target_mourn_inferior ();
6017 }
6018
6019 static void
6020 remote_mourn ()
6021 {
6022   remote_mourn_1 (&remote_ops);
6023 }
6024
6025 static void
6026 extended_remote_mourn ()
6027 {
6028   /* We do _not_ want to mourn the target like this; this will
6029      remove the extended remote target  from the target stack,
6030      and the next time the user says "run" it'll fail. 
6031
6032      FIXME: What is the right thing to do here?  */
6033 #if 0
6034   remote_mourn_1 (&extended_remote_ops);
6035 #endif
6036 }
6037
6038 /* Worker function for remote_mourn.  */
6039 static void
6040 remote_mourn_1 (target)
6041      struct target_ops *target;
6042 {
6043   unpush_target (target);
6044   generic_mourn_inferior ();
6045 }
6046
6047 /* In the extended protocol we want to be able to do things like
6048    "run" and have them basically work as expected.  So we need
6049    a special create_inferior function. 
6050
6051    FIXME: One day add support for changing the exec file
6052    we're debugging, arguments and an environment.  */
6053
6054 static void
6055 extended_remote_create_inferior (exec_file, args, env)
6056      char *exec_file;
6057      char *args;
6058      char **env;
6059 {
6060   /* Rip out the breakpoints; we'll reinsert them after restarting
6061      the remote server.  */
6062   remove_breakpoints ();
6063
6064   /* Now restart the remote server.  */
6065   extended_remote_restart ();
6066
6067   /* Now put the breakpoints back in.  This way we're safe if the
6068      restart function works via a unix fork on the remote side.  */
6069   insert_breakpoints ();
6070
6071   /* Clean up from the last time we were running.  */
6072   clear_proceed_status ();
6073
6074   /* Let the remote process run.  */
6075   proceed (-1, TARGET_SIGNAL_0, 0);
6076 }
6077
6078 \f
6079 /* On some machines, e.g. 68k, we may use a different breakpoint instruction
6080    than other targets; in those use REMOTE_BREAKPOINT instead of just
6081    BREAKPOINT.  Also, bi-endian targets may define LITTLE_REMOTE_BREAKPOINT
6082    and BIG_REMOTE_BREAKPOINT.  If none of these are defined, we just call
6083    the standard routines that are in mem-break.c.  */
6084
6085 /* FIXME, these ought to be done in a more dynamic fashion.  For instance,
6086    the choice of breakpoint instruction affects target program design and
6087    vice versa, and by making it user-tweakable, the special code here
6088    goes away and we need fewer special GDB configurations.  */
6089
6090 #if defined (LITTLE_REMOTE_BREAKPOINT) && defined (BIG_REMOTE_BREAKPOINT) && !defined(REMOTE_BREAKPOINT)
6091 #define REMOTE_BREAKPOINT
6092 #endif
6093
6094 #ifdef REMOTE_BREAKPOINT
6095
6096 /* If the target isn't bi-endian, just pretend it is.  */
6097 #if !defined (LITTLE_REMOTE_BREAKPOINT) && !defined (BIG_REMOTE_BREAKPOINT)
6098 #define LITTLE_REMOTE_BREAKPOINT REMOTE_BREAKPOINT
6099 #define BIG_REMOTE_BREAKPOINT REMOTE_BREAKPOINT
6100 #endif
6101
6102 static unsigned char big_break_insn[] = BIG_REMOTE_BREAKPOINT;
6103 static unsigned char little_break_insn[] = LITTLE_REMOTE_BREAKPOINT;
6104
6105 #endif /* REMOTE_BREAKPOINT */
6106
6107 /* Insert a breakpoint on targets that don't have any better breakpoint
6108    support.  We read the contents of the target location and stash it,
6109    then overwrite it with a breakpoint instruction.  ADDR is the target
6110    location in the target machine.  CONTENTS_CACHE is a pointer to 
6111    memory allocated for saving the target contents.  It is guaranteed
6112    by the caller to be long enough to save sizeof BREAKPOINT bytes (this
6113    is accomplished via BREAKPOINT_MAX).  */
6114
6115 static int
6116 remote_insert_breakpoint (addr, contents_cache)
6117      CORE_ADDR addr;
6118      char *contents_cache;
6119 {
6120 #ifdef REMOTE_BREAKPOINT
6121   int val;
6122
6123   val = target_read_memory (addr, contents_cache, sizeof big_break_insn);
6124
6125   if (val == 0)
6126     {
6127       if (TARGET_BYTE_ORDER == BIG_ENDIAN)
6128         val = target_write_memory (addr, (char *) big_break_insn,
6129                                    sizeof big_break_insn);
6130       else
6131         val = target_write_memory (addr, (char *) little_break_insn,
6132                                    sizeof little_break_insn);
6133     }
6134
6135   return val;
6136 #else
6137   return memory_insert_breakpoint (addr, contents_cache);
6138 #endif /* REMOTE_BREAKPOINT */
6139 }
6140
6141 static int
6142 remote_remove_breakpoint (addr, contents_cache)
6143      CORE_ADDR addr;
6144      char *contents_cache;
6145 {
6146 #ifdef REMOTE_BREAKPOINT
6147   return target_write_memory (addr, contents_cache, sizeof big_break_insn);
6148 #else
6149   return memory_remove_breakpoint (addr, contents_cache);
6150 #endif /* REMOTE_BREAKPOINT */
6151 }
6152
6153 /* Some targets are only capable of doing downloads, and afterwards they switch
6154    to the remote serial protocol.  This function provides a clean way to get
6155    from the download target to the remote target.  It's basically just a
6156    wrapper so that we don't have to expose any of the internal workings of
6157    remote.c.
6158
6159    Prior to calling this routine, you should shutdown the current target code,
6160    else you will get the "A program is being debugged already..." message.
6161    Usually a call to pop_target() suffices.
6162 */
6163
6164 void
6165 push_remote_target (name, from_tty)
6166      char *name;
6167      int from_tty;
6168 {
6169   printf_filtered ("Switching to remote protocol\n");
6170   remote_open (name, from_tty);
6171 }
6172
6173 /* Other targets want to use the entire remote serial module but with
6174    certain remote_ops overridden. */
6175
6176 void
6177 open_remote_target (name, from_tty, target, extended_p)
6178      char *name;
6179      int from_tty;
6180      struct target_ops *target;
6181      int extended_p;
6182 {
6183   printf_filtered ("Selecting the %sremote protocol\n",
6184                    (extended_p ? "extended-" : ""));
6185   remote_open_1 (name, from_tty, target, extended_p);
6186 }
6187
6188 /* Table used by the crc32 function to calcuate the checksum. */
6189 static unsigned long crc32_table[256] = {0, 0};
6190
6191 static unsigned long
6192 crc32 (buf, len, crc)
6193      unsigned char *buf;
6194      int len;
6195      unsigned int crc;
6196 {
6197   if (! crc32_table[1])
6198     {
6199       /* Initialize the CRC table and the decoding table. */
6200       int i, j;
6201       unsigned int c;
6202
6203       for (i = 0; i < 256; i++)
6204         {
6205           for (c = i << 24, j = 8; j > 0; --j)
6206             c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
6207           crc32_table[i] = c;
6208         }
6209     }
6210
6211   while (len--)
6212     {
6213       crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
6214       buf++;
6215     }
6216   return crc;
6217 }
6218
6219 /* compare-sections command
6220
6221    With no arguments, compares each loadable section in the exec bfd
6222    with the same memory range on the target, and reports mismatches.
6223    Useful for verifying the image on the target against the exec file.
6224    Depends on the target understanding the new "qCRC:" request.  */
6225
6226 static void
6227 remote_compare_command (args, from_tty)
6228      char *args;
6229      int from_tty;
6230 {
6231   asection *s;
6232   unsigned long host_crc, target_crc;
6233   extern bfd *exec_bfd;
6234   struct cleanup *old_chain;
6235   char *tmp, *sectdata, *sectname, buf[PBUFSIZ];
6236   bfd_size_type size;
6237   bfd_vma lma;
6238   int matched = 0;
6239
6240   if (!exec_bfd)
6241     error ("command cannot be used without an exec file");
6242   if (!current_target.to_shortname ||
6243       strcmp (current_target.to_shortname, "remote") != 0)
6244     error ("command can only be used with remote target");
6245
6246   for (s = exec_bfd->sections; s; s = s->next) 
6247     {
6248       if (!(s->flags & SEC_LOAD))
6249         continue;       /* skip non-loadable section */
6250
6251       size = bfd_get_section_size_before_reloc (s);
6252       if (size == 0)
6253         continue;       /* skip zero-length section */
6254
6255       sectname = (char *) bfd_get_section_name (exec_bfd, s);
6256       if (args && strcmp (args, sectname) != 0)
6257         continue;       /* not the section selected by user */
6258
6259       matched = 1;      /* do this section */
6260       lma = s->lma;
6261       /* FIXME: assumes lma can fit into long */
6262       sprintf (buf, "qCRC:%lx,%lx", (long) lma, (long) size);
6263       putpkt (buf);
6264
6265       /* be clever; compute the host_crc before waiting for target reply */
6266       sectdata = xmalloc (size);
6267       old_chain = make_cleanup (free, sectdata);
6268       bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
6269       host_crc = crc32 ((unsigned char *) sectdata, size, 0xffffffff);
6270
6271       getpkt (buf, 0);
6272       if (buf[0] == 'E')
6273         error ("target memory fault, section %s, range 0x%08x -- 0x%08x",
6274                sectname, lma, lma + size);
6275       if (buf[0] != 'C')
6276         error ("remote target does not support this operation");
6277
6278       for (target_crc = 0, tmp = &buf[1]; *tmp; tmp++)
6279         target_crc = target_crc * 16 + fromhex (*tmp);
6280
6281       printf_filtered ("Section %s, range 0x%08x -- 0x%08x: ",
6282                        sectname, lma, lma + size);
6283       if (host_crc == target_crc)
6284         printf_filtered ("matched.\n");
6285       else
6286         printf_filtered ("MIS-MATCHED!\n");
6287
6288       do_cleanups (old_chain);
6289     }
6290   if (args && !matched)
6291     printf_filtered ("No loaded section named '%s'.\n", args);
6292 }
6293
6294 /* reload command
6295
6296    With no arguments, compares each loadable section on the target 
6297    with the binary image in the current exec bfd.  Sections that 
6298    are not identical are downloaded to the target.  Depends on the
6299    target understanding the "qCRC:" request.
6300
6301    Optionally accepts the name of a section as an argument, and
6302    downloads that section; in this case no comparison is done --
6303    the section is downloaded unconditionally.  */
6304
6305 static void
6306 remote_reload_command (args, from_tty)
6307      char *args;
6308      int from_tty;
6309 {
6310   asection *s;
6311   unsigned long host_crc, target_crc;
6312   extern bfd *exec_bfd;
6313   struct cleanup *old_chain;
6314   char *tmp, *sectdata, *sectname, buf[PBUFSIZ];
6315   bfd_size_type size;
6316   bfd_vma lma;
6317   unsigned long sent, len, l;
6318   int matched = 0;
6319   int err;
6320
6321   if (!exec_bfd)
6322     error ("command cannot be used without an exec file");
6323
6324   for (s = exec_bfd->sections; s; s = s->next) 
6325     {
6326       if (!(s->flags & SEC_LOAD))
6327         continue;       /* skip non-loadable section */
6328
6329       size = bfd_get_section_size_before_reloc (s);
6330       if (size == 0)
6331         continue;       /* skip zero-length section */
6332
6333       sectname = (char *) bfd_get_section_name (exec_bfd, s);
6334       if (args && strcmp (args, sectname) != 0)
6335         continue;       /* not the section selected by user */
6336
6337       matched = 1;      /* do this section */
6338       lma = s->lma;
6339       sectdata = xmalloc (size);
6340       old_chain = make_cleanup (free, sectdata);
6341       bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
6342
6343       if (args == 0)
6344         {
6345           /*
6346            * Compare all sections, and reload those that don't match.
6347            */
6348
6349           if (!current_target.to_shortname ||
6350               strcmp (current_target.to_shortname, "remote") != 0)
6351             error ("command can only be used with remote target");
6352
6353           /* FIXME: assumes lma can fit into long */
6354           sprintf (buf, "qCRC:%lx,%lx", (long) lma, (long) size);
6355           putpkt (buf);
6356
6357           /* be clever; compute the host_crc before waiting for target reply */
6358           host_crc = crc32 ((unsigned char *) sectdata, size, 0xffffffff);
6359
6360           getpkt (buf, 0);
6361           if (buf[0] == 'E')
6362             error ("target memory fault, section %s, range 0x%08x -- 0x%08x",
6363                    sectname, lma, lma + size);
6364           if (buf[0] != 'C')
6365             error ("remote target does not support this operation");
6366
6367           for (target_crc = 0, tmp = &buf[1]; *tmp; tmp++)
6368             target_crc = target_crc * 16 + fromhex (*tmp);
6369         }
6370
6371       printf_filtered ("Section %s, range 0x%08x -- 0x%08x: ",
6372                        sectname, lma, lma + size);
6373
6374       if (args != 0 ||  /* section specified -- reload unconditionally */
6375           host_crc != target_crc)       /* section changed on target   */
6376         {
6377           printf_filtered ("being reloaded now.\n");
6378           l = size / 100;
6379           l = l > 100 ? l : 100;        /* chunk size; at least 100 */
6380           sent = 0;
6381           do 
6382             {
6383               len = (size - sent) < l ? (size - sent) : l;
6384               sent += len;
6385               err = target_write_memory (lma, sectdata, len);
6386               lma += len;
6387               sectdata += len;
6388             }
6389           while (err == 0 && sent < size);
6390         }
6391       else
6392         printf_filtered ("unchanged.\n");
6393
6394       do_cleanups (old_chain);
6395     }
6396   if (args && !matched)
6397     printf_filtered ("No loaded section named '%s'.\n", args);
6398 }
6399
6400 void
6401 _initialize_remote ()
6402 {
6403   init_remote_ops() ;
6404   init_extended_remote_ops() ;
6405   add_target (&remote_ops);
6406   add_target (&extended_remote_ops);
6407
6408   add_cmd ("compare-sections", class_obscure, remote_compare_command, 
6409            "Compare section data on remote target to the exec file.\n\
6410 Optional argument is a single section name (default: all loadable sections).", 
6411            &cmdlist);
6412
6413   add_show_from_set (add_set_cmd ("remotetimeout", no_class,
6414                                   var_integer, (char *)&remote_timeout,
6415                                   "Set timeout value for remote read.\n", &setlist),
6416                      &showlist);
6417
6418   add_show_from_set (add_set_cmd ("remotebreak", no_class,
6419                                   var_integer, (char *)&remote_break,
6420                                   "Set whether to send break if interrupted.\n", &setlist),
6421                      &showlist);
6422
6423   add_show_from_set (add_set_cmd ("remotewritesize", no_class,
6424                                   var_integer, (char *)&remote_write_size,
6425                                   "Set the maximum number of bytes in each memory write packet.\n", &setlist),
6426                      &showlist);
6427 }