Include string.h in common-defs.h
[platform/upstream/binutils.git] / gdb / remote-mips.c
1 /* Remote debugging interface for MIPS remote debugging protocol.
2
3    Copyright (C) 1993-2014 Free Software Foundation, Inc.
4
5    Contributed by Cygnus Support.  Written by Ian Lance Taylor
6    <ian@cygnus.com>.
7
8    This file is part of GDB.
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
22
23 #include "defs.h"
24 #include "inferior.h"
25 #include "infrun.h"
26 #include "bfd.h"
27 #include "symfile.h"
28 #include "gdbcmd.h"
29 #include "gdbcore.h"
30 #include "serial.h"
31 #include "target.h"
32 #include "exceptions.h"
33 #include <sys/stat.h>
34 #include "gdb_usleep.h"
35 #include "regcache.h"
36 #include <ctype.h>
37 #include "mips-tdep.h"
38 #include "gdbthread.h"
39 #include "gdb_bfd.h"
40 \f
41
42 /* Breakpoint types.  Values 0, 1, and 2 must agree with the watch
43    types passed by breakpoint.c to target_insert_watchpoint.
44    Value 3 is our own invention, and is used for ordinary instruction
45    breakpoints.  Value 4 is used to mark an unused watchpoint in tables.  */
46 enum break_type
47   {
48     BREAK_WRITE,                /* 0 */
49     BREAK_READ,                 /* 1 */
50     BREAK_ACCESS,               /* 2 */
51     BREAK_FETCH,                /* 3 */
52     BREAK_UNUSED                /* 4 */
53   };
54
55 /* Prototypes for local functions.  */
56
57 static int mips_readchar (int timeout);
58
59 static int mips_receive_header (unsigned char *hdr, int *pgarbage,
60                                 int ch, int timeout);
61
62 static int mips_receive_trailer (unsigned char *trlr, int *pgarbage,
63                                  int *pch, int timeout);
64
65 static int mips_cksum (const unsigned char *hdr,
66                        const char *data, int len);
67
68 static void mips_send_packet (const char *s, int get_ack);
69
70 static void mips_send_command (const char *cmd, int prompt);
71
72 static int mips_receive_packet (char *buff, int throw_error, int timeout);
73
74 static ULONGEST mips_request (int cmd, ULONGEST addr, ULONGEST data,
75                               int *perr, int timeout, char *buff);
76
77 static void mips_initialize (void);
78
79 static void mips_close (struct target_ops *self);
80
81 static int mips_map_regno (struct gdbarch *, int);
82
83 static void mips_set_register (int regno, ULONGEST value);
84
85 static void mips_prepare_to_store (struct target_ops *self,
86                                    struct regcache *regcache);
87
88 static int mips_fetch_word (CORE_ADDR addr, unsigned int *valp);
89
90 static int mips_store_word (CORE_ADDR addr, unsigned int value,
91                             int *old_contents);
92
93 static enum target_xfer_status mips_xfer_memory (gdb_byte *readbuf,
94                                                  const gdb_byte *writebuf,
95                                                  ULONGEST memaddr,
96                                                  ULONGEST len,
97                                                  ULONGEST *xfered_len);
98
99 static void mips_files_info (struct target_ops *ignore);
100
101 static void mips_mourn_inferior (struct target_ops *ops);
102
103 static int pmon_makeb64 (unsigned long v, char *p, int n, unsigned int *chksum);
104
105 static int pmon_zeroset (int recsize, char **buff, unsigned int *amount,
106                          unsigned int *chksum);
107
108 static int pmon_checkset (int recsize, char **buff, unsigned int *value);
109
110 static void pmon_make_fastrec (char **outbuf, unsigned char *inbuf,
111                                int *inptr, int inamount, int *recsize,
112                                unsigned int *csum, unsigned int *zerofill);
113
114 static int pmon_check_ack (char *mesg);
115
116 static void pmon_start_download (void);
117
118 static void pmon_end_download (int final, int bintotal);
119
120 static void pmon_download (char *buffer, int length);
121
122 static void mips_load (struct target_ops *self, const char *file, int from_tty);
123
124 static int mips_make_srec (char *buffer, int type, CORE_ADDR memaddr,
125                            unsigned char *myaddr, int len);
126
127 static int mips_set_breakpoint (CORE_ADDR addr, int len, enum break_type type);
128
129 static int mips_clear_breakpoint (CORE_ADDR addr, int len,
130                                   enum break_type type);
131
132 static int mips_common_breakpoint (int set, CORE_ADDR addr, int len,
133                                    enum break_type type);
134
135 /* Forward declarations.  */
136 extern struct target_ops mips_ops;
137 extern struct target_ops pmon_ops;
138 extern struct target_ops ddb_ops;
139 extern struct target_ops rockhopper_ops;
140 \f/* *INDENT-OFF* */
141 /* The MIPS remote debugging interface is built on top of a simple
142    packet protocol.  Each packet is organized as follows:
143
144    SYN  The first character is always a SYN (ASCII 026, or ^V).  SYN
145    may not appear anywhere else in the packet.  Any time a SYN is
146    seen, a new packet should be assumed to have begun.
147
148    TYPE_LEN
149    This byte contains the upper five bits of the logical length
150    of the data section, plus a single bit indicating whether this
151    is a data packet or an acknowledgement.  The documentation
152    indicates that this bit is 1 for a data packet, but the actual
153    board uses 1 for an acknowledgement.  The value of the byte is
154    0x40 + (ack ? 0x20 : 0) + (len >> 6)
155    (we always have 0 <= len < 1024).  Acknowledgement packets do
156    not carry data, and must have a data length of 0.
157
158    LEN1 This byte contains the lower six bits of the logical length of
159    the data section.  The value is
160    0x40 + (len & 0x3f)
161
162    SEQ  This byte contains the six bit sequence number of the packet.
163    The value is
164    0x40 + seq
165    An acknowlegment packet contains the sequence number of the
166    packet being acknowledged plus 1 modulo 64.  Data packets are
167    transmitted in sequence.  There may only be one outstanding
168    unacknowledged data packet at a time.  The sequence numbers
169    are independent in each direction.  If an acknowledgement for
170    the previous packet is received (i.e., an acknowledgement with
171    the sequence number of the packet just sent) the packet just
172    sent should be retransmitted.  If no acknowledgement is
173    received within a timeout period, the packet should be
174    retransmitted.  This has an unfortunate failure condition on a
175    high-latency line, as a delayed acknowledgement may lead to an
176    endless series of duplicate packets.
177
178    DATA The actual data bytes follow.  The following characters are
179    escaped inline with DLE (ASCII 020, or ^P):
180    SYN (026)    DLE S
181    DLE (020)    DLE D
182    ^C  (003)    DLE C
183    ^S  (023)    DLE s
184    ^Q  (021)    DLE q
185    The additional DLE characters are not counted in the logical
186    length stored in the TYPE_LEN and LEN1 bytes.
187
188    CSUM1
189    CSUM2
190    CSUM3
191    These bytes contain an 18 bit checksum of the complete
192    contents of the packet excluding the SEQ byte and the
193    CSUM[123] bytes.  The checksum is simply the twos complement
194    addition of all the bytes treated as unsigned characters.  The
195    values of the checksum bytes are:
196    CSUM1: 0x40 + ((cksum >> 12) & 0x3f)
197    CSUM2: 0x40 + ((cksum >> 6) & 0x3f)
198    CSUM3: 0x40 + (cksum & 0x3f)
199
200    It happens that the MIPS remote debugging protocol always
201    communicates with ASCII strings.  Because of this, this
202    implementation doesn't bother to handle the DLE quoting mechanism,
203    since it will never be required.  */
204 /* *INDENT-ON* */
205
206
207 /* The SYN character which starts each packet.  */
208 #define SYN '\026'
209
210 /* The 0x40 used to offset each packet (this value ensures that all of
211    the header and trailer bytes, other than SYN, are printable ASCII
212    characters).  */
213 #define HDR_OFFSET 0x40
214
215 /* The indices of the bytes in the packet header.  */
216 #define HDR_INDX_SYN 0
217 #define HDR_INDX_TYPE_LEN 1
218 #define HDR_INDX_LEN1 2
219 #define HDR_INDX_SEQ 3
220 #define HDR_LENGTH 4
221
222 /* The data/ack bit in the TYPE_LEN header byte.  */
223 #define TYPE_LEN_DA_BIT 0x20
224 #define TYPE_LEN_DATA 0
225 #define TYPE_LEN_ACK TYPE_LEN_DA_BIT
226
227 /* How to compute the header bytes.  */
228 #define HDR_SET_SYN(data, len, seq) (SYN)
229 #define HDR_SET_TYPE_LEN(data, len, seq) \
230   (HDR_OFFSET \
231    + ((data) ? TYPE_LEN_DATA : TYPE_LEN_ACK) \
232    + (((len) >> 6) & 0x1f))
233 #define HDR_SET_LEN1(data, len, seq) (HDR_OFFSET + ((len) & 0x3f))
234 #define HDR_SET_SEQ(data, len, seq) (HDR_OFFSET + (seq))
235
236 /* Check that a header byte is reasonable.  */
237 #define HDR_CHECK(ch) (((ch) & HDR_OFFSET) == HDR_OFFSET)
238
239 /* Get data from the header.  These macros evaluate their argument
240    multiple times.  */
241 #define HDR_IS_DATA(hdr) \
242   (((hdr)[HDR_INDX_TYPE_LEN] & TYPE_LEN_DA_BIT) == TYPE_LEN_DATA)
243 #define HDR_GET_LEN(hdr) \
244   ((((hdr)[HDR_INDX_TYPE_LEN] & 0x1f) << 6) + (((hdr)[HDR_INDX_LEN1] & 0x3f)))
245 #define HDR_GET_SEQ(hdr) ((unsigned int)(hdr)[HDR_INDX_SEQ] & 0x3f)
246
247 /* The maximum data length.  */
248 #define DATA_MAXLEN 1023
249
250 /* The trailer offset.  */
251 #define TRLR_OFFSET HDR_OFFSET
252
253 /* The indices of the bytes in the packet trailer.  */
254 #define TRLR_INDX_CSUM1 0
255 #define TRLR_INDX_CSUM2 1
256 #define TRLR_INDX_CSUM3 2
257 #define TRLR_LENGTH 3
258
259 /* How to compute the trailer bytes.  */
260 #define TRLR_SET_CSUM1(cksum) (TRLR_OFFSET + (((cksum) >> 12) & 0x3f))
261 #define TRLR_SET_CSUM2(cksum) (TRLR_OFFSET + (((cksum) >>  6) & 0x3f))
262 #define TRLR_SET_CSUM3(cksum) (TRLR_OFFSET + (((cksum)      ) & 0x3f))
263
264 /* Check that a trailer byte is reasonable.  */
265 #define TRLR_CHECK(ch) (((ch) & TRLR_OFFSET) == TRLR_OFFSET)
266
267 /* Get data from the trailer.  This evaluates its argument multiple
268    times.  */
269 #define TRLR_GET_CKSUM(trlr) \
270   ((((trlr)[TRLR_INDX_CSUM1] & 0x3f) << 12) \
271    + (((trlr)[TRLR_INDX_CSUM2] & 0x3f) <<  6) \
272    + ((trlr)[TRLR_INDX_CSUM3] & 0x3f))
273
274 /* The sequence number modulos.  */
275 #define SEQ_MODULOS (64)
276
277 /* PMON commands to load from the serial port or UDP socket.  */
278 #define LOAD_CMD        "load -b -s tty0\r"
279 #define LOAD_CMD_UDP    "load -b -s udp\r"
280
281 /* The target vectors for the four different remote MIPS targets.
282    These are initialized with code in _initialize_remote_mips instead
283    of static initializers, to make it easier to extend the target_ops
284    vector later.  */
285 struct target_ops mips_ops, pmon_ops, ddb_ops, rockhopper_ops, lsi_ops;
286
287 enum mips_monitor_type
288   {
289     /* IDT/SIM monitor being used: */
290     MON_IDT,
291     /* PMON monitor being used: */
292     MON_PMON,                   /* 3.0.83 [COGENT,EB,FP,NET]
293                                    Algorithmics Ltd. Nov  9 1995 17:19:50 */
294     MON_DDB,                    /* 2.7.473 [DDBVR4300,EL,FP,NET]
295                                    Risq Modular Systems,
296                                    Thu Jun 6 09:28:40 PDT 1996 */
297     MON_LSI,                    /* 4.3.12 [EB,FP],
298                                    LSI LOGIC Corp. Tue Feb 25 13:22:14 1997 */
299     MON_ROCKHOPPER,
300     /* Last and unused value, for sizing vectors, etc.  */
301     MON_LAST
302   };
303 static enum mips_monitor_type mips_monitor = MON_LAST;
304
305 /* The monitor prompt text.  If the user sets the PMON prompt
306    to some new value, the GDB `set monitor-prompt' command must also
307    be used to inform GDB about the expected prompt.  Otherwise, GDB
308    will not be able to connect to PMON in mips_initialize().
309    If the `set monitor-prompt' command is not used, the expected
310    default prompt will be set according the target:
311    target               prompt
312    -----                -----
313    pmon         PMON> 
314    ddb          NEC010>
315    lsi          PMON>
316  */
317 static char *mips_monitor_prompt;
318
319 /* Set to 1 if the target is open.  */
320 static int mips_is_open;
321
322 /* Currently active target description (if mips_is_open == 1).  */
323 static struct target_ops *current_ops;
324
325 /* Set to 1 while the connection is being initialized.  */
326 static int mips_initializing;
327
328 /* Set to 1 while the connection is being brought down.  */
329 static int mips_exiting;
330
331 /* The next sequence number to send.  */
332 static unsigned int mips_send_seq;
333
334 /* The next sequence number we expect to receive.  */
335 static unsigned int mips_receive_seq;
336
337 /* The time to wait before retransmitting a packet, in seconds.  */
338 static int mips_retransmit_wait = 3;
339
340 /* The number of times to try retransmitting a packet before giving up.  */
341 static int mips_send_retries = 10;
342
343 /* The number of garbage characters to accept when looking for an
344    SYN for the next packet.  */
345 static int mips_syn_garbage = 10;
346
347 /* The time to wait for a packet, in seconds.  */
348 static int mips_receive_wait = 5;
349
350 /* Set if we have sent a packet to the board but have not yet received
351    a reply.  */
352 static int mips_need_reply = 0;
353
354 /* Handle used to access serial I/O stream.  */
355 static struct serial *mips_desc;
356
357 /* UDP handle used to download files to target.  */
358 static struct serial *udp_desc;
359 static int udp_in_use;
360
361 /* TFTP filename used to download files to DDB board, in the form
362    host:filename.  */
363 static char *tftp_name;         /* host:filename */
364 static char *tftp_localname;    /* filename portion of above */
365 static int tftp_in_use;
366 static FILE *tftp_file;
367
368 /* Counts the number of times the user tried to interrupt the target (usually
369    via ^C.  */
370 static int interrupt_count;
371
372 /* If non-zero, means that the target is running.  */
373 static int mips_wait_flag = 0;
374
375 /* If non-zero, monitor supports breakpoint commands.  */
376 static int monitor_supports_breakpoints = 0;
377
378 /* Data cache header.  */
379
380 #if 0                           /* not used (yet?)  */
381 static DCACHE *mips_dcache;
382 #endif
383
384 /* Non-zero means that we've just hit a read or write watchpoint.  */
385 static int hit_watchpoint;
386
387 /* Table of breakpoints/watchpoints (used only on LSI PMON target).
388    The table is indexed by a breakpoint number, which is an integer
389    from 0 to 255 returned by the LSI PMON when a breakpoint is set.  */
390
391 #define MAX_LSI_BREAKPOINTS 256
392 struct lsi_breakpoint_info
393   {
394     enum break_type type;       /* type of breakpoint */
395     CORE_ADDR addr;             /* address of breakpoint */
396     int len;                    /* length of region being watched */
397     unsigned long value;        /* value to watch */
398   }
399 lsi_breakpoints[MAX_LSI_BREAKPOINTS];
400
401 /* Error/warning codes returned by LSI PMON for breakpoint commands.
402    Warning values may be ORed together; error values may not.  */
403 #define W_WARN  0x100           /* This bit is set if the error code
404                                    is a warning */
405 #define W_MSK   0x101           /* warning: Range feature is supported
406                                    via mask */
407 #define W_VAL   0x102           /* warning: Value check is not
408                                    supported in hardware */
409 #define W_QAL   0x104           /* warning: Requested qualifiers are
410                                    not supported in hardware */
411
412 #define E_ERR   0x200           /* This bit is set if the error code
413                                    is an error */
414 #define E_BPT   0x200           /* error: No such breakpoint number */
415 #define E_RGE   0x201           /* error: Range is not supported */
416 #define E_QAL   0x202           /* error: The requested qualifiers can
417                                    not be used */
418 #define E_OUT   0x203           /* error: Out of hardware resources */
419 #define E_NON   0x204           /* error: Hardware breakpoint not supported */
420
421 struct lsi_error
422   {
423     int code;                   /* error code */
424     char *string;               /* string associated with this code */
425   };
426
427 struct lsi_error lsi_warning_table[] =
428 {
429   {W_MSK, "Range feature is supported via mask"},
430   {W_VAL, "Value check is not supported in hardware"},
431   {W_QAL, "Requested qualifiers are not supported in hardware"},
432   {0, NULL}
433 };
434
435 struct lsi_error lsi_error_table[] =
436 {
437   {E_BPT, "No such breakpoint number"},
438   {E_RGE, "Range is not supported"},
439   {E_QAL, "The requested qualifiers can not be used"},
440   {E_OUT, "Out of hardware resources"},
441   {E_NON, "Hardware breakpoint not supported"},
442   {0, NULL}
443 };
444
445 /* Set to 1 with the 'set monitor-warnings' command to enable printing
446    of warnings returned by PMON when hardware breakpoints are used.  */
447 static int monitor_warnings;
448
449 /* This is the ptid we use while we're connected to the remote.  Its
450    value is arbitrary, as the remote-mips target doesn't have a notion of
451    processes or threads, but we need something non-null to place in
452    inferior_ptid.  */
453 static ptid_t remote_mips_ptid;
454
455 /* Close any ports which might be open.  Reset certain globals indicating
456    the state of those ports.  */
457
458 static void
459 close_ports (void)
460 {
461   mips_is_open = 0;
462   serial_close (mips_desc);
463
464   if (udp_in_use)
465     {
466       serial_close (udp_desc);
467       udp_in_use = 0;
468     }
469   tftp_in_use = 0;
470 }
471
472 /* Handle low-level error that we can't recover from.  Note that just
473    error()ing out from target_wait or some such low-level place will cause
474    all hell to break loose--the rest of GDB will tend to get left in an
475    inconsistent state.  */
476
477 static void ATTRIBUTE_NORETURN
478 mips_error (char *string,...)
479 {
480   va_list args;
481   char *fmt;
482
483   target_terminal_ours ();
484   wrap_here ("");               /* Force out any buffered output.  */
485   gdb_flush (gdb_stdout);
486   gdb_flush (gdb_stderr);
487
488   /* Clean up in such a way that mips_close won't try to talk to the
489      board (it almost surely won't work since we weren't able to talk to
490      it).  */
491   close_ports ();
492
493   if (!ptid_equal (inferior_ptid, null_ptid))
494     target_mourn_inferior ();
495
496   fmt = concat (_("Ending remote MIPS debugging: "),
497                 string, (char *) NULL);
498   make_cleanup (xfree, fmt);
499
500   va_start (args, string);
501   throw_verror (TARGET_CLOSE_ERROR, fmt, args);
502   va_end (args);
503 }
504
505 /* putc_readable - print a character, displaying non-printable chars in
506    ^x notation or in hex.  */
507
508 static void
509 fputc_readable (int ch, struct ui_file *file)
510 {
511   if (ch == '\n')
512     fputc_unfiltered ('\n', file);
513   else if (ch == '\r')
514     fprintf_unfiltered (file, "\\r");
515   else if (ch < 0x20)           /* ASCII control character */
516     fprintf_unfiltered (file, "^%c", ch + '@');
517   else if (ch >= 0x7f)          /* non-ASCII characters (rubout or greater) */
518     fprintf_unfiltered (file, "[%02x]", ch & 0xff);
519   else
520     fputc_unfiltered (ch, file);
521 }
522
523
524 /* puts_readable - print a string, displaying non-printable chars in
525    ^x notation or in hex.  */
526
527 static void
528 fputs_readable (const char *string, struct ui_file *file)
529 {
530   int c;
531
532   while ((c = *string++) != '\0')
533     fputc_readable (c, file);
534 }
535
536
537 /* Read P as a hex value.  Return true if every character made sense,
538    storing the result in *RESULT.  Leave *RESULT unchanged otherwise.  */
539
540 static int
541 read_hex_value (const char *p, ULONGEST *result)
542 {
543   ULONGEST retval;
544
545   retval = 0;
546   while (*p != 0)
547     {
548       retval <<= 4;
549       if (*p >= '0' && *p <= '9')
550         retval |= *p - '0';
551       else if (*p >= 'A' && *p <= 'F')
552         retval |= *p - 'A' + 10;
553       else if (*p >= 'a' && *p <= 'f')
554         retval |= *p - 'a' + 10;
555       else
556         return 0;
557       p++;
558     }
559   *result = retval;
560   return 1;
561 }
562
563
564 /* Wait until STRING shows up in mips_desc.  Returns 1 if successful, else 0 if
565    timed out.  TIMEOUT specifies timeout value in seconds.  */
566
567 static int
568 mips_expect_timeout (const char *string, int timeout)
569 {
570   const char *p = string;
571
572   if (remote_debug)
573     {
574       fprintf_unfiltered (gdb_stdlog, "Expected \"");
575       fputs_readable (string, gdb_stdlog);
576       fprintf_unfiltered (gdb_stdlog, "\", got \"");
577     }
578
579   immediate_quit++;
580   QUIT;
581   while (1)
582     {
583       int c;
584
585       /* Must use serial_readchar() here cuz mips_readchar would get
586          confused if we were waiting for the mips_monitor_prompt...  */
587
588       c = serial_readchar (mips_desc, timeout);
589
590       if (c == SERIAL_TIMEOUT)
591         {
592           if (remote_debug)
593             fprintf_unfiltered (gdb_stdlog, "\": FAIL\n");
594           return 0;
595         }
596
597       if (remote_debug)
598         fputc_readable (c, gdb_stdlog);
599
600       if (c == *p++)
601         {
602           if (*p == '\0')
603             {
604               immediate_quit--;
605               if (remote_debug)
606                 fprintf_unfiltered (gdb_stdlog, "\": OK\n");
607               return 1;
608             }
609         }
610       else
611         {
612           p = string;
613           if (c == *p)
614             p++;
615         }
616     }
617 }
618
619 /* Wait until STRING shows up in mips_desc.  Returns 1 if successful, else 0 if
620    timed out.  The timeout value is hard-coded to 2 seconds.  Use
621    mips_expect_timeout if a different timeout value is needed.  */
622
623 static int
624 mips_expect (const char *string)
625 {
626   return mips_expect_timeout (string, remote_timeout);
627 }
628
629 /* Read a character from the remote, aborting on error.  Returns
630    SERIAL_TIMEOUT on timeout (since that's what serial_readchar()
631    returns).  FIXME: If we see the string mips_monitor_prompt from the
632    board, then we are debugging on the main console port, and we have
633    somehow dropped out of remote debugging mode.  In this case, we
634    automatically go back in to remote debugging mode.  This is a hack,
635    put in because I can't find any way for a program running on the
636    remote board to terminate without also ending remote debugging
637    mode.  I assume users won't have any trouble with this; for one
638    thing, the IDT documentation generally assumes that the remote
639    debugging port is not the console port.  This is, however, very
640    convenient for DejaGnu when you only have one connected serial
641    port.  */
642
643 static int
644 mips_readchar (int timeout)
645 {
646   int ch;
647   static int state = 0;
648   int mips_monitor_prompt_len = strlen (mips_monitor_prompt);
649
650   { /* FIXME this whole block is dead code!  */
651     int i;
652
653     i = timeout;
654     if (i == -1 && watchdog > 0)
655       i = watchdog;
656   }
657
658   if (state == mips_monitor_prompt_len)
659     timeout = 1;
660   ch = serial_readchar (mips_desc, timeout);
661
662   if (ch == SERIAL_TIMEOUT && timeout == -1)    /* Watchdog went off.  */
663     {
664       target_mourn_inferior ();
665       error (_("Watchdog has expired.  Target detached."));
666     }
667
668   if (ch == SERIAL_EOF)
669     mips_error (_("End of file from remote"));
670   if (ch == SERIAL_ERROR)
671     mips_error (_("Error reading from remote: %s"), safe_strerror (errno));
672   if (remote_debug > 1)
673     {
674       /* Don't use _filtered; we can't deal with a QUIT out of
675          target_wait, and I think this might be called from there.  */
676       if (ch != SERIAL_TIMEOUT)
677         fprintf_unfiltered (gdb_stdlog, "Read '%c' %d 0x%x\n", ch, ch, ch);
678       else
679         fprintf_unfiltered (gdb_stdlog, "Timed out in read\n");
680     }
681
682   /* If we have seen mips_monitor_prompt and we either time out, or
683      we see a @ (which was echoed from a packet we sent), reset the
684      board as described above.  The first character in a packet after
685      the SYN (which is not echoed) is always an @ unless the packet is
686      more than 64 characters long, which ours never are.  */
687   if ((ch == SERIAL_TIMEOUT || ch == '@')
688       && state == mips_monitor_prompt_len
689       && !mips_initializing
690       && !mips_exiting)
691     {
692       if (remote_debug > 0)
693         /* Don't use _filtered; we can't deal with a QUIT out of
694            target_wait, and I think this might be called from there.  */
695         fprintf_unfiltered (gdb_stdlog,
696                             "Reinitializing MIPS debugging mode\n");
697
698       mips_need_reply = 0;
699       mips_initialize ();
700
701       state = 0;
702
703       /* At this point, about the only thing we can do is abort the command
704          in progress and get back to command level as quickly as possible.  */
705
706       error (_("Remote board reset, debug protocol re-initialized."));
707     }
708
709   if (ch == mips_monitor_prompt[state])
710     ++state;
711   else
712     state = 0;
713
714   return ch;
715 }
716
717 /* Get a packet header, putting the data in the supplied buffer.
718    PGARBAGE is a pointer to the number of garbage characters received
719    so far.  CH is the last character received.  Returns 0 for success,
720    or -1 for timeout.  */
721
722 static int
723 mips_receive_header (unsigned char *hdr, int *pgarbage, int ch, int timeout)
724 {
725   int i;
726
727   while (1)
728     {
729       /* Wait for a SYN.  mips_syn_garbage is intended to prevent
730          sitting here indefinitely if the board sends us one garbage
731          character per second.  ch may already have a value from the
732          last time through the loop.  */
733       while (ch != SYN)
734         {
735           ch = mips_readchar (timeout);
736           if (ch == SERIAL_TIMEOUT)
737             return -1;
738           if (ch != SYN)
739             {
740               /* Printing the character here lets the user of gdb see
741                  what the program is outputting, if the debugging is
742                  being done on the console port.  Don't use _filtered:
743                  we can't deal with a QUIT out of target_wait and
744                  buffered target output confuses the user.  */
745               if (!mips_initializing || remote_debug > 0)
746                 {
747                   if (isprint (ch) || isspace (ch))
748                     {
749                       fputc_unfiltered (ch, gdb_stdtarg);
750                     }
751                   else
752                     {
753                       fputc_readable (ch, gdb_stdtarg);
754                     }
755                   gdb_flush (gdb_stdtarg);
756                 }
757               
758               /* Only count unprintable characters.  */
759               if (! (isprint (ch) || isspace (ch)))
760                 (*pgarbage) += 1;
761
762               if (mips_syn_garbage > 0
763                   && *pgarbage > mips_syn_garbage)
764                 mips_error (_("Debug protocol failure:  more "
765                             "than %d characters before a sync."),
766                             mips_syn_garbage);
767             }
768         }
769
770       /* Get the packet header following the SYN.  */
771       for (i = 1; i < HDR_LENGTH; i++)
772         {
773           ch = mips_readchar (timeout);
774           if (ch == SERIAL_TIMEOUT)
775             return -1;
776           /* Make sure this is a header byte.  */
777           if (ch == SYN || !HDR_CHECK (ch))
778             break;
779
780           hdr[i] = ch;
781         }
782
783       /* If we got the complete header, we can return.  Otherwise we
784          loop around and keep looking for SYN.  */
785       if (i >= HDR_LENGTH)
786         return 0;
787     }
788 }
789
790 /* Get a packet header, putting the data in the supplied buffer.
791    PGARBAGE is a pointer to the number of garbage characters received
792    so far.  The last character read is returned in *PCH.  Returns 0
793    for success, -1 for timeout, -2 for error.  */
794
795 static int
796 mips_receive_trailer (unsigned char *trlr, int *pgarbage,
797                       int *pch, int timeout)
798 {
799   int i;
800   int ch;
801
802   for (i = 0; i < TRLR_LENGTH; i++)
803     {
804       ch = mips_readchar (timeout);
805       *pch = ch;
806       if (ch == SERIAL_TIMEOUT)
807         return -1;
808       if (!TRLR_CHECK (ch))
809         return -2;
810       trlr[i] = ch;
811     }
812   return 0;
813 }
814
815 /* Get the checksum of a packet.  HDR points to the packet header.
816    DATASTR points to the packet data.  LEN is the length of DATASTR.  */
817
818 static int
819 mips_cksum (const unsigned char *hdr, const char *datastr, int len)
820 {
821   const unsigned char *p;
822   const unsigned char *data = (const unsigned char *) datastr;
823   int c;
824   int cksum;
825
826   cksum = 0;
827
828   /* The initial SYN is not included in the checksum.  */
829   c = HDR_LENGTH - 1;
830   p = hdr + 1;
831   while (c-- != 0)
832     cksum += *p++;
833
834   c = len;
835   p = data;
836   while (c-- != 0)
837     cksum += *p++;
838
839   return cksum;
840 }
841
842 /* Send a packet containing the given ASCII string.  */
843
844 static void
845 mips_send_packet (const char *s, int get_ack)
846 {
847   /* unsigned */ int len;
848   unsigned char *packet;
849   int cksum;
850   int try;
851
852   len = strlen (s);
853   if (len > DATA_MAXLEN)
854     mips_error (_("MIPS protocol data packet too long: %s"), s);
855
856   packet = (unsigned char *) alloca (HDR_LENGTH + len + TRLR_LENGTH + 1);
857
858   packet[HDR_INDX_SYN] = HDR_SET_SYN (1, len, mips_send_seq);
859   packet[HDR_INDX_TYPE_LEN] = HDR_SET_TYPE_LEN (1, len, mips_send_seq);
860   packet[HDR_INDX_LEN1] = HDR_SET_LEN1 (1, len, mips_send_seq);
861   packet[HDR_INDX_SEQ] = HDR_SET_SEQ (1, len, mips_send_seq);
862
863   memcpy (packet + HDR_LENGTH, s, len);
864
865   cksum = mips_cksum (packet, (char *) packet + HDR_LENGTH, len);
866   packet[HDR_LENGTH + len + TRLR_INDX_CSUM1] = TRLR_SET_CSUM1 (cksum);
867   packet[HDR_LENGTH + len + TRLR_INDX_CSUM2] = TRLR_SET_CSUM2 (cksum);
868   packet[HDR_LENGTH + len + TRLR_INDX_CSUM3] = TRLR_SET_CSUM3 (cksum);
869
870   /* Increment the sequence number.  This will set mips_send_seq to
871      the sequence number we expect in the acknowledgement.  */
872   mips_send_seq = (mips_send_seq + 1) % SEQ_MODULOS;
873
874   /* We can only have one outstanding data packet, so we just wait for
875      the acknowledgement here.  Keep retransmitting the packet until
876      we get one, or until we've tried too many times.  */
877   for (try = 0; try < mips_send_retries; try++)
878     {
879       int garbage;
880       int ch;
881
882       if (remote_debug > 0)
883         {
884           /* Don't use _filtered; we can't deal with a QUIT out of
885              target_wait, and I think this might be called from there.  */
886           packet[HDR_LENGTH + len + TRLR_LENGTH] = '\0';
887           fprintf_unfiltered (gdb_stdlog, "Writing \"%s\"\n", packet + 1);
888         }
889
890       if (serial_write (mips_desc, packet,
891                         HDR_LENGTH + len + TRLR_LENGTH) != 0)
892         mips_error (_("write to target failed: %s"), safe_strerror (errno));
893
894       if (!get_ack)
895         return;
896
897       garbage = 0;
898       ch = 0;
899       while (1)
900         {
901           unsigned char hdr[HDR_LENGTH + 1];
902           unsigned char trlr[TRLR_LENGTH + 1];
903           int err;
904           unsigned int seq;
905
906           /* Get the packet header.  If we time out, resend the data
907              packet.  */
908           err = mips_receive_header (hdr, &garbage, ch, mips_retransmit_wait);
909           if (err != 0)
910             break;
911
912           ch = 0;
913
914           /* If we get a data packet, assume it is a duplicate and
915              ignore it.  FIXME: If the acknowledgement is lost, this
916              data packet may be the packet the remote sends after the
917              acknowledgement.  */
918           if (HDR_IS_DATA (hdr))
919             {
920               int i;
921
922               /* Ignore any errors raised whilst attempting to ignore
923                  packet.  */
924
925               len = HDR_GET_LEN (hdr);
926
927               for (i = 0; i < len; i++)
928                 {
929                   int rch;
930
931                   rch = mips_readchar (remote_timeout);
932                   if (rch == SYN)
933                     {
934                       ch = SYN;
935                       break;
936                     }
937                   if (rch == SERIAL_TIMEOUT)
938                     break;
939                   /* Ignore the character.  */
940                 }
941
942               if (i == len)
943                 (void) mips_receive_trailer (trlr, &garbage, &ch,
944                                              remote_timeout);
945
946               /* We don't bother checking the checksum, or providing an
947                  ACK to the packet.  */
948               continue;
949             }
950
951           /* If the length is not 0, this is a garbled packet.  */
952           if (HDR_GET_LEN (hdr) != 0)
953             continue;
954
955           /* Get the packet trailer.  */
956           err = mips_receive_trailer (trlr, &garbage, &ch,
957                                       mips_retransmit_wait);
958
959           /* If we timed out, resend the data packet.  */
960           if (err == -1)
961             break;
962
963           /* If we got a bad character, reread the header.  */
964           if (err != 0)
965             continue;
966
967           /* If the checksum does not match the trailer checksum, this
968              is a bad packet; ignore it.  */
969           if (mips_cksum (hdr, NULL, 0) != TRLR_GET_CKSUM (trlr))
970             continue;
971
972           if (remote_debug > 0)
973             {
974               hdr[HDR_LENGTH] = '\0';
975               trlr[TRLR_LENGTH] = '\0';
976               /* Don't use _filtered; we can't deal with a QUIT out of
977                  target_wait, and I think this might be called from there.  */
978               fprintf_unfiltered (gdb_stdlog, "Got ack %d \"%s%s\"\n",
979                                   HDR_GET_SEQ (hdr), hdr + 1, trlr);
980             }
981
982           /* If this ack is for the current packet, we're done.  */
983           seq = HDR_GET_SEQ (hdr);
984           if (seq == mips_send_seq)
985             return;
986
987           /* If this ack is for the last packet, resend the current
988              packet.  */
989           if ((seq + 1) % SEQ_MODULOS == mips_send_seq)
990             break;
991
992           /* Otherwise this is a bad ack; ignore it.  Increment the
993              garbage count to ensure that we do not stay in this loop
994              forever.  */
995           ++garbage;
996         }
997     }
998
999   mips_error (_("Remote did not acknowledge packet"));
1000 }
1001
1002 /* Receive and acknowledge a packet, returning the data in BUFF (which
1003    should be DATA_MAXLEN + 1 bytes).  The protocol documentation
1004    implies that only the sender retransmits packets, so this code just
1005    waits silently for a packet.  It returns the length of the received
1006    packet.  If THROW_ERROR is nonzero, call error() on errors.  If not,
1007    don't print an error message and return -1.  */
1008
1009 static int
1010 mips_receive_packet (char *buff, int throw_error, int timeout)
1011 {
1012   int ch;
1013   int garbage;
1014   int len;
1015   unsigned char ack[HDR_LENGTH + TRLR_LENGTH + 1];
1016   int cksum;
1017
1018   ch = 0;
1019   garbage = 0;
1020   while (1)
1021     {
1022       unsigned char hdr[HDR_LENGTH];
1023       unsigned char trlr[TRLR_LENGTH];
1024       int i;
1025       int err;
1026
1027       if (mips_receive_header (hdr, &garbage, ch, timeout) != 0)
1028         {
1029           if (throw_error)
1030             mips_error (_("Timed out waiting for remote packet"));
1031           else
1032             return -1;
1033         }
1034
1035       ch = 0;
1036
1037       /* An acknowledgement is probably a duplicate; ignore it.  */
1038       if (!HDR_IS_DATA (hdr))
1039         {
1040           len = HDR_GET_LEN (hdr);
1041           /* Check if the length is valid for an ACK, we may aswell
1042              try and read the remainder of the packet: */
1043           if (len == 0)
1044             {
1045               /* Ignore the error condition, since we are going to
1046                  ignore the packet anyway.  */
1047               (void) mips_receive_trailer (trlr, &garbage, &ch, timeout);
1048             }
1049           /* Don't use _filtered; we can't deal with a QUIT out of
1050              target_wait, and I think this might be called from there.  */
1051           if (remote_debug > 0)
1052             fprintf_unfiltered (gdb_stdlog, "Ignoring unexpected ACK\n");
1053           continue;
1054         }
1055
1056       len = HDR_GET_LEN (hdr);
1057       for (i = 0; i < len; i++)
1058         {
1059           int rch;
1060
1061           rch = mips_readchar (timeout);
1062           if (rch == SYN)
1063             {
1064               ch = SYN;
1065               break;
1066             }
1067           if (rch == SERIAL_TIMEOUT)
1068             {
1069               if (throw_error)
1070                 mips_error (_("Timed out waiting for remote packet"));
1071               else
1072                 return -1;
1073             }
1074           buff[i] = rch;
1075         }
1076
1077       if (i < len)
1078         {
1079           /* Don't use _filtered; we can't deal with a QUIT out of
1080              target_wait, and I think this might be called from there.  */
1081           if (remote_debug > 0)
1082             fprintf_unfiltered (gdb_stdlog,
1083                                 "Got new SYN after %d chars (wanted %d)\n",
1084                                 i, len);
1085           continue;
1086         }
1087
1088       err = mips_receive_trailer (trlr, &garbage, &ch, timeout);
1089       if (err == -1)
1090         {
1091           if (throw_error)
1092             mips_error (_("Timed out waiting for packet"));
1093           else
1094             return -1;
1095         }
1096       if (err == -2)
1097         {
1098           /* Don't use _filtered; we can't deal with a QUIT out of
1099              target_wait, and I think this might be called from there.  */
1100           if (remote_debug > 0)
1101             fprintf_unfiltered (gdb_stdlog, "Got SYN when wanted trailer\n");
1102           continue;
1103         }
1104
1105       /* If this is the wrong sequence number, ignore it.  */
1106       if (HDR_GET_SEQ (hdr) != mips_receive_seq)
1107         {
1108           /* Don't use _filtered; we can't deal with a QUIT out of
1109              target_wait, and I think this might be called from there.  */
1110           if (remote_debug > 0)
1111             fprintf_unfiltered (gdb_stdlog,
1112                                 "Ignoring sequence number %d (want %d)\n",
1113                                 HDR_GET_SEQ (hdr), mips_receive_seq);
1114           continue;
1115         }
1116
1117       if (mips_cksum (hdr, buff, len) == TRLR_GET_CKSUM (trlr))
1118         break;
1119
1120       if (remote_debug > 0)
1121         /* Don't use _filtered; we can't deal with a QUIT out of
1122            target_wait, and I think this might be called from there.  */
1123         printf_unfiltered ("Bad checksum; data %d, trailer %d\n",
1124                            mips_cksum (hdr, buff, len),
1125                            TRLR_GET_CKSUM (trlr));
1126
1127       /* The checksum failed.  Send an acknowledgement for the
1128          previous packet to tell the remote to resend the packet.  */
1129       ack[HDR_INDX_SYN] = HDR_SET_SYN (0, 0, mips_receive_seq);
1130       ack[HDR_INDX_TYPE_LEN] = HDR_SET_TYPE_LEN (0, 0, mips_receive_seq);
1131       ack[HDR_INDX_LEN1] = HDR_SET_LEN1 (0, 0, mips_receive_seq);
1132       ack[HDR_INDX_SEQ] = HDR_SET_SEQ (0, 0, mips_receive_seq);
1133
1134       cksum = mips_cksum (ack, NULL, 0);
1135
1136       ack[HDR_LENGTH + TRLR_INDX_CSUM1] = TRLR_SET_CSUM1 (cksum);
1137       ack[HDR_LENGTH + TRLR_INDX_CSUM2] = TRLR_SET_CSUM2 (cksum);
1138       ack[HDR_LENGTH + TRLR_INDX_CSUM3] = TRLR_SET_CSUM3 (cksum);
1139
1140       if (remote_debug > 0)
1141         {
1142           ack[HDR_LENGTH + TRLR_LENGTH] = '\0';
1143           /* Don't use _filtered; we can't deal with a QUIT out of
1144              target_wait, and I think this might be called from there.  */
1145           printf_unfiltered ("Writing ack %d \"%s\"\n", mips_receive_seq,
1146                              ack + 1);
1147         }
1148
1149       if (serial_write (mips_desc, ack, HDR_LENGTH + TRLR_LENGTH) != 0)
1150         {
1151           if (throw_error)
1152             mips_error (_("write to target failed: %s"),
1153                         safe_strerror (errno));
1154           else
1155             return -1;
1156         }
1157     }
1158
1159   if (remote_debug > 0)
1160     {
1161       buff[len] = '\0';
1162       /* Don't use _filtered; we can't deal with a QUIT out of
1163          target_wait, and I think this might be called from there.  */
1164       printf_unfiltered ("Got packet \"%s\"\n", buff);
1165     }
1166
1167   /* We got the packet.  Send an acknowledgement.  */
1168   mips_receive_seq = (mips_receive_seq + 1) % SEQ_MODULOS;
1169
1170   ack[HDR_INDX_SYN] = HDR_SET_SYN (0, 0, mips_receive_seq);
1171   ack[HDR_INDX_TYPE_LEN] = HDR_SET_TYPE_LEN (0, 0, mips_receive_seq);
1172   ack[HDR_INDX_LEN1] = HDR_SET_LEN1 (0, 0, mips_receive_seq);
1173   ack[HDR_INDX_SEQ] = HDR_SET_SEQ (0, 0, mips_receive_seq);
1174
1175   cksum = mips_cksum (ack, NULL, 0);
1176
1177   ack[HDR_LENGTH + TRLR_INDX_CSUM1] = TRLR_SET_CSUM1 (cksum);
1178   ack[HDR_LENGTH + TRLR_INDX_CSUM2] = TRLR_SET_CSUM2 (cksum);
1179   ack[HDR_LENGTH + TRLR_INDX_CSUM3] = TRLR_SET_CSUM3 (cksum);
1180
1181   if (remote_debug > 0)
1182     {
1183       ack[HDR_LENGTH + TRLR_LENGTH] = '\0';
1184       /* Don't use _filtered; we can't deal with a QUIT out of
1185          target_wait, and I think this might be called from there.  */
1186       printf_unfiltered ("Writing ack %d \"%s\"\n", mips_receive_seq,
1187                          ack + 1);
1188     }
1189
1190   if (serial_write (mips_desc, ack, HDR_LENGTH + TRLR_LENGTH) != 0)
1191     {
1192       if (throw_error)
1193         mips_error (_("write to target failed: %s"), safe_strerror (errno));
1194       else
1195         return -1;
1196     }
1197
1198   return len;
1199 }
1200 \f
1201 /* Optionally send a request to the remote system and optionally wait
1202    for the reply.  This implements the remote debugging protocol,
1203    which is built on top of the packet protocol defined above.  Each
1204    request has an ADDR argument and a DATA argument.  The following
1205    requests are defined:
1206
1207    \0   don't send a request; just wait for a reply
1208    i    read word from instruction space at ADDR
1209    d    read word from data space at ADDR
1210    I    write DATA to instruction space at ADDR
1211    D    write DATA to data space at ADDR
1212    r    read register number ADDR
1213    R    set register number ADDR to value DATA
1214    c    continue execution (if ADDR != 1, set pc to ADDR)
1215    s    single step (if ADDR != 1, set pc to ADDR)
1216
1217    The read requests return the value requested.  The write requests
1218    return the previous value in the changed location.  The execution
1219    requests return a UNIX wait value (the approximate signal which
1220    caused execution to stop is in the upper eight bits).
1221
1222    If PERR is not NULL, this function waits for a reply.  If an error
1223    occurs, it sets *PERR to 1 and sets errno according to what the
1224    target board reports.  */
1225
1226 static ULONGEST
1227 mips_request (int cmd,
1228               ULONGEST addr,
1229               ULONGEST data,
1230               int *perr,
1231               int timeout,
1232               char *buff)
1233 {
1234   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
1235   char myBuff[DATA_MAXLEN + 1];
1236   char response_string[17];
1237   int len;
1238   int rpid;
1239   char rcmd;
1240   int rerrflg;
1241   ULONGEST rresponse;
1242
1243   if (buff == (char *) NULL)
1244     buff = myBuff;
1245
1246   if (cmd != '\0')
1247     {
1248       if (mips_need_reply)
1249         internal_error (__FILE__, __LINE__,
1250                         _("mips_request: Trying to send "
1251                           "command before reply"));
1252       /* 'T' sets a register to a 64-bit value, so make sure we use
1253          the right conversion function.  */
1254       if (cmd == 'T')
1255         sprintf (buff, "0x0 %c 0x%s 0x%s", cmd,
1256                  phex_nz (addr, addr_size), phex_nz (data, 8));
1257       else
1258         sprintf (buff, "0x0 %c 0x%s 0x%s", cmd,
1259                  phex_nz (addr, addr_size), phex_nz (data, addr_size));
1260
1261       mips_send_packet (buff, 1);
1262       mips_need_reply = 1;
1263     }
1264
1265   if (perr == (int *) NULL)
1266     return 0;
1267
1268   if (!mips_need_reply)
1269     internal_error (__FILE__, __LINE__,
1270                     _("mips_request: Trying to get reply before command"));
1271
1272   mips_need_reply = 0;
1273
1274   len = mips_receive_packet (buff, 1, timeout);
1275   buff[len] = '\0';
1276
1277   if (sscanf (buff, "0x%x %c 0x%x 0x%16s",
1278               &rpid, &rcmd, &rerrflg, response_string) != 4
1279       || !read_hex_value (response_string, &rresponse)
1280       || (cmd != '\0' && rcmd != cmd))
1281     mips_error (_("Bad response from remote board"));
1282
1283   if (rerrflg != 0)
1284     {
1285       *perr = 1;
1286
1287       /* FIXME: This will returns MIPS errno numbers, which may or may
1288          not be the same as errno values used on other systems.  If
1289          they stick to common errno values, they will be the same, but
1290          if they don't, they must be translated.  */
1291       errno = rresponse;
1292
1293       return 0;
1294     }
1295
1296   *perr = 0;
1297   return rresponse;
1298 }
1299
1300 /* Cleanup associated with mips_initialize().  */
1301
1302 static void
1303 mips_initialize_cleanups (void *arg)
1304 {
1305   mips_initializing = 0;
1306 }
1307
1308 /* Cleanup associated with mips_exit_debug().  */
1309
1310 static void
1311 mips_exit_cleanups (void *arg)
1312 {
1313   mips_exiting = 0;
1314 }
1315
1316 /* Send a command and wait for that command to be echoed back.  Wait,
1317    too, for the following prompt.  */
1318
1319 static void
1320 mips_send_command (const char *cmd, int prompt)
1321 {
1322   serial_write (mips_desc, cmd, strlen (cmd));
1323   mips_expect (cmd);
1324   mips_expect ("\n");
1325   if (prompt)
1326     mips_expect (mips_monitor_prompt);
1327 }
1328
1329 /* Enter remote (dbx) debug mode: */
1330
1331 static void
1332 mips_enter_debug (void)
1333 {
1334   /* Reset the sequence numbers, ready for the new debug sequence: */
1335   mips_send_seq = 0;
1336   mips_receive_seq = 0;
1337
1338   if (mips_monitor != MON_IDT)
1339     mips_send_command ("debug\r", 0);
1340   else                          /* Assume IDT monitor by default.  */
1341     mips_send_command ("db tty0\r", 0);
1342
1343   gdb_usleep (1000000);
1344   serial_write (mips_desc, "\r", sizeof "\r" - 1);
1345
1346   /* We don't need to absorb any spurious characters here, since the
1347      mips_receive_header will eat up a reasonable number of characters
1348      whilst looking for the SYN, however this avoids the "garbage"
1349      being displayed to the user.  */
1350   if (mips_monitor != MON_IDT)
1351     mips_expect ("\r");
1352
1353   {
1354     char buff[DATA_MAXLEN + 1];
1355
1356     if (mips_receive_packet (buff, 1, 3) < 0)
1357       mips_error (_("Failed to initialize (didn't receive packet)."));
1358   }
1359 }
1360
1361 /* Exit remote (dbx) debug mode, returning to the monitor prompt: */
1362
1363 static int
1364 mips_exit_debug (void)
1365 {
1366   int err;
1367   struct cleanup *old_cleanups = make_cleanup (mips_exit_cleanups, NULL);
1368
1369   mips_exiting = 1;
1370
1371   if (mips_monitor != MON_IDT && mips_monitor != MON_ROCKHOPPER)
1372     {
1373       /* The DDB (NEC) and MiniRISC (LSI) versions of PMON exit immediately,
1374          so we do not get a reply to this command: */
1375       mips_request ('x', 0, 0, NULL, mips_receive_wait, NULL);
1376       mips_need_reply = 0;
1377       if (!mips_expect (" break!"))
1378         {
1379           do_cleanups (old_cleanups);
1380           return -1;
1381         }
1382     }
1383   else
1384     mips_request ('x', 0, 0, &err, mips_receive_wait, NULL);
1385
1386   if (!mips_expect (mips_monitor_prompt))
1387     {
1388       do_cleanups (old_cleanups);
1389       return -1;
1390     }
1391
1392   do_cleanups (old_cleanups);
1393
1394   return 0;
1395 }
1396
1397 /* Initialize a new connection to the MIPS board, and make sure we are
1398    really connected.  */
1399
1400 static void
1401 mips_initialize (void)
1402 {
1403   int err;
1404   struct cleanup *old_cleanups;
1405   int j;
1406
1407   /* What is this code doing here?  I don't see any way it can happen, and
1408      it might mean mips_initializing didn't get cleared properly.
1409      So I'll make it a warning.  */
1410
1411   if (mips_initializing)
1412     {
1413       warning (_("internal error: mips_initialize called twice"));
1414       return;
1415     }
1416
1417   old_cleanups = make_cleanup (mips_initialize_cleanups, NULL);
1418
1419   mips_wait_flag = 0;
1420   mips_initializing = 1;
1421
1422   /* At this point, the packit protocol isn't responding.  We'll try getting
1423      into the monitor, and restarting the protocol.  */
1424
1425   /* Force the system into the monitor.  After this we *should* be at
1426      the mips_monitor_prompt.  */
1427   if (mips_monitor != MON_IDT)
1428     j = 0;                      /* Start by checking if we are already
1429                                    at the prompt.  */
1430   else
1431     j = 1;                      /* Start by sending a break.  */
1432   for (; j <= 4; j++)
1433     {
1434       switch (j)
1435         {
1436         case 0:         /* First, try sending a CR.  */
1437           serial_flush_input (mips_desc);
1438           serial_write (mips_desc, "\r", 1);
1439           break;
1440         case 1:         /* First, try sending a break.  */
1441           serial_send_break (mips_desc);
1442           break;
1443         case 2:         /* Then, try a ^C.  */
1444           serial_write (mips_desc, "\003", 1);
1445           break;
1446         case 3:         /* Then, try escaping from download.  */
1447           {
1448             if (mips_monitor != MON_IDT)
1449               {
1450                 char tbuff[7];
1451
1452                 /* We shouldn't need to send multiple termination
1453                    sequences, since the target performs line (or
1454                    block) reads, and then processes those
1455                    packets.  In-case we were downloading a large packet
1456                    we flush the output buffer before inserting a
1457                    termination sequence.  */
1458                 serial_flush_output (mips_desc);
1459                 sprintf (tbuff, "\r/E/E\r");
1460                 serial_write (mips_desc, tbuff, 6);
1461               }
1462             else
1463               {
1464                 char srec[10];
1465                 int i;
1466
1467                 /* We are possibly in binary download mode, having
1468                    aborted in the middle of an S-record.  ^C won't
1469                    work because of binary mode.  The only reliable way
1470                    out is to send enough termination packets (8 bytes)
1471                    to fill up and then overflow the largest size
1472                    S-record (255 bytes in this case).  This amounts to
1473                    256/8 + 1 packets.  */
1474
1475                 mips_make_srec (srec, '7', 0, NULL, 0);
1476
1477                 for (i = 1; i <= 33; i++)
1478                   {
1479                     serial_write (mips_desc, srec, 8);
1480
1481                     if (serial_readchar (mips_desc, 0) >= 0)
1482                       break;    /* Break immediatly if we get something from
1483                                    the board.  */
1484                   }
1485               }
1486           }
1487           break;
1488         case 4:
1489           mips_error (_("Failed to initialize."));
1490         }
1491
1492       if (mips_expect (mips_monitor_prompt))
1493         break;
1494     }
1495
1496   if (mips_monitor != MON_IDT)
1497     {
1498       /* Sometimes PMON ignores the first few characters in the first
1499          command sent after a load.  Sending a blank command gets
1500          around that.  */
1501       mips_send_command ("\r", -1);
1502
1503       /* Ensure the correct target state: */
1504       if (mips_monitor != MON_LSI)
1505         mips_send_command ("set regsize 64\r", -1);
1506       mips_send_command ("set hostport tty0\r", -1);
1507       mips_send_command ("set brkcmd \"\"\r", -1);
1508       /* Delete all the current breakpoints: */
1509       mips_send_command ("db *\r", -1);
1510       /* NOTE: PMON does not have breakpoint support through the
1511          "debug" mode, only at the monitor command-line.  */
1512     }
1513
1514   mips_enter_debug ();
1515
1516   /* Clear all breakpoints: */
1517   if ((mips_monitor == MON_IDT
1518        && mips_clear_breakpoint (-1, 0, BREAK_UNUSED) == 0)
1519       || mips_monitor == MON_LSI)
1520     monitor_supports_breakpoints = 1;
1521   else
1522     monitor_supports_breakpoints = 0;
1523
1524   do_cleanups (old_cleanups);
1525
1526   /* If this doesn't call error, we have connected; we don't care if
1527      the request itself succeeds or fails.  */
1528
1529   mips_request ('r', 0, 0, &err, mips_receive_wait, NULL);
1530 }
1531
1532 /* Open a connection to the remote board.  */
1533
1534 static void
1535 common_open (struct target_ops *ops, const char *name, int from_tty,
1536              enum mips_monitor_type new_monitor,
1537              const char *new_monitor_prompt)
1538 {
1539   char *serial_port_name;
1540   char *remote_name = 0;
1541   char *local_name = 0;
1542   char **argv;
1543   struct cleanup *cleanup;
1544
1545   if (name == 0)
1546     error (_("\
1547 To open a MIPS remote debugging connection, you need to specify what\n\
1548 serial device is attached to the target board (e.g., /dev/ttya).\n\
1549 If you want to use TFTP to download to the board, specify the name of a\n\
1550 temporary file to be used by GDB for downloads as the second argument.\n\
1551 This filename must be in the form host:filename, where host is the name\n\
1552 of the host running the TFTP server, and the file must be readable by the\n\
1553 world.  If the local name of the temporary file differs from the name as\n\
1554 seen from the board via TFTP, specify that name as the third parameter.\n"));
1555
1556   /* Parse the serial port name, the optional TFTP name, and the
1557      optional local TFTP name.  */
1558   argv = gdb_buildargv (name);
1559   cleanup = make_cleanup_freeargv (argv);
1560
1561   serial_port_name = xstrdup (argv[0]);
1562   if (argv[1])                  /* Remote TFTP name specified?  */
1563     {
1564       remote_name = argv[1];
1565       if (argv[2])              /* Local TFTP filename specified?  */
1566         local_name = argv[2];
1567     }
1568
1569   target_preopen (from_tty);
1570
1571   if (mips_is_open)
1572     unpush_target (current_ops);
1573
1574   /* Open and initialize the serial port.  */
1575   mips_desc = serial_open (serial_port_name);
1576   if (mips_desc == NULL)
1577     perror_with_name (serial_port_name);
1578
1579   if (baud_rate != -1)
1580     {
1581       if (serial_setbaudrate (mips_desc, baud_rate))
1582         {
1583           serial_close (mips_desc);
1584           perror_with_name (serial_port_name);
1585         }
1586     }
1587
1588   serial_raw (mips_desc);
1589
1590   /* Open and initialize the optional download port.  If it is in the form
1591      hostname#portnumber, it's a UDP socket.  If it is in the form
1592      hostname:filename, assume it's the TFTP filename that must be
1593      passed to the DDB board to tell it where to get the load file.  */
1594   if (remote_name)
1595     {
1596       if (strchr (remote_name, '#'))
1597         {
1598           udp_desc = serial_open (remote_name);
1599           if (!udp_desc)
1600             perror_with_name (_("Unable to open UDP port"));
1601           udp_in_use = 1;
1602         }
1603       else
1604         {
1605           /* Save the remote and local names of the TFTP temp file.  If
1606              the user didn't specify a local name, assume it's the same
1607              as the part of the remote name after the "host:".  */
1608           if (tftp_name)
1609             xfree (tftp_name);
1610           if (tftp_localname)
1611             xfree (tftp_localname);
1612           if (local_name == NULL)
1613             if ((local_name = strchr (remote_name, ':')) != NULL)
1614               local_name++;     /* Skip over the colon.  */
1615           if (local_name == NULL)
1616             local_name = remote_name;   /* Local name same as remote name.  */
1617           tftp_name = xstrdup (remote_name);
1618           tftp_localname = xstrdup (local_name);
1619           tftp_in_use = 1;
1620         }
1621     }
1622
1623   current_ops = ops;
1624   mips_is_open = 1;
1625
1626   /* Reset the expected monitor prompt if it's never been set before.  */
1627   if (mips_monitor_prompt == NULL)
1628     mips_monitor_prompt = xstrdup (new_monitor_prompt);
1629   mips_monitor = new_monitor;
1630
1631   mips_initialize ();
1632
1633   if (from_tty)
1634     printf_unfiltered ("Remote MIPS debugging using %s\n", serial_port_name);
1635
1636   /* Switch to using remote target now.  */
1637   push_target (ops);
1638
1639   inferior_ptid = remote_mips_ptid;
1640   inferior_appeared (current_inferior (), ptid_get_pid (inferior_ptid));
1641   add_thread_silent (inferior_ptid);
1642
1643   /* Try to figure out the processor model if possible.  */
1644   deprecated_mips_set_processor_regs_hack ();
1645
1646   /* This is really the job of start_remote however, that makes an
1647      assumption that the target is about to print out a status message
1648      of some sort.  That doesn't happen here (in fact, it may not be
1649      possible to get the monitor to send the appropriate packet).  */
1650
1651   reinit_frame_cache ();
1652   registers_changed ();
1653   stop_pc = regcache_read_pc (get_current_regcache ());
1654   print_stack_frame (get_selected_frame (NULL), 0, SRC_AND_LOC, 1);
1655   xfree (serial_port_name);
1656
1657   do_cleanups (cleanup);
1658 }
1659
1660 /* Open a connection to an IDT board.  */
1661
1662 static void
1663 mips_open (const char *name, int from_tty)
1664 {
1665   const char *monitor_prompt = NULL;
1666   if (gdbarch_bfd_arch_info (target_gdbarch ()) != NULL
1667       && gdbarch_bfd_arch_info (target_gdbarch ())->arch == bfd_arch_mips)
1668     {
1669     switch (gdbarch_bfd_arch_info (target_gdbarch ())->mach)
1670       {
1671       case bfd_mach_mips4100:
1672       case bfd_mach_mips4300:
1673       case bfd_mach_mips4600:
1674       case bfd_mach_mips4650:
1675       case bfd_mach_mips5000:
1676         monitor_prompt = "<RISQ> ";
1677         break;
1678       }
1679     }
1680   if (monitor_prompt == NULL)
1681     monitor_prompt = "<IDT>";
1682   common_open (&mips_ops, name, from_tty, MON_IDT, monitor_prompt);
1683 }
1684
1685 /* Open a connection to a PMON board.  */
1686
1687 static void
1688 pmon_open (const char *name, int from_tty)
1689 {
1690   common_open (&pmon_ops, name, from_tty, MON_PMON, "PMON> ");
1691 }
1692
1693 /* Open a connection to a DDB board.  */
1694
1695 static void
1696 ddb_open (const char *name, int from_tty)
1697 {
1698   common_open (&ddb_ops, name, from_tty, MON_DDB, "NEC010>");
1699 }
1700
1701 /* Open a connection to a rockhopper board.  */
1702
1703 static void
1704 rockhopper_open (const char *name, int from_tty)
1705 {
1706   common_open (&rockhopper_ops, name, from_tty, MON_ROCKHOPPER, "NEC01>");
1707 }
1708
1709 /* Open a connection to an LSI board.  */
1710
1711 static void
1712 lsi_open (const char *name, int from_tty)
1713 {
1714   int i;
1715
1716   /* Clear the LSI breakpoint table.  */
1717   for (i = 0; i < MAX_LSI_BREAKPOINTS; i++)
1718     lsi_breakpoints[i].type = BREAK_UNUSED;
1719
1720   common_open (&lsi_ops, name, from_tty, MON_LSI, "PMON> ");
1721 }
1722
1723 /* Close a connection to the remote board.  */
1724
1725 static void
1726 mips_close (struct target_ops *self)
1727 {
1728   if (mips_is_open)
1729     {
1730       /* Get the board out of remote debugging mode.  */
1731       (void) mips_exit_debug ();
1732
1733       close_ports ();
1734     }
1735
1736   generic_mourn_inferior ();
1737 }
1738
1739 /* Detach from the remote board.  */
1740
1741 static void
1742 mips_detach (struct target_ops *ops, const char *args, int from_tty)
1743 {
1744   if (args)
1745     error (_("Argument given to \"detach\" when remotely debugging."));
1746
1747   unpush_target (ops);
1748
1749   if (from_tty)
1750     printf_unfiltered ("Ending remote MIPS debugging.\n");
1751 }
1752
1753 /* Tell the target board to resume.  This does not wait for a reply
1754    from the board, except in the case of single-stepping on LSI boards,
1755    where PMON does return a reply.  */
1756
1757 static void
1758 mips_resume (struct target_ops *ops,
1759              ptid_t ptid, int step, enum gdb_signal siggnal)
1760 {
1761   int err;
1762
1763   /* LSI PMON requires returns a reply packet "0x1 s 0x0 0x57f" after
1764      a single step, so we wait for that.  */
1765   mips_request (step ? 's' : 'c', 1, siggnal,
1766                 mips_monitor == MON_LSI && step ? &err : (int *) NULL,
1767                 mips_receive_wait, NULL);
1768 }
1769
1770 /* Return the signal corresponding to SIG, where SIG is the number which
1771    the MIPS protocol uses for the signal.  */
1772
1773 static enum gdb_signal
1774 mips_signal_from_protocol (int sig)
1775 {
1776   /* We allow a few more signals than the IDT board actually returns, on
1777      the theory that there is at least *some* hope that perhaps the numbering
1778      for these signals is widely agreed upon.  */
1779   if (sig <= 0
1780       || sig > 31)
1781     return GDB_SIGNAL_UNKNOWN;
1782
1783   /* Don't want to use gdb_signal_from_host because we are converting
1784      from MIPS signal numbers, not host ones.  Our internal numbers
1785      match the MIPS numbers for the signals the board can return, which
1786      are: SIGINT, SIGSEGV, SIGBUS, SIGILL, SIGFPE, SIGTRAP.  */
1787   return (enum gdb_signal) sig;
1788 }
1789
1790 /* Set the register designated by REGNO to the value designated by VALUE.  */
1791
1792 static void
1793 mips_set_register (int regno, ULONGEST value)
1794 {
1795   gdb_byte buf[MAX_REGISTER_SIZE];
1796   struct regcache *regcache = get_current_regcache ();
1797   struct gdbarch *gdbarch = get_regcache_arch (regcache);
1798   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1799
1800   /* We got the number the register holds, but gdb expects to see a
1801      value in the target byte ordering.  */
1802
1803   if (mips_monitor != MON_ROCKHOPPER
1804       && (regno == mips_regnum (gdbarch)->pc || regno < 32))
1805     /* Some 64-bit boards have monitors that only send the bottom 32 bits.
1806        In such cases we can only really debug 32-bit code properly so,
1807        when reading a GPR or the PC, assume that the full 64-bit
1808        value is the sign extension of the lower 32 bits.  */
1809     store_signed_integer (buf, register_size (gdbarch, regno), byte_order,
1810                           value);
1811   else
1812     store_unsigned_integer (buf, register_size (gdbarch, regno), byte_order,
1813                             value);
1814
1815   regcache_raw_supply (regcache, regno, buf);
1816 }
1817
1818 /* Wait until the remote stops, and return a wait status.  */
1819
1820 static ptid_t
1821 mips_wait (struct target_ops *ops,
1822            ptid_t ptid, struct target_waitstatus *status, int options)
1823 {
1824   int rstatus;
1825   int err;
1826   char buff[DATA_MAXLEN];
1827   ULONGEST rpc, rfp, rsp;
1828   char pc_string[17], fp_string[17], sp_string[17], flags[20];
1829   int nfields;
1830
1831   interrupt_count = 0;
1832   hit_watchpoint = 0;
1833
1834   /* If we have not sent a single step or continue command, then the
1835      board is waiting for us to do something.  Return a status
1836      indicating that it is stopped.  */
1837   if (!mips_need_reply)
1838     {
1839       status->kind = TARGET_WAITKIND_STOPPED;
1840       status->value.sig = GDB_SIGNAL_TRAP;
1841       return inferior_ptid;
1842     }
1843
1844   /* No timeout; we sit here as long as the program continues to execute.  */
1845   mips_wait_flag = 1;
1846   rstatus = mips_request ('\000', 0, 0, &err, -1, buff);
1847   mips_wait_flag = 0;
1848   if (err)
1849     mips_error (_("Remote failure: %s"), safe_strerror (errno));
1850
1851   /* On returning from a continue, the PMON monitor seems to start
1852      echoing back the messages we send prior to sending back the
1853      ACK.  The code can cope with this, but to try and avoid the
1854      unnecessary serial traffic, and "spurious" characters displayed
1855      to the user, we cheat and reset the debug protocol.  The problems
1856      seems to be caused by a check on the number of arguments, and the
1857      command length, within the monitor causing it to echo the command
1858      as a bad packet.  */
1859   if (mips_monitor == MON_PMON)
1860     {
1861       mips_exit_debug ();
1862       mips_enter_debug ();
1863     }
1864
1865   /* See if we got back extended status.  If so, pick out the pc, fp,
1866      sp, etc...  */
1867
1868   nfields = sscanf (buff,
1869                     "0x%*x %*c 0x%*x 0x%*x 0x%16s 0x%16s 0x%16s 0x%*x %s",
1870                     pc_string, fp_string, sp_string, flags);
1871   if (nfields >= 3
1872       && read_hex_value (pc_string, &rpc)
1873       && read_hex_value (fp_string, &rfp)
1874       && read_hex_value (sp_string, &rsp))
1875     {
1876       struct regcache *regcache = get_current_regcache ();
1877       struct gdbarch *gdbarch = get_regcache_arch (regcache);
1878
1879       mips_set_register (gdbarch_pc_regnum (gdbarch), rpc);
1880       mips_set_register (30, rfp);
1881       mips_set_register (gdbarch_sp_regnum (gdbarch), rsp);
1882
1883       if (nfields == 9)
1884         {
1885           int i;
1886
1887           for (i = 0; i <= 2; i++)
1888             if (flags[i] == 'r' || flags[i] == 'w')
1889               hit_watchpoint = 1;
1890             else if (flags[i] == '\000')
1891               break;
1892         }
1893     }
1894
1895   if (strcmp (target_shortname, "lsi") == 0)
1896     {
1897 #if 0
1898       /* If this is an LSI PMON target, see if we just hit a
1899          hardrdware watchpoint.  Right now, PMON doesn't give us
1900          enough information to determine which breakpoint we hit.  So
1901          we have to look up the PC in our own table of breakpoints,
1902          and if found, assume it's just a normal instruction fetch
1903          breakpoint, not a data watchpoint.  FIXME when PMON provides
1904          some way to tell us what type of breakpoint it is.  */
1905       int i;
1906       CORE_ADDR pc = regcache_read_pc (get_current_regcache ());
1907
1908       hit_watchpoint = 1;
1909       for (i = 0; i < MAX_LSI_BREAKPOINTS; i++)
1910         {
1911           if (lsi_breakpoints[i].addr == pc
1912               && lsi_breakpoints[i].type == BREAK_FETCH)
1913             {
1914               hit_watchpoint = 0;
1915               break;
1916             }
1917         }
1918 #else
1919       /* If a data breakpoint was hit, PMON returns the following packet:
1920          0x1 c 0x0 0x57f 0x1
1921          The return packet from an ordinary breakpoint doesn't have the
1922          extra 0x01 field tacked onto the end.  */
1923       if (nfields == 1 && rpc == 1)
1924         hit_watchpoint = 1;
1925 #endif
1926     }
1927
1928   /* NOTE: The following (sig) numbers are defined by PMON:
1929      SPP_SIGTRAP     5       breakpoint
1930      SPP_SIGINT      2
1931      SPP_SIGSEGV     11
1932      SPP_SIGBUS      10
1933      SPP_SIGILL      4
1934      SPP_SIGFPE      8
1935      SPP_SIGTERM     15 */
1936
1937   /* Translate a MIPS waitstatus.  We use constants here rather than WTERMSIG
1938      and so on, because the constants we want here are determined by the
1939      MIPS protocol and have nothing to do with what host we are running on.  */
1940   if ((rstatus & 0xff) == 0)
1941     {
1942       status->kind = TARGET_WAITKIND_EXITED;
1943       status->value.integer = (((rstatus) >> 8) & 0xff);
1944     }
1945   else if ((rstatus & 0xff) == 0x7f)
1946     {
1947       status->kind = TARGET_WAITKIND_STOPPED;
1948       status->value.sig = mips_signal_from_protocol (((rstatus) >> 8) & 0xff);
1949
1950       /* If the stop PC is in the _exit function, assume
1951          we hit the 'break 0x3ff' instruction in _exit, so this
1952          is not a normal breakpoint.  */
1953       if (strcmp (target_shortname, "lsi") == 0)
1954         {
1955           const char *func_name;
1956           CORE_ADDR func_start;
1957           CORE_ADDR pc = regcache_read_pc (get_current_regcache ());
1958
1959           find_pc_partial_function (pc, &func_name, &func_start, NULL);
1960           if (func_name != NULL && strcmp (func_name, "_exit") == 0
1961               && func_start == pc)
1962             status->kind = TARGET_WAITKIND_EXITED;
1963         }
1964     }
1965   else
1966     {
1967       status->kind = TARGET_WAITKIND_SIGNALLED;
1968       status->value.sig = mips_signal_from_protocol (rstatus & 0x7f);
1969     }
1970
1971   return inferior_ptid;
1972 }
1973
1974 /* We have to map between the register numbers used by gdb and the
1975    register numbers used by the debugging protocol.  */
1976
1977 #define REGNO_OFFSET 96
1978
1979 static int
1980 mips_map_regno (struct gdbarch *gdbarch, int regno)
1981 {
1982   if (regno < 32)
1983     return regno;
1984   if (regno >= mips_regnum (gdbarch)->fp0
1985       && regno < mips_regnum (gdbarch)->fp0 + 32)
1986     return regno - mips_regnum (gdbarch)->fp0 + 32;
1987   else if (regno == mips_regnum (gdbarch)->pc)
1988     return REGNO_OFFSET + 0;
1989   else if (regno == mips_regnum (gdbarch)->cause)
1990     return REGNO_OFFSET + 1;
1991   else if (regno == mips_regnum (gdbarch)->hi)
1992     return REGNO_OFFSET + 2;
1993   else if (regno == mips_regnum (gdbarch)->lo)
1994     return REGNO_OFFSET + 3;
1995   else if (regno == mips_regnum (gdbarch)->fp_control_status)
1996     return REGNO_OFFSET + 4;
1997   else if (regno == mips_regnum (gdbarch)->fp_implementation_revision)
1998     return REGNO_OFFSET + 5;
1999   else
2000     /* FIXME: Is there a way to get the status register?  */
2001     return 0;
2002 }
2003
2004 /* Fetch the remote registers.  */
2005
2006 static void
2007 mips_fetch_registers (struct target_ops *ops,
2008                       struct regcache *regcache, int regno)
2009 {
2010   struct gdbarch *gdbarch = get_regcache_arch (regcache);
2011   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
2012   ULONGEST val;
2013   int err;
2014
2015   if (regno == -1)
2016     {
2017       for (regno = 0; regno < gdbarch_num_regs (gdbarch); regno++)
2018         mips_fetch_registers (ops, regcache, regno);
2019       return;
2020     }
2021
2022   if (regno == gdbarch_deprecated_fp_regnum (gdbarch)
2023       || regno == MIPS_ZERO_REGNUM)
2024     /* gdbarch_deprecated_fp_regnum on the mips is a hack which is just
2025        supposed to read zero (see also mips-nat.c).  */
2026     val = 0;
2027   else
2028     {
2029       /* If PMON doesn't support this register, don't waste serial
2030          bandwidth trying to read it.  */
2031       int pmon_reg = mips_map_regno (gdbarch, regno);
2032
2033       if (regno != 0 && pmon_reg == 0)
2034         val = 0;
2035       else
2036         {
2037           /* Unfortunately the PMON version in the Vr4300 board has been
2038              compiled without the 64bit register access commands.  This
2039              means we cannot get hold of the full register width.  */
2040           if (mips_monitor == MON_DDB || mips_monitor == MON_ROCKHOPPER)
2041             val = mips_request ('t', pmon_reg, 0,
2042                                 &err, mips_receive_wait, NULL);
2043           else
2044             val = mips_request ('r', pmon_reg, 0,
2045                                 &err, mips_receive_wait, NULL);
2046           if (err)
2047             mips_error (_("Can't read register %d: %s"), regno,
2048                         safe_strerror (errno));
2049         }
2050     }
2051
2052   mips_set_register (regno, val);
2053 }
2054
2055 /* Prepare to store registers.  The MIPS protocol can store individual
2056    registers, so this function doesn't have to do anything.  */
2057
2058 static void
2059 mips_prepare_to_store (struct target_ops *self, struct regcache *regcache)
2060 {
2061 }
2062
2063 /* Store remote register(s).  */
2064
2065 static void
2066 mips_store_registers (struct target_ops *ops,
2067                       struct regcache *regcache, int regno)
2068 {
2069   struct gdbarch *gdbarch = get_regcache_arch (regcache);
2070   ULONGEST val;
2071   int err;
2072
2073   if (regno == -1)
2074     {
2075       for (regno = 0; regno < gdbarch_num_regs (gdbarch); regno++)
2076         mips_store_registers (ops, regcache, regno);
2077       return;
2078     }
2079
2080   regcache_cooked_read_unsigned (regcache, regno, &val);
2081   mips_request (mips_monitor == MON_ROCKHOPPER ? 'T' : 'R',
2082                 mips_map_regno (gdbarch, regno),
2083                 val,
2084                 &err, mips_receive_wait, NULL);
2085   if (err)
2086     mips_error (_("Can't write register %d: %s"), regno,
2087                 safe_strerror (errno));
2088 }
2089
2090 /* Fetch a word from the target board.  Return word fetched in location
2091    addressed by VALP.  Return 0 when successful; return positive error
2092    code when not.  */
2093
2094 static int
2095 mips_fetch_word (CORE_ADDR addr, unsigned int *valp)
2096 {
2097   int err;
2098
2099   *valp = mips_request ('d', addr, 0, &err, mips_receive_wait, NULL);
2100   if (err)
2101     {
2102       /* Data space failed; try instruction space.  */
2103       *valp = mips_request ('i', addr, 0, &err,
2104                             mips_receive_wait, NULL);
2105     }
2106   return err;
2107 }
2108
2109 /* Store a word to the target board.  Returns errno code or zero for
2110    success.  If OLD_CONTENTS is non-NULL, put the old contents of that
2111    memory location there.  */
2112
2113 /* FIXME! make sure only 32-bit quantities get stored!  */
2114 static int
2115 mips_store_word (CORE_ADDR addr, unsigned int val, int *old_contents)
2116 {
2117   int err;
2118   unsigned int oldcontents;
2119
2120   oldcontents = mips_request ('D', addr, val, &err,
2121                               mips_receive_wait, NULL);
2122   if (err)
2123     {
2124       /* Data space failed; try instruction space.  */
2125       oldcontents = mips_request ('I', addr, val, &err,
2126                                   mips_receive_wait, NULL);
2127       if (err)
2128         return errno;
2129     }
2130   if (old_contents != NULL)
2131     *old_contents = oldcontents;
2132   return 0;
2133 }
2134
2135 /* Helper for mips_xfer_partial that handles memory transfers.
2136    Arguments are like target_xfer_partial.  Note that the protocol
2137    gives us the correct value for a longword, since it transfers
2138    values in ASCII.  We want the byte values, so we have to swap the
2139    longword values.  */
2140
2141 static int mask_address_p = 1;
2142
2143 static enum target_xfer_status
2144 mips_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
2145                   ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
2146 {
2147   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
2148   int i;
2149   CORE_ADDR addr;
2150   int count;
2151   gdb_byte *buffer;
2152   int status;
2153
2154   /* PMON targets do not cope well with 64 bit addresses.  Mask the
2155      value down to 32 bits.  */
2156   if (mask_address_p)
2157     memaddr &= (CORE_ADDR) 0xffffffff;
2158
2159   /* Round starting address down to longword boundary.  */
2160   addr = memaddr & ~3;
2161   /* Round ending address up; get number of longwords that makes.  */
2162   count = (((memaddr + len) - addr) + 3) / 4;
2163   /* Allocate buffer of that many longwords.  */
2164   buffer = alloca (count * 4);
2165
2166   if (writebuf != NULL)
2167     {
2168       /* Fill start and end extra bytes of buffer with existing data.  */
2169       if (addr != memaddr || len < 4)
2170         {
2171           unsigned int val;
2172
2173           if (mips_fetch_word (addr, &val))
2174             return TARGET_XFER_E_IO;
2175
2176           /* Need part of initial word -- fetch it.  */
2177           store_unsigned_integer (&buffer[0], 4, byte_order, val);
2178         }
2179
2180       if (count > 1)
2181         {
2182           unsigned int val;
2183
2184           /* Need part of last word -- fetch it.  FIXME: we do this even
2185              if we don't need it.  */
2186           if (mips_fetch_word (addr + (count - 1) * 4, &val))
2187             return TARGET_XFER_E_IO;
2188
2189           store_unsigned_integer (&buffer[(count - 1) * 4],
2190                                   4, byte_order, val);
2191         }
2192
2193       /* Copy data to be written over corresponding part of buffer.  */
2194
2195       memcpy ((char *) buffer + (memaddr & 3), writebuf, len);
2196
2197       /* Write the entire buffer.  */
2198
2199       for (i = 0; i < count; i++, addr += 4)
2200         {
2201           int word;
2202
2203           word = extract_unsigned_integer (&buffer[i * 4], 4, byte_order);
2204           status = mips_store_word (addr, word, NULL);
2205           /* Report each kilobyte (we download 32-bit words at a time).  */
2206           if (i % 256 == 255)
2207             {
2208               printf_unfiltered ("*");
2209               gdb_flush (gdb_stdout);
2210             }
2211           if (status)
2212             return TARGET_XFER_E_IO;
2213           /* FIXME: Do we want a QUIT here?  */
2214         }
2215       if (count >= 256)
2216         printf_unfiltered ("\n");
2217     }
2218   else
2219     {
2220       /* Read all the longwords.  */
2221       for (i = 0; i < count; i++, addr += 4)
2222         {
2223           unsigned int val;
2224
2225           if (mips_fetch_word (addr, &val))
2226             return TARGET_XFER_E_IO;
2227
2228           store_unsigned_integer (&buffer[i * 4], 4, byte_order, val);
2229           QUIT;
2230         }
2231
2232       /* Copy appropriate bytes out of the buffer.  */
2233       memcpy (readbuf, buffer + (memaddr & 3), len);
2234     }
2235   return len;
2236 }
2237
2238 /* Target to_xfer_partial implementation.  */
2239
2240 static enum target_xfer_status
2241 mips_xfer_partial (struct target_ops *ops, enum target_object object,
2242                    const char *annex, gdb_byte *readbuf,
2243                    const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
2244                    ULONGEST *xfered_len)
2245 {
2246   switch (object)
2247     {
2248     case TARGET_OBJECT_MEMORY:
2249       return mips_xfer_memory (readbuf, writebuf, offset, len, xfered_len);
2250
2251     default:
2252       return ops->beneath->to_xfer_partial (ops->beneath, object, annex,
2253                                             readbuf, writebuf, offset, len,
2254                                             xfered_len);
2255     }
2256 }
2257
2258 /* Print info on this target.  */
2259
2260 static void
2261 mips_files_info (struct target_ops *ignore)
2262 {
2263   printf_unfiltered ("Debugging a MIPS board over a serial line.\n");
2264 }
2265
2266 /* Kill the process running on the board.  This will actually only
2267    work if we are doing remote debugging over the console input.  I
2268    think that if IDT/sim had the remote debug interrupt enabled on the
2269    right port, we could interrupt the process with a break signal.  */
2270
2271 static void
2272 mips_kill (struct target_ops *ops)
2273 {
2274   if (!mips_wait_flag)
2275     {
2276       target_mourn_inferior ();
2277       return;
2278     }
2279
2280   interrupt_count++;
2281
2282   if (interrupt_count >= 2)
2283     {
2284       interrupt_count = 0;
2285
2286       target_terminal_ours ();
2287
2288       if (query (_("Interrupted while waiting for the program.\n\
2289 Give up (and stop debugging it)? ")))
2290         {
2291           /* Clean up in such a way that mips_close won't try to talk
2292              to the board (it almost surely won't work since we
2293              weren't able to talk to it).  */
2294           mips_wait_flag = 0;
2295           close_ports ();
2296
2297           printf_unfiltered ("Ending remote MIPS debugging.\n");
2298           target_mourn_inferior ();
2299           quit ();
2300         }
2301
2302       target_terminal_inferior ();
2303     }
2304
2305   if (remote_debug > 0)
2306     printf_unfiltered ("Sending break\n");
2307
2308   serial_send_break (mips_desc);
2309
2310   target_mourn_inferior ();
2311
2312 #if 0
2313   if (mips_is_open)
2314     {
2315       char cc;
2316
2317       /* Send a ^C.  */
2318       cc = '\003';
2319       serial_write (mips_desc, &cc, 1);
2320       sleep (1);
2321       target_mourn_inferior ();
2322     }
2323 #endif
2324 }
2325
2326 /* Start running on the target board.  */
2327
2328 static void
2329 mips_create_inferior (struct target_ops *ops, char *execfile,
2330                       char *args, char **env, int from_tty)
2331 {
2332   CORE_ADDR entry_pt;
2333
2334   if (args && *args)
2335     {
2336       warning (_("\
2337 Can't pass arguments to remote MIPS board; arguments ignored."));
2338       /* And don't try to use them on the next "run" command.  */
2339       execute_command ("set args", 0);
2340     }
2341
2342   if (execfile == 0 || exec_bfd == 0)
2343     error (_("No executable file specified"));
2344
2345   entry_pt = (CORE_ADDR) bfd_get_start_address (exec_bfd);
2346
2347   init_wait_for_inferior ();
2348
2349   regcache_write_pc (get_current_regcache (), entry_pt);
2350 }
2351
2352 /* Clean up after a process. The bulk of the work is done in mips_close(),
2353    which is called when unpushing the target.  */
2354
2355 static void
2356 mips_mourn_inferior (struct target_ops *ops)
2357 {
2358   if (current_ops != NULL)
2359     unpush_target (current_ops);
2360 }
2361 \f
2362 /* We can write a breakpoint and read the shadow contents in one
2363    operation.  */
2364
2365 /* Insert a breakpoint.  On targets that don't have built-in
2366    breakpoint support, we read the contents of the target location and
2367    stash it, then overwrite it with a breakpoint instruction.  ADDR is
2368    the target location in the target machine.  BPT is the breakpoint
2369    being inserted or removed, which contains memory for saving the
2370    target contents.  */
2371
2372 static int
2373 mips_insert_breakpoint (struct target_ops *ops, struct gdbarch *gdbarch,
2374                         struct bp_target_info *bp_tgt)
2375 {
2376   if (monitor_supports_breakpoints)
2377     return mips_set_breakpoint (bp_tgt->placed_address, MIPS_INSN32_SIZE,
2378                                 BREAK_FETCH);
2379   else
2380     return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
2381 }
2382
2383 /* Remove a breakpoint.  */
2384
2385 static int
2386 mips_remove_breakpoint (struct target_ops *ops, struct gdbarch *gdbarch,
2387                         struct bp_target_info *bp_tgt)
2388 {
2389   if (monitor_supports_breakpoints)
2390     return mips_clear_breakpoint (bp_tgt->placed_address, MIPS_INSN32_SIZE,
2391                                   BREAK_FETCH);
2392   else
2393     return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
2394 }
2395
2396 /* Tell whether this target can support a hardware breakpoint.  CNT
2397    is the number of hardware breakpoints already installed.  This
2398    implements the target_can_use_hardware_watchpoint macro.  */
2399
2400 static int
2401 mips_can_use_watchpoint (struct target_ops *self,
2402                          int type, int cnt, int othertype)
2403 {
2404   return cnt < MAX_LSI_BREAKPOINTS && strcmp (target_shortname, "lsi") == 0;
2405 }
2406
2407
2408 /* Compute a don't care mask for the region bounding ADDR and ADDR + LEN - 1.
2409    This is used for memory ref breakpoints.  */
2410
2411 static unsigned long
2412 calculate_mask (CORE_ADDR addr, int len)
2413 {
2414   unsigned long mask;
2415   int i;
2416
2417   mask = addr ^ (addr + len - 1);
2418
2419   for (i = 32; i >= 0; i--)
2420     if (mask == 0)
2421       break;
2422     else
2423       mask >>= 1;
2424
2425   mask = (unsigned long) 0xffffffff >> i;
2426
2427   return mask;
2428 }
2429
2430
2431 /* Set a data watchpoint.  ADDR and LEN should be obvious.  TYPE is 0
2432    for a write watchpoint, 1 for a read watchpoint, or 2 for a read/write
2433    watchpoint.  */
2434
2435 static int
2436 mips_insert_watchpoint (struct target_ops *self,
2437                         CORE_ADDR addr, int len, int type,
2438                         struct expression *cond)
2439 {
2440   if (mips_set_breakpoint (addr, len, type))
2441     return -1;
2442
2443   return 0;
2444 }
2445
2446 /* Remove a watchpoint.  */
2447
2448 static int
2449 mips_remove_watchpoint (struct target_ops *self,
2450                         CORE_ADDR addr, int len, int type,
2451                         struct expression *cond)
2452 {
2453   if (mips_clear_breakpoint (addr, len, type))
2454     return -1;
2455
2456   return 0;
2457 }
2458
2459 /* Test to see if a watchpoint has been hit.  Return 1 if so; return 0,
2460    if not.  */
2461
2462 static int
2463 mips_stopped_by_watchpoint (struct target_ops *ops)
2464 {
2465   return hit_watchpoint;
2466 }
2467
2468
2469 /* Insert a breakpoint.  */
2470
2471 static int
2472 mips_set_breakpoint (CORE_ADDR addr, int len, enum break_type type)
2473 {
2474   return mips_common_breakpoint (1, addr, len, type);
2475 }
2476
2477
2478 /* Clear a breakpoint.  */
2479
2480 static int
2481 mips_clear_breakpoint (CORE_ADDR addr, int len, enum break_type type)
2482 {
2483   return mips_common_breakpoint (0, addr, len, type);
2484 }
2485
2486
2487 /* Check the error code from the return packet for an LSI breakpoint
2488    command.  If there's no error, just return 0.  If it's a warning,
2489    print the warning text and return 0.  If it's an error, print
2490    the error text and return 1.  <ADDR> is the address of the breakpoint
2491    that was being set.  <RERRFLG> is the error code returned by PMON.
2492    This is a helper function for mips_common_breakpoint.  */
2493
2494 static int
2495 mips_check_lsi_error (CORE_ADDR addr, int rerrflg)
2496 {
2497   struct lsi_error *err;
2498   const char *saddr = paddress (target_gdbarch (), addr);
2499
2500   if (rerrflg == 0)             /* no error */
2501     return 0;
2502
2503   /* Warnings can be ORed together, so check them all.  */
2504   if (rerrflg & W_WARN)
2505     {
2506       if (monitor_warnings)
2507         {
2508           int found = 0;
2509
2510           for (err = lsi_warning_table; err->code != 0; err++)
2511             {
2512               if ((err->code & rerrflg) == err->code)
2513                 {
2514                   found = 1;
2515                   fprintf_unfiltered (gdb_stderr, "\
2516 mips_common_breakpoint (%s): Warning: %s\n",
2517                                       saddr,
2518                                       err->string);
2519                 }
2520             }
2521           if (!found)
2522             fprintf_unfiltered (gdb_stderr, "\
2523 mips_common_breakpoint (%s): Unknown warning: 0x%x\n",
2524                                 saddr,
2525                                 rerrflg);
2526         }
2527       return 0;
2528     }
2529
2530   /* Errors are unique, i.e. can't be ORed together.  */
2531   for (err = lsi_error_table; err->code != 0; err++)
2532     {
2533       if ((err->code & rerrflg) == err->code)
2534         {
2535           fprintf_unfiltered (gdb_stderr, "\
2536 mips_common_breakpoint (%s): Error: %s\n",
2537                               saddr,
2538                               err->string);
2539           return 1;
2540         }
2541     }
2542   fprintf_unfiltered (gdb_stderr, "\
2543 mips_common_breakpoint (%s): Unknown error: 0x%x\n",
2544                       saddr,
2545                       rerrflg);
2546   return 1;
2547 }
2548
2549
2550 /* This routine sends a breakpoint command to the remote target.
2551
2552    <SET> is 1 if setting a breakpoint, or 0 if clearing a breakpoint.
2553    <ADDR> is the address of the breakpoint.
2554    <LEN> the length of the region to break on.
2555    <TYPE> is the type of breakpoint:
2556    0 = write                    (BREAK_WRITE)
2557    1 = read                     (BREAK_READ)
2558    2 = read/write               (BREAK_ACCESS)
2559    3 = instruction fetch        (BREAK_FETCH)
2560
2561    Return 0 if successful; otherwise 1.  */
2562
2563 static int
2564 mips_common_breakpoint (int set, CORE_ADDR addr, int len, enum break_type type)
2565 {
2566   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
2567   char buf[DATA_MAXLEN + 1];
2568   char cmd, rcmd;
2569   int rpid, rerrflg, rresponse, rlen;
2570   int nfields;
2571
2572   addr = gdbarch_addr_bits_remove (target_gdbarch (), addr);
2573
2574   if (mips_monitor == MON_LSI)
2575     {
2576       if (set == 0)             /* clear breakpoint */
2577         {
2578           /* The LSI PMON "clear breakpoint" has this form:
2579              <pid> 'b' <bptn> 0x0
2580              reply:
2581              <pid> 'b' 0x0 <code>
2582
2583              <bptn> is a breakpoint number returned by an earlier 'B' command.
2584              Possible return codes: OK, E_BPT.  */
2585
2586           int i;
2587
2588           /* Search for the breakpoint in the table.  */
2589           for (i = 0; i < MAX_LSI_BREAKPOINTS; i++)
2590             if (lsi_breakpoints[i].type == type
2591                 && lsi_breakpoints[i].addr == addr
2592                 && lsi_breakpoints[i].len == len)
2593               break;
2594
2595           /* Clear the table entry and tell PMON to clear the breakpoint.  */
2596           if (i == MAX_LSI_BREAKPOINTS)
2597             {
2598               warning (_("\
2599 mips_common_breakpoint: Attempt to clear bogus breakpoint at %s"),
2600                        paddress (target_gdbarch (), addr));
2601               return 1;
2602             }
2603
2604           lsi_breakpoints[i].type = BREAK_UNUSED;
2605           sprintf (buf, "0x0 b 0x%x 0x0", i);
2606           mips_send_packet (buf, 1);
2607
2608           rlen = mips_receive_packet (buf, 1, mips_receive_wait);
2609           buf[rlen] = '\0';
2610
2611           nfields = sscanf (buf, "0x%x b 0x0 0x%x", &rpid, &rerrflg);
2612           if (nfields != 2)
2613             mips_error (_("mips_common_breakpoint: "
2614                         "Bad response from remote board: %s"),
2615                         buf);
2616
2617           return (mips_check_lsi_error (addr, rerrflg));
2618         }
2619       else
2620         /* set a breakpoint */
2621         {
2622           /* The LSI PMON "set breakpoint" command has this form:
2623              <pid> 'B' <addr> 0x0
2624              reply:
2625              <pid> 'B' <bptn> <code>
2626
2627              The "set data breakpoint" command has this form:
2628
2629              <pid> 'A' <addr1> <type> [<addr2>  [<value>]]
2630
2631              where: type= "0x1" = read
2632              "0x2" = write
2633              "0x3" = access (read or write)
2634
2635              The reply returns two values:
2636              bptn - a breakpoint number, which is a small integer with
2637              possible values of zero through 255.
2638              code - an error return code, a value of zero indicates a
2639              succesful completion, other values indicate various
2640              errors and warnings.
2641
2642              Possible return codes: OK, W_QAL, E_QAL, E_OUT, E_NON.  */
2643
2644           if (type == BREAK_FETCH)      /* instruction breakpoint */
2645             {
2646               cmd = 'B';
2647               sprintf (buf, "0x0 B 0x%s 0x0", phex_nz (addr, addr_size));
2648             }
2649           else
2650             /* watchpoint */
2651             {
2652               cmd = 'A';
2653               sprintf (buf, "0x0 A 0x%s 0x%x 0x%s",
2654                        phex_nz (addr, addr_size),
2655                        type == BREAK_READ ? 1 : (type == BREAK_WRITE ? 2 : 3),
2656                        phex_nz (addr + len - 1, addr_size));
2657             }
2658           mips_send_packet (buf, 1);
2659
2660           rlen = mips_receive_packet (buf, 1, mips_receive_wait);
2661           buf[rlen] = '\0';
2662
2663           nfields = sscanf (buf, "0x%x %c 0x%x 0x%x",
2664                             &rpid, &rcmd, &rresponse, &rerrflg);
2665           if (nfields != 4 || rcmd != cmd || rresponse > 255)
2666             mips_error (_("mips_common_breakpoint: "
2667                         "Bad response from remote board: %s"),
2668                         buf);
2669
2670           if (rerrflg != 0)
2671             if (mips_check_lsi_error (addr, rerrflg))
2672               return 1;
2673
2674           /* rresponse contains PMON's breakpoint number.  Record the
2675              information for this breakpoint so we can clear it later.  */
2676           lsi_breakpoints[rresponse].type = type;
2677           lsi_breakpoints[rresponse].addr = addr;
2678           lsi_breakpoints[rresponse].len = len;
2679
2680           return 0;
2681         }
2682     }
2683   else
2684     {
2685       /* On non-LSI targets, the breakpoint command has this form:
2686          0x0 <CMD> <ADDR> <MASK> <FLAGS>
2687          <MASK> is a don't care mask for addresses.
2688          <FLAGS> is any combination of `r', `w', or `f' for 
2689          read/write/fetch.  */
2690
2691       unsigned long mask;
2692
2693       mask = calculate_mask (addr, len);
2694       addr &= ~mask;
2695
2696       if (set)                  /* set a breakpoint */
2697         {
2698           char *flags;
2699
2700           switch (type)
2701             {
2702             case BREAK_WRITE:   /* write */
2703               flags = "w";
2704               break;
2705             case BREAK_READ:    /* read */
2706               flags = "r";
2707               break;
2708             case BREAK_ACCESS:  /* read/write */
2709               flags = "rw";
2710               break;
2711             case BREAK_FETCH:   /* fetch */
2712               flags = "f";
2713               break;
2714             default:
2715               internal_error (__FILE__, __LINE__,
2716                               _("failed internal consistency check"));
2717             }
2718
2719           cmd = 'B';
2720           sprintf (buf, "0x0 B 0x%s 0x%s %s", phex_nz (addr, addr_size),
2721                    phex_nz (mask, addr_size), flags);
2722         }
2723       else
2724         {
2725           cmd = 'b';
2726           sprintf (buf, "0x0 b 0x%s", phex_nz (addr, addr_size));
2727         }
2728
2729       mips_send_packet (buf, 1);
2730
2731       rlen = mips_receive_packet (buf, 1, mips_receive_wait);
2732       buf[rlen] = '\0';
2733
2734       nfields = sscanf (buf, "0x%x %c 0x%x 0x%x",
2735                         &rpid, &rcmd, &rerrflg, &rresponse);
2736
2737       if (nfields != 4 || rcmd != cmd)
2738         mips_error (_("mips_common_breakpoint: "
2739                     "Bad response from remote board: %s"),
2740                     buf);
2741
2742       if (rerrflg != 0)
2743         {
2744           /* Ddb returns "0x0 b 0x16 0x0\000", whereas
2745              Cogent returns "0x0 b 0xffffffff 0x16\000": */
2746           if (mips_monitor == MON_DDB)
2747             rresponse = rerrflg;
2748           if (rresponse != 22)  /* invalid argument */
2749             fprintf_unfiltered (gdb_stderr, "\
2750 mips_common_breakpoint (%s):  Got error: 0x%x\n",
2751                                 paddress (target_gdbarch (), addr), rresponse);
2752           return 1;
2753         }
2754     }
2755   return 0;
2756 }
2757 \f
2758 /* Send one S record as specified by SREC of length LEN, starting
2759    at ADDR.  Note, however, that ADDR is not used except to provide
2760    a useful message to the user in the event that a NACK is received
2761    from the board.  */
2762
2763 static void
2764 send_srec (char *srec, int len, CORE_ADDR addr)
2765 {
2766   while (1)
2767     {
2768       int ch;
2769
2770       serial_write (mips_desc, srec, len);
2771
2772       ch = mips_readchar (remote_timeout);
2773
2774       switch (ch)
2775         {
2776         case SERIAL_TIMEOUT:
2777           error (_("Timeout during download."));
2778           break;
2779         case 0x6:               /* ACK */
2780           return;
2781         case 0x15:              /* NACK */
2782           fprintf_unfiltered (gdb_stderr,
2783                               "Download got a NACK at byte %s!  Retrying.\n",
2784                               paddress (target_gdbarch (), addr));
2785           continue;
2786         default:
2787           error (_("Download got unexpected ack char: 0x%x, retrying."),
2788                  ch);
2789         }
2790     }
2791 }
2792
2793 /*  Download a binary file by converting it to S records.  */
2794
2795 static void
2796 mips_load_srec (const char *args)
2797 {
2798   bfd *abfd;
2799   asection *s;
2800   char srec[1024];
2801   bfd_byte *buffer;
2802   unsigned int i;
2803   unsigned int srec_frame = 200;
2804   int reclen;
2805   struct cleanup *cleanup;
2806   static int hashmark = 1;
2807
2808   buffer = alloca (srec_frame * 2 + 256);
2809
2810   abfd = gdb_bfd_open (args, NULL, -1);
2811   if (!abfd)
2812     {
2813       printf_filtered ("Unable to open file %s\n", args);
2814       return;
2815     }
2816
2817   cleanup = make_cleanup_bfd_unref (abfd);
2818   if (bfd_check_format (abfd, bfd_object) == 0)
2819     {
2820       printf_filtered ("File is not an object file\n");
2821       do_cleanups (cleanup);
2822       return;
2823     }
2824
2825 /* This actually causes a download in the IDT binary format: */
2826   mips_send_command (LOAD_CMD, 0);
2827
2828   for (s = abfd->sections; s; s = s->next)
2829     {
2830       if (s->flags & SEC_LOAD)
2831         {
2832           unsigned int numbytes;
2833
2834           /* FIXME!  vma too small?????  */
2835           printf_filtered ("%s\t: 0x%4lx .. 0x%4lx  ", s->name,
2836                            (long) s->vma,
2837                            (long) (s->vma + bfd_get_section_size (s)));
2838           gdb_flush (gdb_stdout);
2839
2840           for (i = 0; i < bfd_get_section_size (s); i += numbytes)
2841             {
2842               numbytes = min (srec_frame, bfd_get_section_size (s) - i);
2843
2844               bfd_get_section_contents (abfd, s, buffer, i, numbytes);
2845
2846               reclen = mips_make_srec (srec, '3', s->vma + i, 
2847                                        buffer, numbytes);
2848               send_srec (srec, reclen, s->vma + i);
2849
2850               if (deprecated_ui_load_progress_hook)
2851                 deprecated_ui_load_progress_hook (s->name, i);
2852
2853               if (hashmark)
2854                 {
2855                   putchar_unfiltered ('#');
2856                   gdb_flush (gdb_stdout);
2857                 }
2858
2859             }                   /* Per-packet (or S-record) loop */
2860
2861           putchar_unfiltered ('\n');
2862         }                       /* Loadable sections */
2863     }
2864   if (hashmark)
2865     putchar_unfiltered ('\n');
2866
2867   /* Write a type 7 terminator record. no data for a type 7, and there
2868      is no data, so len is 0.  */
2869
2870   reclen = mips_make_srec (srec, '7', abfd->start_address, NULL, 0);
2871
2872   send_srec (srec, reclen, abfd->start_address);
2873
2874   serial_flush_input (mips_desc);
2875   do_cleanups (cleanup);
2876 }
2877
2878 /*
2879  * mips_make_srec -- make an srecord.  This writes each line, one at a
2880  *      time, each with it's own header and trailer line.
2881  *      An srecord looks like this:
2882  *
2883  * byte count-+     address
2884  * start ---+ |        |       data        +- checksum
2885  *          | |        |                   |
2886  *        S01000006F6B692D746573742E73726563E4
2887  *        S315000448600000000000000000FC00005900000000E9
2888  *        S31A0004000023C1400037DE00F023604000377B009020825000348D
2889  *        S30B0004485A0000000000004E
2890  *        S70500040000F6
2891  *
2892  *      S<type><length><address><data><checksum>
2893  *
2894  *      Where
2895  *      - length
2896  *        is the number of bytes following upto the checksum.  Note that
2897  *        this is not the number of chars following, since it takes two
2898  *        chars to represent a byte.
2899  *      - type
2900  *        is one of:
2901  *        0) header record
2902  *        1) two byte address data record
2903  *        2) three byte address data record
2904  *        3) four byte address data record
2905  *        7) four byte address termination record
2906  *        8) three byte address termination record
2907  *        9) two byte address termination record
2908  *       
2909  *      - address
2910  *        is the start address of the data following, or in the case of
2911  *        a termination record, the start address of the image
2912  *      - data
2913  *        is the data.
2914  *      - checksum
2915  *        is the sum of all the raw byte data in the record, from the length
2916  *        upwards, modulo 256 and subtracted from 255.
2917  *
2918  * This routine returns the length of the S-record.
2919  *
2920  */
2921
2922 static int
2923 mips_make_srec (char *buf, int type, CORE_ADDR memaddr, unsigned char *myaddr,
2924                 int len)
2925 {
2926   unsigned char checksum;
2927   int i;
2928
2929   /* Create the header for the srec.  addr_size is the number of bytes
2930      in the address, and 1 is the number of bytes in the count.  */
2931
2932   /* FIXME!! bigger buf required for 64-bit!  */
2933   buf[0] = 'S';
2934   buf[1] = type;
2935   buf[2] = len + 4 + 1;         /* len + 4 byte address + 1 byte checksum */
2936   /* This assumes S3 style downloads (4byte addresses).  There should
2937      probably be a check, or the code changed to make it more
2938      explicit.  */
2939   buf[3] = memaddr >> 24;
2940   buf[4] = memaddr >> 16;
2941   buf[5] = memaddr >> 8;
2942   buf[6] = memaddr;
2943   memcpy (&buf[7], myaddr, len);
2944
2945   /* Note that the checksum is calculated on the raw data, not the
2946      hexified data.  It includes the length, address and the data
2947      portions of the packet.  */
2948   checksum = 0;
2949   buf += 2;                     /* Point at length byte.  */
2950   for (i = 0; i < len + 4 + 1; i++)
2951     checksum += *buf++;
2952
2953   *buf = ~checksum;
2954
2955   return len + 8;
2956 }
2957
2958 /* The following manifest controls whether we enable the simple flow
2959    control support provided by the monitor.  If enabled the code will
2960    wait for an affirmative ACK between transmitting packets.  */
2961 #define DOETXACK (1)
2962
2963 /* The PMON fast-download uses an encoded packet format constructed of
2964    3byte data packets (encoded as 4 printable ASCII characters), and
2965    escape sequences (preceded by a '/'):
2966
2967    'K'     clear checksum
2968    'C'     compare checksum (12bit value, not included in checksum calculation)
2969    'S'     define symbol name (for addr) terminated with ","
2970            and padded to 4char boundary
2971    'Z'     zero fill multiple of 3bytes
2972    'B'     byte (12bit encoded value, of 8bit data)
2973    'A'     address (36bit encoded value)
2974    'E'     define entry as original address, and exit load
2975
2976    The packets are processed in 4 character chunks, so the escape
2977    sequences that do not have any data (or variable length data)
2978    should be padded to a 4 character boundary.  The decoder will give
2979    an error if the complete message block size is not a multiple of
2980    4bytes (size of record).
2981
2982    The encoding of numbers is done in 6bit fields.  The 6bit value is
2983    used to index into this string to get the specific character
2984    encoding for the value: */
2985 static char encoding[] =
2986   "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789,.";
2987
2988 /* Convert the number of bits required into an encoded number, 6bits
2989    at a time (range 0..63).  Keep a checksum if required (passed
2990    pointer non-NULL).  The function returns the number of encoded
2991    characters written into the buffer.  */
2992
2993 static int
2994 pmon_makeb64 (unsigned long v, char *p, int n, unsigned int *chksum)
2995 {
2996   int count = (n / 6);
2997
2998   if ((n % 12) != 0)
2999     {
3000       fprintf_unfiltered (gdb_stderr,
3001                           "Fast encoding bitcount must be a "
3002                           "multiple of 12bits: %dbit%s\n",
3003                           n, (n == 1) ? "" : "s");
3004       return (0);
3005     }
3006   if (n > 36)
3007     {
3008       fprintf_unfiltered (gdb_stderr,
3009                           "Fast encoding cannot process more "
3010                           "than 36bits at the moment: %dbits\n", n);
3011       return (0);
3012     }
3013
3014   /* Deal with the checksum: */
3015   if (chksum != NULL)
3016     {
3017       switch (n)
3018         {
3019         case 36:
3020           *chksum += ((v >> 24) & 0xFFF);
3021         case 24:
3022           *chksum += ((v >> 12) & 0xFFF);
3023         case 12:
3024           *chksum += ((v >> 0) & 0xFFF);
3025         }
3026     }
3027
3028   do
3029     {
3030       n -= 6;
3031       *p++ = encoding[(v >> n) & 0x3F];
3032     }
3033   while (n > 0);
3034
3035   return (count);
3036 }
3037
3038 /* Shorthand function (that could be in-lined) to output the zero-fill
3039    escape sequence into the data stream.  */
3040
3041 static int
3042 pmon_zeroset (int recsize, char **buff,
3043               unsigned int *amount, unsigned int *chksum)
3044 {
3045   int count;
3046
3047   sprintf (*buff, "/Z");
3048   count = pmon_makeb64 (*amount, (*buff + 2), 12, chksum);
3049   *buff += (count + 2);
3050   *amount = 0;
3051   return (recsize + count + 2);
3052 }
3053
3054 /* Add the checksum specified by *VALUE to end of the record under
3055    construction.  *BUF specifies the location at which to begin
3056    writing characters comprising the checksum information.  RECSIZE
3057    specifies the size of the record constructed thus far.  (A trailing
3058    NUL character may be present in the buffer holding the record, but
3059    the record size does not include this character.)
3060
3061    Return the total size of the record after adding the checksum escape,
3062    the checksum itself, and the trailing newline.
3063    
3064    The checksum specified by *VALUE is zeroed out prior to returning.
3065    Additionally, *BUF is updated to refer to the location just beyond
3066    the record elements added by this call.  */
3067
3068 static int
3069 pmon_checkset (int recsize, char **buff, unsigned int *value)
3070 {
3071   int count;
3072
3073   /* Add the checksum (without updating the value): */
3074   sprintf (*buff, "/C");
3075   count = pmon_makeb64 (*value, (*buff + 2), 12, NULL);
3076   *buff += (count + 2);
3077   sprintf (*buff, "\n");
3078   *buff += 2;                   /* Include zero terminator.  */
3079   /* Forcing a checksum validation clears the sum: */
3080   *value = 0;
3081   return (recsize + count + 3);
3082 }
3083
3084 /* Amount of padding we leave after at the end of the output buffer,
3085    for the checksum and line termination characters: */
3086 #define CHECKSIZE (4 + 4 + 4 + 2)
3087 /* zero-fill, checksum, transfer end and line termination space.  */
3088
3089 /* The amount of binary data loaded from the object file in a single
3090    operation: */
3091 #define BINCHUNK (1024)
3092
3093 /* Maximum line of data accepted by the monitor: */
3094 #define MAXRECSIZE (550)
3095 /* NOTE: This constant depends on the monitor being used.  This value
3096    is for PMON 5.x on the Cogent Vr4300 board.  */
3097
3098 /* Create a FastLoad format record.
3099
3100    *OUTBUF is the buffer into which a FastLoad formatted record is
3101    written.  On return, the pointer position represented by *OUTBUF
3102    is updated to point at the end of the data, i.e. the next position
3103    in the buffer that may be written.  No attempt is made to NUL-
3104    terminate this portion of the record written to the buffer.
3105    
3106    INBUF contains the binary input data from which the FastLoad
3107    formatted record will be built.  *INPTR is an index into this
3108    buffer.  *INPTR is updated as the input is consumed.  Thus, on
3109    return, the caller has access to the position of the next input
3110    byte yet to be processed.  INAMOUNT is the size, in bytes, of the
3111    input data.
3112
3113    *RECSIZE will be written with the size of the record written to the
3114    output buffer prior to returning.  This size does not include a
3115    NUL-termination byte as none is written to the output buffer.
3116
3117    *CSUM is the output buffer checksum.  It is updated as data is
3118    written to the output buffer.
3119    
3120    *ZEROFILL is the current number of 3-byte zero sequences that have
3121    been encountered.  It is both an input and an output to this
3122    function.  */
3123
3124 static void
3125 pmon_make_fastrec (char **outbuf, unsigned char *inbuf, int *inptr,
3126                    int inamount, int *recsize, unsigned int *csum,
3127                    unsigned int *zerofill)
3128 {
3129   int count = 0;
3130   char *p = *outbuf;
3131
3132   /* This is a simple check to ensure that our data will fit within
3133      the maximum allowable record size.  Each record output is 4bytes
3134      in length.  We must allow space for a pending zero fill command,
3135      the record, and a checksum record.  */
3136   while ((*recsize < (MAXRECSIZE - CHECKSIZE)) && ((inamount - *inptr) > 0))
3137     {
3138       /* Process the binary data: */
3139       if ((inamount - *inptr) < 3)
3140         {
3141           if (*zerofill != 0)
3142             *recsize = pmon_zeroset (*recsize, &p, zerofill, csum);
3143           sprintf (p, "/B");
3144           count = pmon_makeb64 (inbuf[*inptr], &p[2], 12, csum);
3145           p += (2 + count);
3146           *recsize += (2 + count);
3147           (*inptr)++;
3148         }
3149       else
3150         {
3151           unsigned int value = ((inbuf[*inptr + 0] << 16)
3152                                 | (inbuf[*inptr + 1] << 8)
3153                                 | (inbuf[*inptr + 2]));
3154
3155           /* Simple check for zero data.  TODO: A better check would be
3156              to check the last, and then the middle byte for being zero
3157              (if the first byte is not).  We could then check for
3158              following runs of zeros, and if above a certain size it is
3159              worth the 4 or 8 character hit of the byte insertions used
3160              to pad to the start of the zeroes.  NOTE: This also depends
3161              on the alignment at the end of the zero run.  */
3162           if (value == 0x00000000)
3163             {
3164               (*zerofill)++;
3165               if (*zerofill == 0xFFF)   /* 12bit counter */
3166                 *recsize = pmon_zeroset (*recsize, &p, zerofill, csum);
3167             }
3168           else
3169             {
3170               if (*zerofill != 0)
3171                 *recsize = pmon_zeroset (*recsize, &p, zerofill, csum);
3172               count = pmon_makeb64 (value, p, 24, csum);
3173               p += count;
3174               *recsize += count;
3175             }
3176           *inptr += 3;
3177         }
3178     }
3179
3180   *outbuf = p;
3181   return;
3182 }
3183
3184 /* Attempt to read an ACK.  If an ACK is not read in a timely manner,
3185    output the message specified by MESG.  Return -1 for failure, 0
3186    for success.  */
3187
3188 static int
3189 pmon_check_ack (char *mesg)
3190 {
3191 #if defined(DOETXACK)
3192   int c;
3193
3194   if (!tftp_in_use)
3195     {
3196       c = serial_readchar (udp_in_use ? udp_desc : mips_desc,
3197                            remote_timeout);
3198       if ((c == SERIAL_TIMEOUT) || (c != 0x06))
3199         {
3200           fprintf_unfiltered (gdb_stderr,
3201                               "Failed to receive valid ACK for %s\n", mesg);
3202           return (-1);          /* Terminate the download.  */
3203         }
3204     }
3205 #endif /* DOETXACK */
3206   return (0);
3207 }
3208
3209 /* pmon_download - Send a sequence of characters to the PMON download port,
3210    which is either a serial port or a UDP socket.  */
3211
3212 static void
3213 pmon_start_download (void)
3214 {
3215   if (tftp_in_use)
3216     {
3217       /* Create the temporary download file.  */
3218       if ((tftp_file = fopen (tftp_localname, "w")) == NULL)
3219         perror_with_name (tftp_localname);
3220     }
3221   else
3222     {
3223       mips_send_command (udp_in_use ? LOAD_CMD_UDP : LOAD_CMD, 0);
3224       mips_expect ("Downloading from ");
3225       mips_expect (udp_in_use ? "udp" : "tty0");
3226       mips_expect (", ^C to abort\r\n");
3227     }
3228 }
3229
3230 /* Look for the string specified by STRING sent from the target board
3231    during a download operation.  If the string in question is not
3232    seen, output an error message, remove the temporary file, if
3233    appropriate, and return 0.  Otherwise, return 1 to indicate
3234    success.  */
3235
3236 static int
3237 mips_expect_download (char *string)
3238 {
3239   if (!mips_expect (string))
3240     {
3241       fprintf_unfiltered (gdb_stderr, "Load did not complete successfully.\n");
3242       if (tftp_in_use)
3243         remove (tftp_localname);        /* Remove temporary file.  */
3244       return 0;
3245     }
3246   else
3247     return 1;
3248 }
3249
3250 /* Look for messages from the target board associated with the entry
3251    address.
3252
3253    NOTE: This function doesn't indicate success or failure, so we
3254    have no way to determine whether or not the output from the board
3255    was correctly seen.  However, given that other items are checked
3256    after this, it seems unlikely that those checks will pass if this
3257    check doesn't first (silently) pass.  */
3258
3259 static void
3260 pmon_check_entry_address (char *entry_address, int final)
3261 {
3262   char hexnumber[9];            /* Includes '\0' space.  */
3263
3264   mips_expect_timeout (entry_address, tftp_in_use ? 15 : remote_timeout);
3265   sprintf (hexnumber, "%x", final);
3266   mips_expect (hexnumber);
3267   mips_expect ("\r\n");
3268 }
3269
3270 /* Look for messages from the target board showing the total number of
3271    bytes downloaded to the board.  Output 1 for success if the tail
3272    end of the message was read correctly, 0 otherwise.  */
3273
3274 static int
3275 pmon_check_total (int bintotal)
3276 {
3277   char hexnumber[9];            /* Includes '\0' space.  */
3278
3279   mips_expect ("\r\ntotal = 0x");
3280   sprintf (hexnumber, "%x", bintotal);
3281   mips_expect (hexnumber);
3282   return mips_expect_download (" bytes\r\n");
3283 }
3284
3285 /* Look for the termination messages associated with the end of
3286    a download to the board.
3287
3288    Also, when `tftp_in_use' is set, issue the load command to the
3289    board causing the file to be transferred.  (This is done prior
3290    to looking for the above mentioned termination messages.)  */
3291    
3292 static void
3293 pmon_end_download (int final, int bintotal)
3294 {
3295   char hexnumber[9];            /* Includes '\0' space.  */
3296
3297   if (tftp_in_use)
3298     {
3299       static char *load_cmd_prefix = "load -b -s ";
3300       char *cmd;
3301       struct stat stbuf;
3302
3303       /* Close off the temporary file containing the load data.  */
3304       fclose (tftp_file);
3305       tftp_file = NULL;
3306
3307       /* Make the temporary file readable by the world.  */
3308       if (stat (tftp_localname, &stbuf) == 0)
3309         chmod (tftp_localname, stbuf.st_mode | S_IROTH);
3310
3311       /* Must reinitialize the board to prevent PMON from crashing.  */
3312       if (mips_monitor != MON_ROCKHOPPER)
3313         mips_send_command ("initEther\r", -1);
3314
3315       /* Send the load command.  */
3316       cmd = xmalloc (strlen (load_cmd_prefix) + strlen (tftp_name) + 2);
3317       strcpy (cmd, load_cmd_prefix);
3318       strcat (cmd, tftp_name);
3319       strcat (cmd, "\r");
3320       mips_send_command (cmd, 0);
3321       xfree (cmd);
3322       if (!mips_expect_download ("Downloading from "))
3323         return;
3324       if (!mips_expect_download (tftp_name))
3325         return;
3326       if (!mips_expect_download (", ^C to abort\r\n"))
3327         return;
3328     }
3329
3330   /* Wait for the stuff that PMON prints after the load has completed.
3331      The timeout value for use in the tftp case (15 seconds) was picked
3332      arbitrarily but might be too small for really large downloads.  FIXME.  */
3333   switch (mips_monitor)
3334     {
3335     case MON_LSI:
3336       pmon_check_ack ("termination");
3337       pmon_check_entry_address ("Entry address is ", final);
3338       if (!pmon_check_total (bintotal))
3339         return;
3340       break;
3341     case MON_ROCKHOPPER:
3342       if (!pmon_check_total (bintotal))
3343         return;
3344       pmon_check_entry_address ("Entry Address  = ", final);
3345       break;
3346     default:
3347       pmon_check_entry_address ("Entry Address  = ", final);
3348       pmon_check_ack ("termination");
3349       if (!pmon_check_total (bintotal))
3350         return;
3351       break;
3352     }
3353
3354   if (tftp_in_use)
3355     remove (tftp_localname);    /* Remove temporary file.  */
3356 }
3357
3358 /* Write the buffer specified by BUFFER of length LENGTH to either
3359    the board or the temporary file that'll eventually be transferred
3360    to the board.  */
3361
3362 static void
3363 pmon_download (char *buffer, int length)
3364 {
3365   if (tftp_in_use)
3366     {
3367       size_t written;
3368
3369       written = fwrite (buffer, 1, length, tftp_file);
3370       if (written < length)
3371         perror_with_name (tftp_localname);
3372     }
3373   else
3374     serial_write (udp_in_use ? udp_desc : mips_desc, buffer, length);
3375 }
3376
3377 /* Open object or executable file, FILE, and send it to the board
3378    using the FastLoad format.  */
3379
3380 static void
3381 pmon_load_fast (const char *file)
3382 {
3383   bfd *abfd;
3384   asection *s;
3385   unsigned char *binbuf;
3386   char *buffer;
3387   int reclen;
3388   unsigned int csum = 0;
3389   int hashmark = !tftp_in_use;
3390   int bintotal = 0;
3391   int final = 0;
3392   int finished = 0;
3393   struct cleanup *cleanup;
3394
3395   buffer = (char *) xmalloc (MAXRECSIZE + 1);
3396   binbuf = (unsigned char *) xmalloc (BINCHUNK);
3397
3398   abfd = gdb_bfd_open (file, NULL, -1);
3399   if (!abfd)
3400     {
3401       printf_filtered ("Unable to open file %s\n", file);
3402       return;
3403     }
3404   cleanup = make_cleanup_bfd_unref (abfd);
3405
3406   if (bfd_check_format (abfd, bfd_object) == 0)
3407     {
3408       printf_filtered ("File is not an object file\n");
3409       do_cleanups (cleanup);
3410       return;
3411     }
3412
3413   /* Setup the required download state: */
3414   mips_send_command ("set dlproto etxack\r", -1);
3415   mips_send_command ("set dlecho off\r", -1);
3416   /* NOTE: We get a "cannot set variable" message if the variable is
3417      already defined to have the argument we give.  The code doesn't
3418      care, since it just scans to the next prompt anyway.  */
3419   /* Start the download: */
3420   pmon_start_download ();
3421
3422   /* Zero the checksum.  */
3423   sprintf (buffer, "/Kxx\n");
3424   reclen = strlen (buffer);
3425   pmon_download (buffer, reclen);
3426   finished = pmon_check_ack ("/Kxx");
3427
3428   for (s = abfd->sections; s && !finished; s = s->next)
3429     if (s->flags & SEC_LOAD)    /* Only deal with loadable sections.  */
3430       {
3431         bintotal += bfd_get_section_size (s);
3432         final = (s->vma + bfd_get_section_size (s));
3433
3434         printf_filtered ("%s\t: 0x%4x .. 0x%4x  ", s->name,
3435                          (unsigned int) s->vma,
3436                          (unsigned int) (s->vma + bfd_get_section_size (s)));
3437         gdb_flush (gdb_stdout);
3438
3439         /* Output the starting address.  */
3440         sprintf (buffer, "/A");
3441         reclen = pmon_makeb64 (s->vma, &buffer[2], 36, &csum);
3442         buffer[2 + reclen] = '\n';
3443         buffer[3 + reclen] = '\0';
3444         reclen += 3;    /* For the initial escape code and carriage return.  */
3445         pmon_download (buffer, reclen);
3446         finished = pmon_check_ack ("/A");
3447
3448         if (!finished)
3449           {
3450             unsigned int binamount;
3451             unsigned int zerofill = 0;
3452             char *bp = buffer;
3453             unsigned int i;
3454
3455             reclen = 0;
3456
3457             for (i = 0;
3458                  i < bfd_get_section_size (s) && !finished;
3459                  i += binamount)
3460               {
3461                 int binptr = 0;
3462
3463                 binamount = min (BINCHUNK, bfd_get_section_size (s) - i);
3464
3465                 bfd_get_section_contents (abfd, s, binbuf, i, binamount);
3466
3467                 /* This keeps a rolling checksum, until we decide to output
3468                    the line: */
3469                 for (; ((binamount - binptr) > 0);)
3470                   {
3471                     pmon_make_fastrec (&bp, binbuf, &binptr, binamount, 
3472                                        &reclen, &csum, &zerofill);
3473                     if (reclen >= (MAXRECSIZE - CHECKSIZE))
3474                       {
3475                         reclen = pmon_checkset (reclen, &bp, &csum);
3476                         pmon_download (buffer, reclen);
3477                         finished = pmon_check_ack ("data record");
3478                         if (finished)
3479                           {
3480                             zerofill = 0;       /* Do not transmit pending
3481                                                    zerofills.  */
3482                             break;
3483                           }
3484
3485                         if (deprecated_ui_load_progress_hook)
3486                           deprecated_ui_load_progress_hook (s->name, i);
3487
3488                         if (hashmark)
3489                           {
3490                             putchar_unfiltered ('#');
3491                             gdb_flush (gdb_stdout);
3492                           }
3493
3494                         bp = buffer;
3495                         reclen = 0;     /* buffer processed */
3496                       }
3497                   }
3498               }
3499
3500             /* Ensure no out-standing zerofill requests: */
3501             if (zerofill != 0)
3502               reclen = pmon_zeroset (reclen, &bp, &zerofill, &csum);
3503
3504             /* and then flush the line: */
3505             if (reclen > 0)
3506               {
3507                 reclen = pmon_checkset (reclen, &bp, &csum);
3508                 /* Currently pmon_checkset outputs the line terminator by
3509                    default, so we write out the buffer so far: */
3510                 pmon_download (buffer, reclen);
3511                 finished = pmon_check_ack ("record remnant");
3512               }
3513           }
3514
3515         putchar_unfiltered ('\n');
3516       }
3517
3518   /* Terminate the transfer.  We know that we have an empty output
3519      buffer at this point.  */
3520   sprintf (buffer, "/E/E\n");   /* Include dummy padding characters.  */
3521   reclen = strlen (buffer);
3522   pmon_download (buffer, reclen);
3523
3524   if (finished)
3525     {                           /* Ignore the termination message: */
3526       serial_flush_input (udp_in_use ? udp_desc : mips_desc);
3527     }
3528   else
3529     {                           /* Deal with termination message: */
3530       pmon_end_download (final, bintotal);
3531     }
3532
3533   do_cleanups (cleanup);
3534   return;
3535 }
3536
3537 /* mips_load -- download a file.  */
3538
3539 static void
3540 mips_load (struct target_ops *self, const char *file, int from_tty)
3541 {
3542   struct regcache *regcache;
3543
3544   /* Get the board out of remote debugging mode.  */
3545   if (mips_exit_debug ())
3546     error (_("mips_load:  Couldn't get into monitor mode."));
3547
3548   if (mips_monitor != MON_IDT)
3549     pmon_load_fast (file);
3550   else
3551     mips_load_srec (file);
3552
3553   mips_initialize ();
3554
3555   /* Finally, make the PC point at the start address.  */
3556   regcache = get_current_regcache ();
3557   if (mips_monitor != MON_IDT)
3558     {
3559       /* Work around problem where PMON monitor updates the PC after a load
3560          to a different value than GDB thinks it has.  The following ensures
3561          that the regcache_write_pc() WILL update the PC value: */
3562       regcache_invalidate (regcache,
3563                            mips_regnum (get_regcache_arch (regcache))->pc);
3564     }
3565   if (exec_bfd)
3566     regcache_write_pc (regcache, bfd_get_start_address (exec_bfd));
3567 }
3568
3569 /* Check to see if a thread is still alive.  */
3570  
3571 static int
3572 mips_thread_alive (struct target_ops *ops, ptid_t ptid)
3573 {
3574   if (ptid_equal (ptid, remote_mips_ptid))
3575     /* The monitor's task is always alive.  */
3576     return 1;
3577
3578   return 0;
3579 }
3580
3581 /* Convert a thread ID to a string.  Returns the string in a static
3582    buffer.  */
3583
3584 static char *
3585 mips_pid_to_str (struct target_ops *ops, ptid_t ptid)
3586 {
3587   static char buf[64];
3588
3589   if (ptid_equal (ptid, remote_mips_ptid))
3590     {
3591       xsnprintf (buf, sizeof buf, "Thread <main>");
3592       return buf;
3593     }
3594
3595   return normal_pid_to_str (ptid);
3596 }
3597
3598 /* Pass the command argument as a packet to PMON verbatim.  */
3599
3600 static void
3601 pmon_command (char *args, int from_tty)
3602 {
3603   char buf[DATA_MAXLEN + 1];
3604   int rlen;
3605
3606   sprintf (buf, "0x0 %s", args);
3607   mips_send_packet (buf, 1);
3608   printf_filtered ("Send packet: %s\n", buf);
3609
3610   rlen = mips_receive_packet (buf, 1, mips_receive_wait);
3611   buf[rlen] = '\0';
3612   printf_filtered ("Received packet: %s\n", buf);
3613 }
3614 \f
3615 /* -Wmissing-prototypes */
3616 extern initialize_file_ftype _initialize_remote_mips;
3617
3618 /* Initialize mips_ops, lsi_ops, ddb_ops, pmon_ops, and rockhopper_ops.
3619    Create target specific commands and perform other initializations
3620    specific to this file.  */
3621
3622 void
3623 _initialize_remote_mips (void)
3624 {
3625   /* Initialize the fields in mips_ops that are common to all four targets.  */
3626   mips_ops.to_longname = "Remote MIPS debugging over serial line";
3627   mips_ops.to_close = mips_close;
3628   mips_ops.to_detach = mips_detach;
3629   mips_ops.to_resume = mips_resume;
3630   mips_ops.to_fetch_registers = mips_fetch_registers;
3631   mips_ops.to_store_registers = mips_store_registers;
3632   mips_ops.to_prepare_to_store = mips_prepare_to_store;
3633   mips_ops.to_xfer_partial = mips_xfer_partial;
3634   mips_ops.to_files_info = mips_files_info;
3635   mips_ops.to_insert_breakpoint = mips_insert_breakpoint;
3636   mips_ops.to_remove_breakpoint = mips_remove_breakpoint;
3637   mips_ops.to_insert_watchpoint = mips_insert_watchpoint;
3638   mips_ops.to_remove_watchpoint = mips_remove_watchpoint;
3639   mips_ops.to_stopped_by_watchpoint = mips_stopped_by_watchpoint;
3640   mips_ops.to_can_use_hw_breakpoint = mips_can_use_watchpoint;
3641   mips_ops.to_kill = mips_kill;
3642   mips_ops.to_load = mips_load;
3643   mips_ops.to_create_inferior = mips_create_inferior;
3644   mips_ops.to_mourn_inferior = mips_mourn_inferior;
3645   mips_ops.to_thread_alive = mips_thread_alive;
3646   mips_ops.to_pid_to_str = mips_pid_to_str;
3647   mips_ops.to_log_command = serial_log_command;
3648   mips_ops.to_stratum = process_stratum;
3649   mips_ops.to_has_all_memory = default_child_has_all_memory;
3650   mips_ops.to_has_memory = default_child_has_memory;
3651   mips_ops.to_has_stack = default_child_has_stack;
3652   mips_ops.to_has_registers = default_child_has_registers;
3653   mips_ops.to_has_execution = default_child_has_execution;
3654   mips_ops.to_magic = OPS_MAGIC;
3655
3656   /* Copy the common fields to all four target vectors.  */
3657   rockhopper_ops = pmon_ops = ddb_ops = lsi_ops = mips_ops;
3658
3659   /* Initialize target-specific fields in the target vectors.  */
3660   mips_ops.to_shortname = "mips";
3661   mips_ops.to_doc = "\
3662 Debug a board using the MIPS remote debugging protocol over a serial line.\n\
3663 The argument is the device it is connected to or, if it contains a colon,\n\
3664 HOST:PORT to access a board over a network";
3665   mips_ops.to_open = mips_open;
3666   mips_ops.to_wait = mips_wait;
3667
3668   pmon_ops.to_shortname = "pmon";
3669   pmon_ops.to_doc = "\
3670 Debug a board using the PMON MIPS remote debugging protocol over a serial\n\
3671 line. The argument is the device it is connected to or, if it contains a\n\
3672 colon, HOST:PORT to access a board over a network";
3673   pmon_ops.to_open = pmon_open;
3674   pmon_ops.to_wait = mips_wait;
3675
3676   ddb_ops.to_shortname = "ddb";
3677   ddb_ops.to_doc = "\
3678 Debug a board using the PMON MIPS remote debugging protocol over a serial\n\
3679 line. The first argument is the device it is connected to or, if it contains\n\
3680 a colon, HOST:PORT to access a board over a network.  The optional second\n\
3681 parameter is the temporary file in the form HOST:FILENAME to be used for\n\
3682 TFTP downloads to the board.  The optional third parameter is the local name\n\
3683 of the TFTP temporary file, if it differs from the filename seen by the board.";
3684   ddb_ops.to_open = ddb_open;
3685   ddb_ops.to_wait = mips_wait;
3686
3687   rockhopper_ops.to_shortname = "rockhopper";
3688   rockhopper_ops.to_doc = ddb_ops.to_doc;
3689   rockhopper_ops.to_open = rockhopper_open;
3690   rockhopper_ops.to_wait = mips_wait;
3691
3692   lsi_ops.to_shortname = "lsi";
3693   lsi_ops.to_doc = pmon_ops.to_doc;
3694   lsi_ops.to_open = lsi_open;
3695   lsi_ops.to_wait = mips_wait;
3696
3697   /* Add the targets.  */
3698   add_target (&mips_ops);
3699   add_target (&pmon_ops);
3700   add_target (&ddb_ops);
3701   add_target (&lsi_ops);
3702   add_target (&rockhopper_ops);
3703
3704   add_setshow_zinteger_cmd ("timeout", no_class, &mips_receive_wait, _("\
3705 Set timeout in seconds for remote MIPS serial I/O."), _("\
3706 Show timeout in seconds for remote MIPS serial I/O."), NULL,
3707                             NULL,
3708                             NULL, /* FIXME: i18n: */
3709                             &setlist, &showlist);
3710
3711   add_setshow_zinteger_cmd ("retransmit-timeout", no_class,
3712                             &mips_retransmit_wait, _("\
3713 Set retransmit timeout in seconds for remote MIPS serial I/O."), _("\
3714 Show retransmit timeout in seconds for remote MIPS serial I/O."), _("\
3715 This is the number of seconds to wait for an acknowledgement to a packet\n\
3716 before resending the packet."),
3717                             NULL,
3718                             NULL, /* FIXME: i18n: */
3719                             &setlist, &showlist);
3720
3721   add_setshow_zinteger_cmd ("syn-garbage-limit", no_class,
3722                             &mips_syn_garbage,  _("\
3723 Set the maximum number of characters to ignore when scanning for a SYN."), _("\
3724 Show the maximum number of characters to ignore when scanning for a SYN."), _("\
3725 This is the maximum number of characters GDB will ignore when trying to\n\
3726 synchronize with the remote system.  A value of -1 means that there is no\n\
3727 limit. (Note that these characters are printed out even though they are\n\
3728 ignored.)"),
3729                             NULL,
3730                             NULL, /* FIXME: i18n: */
3731                             &setlist, &showlist);
3732
3733   add_setshow_string_cmd ("monitor-prompt", class_obscure,
3734                           &mips_monitor_prompt, _("\
3735 Set the prompt that GDB expects from the monitor."), _("\
3736 Show the prompt that GDB expects from the monitor."), NULL,
3737                           NULL,
3738                           NULL, /* FIXME: i18n: */
3739                           &setlist, &showlist);
3740
3741   add_setshow_zinteger_cmd ("monitor-warnings", class_obscure,
3742                             &monitor_warnings, _("\
3743 Set printing of monitor warnings."), _("\
3744 Show printing of monitor warnings."), _("\
3745 When enabled, monitor warnings about hardware breakpoints will be displayed."),
3746                             NULL,
3747                             NULL, /* FIXME: i18n: */
3748                             &setlist, &showlist);
3749
3750   add_com ("pmon", class_obscure, pmon_command,
3751            _("Send a packet to PMON (must be in debug mode)."));
3752
3753   add_setshow_boolean_cmd ("mask-address", no_class, &mask_address_p, _("\
3754 Set zeroing of upper 32 bits of 64-bit addresses when talking to PMON targets."), _("\
3755 Show zeroing of upper 32 bits of 64-bit addresses when talking to PMON targets."), _("\
3756 Use \"on\" to enable the masking and \"off\" to disable it."),
3757                            NULL,
3758                            NULL, /* FIXME: i18n: */
3759                            &setlist, &showlist);
3760   remote_mips_ptid = ptid_build (42000, 0, 42000);
3761 }