]> Git Repo - binutils.git/blob - gdb/monitor.c
* monitor.[ch], op50-rom.c, rom68k-rom.c, w89k-rom.c: Add support
[binutils.git] / gdb / monitor.c
1 /* Remote debugging interface for boot monitors, for GDB.
2    Copyright 1990, 1991, 1992, 1993 Free Software Foundation, Inc.
3    Contributed by Cygnus Support. Written by Rob Savoye for Cygnus.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
20
21 /* This file was derived from various remote-* modules. It is a collection
22    of generic support functions so GDB can talk directly to a ROM based
23    monitor. This saves use from having to hack an exception based handler
24    into existance, and makes for quick porting.
25
26    This module talks to a debug monitor called 'MONITOR', which
27    We communicate with MONITOR via either a direct serial line, or a TCP
28    (or possibly TELNET) stream to a terminal multiplexor,
29    which in turn talks to the target board.
30 */
31
32 #include "defs.h"
33 #include "gdbcore.h"
34 #include "target.h"
35 #include "wait.h"
36 #include <varargs.h>
37 #include <signal.h>
38 #include <string.h>
39 #include <sys/types.h>
40 #include "command.h"
41 #include "serial.h"
42 #include "monitor.h"
43 #include "remote-utils.h"
44
45 #if !defined (HAVE_TERMIOS) && !defined (HAVE_TERMIO) && !defined (HAVE_SGTTY)
46 #define HAVE_SGTTY
47 #endif
48
49 #ifdef HAVE_TERMIOS
50 #include <termio.h>
51 #include <termios.h>
52 #  define TERMINAL struct termios
53 #else
54 #include <fcntl.h>
55 #  define TERMINAL struct sgttyb
56 #endif
57 #include "terminal.h"
58 #ifndef CSTOPB
59 #define  CSTOPB  0x00000040
60 #endif
61
62 #define SWAP_TARGET_AND_HOST(buffer,len)                                \
63   do                                                                    \
64     {                                                                   \
65       if (TARGET_BYTE_ORDER != HOST_BYTE_ORDER)                         \
66         {                                                               \
67           char tmp;                                                     \
68           char *p = (char *)(buffer);                                   \
69           char *q = ((char *)(buffer)) + len - 1;                       \
70           for (; p < q; p++, q--)                                       \
71             {                                                           \
72               tmp = *q;                                                 \
73               *q = *p;                                                  \
74               *p = tmp;                                                 \
75             }                                                           \
76         }                                                               \
77     }                                                                   \
78   while (0)
79
80
81 extern void make_xmodem_packet();
82 extern void print_xmodem_packet();
83
84 struct monitor_ops *current_monitor;
85 extern struct cmd_list_element *setlist;
86 extern struct cmd_list_element *unsetlist;
87 struct cmd_list_element *showlist;
88 extern char *version;
89 extern char *host_name;
90 extern char *target_name;
91
92 static int hashmark;                            /* flag set by "set hash" */
93
94 #define LOG_FILE "monitor.log"
95 #if defined (LOG_FILE)
96 FILE *log_file;
97 #endif
98
99 static int timeout = 24;
100
101 /* 
102  * Descriptor for I/O to remote machine.  Initialize it to NULL so that
103  * monitor_open knows that we don't have a file open when the program starts.
104  */
105 serial_t monitor_desc = NULL;
106
107 /* sets the download protocol, choices are srec, generic, boot */
108 char *loadtype;
109 static char *loadtype_str;
110 static char *loadproto_str;
111 static void set_loadtype_command();
112 static void set_loadproto_command();
113 static void monitor_load_srec();
114 static int monitor_write_srec();
115
116 /*
117  * these definitions are for xmodem protocol
118  */
119 #define SOH     0x01
120 #define ACK     0x06
121 #define NAK     0x15
122 #define EOT     0x04
123 #define CANCEL  0x18
124 #define GETACK          getacknak(ACK)
125 #define GETNAK          getacknak(NAK)
126 #define XMODEM_DATASIZE 128             /* the data   size is ALWAYS 128 */
127 #define XMODEM_PACKETSIZE       131     /* the packet size is ALWAYS 132 (zero based) */
128 #define XMODEM          1
129
130 /*
131  * set_loadtype_command -- set the type for downloading. Check to make
132  *      sure you have a support protocol for this target.
133  */
134 static void
135 set_loadtype_command (ignore, from_tty, c)
136      char *ignore;
137      int from_tty;
138      struct cmd_list_element *c;
139 {
140   char *tmp;
141   char *type;
142
143   if (current_monitor == 0x0)
144     return;
145
146     if (STREQ (LOADTYPES, "")) {
147     error ("No loadtype set");
148     return;
149   }
150   
151   tmp = savestring (LOADTYPES, strlen(LOADTYPES));
152   type = strtok(tmp, ",");
153   if (STREQ (type, (*(char **) c->var))) {
154       loadtype_str = savestring (*(char **) c->var, strlen (*(char **) c->var));
155       return;
156     }
157   
158   while ((type = strtok (NULL, ",")) != (char *)NULL) {
159     if (STREQ (type, (*(char **) c->var)))
160       loadtype_str = savestring (*(char **) c->var, strlen (*(char **) c->var));
161     return;
162   }
163   free (tmp);
164   error ("Loadtype \"%s\" does not exist.", (*(char **) c->var));
165 }
166 /*
167  * set_loadproto_command -- set the protocol for downloading. Check to make
168  *      sure you have a supported protocol for this target.
169  */
170 static void
171 set_loadproto_command (ignore, from_tty, c)
172      char *ignore;
173      int from_tty;
174      struct cmd_list_element *c;
175 {
176   char *tmp;
177   char *type;
178
179   if (current_monitor == 0x0)
180     return;
181
182   if (STREQ (LOADPROTOS, "")) {
183     error ("No load protocols set");
184     return;
185   }
186   
187   tmp = savestring (LOADPROTOS, strlen(LOADPROTOS));
188   type = strtok(tmp, ",");
189   if (STREQ (type, (*(char **) c->var))) {
190       loadproto_str = savestring (*(char **) c->var, strlen (*(char **) c->var));
191       return;
192     }
193   
194   while ((type = strtok (NULL, ",")) != (char *)NULL) {
195     if (STREQ (type, (*(char **) c->var)))
196       loadproto_str = savestring (*(char **) c->var, strlen (*(char **) c->var));
197     return;
198   }
199   free (tmp);
200   error ("Load protocol \"%s\" does not exist.", (*(char **) c->var));
201 }
202
203 /*
204  * printf_monitor -- send data to monitor.  Works just like printf.
205  */
206 static void
207 printf_monitor(va_alist)
208      va_dcl
209 {
210   va_list args;
211   char *pattern;
212   char buf[200];
213   int i;
214
215   va_start(args);
216
217   pattern = va_arg(args, char *);
218
219   vsprintf(buf, pattern, args);
220
221   debuglogs (1, "printf_monitor(), Sending: \"%s\".", buf);
222
223   if (SERIAL_WRITE(monitor_desc, buf, strlen(buf)))
224     fprintf(stderr, "SERIAL_WRITE failed: %s\n", safe_strerror(errno));
225 }
226 /*
227  * write_monitor -- send raw data to monitor.
228  */
229 static void
230 write_monitor(data, len)
231      char data[];
232      int len;
233 {
234   if (SERIAL_WRITE(monitor_desc, data, len))
235     fprintf(stderr, "SERIAL_WRITE failed: %s\n", safe_strerror(errno));
236  
237   *(data + len+1) = '\0';
238   debuglogs (1, "write_monitor(), Sending: \"%s\".", data);
239
240 }
241
242 /*
243  * debuglogs -- deal with debugging info to multiple sources. This takes
244  *      two real args, the first one is the level to be compared against 
245  *      the sr_get_debug() value, the second arg is a printf buffer and args
246  *      to be formatted and printed. A CR is added after each string is printed.
247  */
248 void
249 debuglogs(va_alist)
250      va_dcl
251 {
252   va_list args;
253   char *pattern, *p;
254   char buf[200];
255   char newbuf[300];
256   int level, i;
257
258   va_start(args);
259
260   level = va_arg(args, int);                    /* get the debug level */
261   if ((level <0) || (level > 100)) {
262     error ("Bad argument passed to debuglogs(), needs debug level");
263     return;
264   }
265       
266   pattern = va_arg(args, char *);               /* get the printf style pattern */
267
268   vsprintf(buf, pattern, args);                 /* format the string */
269   
270   /* convert some characters so it'll look right in the log */
271   p = newbuf;
272   for (i=0 ; buf[i] != '\0'; i++) {
273     switch (buf[i]) {
274     case '\n':                                  /* newlines */
275       *p++ = '\\';
276       *p++ = 'n';
277       continue;
278     case '\r':                                  /* carriage returns */
279       *p++ = '\\';
280       *p++ = 'r';
281       continue;
282     case '\033':                                /* escape */
283       *p++ = '\\';
284       *p++ = 'e';
285       continue;
286     case '\t':                                  /* tab */
287       *p++ = '\\';
288       *p++ = 't';
289       continue;
290     case '\b':                                  /* backspace */
291       *p++ = '\\';
292       *p++ = 'b';
293       continue;
294     default:                                    /* no change */
295       *p++ = buf[i];
296     }
297
298     if (buf[i] < 26) {                          /* modify control characters */
299       *p++ = '^';
300       *p++ = buf[i] + 'A';
301       continue;
302     }
303   }
304   *p = '\0';                                    /* terminate the string */
305
306   if (sr_get_debug() > level)
307     puts (newbuf);
308
309 #ifdef LOG_FILE                                 /* write to the monitor log */
310   if (log_file != 0x0) {
311     fputs (newbuf, log_file);
312     fputc ('\n', log_file);
313     fflush (log_file);
314   }
315 #endif
316 }
317
318 /* readchar -- read a character from the remote system, doing all the fancy
319  *      timeout stuff.
320  */
321 static int
322 readchar(timeout)
323      int timeout;
324 {
325   int c;
326
327   c = SERIAL_READCHAR(monitor_desc, timeout);
328
329   if (sr_get_debug() > 5)
330     putchar(c & 0x7f);
331
332 #ifdef LOG_FILE
333   if (isascii (c))
334     putc(c & 0x7f, log_file);
335 #endif
336
337   if (c >= 0)
338     return c & 0x7f;
339
340   if (c == SERIAL_TIMEOUT) {
341     if (timeout == 0)
342       return c;         /* Polls shouldn't generate timeout errors */
343     error("Timeout reading from remote system.");
344 #ifdef LOG_FILE
345       fputs ("ERROR: Timeout reading from remote system", log_file);
346 #endif
347   }
348   perror_with_name("remote-monitor");
349 }
350
351 /* 
352  * expect --  scan input from the remote system, until STRING is found.
353  *      If DISCARD is non-zero, then discard non-matching input, else print
354  *      it out. Let the user break out immediately.
355  */
356 static void
357 expect (string, discard)
358      char *string;
359      int discard;
360 {
361   char *p = string;
362   int c;
363
364
365   debuglogs (1, "Expecting \"%s\".", string);
366
367   immediate_quit = 1;
368   while (1) {
369     c = readchar(timeout);
370     if (!isascii (c))
371       continue;
372     if (c == *p++) {
373       if (*p == '\0') {
374         immediate_quit = 0;
375         debuglogs (4, "Matched");
376         return;
377       }
378     } else {
379       if (!discard) {
380         fwrite(string, 1, (p - 1) - string, stdout);
381         putchar((char)c);
382         fflush(stdout);
383       }
384       p = string;
385     }
386   }
387 }
388
389 /* Keep discarding input until we see the MONITOR prompt.
390
391    The convention for dealing with the prompt is that you
392    o give your command
393    o *then* wait for the prompt.
394
395    Thus the last thing that a procedure does with the serial line
396    will be an expect_prompt().  Exception:  monitor_resume does not
397    wait for the prompt, because the terminal is being handed over
398    to the inferior.  However, the next thing which happens after that
399    is a monitor_wait which does wait for the prompt.
400    Note that this includes abnormal exit, e.g. error().  This is
401    necessary to prevent getting into states from which we can't
402    recover.  */
403 static void
404 expect_prompt(discard)
405      int discard;
406 {
407   expect (PROMPT, discard);
408 }
409
410 /*
411  * junk -- ignore junk characters. Returns a 1 if junk, 0 otherwise
412  */
413 static int
414 junk(ch)
415      char ch;
416 {
417   switch (ch) {
418   case '\0':
419   case ' ':
420   case '-':
421   case '\t':
422   case '\r':
423   case '\n':
424     if (sr_get_debug() > 5)
425       debuglogs (5, "Ignoring \'%c\'.", ch);
426     return 1;
427   default:
428     if (sr_get_debug() > 5)
429       debuglogs (5, "Accepting \'%c\'.", ch);
430     return 0;
431   }
432 }
433
434 /* 
435  *  get_hex_digit -- Get a hex digit from the remote system & return its value.
436  *              If ignore is nonzero, ignore spaces, newline & tabs.
437  */
438 static int
439 get_hex_digit(ignore)
440      int ignore;
441 {
442   static int ch;
443   while (1) {
444     ch = readchar(timeout);
445     if (junk(ch))
446       continue;
447     if (sr_get_debug() > 4) {
448       debuglogs (4, "get_hex_digit() got a 0x%x(%c)", ch, ch);
449     } else {
450 #ifdef LOG_FILE                                 /* write to the monitor log */
451       if (log_file != 0x0) {
452         fputs ("get_hex_digit() got a 0x", log_file);
453         fputc (ch, log_file);
454         fputc ('\n', log_file);
455         fflush (log_file);
456       }
457 #endif
458     }
459
460     if (ch >= '0' && ch <= '9')
461       return ch - '0';
462     else if (ch >= 'A' && ch <= 'F')
463       return ch - 'A' + 10;
464     else if (ch >= 'a' && ch <= 'f')
465       return ch - 'a' + 10;
466     else if (ch == ' ' && ignore)
467       ;
468     else {
469       expect_prompt(1);
470       debuglogs (4, "Invalid hex digit from remote system. (0x%x)", ch);
471       error("Invalid hex digit from remote system. (0x%x)", ch);
472     }
473   }
474 }
475
476 /* get_hex_byte -- Get a byte from monitor and put it in *BYT. 
477  *      Accept any number leading spaces.
478  */
479 static void
480 get_hex_byte (byt)
481      char *byt;
482 {
483   int val;
484
485   val = get_hex_digit (1) << 4;
486   debuglogs (4, "get_hex_byte() -- Read first nibble 0x%x", val);
487  
488   val |= get_hex_digit (0);
489   debuglogs (4, "get_hex_byte() -- Read second nibble 0x%x", val);
490   *byt = val;
491   
492   debuglogs (4, "get_hex_byte() -- Read a 0x%x", val);
493 }
494
495 /* 
496  * get_hex_word --  Get N 32-bit words from remote, each preceded by a space,
497  *      and put them in registers starting at REGNO.
498  */
499 static int
500 get_hex_word ()
501 {
502   long val, newval;
503   int i;
504
505   val = 0;
506
507 #if 0
508   if (HOST_BYTE_ORDER == BIG_ENDIAN) {
509 #endif
510     for (i = 0; i < 8; i++)
511       val = (val << 4) + get_hex_digit (i == 0);
512 #if 0
513   } else {
514     for (i = 7; i >= 0; i--)
515       val = (val << 4) + get_hex_digit (i == 0);
516   }
517 #endif
518
519   debuglogs (4, "get_hex_word() got a 0x%x for a %s host.", val, (HOST_BYTE_ORDER == BIG_ENDIAN) ? "big endian" : "little endian");
520
521   return val;
522 }
523
524 /* This is called not only when we first attach, but also when the
525    user types "run" after having attached.  */
526 void
527 monitor_create_inferior (execfile, args, env)
528      char *execfile;
529      char *args;
530      char **env;
531 {
532   int entry_pt;
533
534   if (args && *args)
535     error("Can't pass arguments to remote MONITOR process");
536
537   if (execfile == 0 || exec_bfd == 0)
538     error("No exec file specified");
539
540   entry_pt = (int) bfd_get_start_address (exec_bfd);
541
542   debuglogs (3, "create_inferior(exexfile=%s, args=%s, env=%s)", execfile, args, env);
543
544 /* The "process" (board) is already stopped awaiting our commands, and
545    the program is already downloaded.  We just set its PC and go.  */
546
547   clear_proceed_status ();
548
549   /* Tell wait_for_inferior that we've started a new process.  */
550   init_wait_for_inferior ();
551
552   /* Set up the "saved terminal modes" of the inferior
553      based on what modes we are starting it with.  */
554   target_terminal_init ();
555
556   /* Install inferior's terminal modes.  */
557   target_terminal_inferior ();
558
559   /* insert_step_breakpoint ();  FIXME, do we need this?  */
560
561   /* Let 'er rip... */
562   proceed ((CORE_ADDR)entry_pt, TARGET_SIGNAL_DEFAULT, 0);
563 }
564
565 /*
566  * monitor_open -- open a connection to a remote debugger.
567  *      NAME is the filename used for communication.
568  */
569 static int baudrate = 9600;
570 static char dev_name[100];
571
572 void
573 monitor_open(args, name, from_tty)
574      char *args;
575      char *name;
576      int from_tty;
577 {
578   TERMINAL *temptempio;
579
580   if (args == NULL)
581     error ("Use `target %s DEVICE-NAME' to use a serial port, or \n\
582 `target %s HOST-NAME:PORT-NUMBER' to use a network connection.", name, name);
583
584 /*  if (is_open) */
585     monitor_close(0);
586
587   strcpy(dev_name, args);
588   monitor_desc = SERIAL_OPEN(dev_name);
589
590   if (monitor_desc == NULL)
591     perror_with_name(dev_name);
592
593   if (baud_rate != -1) {
594     if (SERIAL_SETBAUDRATE (monitor_desc, baud_rate)) {
595       SERIAL_CLOSE (monitor_desc);
596       perror_with_name (name);
597     }
598   }
599   
600   SERIAL_RAW(monitor_desc);
601
602 #ifndef __GO32__
603   /* some systems only work with 2 stop bits */
604   if (STOPBITS == 2) {
605     temptempio = (TERMINAL *)SERIAL_GET_TTY_STATE(monitor_desc);
606 #ifdef HAVE_SGTTY
607     temptempio->sg_cflag |= baud_rate | CSTOPB;
608 #else
609     temptempio->c_cflag |= baud_rate | CSTOPB;
610 #endif
611     SERIAL_SET_TTY_STATE(monitor_desc, temptempio);
612     debuglogs (4, "Set serial port to 2 stop bits");
613   }
614 #endif  /* __GO32__ */
615
616 #if defined (LOG_FILE)
617   log_file = fopen (LOG_FILE, "w");
618   if (log_file == NULL)
619     perror_with_name (LOG_FILE);
620   fprintf_filtered (log_file, "GDB %s (%s", version, host_name);
621   fprintf_filtered (log_file, " --target %s)\n", target_name);
622   fprintf_filtered (log_file, "Remote target %s connected to %s\n\n", TARGET_NAME, dev_name);
623 #endif
624
625   /* wake up the monitor and see if it's alive */
626   printf_monitor(INIT_CMD);
627   expect_prompt(1);             /* See if we get a prompt */
628
629   /* try again to be sure */
630   printf_monitor(INIT_CMD);
631   expect_prompt(1);             /* See if we get a prompt */
632
633   if (from_tty)
634     printf("Remote target %s connected to %s\n", TARGET_NAME, dev_name);
635 }
636
637 /*
638  * monitor_close -- Close out all files and local state before this
639  *      target loses control.
640  */
641
642 void
643 monitor_close (quitting)
644      int quitting;
645 {
646   SERIAL_CLOSE(monitor_desc);
647   monitor_desc = NULL;
648
649   debuglogs (1, "monitor_close (quitting=%d)", quitting);
650
651 #if defined (LOG_FILE)
652   if (log_file) {
653     if (ferror(log_file))
654       fprintf(stderr, "Error writing log file.\n");
655     if (fclose(log_file) != 0)
656       fprintf(stderr, "Error closing log file.\n");
657   }
658 #endif
659 }
660
661 /* 
662  * monitor_detach -- terminate the open connection to the remote
663  *      debugger. Use this when you want to detach and do something
664  *      else with your gdb.
665  */
666 void
667 monitor_detach (from_tty)
668      int from_tty;
669 {
670
671   debuglogs (1, "monitor_detach ()");
672
673   pop_target();         /* calls monitor_close to do the real work */
674   if (from_tty)
675     printf ("Ending remote %s debugging\n", target_shortname);
676 }
677
678 /*
679  * monitor_attach -- attach GDB to the target.
680  */
681 void
682 monitor_attach (args, from_tty)
683      char *args;
684      int from_tty;
685 {
686   if (from_tty)
687     printf ("Starting remote %s debugging\n", target_shortname);
688  
689   debuglogs (1, "monitor_attach (args=%s)", args);
690   
691   printf_monitor (GO_CMD);
692   /* swallow the echo.  */
693   expect (GO_CMD, 1);
694 }
695   
696 /*
697  * monitor_resume -- Tell the remote machine to resume.
698  */
699 void
700 monitor_resume (pid, step, sig)
701      int pid, step;
702      enum target_signal sig;
703 {
704   debuglogs (1, "monitor_resume (step=%d, sig=%d)", step, sig);
705
706   if (step) {
707     printf_monitor (STEP_CMD);
708   } else {
709     printf_monitor (CONT_CMD);
710   }
711 }
712
713 /*
714  * monitor_wait -- Wait until the remote machine stops, then return,
715  *          storing status in status just as `wait' would.
716  */
717 int
718 monitor_wait (pid, status)
719      int pid;
720      struct target_waitstatus *status;
721 {
722   int old_timeout = timeout;
723
724   debuglogs(1, "monitor_wait (), printing extraneous text.");
725   
726   status->kind = TARGET_WAITKIND_EXITED;
727   status->value.integer = 0;
728
729   timeout = 0;          /* Don't time out -- user program is running. */
730
731   expect_prompt(0);    /* Wait for prompt, outputting extraneous text */
732   debuglogs (4, "monitor_wait(), got the prompt.");
733
734   status->kind = TARGET_WAITKIND_STOPPED;
735   status->value.sig = TARGET_SIGNAL_TRAP;
736
737
738
739   timeout = old_timeout;
740
741   return 0;
742 }
743
744 /* Return the name of register number regno in the form input and output by
745    monitor.  Currently, register_names just happens to contain exactly what
746    monitor wants.  Lets take advantage of that just as long as possible! */
747
748 static char *
749 get_reg_name (regno)
750      int regno;
751 {
752   static char buf[50];
753   const char *p;
754   char *b;
755  
756   b = buf;
757
758   if (regno < 0)
759     return ("");
760
761   for (p = REGNAMES(regno); *p; p++)
762     *b++ = tolower(*p);
763
764   *b = '\000';
765
766   debuglogs (5, "Got name \"%s\" from regno #%d.", buf, regno);
767
768   return buf;
769 }
770
771 /*
772  * monitor_fetch_registers -- read the remote registers into the
773  *      block regs.
774  */
775 void
776 monitor_fetch_registers ()
777 {
778   int regno;
779
780   /* yeah yeah, i know this is horribly inefficient.  but it isn't done
781      very often...  i'll clean it up later.  */
782
783   for (regno = 0; regno <= PC_REGNUM; regno++)
784     monitor_fetch_register(regno);
785 }
786
787 /* 
788  * monitor_fetch_register -- fetch register REGNO, or all registers if REGNO
789  *      is -1. Returns errno value.
790  */
791 void
792 monitor_fetch_register (regno)
793      int regno;
794 {
795   int newval, val, j;
796
797   debuglogs (1, "monitor_fetch_register (reg=%s)", get_reg_name (regno));
798
799   if (regno < 0) {
800     monitor_fetch_registers ();
801   } else {
802     char *name = get_reg_name (regno);
803     if (STREQ(name, ""))
804       return;
805     printf_monitor (ROMCMD(GET_REG), name);     /* send the command */
806     expect (name, 1);                           /* then strip the leading garbage */
807     if (*ROMDELIM(GET_REG) != 0) {              /* if there's a delimiter */
808       expect (ROMDELIM(GET_REG), 1);
809     }
810     
811     val =  get_hex_word();                      /* get the value, ignore junk */
812
813
814     /* supply register stores in target byte order, so swap here */
815     SWAP_TARGET_AND_HOST (&val, 4);
816     supply_register (regno, (char *) &val);
817     
818     if (*ROMDELIM(GET_REG) != 0) {
819 /***  expect (ROMRES(GET_REG)); ***/
820       printf_monitor (CMD_END);
821     }
822     expect_prompt (1);
823   }
824   return;
825 }
826
827 /* Store the remote registers from the contents of the block REGS.  */
828
829 void
830 monitor_store_registers ()
831 {
832   int regno;
833
834   debuglogs (1, "monitor_store_registers()");
835
836   for (regno = 0; regno <= PC_REGNUM; regno++)
837     monitor_store_register(regno);
838
839   registers_changed ();
840 }
841
842 /* 
843  * monitor_store_register -- store register REGNO, or all if REGNO == 0.
844  *      return errno value.
845  */
846 void
847 monitor_store_register (regno)
848      int regno;
849 {
850   char *name;
851   int i;
852
853   i = read_register(regno);
854
855   debuglogs (1, "monitor_store_register (regno=%d)", regno);
856
857   if (regno < 0)
858     monitor_store_registers ();
859   else {
860       debuglogs (3, "Setting register %s to 0x%x", get_reg_name (regno), read_register (regno));
861     
862     name = get_reg_name (regno);
863     if (STREQ(name, ""))
864       return;
865     printf_monitor (ROMCMD(SET_REG), name, read_register(regno));
866     expect (name, 1);                           /* strip the leading garbage */
867     if (*ROMDELIM(SET_REG) != 0) {              /* if there's a delimiter */
868       expect (ROMDELIM(SET_REG), 1);
869       get_hex_word(1);
870       printf_monitor ("%d%s\n", i, CMD_END);
871     }
872     expect_prompt (1);
873   }
874   return;
875   
876 #if 0
877       printf_monitor (SET_REG, get_reg_name (regno),
878                       read_register (regno));
879       expect_prompt (1);
880     }
881 #endif
882 }
883
884 /* Get ready to modify the registers array.  On machines which store
885    individual registers, this doesn't need to do anything.  On machines
886    which store all the registers in one fell swoop, this makes sure
887    that registers contains all the registers from the program being
888    debugged.  */
889
890 void
891 monitor_prepare_to_store ()
892 {
893   /* Do nothing, since we can store individual regs */
894 }
895
896 void
897 monitor_files_info ()
898 {
899   printf ("\tAttached to %s at %d baud.\n",
900           dev_name, baudrate);
901 }
902
903 /*
904  * monitor_write_inferior_memory -- Copy LEN bytes of data from debugger
905  *      memory at MYADDR to inferior's memory at MEMADDR.  Returns length moved.
906  */
907 int
908 monitor_write_inferior_memory (memaddr, myaddr, len)
909      CORE_ADDR memaddr;
910      unsigned char *myaddr;
911      int len;
912 {
913   int i;
914   char buf[10];
915
916   debuglogs (1, "monitor_write_inferior_memory (memaddr=0x%x, myaddr=0x%x, len=%d)", memaddr, myaddr, len);
917
918   for (i = 0; i < len; i++) {
919     printf_monitor (ROMCMD(SET_MEM), memaddr + i, myaddr[i] );
920     if (*ROMDELIM(SET_MEM) != 0) {              /* if there's a delimiter */
921       expect (ROMDELIM(SET_MEM), 1);
922       expect (CMD_DELIM);
923       printf_monitor ("%x", myaddr[i]);
924     }
925 /***    printf_monitor ("%x", myaddr[i]); ***/
926     if (sr_get_debug() > 1)
927       printf ("\nSet 0x%x to 0x%x\n", memaddr + i, myaddr[i]);
928     if (*ROMDELIM(SET_MEM) != 0) {
929       expect (CMD_DELIM);
930       printf_monitor (CMD_END);
931     }
932     expect_prompt (1);
933   }
934   return len;
935 }
936
937 /*
938  * monitor_read_inferior_memory -- read LEN bytes from inferior memory
939  *      at MEMADDR.  Put the result at debugger address MYADDR.  Returns
940  *      length moved.
941  */
942 int
943 monitor_read_inferior_memory(memaddr, myaddr, len)
944      CORE_ADDR memaddr;
945      char *myaddr;
946      int len;
947 {
948   int i, j;
949   char buf[20];
950
951   /* Number of bytes read so far.  */
952   int count;
953
954   /* Starting address of this pass.  */
955   unsigned long startaddr;
956
957   /* Starting address of this pass.  */
958   unsigned long endaddr;
959
960   /* Number of bytes to read in this pass.  */
961   int len_this_pass;
962
963   debuglogs (1, "monitor_read_inferior_memory (memaddr=0x%x, myaddr=0x%x, len=%d)", memaddr, myaddr, len);
964
965   /* Note that this code works correctly if startaddr is just less
966      than UINT_MAX (well, really CORE_ADDR_MAX if there was such a
967      thing).  That is, something like
968      monitor_read_bytes (CORE_ADDR_MAX - 4, foo, 4)
969      works--it never adds len To memaddr and gets 0.  */
970   /* However, something like
971      monitor_read_bytes (CORE_ADDR_MAX - 3, foo, 4)
972      doesn't need to work.  Detect it and give up if there's an attempt
973      to do that.  */
974   if (((memaddr - 1) + len) < memaddr) {
975     errno = EIO;
976     return 0;
977   }
978   
979   startaddr = memaddr;
980   count = 0;
981   while (count < len) {
982     len_this_pass = 16;
983     if ((startaddr % 16) != 0)
984       len_this_pass -= startaddr % 16;
985     if (len_this_pass > (len - count))
986       len_this_pass = (len - count);
987     
988     debuglogs (3, "Display %d bytes at %x for Big Endian host", len_this_pass, startaddr);
989     
990     for (i = 0; i < len_this_pass; i++) {
991       printf_monitor (ROMCMD(GET_MEM), startaddr, startaddr);
992       sprintf (buf, ROMCMD(GET_MEM), startaddr, startaddr);
993       if (*ROMDELIM(GET_MEM) != 0) {            /* if there's a delimiter */
994         expect (ROMDELIM(GET_MEM), 1);
995       } else {
996         sprintf (buf, ROMCMD(GET_MEM), startaddr, startaddr);
997         expect (buf,1);                         /* get the command echo */
998         get_hex_word(1);                        /* strip away the address */
999       }
1000       get_hex_byte (&myaddr[count++]);          /* get the value at this address */
1001       
1002       if (*ROMDELIM(GET_MEM) != 0) {
1003         printf_monitor (CMD_END);
1004       }
1005       expect_prompt (1);
1006       startaddr += 1;
1007     }
1008   } 
1009   return len;
1010 }
1011
1012 /* FIXME-someday!  merge these two.  */
1013 int
1014 monitor_xfer_inferior_memory (memaddr, myaddr, len, write, target)
1015      CORE_ADDR memaddr;
1016      char *myaddr;
1017      int len;
1018      int write;
1019      struct target_ops *target;         /* ignored */
1020 {
1021   if (write)
1022     return monitor_write_inferior_memory (memaddr, myaddr, len);
1023   else
1024     return monitor_read_inferior_memory (memaddr, myaddr, len);
1025 }
1026
1027 void
1028 monitor_kill (args, from_tty)
1029      char *args;
1030      int from_tty;
1031 {
1032   return;               /* ignore attempts to kill target system */
1033 }
1034
1035 /* Clean up when a program exits.
1036    The program actually lives on in the remote processor's RAM, and may be
1037    run again without a download.  Don't leave it full of breakpoint
1038    instructions.  */
1039
1040 void
1041 monitor_mourn_inferior ()
1042 {
1043   remove_breakpoints ();
1044   generic_mourn_inferior ();    /* Do all the proper things now */
1045 }
1046
1047 #define MAX_MONITOR_BREAKPOINTS 16
1048
1049 extern int memory_breakpoint_size;
1050 static CORE_ADDR breakaddr[MAX_MONITOR_BREAKPOINTS] = {0};
1051
1052 /*
1053  * monitor_insert_breakpoint -- add a breakpoint
1054  */
1055 int
1056 monitor_insert_breakpoint (addr, shadow)
1057      CORE_ADDR addr;
1058      char *shadow;
1059 {
1060   int i;
1061
1062   debuglogs (1, "monitor_insert_breakpoint() addr = 0x%x", addr);
1063
1064   for (i = 0; i <= MAX_MONITOR_BREAKPOINTS; i++) {
1065     if (breakaddr[i] == 0) {
1066       breakaddr[i] = addr;
1067       if (sr_get_debug() > 4)
1068         printf ("Breakpoint at %x\n", addr);
1069       monitor_read_inferior_memory(addr, shadow, memory_breakpoint_size);
1070       printf_monitor(SET_BREAK_CMD, addr);
1071       expect_prompt(1);
1072       return 0;
1073     }
1074   }
1075
1076   fprintf(stderr, "Too many breakpoints (> 16) for monitor\n");
1077   return 1;
1078 }
1079
1080 /*
1081  * _remove_breakpoint -- Tell the monitor to remove a breakpoint
1082  */
1083 int
1084 monitor_remove_breakpoint (addr, shadow)
1085      CORE_ADDR addr;
1086      char *shadow;
1087 {
1088   int i;
1089
1090   debuglogs (1, "monitor_remove_breakpoint() addr = 0x%x", addr);
1091
1092   for (i = 0; i < MAX_MONITOR_BREAKPOINTS; i++) {
1093     if (breakaddr[i] == addr) {
1094       breakaddr[i] = 0;
1095       /* some monitors remove breakpoints based on the address */
1096       if (CLR_BREAK_ADDR)   
1097         printf_monitor(CLR_BREAK_CMD, addr);
1098       else
1099         printf_monitor(CLR_BREAK_CMD, i);
1100       expect_prompt(1);
1101       return 0;
1102     }
1103   }
1104   fprintf(stderr, "Can't find breakpoint associated with 0x%x\n", addr);
1105   return 1;
1106 }
1107
1108 /* monitor_load -- load a file. This file determines which of the
1109  *      supported formats to use. The current types are:
1110  *      FIXME: not all types supported yet.
1111  *      default - reads any file using bfd and writes it to memory. This
1112  *              is really slow.
1113  *      srec    - reads binary file using bfd and writes it as an
1114  *              ascii srecord.
1115  *      xmodem-bin - reads a binary file using bfd, and  downloads it
1116  *               using xmodem protocol.
1117  *      xmodem-srec - reads a binary file using bfd, and after converting
1118  *               it downloads it as an srecord using xmodem protocol.
1119  *      ascii-srec - reads a ascii srecord file and downloads it
1120  *              without a change.
1121  *      ascii-xmodem - reads a ascii file and downloads using xmodem
1122  *              protocol.
1123  */
1124 void
1125 monitor_load (file, fromtty)
1126     char *file;
1127     int  fromtty;
1128 {
1129   FILE *download;
1130   int i, bytes_read;
1131
1132   debuglogs (1, "Loading %s to monitor", file);
1133
1134   if (STREQ (loadtype_str, "default")) {        /* default, load a binary */
1135     gr_load_image (file, fromtty);              /* by writing it into memory */
1136     return;
1137   }
1138
1139   /* load an srecord by converting */
1140   if ((STREQ (loadtype_str, "srec")) && STREQ (loadproto_str, "xmodem")) {
1141     monitor_load_srec(file, XMODEM);
1142     return;
1143   }
1144
1145   if (STREQ (loadtype_str, "srec")) {           /* load an srecord by converting */
1146     monitor_load_srec(file, 0);                 /* if from a binary */
1147     return;
1148   }
1149
1150   if (STREQ (loadtype_str, "none")) {           /* load an srecord by converting */
1151     error ("Unimplemented");
1152     return;
1153   }
1154
1155   if (STREQ (loadproto_str, "none")) {  /* load an srecord file */
1156     monitor_load_ascii_srec(file, fromtty);             /* if from a binary */
1157     return;
1158   }
1159
1160   if (STREQ (loadproto_str, "xmodem")) {                /* load an srecord using the */
1161     monitor_load_srec(file, XMODEM);
1162     return;
1163   }
1164 }
1165
1166 /*
1167  * monitor_load_ascii_srec -- download an ASCII srecord file.
1168  */
1169 #define DOWNLOAD_LINE_SIZE 100
1170 int
1171 monitor_load_ascii_srec (file, fromtty)
1172     char *file;
1173     int fromtty;
1174 {
1175   FILE *download;
1176   char buf[DOWNLOAD_LINE_SIZE];
1177   int i, bytes_read;
1178
1179   debuglogs (1, "Loading an ASCII srecord file, %s.", file);
1180
1181   download = fopen (file, "r");
1182   if (download == NULL) {
1183     error ("%s Does not exist", file);
1184     return;
1185   }
1186
1187   printf_monitor (LOAD_CMD);
1188   sleep(1);
1189   while (!feof (download)) {
1190     bytes_read = fread (buf, sizeof (char), DOWNLOAD_LINE_SIZE, download);
1191     if (hashmark) {
1192       putchar ('.');
1193       fflush (stdout);
1194     }
1195     if (SERIAL_WRITE(monitor_desc, buf, bytes_read)) {
1196       fprintf(stderr, "SERIAL_WRITE failed: (while downloading) %s\n", safe_strerror(errno));
1197       break;
1198     }
1199     i = 0;
1200     while (i++ <=200) {} ;                      /* Ugly HACK, probably needs flow control */
1201     if (bytes_read < DOWNLOAD_LINE_SIZE) {
1202       if (!feof (download))
1203         error ("Only read %d bytes\n", bytes_read);
1204       break;
1205     }
1206   }
1207   
1208   if (hashmark) {
1209     putchar ('\n');
1210   }
1211   if (!feof (download))
1212     error ("Never got EOF while downloading");
1213   expect_prompt(1);
1214   fclose (download);
1215 }
1216
1217 /* 
1218  * monitor_command -- put a command string, in args, out to MONITOR.
1219  *      Output from MONITOR is placed on the users terminal until the
1220  *      prompt is seen. FIXME: We read the charcters ourseleves here
1221  *      cause of a nasty echo.
1222  */
1223 void
1224 monitor_command (args, fromtty)
1225      char       *args;
1226      int        fromtty;
1227 {
1228
1229   char *p;
1230   char c, cp;
1231   p = PROMPT;
1232
1233   debuglogs (1, "monitor_command (args=%s)", args);
1234
1235   if (monitor_desc == NULL)
1236     error("monitor target not open.");
1237
1238   if (!args)
1239     error("Missing command.");
1240         
1241   printf_monitor ("%s\n", args);
1242
1243   expect_prompt(0);
1244 }
1245
1246 /*
1247  * monitor_load_srec -- download a binary file by converting it to srecords. This
1248  *      will also use xmodem to download the resulting file.
1249  *
1250  *      A download goes like this when using xmodem:
1251  *      Receiver:               Sender
1252  *      NAK ---------->
1253  *              <-------- (packet)      [SOH|1|1|data|SUM]
1254  *      ACK ---------->
1255  *              <-------- (packet)      [SOH|2|2|data|SUM]
1256  *      ACK ---------->
1257  *              <-------- EOT
1258  *      ACK ---------->
1259  *
1260  *      ACK = 0x06
1261  *      NAK = 0x15
1262  *      EOT = 0x04
1263  *
1264  */
1265 static void
1266 monitor_load_srec (args, protocol)
1267      char *args;
1268      int protocol;
1269 {
1270   bfd *abfd;
1271   asection *s;
1272   char buffer[1024];
1273   char srec[1024];
1274   char packet[XMODEM_PACKETSIZE];
1275   int i;
1276   int retries;
1277   int type = 0;                                 /* default to a type 0, header record */
1278   int srec_frame = 57;                          /* FIXME: this must be 57 There is 12 bytes
1279                                                  of header, and 2 bytes of checksum at the end.
1280                                                  The problem is an xmodem packet holds exactly
1281                                                  128 bytes. */
1282
1283   abfd = bfd_openr (args, 0);
1284   if (!abfd) {
1285     printf_filtered ("Unable to open file %s\n", args);
1286     return;
1287   }
1288
1289   if (bfd_check_format (abfd, bfd_object) == 0) {
1290     printf_filtered ("File is not an object file\n");
1291     return;
1292   }
1293   
1294   printf_monitor (LOAD_CMD);                    /* tell the monitor to load */
1295   if (protocol == XMODEM) {                     /* get the NAK from the target */
1296     if (GETNAK) {
1297       debuglogs (3, "Got the NAK to start loading");
1298     } else {
1299       printf_monitor ("%c", EOT);
1300       debuglogs (3, "Never got the NAK to start loading");
1301       error ("Never got the NAK to start loading");
1302     }
1303   }
1304   
1305   s = abfd->sections;
1306   while (s != (asection *) NULL) {
1307     if (s->flags & SEC_LOAD) {
1308       char *buffer = xmalloc (srec_frame);
1309       printf_filtered ("%s\t: 0x%4x .. 0x%4x  ", s->name, s->vma, s->vma + s->_raw_size);
1310       fflush (stdout);
1311       for (i = 0; i < s->_raw_size; i += srec_frame) {
1312         if (srec_frame > s->_raw_size - i)
1313           srec_frame = s->_raw_size - i;
1314         
1315         bfd_get_section_contents (abfd, s, buffer, i, srec_frame);
1316         monitor_make_srec (srec, type, s->vma + i, buffer, srec_frame);
1317         if (protocol == XMODEM) {               /* send a packet using xmodem */
1318           make_xmodem_packet (packet, srec, XMODEM_DATASIZE);
1319           write_monitor (packet, XMODEM_PACKETSIZE+1);
1320           retries = 0;
1321           while (retries++ <= 3) {
1322             if (GETNAK) {                       /* Resend packet */
1323               debuglogs (3, "Got a NAK, resending packet");
1324               sleep(1);
1325               write_monitor (packet, XMODEM_PACKETSIZE+1); /* send it again */
1326               if (GETACK)                       /* ACKnowledged, get next data chunk */
1327                 break;
1328             } else {                            /* assume we got an ACK */
1329               if (hashmark)
1330                 printf_filtered ("#");
1331               debuglogs (3, "Got an ACK, sending next packet");
1332               break;
1333             }
1334           }
1335           if (retries >= 4) {                   /* too many tries, must be hosed */
1336             printf_monitor ("%c", EOT);
1337             error ("Never got a ACK after sending an xmodem packet");
1338           }
1339         } else {                                /* no protocols at all */
1340           printf_monitor ("%s\n", srec);
1341         }
1342         if (hashmark)
1343           printf_filtered ("#");
1344         type = 3;                               /* switch to a 4 byte address record */
1345         fflush (stdout);
1346       }
1347       free (buffer);
1348     } else {
1349       debuglogs (3, "%s doesn't need to be loaded", s->name);
1350     }
1351     s = s->next;
1352   }
1353   printf_filtered ("\n");
1354   
1355   /*
1356      write a type 7 terminator record. no data for a type 7,
1357      and there is no data, so len is 0. 
1358    */
1359   if (protocol == XMODEM) {             /* send a packet using xmodem */
1360     monitor_make_srec (srec, 7, abfd->start_address, "", 0);
1361     make_xmodem_packet (packet, srec, XMODEM_DATASIZE);  
1362     write_monitor (packet, XMODEM_PACKETSIZE+1);
1363   } else {
1364     monitor_make_srec (srec, 7, abfd->start_address, "", 0);
1365     printf_monitor ("%s\n", srec);
1366   }
1367   if (protocol == XMODEM) {
1368     printf_monitor ("%c", EOT);
1369     if (!GETACK)
1370       error ("Never got ACK after sending EOT");
1371   }
1372
1373   if (hashmark) 
1374     putchar ('\n');
1375   
1376   expect_prompt ();
1377 }
1378
1379 /*
1380  * getacknak -- get an ACK or a NAK from the target.
1381  *              returns 1 (true) or 0 (false) This is
1382  *              for xmodem. ANy string starting with "***"
1383  *              is an error message from the target.
1384  *      Here's a few from the WinBond w89k "Cougar" PA board.
1385  *              *** Too many errors found.
1386  *              *** Bad command
1387  *              *** Command syntax error
1388  */
1389 int
1390 getacknak (byte)
1391      int byte;
1392 {
1393   char character;
1394   int i;
1395   
1396   i = 0;
1397   while (i++ < 60) {
1398     character = (char)readchar (0);
1399     if ((character == 0xfffffffe) || (character == 0x7f)) {             /* empty uart */
1400       if (sr_get_debug() > 3)
1401         putchar ('.');
1402       fflush (stdout);
1403       sleep (1);
1404       continue;
1405     }
1406     if (character == CANCEL) {                  /* target aborted load */
1407       expect_prompt (0);
1408       error ("Got a CANCEL from the target.");
1409     }
1410     if (character == '*') {                     /* look for missed error message */
1411       expect_prompt (0);
1412       error ("Got an error message from the target");
1413     }
1414     debuglogs (3, "Got a %s (0x%x or \'%c\'), expecting a %s.\n",
1415                (character == ACK) ? "ACK" : (character == NAK) ? "NAK" : "BOGUS",
1416                character,  character, (byte == ACK) ? "ACK" : "NAK");
1417     if (character == byte)                      /* got what we wanted */
1418       return 1;
1419     if (character == ((byte == ACK) ? NAK : ACK)) {     /* got the opposite */
1420       debuglogs (3, "Got the opposite, wanted 0x%x, got a 0x%x", byte, character);
1421       return 0;
1422     }
1423     sleep (1); 
1424   }
1425   return 0;
1426 }
1427
1428 /*
1429  * monitor_make_srec -- make an srecord. This writes each line, one at a
1430  *      time, each with it's own header and trailer line.
1431  *      An srecord looks like this:
1432  *
1433  * byte count-+     address
1434  * start ---+ |        |       data        +- checksum
1435  *          | |        |                   |
1436  *        S01000006F6B692D746573742E73726563E4
1437  *        S315000448600000000000000000FC00005900000000E9
1438  *        S31A0004000023C1400037DE00F023604000377B009020825000348D
1439  *        S30B0004485A0000000000004E
1440  *        S70500040000F6
1441  *
1442  *      S<type><length><address><data><checksum>
1443  *
1444  *      Where
1445  *      - length
1446  *        is the number of bytes following upto the checksum. Note that
1447  *        this is not the number of chars following, since it takes two
1448  *        chars to represent a byte.
1449  *      - type
1450  *        is one of:
1451  *        0) header record
1452  *        1) two byte address data record
1453  *        2) three byte address data record
1454  *        3) four byte address data record
1455  *        7) four byte address termination record
1456  *        8) three byte address termination record
1457  *        9) two byte address termination record
1458  *       
1459  *      - address
1460  *        is the start address of the data following, or in the case of
1461  *        a termination record, the start address of the image
1462  *      - data
1463  *        is the data.
1464  *      - checksum
1465  *        is the sum of all the raw byte data in the record, from the length
1466  *        upwards, modulo 256 and subtracted from 255.
1467  */
1468 int
1469 monitor_make_srec (buffer, type, memaddr, myaddr, len)
1470      char *buffer;
1471      int type;
1472      CORE_ADDR memaddr;
1473      unsigned char *myaddr;
1474      int len;
1475 {
1476   int checksum;
1477   int i;
1478   char *buf;
1479
1480   buf = buffer;
1481   debuglogs (4, "monitor_make_srec (buffer=0x%x, type=%d, memaddr=0x%x, len=%d",
1482                                     buffer, type, memaddr, len); 
1483   checksum = 0;
1484   
1485   /*
1486      create the header for the srec. 4 is the number of bytes in the address,
1487      and 1 is the number of bytes in the count.
1488    */
1489   if (type == 0)                                /* FIXME: type 0 is optional */
1490     type = 3;                                   /* so use data as it works */
1491   sprintf (buf, "S%d%02X%08X", type, len + 4 + 1, memaddr);
1492   buf += 12;
1493   
1494   checksum += (len + 4 + 1                      /* calculate the checksum */
1495                + (memaddr & 0xff)
1496                + ((memaddr >>  8) & 0xff)
1497                + ((memaddr >> 16) & 0xff)
1498                + ((memaddr >> 24) & 0xff));
1499   
1500   for (i = 0; i < len; i++) {           /* build the srecord */
1501     sprintf (buf, "%02X", myaddr[i]);
1502     checksum += myaddr[i];
1503     buf += 2;
1504   }
1505
1506   sprintf(buf, "%02X", ~checksum & 0xff);       /* add the checksum */
1507   debuglogs (3, "srec is \"%s\"", buffer);
1508   
1509   return(0);
1510 }
1511
1512 /*
1513  * make_xmodem_packet -- this takes a 128 bytes of data and makes a packet
1514  *      out of it.
1515  *
1516  *      Each packet looks like this:
1517  *      +-----+-------+-------+------+-----+
1518  *      | SOH | Seq1. | Seq2. | data | SUM |
1519  *      +-----+-------+-------+------+-----+
1520  *      SOH  = 0x01
1521  *      Seq1 = The sequence number.
1522  *      Seq2 = The complement of the sequence number.
1523  *      Data = A 128 bytes of data.
1524  *      SUM  = Add the contents of the 128 bytes and use the low-order
1525  *             8 bits of the result.
1526  */
1527 void
1528 make_xmodem_packet (packet, data, len)
1529      unsigned char packet[];
1530      unsigned char *data;
1531      int len;
1532 {
1533   static int sequence = 1;
1534   int i, sum;
1535   unsigned char *buf;
1536   
1537   buf = data;
1538   /* build the packet header */
1539   packet[0] = SOH;
1540   packet[1] = sequence;
1541   packet[2] = 255 - sequence;
1542   sequence++;
1543 #if 0
1544   packet[2] = ~sequence++;                      /* the complement is the sequence checksum */
1545 #endif
1546   
1547   sum = 0;                                      /* calculate the data checksum */
1548   for (i = 3; i <= len + 2; i++) {
1549     packet[i] = *buf;
1550     sum += *buf;
1551     buf++;
1552   }
1553
1554   for (i = len+1 ; i <= XMODEM_DATASIZE ; i++) {        /* add padding for the rest of the packet */
1555     packet[i] = '0';
1556   }
1557
1558   packet[XMODEM_PACKETSIZE] = sum & 0xff;       /* add the checksum */
1559
1560   if (sr_get_debug() > 4) {
1561     debuglogs (4, "The xmodem checksum is %d (0x%x)\n", sum & 0xff, sum & 0xff);
1562     print_xmodem_packet (packet);
1563     }
1564 }
1565
1566 /*
1567  * print_xmodem_packet -- print the packet as a debug check
1568  */
1569 void
1570 print_xmodem_packet(packet)
1571      char packet[];
1572 {
1573   int i;
1574   static int lastseq;
1575   int sum;
1576
1577   /* take apart the packet header the packet header */
1578   if (packet[0] == SOH) {
1579      ("SOH");
1580   } else {
1581     error ("xmodem: SOH is wrong");
1582   }
1583   
1584   /* check the sequence */
1585   if (packet[1] != 0) {
1586     lastseq = packet[1];
1587     if (packet[2] != ~lastseq)
1588       error ("xmodem: Sequence checksum is wrong");
1589     else
1590       printf_filtered (" %d %d", lastseq, ~lastseq);
1591   }
1592   
1593   /* check the data checksum */
1594   sum = 0;
1595   for (i = 3; i <= XMODEM_DATASIZE; i++) {
1596     sum += packet[i];
1597   }
1598
1599   /* ignore the data */
1600 #if 0
1601   printf (" [128 bytes of data] %d\n", sum & 0xff);
1602 #endif
1603   printf_filtered (" [%s] %d\n", packet, sum & 0xff);
1604
1605   if ((packet[XMODEM_PACKETSIZE] & 0xff) != (sum & 0xff)) {
1606     debuglogs (4, "xmodem: data checksum wrong, got a %d", packet[XMODEM_PACKETSIZE] & 0xff);
1607   }
1608   putchar ('\n');
1609 }
1610
1611 /*
1612  * _initialize_remote_monitors -- setup a few addtitional commands that
1613  *              are usually only used by monitors.
1614  */
1615 void
1616 _initialize_remote_monitors ()
1617 {
1618   struct cmd_list_element *c;
1619
1620   /* this sets the type of download protocol */
1621   c = add_set_cmd ("remoteloadprotocol", no_class, var_string, (char *)&loadproto_str,
1622        "Set the type of the remote load protocol.\n", &setlist);
1623   c->function.sfunc =  set_loadproto_command;
1624   add_show_from_set (c, &showlist);
1625   loadproto_str = savestring ("none", 5);
1626
1627   /* this sets the conversion type when loading */
1628   c = add_set_cmd ("remoteloadtype", no_class, var_string, (char *)&loadtype_str,
1629        "Set the type of the remote load protocol.\n", &setlist);
1630   c->function.sfunc =  set_loadtype_command;
1631   add_show_from_set (c, &showlist);
1632   loadtype_str = savestring ("srec", 5);
1633
1634   add_show_from_set (add_set_cmd ("hash", no_class, var_boolean,
1635                                   (char *)&hashmark,
1636                                   "Set display of activity while downloading a file.\n\
1637 When enabled, a period \'.\' is displayed.",
1638                                   &setlist),
1639                      &showlist);
1640
1641   /* generic monitor command */
1642   add_com ("monitor", class_obscure, monitor_command,
1643            "Send a command to the debug monitor."); 
1644 }
This page took 0.115228 seconds and 4 git commands to generate.