gdb/stubs/m32r-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. *  Modified for M32R by Michael Snyder, Cygnus Support.
  28. *
  29. *  To enable debugger support, two things need to happen.  One, a
  30. *  call to set_debug_traps() is necessary in order to allow any breakpoints
  31. *  or error conditions to be properly intercepted and reported to gdb.
  32. Two, a breakpoint needs to be generated to begin communication.  This
  33. *  is most easily accomplished by a call to breakpoint().  Breakpoint()
  34. *  simulates a breakpoint by executing a trap #1.
  35. *
  36. *  The external function exceptionHandler() is
  37. *  used to attach a specific handler to a specific M32R vector number.
  38. *  It should use the same privilege level it runs at.  It should
  39. *  install it as an interrupt gate so that interrupts are masked
  40. *  while the handler runs.
  41. *
  42. *  Because gdb will sometimes write to the stack area to execute function
  43. *  calls, this program cannot rely on using the supervisor stack so it
  44. *  uses it's own stack area reserved in the int array remcomStack.
  45. *
  46. *************
  47. *
  48. *    The following gdb commands are supported:
  49. *
  50. * command          function                               Return value
  51. *
  52. *    g             return the value of the CPU registers  hex data or ENN
  53. *    G             set the value of the CPU registers     OK or ENN
  54. *
  55. *    mAA..AA,LLLL  Read LLLL bytes at address AA..AA      hex data or ENN
  56. *    MAA..AA,LLLL: Write LLLL bytes at address AA.AA      OK or ENN
  57. *    XAA..AA,LLLL: Write LLLL binary bytes at address     OK or ENN
  58. *                  AA..AA
  59. *
  60. *    c             Resume at current address              SNN   ( signal NN)
  61. *    cAA..AA       Continue at address AA..AA             SNN
  62. *
  63. *    s             Step one instruction                   SNN
  64. *    sAA..AA       Step one instruction from AA..AA       SNN
  65. *
  66. *    k             kill
  67. *
  68. *    ?             What was the last sigval ?             SNN   (signal NN)
  69. *
  70. * All commands and responses are sent with a packet which includes a
  71. * checksum.  A packet consists of
  72. *
  73. * $<packet info>#<checksum>.
  74. *
  75. * where
  76. * <packet info> :: <characters representing the command or response>
  77. * <checksum>    :: <two hex digits computed as modulo 256 sum of <packetinfo>>
  78. *
  79. * When a packet is received, it is first acknowledged with either '+' or '-'.
  80. * '+' indicates a successful transfer.  '-' indicates a failed transfer.
  81. *
  82. * Example:
  83. *
  84. * Host:                  Reply:
  85. * $m0,10#2a               +$00010203040506070809101112131415#42
  86. *
  87. ****************************************************************************/


  88. /************************************************************************
  89. *
  90. * external low-level support routines
  91. */
  92. extern void putDebugChar ();        /* write a single character      */
  93. extern int getDebugChar ();        /* read and return a single char */
  94. extern void exceptionHandler ();        /* assign an exception handler   */

  95. /*****************************************************************************
  96. * BUFMAX defines the maximum number of characters in inbound/outbound buffers
  97. * at least NUMREGBYTES*2 are needed for register packets
  98. */
  99. #define BUFMAX 400

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

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

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

  104. #define NUMREGS 24

  105. /* Number of bytes of registers.  */
  106. #define NUMREGBYTES (NUMREGS * 4)
  107. enum regnames
  108. { R0, R1, R2, R3, R4, R5, R6, R7,
  109.   R8, R9, R10, R11, R12, R13, R14, R15,
  110.   PSW, CBR, SPI, SPU, BPC, PC, ACCL, ACCH
  111. };

  112. enum SYS_calls
  113. {
  114.   SYS_null,
  115.   SYS_exit,
  116.   SYS_open,
  117.   SYS_close,
  118.   SYS_read,
  119.   SYS_write,
  120.   SYS_lseek,
  121.   SYS_unlink,
  122.   SYS_getpid,
  123.   SYS_kill,
  124.   SYS_fstat,
  125.   SYS_sbrk,
  126.   SYS_fork,
  127.   SYS_execve,
  128.   SYS_wait4,
  129.   SYS_link,
  130.   SYS_chdir,
  131.   SYS_stat,
  132.   SYS_utime,
  133.   SYS_chown,
  134.   SYS_chmod,
  135.   SYS_time,
  136.   SYS_pipe
  137. };

  138. static int registers[NUMREGS];

  139. #define STACKSIZE 8096
  140. static unsigned char remcomInBuffer[BUFMAX];
  141. static unsigned char remcomOutBuffer[BUFMAX];
  142. static int remcomStack[STACKSIZE / sizeof (int)];
  143. static int *stackPtr = &remcomStack[STACKSIZE / sizeof (int) - 1];

  144. static unsigned int save_vectors[18];        /* previous exception vectors */

  145. /* Indicate to caller of mem2hex or hex2mem that there has been an error. */
  146. static volatile int mem_err = 0;

  147. /* Store the vector number here (since GDB only gets the signal
  148.    number through the usual means, and that's not very specific).  */
  149. int gdb_m32r_vector = -1;

  150. #if 0
  151. #include "syscall.h"                /* for SYS_exit, SYS_write etc. */
  152. #endif

  153. /* Global entry points:
  154. */

  155. extern void handle_exception (int);
  156. extern void set_debug_traps (void);
  157. extern void breakpoint (void);

  158. /* Local functions:
  159. */

  160. static int computeSignal (int);
  161. static void putpacket (unsigned char *);
  162. static unsigned char *getpacket (void);

  163. static unsigned char *mem2hex (unsigned char *, unsigned char *, int, int);
  164. static unsigned char *hex2mem (unsigned char *, unsigned char *, int, int);
  165. static int hexToInt (unsigned char **, int *);
  166. static unsigned char *bin2mem (unsigned char *, unsigned char *, int, int);
  167. static void stash_registers (void);
  168. static void restore_registers (void);
  169. static int prepare_to_step (int);
  170. static int finish_from_step (void);
  171. static unsigned long crc32 (unsigned char *, int, unsigned long);

  172. static void gdb_error (char *, char *);
  173. static int gdb_putchar (int), gdb_puts (char *), gdb_write (char *, int);

  174. static unsigned char *strcpy (unsigned char *, const unsigned char *);
  175. static int strlen (const unsigned char *);

  176. /*
  177. * This function does all command procesing for interfacing to gdb.
  178. */

  179. void
  180. handle_exception (int exceptionVector)
  181. {
  182.   int sigval, stepping;
  183.   int addr, length, i;
  184.   unsigned char *ptr;
  185.   unsigned char buf[16];
  186.   int binary;

  187.   if (!finish_from_step ())
  188.     return;                        /* "false step": let the target continue */

  189.   gdb_m32r_vector = exceptionVector;

  190.   if (remote_debug)
  191.     {
  192.       mem2hex ((unsigned char *) &exceptionVector, buf, 4, 0);
  193.       gdb_error ("Handle exception %s, ", buf);
  194.       mem2hex ((unsigned char *) &registers[PC], buf, 4, 0);
  195.       gdb_error ("PC == 0x%s\n", buf);
  196.     }

  197.   /* reply to host that an exception has occurred */
  198.   sigval = computeSignal (exceptionVector);

  199.   ptr = remcomOutBuffer;

  200.   *ptr++ = 'T';                        /* notify gdb with signo, PC, FP and SP */
  201.   *ptr++ = hexchars[sigval >> 4];
  202.   *ptr++ = hexchars[sigval & 0xf];

  203.   *ptr++ = hexchars[PC >> 4];
  204.   *ptr++ = hexchars[PC & 0xf];
  205.   *ptr++ = ':';
  206.   ptr = mem2hex ((unsigned char *) &registers[PC], ptr, 4, 0);        /* PC */
  207.   *ptr++ = ';';

  208.   *ptr++ = hexchars[R13 >> 4];
  209.   *ptr++ = hexchars[R13 & 0xf];
  210.   *ptr++ = ':';
  211.   ptr = mem2hex ((unsigned char *) &registers[R13], ptr, 4, 0);        /* FP */
  212.   *ptr++ = ';';

  213.   *ptr++ = hexchars[R15 >> 4];
  214.   *ptr++ = hexchars[R15 & 0xf];
  215.   *ptr++ = ':';
  216.   ptr = mem2hex ((unsigned char *) &registers[R15], ptr, 4, 0);        /* SP */
  217.   *ptr++ = ';';
  218.   *ptr++ = 0;

  219.   if (exceptionVector == 0)        /* simulated SYS call stuff */
  220.     {
  221.       mem2hex ((unsigned char *) &registers[PC], buf, 4, 0);
  222.       switch (registers[R0])
  223.         {
  224.         case SYS_exit:
  225.           gdb_error ("Target program has exited at %s\n", buf);
  226.           ptr = remcomOutBuffer;
  227.           *ptr++ = 'W';
  228.           sigval = registers[R1] & 0xff;
  229.           *ptr++ = hexchars[sigval >> 4];
  230.           *ptr++ = hexchars[sigval & 0xf];
  231.           *ptr++ = 0;
  232.           break;
  233.         case SYS_open:
  234.           gdb_error ("Target attempts SYS_open call at %s\n", buf);
  235.           break;
  236.         case SYS_close:
  237.           gdb_error ("Target attempts SYS_close call at %s\n", buf);
  238.           break;
  239.         case SYS_read:
  240.           gdb_error ("Target attempts SYS_read call at %s\n", buf);
  241.           break;
  242.         case SYS_write:
  243.           if (registers[R1] == 1 ||        /* write to stdout  */
  244.               registers[R1] == 2)        /* write to stderr  */
  245.             {                        /* (we can do that) */
  246.               registers[R0] =
  247.                 gdb_write ((void *) registers[R2], registers[R3]);
  248.               return;
  249.             }
  250.           else
  251.             gdb_error ("Target attempts SYS_write call at %s\n", buf);
  252.           break;
  253.         case SYS_lseek:
  254.           gdb_error ("Target attempts SYS_lseek call at %s\n", buf);
  255.           break;
  256.         case SYS_unlink:
  257.           gdb_error ("Target attempts SYS_unlink call at %s\n", buf);
  258.           break;
  259.         case SYS_getpid:
  260.           gdb_error ("Target attempts SYS_getpid call at %s\n", buf);
  261.           break;
  262.         case SYS_kill:
  263.           gdb_error ("Target attempts SYS_kill call at %s\n", buf);
  264.           break;
  265.         case SYS_fstat:
  266.           gdb_error ("Target attempts SYS_fstat call at %s\n", buf);
  267.           break;
  268.         default:
  269.           gdb_error ("Target attempts unknown SYS call at %s\n", buf);
  270.           break;
  271.         }
  272.     }

  273.   putpacket (remcomOutBuffer);

  274.   stepping = 0;

  275.   while (1 == 1)
  276.     {
  277.       remcomOutBuffer[0] = 0;
  278.       ptr = getpacket ();
  279.       binary = 0;
  280.       switch (*ptr++)
  281.         {
  282.         default:                /* Unknown code.  Return an empty reply message. */
  283.           break;
  284.         case 'R':
  285.           if (hexToInt (&ptr, &addr))
  286.             registers[PC] = addr;
  287.           strcpy (remcomOutBuffer, "OK");
  288.           break;
  289.         case '!':
  290.           strcpy (remcomOutBuffer, "OK");
  291.           break;
  292.         case 'X':                /* XAA..AA,LLLL:<binary data>#cs */
  293.           binary = 1;
  294.         case 'M':                /* MAA..AA,LLLL: Write LLLL bytes at address AA.AA return OK */
  295.           /* TRY TO READ '%x,%x:'.  IF SUCCEED, SET PTR = 0 */
  296.           {
  297.             if (hexToInt (&ptr, &addr))
  298.               if (*(ptr++) == ',')
  299.                 if (hexToInt (&ptr, &length))
  300.                   if (*(ptr++) == ':')
  301.                     {
  302.                       mem_err = 0;
  303.                       if (binary)
  304.                         bin2mem (ptr, (unsigned char *) addr, length, 1);
  305.                       else
  306.                         hex2mem (ptr, (unsigned char *) addr, length, 1);
  307.                       if (mem_err)
  308.                         {
  309.                           strcpy (remcomOutBuffer, "E03");
  310.                           gdb_error ("memory fault", "");
  311.                         }
  312.                       else
  313.                         {
  314.                           strcpy (remcomOutBuffer, "OK");
  315.                         }
  316.                       ptr = 0;
  317.                     }
  318.             if (ptr)
  319.               {
  320.                 strcpy (remcomOutBuffer, "E02");
  321.               }
  322.           }
  323.           break;
  324.         case 'm':                /* mAA..AA,LLLL  Read LLLL bytes at address AA..AA */
  325.           /* TRY TO READ %x,%x.  IF SUCCEED, SET PTR = 0 */
  326.           if (hexToInt (&ptr, &addr))
  327.             if (*(ptr++) == ',')
  328.               if (hexToInt (&ptr, &length))
  329.                 {
  330.                   ptr = 0;
  331.                   mem_err = 0;
  332.                   mem2hex ((unsigned char *) addr, remcomOutBuffer, length,
  333.                            1);
  334.                   if (mem_err)
  335.                     {
  336.                       strcpy (remcomOutBuffer, "E03");
  337.                       gdb_error ("memory fault", "");
  338.                     }
  339.                 }
  340.           if (ptr)
  341.             {
  342.               strcpy (remcomOutBuffer, "E01");
  343.             }
  344.           break;
  345.         case '?':
  346.           remcomOutBuffer[0] = 'S';
  347.           remcomOutBuffer[1] = hexchars[sigval >> 4];
  348.           remcomOutBuffer[2] = hexchars[sigval % 16];
  349.           remcomOutBuffer[3] = 0;
  350.           break;
  351.         case 'd':
  352.           remote_debug = !(remote_debug);        /* toggle debug flag */
  353.           break;
  354.         case 'g':                /* return the value of the CPU registers */
  355.           mem2hex ((unsigned char *) registers, remcomOutBuffer, NUMREGBYTES,
  356.                    0);
  357.           break;
  358.         case 'P':                /* set the value of a single CPU register - return OK */
  359.           {
  360.             int regno;

  361.             if (hexToInt (&ptr, &regno) && *ptr++ == '=')
  362.               if (regno >= 0 && regno < NUMREGS)
  363.                 {
  364.                   int stackmode;

  365.                   hex2mem (ptr, (unsigned char *) &registers[regno], 4, 0);
  366.                   /*
  367.                    * Since we just changed a single CPU register, let's
  368.                    * make sure to keep the several stack pointers consistant.
  369.                    */
  370.                   stackmode = registers[PSW] & 0x80;
  371.                   if (regno == R15)        /* stack pointer changed */
  372.                     {                /* need to change SPI or SPU */
  373.                       if (stackmode == 0)
  374.                         registers[SPI] = registers[R15];
  375.                       else
  376.                         registers[SPU] = registers[R15];
  377.                     }
  378.                   else if (regno == SPU)        /* "user" stack pointer changed */
  379.                     {
  380.                       if (stackmode != 0)        /* stack in user mode: copy SP */
  381.                         registers[R15] = registers[SPU];
  382.                     }
  383.                   else if (regno == SPI)        /* "interrupt" stack pointer changed */
  384.                     {
  385.                       if (stackmode == 0)        /* stack in interrupt mode: copy SP */
  386.                         registers[R15] = registers[SPI];
  387.                     }
  388.                   else if (regno == PSW)        /* stack mode may have changed! */
  389.                     {                /* force SP to either SPU or SPI */
  390.                       if (stackmode == 0)        /* stack in user mode */
  391.                         registers[R15] = registers[SPI];
  392.                       else        /* stack in interrupt mode */
  393.                         registers[R15] = registers[SPU];
  394.                     }
  395.                   strcpy (remcomOutBuffer, "OK");
  396.                   break;
  397.                 }
  398.             strcpy (remcomOutBuffer, "E01");
  399.             break;
  400.           }
  401.         case 'G':                /* set the value of the CPU registers - return OK */
  402.           hex2mem (ptr, (unsigned char *) registers, NUMREGBYTES, 0);
  403.           strcpy (remcomOutBuffer, "OK");
  404.           break;
  405.         case 's':                /* sAA..AA      Step one instruction from AA..AA(optional) */
  406.           stepping = 1;
  407.         case 'c':                /* cAA..AA      Continue from address AA..AA(optional) */
  408.           /* try to read optional parameter, pc unchanged if no parm */
  409.           if (hexToInt (&ptr, &addr))
  410.             registers[PC] = addr;

  411.           if (stepping)                /* single-stepping */
  412.             {
  413.               if (!prepare_to_step (0))        /* set up for single-step */
  414.                 {
  415.                   /* prepare_to_step has already emulated the target insn:
  416.                      Send SIGTRAP to gdb, don't resume the target at all.  */
  417.                   ptr = remcomOutBuffer;
  418.                   *ptr++ = 'T';        /* Simulate stopping with SIGTRAP */
  419.                   *ptr++ = '0';
  420.                   *ptr++ = '5';

  421.                   *ptr++ = hexchars[PC >> 4];        /* send PC */
  422.                   *ptr++ = hexchars[PC & 0xf];
  423.                   *ptr++ = ':';
  424.                   ptr = mem2hex ((unsigned char *) &registers[PC], ptr, 4, 0);
  425.                   *ptr++ = ';';

  426.                   *ptr++ = hexchars[R13 >> 4];        /* send FP */
  427.                   *ptr++ = hexchars[R13 & 0xf];
  428.                   *ptr++ = ':';
  429.                   ptr =
  430.                     mem2hex ((unsigned char *) &registers[R13], ptr, 4, 0);
  431.                   *ptr++ = ';';

  432.                   *ptr++ = hexchars[R15 >> 4];        /* send SP */
  433.                   *ptr++ = hexchars[R15 & 0xf];
  434.                   *ptr++ = ':';
  435.                   ptr =
  436.                     mem2hex ((unsigned char *) &registers[R15], ptr, 4, 0);
  437.                   *ptr++ = ';';
  438.                   *ptr++ = 0;

  439.                   break;
  440.                 }
  441.             }
  442.           else                        /* continuing, not single-stepping */
  443.             {
  444.               /* OK, about to do a "continue".  First check to see if the
  445.                  target pc is on an odd boundary (second instruction in the
  446.                  word).  If so, we must do a single-step first, because
  447.                  ya can't jump or return back to an odd boundary!  */
  448.               if ((registers[PC] & 2) != 0)
  449.                 prepare_to_step (1);
  450.             }

  451.           return;

  452.         case 'D':                /* Detach */
  453. #if 0
  454.           /* I am interpreting this to mean, release the board from control
  455.              by the remote stub.  To do this, I am restoring the original
  456.              (or at least previous) exception vectors.
  457.            */
  458.           for (i = 0; i < 18; i++)
  459.             exceptionHandler (i, save_vectors[i]);
  460.           putpacket ("OK");
  461.           return;                /* continue the inferior */
  462. #else
  463.           strcpy (remcomOutBuffer, "OK");
  464.           break;
  465. #endif
  466.         case 'q':
  467.           if (*ptr++ == 'C' &&
  468.               *ptr++ == 'R' && *ptr++ == 'C' && *ptr++ == ':')
  469.             {
  470.               unsigned long start, len, our_crc;

  471.               if (hexToInt (&ptr, (int *) &start) &&
  472.                   *ptr++ == ',' && hexToInt (&ptr, (int *) &len))
  473.                 {
  474.                   remcomOutBuffer[0] = 'C';
  475.                   our_crc = crc32 ((unsigned char *) start, len, 0xffffffff);
  476.                   mem2hex ((char *) &our_crc,
  477.                            &remcomOutBuffer[1], sizeof (long), 0);
  478.                 }                /* else do nothing */
  479.             }                        /* else do nothing */
  480.           break;

  481.         case 'k':                /* kill the program */
  482.           continue;
  483.         }                        /* switch */

  484.       /* reply to the request */
  485.       putpacket (remcomOutBuffer);
  486.     }
  487. }

  488. /* qCRC support */

  489. /* Table used by the crc32 function to calcuate the checksum. */
  490. static unsigned long crc32_table[256] = { 0, 0 };

  491. static unsigned long
  492. crc32 (unsigned char *buf, int len, unsigned long crc)
  493. {
  494.   if (!crc32_table[1])
  495.     {
  496.       /* Initialize the CRC table and the decoding table. */
  497.       int i, j;
  498.       unsigned long c;

  499.       for (i = 0; i < 256; i++)
  500.         {
  501.           for (c = i << 24, j = 8; j > 0; --j)
  502.             c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
  503.           crc32_table[i] = c;
  504.         }
  505.     }

  506.   while (len--)
  507.     {
  508.       crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
  509.       buf++;
  510.     }
  511.   return crc;
  512. }

  513. static int
  514. hex (unsigned char ch)
  515. {
  516.   if ((ch >= 'a') && (ch <= 'f'))
  517.     return (ch - 'a' + 10);
  518.   if ((ch >= '0') && (ch <= '9'))
  519.     return (ch - '0');
  520.   if ((ch >= 'A') && (ch <= 'F'))
  521.     return (ch - 'A' + 10);
  522.   return (-1);
  523. }

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

  525. unsigned char *
  526. getpacket (void)
  527. {
  528.   unsigned char *buffer = &remcomInBuffer[0];
  529.   unsigned char checksum;
  530.   unsigned char xmitcsum;
  531.   int count;
  532.   char ch;

  533.   while (1)
  534.     {
  535.       /* wait around for the start character, ignore all other characters */
  536.       while ((ch = getDebugChar ()) != '$')
  537.         ;

  538.     retry:
  539.       checksum = 0;
  540.       xmitcsum = -1;
  541.       count = 0;

  542.       /* now, read until a # or end of buffer is found */
  543.       while (count < BUFMAX - 1)
  544.         {
  545.           ch = getDebugChar ();
  546.           if (ch == '$')
  547.             goto retry;
  548.           if (ch == '#')
  549.             break;
  550.           checksum = checksum + ch;
  551.           buffer[count] = ch;
  552.           count = count + 1;
  553.         }
  554.       buffer[count] = 0;

  555.       if (ch == '#')
  556.         {
  557.           ch = getDebugChar ();
  558.           xmitcsum = hex (ch) << 4;
  559.           ch = getDebugChar ();
  560.           xmitcsum += hex (ch);

  561.           if (checksum != xmitcsum)
  562.             {
  563.               if (remote_debug)
  564.                 {
  565.                   unsigned char buf[16];

  566.                   mem2hex ((unsigned char *) &checksum, buf, 4, 0);
  567.                   gdb_error ("Bad checksum: my count = %s, ", buf);
  568.                   mem2hex ((unsigned char *) &xmitcsum, buf, 4, 0);
  569.                   gdb_error ("sent count = %s\n", buf);
  570.                   gdb_error (" -- Bad buffer: \"%s\"\n", buffer);
  571.                 }
  572.               putDebugChar ('-');        /* failed checksum */
  573.             }
  574.           else
  575.             {
  576.               putDebugChar ('+');        /* successful transfer */

  577.               /* if a sequence char is present, reply the sequence ID */
  578.               if (buffer[2] == ':')
  579.                 {
  580.                   putDebugChar (buffer[0]);
  581.                   putDebugChar (buffer[1]);

  582.                   return &buffer[3];
  583.                 }

  584.               return &buffer[0];
  585.             }
  586.         }
  587.     }
  588. }

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

  590. static void
  591. putpacket (unsigned char *buffer)
  592. {
  593.   unsigned char checksum;
  594.   int count;
  595.   char ch;

  596.   /*  $<packet info>#<checksum>. */
  597.   do
  598.     {
  599.       putDebugChar ('$');
  600.       checksum = 0;
  601.       count = 0;

  602.       while (ch = buffer[count])
  603.         {
  604.           putDebugChar (ch);
  605.           checksum += ch;
  606.           count += 1;
  607.         }
  608.       putDebugChar ('#');
  609.       putDebugChar (hexchars[checksum >> 4]);
  610.       putDebugChar (hexchars[checksum % 16]);
  611.     }
  612.   while (getDebugChar () != '+');
  613. }

  614. /* Address of a routine to RTE to if we get a memory fault.  */

  615. static void (*volatile mem_fault_routine) () = 0;

  616. static void
  617. set_mem_err (void)
  618. {
  619.   mem_err = 1;
  620. }

  621. /* Check the address for safe access ranges.  As currently defined,
  622.    this routine will reject the "expansion bus" address range(s).
  623.    To make those ranges useable, someone must implement code to detect
  624.    whether there's anything connected to the expansion bus. */

  625. static int
  626. mem_safe (unsigned char *addr)
  627. {
  628. #define BAD_RANGE_ONE_START        ((unsigned char *) 0x600000)
  629. #define BAD_RANGE_ONE_END        ((unsigned char *) 0xa00000)
  630. #define BAD_RANGE_TWO_START        ((unsigned char *) 0xff680000)
  631. #define BAD_RANGE_TWO_END        ((unsigned char *) 0xff800000)

  632.   if (addr < BAD_RANGE_ONE_START)
  633.     return 1;                        /* safe */
  634.   if (addr < BAD_RANGE_ONE_END)
  635.     return 0;                        /* unsafe */
  636.   if (addr < BAD_RANGE_TWO_START)
  637.     return 1;                        /* safe */
  638.   if (addr < BAD_RANGE_TWO_END)
  639.     return 0;                        /* unsafe */
  640. }

  641. /* These are separate functions so that they are so short and sweet
  642.    that the compiler won't save any registers (if there is a fault
  643.    to mem_fault, they won't get restored, so there better not be any
  644.    saved).  */
  645. static int
  646. get_char (unsigned char *addr)
  647. {
  648. #if 1
  649.   if (mem_fault_routine && !mem_safe (addr))
  650.     {
  651.       mem_fault_routine ();
  652.       return 0;
  653.     }
  654. #endif
  655.   return *addr;
  656. }

  657. static void
  658. set_char (unsigned char *addr, unsigned char val)
  659. {
  660. #if 1
  661.   if (mem_fault_routine && !mem_safe (addr))
  662.     {
  663.       mem_fault_routine ();
  664.       return;
  665.     }
  666. #endif
  667.   *addr = val;
  668. }

  669. /* Convert the memory pointed to by mem into hex, placing result in buf.
  670.    Return a pointer to the last char put in buf (null).
  671.    If MAY_FAULT is non-zero, then we should set mem_err in response to
  672.    a fault; if zero treat a fault like any other fault in the stub.  */

  673. static unsigned char *
  674. mem2hex (unsigned char *mem, unsigned char *buf, int count, int may_fault)
  675. {
  676.   int i;
  677.   unsigned char ch;

  678.   if (may_fault)
  679.     mem_fault_routine = set_mem_err;
  680.   for (i = 0; i < count; i++)
  681.     {
  682.       ch = get_char (mem++);
  683.       if (may_fault && mem_err)
  684.         return (buf);
  685.       *buf++ = hexchars[ch >> 4];
  686.       *buf++ = hexchars[ch % 16];
  687.     }
  688.   *buf = 0;
  689.   if (may_fault)
  690.     mem_fault_routine = 0;
  691.   return (buf);
  692. }

  693. /* Convert the hex array pointed to by buf into binary to be placed in mem.
  694.    Return a pointer to the character AFTER the last byte written. */

  695. static unsigned char *
  696. hex2mem (unsigned char *buf, unsigned char *mem, int count, int may_fault)
  697. {
  698.   int i;
  699.   unsigned char ch;

  700.   if (may_fault)
  701.     mem_fault_routine = set_mem_err;
  702.   for (i = 0; i < count; i++)
  703.     {
  704.       ch = hex (*buf++) << 4;
  705.       ch = ch + hex (*buf++);
  706.       set_char (mem++, ch);
  707.       if (may_fault && mem_err)
  708.         return (mem);
  709.     }
  710.   if (may_fault)
  711.     mem_fault_routine = 0;
  712.   return (mem);
  713. }

  714. /* Convert the binary stream in BUF to memory.

  715.    Gdb will escape $, #, and the escape char (0x7d).
  716.    COUNT is the total number of bytes to write into
  717.    memory. */
  718. static unsigned char *
  719. bin2mem (unsigned char *buf, unsigned char *mem, int count, int may_fault)
  720. {
  721.   int i;
  722.   unsigned char ch;

  723.   if (may_fault)
  724.     mem_fault_routine = set_mem_err;
  725.   for (i = 0; i < count; i++)
  726.     {
  727.       /* Check for any escaped characters. Be paranoid and
  728.          only unescape chars that should be escaped. */
  729.       if (*buf == 0x7d)
  730.         {
  731.           switch (*(buf + 1))
  732.             {
  733.             case 0x3:                /* # */
  734.             case 0x4:                /* $ */
  735.             case 0x5d:                /* escape char */
  736.               buf++;
  737.               *buf |= 0x20;
  738.               break;
  739.             default:
  740.               /* nothing */
  741.               break;
  742.             }
  743.         }

  744.       set_char (mem++, *buf++);

  745.       if (may_fault && mem_err)
  746.         return mem;
  747.     }

  748.   if (may_fault)
  749.     mem_fault_routine = 0;
  750.   return mem;
  751. }

  752. /* this function takes the m32r exception vector and attempts to
  753.    translate this number into a unix compatible signal value */

  754. static int
  755. computeSignal (int exceptionVector)
  756. {
  757.   int sigval;
  758.   switch (exceptionVector)
  759.     {
  760.     case 0:
  761.       sigval = 23;
  762.       break;                        /* I/O trap                    */
  763.     case 1:
  764.       sigval = 5;
  765.       break;                        /* breakpoint                  */
  766.     case 2:
  767.       sigval = 5;
  768.       break;                        /* breakpoint                  */
  769.     case 3:
  770.       sigval = 5;
  771.       break;                        /* breakpoint                  */
  772.     case 4:
  773.       sigval = 5;
  774.       break;                        /* breakpoint                  */
  775.     case 5:
  776.       sigval = 5;
  777.       break;                        /* breakpoint                  */
  778.     case 6:
  779.       sigval = 5;
  780.       break;                        /* breakpoint                  */
  781.     case 7:
  782.       sigval = 5;
  783.       break;                        /* breakpoint                  */
  784.     case 8:
  785.       sigval = 5;
  786.       break;                        /* breakpoint                  */
  787.     case 9:
  788.       sigval = 5;
  789.       break;                        /* breakpoint                  */
  790.     case 10:
  791.       sigval = 5;
  792.       break;                        /* breakpoint                  */
  793.     case 11:
  794.       sigval = 5;
  795.       break;                        /* breakpoint                  */
  796.     case 12:
  797.       sigval = 5;
  798.       break;                        /* breakpoint                  */
  799.     case 13:
  800.       sigval = 5;
  801.       break;                        /* breakpoint                  */
  802.     case 14:
  803.       sigval = 5;
  804.       break;                        /* breakpoint                  */
  805.     case 15:
  806.       sigval = 5;
  807.       break;                        /* breakpoint                  */
  808.     case 16:
  809.       sigval = 10;
  810.       break;                        /* BUS ERROR (alignment)       */
  811.     case 17:
  812.       sigval = 2;
  813.       break;                        /* INTerrupt                   */
  814.     default:
  815.       sigval = 7;
  816.       break;                        /* "software generated"        */
  817.     }
  818.   return (sigval);
  819. }

  820. /**********************************************/
  821. /* WHILE WE FIND NICE HEX CHARS, BUILD AN INT */
  822. /* RETURN NUMBER OF CHARS PROCESSED           */
  823. /**********************************************/
  824. static int
  825. hexToInt (unsigned char **ptr, int *intValue)
  826. {
  827.   int numChars = 0;
  828.   int hexValue;

  829.   *intValue = 0;
  830.   while (**ptr)
  831.     {
  832.       hexValue = hex (**ptr);
  833.       if (hexValue >= 0)
  834.         {
  835.           *intValue = (*intValue << 4) | hexValue;
  836.           numChars++;
  837.         }
  838.       else
  839.         break;
  840.       (*ptr)++;
  841.     }
  842.   return (numChars);
  843. }

  844. /*
  845.   Table of branch instructions:

  846.   10B6                RTE        return from trap or exception
  847.   1FCr                JMP        jump
  848.   1ECr                JL        jump and link
  849.   7Fxx                BRA        branch
  850.   FFxxxxxx        BRA        branch (long)
  851.   B09rxxxx        BNEZ        branch not-equal-zero
  852.   Br1rxxxx        BNE        branch not-equal
  853.   7Dxx                BNC        branch not-condition
  854.   FDxxxxxx        BNC        branch not-condition (long)
  855.   B0Arxxxx        BLTZ        branch less-than-zero
  856.   B0Crxxxx        BLEZ        branch less-equal-zero
  857.   7Exx                BL        branch and link
  858.   FExxxxxx        BL        branch and link (long)
  859.   B0Drxxxx        BGTZ        branch greater-than-zero
  860.   B0Brxxxx        BGEZ        branch greater-equal-zero
  861.   B08rxxxx        BEQZ        branch equal-zero
  862.   Br0rxxxx        BEQ        branch equal
  863.   7Cxx                BC        branch condition
  864.   FCxxxxxx        BC        branch condition (long)
  865.   */

  866. static int
  867. isShortBranch (unsigned char *instr)
  868. {
  869.   unsigned char instr0 = instr[0] & 0x7F;        /* mask off high bit */

  870.   if (instr0 == 0x10 && instr[1] == 0xB6)        /* RTE */
  871.     return 1;                        /* return from trap or exception */

  872.   if (instr0 == 0x1E || instr0 == 0x1F)        /* JL or JMP */
  873.     if ((instr[1] & 0xF0) == 0xC0)
  874.       return 2;                        /* jump thru a register */

  875.   if (instr0 == 0x7C || instr0 == 0x7D ||        /* BC, BNC, BL, BRA */
  876.       instr0 == 0x7E || instr0 == 0x7F)
  877.     return 3;                        /* eight bit PC offset */

  878.   return 0;
  879. }

  880. static int
  881. isLongBranch (unsigned char *instr)
  882. {
  883.   if (instr[0] == 0xFC || instr[0] == 0xFD ||        /* BRA, BNC, BL, BC */
  884.       instr[0] == 0xFE || instr[0] == 0xFF)        /* 24 bit relative */
  885.     return 4;
  886.   if ((instr[0] & 0xF0) == 0xB0)        /* 16 bit relative */
  887.     {
  888.       if ((instr[1] & 0xF0) == 0x00 ||        /* BNE, BEQ */
  889.           (instr[1] & 0xF0) == 0x10)
  890.         return 5;
  891.       if (instr[0] == 0xB0)        /* BNEZ, BLTZ, BLEZ, BGTZ, BGEZ, BEQZ */
  892.         if ((instr[1] & 0xF0) == 0x80 || (instr[1] & 0xF0) == 0x90 ||
  893.             (instr[1] & 0xF0) == 0xA0 || (instr[1] & 0xF0) == 0xB0 ||
  894.             (instr[1] & 0xF0) == 0xC0 || (instr[1] & 0xF0) == 0xD0)
  895.           return 6;
  896.     }
  897.   return 0;
  898. }

  899. /* if address is NOT on a 4-byte boundary, or high-bit of instr is zero,
  900.    then it's a 2-byte instruction, else it's a 4-byte instruction.  */

  901. #define INSTRUCTION_SIZE(addr) \
  902.     ((((int) addr & 2) || (((unsigned char *) addr)[0] & 0x80) == 0) ? 2 : 4)

  903. static int
  904. isBranch (unsigned char *instr)
  905. {
  906.   if (INSTRUCTION_SIZE (instr) == 2)
  907.     return isShortBranch (instr);
  908.   else
  909.     return isLongBranch (instr);
  910. }

  911. static int
  912. willBranch (unsigned char *instr, int branchCode)
  913. {
  914.   switch (branchCode)
  915.     {
  916.     case 0:
  917.       return 0;                        /* not a branch */
  918.     case 1:
  919.       return 1;                        /* RTE */
  920.     case 2:
  921.       return 1;                        /* JL or JMP    */
  922.     case 3:                        /* BC, BNC, BL, BRA (short) */
  923.     case 4:                        /* BC, BNC, BL, BRA (long) */
  924.       switch (instr[0] & 0x0F)
  925.         {
  926.         case 0xC:                /* Branch if Condition Register */
  927.           return (registers[CBR] != 0);
  928.         case 0xD:                /* Branch if NOT Condition Register */
  929.           return (registers[CBR] == 0);
  930.         case 0xE:                /* Branch and Link */
  931.         case 0xF:                /* Branch (unconditional) */
  932.           return 1;
  933.         default:                /* oops? */
  934.           return 0;
  935.         }
  936.     case 5:                        /* BNE, BEQ */
  937.       switch (instr[1] & 0xF0)
  938.         {
  939.         case 0x00:                /* Branch if r1 equal to r2 */
  940.           return (registers[instr[0] & 0x0F] == registers[instr[1] & 0x0F]);
  941.         case 0x10:                /* Branch if r1 NOT equal to r2 */
  942.           return (registers[instr[0] & 0x0F] != registers[instr[1] & 0x0F]);
  943.         default:                /* oops? */
  944.           return 0;
  945.         }
  946.     case 6:                        /* BNEZ, BLTZ, BLEZ, BGTZ, BGEZ ,BEQZ */
  947.       switch (instr[1] & 0xF0)
  948.         {
  949.         case 0x80:                /* Branch if reg equal to zero */
  950.           return (registers[instr[1] & 0x0F] == 0);
  951.         case 0x90:                /* Branch if reg NOT equal to zero */
  952.           return (registers[instr[1] & 0x0F] != 0);
  953.         case 0xA0:                /* Branch if reg less than zero */
  954.           return (registers[instr[1] & 0x0F] < 0);
  955.         case 0xB0:                /* Branch if reg greater or equal to zero */
  956.           return (registers[instr[1] & 0x0F] >= 0);
  957.         case 0xC0:                /* Branch if reg less than or equal to zero */
  958.           return (registers[instr[1] & 0x0F] <= 0);
  959.         case 0xD0:                /* Branch if reg greater than zero */
  960.           return (registers[instr[1] & 0x0F] > 0);
  961.         default:                /* oops? */
  962.           return 0;
  963.         }
  964.     default:                        /* oops? */
  965.       return 0;
  966.     }
  967. }

  968. static int
  969. branchDestination (unsigned char *instr, int branchCode)
  970. {
  971.   switch (branchCode)
  972.     {
  973.     default:
  974.     case 0:                        /* not a branch */
  975.       return 0;
  976.     case 1:                        /* RTE */
  977.       return registers[BPC] & ~3;        /* pop BPC into PC */
  978.     case 2:                        /* JL or JMP */
  979.       return registers[instr[1] & 0x0F] & ~3;        /* jump thru a register */
  980.     case 3:                        /* BC, BNC, BL, BRA (short, 8-bit relative offset) */
  981.       return (((int) instr) & ~3) + ((char) instr[1] << 2);
  982.     case 4:                        /* BC, BNC, BL, BRA (long, 24-bit relative offset) */
  983.       return ((int) instr +
  984.               ((((char) instr[1] << 16) | (instr[2] << 8) | (instr[3])) <<
  985.                2));
  986.     case 5:                        /* BNE, BEQ (16-bit relative offset) */
  987.     case 6:                        /* BNEZ, BLTZ, BLEZ, BGTZ, BGEZ ,BEQZ (ditto) */
  988.       return ((int) instr + ((((char) instr[2] << 8) | (instr[3])) << 2));
  989.     }

  990.   /* An explanatory note: in the last three return expressions, I have
  991.      cast the most-significant byte of the return offset to char.
  992.      What this accomplishes is sign extension.  If the other
  993.      less-significant bytes were signed as well, they would get sign
  994.      extended too and, if negative, their leading bits would clobber
  995.      the bits of the more-significant bytes ahead of them.  There are
  996.      other ways I could have done this, but sign extension from
  997.      odd-sized integers is always a pain. */
  998. }

  999. static void
  1000. branchSideEffects (unsigned char *instr, int branchCode)
  1001. {
  1002.   switch (branchCode)
  1003.     {
  1004.     case 1:                        /* RTE */
  1005.       return;                        /* I <THINK> this is already handled... */
  1006.     case 2:                        /* JL (or JMP) */
  1007.     case 3:                        /* BL (or BC, BNC, BRA) */
  1008.     case 4:
  1009.       if ((instr[0] & 0x0F) == 0x0E)        /* branch/jump and link */
  1010.         registers[R14] = (registers[PC] & ~3) + 4;
  1011.       return;
  1012.     default:                        /* any other branch has no side effects */
  1013.       return;
  1014.     }
  1015. }

  1016. static struct STEPPING_CONTEXT
  1017. {
  1018.   int stepping;                        /* true when we've started a single-step */
  1019.   unsigned long target_addr;        /* the instr we're trying to execute */
  1020.   unsigned long target_size;        /* the size of the target instr */
  1021.   unsigned long noop_addr;        /* where we've inserted a no-op, if any */
  1022.   unsigned long trap1_addr;        /* the trap following the target instr */
  1023.   unsigned long trap2_addr;        /* the trap at a branch destination, if any */
  1024.   unsigned short noop_save;        /* instruction overwritten by our no-op */
  1025.   unsigned short trap1_save;        /* instruction overwritten by trap1 */
  1026.   unsigned short trap2_save;        /* instruction overwritten by trap2 */
  1027.   unsigned short continue_p;        /* true if NOT returning to gdb after step */
  1028. } stepping;

  1029. /* Function: prepare_to_step
  1030.    Called from handle_exception to prepare the user program to single-step.
  1031.    Places a trap instruction after the target instruction, with special
  1032.    extra handling for branch instructions and for instructions in the
  1033.    second half-word of a word.

  1034.    Returns: True  if we should actually execute the instruction;
  1035.             False if we are going to emulate executing the instruction,
  1036.             in which case we simply report to GDB that the instruction
  1037.             has already been executed.  */

  1038. #define TRAP1  0x10f1;                /* trap #1 instruction */
  1039. #define NOOP   0x7000;                /* noop    instruction */

  1040. static unsigned short trap1 = TRAP1;
  1041. static unsigned short noop = NOOP;

  1042. static int
  1043. prepare_to_step (continue_p)
  1044.      int continue_p;                /* if this isn't REALLY a single-step (see below) */
  1045. {
  1046.   unsigned long pc = registers[PC];
  1047.   int branchCode = isBranch ((unsigned char *) pc);
  1048.   unsigned char *p;

  1049.   /* zero out the stepping context
  1050.      (paranoia -- it should already be zeroed) */
  1051.   for (p = (unsigned char *) &stepping;
  1052.        p < ((unsigned char *) &stepping) + sizeof (stepping); p++)
  1053.     *p = 0;

  1054.   if (branchCode != 0)                /* next instruction is a branch */
  1055.     {
  1056.       branchSideEffects ((unsigned char *) pc, branchCode);
  1057.       if (willBranch ((unsigned char *) pc, branchCode))
  1058.         registers[PC] = branchDestination ((unsigned char *) pc, branchCode);
  1059.       else
  1060.         registers[PC] = pc + INSTRUCTION_SIZE (pc);
  1061.       return 0;                        /* branch "executed" -- just notify GDB */
  1062.     }
  1063.   else if (((int) pc & 2) != 0)        /* "second-slot" instruction */
  1064.     {
  1065.       /* insert no-op before pc */
  1066.       stepping.noop_addr = pc - 2;
  1067.       stepping.noop_save = *(unsigned short *) stepping.noop_addr;
  1068.       *(unsigned short *) stepping.noop_addr = noop;
  1069.       /* insert trap  after  pc */
  1070.       stepping.trap1_addr = pc + 2;
  1071.       stepping.trap1_save = *(unsigned short *) stepping.trap1_addr;
  1072.       *(unsigned short *) stepping.trap1_addr = trap1;
  1073.     }
  1074.   else                                /* "first-slot" instruction */
  1075.     {
  1076.       /* insert trap  after  pc */
  1077.       stepping.trap1_addr = pc + INSTRUCTION_SIZE (pc);
  1078.       stepping.trap1_save = *(unsigned short *) stepping.trap1_addr;
  1079.       *(unsigned short *) stepping.trap1_addr = trap1;
  1080.     }
  1081.   /* "continue_p" means that we are actually doing a continue, and not
  1082.      being requested to single-step by GDB.  Sometimes we have to do
  1083.      one single-step before continuing, because the PC is on a half-word
  1084.      boundary.  There's no way to simply resume at such an address.  */
  1085.   stepping.continue_p = continue_p;
  1086.   stepping.stepping = 1;        /* starting a single-step */
  1087.   return 1;
  1088. }

  1089. /* Function: finish_from_step
  1090.    Called from handle_exception to finish up when the user program
  1091.    returns from a single-step.  Replaces the instructions that had
  1092.    been overwritten by traps or no-ops,

  1093.    Returns: True  if we should notify GDB that the target stopped.
  1094.             False if we only single-stepped because we had to before we
  1095.             could continue (ie. we were trying to continue at a
  1096.             half-word boundary).  In that case don't notify GDB:
  1097.             just "continue continuing".  */

  1098. static int
  1099. finish_from_step (void)
  1100. {
  1101.   if (stepping.stepping)        /* anything to do? */
  1102.     {
  1103.       int continue_p = stepping.continue_p;
  1104.       unsigned char *p;

  1105.       if (stepping.noop_addr)        /* replace instr "under" our no-op */
  1106.         *(unsigned short *) stepping.noop_addr = stepping.noop_save;
  1107.       if (stepping.trap1_addr)        /* replace instr "under" our trap  */
  1108.         *(unsigned short *) stepping.trap1_addr = stepping.trap1_save;
  1109.       if (stepping.trap2_addr)        /* ditto our other trap, if any    */
  1110.         *(unsigned short *) stepping.trap2_addr = stepping.trap2_save;

  1111.       for (p = (unsigned char *) &stepping;        /* zero out the stepping context */
  1112.            p < ((unsigned char *) &stepping) + sizeof (stepping); p++)
  1113.         *p = 0;

  1114.       return !(continue_p);
  1115.     }
  1116.   else                                /* we didn't single-step, therefore this must be a legitimate stop */
  1117.     return 1;
  1118. }

  1119. struct PSWreg
  1120. {                                /* separate out the bit flags in the PSW register */
  1121.   int pad1:16;
  1122.   int bsm:1;
  1123.   int bie:1;
  1124.   int pad2:5;
  1125.   int bc:1;
  1126.   int sm:1;
  1127.   int ie:1;
  1128.   int pad3:5;
  1129.   int c:1;
  1130. } *psw;

  1131. /* Upon entry the value for LR to save has been pushed.
  1132.    We unpush that so that the value for the stack pointer saved is correct.
  1133.    Upon entry, all other registers are assumed to have not been modified
  1134.    since the interrupt/trap occured.  */

  1135. asm ("\n\
  1136. stash_registers:\n\
  1137.         push r0\n\
  1138.         push r1\n\
  1139.         seth r1, #shigh(registers)\n\
  1140.         add3 r1, r1, #low(registers)\n\
  1141.         pop r0                ; r1\n\
  1142.         st r0, @(4,r1)\n\
  1143.         pop r0                ; r0\n\
  1144.         st r0, @r1\n\
  1145.         addi r1, #4        ; only add 4 as subsequent saves are `pre inc'\n\
  1146.         st r2, @+r1\n\
  1147.         st r3, @+r1\n\
  1148.         st r4, @+r1\n\
  1149.         st r5, @+r1\n\
  1150.         st r6, @+r1\n\
  1151.         st r7, @+r1\n\
  1152.         st r8, @+r1\n\
  1153.         st r9, @+r1\n\
  1154.         st r10, @+r1\n\
  1155.         st r11, @+r1\n\
  1156.         st r12, @+r1\n\
  1157.         st r13, @+r1    ; fp\n\
  1158.         pop r0                ; lr (r14)\n\
  1159.         st r0, @+r1\n\
  1160.         st sp, @+r1        ; sp contains right value at this point\n\
  1161.         mvfc r0, cr0\n\
  1162.         st r0, @+r1        ; cr0 == PSW\n\
  1163.         mvfc r0, cr1\n\
  1164.         st r0, @+r1        ; cr1 == CBR\n\
  1165.         mvfc r0, cr2\n\
  1166.         st r0, @+r1        ; cr2 == SPI\n\
  1167.         mvfc r0, cr3\n\
  1168.         st r0, @+r1        ; cr3 == SPU\n\
  1169.         mvfc r0, cr6\n\
  1170.         st r0, @+r1        ; cr6 == BPC\n\
  1171.         st r0, @+r1        ; PC  == BPC\n\
  1172.         mvfaclo r0\n\
  1173.         st r0, @+r1        ; ACCL\n\
  1174.         mvfachi r0\n\
  1175.         st r0, @+r1        ; ACCH\n\
  1176.         jmp lr");

  1177. /* C routine to clean up what stash_registers did.
  1178.    It is called after calling stash_registers.
  1179.    This is separate from stash_registers as we want to do this in C
  1180.    but doing stash_registers in C isn't straightforward.  */

  1181. static void
  1182. cleanup_stash (void)
  1183. {
  1184.   psw = (struct PSWreg *) &registers[PSW];        /* fields of PSW register */
  1185.   psw->sm = psw->bsm;                /* fix up pre-trap values of psw fields */
  1186.   psw->ie = psw->bie;
  1187.   psw->c = psw->bc;
  1188.   registers[CBR] = psw->bc;        /* fix up pre-trap "C" register */

  1189. #if 0                                /* FIXME: Was in previous version.  Necessary?
  1190.                                    (Remember that we use the "rte" insn to return from the
  1191.                                    trap/interrupt so the values of bsm, bie, bc are important.  */
  1192.   psw->bsm = psw->bie = psw->bc = 0;        /* zero post-trap values */
  1193. #endif

  1194.   /* FIXME: Copied from previous version.  This can probably be deleted
  1195.      since methinks stash_registers has already done this.  */
  1196.   registers[PC] = registers[BPC];        /* pre-trap PC */

  1197.   /* FIXME: Copied from previous version.  Necessary?  */
  1198.   if (psw->sm)                        /* copy R15 into (psw->sm ? SPU : SPI) */
  1199.     registers[SPU] = registers[R15];
  1200.   else
  1201.     registers[SPI] = registers[R15];
  1202. }

  1203. asm ("\n\
  1204. restore_and_return:\n\
  1205.         seth r0, #shigh(registers+8)\n\
  1206.         add3 r0, r0, #low(registers+8)\n\
  1207.         ld r2, @r0+        ; restore r2\n\
  1208.         ld r3, @r0+        ; restore r3\n\
  1209.         ld r4, @r0+        ; restore r4\n\
  1210.         ld r5, @r0+        ; restore r5\n\
  1211.         ld r6, @r0+        ; restore r6\n\
  1212.         ld r7, @r0+        ; restore r7\n\
  1213.         ld r8, @r0+        ; restore r8\n\
  1214.         ld r9, @r0+        ; restore r9\n\
  1215.         ld r10, @r0+        ; restore r10\n\
  1216.         ld r11, @r0+        ; restore r11\n\
  1217.         ld r12, @r0+        ; restore r12\n\
  1218.         ld r13, @r0+        ; restore r13\n\
  1219.         ld r14, @r0+        ; restore r14\n\
  1220.         ld r15, @r0+        ; restore r15\n\
  1221.         ld r1, @r0+        ; restore cr0 == PSW\n\
  1222.         mvtc r1, cr0\n\
  1223.         ld r1, @r0+        ; restore cr1 == CBR (no-op, because it's read only)\n\
  1224.         mvtc r1, cr1\n\
  1225.         ld r1, @r0+        ; restore cr2 == SPI\n\
  1226.         mvtc r1, cr2\n\
  1227.         ld r1, @r0+        ; restore cr3 == SPU\n\
  1228.         mvtc r1, cr3\n\
  1229.         addi r0, #4        ; skip BPC\n\
  1230.         ld r1, @r0+        ; restore cr6 (BPC) == PC\n\
  1231.         mvtc r1, cr6\n\
  1232.         ld r1, @r0+        ; restore ACCL\n\
  1233.         mvtaclo r1\n\
  1234.         ld r1, @r0+        ; restore ACCH\n\
  1235.         mvtachi r1\n\
  1236.         seth r0, #shigh(registers)\n\
  1237.         add3 r0, r0, #low(registers)\n\
  1238.         ld r1, @(4,r0)        ; restore r1\n\
  1239.         ld r0, @r0        ; restore r0\n\
  1240.         rte");

  1241. /* General trap handler, called after the registers have been stashed.
  1242.    NUM is the trap/exception number.  */

  1243. static void
  1244. process_exception (int num)
  1245. {
  1246.   cleanup_stash ();
  1247.   asm volatile ("\n\
  1248.         seth r1, #shigh(stackPtr)\n\
  1249.         add3 r1, r1, #low(stackPtr)\n\
  1250.         ld r15, @r1                ; setup local stack (protect user stack)\n\
  1251.         mv r0, %0\n\
  1252.         bl handle_exception\n\
  1253.         bl restore_and_return"::"r" (num):"r0", "r1");
  1254. }

  1255. void _catchException0 ();

  1256. asm ("\n\
  1257. _catchException0:\n\
  1258.         push lr\n\
  1259.         bl stash_registers\n\
  1260.         ; Note that at this point the pushed value of `lr' has been popped\n\
  1261.         ldi r0, #0\n\
  1262.         bl process_exception");

  1263. void _catchException1 ();

  1264. asm ("\n\
  1265. _catchException1:\n\
  1266.         push lr\n\
  1267.         bl stash_registers\n\
  1268.         ; Note that at this point the pushed value of `lr' has been popped\n\
  1269.         bl cleanup_stash\n\
  1270.         seth r1, #shigh(stackPtr)\n\
  1271.         add3 r1, r1, #low(stackPtr)\n\
  1272.         ld r15, @r1                ; setup local stack (protect user stack)\n\
  1273.         seth r1, #shigh(registers + 21*4) ; PC\n\
  1274.         add3 r1, r1, #low(registers + 21*4)\n\
  1275.         ld r0, @r1\n\
  1276.         addi r0, #-4                ; back up PC for breakpoint trap.\n\
  1277.         st r0, @r1                ; FIXME: what about bp in right slot?\n\
  1278.         ldi r0, #1\n\
  1279.         bl handle_exception\n\
  1280.         bl restore_and_return");

  1281. void _catchException2 ();

  1282. asm ("\n\
  1283. _catchException2:\n\
  1284.         push lr\n\
  1285.         bl stash_registers\n\
  1286.         ; Note that at this point the pushed value of `lr' has been popped\n\
  1287.         ldi r0, #2\n\
  1288.         bl process_exception");

  1289. void _catchException3 ();

  1290. asm ("\n\
  1291. _catchException3:\n\
  1292.         push lr\n\
  1293.         bl stash_registers\n\
  1294.         ; Note that at this point the pushed value of `lr' has been popped\n\
  1295.         ldi r0, #3\n\
  1296.         bl process_exception");

  1297. void _catchException4 ();

  1298. asm ("\n\
  1299. _catchException4:\n\
  1300.         push lr\n\
  1301.         bl stash_registers\n\
  1302.         ; Note that at this point the pushed value of `lr' has been popped\n\
  1303.         ldi r0, #4\n\
  1304.         bl process_exception");

  1305. void _catchException5 ();

  1306. asm ("\n\
  1307. _catchException5:\n\
  1308.         push lr\n\
  1309.         bl stash_registers\n\
  1310.         ; Note that at this point the pushed value of `lr' has been popped\n\
  1311.         ldi r0, #5\n\
  1312.         bl process_exception");

  1313. void _catchException6 ();

  1314. asm ("\n\
  1315. _catchException6:\n\
  1316.         push lr\n\
  1317.         bl stash_registers\n\
  1318.         ; Note that at this point the pushed value of `lr' has been popped\n\
  1319.         ldi r0, #6\n\
  1320.         bl process_exception");

  1321. void _catchException7 ();

  1322. asm ("\n\
  1323. _catchException7:\n\
  1324.         push lr\n\
  1325.         bl stash_registers\n\
  1326.         ; Note that at this point the pushed value of `lr' has been popped\n\
  1327.         ldi r0, #7\n\
  1328.         bl process_exception");

  1329. void _catchException8 ();

  1330. asm ("\n\
  1331. _catchException8:\n\
  1332.         push lr\n\
  1333.         bl stash_registers\n\
  1334.         ; Note that at this point the pushed value of `lr' has been popped\n\
  1335.         ldi r0, #8\n\
  1336.         bl process_exception");

  1337. void _catchException9 ();

  1338. asm ("\n\
  1339. _catchException9:\n\
  1340.         push lr\n\
  1341.         bl stash_registers\n\
  1342.         ; Note that at this point the pushed value of `lr' has been popped\n\
  1343.         ldi r0, #9\n\
  1344.         bl process_exception");

  1345. void _catchException10 ();

  1346. asm ("\n\
  1347. _catchException10:\n\
  1348.         push lr\n\
  1349.         bl stash_registers\n\
  1350.         ; Note that at this point the pushed value of `lr' has been popped\n\
  1351.         ldi r0, #10\n\
  1352.         bl process_exception");

  1353. void _catchException11 ();

  1354. asm ("\n\
  1355. _catchException11:\n\
  1356.         push lr\n\
  1357.         bl stash_registers\n\
  1358.         ; Note that at this point the pushed value of `lr' has been popped\n\
  1359.         ldi r0, #11\n\
  1360.         bl process_exception");

  1361. void _catchException12 ();

  1362. asm ("\n\
  1363. _catchException12:\n\
  1364.         push lr\n\
  1365.         bl stash_registers\n\
  1366.         ; Note that at this point the pushed value of `lr' has been popped\n\
  1367.         ldi r0, #12\n\
  1368.         bl process_exception");

  1369. void _catchException13 ();

  1370. asm ("\n\
  1371. _catchException13:\n\
  1372.         push lr\n\
  1373.         bl stash_registers\n\
  1374.         ; Note that at this point the pushed value of `lr' has been popped\n\
  1375.         ldi r0, #13\n\
  1376.         bl process_exception");

  1377. void _catchException14 ();

  1378. asm ("\n\
  1379. _catchException14:\n\
  1380.         push lr\n\
  1381.         bl stash_registers\n\
  1382.         ; Note that at this point the pushed value of `lr' has been popped\n\
  1383.         ldi r0, #14\n\
  1384.         bl process_exception");

  1385. void _catchException15 ();

  1386. asm ("\n\
  1387. _catchException15:\n\
  1388.         push lr\n\
  1389.         bl stash_registers\n\
  1390.         ; Note that at this point the pushed value of `lr' has been popped\n\
  1391.         ldi r0, #15\n\
  1392.         bl process_exception");

  1393. void _catchException16 ();

  1394. asm ("\n\
  1395. _catchException16:\n\
  1396.         push lr\n\
  1397.         bl stash_registers\n\
  1398.         ; Note that at this point the pushed value of `lr' has been popped\n\
  1399.         ldi r0, #16\n\
  1400.         bl process_exception");

  1401. void _catchException17 ();

  1402. asm ("\n\
  1403. _catchException17:\n\
  1404.         push lr\n\
  1405.         bl stash_registers\n\
  1406.         ; Note that at this point the pushed value of `lr' has been popped\n\
  1407.         ldi r0, #17\n\
  1408.         bl process_exception");


  1409. /* this function is used to set up exception handlers for tracing and
  1410.    breakpoints */
  1411. void
  1412. set_debug_traps (void)
  1413. {
  1414.   /*  extern void remcomHandler(); */
  1415.   int i;

  1416.   for (i = 0; i < 18; i++)        /* keep a copy of old vectors */
  1417.     if (save_vectors[i] == 0)        /* only copy them the first time */
  1418.       save_vectors[i] = getExceptionHandler (i);

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

  1420.   exceptionHandler (0, _catchException0);
  1421.   exceptionHandler (1, _catchException1);
  1422.   exceptionHandler (2, _catchException2);
  1423.   exceptionHandler (3, _catchException3);
  1424.   exceptionHandler (4, _catchException4);
  1425.   exceptionHandler (5, _catchException5);
  1426.   exceptionHandler (6, _catchException6);
  1427.   exceptionHandler (7, _catchException7);
  1428.   exceptionHandler (8, _catchException8);
  1429.   exceptionHandler (9, _catchException9);
  1430.   exceptionHandler (10, _catchException10);
  1431.   exceptionHandler (11, _catchException11);
  1432.   exceptionHandler (12, _catchException12);
  1433.   exceptionHandler (13, _catchException13);
  1434.   exceptionHandler (14, _catchException14);
  1435.   exceptionHandler (15, _catchException15);
  1436.   exceptionHandler (16, _catchException16);
  1437.   /*  exceptionHandler (17, _catchException17); */

  1438.   initialized = 1;
  1439. }

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

  1444. #define BREAKPOINT() asm volatile ("        trap #2");

  1445. void
  1446. breakpoint (void)
  1447. {
  1448.   if (initialized)
  1449.     BREAKPOINT ();
  1450. }

  1451. /* STDOUT section:
  1452.    Stuff pertaining to simulating stdout by sending chars to gdb to be echoed.
  1453.    Functions: gdb_putchar(char ch)
  1454.               gdb_puts(char *str)
  1455.               gdb_write(char *str, int len)
  1456.               gdb_error(char *format, char *parm)
  1457.               */

  1458. /* Function: gdb_putchar(int)
  1459.    Make gdb write a char to stdout.
  1460.    Returns: the char */

  1461. static int
  1462. gdb_putchar (int ch)
  1463. {
  1464.   char buf[4];

  1465.   buf[0] = 'O';
  1466.   buf[1] = hexchars[ch >> 4];
  1467.   buf[2] = hexchars[ch & 0x0F];
  1468.   buf[3] = 0;
  1469.   putpacket (buf);
  1470.   return ch;
  1471. }

  1472. /* Function: gdb_write(char *, int)
  1473.    Make gdb write n bytes to stdout (not assumed to be null-terminated).
  1474.    Returns: number of bytes written */

  1475. static int
  1476. gdb_write (char *data, int len)
  1477. {
  1478.   char *buf, *cpy;
  1479.   int i;

  1480.   buf = remcomOutBuffer;
  1481.   buf[0] = 'O';
  1482.   i = 0;
  1483.   while (i < len)
  1484.     {
  1485.       for (cpy = buf + 1;
  1486.            i < len && cpy < buf + sizeof (remcomOutBuffer) - 3; i++)
  1487.         {
  1488.           *cpy++ = hexchars[data[i] >> 4];
  1489.           *cpy++ = hexchars[data[i] & 0x0F];
  1490.         }
  1491.       *cpy = 0;
  1492.       putpacket (buf);
  1493.     }
  1494.   return len;
  1495. }

  1496. /* Function: gdb_puts(char *)
  1497.    Make gdb write a null-terminated string to stdout.
  1498.    Returns: the length of the string */

  1499. static int
  1500. gdb_puts (char *str)
  1501. {
  1502.   return gdb_write (str, strlen (str));
  1503. }

  1504. /* Function: gdb_error(char *, char *)
  1505.    Send an error message to gdb's stdout.
  1506.    First string may have 1 (one) optional "%s" in it, which
  1507.    will cause the optional second string to be inserted.  */

  1508. static void
  1509. gdb_error (char *format, char *parm)
  1510. {
  1511.   char buf[400], *cpy;
  1512.   int len;

  1513.   if (remote_debug)
  1514.     {
  1515.       if (format && *format)
  1516.         len = strlen (format);
  1517.       else
  1518.         return;                        /* empty input */

  1519.       if (parm && *parm)
  1520.         len += strlen (parm);

  1521.       for (cpy = buf; *format;)
  1522.         {
  1523.           if (format[0] == '%' && format[1] == 's')        /* include second string */
  1524.             {
  1525.               format += 2;        /* advance two chars instead of just one */
  1526.               while (parm && *parm)
  1527.                 *cpy++ = *parm++;
  1528.             }
  1529.           else
  1530.             *cpy++ = *format++;
  1531.         }
  1532.       *cpy = '\0';
  1533.       gdb_puts (buf);
  1534.     }
  1535. }

  1536. static unsigned char *
  1537. strcpy (unsigned char *dest, const unsigned char *src)
  1538. {
  1539.   unsigned char *ret = dest;

  1540.   if (dest && src)
  1541.     {
  1542.       while (*src)
  1543.         *dest++ = *src++;
  1544.       *dest = 0;
  1545.     }
  1546.   return ret;
  1547. }

  1548. static int
  1549. strlen (const unsigned char *src)
  1550. {
  1551.   int ret;

  1552.   for (ret = 0; *src; src++)
  1553.     ret++;

  1554.   return ret;
  1555. }

  1556. #if 0
  1557. void
  1558. exit (code)
  1559.      int code;
  1560. {
  1561.   _exit (code);
  1562. }

  1563. int
  1564. atexit (void *p)
  1565. {
  1566.   return 0;
  1567. }

  1568. void
  1569. abort (void)
  1570. {
  1571.   _exit (1);
  1572. }
  1573. #endif