gdb/stubs/m68k-stub.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /****************************************************************************

  2.                 THIS SOFTWARE IS NOT COPYRIGHTED

  3.    HP offers the following for use in the public domain.  HP makes no
  4.    warranty with regard to the software or it's performance and the
  5.    user accepts the software "AS IS" with all faults.

  6.    HP DISCLAIMS ANY WARRANTIES, EXPRESS OR IMPLIED, WITH REGARD
  7.    TO THIS SOFTWARE INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  8.    OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.

  9. ****************************************************************************/

  10. /****************************************************************************
  11. *  Header: remcom.c,v 1.34 91/03/09 12:29:49 glenne Exp $
  12. *
  13. *  Module name: remcom.c $
  14. *  Revision: 1.34 $
  15. *  Date: 91/03/09 12:29:49 $
  16. *  Contributor:     Lake Stevens Instrument Division$
  17. *
  18. *  Description:     low level support for gdb debugger. $
  19. *
  20. *  Considerations:  only works on target hardware $
  21. *
  22. *  Written by:      Glenn Engel $
  23. *  ModuleState:     Experimental $
  24. *
  25. *  NOTES:           See Below $
  26. *
  27. *  To enable debugger support, two things need to happen.  One, a
  28. *  call to set_debug_traps() is necessary in order to allow any breakpoints
  29. *  or error conditions to be properly intercepted and reported to gdb.
  30. Two, a breakpoint needs to be generated to begin communication.  This
  31. *  is most easily accomplished by a call to breakpoint().  Breakpoint()
  32. *  simulates a breakpoint by executing a trap #1.  The breakpoint instruction
  33. *  is hardwired to trap #1 because not to do so is a compatibility problem--
  34. *  there either should be a standard breakpoint instruction, or the protocol
  35. *  should be extended to provide some means to communicate which breakpoint
  36. *  instruction is in use (or have the stub insert the breakpoint).
  37. *
  38. *  Some explanation is probably necessary to explain how exceptions are
  39. *  handled.  When an exception is encountered the 68000 pushes the current
  40. *  program counter and status register onto the supervisor stack and then
  41. *  transfers execution to a location specified in it's vector table.
  42. *  The handlers for the exception vectors are hardwired to jmp to an address
  43. *  given by the relation:  (exception - 256) * 6.  These are decending
  44. *  addresses starting from -6, -12, -18, ...  By allowing 6 bytes for
  45. *  each entry, a jsr, jmp, bsr, ... can be used to enter the exception
  46. handler.  Using a jsr to handle an exception has an added benefit of
  47. *  allowing a single handler to service several exceptions and use the
  48. *  return address as the key differentiation.  The vector number can be
  49. *  computed from the return address by [ exception = (addr + 1530) / 6 ].
  50. *  The sole purpose of the routine _catchException is to compute the
  51. *  exception number and push it on the stack in place of the return address.
  52. *  The external function exceptionHandler() is
  53. *  used to attach a specific handler to a specific m68k exception.
  54. *  For 68020 machines, the ability to have a return address around just
  55. *  so the vector can be determined is not necessary because the '020 pushes an
  56. *  extra word onto the stack containing the vector offset
  57. *
  58. *  Because gdb will sometimes write to the stack area to execute function
  59. *  calls, this program cannot rely on using the supervisor stack so it
  60. *  uses it's own stack area reserved in the int array remcomStack.
  61. *
  62. *************
  63. *
  64. *    The following gdb commands are supported:
  65. *
  66. * command          function                               Return value
  67. *
  68. *    g             return the value of the CPU registers  hex data or ENN
  69. *    G             set the value of the CPU registers     OK or ENN
  70. *
  71. *    mAA..AA,LLLL  Read LLLL bytes at address AA..AA      hex data or ENN
  72. *    MAA..AA,LLLL: Write LLLL bytes at address AA.AA      OK or ENN
  73. *
  74. *    c             Resume at current address              SNN   ( signal NN)
  75. *    cAA..AA       Continue at address AA..AA             SNN
  76. *
  77. *    s             Step one instruction                   SNN
  78. *    sAA..AA       Step one instruction from AA..AA       SNN
  79. *
  80. *    k             kill
  81. *
  82. *    ?             What was the last sigval ?             SNN   (signal NN)
  83. *
  84. * All commands and responses are sent with a packet which includes a
  85. * checksum.  A packet consists of
  86. *
  87. * $<packet info>#<checksum>.
  88. *
  89. * where
  90. * <packet info> :: <characters representing the command or response>
  91. * <checksum>    :: < two hex digits computed as modulo 256 sum of <packetinfo>>
  92. *
  93. * When a packet is received, it is first acknowledged with either '+' or '-'.
  94. * '+' indicates a successful transfer.  '-' indicates a failed transfer.
  95. *
  96. * Example:
  97. *
  98. * Host:                  Reply:
  99. * $m0,10#2a               +$00010203040506070809101112131415#42
  100. *
  101. ****************************************************************************/

  102. #include <stdio.h>
  103. #include <string.h>
  104. #include <setjmp.h>

  105. /************************************************************************
  106. *
  107. * external low-level support routines
  108. */
  109. typedef void (*ExceptionHook)(int);   /* pointer to function with int parm */
  110. typedef void (*Function)();           /* pointer to a function */

  111. extern void putDebugChar();        /* write a single character      */
  112. extern int getDebugChar();        /* read and return a single char */

  113. extern Function exceptionHandler();  /* assign an exception handler */
  114. extern ExceptionHook exceptionHook;  /* hook variable for errors/exceptions */

  115. /************************/
  116. /* FORWARD DECLARATIONS */
  117. /************************/
  118. static void
  119. initializeRemcomErrorFrame ();

  120. /************************************************************************/
  121. /* BUFMAX defines the maximum number of characters in inbound/outbound buffers*/
  122. /* at least NUMREGBYTES*2 are needed for register packets */
  123. #define BUFMAX 400

  124. static char initialized/* boolean flag. != 0 means we've been initialized */

  125. int     remote_debug;
  126. /*  debug >  0 prints ill-formed commands in valid packets & checksum errors */

  127. static const char hexchars[]="0123456789abcdef";

  128. /* there are 180 bytes of registers on a 68020 w/68881      */
  129. /* many of the fpa registers are 12 byte (96 bit) registers */
  130. #define NUMREGBYTES 180
  131. enum regnames {D0,D1,D2,D3,D4,D5,D6,D7,
  132.                A0,A1,A2,A3,A4,A5,A6,A7,
  133.                PS,PC,
  134.                FP0,FP1,FP2,FP3,FP4,FP5,FP6,FP7,
  135.                FPCONTROL,FPSTATUS,FPIADDR
  136.               };


  137. /* We keep a whole frame cache here.  "Why?", I hear you cry, "doesn't
  138.    GDB handle that sort of thing?"  Well, yes, I believe the only
  139.    reason for this cache is to save and restore floating point state
  140.    (fsave/frestore).  A cleaner way to do this would be to make the
  141. fsave data part of the registers which GDB deals with like any
  142.    other registers.  This should not be a performance problem if the
  143.    ability to read individual registers is added to the protocol.  */

  144. typedef struct FrameStruct
  145. {
  146.     struct FrameStruct  *previous;
  147.     int       exceptionPC;      /* pc value when this frame created */
  148.     int       exceptionVector;  /* cpu vector causing exception     */
  149.     short     frameSize;        /* size of cpu frame in words       */
  150.     short     sr;               /* for 68000, this not always sr    */
  151.     int       pc;
  152.     short     format;
  153.     int       fsaveHeader;
  154.     int       morejunk[0];        /* exception frame, fp save... */
  155. } Frame;

  156. #define FRAMESIZE 500
  157. int   gdbFrameStack[FRAMESIZE];
  158. static Frame *lastFrame;

  159. /*
  160. * these should not be static cuz they can be used outside this module
  161. */
  162. int registers[NUMREGBYTES/4];
  163. int superStack;

  164. #define STACKSIZE 10000
  165. int remcomStack[STACKSIZE/sizeof(int)];
  166. static int* stackPtr = &remcomStack[STACKSIZE/sizeof(int) - 1];

  167. /*
  168. * In many cases, the system will want to continue exception processing
  169. * when a continue command is given.
  170. * oldExceptionHook is a function to invoke in this case.
  171. */

  172. static ExceptionHook oldExceptionHook;

  173. #ifdef mc68020
  174. /* the size of the exception stack on the 68020 varies with the type of
  175. * exception.  The following table is the number of WORDS used
  176. * for each exception format.
  177. */
  178. const short exceptionSize[] = { 4,4,6,4,4,4,4,4,29,10,16,46,12,4,4,4 };
  179. #endif

  180. #ifdef mc68332
  181. static const short exceptionSize[] = { 4,4,6,4,4,4,4,4,4,4,4,4,16,4,4,4 };
  182. #endif

  183. /************* jump buffer used for setjmp/longjmp **************************/
  184. jmp_buf remcomEnv;

  185. /***************************  ASSEMBLY CODE MACROS *************************/
  186. /*                                                                            */

  187. #ifdef __HAVE_68881__
  188. /* do an fsave, then remember the address to begin a restore from */
  189. #define SAVE_FP_REGS()    asm(" fsave   a0@-");                \
  190.                           asm(" fmovemx fp0-fp7,_registers+72");        \
  191.                           asm(" fmoveml fpcr/fpsr/fpi,_registers+168");
  192. #define RESTORE_FP_REGS()                              \
  193. asm("                                                \n\
  194.     fmoveml  _registers+168,fpcr/fpsr/fpi            \n\
  195.     fmovemx  _registers+72,fp0-fp7                   \n\
  196.     cmpl     #-1,a0@     |  skip frestore flag set ? \n\
  197.     beq      skip_frestore                           \n\
  198.     frestore a0@+                                    \n\
  199. skip_frestore:                                       \n\
  200. ");

  201. #else
  202. #define SAVE_FP_REGS()
  203. #define RESTORE_FP_REGS()
  204. #endif /* __HAVE_68881__ */

  205. void return_to_super();
  206. void return_to_user();

  207. asm("
  208. .text
  209. .globl _return_to_super
  210. _return_to_super:
  211.         movel   _registers+60,sp /* get new stack pointer */
  212.         movel   _lastFrame,a0   /* get last frame info  */
  213.         bra     return_to_any

  214. .globl _return_to_user
  215. _return_to_user:
  216.         movel   _registers+60,a0 /* get usp */
  217.         movel   a0,usp           /* set usp */
  218.         movel   _superStack,sp  /* get original stack pointer */

  219. return_to_any:
  220.         movel   _lastFrame,a0   /* get last frame info  */
  221.         movel   a0@+,_lastFrame /* link in previous frame     */
  222.         addql   #8,a0           /* skip over pc, vector#*/
  223.         movew   a0@+,d0         /* get # of words in cpu frame */
  224.         addw    d0,a0           /* point to end of data        */
  225.         addw    d0,a0           /* point to end of data        */
  226.         movel   a0,a1
  227. #
  228. # copy the stack frame
  229.         subql   #1,d0
  230. copyUserLoop:
  231.         movew   a1@-,sp@-
  232.         dbf     d0,copyUserLoop
  233. ");
  234.         RESTORE_FP_REGS()
  235.    asm("   moveml  _registers,d0-d7/a0-a6");
  236.    asm("   rte");  /* pop and go! */

  237. #define DISABLE_INTERRUPTS()   asm("         oriw   #0x0700,sr");
  238. #define BREAKPOINT() asm("   trap #1");

  239. /* this function is called immediately when a level 7 interrupt occurs */
  240. /* if the previous interrupt level was 7 then we're already servicing  */
  241. /* this interrupt and an rte is in order to return to the debugger.    */
  242. /* For the 68000, the offset for sr is 6 due to the jsr return address */
  243. asm("
  244. .text
  245. .globl __debug_level7
  246. __debug_level7:
  247.         movew   d0,sp@-");
  248. #if defined (mc68020) || defined (mc68332)
  249. asm("        movew   sp@(2),d0");
  250. #else
  251. asm("        movew   sp@(6),d0");
  252. #endif
  253. asm("        andiw   #0x700,d0
  254.         cmpiw   #0x700,d0
  255.         beq     _already7
  256.         movew   sp@+,d0
  257.         bra     __catchException
  258. _already7:
  259.         movew   sp@+,d0");
  260. #if !defined (mc68020) && !defined (mc68332)
  261. asm("        lea     sp@(4),sp");     /* pull off 68000 return address */
  262. #endif
  263. asm("        rte");

  264. extern void _catchException ();

  265. #if defined (mc68020) || defined (mc68332)
  266. /* This function is called when a 68020 exception occurs.  It saves
  267. * all the cpu and fpcp regs in the _registers array, creates a frame on a
  268. * linked list of frames which has the cpu and fpcp stack frames needed
  269. * to properly restore the context of these processors, and invokes
  270. * an exception handler (remcom_handler).
  271. *
  272. * stack on entry:                       stack on exit:
  273. *   N bytes of junk                     exception # MSWord
  274. *   Exception Format Word               exception # MSWord
  275. *   Program counter LSWord
  276. *   Program counter MSWord
  277. *   Status Register
  278. *
  279. *
  280. */
  281. asm("
  282. .text
  283. .globl __catchException
  284. __catchException:");
  285. DISABLE_INTERRUPTS();
  286. asm("
  287.         moveml  d0-d7/a0-a6,_registers /* save registers        */
  288.         movel        _lastFrame,a0        /* last frame pointer */
  289. ");
  290. SAVE_FP_REGS();
  291. asm("
  292.         lea     _registers,a5   /* get address of registers     */
  293.         movew   sp@,d1          /* get status register          */
  294.         movew   d1,a5@(66)      /* save sr                         */
  295.         movel   sp@(2),a4       /* save pc in a4 for later use  */
  296.         movel   a4,a5@(68)      /* save pc in _regisers[]              */

  297. #
  298. # figure out how many bytes in the stack frame
  299.         movew   sp@(6),d0        /* get '020 exception format        */
  300.         movew   d0,d2           /* make a copy of format word   */
  301.         andiw   #0xf000,d0      /* mask off format type         */
  302.         rolw    #5,d0           /* rotate into the low byte *2  */
  303.         lea     _exceptionSize,a1
  304.         addw    d0,a1           /* index into the table         */
  305.         movew   a1@,d0          /* get number of words in frame */
  306.         movew   d0,d3           /* save it                      */
  307.         subw    d0,a0                /* adjust save pointer          */
  308.         subw    d0,a0                /* adjust save pointer(bytes)   */
  309.         movel   a0,a1           /* copy save pointer            */
  310.         subql   #1,d0           /* predecrement loop counter    */
  311. #
  312. # copy the frame
  313. saveFrameLoop:
  314.         movew          sp@+,a1@+
  315.         dbf     d0,saveFrameLoop
  316. #
  317. # now that the stack has been clenaed,
  318. # save the a7 in use at time of exception
  319.         movel   sp,_superStack  /* save supervisor sp           */
  320.         andiw   #0x2000,d1      /* were we in supervisor mode ? */
  321.         beq     userMode
  322.         movel   a7,a5@(60)      /* save a7                  */
  323.         bra     a7saveDone
  324. userMode:
  325.         movel   usp,a1
  326.         movel   a1,a5@(60)      /* save user stack pointer        */
  327. a7saveDone:

  328. #
  329. # save size of frame
  330.         movew   d3,a0@-

  331. #
  332. # compute exception number
  333.         andl    #0xfff,d2           /* mask off vector offset        */
  334.         lsrw    #2,d2           /* divide by 4 to get vect num        */
  335.         movel   d2,a0@-         /* save it                      */
  336. #
  337. # save pc causing exception
  338.         movel   a4,a0@-
  339. #
  340. # save old frame link and set the new value
  341.         movel        _lastFrame,a1        /* last frame pointer */
  342.         movel   a1,a0@-                /* save pointer to prev frame        */
  343.         movel   a0,_lastFrame

  344.         movel   d2,sp@-                /* push exception num           */
  345.         movel   _exceptionHook,a0  /* get address of handler */
  346.         jbsr    a0@             /* and call it */
  347.         clrl    sp@             /* replace exception num parm with frame ptr */
  348.         jbsr     __returnFromException   /* jbsr, but never returns */
  349. ");
  350. #else /* mc68000 */
  351. /* This function is called when an exception occurs.  It translates the
  352. * return address found on the stack into an exception vector # which
  353. * is then handled by either handle_exception or a system handler.
  354. * _catchException provides a front end for both.
  355. *
  356. * stack on entry:                       stack on exit:
  357. *   Program counter MSWord              exception # MSWord
  358. *   Program counter LSWord              exception # MSWord
  359. *   Status Register
  360. *   Return Address  MSWord
  361. *   Return Address  LSWord
  362. */
  363. asm("
  364. .text
  365. .globl __catchException
  366. __catchException:");
  367. DISABLE_INTERRUPTS();
  368. asm("
  369.         moveml d0-d7/a0-a6,_registers  /* save registers               */
  370.         movel        _lastFrame,a0        /* last frame pointer */
  371. ");
  372. SAVE_FP_REGS();
  373. asm("
  374.         lea     _registers,a5   /* get address of registers     */
  375.         movel   sp@+,d2         /* pop return address           */
  376.         addl         #1530,d2        /* convert return addr to         */
  377.         divs         #6,d2           /*  exception number                */
  378.         extl    d2

  379.         moveql  #3,d3           /* assume a three word frame     */

  380.         cmpiw   #3,d2           /* bus error or address error ? */
  381.         bgt     normal          /* if >3 then normal error      */
  382.         movel   sp@+,a0@-       /* copy error info to frame buff*/
  383.         movel   sp@+,a0@-       /* these are never used         */
  384.         moveql  #7,d3           /* this is a 7 word frame       */

  385. normal:
  386.         movew   sp@+,d1         /* pop status register          */
  387.         movel   sp@+,a4         /* pop program counter          */
  388.         movew   d1,a5@(66)      /* save sr                         */
  389.         movel   a4,a5@(68)      /* save pc in _regisers[]              */
  390.         movel   a4,a0@-         /* copy pc to frame buffer      */
  391.         movew   d1,a0@-         /* copy sr to frame buffer      */

  392.         movel   sp,_superStack  /* save supervisor sp          */

  393.         andiw   #0x2000,d1      /* were we in supervisor mode ? */
  394.         beq     userMode
  395.         movel   a7,a5@(60)      /* save a7                  */
  396.         bra     saveDone
  397. userMode:
  398.         movel   usp,a1            /* save user stack pointer         */
  399.         movel   a1,a5@(60)      /* save user stack pointer        */
  400. saveDone:

  401.         movew   d3,a0@-         /* push frame size in words     */
  402.         movel   d2,a0@-         /* push vector number           */
  403.         movel   a4,a0@-         /* push exception pc            */

  404. #
  405. # save old frame link and set the new value
  406.         movel        _lastFrame,a1        /* last frame pointer */
  407.         movel   a1,a0@-                /* save pointer to prev frame        */
  408.         movel   a0,_lastFrame

  409.         movel   d2,sp@-                /* push exception num           */
  410.         movel   _exceptionHook,a0  /* get address of handler */
  411.         jbsr    a0@             /* and call it */
  412.         clrl    sp@             /* replace exception num parm with frame ptr */
  413.         jbsr     __returnFromException   /* jbsr, but never returns */
  414. ");
  415. #endif


  416. /*
  417. * remcomHandler is a front end for handle_exception.  It moves the
  418. * stack pointer into an area reserved for debugger use in case the
  419. * breakpoint happened in supervisor mode.
  420. */
  421. asm("_remcomHandler:");
  422. asm("           addl    #4,sp");        /* pop off return address     */
  423. asm("           movel   sp@+,d0");      /* get the exception number   */
  424. asm("                movel   _stackPtr,sp"); /* move to remcom stack area  */
  425. asm("                movel   d0,sp@-");        /* push exception onto stack  */
  426. asm("                jbsr    _handle_exception");    /* this never returns */
  427. asm("           rts");                  /* return */

  428. void
  429. _returnFromException (Frame * frame)
  430. {
  431.   /* if no passed in frame, use the last one */
  432.   if (!frame)
  433.     {
  434.       frame = lastFrame;
  435.       frame->frameSize = 4;
  436.       frame->format = 0;
  437.       frame->fsaveHeader = -1;        /* restore regs, but we dont have fsave info */
  438.     }

  439. #if !defined (mc68020) && !defined (mc68332)
  440.   /* a 68000 cannot use the internal info pushed onto a bus error
  441.    * or address error frame when doing an RTE so don't put this info
  442.    * onto the stack or the stack will creep every time this happens.
  443.    */
  444.   frame->frameSize = 3;
  445. #endif

  446.   /* throw away any frames in the list after this frame */
  447.   lastFrame = frame;

  448.   frame->sr = registers[(int) PS];
  449.   frame->pc = registers[(int) PC];

  450.   if (registers[(int) PS] & 0x2000)
  451.     {
  452.       /* return to supervisor mode... */
  453.       return_to_super ();
  454.     }
  455.   else
  456.     {                                /* return to user mode */
  457.       return_to_user ();
  458.     }
  459. }

  460. int
  461. hex (ch)
  462.      char ch;
  463. {
  464.   if ((ch >= 'a') && (ch <= 'f'))
  465.     return (ch - 'a' + 10);
  466.   if ((ch >= '0') && (ch <= '9'))
  467.     return (ch - '0');
  468.   if ((ch >= 'A') && (ch <= 'F'))
  469.     return (ch - 'A' + 10);
  470.   return (-1);
  471. }

  472. static char remcomInBuffer[BUFMAX];
  473. static char remcomOutBuffer[BUFMAX];

  474. /* scan for the sequence $<data>#<checksum>     */

  475. unsigned char *
  476. getpacket (void)
  477. {
  478.   unsigned char *buffer = &remcomInBuffer[0];
  479.   unsigned char checksum;
  480.   unsigned char xmitcsum;
  481.   int count;
  482.   char ch;

  483.   while (1)
  484.     {
  485.       /* wait around for the start character, ignore all other characters */
  486.       while ((ch = getDebugChar ()) != '$')
  487.         ;

  488.     retry:
  489.       checksum = 0;
  490.       xmitcsum = -1;
  491.       count = 0;

  492.       /* now, read until a # or end of buffer is found */
  493.       while (count < BUFMAX - 1)
  494.         {
  495.           ch = getDebugChar ();
  496.           if (ch == '$')
  497.             goto retry;
  498.           if (ch == '#')
  499.             break;
  500.           checksum = checksum + ch;
  501.           buffer[count] = ch;
  502.           count = count + 1;
  503.         }
  504.       buffer[count] = 0;

  505.       if (ch == '#')
  506.         {
  507.           ch = getDebugChar ();
  508.           xmitcsum = hex (ch) << 4;
  509.           ch = getDebugChar ();
  510.           xmitcsum += hex (ch);

  511.           if (checksum != xmitcsum)
  512.             {
  513.               if (remote_debug)
  514.                 {
  515.                   fprintf (stderr,
  516.                            "bad checksum.  My count = 0x%x, sent=0x%x. buf=%s\n",
  517.                            checksum, xmitcsum, buffer);
  518.                 }
  519.               putDebugChar ('-');        /* failed checksum */
  520.             }
  521.           else
  522.             {
  523.               putDebugChar ('+');        /* successful transfer */

  524.               /* if a sequence char is present, reply the sequence ID */
  525.               if (buffer[2] == ':')
  526.                 {
  527.                   putDebugChar (buffer[0]);
  528.                   putDebugChar (buffer[1]);

  529.                   return &buffer[3];
  530.                 }

  531.               return &buffer[0];
  532.             }
  533.         }
  534.     }
  535. }

  536. /* send the packet in buffer. */

  537. void
  538. putpacket (buffer)
  539.      char *buffer;
  540. {
  541.   unsigned char checksum;
  542.   int count;
  543.   char ch;

  544.   /*  $<packet info>#<checksum>. */
  545.   do
  546.     {
  547.       putDebugChar ('$');
  548.       checksum = 0;
  549.       count = 0;

  550.       while (ch = buffer[count])
  551.         {
  552.           putDebugChar (ch);
  553.           checksum += ch;
  554.           count += 1;
  555.         }

  556.       putDebugChar ('#');
  557.       putDebugChar (hexchars[checksum >> 4]);
  558.       putDebugChar (hexchars[checksum % 16]);

  559.     }
  560.   while (getDebugChar () != '+');

  561. }

  562. void
  563. debug_error (format, parm)
  564.      char *format;
  565.      char *parm;
  566. {
  567.   if (remote_debug)
  568.     fprintf (stderr, format, parm);
  569. }

  570. /* convert the memory pointed to by mem into hex, placing result in buf */
  571. /* return a pointer to the last char put in buf (null) */
  572. char *
  573. mem2hex (mem, buf, count)
  574.      char *mem;
  575.      char *buf;
  576.      int count;
  577. {
  578.   int i;
  579.   unsigned char ch;
  580.   for (i = 0; i < count; i++)
  581.     {
  582.       ch = *mem++;
  583.       *buf++ = hexchars[ch >> 4];
  584.       *buf++ = hexchars[ch % 16];
  585.     }
  586.   *buf = 0;
  587.   return (buf);
  588. }

  589. /* convert the hex array pointed to by buf into binary to be placed in mem */
  590. /* return a pointer to the character AFTER the last byte written */
  591. char *
  592. hex2mem (buf, mem, count)
  593.      char *buf;
  594.      char *mem;
  595.      int count;
  596. {
  597.   int i;
  598.   unsigned char ch;
  599.   for (i = 0; i < count; i++)
  600.     {
  601.       ch = hex (*buf++) << 4;
  602.       ch = ch + hex (*buf++);
  603.       *mem++ = ch;
  604.     }
  605.   return (mem);
  606. }

  607. /* a bus error has occurred, perform a longjmp
  608.    to return execution and allow handling of the error */

  609. void
  610. handle_buserror ()
  611. {
  612.   longjmp (remcomEnv, 1);
  613. }

  614. /* this function takes the 68000 exception number and attempts to
  615.    translate this number into a unix compatible signal value */
  616. int
  617. computeSignal (exceptionVector)
  618.      int exceptionVector;
  619. {
  620.   int sigval;
  621.   switch (exceptionVector)
  622.     {
  623.     case 2:
  624.       sigval = 10;
  625.       break;                        /* bus error           */
  626.     case 3:
  627.       sigval = 10;
  628.       break;                        /* address error       */
  629.     case 4:
  630.       sigval = 4;
  631.       break;                        /* illegal instruction */
  632.     case 5:
  633.       sigval = 8;
  634.       break;                        /* zero divide         */
  635.     case 6:
  636.       sigval = 8;
  637.       break;                        /* chk instruction     */
  638.     case 7:
  639.       sigval = 8;
  640.       break;                        /* trapv instruction   */
  641.     case 8:
  642.       sigval = 11;
  643.       break;                        /* privilege violation */
  644.     case 9:
  645.       sigval = 5;
  646.       break;                        /* trace trap          */
  647.     case 10:
  648.       sigval = 4;
  649.       break;                        /* line 1010 emulator  */
  650.     case 11:
  651.       sigval = 4;
  652.       break;                        /* line 1111 emulator  */

  653.       /* Coprocessor protocol violation.  Using a standard MMU or FPU
  654.          this cannot be triggered by software.  Call it a SIGBUS.  */
  655.     case 13:
  656.       sigval = 10;
  657.       break;

  658.     case 31:
  659.       sigval = 2;
  660.       break;                        /* interrupt           */
  661.     case 33:
  662.       sigval = 5;
  663.       break;                        /* breakpoint          */

  664.       /* This is a trap #8 instruction.  Apparently it is someone's software
  665.          convention for some sort of SIGFPE condition.  Whose?  How many
  666.          people are being screwed by having this code the way it is?
  667.          Is there a clean solution?  */
  668.     case 40:
  669.       sigval = 8;
  670.       break;                        /* floating point err  */

  671.     case 48:
  672.       sigval = 8;
  673.       break;                        /* floating point err  */
  674.     case 49:
  675.       sigval = 8;
  676.       break;                        /* floating point err  */
  677.     case 50:
  678.       sigval = 8;
  679.       break;                        /* zero divide         */
  680.     case 51:
  681.       sigval = 8;
  682.       break;                        /* underflow           */
  683.     case 52:
  684.       sigval = 8;
  685.       break;                        /* operand error       */
  686.     case 53:
  687.       sigval = 8;
  688.       break;                        /* overflow            */
  689.     case 54:
  690.       sigval = 8;
  691.       break;                        /* NAN                 */
  692.     default:
  693.       sigval = 7;                /* "software generated" */
  694.     }
  695.   return (sigval);
  696. }

  697. /**********************************************/
  698. /* WHILE WE FIND NICE HEX CHARS, BUILD AN INT */
  699. /* RETURN NUMBER OF CHARS PROCESSED           */
  700. /**********************************************/
  701. int
  702. hexToInt (char **ptr, int *intValue)
  703. {
  704.   int numChars = 0;
  705.   int hexValue;

  706.   *intValue = 0;

  707.   while (**ptr)
  708.     {
  709.       hexValue = hex (**ptr);
  710.       if (hexValue >= 0)
  711.         {
  712.           *intValue = (*intValue << 4) | hexValue;
  713.           numChars++;
  714.         }
  715.       else
  716.         break;

  717.       (*ptr)++;
  718.     }

  719.   return (numChars);
  720. }

  721. /*
  722. * This function does all command procesing for interfacing to gdb.
  723. */
  724. void
  725. handle_exception (int exceptionVector)
  726. {
  727.   int sigval, stepping;
  728.   int addr, length;
  729.   char *ptr;
  730.   int newPC;
  731.   Frame *frame;

  732.   if (remote_debug)
  733.     printf ("vector=%d, sr=0x%x, pc=0x%x\n",
  734.             exceptionVector, registers[PS], registers[PC]);

  735.   /* reply to host that an exception has occurred */
  736.   sigval = computeSignal (exceptionVector);
  737.   remcomOutBuffer[0] = 'S';
  738.   remcomOutBuffer[1] = hexchars[sigval >> 4];
  739.   remcomOutBuffer[2] = hexchars[sigval % 16];
  740.   remcomOutBuffer[3] = 0;

  741.   putpacket (remcomOutBuffer);

  742.   stepping = 0;

  743.   while (1 == 1)
  744.     {
  745.       remcomOutBuffer[0] = 0;
  746.       ptr = getpacket ();
  747.       switch (*ptr++)
  748.         {
  749.         case '?':
  750.           remcomOutBuffer[0] = 'S';
  751.           remcomOutBuffer[1] = hexchars[sigval >> 4];
  752.           remcomOutBuffer[2] = hexchars[sigval % 16];
  753.           remcomOutBuffer[3] = 0;
  754.           break;
  755.         case 'd':
  756.           remote_debug = !(remote_debug);        /* toggle debug flag */
  757.           break;
  758.         case 'g':                /* return the value of the CPU registers */
  759.           mem2hex ((char *) registers, remcomOutBuffer, NUMREGBYTES);
  760.           break;
  761.         case 'G':                /* set the value of the CPU registers - return OK */
  762.           hex2mem (ptr, (char *) registers, NUMREGBYTES);
  763.           strcpy (remcomOutBuffer, "OK");
  764.           break;

  765.           /* mAA..AA,LLLL  Read LLLL bytes at address AA..AA */
  766.         case 'm':
  767.           if (setjmp (remcomEnv) == 0)
  768.             {
  769.               exceptionHandler (2, handle_buserror);

  770.               /* TRY TO READ %x,%x.  IF SUCCEED, SET PTR = 0 */
  771.               if (hexToInt (&ptr, &addr))
  772.                 if (*(ptr++) == ',')
  773.                   if (hexToInt (&ptr, &length))
  774.                     {
  775.                       ptr = 0;
  776.                       mem2hex ((char *) addr, remcomOutBuffer, length);
  777.                     }

  778.               if (ptr)
  779.                 {
  780.                   strcpy (remcomOutBuffer, "E01");
  781.                 }
  782.             }
  783.           else
  784.             {
  785.               exceptionHandler (2, _catchException);
  786.               strcpy (remcomOutBuffer, "E03");
  787.               debug_error ("bus error");
  788.             }

  789.           /* restore handler for bus error */
  790.           exceptionHandler (2, _catchException);
  791.           break;

  792.           /* MAA..AA,LLLL: Write LLLL bytes at address AA.AA return OK */
  793.         case 'M':
  794.           if (setjmp (remcomEnv) == 0)
  795.             {
  796.               exceptionHandler (2, handle_buserror);

  797.               /* TRY TO READ '%x,%x:'.  IF SUCCEED, SET PTR = 0 */
  798.               if (hexToInt (&ptr, &addr))
  799.                 if (*(ptr++) == ',')
  800.                   if (hexToInt (&ptr, &length))
  801.                     if (*(ptr++) == ':')
  802.                       {
  803.                         hex2mem (ptr, (char *) addr, length);
  804.                         ptr = 0;
  805.                         strcpy (remcomOutBuffer, "OK");
  806.                       }
  807.               if (ptr)
  808.                 {
  809.                   strcpy (remcomOutBuffer, "E02");
  810.                 }
  811.             }
  812.           else
  813.             {
  814.               exceptionHandler (2, _catchException);
  815.               strcpy (remcomOutBuffer, "E03");
  816.               debug_error ("bus error");
  817.             }

  818.           /* restore handler for bus error */
  819.           exceptionHandler (2, _catchException);
  820.           break;

  821.           /* cAA..AA    Continue at address AA..AA(optional) */
  822.           /* sAA..AA   Step one instruction from AA..AA(optional) */
  823.         case 's':
  824.           stepping = 1;
  825.         case 'c':
  826.           /* try to read optional parameter, pc unchanged if no parm */
  827.           if (hexToInt (&ptr, &addr))
  828.             registers[PC] = addr;

  829.           newPC = registers[PC];

  830.           /* clear the trace bit */
  831.           registers[PS] &= 0x7fff;

  832.           /* set the trace bit if we're stepping */
  833.           if (stepping)
  834.             registers[PS] |= 0x8000;

  835.           /*
  836.            * look for newPC in the linked list of exception frames.
  837.            * if it is found, use the old frame it.  otherwise,
  838.            * fake up a dummy frame in returnFromException().
  839.            */
  840.           if (remote_debug)
  841.             printf ("new pc = 0x%x\n", newPC);
  842.           frame = lastFrame;
  843.           while (frame)
  844.             {
  845.               if (remote_debug)
  846.                 printf ("frame at 0x%x has pc=0x%x, except#=%d\n",
  847.                         frame, frame->exceptionPC, frame->exceptionVector);
  848.               if (frame->exceptionPC == newPC)
  849.                 break;                /* bingo! a match */
  850.               /*
  851.                * for a breakpoint instruction, the saved pc may
  852.                * be off by two due to re-executing the instruction
  853.                * replaced by the trap instruction.  Check for this.
  854.                */
  855.               if ((frame->exceptionVector == 33) &&
  856.                   (frame->exceptionPC == (newPC + 2)))
  857.                 break;
  858.               if (frame == frame->previous)
  859.                 {
  860.                   frame = 0;        /* no match found */
  861.                   break;
  862.                 }
  863.               frame = frame->previous;
  864.             }

  865.           /*
  866.            * If we found a match for the PC AND we are not returning
  867.            * as a result of a breakpoint (33),
  868.            * trace exception (9), nmi (31), jmp to
  869.            * the old exception handler as if this code never ran.
  870.            */
  871.           if (frame)
  872.             {
  873.               if ((frame->exceptionVector != 9) &&
  874.                   (frame->exceptionVector != 31) &&
  875.                   (frame->exceptionVector != 33))
  876.                 {
  877.                   /*
  878.                    * invoke the previous handler.
  879.                    */
  880.                   if (oldExceptionHook)
  881.                     (*oldExceptionHook) (frame->exceptionVector);
  882.                   newPC = registers[PC];        /* pc may have changed  */
  883.                   if (newPC != frame->exceptionPC)
  884.                     {
  885.                       if (remote_debug)
  886.                         printf ("frame at 0x%x has pc=0x%x, except#=%d\n",
  887.                                 frame, frame->exceptionPC,
  888.                                 frame->exceptionVector);
  889.                       /* re-use the last frame, we're skipping it (longjump?) */
  890.                       frame = (Frame *) 0;
  891.                       _returnFromException (frame);        /* this is a jump */
  892.                     }
  893.                 }
  894.             }

  895.           /* if we couldn't find a frame, create one */
  896.           if (frame == 0)
  897.             {
  898.               frame = lastFrame - 1;

  899.               /* by using a bunch of print commands with breakpoints,
  900.                  it's possible for the frame stack to creep down.  If it creeps
  901.                  too far, give up and reset it to the topNormal use should
  902.                  not see this happen.
  903.                */
  904.               if ((unsigned int) (frame - 2) < (unsigned int) &gdbFrameStack)
  905.                 {
  906.                   initializeRemcomErrorFrame ();
  907.                   frame = lastFrame;
  908.                 }
  909.               frame->previous = lastFrame;
  910.               lastFrame = frame;
  911.               frame = 0;        /* null so _return... will properly initialize it */
  912.             }

  913.           _returnFromException (frame);        /* this is a jump */

  914.           break;

  915.           /* kill the program */
  916.         case 'k':                /* do nothing */
  917.           break;
  918.         }                        /* switch */

  919.       /* reply to the request */
  920.       putpacket (remcomOutBuffer);
  921.     }
  922. }


  923. void
  924. initializeRemcomErrorFrame (void)
  925. {
  926.   lastFrame = ((Frame *) & gdbFrameStack[FRAMESIZE - 1]) - 1;
  927.   lastFrame->previous = lastFrame;
  928. }

  929. /* this function is used to set up exception handlers for tracing and
  930.    breakpoints */
  931. void
  932. set_debug_traps ()
  933. {
  934.   extern void _debug_level7 ();
  935.   extern void remcomHandler ();
  936.   int exception;

  937.   initializeRemcomErrorFrame ();
  938.   stackPtr = &remcomStack[STACKSIZE / sizeof (int) - 1];

  939.   for (exception = 2; exception <= 23; exception++)
  940.     exceptionHandler (exception, _catchException);

  941.   /* level 7 interrupt              */
  942.   exceptionHandler (31, _debug_level7);

  943.   /* breakpoint exception (trap #1) */
  944.   exceptionHandler (33, _catchException);

  945.   /* This is a trap #8 instruction.  Apparently it is someone's software
  946.      convention for some sort of SIGFPE condition.  Whose?  How many
  947.      people are being screwed by having this code the way it is?
  948.      Is there a clean solution?  */
  949.   exceptionHandler (40, _catchException);

  950.   /* 48 to 54 are floating point coprocessor errors */
  951.   for (exception = 48; exception <= 54; exception++)
  952.     exceptionHandler (exception, _catchException);

  953.   if (oldExceptionHook != remcomHandler)
  954.     {
  955.       oldExceptionHook = exceptionHook;
  956.       exceptionHook = remcomHandler;
  957.     }

  958.   initialized = 1;

  959. }

  960. /* This function will generate a breakpoint exception.  It is used at the
  961.    beginning of a program to sync up with a debugger and can be used
  962.    otherwise as a quick means to stop program execution and "break" into
  963.    the debugger. */

  964. void
  965. breakpoint ()
  966. {
  967.   if (initialized)
  968.     BREAKPOINT ();
  969. }