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