]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/monitor.c
* defs.h: define SWAP_TARGET_AND_HOST macro.
[thirdparty/binutils-gdb.git] / gdb / monitor.c
1 /* Remote debugging interface for boot monitors, for GDB.
2 Copyright 1990, 1991, 1992, 1993, 1995 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 #include "defs.h"
32 #include "gdbcore.h"
33 #include "target.h"
34 #include "wait.h"
35 #include <varargs.h>
36 #include <signal.h>
37 #include <string.h>
38 #include <sys/types.h>
39 #include "command.h"
40 #include "serial.h"
41 #include "monitor.h"
42 #include "remote-utils.h"
43
44 #if !defined (HAVE_TERMIOS) && !defined (HAVE_TERMIO) && !defined (HAVE_SGTTY)
45 #define HAVE_SGTTY
46 #endif
47
48 #ifdef HAVE_TERMIOS
49 #include <termio.h>
50 #include <termios.h>
51 # define TERMINAL struct termios
52 #else
53 #include <fcntl.h>
54 # define TERMINAL struct sgttyb
55 #endif
56 #include "terminal.h"
57 #ifndef CSTOPB
58 #define CSTOPB 0x00000040
59 #endif
60
61 static const char hexchars[] = "0123456789abcdef";
62 static char *hex2mem ();
63
64 static void make_xmodem_packet();
65 static void print_xmodem_packet();
66 static void make_gdb_packet();
67 static unsigned long ascii2hexword();
68 static char *hexword2ascii();
69 static int tohex();
70 static int to_hex();
71 static int from_hex();
72
73 static void monitor_load_ascii_srec PARAMS ((char *file, int fromtty));
74
75 static int monitor_make_srec PARAMS ((char *buffer, int type,
76 CORE_ADDR memaddr,
77 unsigned char *myaddr, int len));
78
79 static unsigned long ascii2hexword ();
80 static char *hexword2ascii ();
81 static int tohex ();
82 static int to_hex ();
83 static int from_hex ();
84
85 struct monitor_ops *current_monitor;
86
87 extern struct cmd_list_element *setlist;
88 extern struct cmd_list_element *unsetlist;
89
90 struct cmd_list_element *showlist;
91
92 extern char *version;
93 extern char *host_name;
94 extern char *target_name;
95
96 static int hashmark; /* flag set by "set hash" */
97
98 #define LOG_FILE "monitor.log"
99 #if defined (LOG_FILE)
100 FILE *log_file;
101 #endif
102
103 static int timeout = 30;
104
105 /* Having this larger than 400 causes us to be incompatible with m68k-stub.c
106 and i386-stub.c. Normally, no one would notice because it only matters
107 for writing large chunks of memory (e.g. in downloads). Also, this needs
108 to be more than 400 if required to hold the registers (see below, where
109 we round it up based on REGISTER_BYTES). */
110
111 #define PBUFSIZ 400
112
113 /* Descriptor for I/O to remote machine. Initialize it to NULL so
114 that monitor_open knows that we don't have a file open when the
115 program starts. */
116
117 serial_t monitor_desc = NULL;
118
119 /* sets the download protocol, choices are srec, generic, boot */
120 char *loadtype;
121
122 static char *loadtype_str;
123 static char *loadproto_str;
124 static void set_loadtype_command();
125 static void set_loadproto_command();
126 static void monitor_load_srec();
127
128 /* These definitions are for xmodem protocol. */
129
130 #define SOH 0x01
131 #define ACK 0x06
132 #define NAK 0x15
133 #define EOT 0x04
134 #define CANCEL 0x18
135 #define GETACK getacknak(ACK)
136 #define GETNAK getacknak(NAK)
137 #define XMODEM_DATASIZE 128 /* the data size is ALWAYS 128 */
138 #define XMODEM_PACKETSIZE 131 /* the packet size is ALWAYS 132 (zero based) */
139 #define XMODEM 1
140
141 /*
142 * set_loadtype_command -- set the type for downloading. Check to make
143 * sure you have a support protocol for this target.
144 */
145 static void
146 set_loadtype_command (ignore, from_tty, c)
147 char *ignore;
148 int from_tty;
149 struct cmd_list_element *c;
150 {
151 char *tmp;
152 char *type;
153
154 if (current_monitor == 0x0)
155 return;
156
157 if (STREQ (LOADTYPES, "")) {
158 error ("No loadtype set");
159 return;
160 }
161
162 tmp = savestring (LOADTYPES, strlen(LOADTYPES));
163 type = strtok(tmp, ",");
164 if (STREQ (type, (*(char **) c->var))) {
165 loadtype_str = savestring (*(char **) c->var, strlen (*(char **) c->var));
166 return;
167 }
168
169 while ((type = strtok (NULL, ",")) != (char *)NULL) {
170 if (STREQ (type, (*(char **) c->var)))
171 loadtype_str = savestring (*(char **) c->var, strlen (*(char **) c->var));
172 return;
173 }
174 free (tmp);
175 error ("Loadtype \"%s\" does not exist.", (*(char **) c->var));
176 }
177 /*
178 * set_loadproto_command -- set the protocol for downloading. Check to make
179 * sure you have a supported protocol for this target.
180 */
181 static void
182 set_loadproto_command (ignore, from_tty, c)
183 char *ignore;
184 int from_tty;
185 struct cmd_list_element *c;
186 {
187 char *tmp;
188 char *type;
189
190 if (current_monitor == 0x0)
191 return;
192
193 if (STREQ (LOADPROTOS, "")) {
194 error ("No load protocols set");
195 return;
196 }
197
198 tmp = savestring (LOADPROTOS, strlen(LOADPROTOS));
199 type = strtok(tmp, ",");
200 if (STREQ (type, (*(char **) c->var))) {
201 loadproto_str = savestring (*(char **) c->var, strlen (*(char **) c->var));
202 return;
203 }
204
205 while ((type = strtok (NULL, ",")) != (char *)NULL) {
206 if (STREQ (type, (*(char **) c->var)))
207 loadproto_str = savestring (*(char **) c->var, strlen (*(char **) c->var));
208 return;
209 }
210 free (tmp);
211 error ("Load protocol \"%s\" does not exist.", (*(char **) c->var));
212 }
213
214 /* printf_monitor -- send data to monitor. Works just like printf. */
215
216 static void
217 printf_monitor (va_alist)
218 va_dcl
219 {
220 va_list args;
221 char *pattern;
222 char buf[PBUFSIZ];
223
224 va_start (args);
225
226 pattern = va_arg (args, char *);
227
228 vsprintf (buf, pattern, args);
229
230 debuglogs (1, "printf_monitor(), Sending: \"%s\".", buf);
231
232 if (strlen (buf) > PBUFSIZ)
233 error ("printf_monitor(): string too long");
234 if (SERIAL_WRITE(monitor_desc, buf, strlen (buf)))
235 fprintf (stderr, "SERIAL_WRITE failed: %s\n", safe_strerror (errno));
236 }
237
238 /* Send raw data to monitor. */
239
240 static void
241 write_monitor (data, len)
242 char *data;
243 int len;
244 {
245 if (SERIAL_WRITE (monitor_desc, data, len))
246 fprintf (stderr, "SERIAL_WRITE failed: %s\n", safe_strerror(errno));
247
248 *(data + len + 1) = '\0';
249 debuglogs (1, "write_monitor(), Sending: \"%s\".", data);
250 }
251
252 /* Deal with debugging info to multiple sources. This takes two real
253 args, the first one is the level to be compared against the
254 sr_get_debug() value, the second arg is a printf buffer and args to
255 be formatted and printed. A CR is added after each string is
256 printed. */
257
258 void
259 debuglogs (va_alist)
260 va_dcl
261 {
262 va_list args;
263 char *pattern, *p;
264 unsigned char buf[PBUFSIZ];
265 char newbuf[PBUFSIZ];
266 int level, i;
267
268 va_start(args);
269
270 level = va_arg(args, int); /* get the debug level */
271 if ((level < 0) || (level > 100))
272 {
273 error ("Bad argument passed to debuglogs(), needs debug level");
274 return;
275 }
276
277 pattern = va_arg(args, char *); /* get the printf style pattern */
278
279 vsprintf(buf, pattern, args); /* format the string */
280
281 /* convert some characters so it'll look right in the log */
282 p = newbuf;
283 for (i = 0 ; buf[i] != '\0'; i++)
284 {
285 if (i > PBUFSIZ)
286 error ("Debug message too long");
287 switch (buf[i])
288 {
289 case '\n': /* newlines */
290 *p++ = '\\';
291 *p++ = 'n';
292 continue;
293 case '\r': /* carriage returns */
294 *p++ = '\\';
295 *p++ = 'r';
296 continue;
297 case '\033': /* escape */
298 *p++ = '\\';
299 *p++ = 'e';
300 continue;
301 case '\t': /* tab */
302 *p++ = '\\';
303 *p++ = 't';
304 continue;
305 case '\b': /* backspace */
306 *p++ = '\\';
307 *p++ = 'b';
308 continue;
309 default: /* no change */
310 *p++ = buf[i];
311 }
312
313 /* modify control characters */
314 if (buf[i] < 26)
315 {
316 *p++ = '^';
317 *p++ = buf[i] + 'A';
318 continue;
319 }
320
321 /* modify control characters */
322 if (buf[i] >= 128)
323 {
324 *p++ = '!';
325 *p++ = buf[i] + 'A';
326 continue;
327 }
328 }
329 *p = '\0'; /* terminate the string */
330
331 if (sr_get_debug () > level)
332 printf_unfiltered ("%s\n", newbuf);
333
334 #ifdef LOG_FILE /* write to the monitor log */
335 if (log_file != 0x0)
336 {
337 fputs (newbuf, log_file);
338 fputc ('\n', log_file);
339 fflush (log_file);
340 }
341 #endif
342 }
343
344 /* Read a character from the remote system, doing all the fancy
345 timeout stuff. */
346
347 static int
348 readchar (timeout)
349 int timeout;
350 {
351 int c;
352
353 c = SERIAL_READCHAR (monitor_desc, timeout);
354
355 if (sr_get_debug () > 5)
356 {
357 putchar (c & 0x7f);
358 debuglogs (5, "readchar: timeout = %d\n", timeout);
359 }
360
361 #ifdef LOG_FILE
362 if (isascii (c))
363 putc(c & 0x7f, log_file);
364 #endif
365
366 if (c >= 0)
367 return c & 0x7f;
368
369 if (c == SERIAL_TIMEOUT)
370 {
371 if (timeout == 0)
372 return c; /* Polls shouldn't generate timeout errors */
373 error ("Timeout reading from remote system.");
374 #ifdef LOG_FILE
375 fputs ("ERROR: Timeout reading from remote system", log_file);
376 #endif
377 }
378 perror_with_name ("remote-monitor");
379 }
380
381 /* Scan input from the remote system, until STRING is found. If
382 DISCARD is non-zero, then discard non-matching input, else print it
383 out. Let the user break out immediately. */
384
385 static void
386 expect (string, discard)
387 char *string;
388 int discard;
389 {
390 char *p = string;
391 int c;
392
393 debuglogs (1, "Expecting \"%s\".", string);
394
395 immediate_quit = 1;
396 while (1)
397 {
398 c = readchar (timeout);
399 if (!isascii (c))
400 continue;
401 if (c == *p++)
402 {
403 if (*p == '\0')
404 {
405 immediate_quit = 0;
406 debuglogs (4, "Matched");
407 return;
408 }
409 }
410 else
411 {
412 if (!discard)
413 {
414 putc_unfiltered (c);
415 #if 0
416 fwrite(string, 1, (p - 1) - string, stdout);
417 putchar ((char)c);
418 fflush (stdout);
419 #endif
420 }
421 p = string;
422 }
423 }
424 }
425
426 /* Keep discarding input until we see the MONITOR prompt.
427
428 The convention for dealing with the prompt is that you
429 o give your command
430 o *then* wait for the prompt.
431
432 Thus the last thing that a procedure does with the serial line
433 will be an expect_prompt(). Exception: monitor_resume does not
434 wait for the prompt, because the terminal is being handed over
435 to the inferior. However, the next thing which happens after that
436 is a monitor_wait which does wait for the prompt.
437 Note that this includes abnormal exit, e.g. error(). This is
438 necessary to prevent getting into states from which we can't
439 recover. */
440
441 static void
442 expect_prompt (discard)
443 int discard;
444 {
445 expect (PROMPT, discard);
446 }
447
448 /* Ignore junk characters. Returns a 1 if junk, 0 otherwise. */
449
450 static int
451 junk (ch)
452 char ch;
453 {
454 switch (ch)
455 {
456 case '\0':
457 case ' ':
458 case '-':
459 case '\t':
460 case '\r':
461 case '\n':
462 if (sr_get_debug () > 5)
463 debuglogs (5, "Ignoring \'%c\'.", ch);
464 return 1;
465 default:
466 if (sr_get_debug () > 5)
467 debuglogs (5, "Accepting \'%c\'.", ch);
468 return 0;
469 }
470 }
471
472 /* Get a hex digit from the remote system & return its value. If
473 ignore is nonzero, ignore spaces, newline & tabs. */
474
475 static int
476 get_hex_digit (ignore)
477 int ignore;
478 {
479 static int ch;
480
481 while (1)
482 {
483 ch = readchar (timeout);
484 if (junk (ch))
485 continue;
486 if (sr_get_debug () > 4)
487 {
488 debuglogs (4, "get_hex_digit() got a 0x%x(%c)", ch, ch);
489 }
490 else
491 {
492 #ifdef LOG_FILE /* write to the monitor log */
493 if (log_file != 0x0)
494 {
495 fputs ("get_hex_digit() got a 0x", log_file);
496 fputc (ch, log_file);
497 fputc ('\n', log_file);
498 fflush (log_file);
499 }
500 #endif
501 }
502
503 if (ch >= '0' && ch <= '9')
504 return ch - '0';
505 else if (ch >= 'A' && ch <= 'F')
506 return ch - 'A' + 10;
507 else if (ch >= 'a' && ch <= 'f')
508 return ch - 'a' + 10;
509 else if (ch == ' ' && ignore)
510 ;
511 else
512 {
513 expect_prompt (1);
514 debuglogs (4, "Invalid hex digit from remote system. (0x%x)", ch);
515 error ("Invalid hex digit from remote system. (0x%x)", ch);
516 }
517 }
518 }
519
520 /* Get a byte from monitor and put it in *BYT. Accept any number of
521 leading spaces. */
522
523 static void
524 get_hex_byte (byt)
525 char *byt;
526 {
527 int val;
528
529 val = get_hex_digit (1) << 4;
530 debuglogs (4, "get_hex_byte() -- Read first nibble 0x%x", val);
531
532 val |= get_hex_digit (0);
533 debuglogs (4, "get_hex_byte() -- Read second nibble 0x%x", val);
534 *byt = val;
535
536 debuglogs (4, "get_hex_byte() -- Read a 0x%x", val);
537 }
538
539 /* Get N 32-bit words from remote, each preceded by a space, and put
540 them in registers starting at REGNO. */
541
542 static int
543 get_hex_word ()
544 {
545 long val;
546 int i;
547
548 val = 0;
549
550 #if 0
551 if (HOST_BYTE_ORDER == BIG_ENDIAN)
552 {
553 #endif
554 for (i = 0; i < 8; i++)
555 val = (val << 4) + get_hex_digit (i == 0);
556 #if 0
557 }
558 else
559 {
560 for (i = 7; i >= 0; i--)
561 val = (val << 4) + get_hex_digit (i == 0);
562 }
563 #endif
564
565 debuglogs (4, "get_hex_word() got a 0x%x for a %s host.",
566 val,
567 (HOST_BYTE_ORDER == BIG_ENDIAN) ? "big endian" : "little endian");
568
569 return val;
570 }
571
572 /* This is called not only when we first attach, but also when the
573 user types "run" after having attached. */
574
575 void
576 monitor_create_inferior (execfile, args, env)
577 char *execfile;
578 char *args;
579 char **env;
580 {
581 int entry_pt;
582
583 if (args && *args)
584 error ("Can't pass arguments to remote MONITOR process");
585
586 if (execfile == 0 || exec_bfd == 0)
587 error ("No exec file specified");
588
589 entry_pt = (int) bfd_get_start_address (exec_bfd);
590
591 /* The "process" (board) is already stopped awaiting our commands, and
592 the program is already downloaded. We just set its PC and go. */
593
594 clear_proceed_status ();
595
596 /* Tell wait_for_inferior that we've started a new process. */
597 init_wait_for_inferior ();
598
599 /* Set up the "saved terminal modes" of the inferior
600 based on what modes we are starting it with. */
601 target_terminal_init ();
602
603 /* Install inferior's terminal modes. */
604 target_terminal_inferior ();
605
606 /* insert_step_breakpoint (); FIXME, do we need this? */
607
608 /* Let 'er rip... */
609 proceed ((CORE_ADDR)entry_pt, TARGET_SIGNAL_DEFAULT, 0);
610 }
611
612 /* Open a connection to a remote debugger. NAME is the filename used
613 for communication. */
614
615 static int baudrate = 9600;
616 static char dev_name[100];
617
618 void
619 monitor_open (args, name, from_tty)
620 char *args;
621 char *name;
622 int from_tty;
623 {
624 TERMINAL *temptempio;
625
626 if (args == NULL)
627 error ("Use `target %s DEVICE-NAME' to use a serial port, or \n\
628 `target %s HOST-NAME:PORT-NUMBER' to use a network connection.", name, name);
629
630 /* if (is_open) */
631 monitor_close (0);
632
633 strcpy (dev_name, args);
634 monitor_desc = SERIAL_OPEN (dev_name);
635
636 if (monitor_desc == NULL)
637 perror_with_name (dev_name);
638
639 if (baud_rate != -1)
640 {
641 if (SERIAL_SETBAUDRATE (monitor_desc, baud_rate))
642 {
643 SERIAL_CLOSE (monitor_desc);
644 perror_with_name (name);
645 }
646 }
647
648 SERIAL_RAW (monitor_desc);
649
650 /* some systems only work with 2 stop bits */
651 #if !defined(__GO32__) && !defined(GDB_TARGET_IS_PA_ELF)
652 if (STOPBITS == 2) {
653 if (!strchr (dev_name, ':')) { /* don't set for a tcp connection */
654 temptempio = (TERMINAL *) SERIAL_GET_TTY_STATE (monitor_desc);
655 #ifdef HAVE_SGTTY
656 temptempio->sg_cflag |= baud_rate | CSTOPB;
657 #else
658 temptempio->c_cflag |= baud_rate | CSTOPB;
659 #endif
660 SERIAL_SET_TTY_STATE (monitor_desc, temptempio);
661 debuglogs (4, "Set serial port to 2 stop bits");
662 }
663 }
664 #endif /* __GO32__ */
665
666 #if defined (LOG_FILE)
667 log_file = fopen (LOG_FILE, "w");
668 if (log_file == NULL)
669 perror_with_name (LOG_FILE);
670 fprintf_filtered (log_file, "GDB %s (%s", version, host_name);
671 fprintf_filtered (log_file, " --target %s)\n", target_name);
672 fprintf_filtered (log_file, "Remote target %s connected to %s\n\n",
673 TARGET_NAME, dev_name);
674 #endif
675
676 /* see if the target is alive. For a ROM monitor, we can just try to
677 force the prompt to print a few times. FOr the GDB remote
678 protocol, the application being debugged is sitting at a
679 breakpoint and waiting for GDB to initialize the connection. We
680 force it to give us an empty packet to see if it's alive. */
681
682 if (GDBPROTO)
683 {
684 debuglogs (3, "Trying to ACK the target's debug stub");
685 printf_monitor (INIT_CMD); /* ask for the last signal */
686 expect ("$S05#b8",0); /* look for a response */
687 printf_monitor ("+"); /* ask for the last signal */
688 expect_prompt (1); /* See if we get a prompt */
689 }
690 else
691 {
692 /* wake up the monitor and see if it's alive */
693 printf_monitor (INIT_CMD);
694 expect_prompt (1); /* See if we get a prompt */
695
696 /* try again to be sure */
697 printf_monitor (INIT_CMD);
698 expect_prompt (1); /* See if we get a prompt */
699 }
700
701 if (from_tty)
702 printf ("Remote target %s connected to %s\n", TARGET_NAME, dev_name);
703 }
704
705 /* Close out all files and local state before this target loses
706 control. */
707
708 void
709 monitor_close (quitting)
710 int quitting;
711 {
712 SERIAL_CLOSE (monitor_desc);
713 monitor_desc = NULL;
714
715 debuglogs (1, "monitor_close (quitting=%d)", quitting);
716
717 #if defined (LOG_FILE)
718 if (log_file)
719 {
720 if (ferror (log_file))
721 printf_filtered ("Error writing log file.\n");
722 if (fclose (log_file) != 0)
723 printf_filtered ("Error closing log file.\n");
724 }
725 #endif
726 }
727
728 /* Terminate the open connection to the remote debugger. Use this
729 when you want to detach and do something else with your gdb. */
730
731 void
732 monitor_detach (from_tty)
733 int from_tty;
734 {
735 debuglogs (1, "monitor_detach ()");
736
737 pop_target (); /* calls monitor_close to do the real work */
738 if (from_tty)
739 printf ("Ending remote %s debugging\n", target_shortname);
740 }
741
742 /* Attach GDB to the target. */
743
744 void
745 monitor_attach (args, from_tty)
746 char *args;
747 int from_tty;
748 {
749 if (from_tty)
750 printf ("Starting remote %s debugging\n", target_shortname);
751
752 debuglogs (1, "monitor_attach (args=%s)", args);
753
754 printf_monitor (GO_CMD);
755 /* swallow the echo. */
756 expect (GO_CMD, 1);
757 }
758
759 /* Tell the remote machine to resume. */
760
761 void
762 monitor_resume (pid, step, sig)
763 int pid, step;
764 enum target_signal sig;
765 {
766 debuglogs (1, "monitor_resume (step=%d, sig=%d)", step, sig);
767
768 if (step)
769 printf_monitor (STEP_CMD);
770 else
771 printf_monitor (CONT_CMD);
772 }
773
774 /* Wait until the remote machine stops, then return, storing status in
775 status just as `wait' would. */
776
777 int
778 monitor_wait (pid, status)
779 int pid;
780 struct target_waitstatus *status;
781 {
782 int old_timeout = timeout;
783
784 debuglogs(1, "monitor_wait (), printing extraneous text.");
785
786 status->kind = TARGET_WAITKIND_EXITED;
787 status->value.integer = 0;
788
789 timeout = 0; /* Don't time out -- user program is running. */
790
791 expect_prompt (0); /* Wait for prompt, outputting extraneous text */
792 debuglogs (4, "monitor_wait(), got the prompt.");
793
794 status->kind = TARGET_WAITKIND_STOPPED;
795 status->value.sig = TARGET_SIGNAL_TRAP;
796
797 timeout = old_timeout;
798
799 return 0;
800 }
801
802 /* Return the name of register number regno in the form input and output by
803 monitor. Currently, register_names just happens to contain exactly what
804 monitor wants. Lets take advantage of that just as long as possible! */
805
806 static char *
807 get_reg_name (regno)
808 int regno;
809 {
810 static char buf[50];
811 const char *p;
812 char *b;
813
814 b = buf;
815
816 if (regno < 0)
817 return ("");
818
819 for (p = REGNAMES (regno); *p; p++)
820 *b++ = tolower (*p);
821
822 *b = '\000';
823
824 debuglogs (5, "Got name \"%s\" from regno #%d.", buf, regno);
825
826 return buf;
827 }
828
829 /* Read the remote registers into the block regs. */
830
831 void
832 monitor_fetch_registers (ignored)
833 int ignored;
834 {
835 int regno, i;
836 unsigned char packet[PBUFSIZ];
837 char regs[REGISTER_BYTES];
838
839 debuglogs (1, "monitor_fetch_registers (ignored=%d)\n", ignored);
840
841 memset (packet, 0, PBUFSIZ);
842 if (GDBPROTO)
843 {
844 /* Unimplemented registers read as all bits zero. */
845 memset (regs, 0, REGISTER_BYTES);
846 make_gdb_packet (packet, "g");
847 if (monitor_send_packet (packet) == 0)
848 error ("Couldn't transmit packet\n");
849 if (monitor_get_packet (packet) == 0)
850 error ("Couldn't receive packet\n");
851 /* FIXME: read bytes from packet */
852 debuglogs (4, "monitor_fetch_registers: Got a \"%s\" back\n", packet);
853 for (regno = 0; regno <= PC_REGNUM+4; regno++)
854 {
855 /* supply register stores in target byte order, so swap here */
856 /* FIXME: convert from ASCII hex to raw bytes */
857 i = ascii2hexword (packet + (regno * 8));
858 debuglogs (5, "Adding register %d = %x\n", regno, i);
859 SWAP_TARGET_AND_HOST (&i, 4);
860 supply_register (regno, (char *)&i);
861 }
862 }
863 else
864 {
865 for (regno = 0; regno <= PC_REGNUM; regno++)
866 monitor_fetch_register (regno);
867 }
868 }
869
870 /* Fetch register REGNO, or all registers if REGNO is -1. Returns
871 errno value. */
872
873 void
874 monitor_fetch_register (regno)
875 int regno;
876 {
877 int val;
878 char *name;
879
880 debuglogs (1, "monitor_fetch_register (reg=%s)", get_reg_name (regno));
881
882 if (regno < 0)
883 monitor_fetch_registers ();
884 else
885 {
886 name = get_reg_name (regno);
887
888 if (STREQ (name, ""))
889 return;
890
891 printf_monitor (ROMCMD (GET_REG), name); /* send the command */
892 expect (name, 1); /* then strip the leading garbage */
893 if (*ROMDELIM (GET_REG) != 0)
894 expect (ROMDELIM (GET_REG), 1);
895
896 val = get_hex_word (); /* get the value, ignore junk */
897
898 /* supply register stores in target byte order, so swap here */
899 SWAP_TARGET_AND_HOST (&val, 4);
900 supply_register (regno, (char *) &val);
901
902 if (*ROMDELIM(GET_REG) != 0)
903 {
904 /*** expect (ROMRES(GET_REG)); ***/
905 printf_monitor (CMD_END);
906 }
907 expect_prompt (1);
908 }
909 }
910
911 /* Store the remote registers. */
912
913 void
914 monitor_store_registers (ignored)
915 int ignored;
916 {
917 int regno;
918 unsigned long i;
919 char packet[PBUFSIZ];
920 char buf[PBUFSIZ];
921 char num[9];
922
923 debuglogs (1, "monitor_store_registers()");
924
925 if (GDBPROTO)
926 {
927 memset (packet, 0, PBUFSIZ);
928 memset (buf, 0, PBUFSIZ);
929 buf[0] = 'G';
930
931 /* Unimplemented registers read as all bits zero. */
932 /* FIXME: read bytes from packet */
933 for (regno = 0; regno < 41; regno++) /* FIXME */
934 {
935 /* supply register stores in target byte order, so swap here */
936 /* FIXME: convert from ASCII hex to raw bytes */
937 i = (unsigned long)read_register (regno);
938 #if 0
939 SWAP_TARGET_AND_HOST (&i, 4);
940 #endif
941 hexword2ascii (num, i);
942 strcpy (buf + (regno * 8) + 1, num);
943 }
944
945 *(buf + (regno * 8) + 2) = 0;
946 make_gdb_packet (packet, buf);
947 if (monitor_send_packet (packet) == 0)
948 error ("Couldn't transmit packet\n");
949 if (monitor_get_packet (packet) == 0)
950 error ("Couldn't receive packet\n");
951 }
952 else
953 {
954 for (regno = 0; regno <= PC_REGNUM; regno++)
955 monitor_store_register(regno);
956 }
957
958 registers_changed ();
959 }
960
961 /* Store register REGNO, or all if REGNO == 0. Return errno value. */
962
963 void
964 monitor_store_register (regno)
965 int regno;
966 {
967 char *name;
968 int i;
969
970 i = read_register (regno);
971
972 debuglogs (1, "monitor_store_register (regno=%d)", regno);
973
974 if (regno < 0)
975 monitor_store_registers ();
976 else
977 {
978 debuglogs (3, "Setting register %s to 0x%x",
979 get_reg_name (regno), read_register (regno));
980
981 name = get_reg_name (regno);
982 if (STREQ (name, ""))
983 return;
984 printf_monitor (ROMCMD (SET_REG), name, read_register (regno));
985 expect (name, 1); /* strip the leading garbage */
986 if (*ROMDELIM (SET_REG) != 0)
987 {
988 expect (ROMDELIM (SET_REG), 1);
989 get_hex_word (1);
990 printf_monitor ("%d%s\n", i, CMD_END);
991 }
992 expect_prompt (1);
993 }
994 return;
995
996 #if 0
997 printf_monitor (SET_REG, get_reg_name (regno),
998 read_register (regno));
999 expect_prompt (1);
1000 #endif
1001 }
1002
1003 /* Get ready to modify the registers array. On machines which store
1004 individual registers, this doesn't need to do anything. On machines
1005 which store all the registers in one fell swoop, this makes sure
1006 that registers contains all the registers from the program being
1007 debugged. */
1008
1009 void
1010 monitor_prepare_to_store ()
1011 {
1012 /* Do nothing, since we can store individual regs */
1013 }
1014
1015 void
1016 monitor_files_info ()
1017 {
1018 printf ("\tAttached to %s at %d baud.\n", dev_name, baudrate);
1019 }
1020
1021 /* Copy LEN bytes of data from debugger memory at MYADDR to inferior's
1022 memory at MEMADDR. Returns length moved. */
1023
1024 int
1025 monitor_write_inferior_memory (memaddr, myaddr, len)
1026 CORE_ADDR memaddr;
1027 unsigned char *myaddr;
1028 int len;
1029 {
1030 unsigned long i;
1031 int j;
1032 char packet[PBUFSIZ];
1033 char buf[PBUFSIZ];
1034 char num[9];
1035 char *p;
1036
1037 debuglogs (1, "monitor_write_inferior_memory (memaddr=0x%x, myaddr=0x%x, len=%d)",
1038 memaddr, myaddr, len);
1039 memset (buf, '\0', PBUFSIZ); /* this also sets the string terminator */
1040 p = buf;
1041
1042 if (GDBPROTO)
1043 {
1044 *p++ = 'M'; /* The command to write memory */
1045 hexword2ascii (num, memaddr); /* convert the address */
1046 strcpy (p, num); /* copy the address */
1047 p += 8;
1048 *p++ = ','; /* add comma delimeter */
1049 hexword2ascii (num, len); /* Get the length as a 4 digit number */
1050 *p++ = num[4];
1051 *p++ = num[5];
1052 *p++ = num[6];
1053 *p++ = num[7];
1054 *p++ = ':'; /* add the colon delimeter */
1055 for (j = 0; j < len; j++)
1056 { /* copy the data in after converting it */
1057 *p++ = tohex ((myaddr[j] >> 4) & 0xf);
1058 *p++ = tohex (myaddr[j] & 0xf);
1059 }
1060
1061 make_gdb_packet (packet, buf);
1062 if (monitor_send_packet (packet) == 0)
1063 error ("Couldn't transmit packet\n");
1064 if (monitor_get_packet (packet) == 0)
1065 error ("Couldn't receive packet\n");
1066 }
1067 else
1068 {
1069 for (i = 0; i < len; i++)
1070 {
1071 printf_monitor (ROMCMD (SET_MEM), memaddr + i, myaddr[i]);
1072 if (*ROMDELIM (SET_MEM) != 0)
1073 {
1074 expect (ROMDELIM (SET_MEM), 1);
1075 expect (CMD_DELIM);
1076 printf_monitor ("%x", myaddr[i]);
1077 }
1078 /*** printf_monitor ("%x", myaddr[i]); ***/
1079 if (sr_get_debug() > 1)
1080 printf ("\nSet 0x%x to 0x%x\n", memaddr + i, myaddr[i]);
1081 if (*ROMDELIM (SET_MEM) != 0)
1082 {
1083 expect (CMD_DELIM);
1084 printf_monitor (CMD_END);
1085 }
1086 expect_prompt (1);
1087 }
1088 }
1089 return len;
1090 }
1091
1092 /* Read LEN bytes from inferior memory at MEMADDR. Put the result at
1093 debugger address MYADDR. Returns length moved. */
1094
1095 int
1096 monitor_read_inferior_memory(memaddr, myaddr, len)
1097 CORE_ADDR memaddr;
1098 char *myaddr;
1099 int len;
1100 {
1101 int i, j;
1102 char buf[20];
1103 char packet[PBUFSIZ];
1104
1105 /* Number of bytes read so far. */
1106 int count;
1107
1108 /* Starting address of this pass. */
1109 unsigned long startaddr;
1110
1111 /* Starting address of this pass. */
1112 unsigned long endaddr;
1113
1114 /* Number of bytes to read in this pass. */
1115 int len_this_pass;
1116
1117 debuglogs (1, "monitor_read_inferior_memory (memaddr=0x%x, myaddr=0x%x, len=%d)", memaddr, myaddr, len);
1118
1119 /* Note that this code works correctly if startaddr is just less
1120 than UINT_MAX (well, really CORE_ADDR_MAX if there was such a
1121 thing). That is, something like
1122 monitor_read_bytes (CORE_ADDR_MAX - 4, foo, 4)
1123 works--it never adds len To memaddr and gets 0. */
1124 /* However, something like
1125 monitor_read_bytes (CORE_ADDR_MAX - 3, foo, 4)
1126 doesn't need to work. Detect it and give up if there's an attempt
1127 to do that. */
1128 if (((memaddr - 1) + len) < memaddr)
1129 {
1130 errno = EIO;
1131 return 0;
1132 }
1133
1134 startaddr = memaddr;
1135 count = 0;
1136 while (count < len)
1137 {
1138 len_this_pass = 16;
1139 if ((startaddr % 16) != 0)
1140 len_this_pass -= startaddr % 16;
1141 if (len_this_pass > (len - count))
1142 len_this_pass = (len - count);
1143
1144 debuglogs (3, "Display %d bytes at %x for Big Endian host",
1145 len_this_pass, startaddr);
1146
1147 if (GDBPROTO)
1148 {
1149 for (i = 0; i < len_this_pass; i++)
1150 {
1151 sprintf (buf, "m%08x,%04x", startaddr, len_this_pass);
1152 make_gdb_packet (packet, buf);
1153 if (monitor_send_packet (packet) == 0)
1154 error ("Couldn't transmit packet\n");
1155 if (monitor_get_packet (packet) == 0)
1156 error ("Couldn't receive packet\n");
1157 debuglogs (4, "monitor_read_inferior: Got a \"%s\" back\n",
1158 packet);
1159 for (j = 0; j < len_this_pass ; j++)
1160 {
1161 myaddr[count++] =
1162 from_hex (*(packet+(j*2))) * 16
1163 + from_hex (*(packet+(j*2)+1));
1164 debuglogs (5, "myaddr set to %x\n", myaddr[count-1]);
1165 }
1166 startaddr += 1;
1167 }
1168 }
1169 else
1170 {
1171 for (i = 0; i < len_this_pass; i++)
1172 {
1173 printf_monitor (ROMCMD (GET_MEM), startaddr, startaddr);
1174 sprintf (buf, ROMCMD (GET_MEM), startaddr, startaddr);
1175 if (*ROMDELIM(GET_MEM) != 0)
1176 {
1177 expect (ROMDELIM(GET_MEM), 1);
1178 }
1179 else
1180 {
1181 sprintf (buf, ROMCMD (GET_MEM), startaddr, startaddr);
1182 expect (buf,1); /* get the command echo */
1183 get_hex_word (1); /* strip away the address */
1184 }
1185 get_hex_byte (&myaddr[count++]); /* get the value at this address */
1186
1187 if (*ROMDELIM(GET_MEM) != 0)
1188 printf_monitor (CMD_END);
1189 expect_prompt (1);
1190 startaddr += 1;
1191 }
1192 }
1193 }
1194 return len;
1195 }
1196
1197 /* FIXME-someday! merge these two. */
1198
1199 int
1200 monitor_xfer_inferior_memory (memaddr, myaddr, len, write, target)
1201 CORE_ADDR memaddr;
1202 char *myaddr;
1203 int len;
1204 int write;
1205 struct target_ops *target; /* ignored */
1206 {
1207 if (write)
1208 return monitor_write_inferior_memory (memaddr, myaddr, len);
1209 else
1210 return monitor_read_inferior_memory (memaddr, myaddr, len);
1211 }
1212
1213 void
1214 monitor_kill (args, from_tty)
1215 char *args;
1216 int from_tty;
1217 {
1218 return; /* ignore attempts to kill target system */
1219 }
1220
1221 /* Clean up when a program exits.
1222 The program actually lives on in the remote processor's RAM, and may be
1223 run again without a download. Don't leave it full of breakpoint
1224 instructions. */
1225
1226 void
1227 monitor_mourn_inferior ()
1228 {
1229 remove_breakpoints ();
1230 generic_mourn_inferior (); /* Do all the proper things now */
1231 }
1232
1233 #define MAX_MONITOR_BREAKPOINTS 16
1234
1235 extern int memory_breakpoint_size;
1236 static CORE_ADDR breakaddr[MAX_MONITOR_BREAKPOINTS] = {0};
1237
1238 /* Tell the monitor to add a breakpoint. */
1239
1240 int
1241 monitor_insert_breakpoint (addr, shadow)
1242 CORE_ADDR addr;
1243 char *shadow;
1244 {
1245 int i;
1246
1247 debuglogs (1, "monitor_insert_breakpoint() addr = 0x%x", addr);
1248
1249 for (i = 0; i <= MAX_MONITOR_BREAKPOINTS; i++)
1250 {
1251 if (breakaddr[i] == 0)
1252 {
1253 breakaddr[i] = addr;
1254 if (sr_get_debug () > 4)
1255 printf ("Breakpoint at %x\n", addr);
1256 monitor_read_inferior_memory (addr, shadow, memory_breakpoint_size);
1257 printf_monitor (SET_BREAK_CMD, addr);
1258 expect_prompt (1);
1259 return 0;
1260 }
1261 }
1262
1263 fprintf (stderr, "Too many breakpoints (> 16) for monitor\n");
1264 return 1;
1265 }
1266
1267 /* Tell the monitor to remove a breakpoint. */
1268
1269 int
1270 monitor_remove_breakpoint (addr, shadow)
1271 CORE_ADDR addr;
1272 char *shadow;
1273 {
1274 int i;
1275
1276 debuglogs (1, "monitor_remove_breakpoint() addr = 0x%x", addr);
1277
1278 for (i = 0; i < MAX_MONITOR_BREAKPOINTS; i++)
1279 {
1280 if (breakaddr[i] == addr)
1281 {
1282 breakaddr[i] = 0;
1283 /* some monitors remove breakpoints based on the address */
1284 if (CLR_BREAK_ADDR)
1285 printf_monitor(CLR_BREAK_CMD, addr);
1286 else
1287 printf_monitor(CLR_BREAK_CMD, i);
1288 expect_prompt (1);
1289 return 0;
1290 }
1291 }
1292 fprintf (stderr, "Can't find breakpoint associated with 0x%x\n", addr);
1293 return 1;
1294 }
1295
1296 /* monitor_load -- load a file. This file determines which of the
1297 * supported formats to use. The current types are:
1298 * FIXME: not all types supported yet.
1299 * default - reads any file using bfd and writes it to memory. This
1300 * is really slow.
1301 * srec - reads binary file using bfd and writes it as an
1302 * ascii srecord.
1303 * xmodem-bin - reads a binary file using bfd, and downloads it
1304 * using xmodem protocol.
1305 * xmodem-srec - reads a binary file using bfd, and after converting
1306 * it downloads it as an srecord using xmodem protocol.
1307 * ascii-srec - reads a ascii srecord file and downloads it
1308 * without a change.
1309 * ascii-xmodem - reads a ascii file and downloads using xmodem
1310 * protocol.
1311 */
1312
1313 void
1314 monitor_load (file, fromtty)
1315 char *file;
1316 int fromtty;
1317 {
1318 debuglogs (1, "Loading %s to monitor", file);
1319
1320 /* default, load a binary */
1321 if (STREQ (loadtype_str, "default"))
1322 {
1323 gr_load_image (file, fromtty); /* by writing it into memory */
1324 return;
1325 }
1326
1327 /* load an srecord by converting */
1328 if ((STREQ (loadtype_str, "srec")) && STREQ (loadproto_str, "xmodem"))
1329 {
1330 monitor_load_srec (file, XMODEM);
1331 return;
1332 }
1333
1334 /* load an srecord by converting */
1335 if (STREQ (loadtype_str, "srec"))
1336 {
1337 monitor_load_srec (file, 0); /* if from a binary */
1338 return;
1339 }
1340
1341 /* load an srecord by converting */
1342 if (STREQ (loadtype_str, "none"))
1343 {
1344 error ("Unimplemented");
1345 return;
1346 }
1347
1348 /* load an srecord file */
1349 if (STREQ (loadproto_str, "none"))
1350 {
1351 monitor_load_ascii_srec (file, fromtty); /* if from a binary */
1352 return;
1353 }
1354
1355 if (STREQ (loadproto_str, "xmodem"))
1356 {
1357 monitor_load_srec (file, XMODEM);
1358 return;
1359 }
1360 }
1361
1362 /* Download an ASCII srecord file. */
1363
1364 #define DOWNLOAD_LINE_SIZE 100
1365
1366 static void
1367 monitor_load_ascii_srec (file, fromtty)
1368 char *file;
1369 int fromtty;
1370 {
1371 FILE *download;
1372 char buf[DOWNLOAD_LINE_SIZE];
1373 int i, bytes_read;
1374
1375 debuglogs (1, "Loading an ASCII srecord file, %s.", file);
1376
1377 download = fopen (file, "r");
1378 if (download == NULL)
1379 {
1380 error ("%s does not exist", file);
1381 return;
1382 }
1383
1384 printf_monitor (LOAD_CMD);
1385 sleep (1);
1386 while (!feof (download))
1387 {
1388 bytes_read = fread (buf, sizeof (char), DOWNLOAD_LINE_SIZE, download);
1389 if (hashmark)
1390 {
1391 putchar ('.');
1392 fflush (stdout);
1393 }
1394 if (SERIAL_WRITE (monitor_desc, buf, bytes_read))
1395 {
1396 fprintf (stderr, "SERIAL_WRITE failed: (while downloading) %s\n",
1397 safe_strerror (errno));
1398 break;
1399 }
1400 i = 0;
1401 while (i++ <=200) {} ; /* Ugly HACK, probably needs flow control */
1402 if (bytes_read < DOWNLOAD_LINE_SIZE)
1403 {
1404 if (!feof (download))
1405 error ("Only read %d bytes\n", bytes_read);
1406 break;
1407 }
1408 }
1409
1410 if (hashmark)
1411 putchar ('\n');
1412
1413 if (!feof (download))
1414 error ("Never got EOF while downloading");
1415 expect_prompt (1);
1416 fclose (download);
1417 }
1418
1419 /* Put a command string, in args, out to MONITOR. Output from MONITOR
1420 is placed on the users terminal until the prompt is seen. FIXME: We
1421 read the characters ourseleves here cause of a nasty echo. */
1422
1423 void
1424 monitor_command (args, fromtty)
1425 char *args;
1426 int fromtty;
1427 {
1428 char *p;
1429
1430 p = PROMPT;
1431
1432 debuglogs (1, "monitor_command (args=%s)", args);
1433
1434 if (monitor_desc == NULL)
1435 error ("monitor target not open.");
1436
1437 /* Send the command. Note that if no args were supplied, then we're
1438 just sending the monitor a newline, which is sometimes useful. */
1439
1440 printf_monitor ("%s\n", (args ? args : ""));
1441
1442 expect_prompt (0);
1443 }
1444
1445 /* Download a binary file by converting it to srecords. This
1446 will also use xmodem to download the resulting file.
1447
1448 A download goes like this when using xmodem:
1449 Receiver: Sender
1450 NAK ---------->
1451 <-------- (packet) [SOH|1|1|data|SUM]
1452 ACK ---------->
1453 <-------- (packet) [SOH|2|2|data|SUM]
1454 ACK ---------->
1455 <-------- EOT
1456 ACK ---------->
1457
1458 ACK = 0x06
1459 NAK = 0x15
1460 EOT = 0x04
1461 */
1462
1463 static void
1464 monitor_load_srec (args, protocol)
1465 char *args;
1466 int protocol;
1467 {
1468 bfd *abfd;
1469 asection *s;
1470 char *buffer, srec[1024];
1471 char packet[XMODEM_PACKETSIZE];
1472 int i;
1473 int retries;
1474 int type = 0; /* default to a type 0, header record */
1475 int srec_frame = 57; /* FIXME: this must be 57 There is 12 bytes
1476 of header, and 2 bytes of checksum at the end.
1477 The problem is an xmodem packet holds exactly
1478 128 bytes. */
1479
1480 abfd = bfd_openr (args, 0);
1481 if (!abfd)
1482 {
1483 printf_filtered ("Unable to open file %s\n", args);
1484 return;
1485 }
1486
1487 if (bfd_check_format (abfd, bfd_object) == 0)
1488 {
1489 printf_filtered ("File is not an object file\n");
1490 return;
1491 }
1492
1493 printf_monitor (LOAD_CMD); /* tell the monitor to load */
1494 sleep (3);
1495 /* get the NAK from the target */
1496 if (protocol == XMODEM)
1497 {
1498 if (GETNAK)
1499 {
1500 debuglogs (3, "Got the NAK to start loading");
1501 }
1502 else
1503 {
1504 printf_monitor ("%c", EOT);
1505 debuglogs (3, "Never got the NAK to start loading");
1506 error ("Never got the NAK to start loading");
1507 }
1508 }
1509
1510 s = abfd->sections;
1511 while (s != (asection *) NULL)
1512 {
1513 if (s->flags & SEC_LOAD)
1514 {
1515 buffer = xmalloc (srec_frame);
1516
1517 printf_filtered ("%s\t: 0x%4x .. 0x%4x ",
1518 s->name, s->vma, s->vma + s->_raw_size);
1519 fflush (stdout);
1520 for (i = 0; i < s->_raw_size; i += srec_frame)
1521 {
1522 if (srec_frame > s->_raw_size - i)
1523 srec_frame = s->_raw_size - i;
1524
1525 bfd_get_section_contents (abfd, s, buffer, i, srec_frame);
1526 monitor_make_srec (srec, type, s->vma + i, buffer, srec_frame);
1527 /* send a packet using xmodem */
1528 if (protocol == XMODEM)
1529 {
1530 make_xmodem_packet (packet, srec, XMODEM_DATASIZE);
1531 write_monitor (packet, XMODEM_PACKETSIZE+1);
1532 retries = 0;
1533 while (retries++ <= 3)
1534 {
1535 /* Resend packet */
1536 if (GETNAK)
1537 {
1538 debuglogs (3, "Got a NAK, resending packet");
1539 sleep (1);
1540 /* send it again */
1541 write_monitor (packet, XMODEM_PACKETSIZE+1);
1542 if (GETACK) /* ACKnowledged, get next data chunk */
1543 break;
1544 }
1545 else
1546 { /* assume we got an ACK */
1547 if (hashmark)
1548 {
1549 putc_unfiltered ('#');
1550 gdb_flush (gdb_stdout);
1551 }
1552 debuglogs (3, "Got an ACK, sending next packet");
1553 break;
1554 }
1555 }
1556 if (retries >= 4)
1557 { /* too many tries, must be hosed */
1558 printf_monitor ("%c", EOT);
1559 error ("Never got a ACK after sending an xmodem packet");
1560 }
1561 }
1562 else
1563 { /* no protocols at all */
1564 printf_monitor ("%s\n", srec);
1565 }
1566 if (hashmark)
1567 {
1568 putc_unfiltered ('#');
1569 gdb_flush (gdb_stdout);
1570 }
1571 type = 3; /* switch to a 4 byte address record */
1572 fflush (gdb_stdout);
1573 }
1574 free (buffer);
1575 }
1576 else
1577 {
1578 debuglogs (3, "%s doesn't need to be loaded", s->name);
1579 }
1580 s = s->next;
1581 }
1582 putc_unfiltered ('\n');
1583
1584 /* Write a type 7 terminator record. no data for a type 7, and there
1585 is no data, so len is 0. */
1586
1587 if (protocol == XMODEM)
1588 {
1589 /* send a packet using xmodem */
1590 monitor_make_srec (srec, 7, abfd->start_address, "", 0);
1591 make_xmodem_packet (packet, srec, XMODEM_DATASIZE);
1592 write_monitor (packet, XMODEM_PACKETSIZE+1);
1593 }
1594 else
1595 {
1596 monitor_make_srec (srec, 7, abfd->start_address, "", 0);
1597 printf_monitor ("%s\n", srec);
1598 }
1599 if (protocol == XMODEM)
1600 {
1601 printf_monitor ("%c", EOT);
1602 if (!GETACK)
1603 error ("Never got ACK after sending EOT");
1604 }
1605
1606 if (hashmark)
1607 putc_unfiltered ('\n');
1608
1609 expect_prompt ();
1610 }
1611
1612 /* Get an ACK or a NAK from the target. returns 1 (true) or 0 (false)
1613 This is for xmodem. ANy string starting with "***" is an error
1614 message from the target. Here's a few from the WinBond w89k
1615 "Cougar" PA board:
1616 *** Too many errors found.
1617 *** Bad command
1618 *** Command syntax error
1619 */
1620
1621 int
1622 getacknak (byte)
1623 int byte;
1624 {
1625 char character;
1626 int i;
1627
1628 i = 0;
1629 while (i++ < 60)
1630 {
1631 character = (char) readchar (0);
1632 if ((character == 0xfffffffe) || (character == 0x7f))
1633 { /* empty uart */
1634 if (sr_get_debug () > 3)
1635 putchar ('.');
1636 fflush (stdout);
1637 sleep (1);
1638 continue;
1639 }
1640 if (character == CANCEL)
1641 { /* target aborted load */
1642 expect_prompt (0);
1643 error ("Got a CANCEL from the target.");
1644 }
1645 if (character == '*')
1646 { /* look for missed error message */
1647 expect_prompt (0);
1648 error ("Got an error message from the target");
1649 }
1650 debuglogs (3, "Got a %s (0x%x or \'%c\'), expecting a %s.\n",
1651 (character == ACK) ? "ACK"
1652 : (character == NAK) ? "NAK"
1653 : "BOGUS",
1654 character, character, (byte == ACK) ? "ACK" : "NAK");
1655 if (character == byte) /* got what we wanted */
1656 return 1;
1657 if (character == ((byte == ACK) ? NAK : ACK))
1658 { /* got the opposite */
1659 debuglogs (3, "Got the opposite, wanted 0x%x, got a 0x%x",
1660 byte, character);
1661 return 0;
1662 }
1663 sleep (1);
1664 }
1665
1666 return 0;
1667 }
1668
1669 /*
1670 * monitor_make_srec -- make an srecord. This writes each line, one at a
1671 * time, each with it's own header and trailer line.
1672 * An srecord looks like this:
1673 *
1674 * byte count-+ address
1675 * start ---+ | | data +- checksum
1676 * | | | |
1677 * S01000006F6B692D746573742E73726563E4
1678 * S315000448600000000000000000FC00005900000000E9
1679 * S31A0004000023C1400037DE00F023604000377B009020825000348D
1680 * S30B0004485A0000000000004E
1681 * S70500040000F6
1682 *
1683 * S<type><length><address><data><checksum>
1684 *
1685 * Where
1686 * - length
1687 * is the number of bytes following upto the checksum. Note that
1688 * this is not the number of chars following, since it takes two
1689 * chars to represent a byte.
1690 * - type
1691 * is one of:
1692 * 0) header record
1693 * 1) two byte address data record
1694 * 2) three byte address data record
1695 * 3) four byte address data record
1696 * 7) four byte address termination record
1697 * 8) three byte address termination record
1698 * 9) two byte address termination record
1699 *
1700 * - address
1701 * is the start address of the data following, or in the case of
1702 * a termination record, the start address of the image
1703 * - data
1704 * is the data.
1705 * - checksum
1706 * is the sum of all the raw byte data in the record, from the length
1707 * upwards, modulo 256 and subtracted from 255.
1708 */
1709
1710 static int
1711 monitor_make_srec (buffer, type, memaddr, myaddr, len)
1712 char *buffer;
1713 int type;
1714 CORE_ADDR memaddr;
1715 unsigned char *myaddr;
1716 int len;
1717 {
1718 int checksum;
1719 int i;
1720 char *buf;
1721
1722 buf = buffer;
1723 debuglogs (4, "monitor_make_srec (buffer=0x%x, type=%d, memaddr=0x%x, len=%d",
1724 buffer, type, memaddr, len);
1725 checksum = 0;
1726
1727 /* Create the header for the srec. 4 is the number of bytes in the address,
1728 and 1 is the number of bytes in the count. */
1729
1730 if (type == 0) /* FIXME: type 0 is optional */
1731 type = 3; /* so use data as it works */
1732 sprintf (buf, "S%d%02X%08X", type, len + 4 + 1, memaddr);
1733 buf += 12;
1734
1735 checksum += (len + 4 + 1 /* calculate the checksum */
1736 + (memaddr & 0xff)
1737 + ((memaddr >> 8) & 0xff)
1738 + ((memaddr >> 16) & 0xff)
1739 + ((memaddr >> 24) & 0xff));
1740
1741 /* build the srecord */
1742 for (i = 0; i < len; i++)
1743 {
1744 sprintf (buf, "%02X", myaddr[i]);
1745 checksum += myaddr[i];
1746 buf += 2;
1747 }
1748
1749 sprintf(buf, "%02X", ~checksum & 0xff); /* add the checksum */
1750 debuglogs (3, "srec is \"%s\"", buffer);
1751
1752 return 0;
1753 }
1754
1755 /* Take 128 bytes of data and make a packet out of it.
1756 *
1757 * Each packet looks like this:
1758 * +-----+-------+-------+------+-----+
1759 * | SOH | Seq1. | Seq2. | data | SUM |
1760 * +-----+-------+-------+------+-----+
1761 * SOH = 0x01
1762 * Seq1 = The sequence number.
1763 * Seq2 = The complement of the sequence number.
1764 * Data = A 128 bytes of data.
1765 * SUM = Add the contents of the 128 bytes and use the low-order
1766 * 8 bits of the result.
1767 */
1768
1769 static void
1770 make_xmodem_packet (packet, data, len)
1771 unsigned char *packet;
1772 unsigned char *data;
1773 int len;
1774 {
1775 static int sequence = 1;
1776 int i, sum;
1777 unsigned char *buf;
1778
1779 buf = data;
1780 /* build the packet header */
1781 packet[0] = SOH;
1782 packet[1] = sequence;
1783 packet[2] = 255 - sequence;
1784 sequence++;
1785 #if 0
1786 packet[2] = ~sequence++; /* the complement is the sequence checksum */
1787 #endif
1788
1789 sum = 0; /* calculate the data checksum */
1790 for (i = 3; i <= len + 2; i++) {
1791 packet[i] = *buf;
1792 sum += *buf;
1793 buf++;
1794 }
1795
1796 /* add padding for the rest of the packet */
1797 for (i = len+1 ; i <= XMODEM_DATASIZE ; i++)
1798 packet[i] = '0';
1799
1800 packet[XMODEM_PACKETSIZE] = sum & 0xff; /* add the checksum */
1801
1802 if (sr_get_debug () > 4)
1803 {
1804 debuglogs (4, "The xmodem checksum is %d (0x%x)\n",
1805 sum & 0xff, sum & 0xff);
1806 print_xmodem_packet (packet);
1807 }
1808 }
1809
1810 /* Print the packet as a debug check. */
1811
1812 static void
1813 print_xmodem_packet (packet)
1814 char *packet;
1815 {
1816 int i;
1817 static int lastseq;
1818 int sum;
1819
1820 /* take apart the packet header the packet header */
1821 if (packet[0] == SOH)
1822 printf ("SOH");
1823 else
1824 error ("xmodem: SOH is wrong");
1825
1826 /* check the sequence */
1827 if (packet[1] != 0)
1828 {
1829 lastseq = packet[1];
1830 if (packet[2] != ~lastseq)
1831 error ("xmodem: Sequence checksum is wrong");
1832 else
1833 printf_filtered (" %d %d", lastseq, ~lastseq);
1834 }
1835
1836 /* check the data checksum */
1837 sum = 0;
1838 for (i = 3; i <= XMODEM_DATASIZE; i++)
1839 sum += packet[i];
1840
1841 /* ignore the data */
1842 #if 0
1843 printf (" [128 bytes of data] %d\n", sum & 0xff);
1844 #endif
1845 printf_filtered (" [%s] %d\n", packet, sum & 0xff);
1846
1847 if ((packet[XMODEM_PACKETSIZE] & 0xff) != (sum & 0xff))
1848 debuglogs (4, "xmodem: data checksum wrong, got a %d",
1849 packet[XMODEM_PACKETSIZE] & 0xff);
1850
1851 putchar ('\n');
1852 }
1853
1854 /* Make a GDB packet. The data is always ASCII.
1855 * A debug packet whose contents are <data>
1856 * is encapsulated for transmission in the form:
1857 *
1858 * $ <data> # CSUM1 CSUM2
1859 *
1860 * <data> must be ASCII alphanumeric and cannot include characters
1861 * '$' or '#'. If <data> starts with two characters followed by
1862 * ':', then the existing stubs interpret this as a sequence number.
1863 *
1864 * CSUM1 and CSUM2 are ascii hex representation of an 8-bit
1865 * checksum of <data>, the most significant nibble is sent first.
1866 * the hex digits 0-9,a-f are used. */
1867
1868 static void
1869 make_gdb_packet (buf, data)
1870 char *buf, *data;
1871 {
1872 int i;
1873 unsigned char csum = 0;
1874 int cnt;
1875 char *p;
1876
1877 debuglogs (3, "make_gdb_packet(%s)\n", data);
1878 cnt = strlen (data);
1879 if (cnt > PBUFSIZ)
1880 error ("make_gdb_packet(): to much data\n");
1881
1882 /* start with the packet header */
1883 p = buf;
1884 *p++ = '$';
1885
1886 /* calculate the checksum */
1887 for (i = 0; i < cnt; i++)
1888 {
1889 csum += data[i];
1890 *p++ = data[i];
1891 }
1892
1893 /* terminate the data with a '#' */
1894 *p++ = '#';
1895
1896 /* add the checksum as two ascii digits */
1897 *p++ = tohex ((csum >> 4) & 0xf);
1898 *p++ = tohex (csum & 0xf);
1899 *p = 0x0; /* Null terminator on string */
1900 }
1901
1902 /* Send a GDB packet to the target with error handling. We get a '+'
1903 (ACK) back if the packet is received and the checksum
1904 matches. Otherwise a '-' (NAK) is returned. It returns a 1 for a
1905 successful transmition, or a 0 for a failure. */
1906
1907 int
1908 monitor_send_packet (packet)
1909 char *packet;
1910 {
1911 int c, retries, i;
1912 char junk[PBUFSIZ];
1913
1914 retries = 0;
1915
1916 #if 0
1917 /* scan the packet to make sure it only contains valid characters.
1918 this may sound silly, but sometimes a garbled packet will hang
1919 the target board. We scan the whole thing, then print the error
1920 message.
1921 */
1922 for (i = 0; i < strlen(packet); i++) {
1923 debuglogs (5, "monitor_send_packet(): Scanning \'%c\'\n", packet[i]);
1924 /* legit hex numbers or command */
1925 if ((isxdigit(packet[i])) || (isalpha(packet[i])))
1926 continue;
1927 switch (packet[i]) {
1928 case '+': /* ACK */
1929 case '-': /* NAK */
1930 case '#': /* end of packet */
1931 case '$': /* start of packet */
1932 continue;
1933 default: /* bogus character */
1934 retries++;
1935 debuglogs (4, "monitor_send_packet(): Found a non-ascii digit \'%c\' in the packet.\n", packet[i]);
1936 }
1937 }
1938 #endif
1939
1940 if (retries > 0)
1941 error ("Can't send packet, found %d non-ascii characters", retries);
1942
1943 /* ok, try to send the packet */
1944 retries = 0;
1945 while (retries <= 10)
1946 {
1947 printf_monitor ("%s", packet);
1948
1949 /* read until either a timeout occurs (-2) or '+' is read */
1950 while (retries <= 10)
1951 {
1952 c = readchar (timeout);
1953 debuglogs (3, "Reading a GDB protocol packet... Got a '%c'\n", c);
1954 switch (c)
1955 {
1956 case '+':
1957 debuglogs (3, "Got Ack\n");
1958 return 1;
1959 case SERIAL_TIMEOUT:
1960 debuglogs (3, "Timed out reading serial port\n");
1961 break; /* Retransmit buffer */
1962 case '-':
1963 debuglogs (3, "Got NAK\n");
1964 break; /* FIXME: (maybe) was a continue */
1965 case '$':
1966 /* It's probably an old response, or the echo of our
1967 command. just gobble up the packet and ignore it. */
1968 debuglogs (3, "Got a junk packet\n");
1969 do
1970 {
1971 c = readchar (timeout);
1972 junk[i++] = c;
1973 } while (c != '#');
1974 c = readchar (timeout);
1975 junk[i++] = c;
1976 c = readchar (timeout);
1977 junk[i++] = c;
1978 junk[i++] = '\0';
1979 debuglogs (3, "Reading a junk packet, got a \"%s\"\n", junk);
1980 continue; /* Now, go look for next packet */
1981 default:
1982 continue;
1983 }
1984 retries++;
1985 debuglogs (3, "Retransmitting packet \"%s\"\n", packet);
1986 break; /* Here to retransmit */
1987 }
1988 } /* outer while */
1989 return 0;
1990 }
1991
1992 /* Get a GDB packet from the target. Basically we read till we see a
1993 '#', then check the checksum. It returns a 1 if it's gotten a
1994 packet, or a 0 it the packet wasn't transmitted correctly. */
1995
1996 int
1997 monitor_get_packet (packet)
1998 char *packet;
1999 {
2000 int c;
2001 int retries;
2002 unsigned char csum;
2003 unsigned char pktcsum;
2004 char *bp;
2005
2006 csum = 0;
2007 bp = packet;
2008
2009 memset (packet, 1, PBUFSIZ);
2010 retries = 0;
2011 while (retries <= 10)
2012 {
2013 do
2014 {
2015 c = readchar (timeout);
2016 if (c == SERIAL_TIMEOUT)
2017 {
2018 debuglogs (3, "monitor_get_packet: got time out from serial port.\n");
2019 }
2020 debuglogs (3, "Waiting for a '$', got a %c\n", c);
2021 } while (c != '$');
2022
2023 retries = 0;
2024 while (retries <= 10)
2025 {
2026 c = readchar (timeout);
2027 debuglogs (3, "monitor_get_packet: got a '%c'\n", c);
2028 switch (c)
2029 {
2030 case SERIAL_TIMEOUT:
2031 debuglogs (3, "Timeout in mid-packet, retrying\n");
2032 return 0;
2033 case '$':
2034 debuglogs (3, "Saw new packet start in middle of old one\n");
2035 return 0; /* Start a new packet, count retries */
2036 case '#':
2037 *bp = '\0';
2038 pktcsum = from_hex (readchar (timeout)) << 4;
2039 pktcsum |= from_hex (readchar (timeout));
2040 if (csum == pktcsum)
2041 {
2042 debuglogs (3, "\nGDB packet checksum correct, packet data is \"%s\",\n", packet);
2043 printf_monitor ("+");
2044 expect_prompt (1);
2045 return 1;
2046 }
2047 debuglogs (3, "Bad checksum, sentsum=0x%x, csum=0x%x\n", pktcsum, csum);
2048 return 0;
2049 case '*': /* Run length encoding */
2050 debuglogs (5, "Run length encoding in packet\n");
2051 csum += c;
2052 c = readchar (timeout);
2053 csum += c;
2054 c = c - ' ' + 3; /* Compute repeat count */
2055
2056 if (c > 0 && c < 255 && bp + c - 1 < packet + PBUFSIZ - 1)
2057 {
2058 memset (bp, *(bp - 1), c);
2059 bp += c;
2060 continue;
2061 }
2062 *bp = '\0';
2063 printf_filtered ("Repeat count %d too large for buffer.\n", c);
2064 return 0;
2065
2066 default:
2067 if ((!isxdigit (c)) && (!ispunct (c)))
2068 debuglogs (4, "Got a non-ascii digit \'%c\'.\\n", c);
2069 if (bp < packet + PBUFSIZ - 1)
2070 {
2071 *bp++ = c;
2072 csum += c;
2073 continue;
2074 }
2075
2076 *bp = '\0';
2077 puts_filtered ("Remote packet too long.\n");
2078 return 0;
2079 }
2080 }
2081 }
2082 }
2083
2084 /* Convert an ascii number represented by 8 digits to a hex value. */
2085
2086 static unsigned long
2087 ascii2hexword (mem)
2088 unsigned char *mem;
2089 {
2090 unsigned long val;
2091 int i;
2092 char buf[9];
2093
2094 val = 0;
2095 for (i = 0; i < 8; i++)
2096 {
2097 val <<= 4;
2098 if (mem[i] >= 'A' && mem[i] <= 'F')
2099 val = val + mem[i] - 'A' + 10;
2100 if (mem[i] >= 'a' && mem[i] <= 'f')
2101 val = val + mem[i] - 'a' + 10;
2102 if (mem[i] >= '0' && mem[i] <= '9')
2103 val = val + mem[i] - '0';
2104 buf[i] = mem[i];
2105 }
2106 buf[8] = '\0';
2107 debuglogs (4, "ascii2hexword() got a 0x%x from %s(%x).\n", val, buf, mem);
2108 return val;
2109 }
2110
2111 /* Convert a hex value to an ascii number represented by 8 digits. */
2112
2113 static char *
2114 hexword2ascii (mem, num)
2115 unsigned char *mem;
2116 unsigned long num;
2117 {
2118 int i;
2119
2120 debuglogs (4, "hexword2ascii() converting %x ", num);
2121 for (i = 7; i >= 0; i--)
2122 {
2123 mem[i] = tohex ((num >> 4) & 0xf);
2124 mem[i] = tohex (num & 0xf);
2125 num = num >> 4;
2126 }
2127 mem[8] = '\0';
2128 debuglogs (4, "\tto a %s", mem);
2129 }
2130
2131 /* Convert hex digit A to a number. */
2132
2133 static int
2134 from_hex (a)
2135 int a;
2136 {
2137 if (a == 0)
2138 return 0;
2139
2140 debuglogs (4, "from_hex got a 0x%x(%c)\n",a,a);
2141 if (a >= '0' && a <= '9')
2142 return a - '0';
2143 if (a >= 'a' && a <= 'f')
2144 return a - 'a' + 10;
2145 if (a >= 'A' && a <= 'F')
2146 return a - 'A' + 10;
2147 error ("Reply contains invalid hex digit 0x%x", a);
2148 }
2149
2150 /* Convert number NIB to a hex digit. */
2151
2152 static int
2153 tohex (nib)
2154 int nib;
2155 {
2156 if (nib < 10)
2157 return '0' + nib;
2158 else
2159 return 'a' + nib - 10;
2160 }
2161
2162 /* Define additional commands that are usually only used by monitors. */
2163
2164 void
2165 _initialize_remote_monitors ()
2166 {
2167 struct cmd_list_element *c;
2168
2169 /* this sets the type of download protocol */
2170 c = add_set_cmd ("remoteloadprotocol", no_class, var_string, (char *)&loadproto_str,
2171 "Set the type of the remote load protocol.\n", &setlist);
2172 c->function.sfunc = set_loadproto_command;
2173 add_show_from_set (c, &showlist);
2174 loadproto_str = savestring ("none", 5);
2175
2176 /* this sets the conversion type when loading */
2177 c = add_set_cmd ("remoteloadtype", no_class, var_string, (char *)&loadtype_str,
2178 "Set the type of the remote load protocol.\n", &setlist);
2179 c->function.sfunc = set_loadtype_command;
2180 add_show_from_set (c, &showlist);
2181 loadtype_str = savestring ("srec", 5);
2182
2183 add_show_from_set (add_set_cmd ("hash", no_class, var_boolean,
2184 (char *)&hashmark,
2185 "Set display of activity while downloading a file.\n\
2186 When enabled, a period \'.\' is displayed.",
2187 &setlist),
2188 &showlist);
2189
2190 add_com ("monitor", class_obscure, monitor_command,
2191 "Send a command to the debug monitor.");
2192 }