* breakpoint.c, breakpoint.h (breakpoint_init_inferior): New function
[external/binutils.git] / gdb / remote-es.c
1 /* Memory-access and commands for remote es1800 processes, for GDB.
2    Copyright (C) 1988, 1992 Free Software Foundation, Inc.
3
4    This file is added to GDB to make it possible to do debugging via an
5    ES-1800 emulator. The code was originally written by Johan Holmberg
6    TT/SJ Ericsson Telecom AB and later modified by Johan Henriksson
7    TT/SJ. It was modified for gdb 4.0 by TX/DK Jan Nordenand by TX/DKG
8    Harald Johansen.
9
10 This file is part of GDB.
11
12 GDB is free software; you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation; either version 1, or (at your option)
15 any later version.
16
17 GDB is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 GNU General Public License for more details.
21
22 You should have received a copy of the GNU General Public License
23 along with GDB; see the file COPYING.  If not, write to
24 the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
25
26
27 /* Emulator communication protocol.
28    All values are encoded in ascii hex digits.
29
30         Request
31 Command
32 Reply
33         read registers:
34 DR<cr>
35      - 0 -    - 1 -    - 2 -    - 3 -      - 4 -    - 5 -    -- 6 -   - 7 - 
36 D = XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX   XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX
37 A = XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX   XXXXXXXX XXXXXXXX XXXXXXXX 
38     PC = XXXXXX       SSP = XXXXXX    USP = XXXXXX     SR = XXXXXXXX
39  >
40 Each byte of register data is described by two hex digits.
41
42         write regs
43 D0=XXXXXXXX<cr>
44  >D1=XXXXXXXX<cr>
45  >D2=XXXXXXXX<cr>
46  >D3=XXXXXXXX<cr>
47  >D4=XXXXXXXX<cr>
48  >D5=XXXXXXXX<cr>
49  >D6=XXXXXXXX<cr>
50  >D7=XXXXXXXX<cr>
51  >A0=XXXXXXXX<cr>
52  >A1=XXXXXXXX<cr>
53  >A2=XXXXXXXX<cr>
54  >A3=XXXXXXXX<cr>
55  >A4=XXXXXXXX<cr>
56  >A5=XXXXXXXX<cr>
57  >A6=XXXXXXXX<cr>
58  >A7=XXXXXXXX<cr>
59  >SR=XXXXXXXX<cr>
60  >PC=XXXXXX<cr>
61  >
62 Each byte of register data is described by two hex digits.
63
64         read mem
65 @.BAA..AA
66 $FFFFFFXX
67  >
68 AA..AA is address, XXXXXXX is the contents
69
70         write mem
71         @.BAA..AA=$XXXXXXXX
72  >
73 AA..AA is address, XXXXXXXX is data
74
75         cont
76 PC=$AA..AA
77  >RBK
78 R>
79 AA..AA is address to resume. If AA..AA is omitted, resume at same address.
80
81         step
82 PC=$AA..AA
83  >STP
84 R>
85 AA..AA is address to resume. If AA..AA is omitted, resume at same address.
86
87         kill req
88 STP
89  >
90 */
91
92
93 #include <stdio.h>
94 #include <signal.h>
95 #include <sys/ioctl.h>
96 #include <sys/file.h>
97 #include <errno.h>
98 #include <ctype.h>
99 #include <string.h>
100 #include <setjmp.h>
101 #include <fcntl.h>
102 #include "defs.h"
103 #include "frame.h"
104 #include "inferior.h"
105 #include "target.h"
106 #include "wait.h"
107 #include "terminal.h"
108 #include "command.h"
109 #include "remote-utils.h"
110
111 #ifdef USG
112 #include <sys/types.h>
113 #include <sgtty.h>
114 #endif
115
116 #include <signal.h>
117
118 /* External variables referenced. */
119
120 extern bfd *exec_bfd;
121
122 /* Prototypes for local functions */
123
124 static void
125 es1800_child_detach PARAMS ((char *, int));
126
127 static void
128 es1800_child_open PARAMS ((char *, int));
129
130 static void 
131 es1800_transparent PARAMS ((char *, int));
132
133 static void
134 es1800_create_inferior PARAMS ((char *, char *, char **));
135
136 static void
137 es1800_load PARAMS ((char *, int));
138
139 static void
140 es1800_kill PARAMS ((void));
141
142 static int
143 verify_break PARAMS ((int));
144
145 static int
146 es1800_remove_breakpoint PARAMS ((CORE_ADDR, char *));
147
148 static int
149 es1800_insert_breakpoint PARAMS ((CORE_ADDR, char *));
150
151 static void
152 es1800_files_info PARAMS ((struct target_ops *));
153
154 static int
155 es1800_xfer_inferior_memory PARAMS ((CORE_ADDR, char *, int, int,
156                                      struct target_ops *));
157
158 static void 
159 es1800_prepare_to_store PARAMS ((void));
160
161 static int
162 es1800_wait PARAMS ((WAITTYPE *));
163
164 static void
165 es1800_resume PARAMS ((int, int, int));
166
167 static void
168 es1800_detach PARAMS ((char *, int));
169
170 static void
171 es1800_attach PARAMS ((char *, int));
172
173 static int
174 damn_b PARAMS ((char *));
175
176 static void
177 es1800_open PARAMS ((char *, int));
178
179 static void
180 es1800_timer PARAMS ((void));
181
182 static void
183 es1800_reset PARAMS ((char *));
184
185 static void
186 es1800_request_quit PARAMS ((void));
187
188 static int
189 readchar PARAMS ((void));
190
191 static void
192 expect PARAMS ((char *, int));
193
194 static void
195 expect_prompt PARAMS ((void));
196
197 static void
198 download PARAMS ((FILE *, int, int));
199
200 #if 0
201 static void
202 bfd_copy PARAMS ((bfd *, bfd *));
203 #endif
204
205 static void
206 get_break_addr PARAMS ((int, CORE_ADDR *));
207
208 static int
209 fromhex PARAMS ((int));
210
211 static int
212 tohex PARAMS ((int));
213
214 static void
215 es1800_close PARAMS ((int));
216
217 static void
218 es1800_fetch_registers PARAMS ((void));
219
220 static void
221 es1800_fetch_register PARAMS ((int));
222
223 static void
224 es1800_store_register PARAMS ((int));
225
226 static void
227 es1800_read_bytes PARAMS ((CORE_ADDR, char *, int));
228
229 static void
230 es1800_write_bytes PARAMS ((CORE_ADDR, char *, int));
231
232 static void
233 send_with_reply PARAMS ((char *, char *, int));
234
235 static void
236 send_command PARAMS ((char *));
237
238 static void
239 send PARAMS ((char *));
240
241 static void
242 getmessage PARAMS ((char *, int));
243
244 static void
245 es1800_mourn_inferior PARAMS ((void));
246
247 static void
248 es1800_create_break_insn PARAMS ((char *, int));
249
250 static void
251 es1800_init_break PARAMS ((char *, int));
252
253 /* Local variables */
254
255 #define LOG_FILE "es1800.log"
256 #if defined (LOG_FILE)
257 static FILE *log_file;
258 #endif
259
260 extern struct target_ops es1800_ops;            /* Forward decl */
261 extern struct target_ops es1800_child_ops;      /* Forward decl */
262
263 static int kiodebug;
264 static int timeout = 100; 
265 static char *savename;                          /* Name of i/o device used */
266 static TERMINAL es1800_sg_save;                 /* Save stty state */
267 static int es1800_fc_save;                      /* Save fcntl state */
268
269 /* indicates that the emulator uses 32-bit data-adress (68020-mode) 
270    instead of 24-bit (68000 -mode) */
271
272 static int m68020;
273
274 #define MODE (m68020 ? "M68020" : "M68000" )
275 #define ES1800_BREAK_VEC (0xf)
276
277 /* Descriptor for I/O to remote machine.  Initialize it to -1 so that
278    es1800_open knows that we don't have a file open when the program
279    starts.  */
280
281 static int es1800_desc = -1;
282
283 #define PBUFSIZ 1000
284 #define HDRLEN sizeof("@.BAAAAAAAA=$VV\r")
285
286 /* Maximum number of bytes to read/write at once.  The value here
287    is chosen to fill up a packet.  */
288
289 #define MAXBUFBYTES ((PBUFSIZ-150)*16/75 )
290
291 static int es1800_break_vec = 0;
292 static char es1800_break_insn[2];
293 static long es1800_break_address;
294 static void (*old_sigint)();            /* Old signal-handler for sigint */
295 static jmp_buf interrupt;
296
297 /* Local signalhandler to allow breaking tranfers or program run.
298    Rely on global variables: old_sigint(), interrupt */
299
300 static void
301 es1800_request_quit ()
302 {
303   /* restore original signalhandler */
304   signal (SIGINT, old_sigint);
305   longjmp (interrupt, 1);
306 }
307
308
309 /* Reset emulator.
310    Sending reset character(octal 32) to emulator.
311    quit - return to '(esgdb)' prompt or continue        */
312
313 static void
314 es1800_reset (quit)
315      char *quit;
316 {
317   char buf[80];
318
319   if (quit)
320     {
321       printf ("\nResetting emulator...  ");
322     }
323   strcpy (buf, "\032");
324   send (buf);
325   expect_prompt ();
326   if (quit)
327     {
328       error ("done\n");
329     }
330 }
331
332
333 /* Called when SIGALRM signal sent due to alarm() timeout.
334    Rely on global variables: timeout  */
335
336 #ifndef HAVE_TERMIO
337
338 static void
339 es1800_timer ()
340 {
341   if (kiodebug)
342     {
343       printf ("es1800_timer called\n");
344     }
345   alarm (timeout);
346 }
347
348 #endif  /* HAVE_TERMIO */
349
350
351 /* Open a connection to a remote debugger and push the new target
352    onto the stack. Check if the emulator is responding and find out
353    what kind of processor the emulator is connected to.
354    Initiate the breakpoint handling in the emulator.
355
356    name     - the filename used for communication (ex. '/dev/tta')
357    from_tty - says whether to be verbose or not */
358
359 static void
360 es1800_open (name, from_tty)
361      char *name;
362      int from_tty;
363 {
364   TERMINAL sg;
365   char buf[PBUFSIZ];
366   char *p;
367   int i, fcflag;
368   char baudrate[1024];
369
370   m68020 = 0;
371
372   if (!name)           /* no device name given in target command */
373     {
374       error_no_arg ("serial port device name");
375     }
376   sprintf(baudrate, "%d", sr_get_baud_rate());
377
378   target_preopen (from_tty);
379   es1800_close (0);
380
381   /* open the device and configure it for communication */
382
383 #ifndef DEBUG_STDIN
384
385   es1800_desc = open (name, O_RDWR);
386   if (es1800_desc < 0)
387     {
388       perror_with_name (name);
389     }
390   savename = savestring (name, strlen (name));
391
392   if (ioctl (es1800_desc, TIOCGETP, &sg) == -1)
393     {
394       perror_with_name (name);
395     }
396   es1800_sg_save = sg;
397
398   if ((fcflag = fcntl (es1800_desc, F_GETFL, 0)) == -1)
399     {
400       perror_with_name ("fcntl serial");
401     }
402   es1800_fc_save = fcflag;
403
404   fcflag = (fcflag & (FREAD | FWRITE)); /* mask out any funny stuff */
405   if (fcntl (es1800_desc, F_SETFL, fcflag) == -1)
406     {
407       perror_with_name ("fcntl serial");
408     }
409
410 #ifdef HAVE_TERMIO
411   sg.c_cc[VMIN] = 0;            /* read with timeout.  */
412   sg.c_cc[VTIME] = timeout * 10;
413   sg.c_lflag &= ~(ICANON | ECHO);
414   sg.c_cflag = (sg.c_cflag & ~CBAUD) | damn_b (baudrate);
415 #else
416   sg.sg_ispeed = damn_b (baudrate);
417   sg.sg_ospeed = damn_b (baudrate);
418   sg.sg_flags = CBREAK+TANDEM;
419 #endif
420
421   if ((ioctl (es1800_desc, TIOCSETP, &sg)) == -1)
422     {
423       perror ("es1800_open: error in ioctl");
424     }
425
426 #endif  /* DEBUG_STDIN */
427
428   push_target (&es1800_ops);    /* Switch to using remote target now */
429   if (from_tty)
430     {
431       printf ("Remote ES1800 debugging using %s\n", name);
432     }
433
434 #ifndef HAVE_TERMIO
435
436 #ifndef NO_SIGINTERRUPT
437
438   /* Cause SIGALRM's to make reads fail with EINTR instead of resuming
439      the read.  */
440
441   if (siginterrupt (SIGALRM, 1) != 0)
442     {
443       perror ("es1800_open: error in siginterrupt");
444     }
445
446 #endif  /* NO_SIGINTERRUPT */
447
448   /* Set up read timeout timer.  */
449
450   if ((void(*)()) signal (SIGALRM, es1800_timer) == (void(*)()) -1)
451     {
452       perror ("es1800_open: error in signal");
453     }
454
455 #endif  /* HAVE_TERMIO */
456
457
458 #if defined (LOG_FILE)
459
460   log_file = fopen (LOG_FILE, "w");
461   if (log_file == NULL)
462     {
463       perror_with_name (LOG_FILE);
464     }
465
466 #endif  /* LOG_FILE */
467
468   /* Hello?  Are you there?, also check mode  */
469
470   /*  send_with_reply( "DB 0 TO 1", buf, sizeof(buf)); */
471   /*  for (p = buf, i = 0; *p++ =='0';)  */   /* count the number of zeros */
472   /*      i++; */
473
474   send ("\032");
475   getmessage (buf, sizeof (buf));  /* send reset character */
476
477   if (from_tty)
478     {
479       printf ("Checking mode.... ");
480     }
481   /*  m68020 = (i==8); */   /* if eight zeros then we are in m68020 mode */
482
483   /* What kind of processor am i talking to ?*/
484   p = buf;
485   while (*p++ != '\n') {;}
486   while (*p++ != '\n') {;}
487   while (*p++ != '\n') {;}
488   for (i = 0; i < 20; i++, p++) {;}
489   m68020 = !strncmp (p, "68020", 5);
490   if (from_tty)
491     {
492       printf ("You are in %s(%c%c%c%c%c)-mode\n", MODE, p[0], p[1], p[2],
493               p[3], p[4]);
494     }
495
496   /* if no init_break statement is present in .gdb file we have to check 
497      whether to download a breakpoint routine or not */
498
499 #if 0
500   if ((es1800_break_vec == 0) || (verify_break (es1800_break_vec) != 0)
501       && query ("No breakpoint routine in ES 1800 emulator!\nDownload a breakpoint routine to the emulator? "))
502     {
503       CORE_ADDR memaddress;
504       printf ("Give the start address of the breakpoint routine: ");
505       scanf ("%li", &memaddress);
506       es1800_init_break ((es1800_break_vec ? es1800_break_vec :
507                           ES1800_BREAK_VEC), memaddress);
508     }
509 #endif
510
511 }
512
513 /*  Close out all files and local state before this target loses control.
514     quitting - are we quitting gdb now? */
515
516 static void
517 es1800_close (quitting)
518      int quitting;
519 {
520   if (es1800_desc >= 0)
521     {
522       printf ("\nClosing connection to emulator...\n");
523       ioctl (es1800_desc, TIOCSETP, &es1800_sg_save);
524       fcntl (es1800_desc,F_SETFL, es1800_fc_save);
525       close (es1800_desc);
526       es1800_desc = -1;
527     }
528   if (savename != NULL)
529     {
530       free (savename);
531     }
532   savename = NULL;
533
534 #if defined (LOG_FILE)
535
536   if (log_file != NULL)
537     {
538       if (ferror (log_file))
539         {
540           printf ("Error writing log file.\n");
541         }
542       if (fclose (log_file) != 0)
543         {
544           printf ("Error closing log file.\n");
545         }
546       log_file = NULL;
547     }
548
549 #endif  /* LOG_FILE */
550
551 }
552
553 /* damn_b()
554
555    Translate baud rates from integers to damn B_codes.  Unix should
556    have outgrown this crap years ago, but even POSIX wouldn't buck it.
557    rate - the baudrate given as a string
558    return value: the baudrate as a B_code */
559
560 #ifndef B19200
561 #  define B19200 EXTA
562 #endif
563 #ifndef B38400
564 #  define B38400 EXTB
565 #endif
566
567 struct
568 {
569   char *rate,
570   damn_b;
571 } baudtab[] = {
572   {"0", B0},
573   {"50", B50},
574   {"75", B75},
575   {"110", B110},
576   {"134", B134},
577   {"150", B150},
578   {"200", B200},
579   {"300", B300},
580   {"600", B600},
581   {"1200", B1200},
582   {"1800", B1800},
583   {"2400", B2400},
584   {"4800", B4800},
585   {"9600", B9600},
586   {"19200", B19200},
587   {"38400", B38400},
588   {0, -1},
589 };
590
591 static int
592 damn_b (rate)
593      char *rate;
594 {
595   int i;
596
597   for (i = 0; baudtab[i].rate != 0; i++)
598     {
599       if (STREQ (rate, baudtab[i].rate))
600         {
601           return (baudtab[i].damn_b);
602         }
603     }
604   error ("Illegal baudrate");
605 }
606
607
608 /*  Attaches to a process on the target side
609     proc_id  - the id of the process to be attached.
610     from_tty - says whether to be verbose or not */
611
612 static void
613 es1800_attach (args, from_tty)
614     char *args;
615     int from_tty;
616 {
617   error ("Cannot attach to pid %s, this feature is not implemented yet.",
618          args);
619 }
620
621
622 /* Takes a program previously attached to and detaches it.
623    We better not have left any breakpoints
624    in the program or it'll die when it hits one.
625    Close the open connection to the remote debugger.
626    Use this when you want to detach and do something else
627    with your gdb.
628  
629    args     - arguments given to the 'detach' command
630    from_tty - says whether to be verbose or not */
631
632 static void
633 es1800_detach (args, from_tty)
634      char *args;
635      int from_tty;
636 {
637   if (args)
638     {
639       error ("Argument given to \"detach\" when remotely debugging.");
640     }
641   pop_target ();
642   if (from_tty)
643     {
644       printf ("Ending es1800 remote debugging.\n");
645     }
646 }
647
648
649 /* Tell the remote machine to resume.
650    step    - single-step or run free
651    siggnal - the signal value to be given to the target (0 = no signal) */
652
653 static void
654 es1800_resume (pid, step, siggnal)
655      int pid;
656      int step;
657      int siggnal;
658 {
659   char buf[PBUFSIZ];
660
661   if (siggnal)
662     {
663       error ("Can't send signals to a remote system.");
664     }
665   if (step)
666     {
667       strcpy (buf,"STP\r");
668       send (buf);
669     }
670   else
671     {
672       send_command ("RBK");
673     }
674 }
675
676 /* Wait until the remote machine stops, then return,
677    storing status in STATUS just as `wait' would.
678    status -  */
679  
680 static int
681 es1800_wait (status)
682      WAITTYPE *status;
683 {
684   unsigned char buf[PBUFSIZ];
685   int old_timeout = timeout;
686
687   WSETEXIT ((*status), 0);
688   timeout = 0;          /* Don't time out -- user program is running. */
689   if (!setjmp (interrupt))
690     {
691       old_sigint = signal (SIGINT, es1800_request_quit);
692       while (1)
693         {
694           getmessage (buf, sizeof(buf));
695           if (strncmp ( buf, "\r\n* BREAK *", 11) == 0) 
696             {
697               WSETSTOP ((*status), SIGTRAP);
698               send_command ("STP");     /* Restore stack and PC and such */
699               if (m68020)
700                 {
701                   send_command ("STP");
702                 }
703               break;
704             }
705           if (strncmp (buf, "STP\r\n ", 6) == 0)
706             {
707               WSETSTOP ((*status), SIGTRAP);
708               break;
709             }
710           if (buf[strlen (buf) - 2] == 'R')
711             {
712               printf ("Unexpected emulator reply: \n%s\n", buf);
713             }
714           else
715             {
716               printf ("Unexpected stop: \n%s\n", buf);
717               WSETSTOP ((*status), SIGQUIT);
718               break;
719             }
720         }
721     }
722   else
723     {
724       fflush (stdin);
725       printf ("\nStopping emulator...");
726       if (!setjmp (interrupt))
727         {
728           old_sigint = signal (SIGINT, es1800_request_quit);
729           send_command ("STP");
730           printf (" emulator stopped\n");
731           WSETSTOP ((*status), SIGINT);
732         }
733       else
734         {
735           fflush (stdin);
736           es1800_reset ((char*) 1);
737         }
738     }
739   signal (SIGINT, old_sigint);
740   timeout = old_timeout;
741   return (0);
742 }
743
744
745 /* Fetch register values from remote machine.
746    regno - the register to be fetched (fetch all registers if -1) */
747
748 static void
749 es1800_fetch_register (regno)
750      int regno;
751 {
752   char buf[PBUFSIZ];
753   int k;
754   int r;
755   char *p;
756   static char regtab[18][4] = 
757     {
758       "D0 ", "D1 ", "D2 ", "D3 ", "D4 ", "D5 ", "D6 ", "D7 ",
759       "A0 ", "A1 ", "A2 ", "A3 ", "A4 ", "A5 ", "A6 ", "SSP",
760       "SR ", "PC "
761     };
762
763   if ((regno < 15) || (regno == 16) || (regno == 17))
764     {
765       r = regno * 4;
766       send_with_reply (regtab[regno], buf, sizeof (buf));
767       p = buf;
768       for (k = 0; k < 4; k++)
769         {
770           if ((p[k*2 + 1] == 0) || (p[k*2 + 2] == 0))
771             {
772               error ("Emulator reply is too short: %s", buf);
773             }
774           registers[r++] = (fromhex (p[k*2 + 1]) * 16) + fromhex (p[k*2 + 2]);
775         }
776     }
777   else
778     {
779       es1800_fetch_registers ();
780     }
781 }
782
783 /* Read the remote registers into REGISTERS.
784    Always fetches all registers. */
785
786 static void
787 es1800_fetch_registers ()
788 {
789   char buf[PBUFSIZ];
790   char SR_buf[PBUFSIZ];
791   int i;
792   int k;
793   int r;
794   char *p;
795
796   send_with_reply ("DR", buf, sizeof (buf));
797
798   /* Reply is edited to a string that describes registers byte by byte,
799      each byte encoded as two hex characters.  */
800
801   p = buf;
802   r = 0;
803
804   /*  parsing row one - D0-D7-registers  */
805
806   while (*p++ != '\n') {;}
807   for (i = 4; i < 70; i += (i == 39 ? 3 : 1))
808     {
809       for (k = 0; k < 4; k++)
810         {
811           if (p[i+0] == 0 || p[i+1] == 0)
812             {
813               error ("Emulator reply is too short: %s", buf);
814             }
815           registers[r++] = (fromhex (p[i+0]) * 16) + fromhex (p[i+1]);
816           i += 2;
817         }
818     }
819   p += i;
820
821   /*  parsing row two - A0-A6-registers  */
822
823   while (*p++ != '\n') {;}
824   for (i = 4; i < 61; i += (i == 39 ? 3 : 1))
825     {
826       for (k = 0; k < 4; k++)
827         {
828           if (p[i+0] == 0 || p[i+1] == 0)
829             {
830               error ("Emulator reply is too short: %s", buf);
831             }
832           registers[r++] = (fromhex (p[i+0])) * 16 + fromhex (p[i+1]);
833           i += 2;
834         }
835     }
836   p += i;
837
838   while (*p++ != '\n') {;}
839
840   /* fetch SSP-, SR- and PC-registers  */
841
842   /* first - check STATUS-word and decide which stackpointer to use */
843
844   send_with_reply ("SR", SR_buf, sizeof (SR_buf));
845   p = SR_buf;
846   p += 5;
847
848   if (m68020)
849     {
850       if (*p == '3')             /* use masterstackpointer MSP */
851         {
852           send_with_reply ("MSP", buf, sizeof (buf));
853         }
854       else if (*p == '2')       /* use interruptstackpointer ISP  */
855         {
856           send_with_reply ("ISP", buf, sizeof (buf));
857         }
858       else                      /* use userstackpointer USP  */
859         {
860           send_with_reply ("USP", buf, sizeof (buf)); 
861         }
862       p = buf;
863       for (k = 0; k<4; k++)
864         {
865           if (p[k*2+1] == 0 || p[k*2+2] == 0)
866             {
867               error ("Emulator reply is too short: %s", buf);
868             }
869           registers[r++] = fromhex (buf[k*2+1]) * 16 + fromhex (buf[k*2+2]);
870         }
871
872       p = SR_buf;
873       for (k = 0; k < 4; k++)
874         {
875           if (p[k*2+1] == 0 || p[k*2+2] == 0)
876             {
877               error ("Emulator reply is too short: %s", buf);
878             }
879           registers[r++] =
880             fromhex (SR_buf[k*2+1]) * 16 + fromhex (SR_buf[k*2+2]);
881         }
882       send_with_reply ("PC", buf, sizeof (buf));
883       p = buf;
884       for (k = 0; k<4; k++)
885         {
886           if (p[k*2+1] == 0 || p[k*2+2] == 0)
887             {
888               error ("Emulator reply is too short: %s", buf);
889             }
890           registers[r++] = fromhex (buf[k*2+1]) * 16 + fromhex (buf[k*2+2]);
891         }
892     }
893   else    /* 68000-mode */
894     {                       
895       if (*p == '2') /* use supervisorstackpointer SSP  */
896         {
897           send_with_reply ("SSP", buf, sizeof (buf)); 
898         }
899       else  /* use userstackpointer USP  */
900         {
901           send_with_reply ("USP", buf, sizeof (buf)); 
902         }
903
904       /* fetch STACKPOINTER */
905
906       p = buf;
907       for (k = 0; k < 4; k++)
908         {
909           if (p[k*2 + 1] == 0 || p[k*2 + 2] == 0)
910             {
911               error ("Emulator reply is too short: %s", buf);
912             }
913           registers[r++] = fromhex (buf[k*2+1]) * 16 + fromhex (buf[k*2+2]);
914         }
915
916       /* fetch STATUS */
917
918       p = SR_buf;
919       for (k = 0; k < 4; k++)
920         {
921           if (p[k*2+1] == 0 || p[k*2+2] == 0)
922             {
923               error ("Emulator reply is too short: %s", buf);
924             }
925           registers[r++] =
926             fromhex (SR_buf[k*2+1]) * 16 + fromhex (SR_buf[k*2+2]);
927         }
928
929       /* fetch PC */
930
931       send_with_reply ("PC", buf, sizeof (buf)); 
932       p = buf;
933       for (k = 0; k < 4; k++)
934         {
935           if (p[k*2+1] == 0 || p[k*2+2] == 0)
936             {
937               error ("Emulator reply is too short: %s", buf);
938             }
939           registers[r++] = fromhex (buf[k*2+1]) * 16 + fromhex (buf[k*2+2]);
940         }    
941     }
942 }
943
944 /* Store register value, located in REGISTER, on the target processor.
945    regno - the register-number of the register to store
946            (-1 means store them all)
947    FIXME: Return errno value.  */
948
949 static void
950 es1800_store_register(regno)
951      int regno;
952 {
953
954   static char regtab[18][4] =
955     {
956       "D0 ", "D1 ", "D2 ", "D3 ", "D4 ", "D5 ", "D6 ", "D7 ",
957       "A0 ", "A1 ", "A2 ", "A3 ", "A4 ", "A5 ", "A6 ", "SSP",
958       "SR ", "PC "
959     };
960
961   char buf[PBUFSIZ];
962   char SR_buf[PBUFSIZ];
963   char stack_pointer[4];
964   char *p;
965   int i;
966   int j;
967   int k;
968   unsigned char *r;
969
970   r = (unsigned char *) registers;
971
972   if (regno == -1)  /* write all registers */
973     {
974       j = 0;
975       k = 18;
976     }
977   else              /* write one register */
978     {
979       j = regno;
980       k = regno+1;
981       r += regno * 4; 
982     }    
983
984   if ((regno == -1) || (regno == 15))
985     {
986       /* fetch current status */
987       send_with_reply ("SR", SR_buf, sizeof (SR_buf));
988       p = SR_buf;
989       p += 5;
990       if (m68020)
991         {
992           if (*p == '3') /* use masterstackpointer MSP */
993             {
994               strcpy (stack_pointer,"MSP");  
995             }
996           else
997             {
998               if (*p == '2') /* use interruptstackpointer ISP  */
999                 {
1000                   strcpy (stack_pointer,"ISP");  
1001                 }
1002               else
1003                 {
1004                   strcpy (stack_pointer,"USP");  /* use userstackpointer USP  */
1005                 }
1006             }
1007         }
1008       else  /* 68000-mode */
1009         {
1010           if (*p == '2') /* use supervisorstackpointer SSP  */
1011             {
1012               strcpy (stack_pointer,"SSP");  
1013             }
1014           else
1015             {
1016               strcpy (stack_pointer,"USP");/* use userstackpointer USP  */  
1017             }
1018         }
1019       strcpy (regtab[15],stack_pointer);
1020     }
1021
1022   for (i = j; i<k; i++)
1023     {
1024       buf[0] = regtab[i][0];
1025       buf[1] = regtab[i][1];
1026       buf[2] = regtab[i][2];
1027       buf[3] = '=';
1028       buf[4] = '$';
1029       buf[5] = tohex ((*r >> 4) & 0x0f);
1030       buf[6] = tohex (*r++ & 0x0f);
1031       buf[7] = tohex ((*r >> 4) & 0x0f);
1032       buf[8] = tohex (*r++ & 0x0f);
1033       buf[9] = tohex ((*r >> 4) & 0x0f);
1034       buf[10] = tohex (*r++ & 0x0f);
1035       buf[11] = tohex ((*r >> 4) & 0x0f);
1036       buf[12] = tohex (*r++ & 0x0f);
1037       buf[13] = 0;
1038
1039       send_with_reply (buf, buf, sizeof (buf)); /* FIXME, reply not used? */
1040     }
1041 }
1042
1043
1044 /* Prepare to store registers.  */
1045
1046 static void 
1047 es1800_prepare_to_store ()
1048 {
1049   /* Do nothing, since we can store individual regs */
1050 }
1051
1052 /* Convert hex digit A to a number.  */
1053
1054 static int
1055 fromhex (a)
1056      int a;
1057 {
1058   if (a >= '0' && a <= '9')
1059     {
1060       return a - '0';
1061     }
1062   else if (a >= 'a' && a <= 'f')
1063     {
1064       return a - 'a' + 10;
1065     }
1066   else if (a >= 'A' && a <= 'F')
1067     {
1068       return a - 'A' + 10;
1069     }
1070   else
1071     {
1072       error ("Reply contains invalid hex digit");
1073     }
1074   return (-1);
1075 }
1076
1077
1078 /* Convert number NIB to a hex digit.  */
1079
1080 static int
1081 tohex (nib)
1082      int nib;
1083 {
1084   if (nib < 10)
1085     {
1086       return ('0' + nib);
1087     }
1088   else
1089     {
1090       return ('A' + nib - 10);
1091     }
1092 }
1093
1094 /* Read or write LEN bytes from inferior memory at MEMADDR, transferring
1095    to or from debugger address MYADDR.  Write to inferior if WRITE is
1096    nonzero.  Returns length of data written or read; 0 for error. 
1097  
1098    memaddr - the target's address
1099    myaddr  - gdb's address
1100    len     - number of bytes 
1101    write   - write if != 0 otherwise read       */
1102
1103 static int
1104 es1800_xfer_inferior_memory (memaddr, myaddr, len, write, tops)
1105      CORE_ADDR memaddr;
1106      char *myaddr;
1107      int len;
1108      int write;
1109      struct target_ops *tops;   /* Unused */
1110 {
1111   int origlen = len;
1112   int xfersize;
1113
1114   while (len > 0)
1115     {
1116       xfersize = len > MAXBUFBYTES ? MAXBUFBYTES : len;
1117       if (write)
1118         {
1119           es1800_write_bytes (memaddr, myaddr, xfersize);
1120         }
1121       else
1122         {
1123           es1800_read_bytes (memaddr, myaddr, xfersize);
1124         }
1125       memaddr += xfersize;
1126       myaddr += xfersize;
1127       len -= xfersize;
1128     }
1129   return (origlen); /* no error possible */
1130 }
1131
1132
1133 /* Write memory data directly to the emulator.
1134    This does not inform the data cache; the data cache uses this.
1135    MEMADDR is the address in the remote memory space.
1136    MYADDR is the address of the buffer in our space.
1137    LEN is the number of bytes.
1138  
1139    memaddr - the target's address
1140    myaddr  - gdb's address
1141    len     - number of bytes   */
1142
1143 static void
1144 es1800_write_bytes (memaddr, myaddr, len)
1145      CORE_ADDR memaddr;
1146      char *myaddr;
1147      int len;
1148 {
1149   char buf[PBUFSIZ];
1150   int i;
1151   char *p;
1152
1153   p = myaddr;
1154   for (i = 0; i < len; i++)
1155     {
1156       sprintf (buf, "@.B$%x=$%x", memaddr+i, (*p++) & 0xff);
1157       send_with_reply (buf, buf, sizeof (buf));      /* FIXME send_command? */
1158     }
1159 }
1160
1161
1162 /* Read memory data directly from the emulator.
1163    This does not use the data cache; the data cache uses this.
1164  
1165    memaddr - the target's address
1166    myaddr  - gdb's address
1167    len     - number of bytes   */
1168
1169 static void
1170 es1800_read_bytes (memaddr, myaddr, len)
1171      CORE_ADDR memaddr;
1172      char *myaddr;
1173      int len;
1174 {
1175   static int DB_tab[16] = {8,11,14,17,20,23,26,29,34,37,40,43,46,49,52,55};
1176   char buf[PBUFSIZ];
1177   int i;
1178   int low_addr;
1179   char *p;
1180   char *b;
1181
1182   if (len > PBUFSIZ / 2 - 1)
1183     {
1184       abort ();
1185     }
1186
1187   if (len == 1) /* The emulator does not like expressions like:  */
1188     {
1189       len = 2;  /* DB.B $20018 TO $20018                       */
1190     }
1191
1192   /* Reply describes registers byte by byte, each byte encoded as two hex
1193      characters.  */
1194
1195   sprintf (buf, "DB.B $%x TO $%x", memaddr, memaddr+len-1);
1196   send_with_reply (buf, buf, sizeof (buf));
1197   b = buf;
1198   low_addr = memaddr&0x0f;
1199   for (i = low_addr; i < low_addr + len; i++)
1200     {
1201       if ((!(i % 16)) && i)
1202         {   /* if (i = 16,32,48)  */
1203           while (*p++!='\n') {;}
1204           b = p;
1205         }
1206       p = b + DB_tab[i%16] + (m68020 ? 2 : 0);
1207       if (p[0] == 32 || p[1] == 32)
1208         {
1209           error ("Emulator reply is too short: %s", buf);
1210         }
1211       myaddr[i-low_addr] = fromhex (p[0]) * 16 + fromhex (p[1]);
1212     }
1213 }
1214
1215 /* Information about the current target  */
1216
1217 static void
1218 es1800_files_info (tops)
1219      struct target_ops *tops;   /* Unused */
1220 {
1221   printf ("ES1800 Attached to %s at %d baud in %s mode\n", savename, 19200,
1222           MODE);
1223 }
1224
1225
1226 /* We read the contents of the target location and stash it,
1227    then overwrite it with a breakpoint instruction.
1228  
1229    addr           - is the target location in the target machine.
1230    contents_cache - is a pointer to memory allocated for saving the target contents.
1231                     It is guaranteed by the caller to be long enough to save sizeof 
1232                     BREAKPOINT bytes.
1233  
1234    FIXME: This size is target_arch dependent and should be available in
1235    the target_arch transfer vector, if we ever have one...  */
1236
1237 static int
1238 es1800_insert_breakpoint (addr, contents_cache)
1239      CORE_ADDR addr;
1240      char *contents_cache;
1241 {
1242   int val; 
1243
1244   val = target_read_memory (addr, contents_cache, sizeof (es1800_break_insn));
1245
1246   if (val == 0)
1247     {
1248       val = target_write_memory (addr, es1800_break_insn,
1249                                  sizeof (es1800_break_insn));
1250     }
1251
1252   return (val);
1253 }
1254
1255
1256 /* Write back the stashed instruction
1257  
1258    addr           - is the target location in the target machine.
1259    contents_cache - is a pointer to memory allocated for saving the target contents.
1260                     It is guaranteed by the caller to be long enough to save sizeof 
1261                     BREAKPOINT bytes.   */
1262  
1263 static int
1264 es1800_remove_breakpoint (addr, contents_cache)
1265      CORE_ADDR addr;
1266      char *contents_cache;
1267 {
1268
1269   return (target_write_memory (addr, contents_cache,
1270                                sizeof (es1800_break_insn)));
1271 }
1272
1273 /* create_break_insn ()
1274    Primitive datastructures containing the es1800 breakpoint instruction  */
1275
1276 static void
1277 es1800_create_break_insn (ins, vec)
1278      char *ins;
1279      int vec;
1280 {
1281   if (vec == 15)
1282     {
1283       ins[0] = 0x4e;
1284       ins[1] = 0x4f;
1285     }
1286 }
1287
1288
1289 /* verify_break ()
1290    Seach for breakpoint routine in emulator memory.
1291    returns non-zero on failure
1292    vec - trap vector used for breakpoints  */
1293
1294 static int
1295 verify_break (vec)
1296      int vec;
1297 {
1298   CORE_ADDR memaddress;
1299   char buf[8];
1300   char *instr = "NqNqNqNs";      /* breakpoint routine */
1301   int status;
1302
1303   get_break_addr (vec, &memaddress);
1304
1305   if (memaddress)
1306     {
1307       status = target_read_memory (memaddress, buf, 8); 
1308       if (status != 0)
1309         {
1310           memory_error (status, memaddress);
1311         }
1312       return (STRCMP (instr, buf));
1313     }
1314     return (-1);
1315 }
1316
1317
1318 /* get_break_addr ()
1319    find address of breakpint routine
1320    vec - trap vector used for breakpoints
1321    addrp - store the address here       */
1322
1323 static void
1324 get_break_addr (vec, addrp)
1325      int vec;
1326      CORE_ADDR *addrp;
1327 {
1328   CORE_ADDR memaddress = 0;
1329   int status;
1330   int k;
1331   char buf[PBUFSIZ];
1332   char base_addr[4];
1333   char *p;
1334
1335   if (m68020)
1336     {
1337       send_with_reply ("VBR ", buf, sizeof (buf));
1338       p = buf;
1339       for (k = 0; k < 4; k++)
1340         {
1341           if ((p[k*2 + 1] == 0) || (p[k*2 + 2] == 0))
1342             {
1343               error ("Emulator reply is too short: %s", buf);
1344             }
1345           base_addr[k] = (fromhex (p[k*2 + 1]) * 16) + fromhex (p[k*2 + 2]);
1346         }
1347       /* base addr of exception vector table */
1348       memaddress = *((CORE_ADDR *) base_addr);
1349     }
1350
1351     memaddress += (vec + 32) * 4;     /* address of trap vector */
1352     status = target_read_memory (memaddress, (char *) addrp, 4); 
1353     if (status != 0)                                                   
1354       {
1355         memory_error (status, memaddress);
1356       }
1357 }
1358
1359
1360 /* Kill an inferior process */
1361
1362 static void
1363 es1800_kill ()
1364 {
1365   if (inferior_pid != 0)
1366     {
1367       inferior_pid = 0;
1368       es1800_mourn_inferior ();
1369     }
1370 }
1371
1372
1373 /* Load a file to the ES1800 emulator. 
1374    Converts the file from a.out format into Extended Tekhex format
1375    before the file is loaded.
1376    Also loads the trap routine, and sets the ES1800 breakpoint on it
1377    filename - the a.out to be loaded
1378    from_tty - says whether to be verbose or not
1379    FIXME Uses emulator overlay memory for trap routine  */
1380  
1381 static void
1382 es1800_load (filename, from_tty)
1383      char *filename;
1384      int from_tty;
1385 {
1386
1387   FILE *instream;
1388   char loadname[15];
1389   char buf[160];
1390   struct cleanup *old_chain;
1391   int es1800_load_format = 5;
1392
1393   if (es1800_desc < 0) 
1394     {
1395       printf ("No emulator attached, type emulator-command first\n");
1396       return;
1397     }
1398
1399   filename = tilde_expand (filename);
1400   make_cleanup (free, filename);
1401
1402   switch (es1800_load_format)
1403     {
1404       case 2:   /* Extended Tekhex  */
1405         if (from_tty)
1406           {
1407             printf ("Converting \"%s\" to Extended Tekhex Format\n", filename);
1408           }
1409         sprintf (buf, "tekhex %s", filename);
1410         system (buf);
1411         sprintf (loadname, "out.hex");
1412         break;
1413
1414       case 5:   /* Motorola S-rec  */
1415         if (from_tty)
1416           {
1417             printf ("Converting \"%s\" to Motorola S-record format\n",
1418                     filename);
1419           }
1420         /* in the future the source code in copy (part of binutils-1.93) will
1421            be included in this file */
1422         sprintf (buf,
1423                  "copy -s \"a.out-sunos-big\" -d \"srec\" %s /tmp/out.hex",
1424                  filename);
1425         system (buf);
1426         sprintf (loadname, "/tmp/out.hex");
1427         break;
1428
1429       default:
1430         error ("Downloading format not defined\n");
1431     }
1432  
1433   breakpoint_init_inferior ();
1434   inferior_pid = 0;
1435   if (from_tty)
1436     {
1437       printf ("Downloading \"%s\" to the ES 1800\n",filename);
1438     }
1439   if ((instream = fopen (loadname, "r")) == NULL)
1440     {
1441       perror_with_name ("fopen:");
1442     }
1443
1444   old_chain = make_cleanup (fclose, instream);
1445   immediate_quit++;
1446
1447   es1800_reset (0);
1448
1449   download (instream, from_tty, es1800_load_format);
1450
1451   /* if breakpoint routine is not present anymore we have to check 
1452      whether to download a new breakpoint routine or not */
1453
1454   if ((verify_break (es1800_break_vec) != 0)
1455       && query ("No breakpoint routine in ES 1800 emulator!\nDownload a breakpoint routine to the emulator? "))
1456     {
1457       char buf[128];
1458       printf ("Using break vector 0x%x\n", es1800_break_vec);
1459       sprintf (buf, "0x%x ", es1800_break_vec);
1460       printf ("Give the start address of the breakpoint routine: ");
1461       fgets (buf + strlen (buf), sizeof (buf) - strlen (buf), stdin);
1462       es1800_init_break (buf, 0);
1463     }
1464
1465   do_cleanups (old_chain);
1466   expect_prompt ();
1467   readchar ();  /* FIXME I am getting a ^G = 7 after the prompt  */
1468   printf ("\n");
1469
1470   if (fclose (instream) == EOF)
1471     {
1472       ;
1473     }
1474
1475   if (es1800_load_format != 2)
1476     {
1477       sprintf (buf, "/usr/bin/rm %s", loadname);
1478       system (buf);
1479     }
1480
1481   symbol_file_command (filename, from_tty);   /* reading symbol table */
1482   immediate_quit--;
1483 }
1484
1485 #if 0
1486
1487 #define NUMCPYBYTES 20
1488
1489 static void
1490 bfd_copy (from_bfd, to_bfd)
1491      bfd *from_bfd;
1492      bfd *to_bfd;
1493 {
1494   asection *p, *new;
1495   int i;
1496   char buf[NUMCPYBYTES];
1497
1498   for (p = from_bfd->sections; p != NULL; p = p->next)
1499     {
1500       printf ("  Copying section %s. Size = %x.\n", p->name, p->_cooked_size);
1501       printf ("    vma = %x,  offset = %x,  output_sec = %x\n",
1502               p->vma, p->output_offset, p->output_section);
1503       new = bfd_make_section (to_bfd, p->name);
1504       if (p->_cooked_size &&
1505           !bfd_set_section_size (to_bfd, new, p->_cooked_size))
1506         {
1507           error ("Wrong BFD size!\n");
1508         }
1509       if (!bfd_set_section_flags (to_bfd, new, p->flags))
1510         {
1511           error ("bfd_set_section_flags");
1512         }
1513       new->vma = p->vma;
1514       
1515       for (i = 0; (i + NUMCPYBYTES) < p->_cooked_size ; i += NUMCPYBYTES)
1516         {
1517           if (!bfd_get_section_contents (from_bfd, p, (PTR) buf, (file_ptr) i,
1518                                         (bfd_size_type) NUMCPYBYTES))
1519             {
1520               error ("bfd_get_section_contents\n");
1521             }
1522         if (!bfd_set_section_contents (to_bfd, new, (PTR) buf, (file_ptr) i,
1523                                       (bfd_size_type) NUMCPYBYTES))
1524           {
1525             error ("bfd_set_section_contents\n");
1526           }
1527       }
1528       bfd_get_section_contents (from_bfd, p, (PTR) buf, (file_ptr) i,
1529                                 (bfd_size_type) (p->_cooked_size - i));
1530       bfd_set_section_contents (to_bfd, new, (PTR) buf,(file_ptr) i,
1531                                 (bfd_size_type) (p->_cooked_size - i));
1532     }
1533 }
1534
1535 #endif
1536
1537 /* Start an process on the es1800 and set inferior_pid to the new
1538    process' pid.
1539    execfile - the file to run
1540    args     - arguments passed to the program
1541    env      - the environment vector to pass    */
1542
1543 static void
1544 es1800_create_inferior (execfile, args, env)
1545      char *execfile;
1546      char *args;
1547      char **env;
1548 {
1549   int entry_pt;
1550   int pid;
1551 #if 0
1552   struct expression *expr;
1553   register struct cleanup *old_chain = 0;
1554   register value val;
1555 #endif
1556
1557   if (args && *args)
1558     {
1559       error ("Can't pass arguments to remote ES1800 process");
1560     }
1561
1562 #if 0
1563   if (query ("Use 'start' as entry point? "))
1564     {
1565       expr = parse_c_expression ("start");
1566       old_chain = make_cleanup (free_current_contents, &expr);
1567       val = evaluate_expression (expr);
1568       entry_pt = (val->location).address;
1569     }
1570   else
1571     {
1572       printf ("Enter the program's entry point (in hexadecimal): ");
1573       scanf ("%x", &entry_pt);
1574     }
1575 #endif
1576
1577   if (execfile == 0 || exec_bfd == 0)
1578     {
1579       error ("No exec file specified");
1580     }
1581
1582   entry_pt = (int) bfd_get_start_address (exec_bfd);
1583
1584   pid = 42;
1585
1586   /* Now that we have a child process, make it our target.  */
1587
1588   push_target (&es1800_child_ops);
1589
1590   /* The "process" (board) is already stopped awaiting our commands, and
1591      the program is already downloaded.  We just set its PC and go.  */
1592
1593   inferior_pid = pid;           /* Needed for wait_for_inferior below */
1594
1595   clear_proceed_status ();
1596
1597   /* Tell wait_for_inferior that we've started a new process.  */
1598
1599   init_wait_for_inferior ();
1600
1601   /* Set up the "saved terminal modes" of the inferior
1602      based on what modes we are starting it with.  */
1603
1604   target_terminal_init ();
1605
1606   /* Install inferior's terminal modes.  */
1607
1608   target_terminal_inferior ();
1609
1610   /* remote_start (args); */
1611   /* trap_expected = 0; */
1612   /* insert_step_breakpoint ();  FIXME, do we need this?  */
1613
1614   proceed ((CORE_ADDR) entry_pt, -1, 0);                /* Let 'er rip... */
1615
1616 }
1617
1618
1619 /* The process has died, clean up.  */
1620
1621 static void
1622 es1800_mourn_inferior ()
1623 {
1624   remove_breakpoints ();
1625   unpush_target (&es1800_child_ops);
1626   generic_mourn_inferior ();    /* Do all the proper things now */
1627 }
1628
1629 /* ES1800-protocol specific routines */
1630
1631 /* Keep discarding input from the remote system, until STRING is found. 
1632    Let the user break out immediately. 
1633    string - the string to expect
1634    nowait - break out if string not the emulator's first respond otherwise
1635             read until string is found (== 0)   */
1636  
1637 static void
1638 expect (string, nowait)
1639      char *string;
1640     int nowait;
1641 {
1642   char c;
1643   char *p = string;
1644
1645   immediate_quit++;
1646   while (1)
1647     {
1648       c = readchar ();
1649       if (isalpha (c))
1650         {
1651           c = toupper (c);
1652         }
1653       if (c == toupper (*p))
1654         {
1655           p++;
1656           if (*p == '\0')
1657             {
1658               immediate_quit--;
1659               return;
1660             }
1661         }
1662       else if (!nowait)
1663         {
1664           p = string;
1665         }
1666       else
1667         {
1668           printf ("\'%s\' expected\n" , string);
1669           printf ("char %d is %d", p - string, c);
1670           error ("\n" );
1671         }
1672     }
1673 }
1674
1675 /* Keep discarding input until we see the prompt.  */
1676
1677 static void
1678 expect_prompt ()
1679 {
1680   expect (">", 0);
1681 }
1682
1683
1684 /* Read one character */
1685
1686 #ifdef DEBUG_STDIN
1687
1688 /* read from stdin */
1689
1690 static int
1691 readchar ()
1692 {
1693   char buf[1];
1694
1695   buf[0] = '\0';
1696   printf ("readchar, give one character\n");
1697   read (0, buf, 1);
1698
1699 #if defined (LOG_FILE)
1700   putc (buf[0] & 0x7f, log_file);
1701 #endif
1702
1703   return (buf[0] & 0x7f);
1704 }
1705
1706 #else   /* !DEBUG_STDIN */
1707
1708 /* Read a character from the remote system, doing all the fancy
1709    timeout stuff.  */
1710
1711 static int
1712 readchar ()
1713 {
1714   char buf[1];
1715
1716   buf[0] = '\0';
1717
1718 #ifdef HAVE_TERMIO
1719
1720   /* termio does the timeout for us.  */
1721   read (es1800_desc, buf, 1);
1722
1723 #else
1724
1725   alarm (timeout);
1726   while (read (es1800_desc, buf, 1) != 1)
1727     {
1728       if (errno == EINTR)
1729         {
1730           error ("Timeout reading from remote system.");
1731         }
1732       else if (errno != EWOULDBLOCK)
1733         {
1734           perror_with_name ("remote read");
1735         }
1736     }
1737   alarm (0);
1738 #endif
1739
1740 #if defined (LOG_FILE)
1741   putc (buf[0] & 0x7f, log_file);
1742   fflush (log_file);
1743 #endif
1744
1745   return (buf[0] & 0x7f);
1746 }
1747
1748 #endif  /* DEBUG_STDIN */
1749
1750
1751 /* Send a command to the emulator and save the reply.
1752    Report an error if we get an error reply.
1753    string - the es1800 command
1754    buf    - containing the emulator reply on return
1755    len    - size of buf  */
1756
1757 static void
1758 send_with_reply (string, buf, len)
1759     char *string, *buf;
1760     int len;
1761 {
1762   send (string);
1763   write (es1800_desc, "\r", 1);
1764
1765 #ifndef DEBUG_STDIN
1766   expect (string, 1);
1767   expect ("\r\n", 0);
1768 #endif
1769
1770   getmessage (buf, len);
1771 }
1772
1773
1774 /* Send the command in STR to the emulator adding \r. check
1775    the echo for consistency. 
1776    string - the es1800 command  */
1777  
1778 static void
1779 send_command (string)
1780      char *string;
1781 {
1782   send (string);
1783   write (es1800_desc, "\r", 1);
1784
1785 #ifndef DEBUG_STDIN
1786   expect (string, 0);
1787   expect_prompt ();
1788 #endif
1789
1790 }
1791
1792 /* Send a string
1793    string - the es1800 command  */
1794
1795 static void
1796 send (string)
1797      char *string;
1798 {
1799   if (kiodebug) 
1800     {
1801       fprintf (stderr, "Sending: %s\n", string);
1802     }
1803   write (es1800_desc, string, strlen (string));
1804 }
1805
1806
1807 /* Read a message from the emulator and store it in BUF. 
1808    buf    - containing the emulator reply on return
1809    len    - size of buf  */
1810  
1811 static void
1812 getmessage (buf, len)
1813      char *buf;
1814      int len;
1815 {
1816   char *bp;
1817   int c;
1818   int prompt_found = 0;
1819   extern kiodebug;
1820
1821 #if defined (LOG_FILE)
1822   /* This is a convenient place to do this.  The idea is to do it often
1823      enough that we never lose much data if we terminate abnormally.  */
1824   fflush (log_file);
1825 #endif
1826
1827   bp = buf;
1828   c = readchar ();
1829   do
1830     {
1831       if (c) 
1832         {
1833           if (len-- < 2) /* char and terminaling NULL */
1834             {
1835               error ("input buffer overrun\n");
1836             }
1837           *bp++ = c;
1838         }
1839       c = readchar ();
1840       if ((c == '>') && (*(bp - 1) == ' '))
1841         {
1842           prompt_found = 1;
1843         }
1844     }
1845   while (!prompt_found);
1846   *bp = 0;
1847   
1848   if (kiodebug)
1849     {
1850       fprintf (stderr,"message received :%s\n", buf);
1851     }
1852 }
1853
1854 static void
1855 download (instream, from_tty, format)
1856 FILE *instream;
1857      int from_tty;
1858      int format;
1859 {
1860   char c;
1861   char buf[160];
1862   int i = 0;
1863
1864   send_command ("SET #2,$1A");                  /* reset char = ^Z */
1865   send_command ("SET #3,$11,$13");              /* XON  XOFF */
1866   if (format == 2)
1867     {
1868       send_command ("SET #26,#2");
1869     }
1870   else
1871     {
1872       send_command ("SET #26,#5");              /* Format=Extended Tekhex */
1873     }
1874   send_command ("DFB = $10");
1875   send_command ("PUR");
1876   send_command ("CES");
1877   send ("DNL\r");
1878   expect ("DNL", 1);
1879   if (from_tty)
1880     {
1881       printf ("    0 records loaded...\r");
1882     }
1883   while (fgets (buf, 160, instream))
1884       {
1885         send (buf);
1886         if (from_tty)
1887           {
1888             printf ("%5d\b\b\b\b\b",++i);
1889             fflush (stdout);
1890           }
1891         if ((c = readchar ()) != 006) 
1892           {
1893             error ("expected ACK");
1894           }
1895       }
1896   if (from_tty)
1897     {
1898       printf ("- All");
1899     }
1900 }
1901
1902 /* Additional commands */
1903
1904 /* Talk directly to the emulator
1905    FIXME, uses busy wait, and is SUNOS (or at least BSD) specific  */
1906
1907 /*ARGSUSED*/
1908 static void 
1909 es1800_transparent (args, from_tty)
1910      char *args;
1911      int from_tty;
1912 {
1913   int console;
1914   struct sgttyb modebl;
1915   int fcflag;
1916   int cc;
1917   struct sgttyb console_mode_save;
1918   int console_fc_save;
1919   int es1800_fc_save;
1920   int inputcnt = 80;
1921   char inputbuf[80];
1922   int consolecnt = 0;
1923   char consolebuf[80];
1924   int es1800_cnt = 0;
1925   char es1800_buf[80];
1926   int i;
1927
1928   dont_repeat ();
1929   if (es1800_desc < 0) 
1930     {
1931       printf ("No emulator attached, type emulator-command first\n");
1932       return;
1933     }
1934
1935   printf ("\n");
1936   printf ("You are now communicating directly with the ES 1800 emulator.\n");
1937   printf ("To leave this mode (transparent mode), press ^E.\n");
1938   printf ("\n");
1939   printf (" >");
1940   fflush (stdout);
1941
1942   if ((console = open ("/dev/tty", O_RDWR)) == -1) 
1943     {
1944       perror_with_name ("/dev/tty:");
1945     }
1946
1947   if ((fcflag = fcntl (console, F_GETFL, 0)) == -1)
1948     {
1949       perror_with_name ("fcntl console");
1950     }
1951
1952   console_fc_save = fcflag;
1953   fcflag = fcflag | FNDELAY;
1954
1955   if (fcntl (console, F_SETFL, fcflag) == -1)
1956     {
1957       perror_with_name ("fcntl console");
1958     }
1959
1960   if (ioctl (console, TIOCGETP, &modebl))
1961     {
1962       perror_with_name ("ioctl console");
1963     }
1964
1965   console_mode_save = modebl;
1966   modebl.sg_flags = RAW; 
1967
1968   if (ioctl (console, TIOCSETP, &modebl))
1969     {
1970       perror_with_name ("ioctl console");
1971     }
1972
1973   if ((fcflag = fcntl (es1800_desc, F_GETFL, 0)) == -1)
1974     {
1975       perror_with_name ("fcntl serial");
1976     }
1977
1978   es1800_fc_save = fcflag;
1979   fcflag = fcflag | FNDELAY;
1980
1981   if (fcntl (es1800_desc, F_SETFL, fcflag) == -1)
1982     {
1983       perror_with_name ("fcntl serial");
1984     }
1985
1986   while (1)
1987     { 
1988       cc = read (console, inputbuf, inputcnt);
1989       if (cc != -1)
1990         {
1991           if ((*inputbuf & 0x7f) == 0x05)
1992             {
1993               break;
1994             }
1995           for (i = 0; i < cc; )
1996             {
1997               es1800_buf[es1800_cnt++] = inputbuf[i++];
1998             }
1999           if ((cc = write (es1800_desc, es1800_buf, es1800_cnt)) == -1)
2000             {
2001               perror_with_name ("FEL! read:");
2002             }
2003           es1800_cnt -= cc;
2004           if (es1800_cnt && cc) 
2005             {
2006               for (i = 0; i < es1800_cnt; i++)
2007                 {
2008                   es1800_buf[i] = es1800_buf[cc+i];
2009                 }
2010             }
2011         }
2012       else if (errno != EWOULDBLOCK)
2013         {
2014           perror_with_name ("FEL! read:");
2015         }
2016       
2017       cc = read (es1800_desc,inputbuf,inputcnt);
2018       if (cc != -1)
2019         {
2020           for (i = 0; i < cc; )
2021             {
2022               consolebuf[consolecnt++] = inputbuf[i++];
2023             }
2024           if ((cc = write (console,consolebuf,consolecnt)) == -1)
2025             {
2026               perror_with_name ("FEL! write:");
2027             }
2028           consolecnt -= cc;
2029           if (consolecnt && cc) 
2030             {
2031               for (i = 0; i < consolecnt; i++)
2032                 {
2033                   consolebuf[i] = consolebuf[cc+i];
2034                 }
2035             }
2036         }
2037       else if (errno != EWOULDBLOCK)
2038         {
2039           perror_with_name ("FEL! read:");
2040         }
2041     }
2042
2043   console_fc_save = console_fc_save & !FNDELAY;
2044   if (fcntl (console, F_SETFL, console_fc_save) == -1)
2045     {
2046       perror_with_name ("FEL! fcntl");
2047     }
2048
2049   if (ioctl (console, TIOCSETP, &console_mode_save))
2050     {
2051       perror_with_name ("FEL! ioctl");
2052     }
2053
2054   close (console);
2055
2056   if (fcntl (es1800_desc, F_SETFL, es1800_fc_save) == -1)
2057     {
2058       perror_with_name ("FEL! fcntl");
2059     }
2060
2061   printf ("\n");
2062
2063 }
2064
2065 static void
2066 es1800_init_break (args, from_tty)
2067      char *args;
2068      int from_tty;
2069 {
2070   CORE_ADDR memaddress = 0;
2071   char buf[PBUFSIZ];
2072   char base_addr[4];
2073   char *space_index;
2074   char *p;
2075   int k;
2076
2077   if (args == NULL)
2078     {
2079       error_no_arg ("a trap vector");
2080     }
2081
2082   if (!(space_index = strchr (args, ' ')))
2083     {
2084       error ("Two arguments needed (trap vector and address of break routine).\n");
2085     }
2086
2087   *space_index = '\0';
2088
2089   es1800_break_vec = strtol (args, (char **) NULL, 0);
2090   es1800_break_address = parse_and_eval_address (space_index + 1);
2091
2092   es1800_create_break_insn (es1800_break_insn, es1800_break_vec);
2093
2094   if (m68020)
2095     {
2096       send_with_reply ("VBR ", buf, sizeof (buf));
2097       p = buf;
2098       for (k = 0; k < 4; k++)
2099         {
2100           if ((p[k*2 + 1] == 0) || (p[k*2 + 2] == 0))
2101             {
2102               error ("Emulator reply is too short: %s", buf);
2103             }
2104           base_addr[k] = (fromhex (p[k*2 + 1]) * 16) + fromhex (p[k*2 + 2]);
2105         }
2106       /* base addr of exception vector table */
2107       memaddress =  *((CORE_ADDR *) base_addr);
2108     }
2109
2110   memaddress += (es1800_break_vec + 32) * 4;     /* address of trap vector */
2111
2112   sprintf (buf, "@.L%lx=$%lx", memaddress, es1800_break_address);
2113   send_command (buf);   /* set the address of the break routine in the */
2114                        /* trap vector */
2115   
2116   sprintf (buf, "@.L%lx=$4E714E71", es1800_break_address);      /* NOP; NOP */
2117   send_command (buf);
2118   sprintf (buf, "@.L%lx=$4E714E73", es1800_break_address + 4);  /* NOP; RTE */
2119   send_command (buf);
2120   
2121   sprintf (buf, "AC2=$%lx", es1800_break_address + 4);
2122   /* breakpoint at es1800-break_address */
2123   send_command (buf);
2124   send_command ("WHEN AC2 THEN BRK");          /* ie in exception routine */
2125
2126   if (from_tty)
2127     {
2128       printf ("Breakpoint (trap $%x) routine at address: %lx\n",
2129               es1800_break_vec, es1800_break_address);
2130     }
2131 }         
2132
2133 static void
2134 es1800_child_open (arg, from_tty)
2135      char *arg;
2136      int from_tty;
2137 {
2138   error ("Use the \"run\" command to start a child process.");
2139 }
2140
2141 static void
2142 es1800_child_detach (args, from_tty)
2143      char *args;
2144      int from_tty;
2145 {
2146   if (args)
2147     {
2148       error ("Argument given to \"detach\" when remotely debugging.");
2149     }
2150   
2151   pop_target ();
2152   if (from_tty)
2153     {
2154       printf ("Ending debugging the process %d.\n", inferior_pid);
2155     }
2156 }
2157
2158
2159 /* Define the target subroutine names  */
2160
2161 static struct target_ops es1800_ops =
2162 {
2163   "es1800",                     /* to_shortname */
2164                                 /* to_longname */
2165   "Remote serial target in ES1800-emulator protocol",
2166                                 /* to_doc */
2167   "Remote debugging on the es1800 emulator via a serial line.\n\
2168 Specify the serial device it is connected to (e.g. /dev/ttya).",
2169   es1800_open,                  /* to_open */
2170   es1800_close,                 /* to_close */
2171   es1800_attach,                /* to_attach */
2172   es1800_detach,                /* to_detach */
2173   es1800_resume,                /* to_resume */
2174   NULL,                         /* to_wait */
2175   NULL,                         /* to_fetch_registers */
2176   NULL,                         /* to_store_registers */
2177   es1800_prepare_to_store,      /* to_prepare_to_store */
2178   es1800_xfer_inferior_memory,  /* to_xfer_memory */
2179   es1800_files_info,            /* to_files_info */
2180   es1800_insert_breakpoint,     /* to_insert_breakpoint */
2181   es1800_remove_breakpoint,     /* to_remove_breakpoint */
2182   NULL,                         /* to_terminal_init */
2183   NULL,                         /* to_terminal_inferior */
2184   NULL,                         /* to_terminal_ours_for_output */
2185   NULL,                         /* to_terminal_ours */
2186   NULL,                         /* to_terminal_info */
2187   NULL,                         /* to_kill */
2188   es1800_load,                  /* to_load */
2189   NULL,                         /* to_lookup_symbol */
2190   es1800_create_inferior,       /* to_create_inferior */
2191   NULL,                         /* to_mourn_inferior */
2192   0,                            /* to_can_run */
2193   0,                            /* notice_signals */
2194   core_stratum,                 /* to_stratum */
2195   0,                            /* to_next */
2196   0,                            /* to_has_all_memory */
2197   1,                            /* to_has_memory */
2198   0,                            /* to_has_stack */
2199   0,                            /* to_has_registers */
2200   0,                            /* to_has_execution */
2201   NULL,                         /* to_sections */
2202   NULL,                         /* to_sections_end */
2203   OPS_MAGIC                     /* to_magic (always last) */
2204 };
2205
2206 /* Define the target subroutine names  */
2207
2208 static struct target_ops es1800_child_ops =
2209 {
2210   "es1800_process",             /* to_shortname */
2211                                 /* to_longname */
2212   "Remote serial target in ES1800-emulator protocol",
2213                                 /* to_doc */
2214   "Remote debugging on the es1800 emulator via a serial line.\n\
2215 Specify the serial device it is connected to (e.g. /dev/ttya).",
2216   es1800_child_open,            /* to_open */
2217   NULL,                         /* to_close */
2218   es1800_attach,                /* to_attach */
2219   es1800_child_detach,          /* to_detach */
2220   es1800_resume,                /* to_resume */
2221   es1800_wait,                  /* to_wait */
2222   es1800_fetch_register,        /* to_fetch_registers */
2223   es1800_store_register,        /* to_store_registers */
2224   es1800_prepare_to_store,      /* to_prepare_to_store */
2225   es1800_xfer_inferior_memory,  /* to_xfer_memory */
2226   es1800_files_info,            /* to_files_info */
2227   es1800_insert_breakpoint,     /* to_insert_breakpoint */
2228   es1800_remove_breakpoint,     /* to_remove_breakpoint */
2229   NULL,                         /* to_terminal_init */
2230   NULL,                         /* to_terminal_inferior */
2231   NULL,                         /* to_terminal_ours_for_output */
2232   NULL,                         /* to_terminal_ours */
2233   NULL,                         /* to_terminal_info */
2234   es1800_kill,                  /* to_kill */
2235   es1800_load,                  /* to_load */
2236   NULL,                         /* to_lookup_symbol */
2237   es1800_create_inferior,       /* to_create_inferior */
2238   es1800_mourn_inferior,        /* to_mourn_inferior */
2239   0,                            /* to_can_run */
2240   0,                            /* notice_signals */
2241   process_stratum,              /* to_stratum */
2242   0,                            /* to_next */
2243   1,                            /* to_has_all_memory */
2244   1,                            /* to_has_memory */
2245   1,                            /* to_has_stack */
2246   1,                            /* to_has_registers */
2247   1,                            /* to_has_execution */
2248   NULL,                         /* to_sections */
2249   NULL,                         /* to_sections_end */
2250   OPS_MAGIC                     /* to_magic (always last) */
2251 };
2252
2253 /* _initialize_es1800 ()  */
2254
2255 void
2256 _initialize_es1800 ()
2257 {
2258   add_target (&es1800_ops);
2259   add_target (&es1800_child_ops);
2260   add_com ("transparent", class_support, es1800_transparent,
2261            "Start transparent communication with the ES 1800 emulator.");
2262   add_com ("init_break", class_support, es1800_init_break,
2263            "Download break routine and initialize break facility on ES 1800");
2264 }