xref: /openbsd/gnu/usr.bin/binutils/gdb/i386-stub.c (revision 78b63d65)
1 /****************************************************************************
2 
3 		THIS SOFTWARE IS NOT COPYRIGHTED
4 
5    HP offers the following for use in the public domain.  HP makes no
6    warranty with regard to the software or it's performance and the
7    user accepts the software "AS IS" with all faults.
8 
9    HP DISCLAIMS ANY WARRANTIES, EXPRESS OR IMPLIED, WITH REGARD
10    TO THIS SOFTWARE INCLUDING BUT NOT LIMITED TO THE WARRANTIES
11    OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
12 
13 ****************************************************************************/
14 
15 /****************************************************************************
16  *  Header: remcom.c,v 1.34 91/03/09 12:29:49 glenne Exp $
17  *
18  *  Module name: remcom.c $
19  *  Revision: 1.34 $
20  *  Date: 91/03/09 12:29:49 $
21  *  Contributor:     Lake Stevens Instrument Division$
22  *
23  *  Description:     low level support for gdb debugger. $
24  *
25  *  Considerations:  only works on target hardware $
26  *
27  *  Written by:      Glenn Engel $
28  *  ModuleState:     Experimental $
29  *
30  *  NOTES:           See Below $
31  *
32  *  Modified for 386 by Jim Kingdon, Cygnus Support.
33  *
34  *  To enable debugger support, two things need to happen.  One, a
35  *  call to set_debug_traps() is necessary in order to allow any breakpoints
36  *  or error conditions to be properly intercepted and reported to gdb.
37  *  Two, a breakpoint needs to be generated to begin communication.  This
38  *  is most easily accomplished by a call to breakpoint().  Breakpoint()
39  *  simulates a breakpoint by executing a trap #1.
40  *
41  *  The external function exceptionHandler() is
42  *  used to attach a specific handler to a specific 386 vector number.
43  *  It should use the same privilege level it runs at.  It should
44  *  install it as an interrupt gate so that interrupts are masked
45  *  while the handler runs.
46  *  Also, need to assign exceptionHook and oldExceptionHook.
47  *
48  *  Because gdb will sometimes write to the stack area to execute function
49  *  calls, this program cannot rely on using the supervisor stack so it
50  *  uses it's own stack area reserved in the int array remcomStack.
51  *
52  *************
53  *
54  *    The following gdb commands are supported:
55  *
56  * command          function                               Return value
57  *
58  *    g             return the value of the CPU registers  hex data or ENN
59  *    G             set the value of the CPU registers     OK or ENN
60  *
61  *    mAA..AA,LLLL  Read LLLL bytes at address AA..AA      hex data or ENN
62  *    MAA..AA,LLLL: Write LLLL bytes at address AA.AA      OK or ENN
63  *
64  *    c             Resume at current address              SNN   ( signal NN)
65  *    cAA..AA       Continue at address AA..AA             SNN
66  *
67  *    s             Step one instruction                   SNN
68  *    sAA..AA       Step one instruction from AA..AA       SNN
69  *
70  *    k             kill
71  *
72  *    ?             What was the last sigval ?             SNN   (signal NN)
73  *
74  * All commands and responses are sent with a packet which includes a
75  * checksum.  A packet consists of
76  *
77  * $<packet info>#<checksum>.
78  *
79  * where
80  * <packet info> :: <characters representing the command or response>
81  * <checksum>    :: < two hex digits computed as modulo 256 sum of <packetinfo>>
82  *
83  * When a packet is received, it is first acknowledged with either '+' or '-'.
84  * '+' indicates a successful transfer.  '-' indicates a failed transfer.
85  *
86  * Example:
87  *
88  * Host:                  Reply:
89  * $m0,10#2a               +$00010203040506070809101112131415#42
90  *
91  ****************************************************************************/
92 
93 #include <stdio.h>
94 #include <string.h>
95 
96 /************************************************************************
97  *
98  * external low-level support routines
99  */
100 typedef void (*ExceptionHook)(int);   /* pointer to function with int parm */
101 typedef void (*Function)();           /* pointer to a function */
102 
103 extern putDebugChar();   /* write a single character      */
104 extern getDebugChar();   /* read and return a single char */
105 
106 extern Function exceptionHandler();  /* assign an exception handler */
107 extern ExceptionHook exceptionHook;  /* hook variable for errors/exceptions */
108 
109 /************************************************************************/
110 /* BUFMAX defines the maximum number of characters in inbound/outbound buffers*/
111 /* at least NUMREGBYTES*2 are needed for register packets */
112 #define BUFMAX 400
113 
114 static char initialized;  /* boolean flag. != 0 means we've been initialized */
115 
116 int     remote_debug;
117 /*  debug >  0 prints ill-formed commands in valid packets & checksum errors */
118 
119 void waitabit();
120 
121 static const char hexchars[]="0123456789abcdef";
122 
123 /* Number of bytes of registers.  */
124 #define NUMREGBYTES 64
125 enum regnames {EAX, ECX, EDX, EBX, ESP, EBP, ESI, EDI,
126 	       PC /* also known as eip */,
127 	       PS /* also known as eflags */,
128 	       CS, SS, DS, ES, FS, GS};
129 
130 /*
131  * these should not be static cuz they can be used outside this module
132  */
133 int registers[NUMREGBYTES/4];
134 
135 #define STACKSIZE 10000
136 int remcomStack[STACKSIZE/sizeof(int)];
137 static int* stackPtr = &remcomStack[STACKSIZE/sizeof(int) - 1];
138 
139 /*
140  * In many cases, the system will want to continue exception processing
141  * when a continue command is given.
142  * oldExceptionHook is a function to invoke in this case.
143  */
144 
145 static ExceptionHook oldExceptionHook;
146 
147 /***************************  ASSEMBLY CODE MACROS *************************/
148 /* 									   */
149 
150 extern void
151 return_to_prog ();
152 
153 /* Restore the program's registers (including the stack pointer, which
154    means we get the right stack and don't have to worry about popping our
155    return address and any stack frames and so on) and return.  */
156 asm(".text");
157 asm(".globl _return_to_prog");
158 asm("_return_to_prog:");
159 asm("        movw _registers+44, %ss");
160 asm("        movl _registers+16, %esp");
161 asm("        movl _registers+4, %ecx");
162 asm("        movl _registers+8, %edx");
163 asm("        movl _registers+12, %ebx");
164 asm("        movl _registers+20, %ebp");
165 asm("        movl _registers+24, %esi");
166 asm("        movl _registers+28, %edi");
167 asm("        movw _registers+48, %ds");
168 asm("        movw _registers+52, %es");
169 asm("        movw _registers+56, %fs");
170 asm("        movw _registers+60, %gs");
171 asm("        movl _registers+36, %eax");
172 asm("        pushl %eax");  /* saved eflags */
173 asm("        movl _registers+40, %eax");
174 asm("        pushl %eax");  /* saved cs */
175 asm("        movl _registers+32, %eax");
176 asm("        pushl %eax");  /* saved eip */
177 asm("        movl _registers, %eax");
178 /* use iret to restore pc and flags together so
179    that trace flag works right.  */
180 asm("        iret");
181 
182 #define BREAKPOINT() asm("   int $3");
183 
184 /* Put the error code here just in case the user cares.  */
185 int gdb_i386errcode;
186 /* Likewise, the vector number here (since GDB only gets the signal
187    number through the usual means, and that's not very specific).  */
188 int gdb_i386vector = -1;
189 
190 /* GDB stores segment registers in 32-bit words (that's just the way
191    m-i386v.h is written).  So zero the appropriate areas in registers.  */
192 #define SAVE_REGISTERS1() \
193   asm ("movl %eax, _registers");                                   	  \
194   asm ("movl %ecx, _registers+4");			  		     \
195   asm ("movl %edx, _registers+8");			  		     \
196   asm ("movl %ebx, _registers+12");			  		     \
197   asm ("movl %ebp, _registers+20");			  		     \
198   asm ("movl %esi, _registers+24");			  		     \
199   asm ("movl %edi, _registers+28");			  		     \
200   asm ("movw $0, %ax");							     \
201   asm ("movw %ds, _registers+48");			  		     \
202   asm ("movw %ax, _registers+50");					     \
203   asm ("movw %es, _registers+52");			  		     \
204   asm ("movw %ax, _registers+54");					     \
205   asm ("movw %fs, _registers+56");			  		     \
206   asm ("movw %ax, _registers+58");					     \
207   asm ("movw %gs, _registers+60");			  		     \
208   asm ("movw %ax, _registers+62");
209 #define SAVE_ERRCODE() \
210   asm ("popl %ebx");                                  \
211   asm ("movl %ebx, _gdb_i386errcode");
212 #define SAVE_REGISTERS2() \
213   asm ("popl %ebx"); /* old eip */			  		     \
214   asm ("movl %ebx, _registers+32");			  		     \
215   asm ("popl %ebx");	 /* old cs */			  		     \
216   asm ("movl %ebx, _registers+40");			  		     \
217   asm ("movw %ax, _registers+42");                                           \
218   asm ("popl %ebx");	 /* old eflags */		  		     \
219   asm ("movl %ebx, _registers+36");			 		     \
220   /* Now that we've done the pops, we can save the stack pointer.");  */   \
221   asm ("movw %ss, _registers+44");					     \
222   asm ("movw %ax, _registers+46");     	       	       	       	       	     \
223   asm ("movl %esp, _registers+16");
224 
225 /* See if mem_fault_routine is set, if so just IRET to that address.  */
226 #define CHECK_FAULT() \
227   asm ("cmpl $0, _mem_fault_routine");					   \
228   asm ("jne mem_fault");
229 
230 asm (".text");
231 asm ("mem_fault:");
232 /* OK to clobber temp registers; we're just going to end up in set_mem_err.  */
233 /* Pop error code from the stack and save it.  */
234 asm ("     popl %eax");
235 asm ("     movl %eax, _gdb_i386errcode");
236 
237 asm ("     popl %eax"); /* eip */
238 /* We don't want to return there, we want to return to the function
239    pointed to by mem_fault_routine instead.  */
240 asm ("     movl _mem_fault_routine, %eax");
241 asm ("     popl %ecx"); /* cs (low 16 bits; junk in hi 16 bits).  */
242 asm ("     popl %edx"); /* eflags */
243 
244 /* Remove this stack frame; when we do the iret, we will be going to
245    the start of a function, so we want the stack to look just like it
246    would after a "call" instruction.  */
247 asm ("     leave");
248 
249 /* Push the stuff that iret wants.  */
250 asm ("     pushl %edx"); /* eflags */
251 asm ("     pushl %ecx"); /* cs */
252 asm ("     pushl %eax"); /* eip */
253 
254 /* Zero mem_fault_routine.  */
255 asm ("     movl $0, %eax");
256 asm ("     movl %eax, _mem_fault_routine");
257 
258 asm ("iret");
259 
260 #define CALL_HOOK() asm("call _remcomHandler");
261 
262 /* This function is called when a i386 exception occurs.  It saves
263  * all the cpu regs in the _registers array, munges the stack a bit,
264  * and invokes an exception handler (remcom_handler).
265  *
266  * stack on entry:                       stack on exit:
267  *   old eflags                          vector number
268  *   old cs (zero-filled to 32 bits)
269  *   old eip
270  *
271  */
272 extern void _catchException3();
273 asm(".text");
274 asm(".globl __catchException3");
275 asm("__catchException3:");
276 SAVE_REGISTERS1();
277 SAVE_REGISTERS2();
278 asm ("pushl $3");
279 CALL_HOOK();
280 
281 /* Same thing for exception 1.  */
282 extern void _catchException1();
283 asm(".text");
284 asm(".globl __catchException1");
285 asm("__catchException1:");
286 SAVE_REGISTERS1();
287 SAVE_REGISTERS2();
288 asm ("pushl $1");
289 CALL_HOOK();
290 
291 /* Same thing for exception 0.  */
292 extern void _catchException0();
293 asm(".text");
294 asm(".globl __catchException0");
295 asm("__catchException0:");
296 SAVE_REGISTERS1();
297 SAVE_REGISTERS2();
298 asm ("pushl $0");
299 CALL_HOOK();
300 
301 /* Same thing for exception 4.  */
302 extern void _catchException4();
303 asm(".text");
304 asm(".globl __catchException4");
305 asm("__catchException4:");
306 SAVE_REGISTERS1();
307 SAVE_REGISTERS2();
308 asm ("pushl $4");
309 CALL_HOOK();
310 
311 /* Same thing for exception 5.  */
312 extern void _catchException5();
313 asm(".text");
314 asm(".globl __catchException5");
315 asm("__catchException5:");
316 SAVE_REGISTERS1();
317 SAVE_REGISTERS2();
318 asm ("pushl $5");
319 CALL_HOOK();
320 
321 /* Same thing for exception 6.  */
322 extern void _catchException6();
323 asm(".text");
324 asm(".globl __catchException6");
325 asm("__catchException6:");
326 SAVE_REGISTERS1();
327 SAVE_REGISTERS2();
328 asm ("pushl $6");
329 CALL_HOOK();
330 
331 /* Same thing for exception 7.  */
332 extern void _catchException7();
333 asm(".text");
334 asm(".globl __catchException7");
335 asm("__catchException7:");
336 SAVE_REGISTERS1();
337 SAVE_REGISTERS2();
338 asm ("pushl $7");
339 CALL_HOOK();
340 
341 /* Same thing for exception 8.  */
342 extern void _catchException8();
343 asm(".text");
344 asm(".globl __catchException8");
345 asm("__catchException8:");
346 SAVE_REGISTERS1();
347 SAVE_ERRCODE();
348 SAVE_REGISTERS2();
349 asm ("pushl $8");
350 CALL_HOOK();
351 
352 /* Same thing for exception 9.  */
353 extern void _catchException9();
354 asm(".text");
355 asm(".globl __catchException9");
356 asm("__catchException9:");
357 SAVE_REGISTERS1();
358 SAVE_REGISTERS2();
359 asm ("pushl $9");
360 CALL_HOOK();
361 
362 /* Same thing for exception 10.  */
363 extern void _catchException10();
364 asm(".text");
365 asm(".globl __catchException10");
366 asm("__catchException10:");
367 SAVE_REGISTERS1();
368 SAVE_ERRCODE();
369 SAVE_REGISTERS2();
370 asm ("pushl $10");
371 CALL_HOOK();
372 
373 /* Same thing for exception 12.  */
374 extern void _catchException12();
375 asm(".text");
376 asm(".globl __catchException12");
377 asm("__catchException12:");
378 SAVE_REGISTERS1();
379 SAVE_ERRCODE();
380 SAVE_REGISTERS2();
381 asm ("pushl $12");
382 CALL_HOOK();
383 
384 /* Same thing for exception 16.  */
385 extern void _catchException16();
386 asm(".text");
387 asm(".globl __catchException16");
388 asm("__catchException16:");
389 SAVE_REGISTERS1();
390 SAVE_REGISTERS2();
391 asm ("pushl $16");
392 CALL_HOOK();
393 
394 /* For 13, 11, and 14 we have to deal with the CHECK_FAULT stuff.  */
395 
396 /* Same thing for exception 13.  */
397 extern void _catchException13 ();
398 asm (".text");
399 asm (".globl __catchException13");
400 asm ("__catchException13:");
401 CHECK_FAULT();
402 SAVE_REGISTERS1();
403 SAVE_ERRCODE();
404 SAVE_REGISTERS2();
405 asm ("pushl $13");
406 CALL_HOOK();
407 
408 /* Same thing for exception 11.  */
409 extern void _catchException11 ();
410 asm (".text");
411 asm (".globl __catchException11");
412 asm ("__catchException11:");
413 CHECK_FAULT();
414 SAVE_REGISTERS1();
415 SAVE_ERRCODE();
416 SAVE_REGISTERS2();
417 asm ("pushl $11");
418 CALL_HOOK();
419 
420 /* Same thing for exception 14.  */
421 extern void _catchException14 ();
422 asm (".text");
423 asm (".globl __catchException14");
424 asm ("__catchException14:");
425 CHECK_FAULT();
426 SAVE_REGISTERS1();
427 SAVE_ERRCODE();
428 SAVE_REGISTERS2();
429 asm ("pushl $14");
430 CALL_HOOK();
431 
432 /*
433  * remcomHandler is a front end for handle_exception.  It moves the
434  * stack pointer into an area reserved for debugger use.
435  */
436 asm("_remcomHandler:");
437 asm("           popl %eax");        /* pop off return address     */
438 asm("           popl %eax");      /* get the exception number   */
439 asm("		movl _stackPtr, %esp"); /* move to remcom stack area  */
440 asm("		pushl %eax");	/* push exception onto stack  */
441 asm("		call  _handle_exception");    /* this never returns */
442 
443 void _returnFromException()
444 {
445   return_to_prog ();
446 }
447 
448 int hex(ch)
449 char ch;
450 {
451   if ((ch >= 'a') && (ch <= 'f')) return (ch-'a'+10);
452   if ((ch >= '0') && (ch <= '9')) return (ch-'0');
453   if ((ch >= 'A') && (ch <= 'F')) return (ch-'A'+10);
454   return (-1);
455 }
456 
457 
458 /* scan for the sequence $<data>#<checksum>     */
459 void getpacket(buffer)
460 char * buffer;
461 {
462   unsigned char checksum;
463   unsigned char xmitcsum;
464   int  i;
465   int  count;
466   char ch;
467 
468   do {
469     /* wait around for the start character, ignore all other characters */
470     while ((ch = (getDebugChar() & 0x7f)) != '$');
471     checksum = 0;
472     xmitcsum = -1;
473 
474     count = 0;
475 
476     /* now, read until a # or end of buffer is found */
477     while (count < BUFMAX) {
478       ch = getDebugChar() & 0x7f;
479       if (ch == '#') break;
480       checksum = checksum + ch;
481       buffer[count] = ch;
482       count = count + 1;
483       }
484     buffer[count] = 0;
485 
486     if (ch == '#') {
487       xmitcsum = hex(getDebugChar() & 0x7f) << 4;
488       xmitcsum += hex(getDebugChar() & 0x7f);
489       if ((remote_debug ) && (checksum != xmitcsum)) {
490         fprintf (stderr ,"bad checksum.  My count = 0x%x, sent=0x%x. buf=%s\n",
491 		 checksum,xmitcsum,buffer);
492       }
493 
494       if (checksum != xmitcsum) putDebugChar('-');  /* failed checksum */
495       else {
496 	 putDebugChar('+');  /* successful transfer */
497 	 /* if a sequence char is present, reply the sequence ID */
498 	 if (buffer[2] == ':') {
499 	    putDebugChar( buffer[0] );
500 	    putDebugChar( buffer[1] );
501 	    /* remove sequence chars from buffer */
502 	    count = strlen(buffer);
503 	    for (i=3; i <= count; i++) buffer[i-3] = buffer[i];
504 	 }
505       }
506     }
507   } while (checksum != xmitcsum);
508 
509 }
510 
511 /* send the packet in buffer.  */
512 
513 
514 void putpacket(buffer)
515 char * buffer;
516 {
517   unsigned char checksum;
518   int  count;
519   char ch;
520 
521   /*  $<packet info>#<checksum>. */
522   do {
523   putDebugChar('$');
524   checksum = 0;
525   count    = 0;
526 
527   while (ch=buffer[count]) {
528     if (! putDebugChar(ch)) return;
529     checksum += ch;
530     count += 1;
531   }
532 
533   putDebugChar('#');
534   putDebugChar(hexchars[checksum >> 4]);
535   putDebugChar(hexchars[checksum % 16]);
536 
537   } while ((getDebugChar() & 0x7f) != '+');
538 
539 }
540 
541 char  remcomInBuffer[BUFMAX];
542 char  remcomOutBuffer[BUFMAX];
543 static short error;
544 
545 
546 void debug_error(format, parm)
547 char * format;
548 char * parm;
549 {
550   if (remote_debug) fprintf (stderr,format,parm);
551 }
552 
553 /* Address of a routine to RTE to if we get a memory fault.  */
554 static void (*volatile mem_fault_routine)() = NULL;
555 
556 /* Indicate to caller of mem2hex or hex2mem that there has been an
557    error.  */
558 static volatile int mem_err = 0;
559 
560 void
561 set_mem_err ()
562 {
563   mem_err = 1;
564 }
565 
566 /* These are separate functions so that they are so short and sweet
567    that the compiler won't save any registers (if there is a fault
568    to mem_fault, they won't get restored, so there better not be any
569    saved).  */
570 int
571 get_char (addr)
572      char *addr;
573 {
574   return *addr;
575 }
576 
577 void
578 set_char (addr, val)
579      char *addr;
580      int val;
581 {
582   *addr = val;
583 }
584 
585 /* convert the memory pointed to by mem into hex, placing result in buf */
586 /* return a pointer to the last char put in buf (null) */
587 /* If MAY_FAULT is non-zero, then we should set mem_err in response to
588    a fault; if zero treat a fault like any other fault in the stub.  */
589 char* mem2hex(mem, buf, count, may_fault)
590 char* mem;
591 char* buf;
592 int   count;
593 int may_fault;
594 {
595       int i;
596       unsigned char ch;
597 
598       if (may_fault)
599 	  mem_fault_routine = set_mem_err;
600       for (i=0;i<count;i++) {
601           ch = get_char (mem++);
602 	  if (may_fault && mem_err)
603 	    return (buf);
604           *buf++ = hexchars[ch >> 4];
605           *buf++ = hexchars[ch % 16];
606       }
607       *buf = 0;
608       if (may_fault)
609 	  mem_fault_routine = NULL;
610       return(buf);
611 }
612 
613 /* convert the hex array pointed to by buf into binary to be placed in mem */
614 /* return a pointer to the character AFTER the last byte written */
615 char* hex2mem(buf, mem, count, may_fault)
616 char* buf;
617 char* mem;
618 int   count;
619 int may_fault;
620 {
621       int i;
622       unsigned char ch;
623 
624       if (may_fault)
625 	  mem_fault_routine = set_mem_err;
626       for (i=0;i<count;i++) {
627           ch = hex(*buf++) << 4;
628           ch = ch + hex(*buf++);
629           set_char (mem++, ch);
630 	  if (may_fault && mem_err)
631 	    return (mem);
632       }
633       if (may_fault)
634 	  mem_fault_routine = NULL;
635       return(mem);
636 }
637 
638 /* this function takes the 386 exception vector and attempts to
639    translate this number into a unix compatible signal value */
640 int computeSignal( exceptionVector )
641 int exceptionVector;
642 {
643   int sigval;
644   switch (exceptionVector) {
645     case 0 : sigval = 8; break; /* divide by zero */
646     case 1 : sigval = 5; break; /* debug exception */
647     case 3 : sigval = 5; break; /* breakpoint */
648     case 4 : sigval = 16; break; /* into instruction (overflow) */
649     case 5 : sigval = 16; break; /* bound instruction */
650     case 6 : sigval = 4; break; /* Invalid opcode */
651     case 7 : sigval = 8; break; /* coprocessor not available */
652     case 8 : sigval = 7; break; /* double fault */
653     case 9 : sigval = 11; break; /* coprocessor segment overrun */
654     case 10 : sigval = 11; break; /* Invalid TSS */
655     case 11 : sigval = 11; break; /* Segment not present */
656     case 12 : sigval = 11; break; /* stack exception */
657     case 13 : sigval = 11; break; /* general protection */
658     case 14 : sigval = 11; break; /* page fault */
659     case 16 : sigval = 7; break; /* coprocessor error */
660     default:
661       sigval = 7;         /* "software generated"*/
662   }
663   return (sigval);
664 }
665 
666 /**********************************************/
667 /* WHILE WE FIND NICE HEX CHARS, BUILD AN INT */
668 /* RETURN NUMBER OF CHARS PROCESSED           */
669 /**********************************************/
670 int hexToInt(char **ptr, int *intValue)
671 {
672     int numChars = 0;
673     int hexValue;
674 
675     *intValue = 0;
676 
677     while (**ptr)
678     {
679         hexValue = hex(**ptr);
680         if (hexValue >=0)
681         {
682             *intValue = (*intValue <<4) | hexValue;
683             numChars ++;
684         }
685         else
686             break;
687 
688         (*ptr)++;
689     }
690 
691     return (numChars);
692 }
693 
694 /*
695  * This function does all command procesing for interfacing to gdb.
696  */
697 void handle_exception(int exceptionVector)
698 {
699   int    sigval;
700   int    addr, length;
701   char * ptr;
702   int    newPC;
703 
704   gdb_i386vector = exceptionVector;
705 
706   if (remote_debug) printf("vector=%d, sr=0x%x, pc=0x%x\n",
707 			    exceptionVector,
708 			    registers[ PS ],
709 			    registers[ PC ]);
710 
711   /* reply to host that an exception has occurred */
712   sigval = computeSignal( exceptionVector );
713   remcomOutBuffer[0] = 'S';
714   remcomOutBuffer[1] =  hexchars[sigval >> 4];
715   remcomOutBuffer[2] =  hexchars[sigval % 16];
716   remcomOutBuffer[3] = 0;
717 
718   putpacket(remcomOutBuffer);
719 
720   while (1==1) {
721     error = 0;
722     remcomOutBuffer[0] = 0;
723     getpacket(remcomInBuffer);
724     switch (remcomInBuffer[0]) {
725       case '?' :   remcomOutBuffer[0] = 'S';
726                    remcomOutBuffer[1] =  hexchars[sigval >> 4];
727                    remcomOutBuffer[2] =  hexchars[sigval % 16];
728                    remcomOutBuffer[3] = 0;
729                  break;
730       case 'd' : remote_debug = !(remote_debug);  /* toggle debug flag */
731                  break;
732       case 'g' : /* return the value of the CPU registers */
733                 mem2hex((char*) registers, remcomOutBuffer, NUMREGBYTES, 0);
734                 break;
735       case 'G' : /* set the value of the CPU registers - return OK */
736                 hex2mem(&remcomInBuffer[1], (char*) registers, NUMREGBYTES, 0);
737                 strcpy(remcomOutBuffer,"OK");
738                 break;
739 
740       /* mAA..AA,LLLL  Read LLLL bytes at address AA..AA */
741       case 'm' :
742 		    /* TRY TO READ %x,%x.  IF SUCCEED, SET PTR = 0 */
743                     ptr = &remcomInBuffer[1];
744                     if (hexToInt(&ptr,&addr))
745                         if (*(ptr++) == ',')
746                             if (hexToInt(&ptr,&length))
747                             {
748                                 ptr = 0;
749 				mem_err = 0;
750                                 mem2hex((char*) addr, remcomOutBuffer, length, 1);
751 				if (mem_err) {
752 				    strcpy (remcomOutBuffer, "E03");
753 				    debug_error ("memory fault");
754 				}
755                             }
756 
757                     if (ptr)
758                     {
759 		      strcpy(remcomOutBuffer,"E01");
760 		      debug_error("malformed read memory command: %s",remcomInBuffer);
761 		    }
762 	          break;
763 
764       /* MAA..AA,LLLL: Write LLLL bytes at address AA.AA return OK */
765       case 'M' :
766 		    /* TRY TO READ '%x,%x:'.  IF SUCCEED, SET PTR = 0 */
767                     ptr = &remcomInBuffer[1];
768                     if (hexToInt(&ptr,&addr))
769                         if (*(ptr++) == ',')
770                             if (hexToInt(&ptr,&length))
771                                 if (*(ptr++) == ':')
772                                 {
773 				    mem_err = 0;
774                                     hex2mem(ptr, (char*) addr, length, 1);
775 
776 				    if (mem_err) {
777 					strcpy (remcomOutBuffer, "E03");
778 					debug_error ("memory fault");
779 				    } else {
780 				        strcpy(remcomOutBuffer,"OK");
781 				    }
782 
783                                     ptr = 0;
784                                 }
785                     if (ptr)
786                     {
787 		      strcpy(remcomOutBuffer,"E02");
788 		      debug_error("malformed write memory command: %s",remcomInBuffer);
789 		    }
790                 break;
791 
792      /* cAA..AA    Continue at address AA..AA(optional) */
793      /* sAA..AA   Step one instruction from AA..AA(optional) */
794      case 'c' :
795      case 's' :
796           /* try to read optional parameter, pc unchanged if no parm */
797          ptr = &remcomInBuffer[1];
798          if (hexToInt(&ptr,&addr))
799              registers[ PC ] = addr;
800 
801           newPC = registers[ PC];
802 
803           /* clear the trace bit */
804           registers[ PS ] &= 0xfffffeff;
805 
806           /* set the trace bit if we're stepping */
807           if (remcomInBuffer[0] == 's') registers[ PS ] |= 0x100;
808 
809           /*
810            * If we found a match for the PC AND we are not returning
811            * as a result of a breakpoint (33),
812            * trace exception (9), nmi (31), jmp to
813            * the old exception handler as if this code never ran.
814            */
815 #if 0
816 	  /* Don't really think we need this, except maybe for protection
817 	     exceptions.  */
818                   /*
819                    * invoke the previous handler.
820                    */
821                   if (oldExceptionHook)
822                       (*oldExceptionHook) (frame->exceptionVector);
823                   newPC = registers[ PC ];    /* pc may have changed  */
824 #endif /* 0 */
825 
826 	  _returnFromException(); /* this is a jump */
827 
828           break;
829 
830       /* kill the program */
831       case 'k' :  /* do nothing */
832 #if 0
833 	/* Huh? This doesn't look like "nothing".
834 	   m68k-stub.c and sparc-stub.c don't have it.  */
835 		BREAKPOINT();
836 #endif
837                 break;
838       } /* switch */
839 
840     /* reply to the request */
841     putpacket(remcomOutBuffer);
842     }
843 }
844 
845 /* this function is used to set up exception handlers for tracing and
846    breakpoints */
847 void set_debug_traps()
848 {
849 extern void remcomHandler();
850 int exception;
851 
852   stackPtr  = &remcomStack[STACKSIZE/sizeof(int) - 1];
853 
854   exceptionHandler (0, _catchException0);
855   exceptionHandler (1, _catchException1);
856   exceptionHandler (3, _catchException3);
857   exceptionHandler (4, _catchException4);
858   exceptionHandler (5, _catchException5);
859   exceptionHandler (6, _catchException6);
860   exceptionHandler (7, _catchException7);
861   exceptionHandler (8, _catchException8);
862   exceptionHandler (9, _catchException9);
863   exceptionHandler (10, _catchException10);
864   exceptionHandler (11, _catchException11);
865   exceptionHandler (12, _catchException12);
866   exceptionHandler (13, _catchException13);
867   exceptionHandler (14, _catchException14);
868   exceptionHandler (16, _catchException16);
869 
870   if (exceptionHook != remcomHandler)
871   {
872       oldExceptionHook = exceptionHook;
873       exceptionHook    = remcomHandler;
874   }
875 
876   /* In case GDB is started before us, ack any packets (presumably
877      "$?#xx") sitting there.  */
878   putDebugChar ('+');
879 
880   initialized = 1;
881 
882 }
883 
884 /* This function will generate a breakpoint exception.  It is used at the
885    beginning of a program to sync up with a debugger and can be used
886    otherwise as a quick means to stop program execution and "break" into
887    the debugger. */
888 
889 void breakpoint()
890 {
891   if (initialized)
892 #if 0
893     handle_exception(3);
894 #else
895     BREAKPOINT();
896 #endif
897   waitabit();
898 }
899 
900 int waitlimit = 1000000;
901 
902 #if 0
903 void
904 bogon()
905 {
906   waitabit();
907 }
908 #endif
909 
910 void
911 waitabit()
912 {
913   int i;
914   for (i = 0; i < waitlimit; i++) ;
915 }
916