source: rtems/c/src/lib/libbsp/m68k/ods68302/startup/m68k-stub.c @ cba474e

4.115
Last change on this file since cba474e was cba474e, checked in by Joel Sherrill <joel.sherrill@…>, on 10/13/14 at 19:50:12

m68k/ods68302: Fix warnings

  • Property mode set to 100644
File size: 35.5 KB
Line 
1/****************************************************************************
2
3                THIS SOFTWARE IS NOT COPYRIGHTED
4
5   HP offers the following for use in the public domain.  HP makes no
6   warranty with regard to the software or it's performance and the
7   user accepts the software "AS IS" with all faults.
8
9   HP DISCLAIMS ANY WARRANTIES, EXPRESS OR IMPLIED, WITH REGARD
10   TO THIS SOFTWARE INCLUDING BUT NOT LIMITED TO THE WARRANTIES
11   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
12
13****************************************************************************/
14
15/****************************************************************************
16 *  Header: remcom.c,v 1.34 91/03/09 12:29:49 glenne Exp $
17 *
18 *  Module name: remcom.c $
19 *  Revision: 1.34 $
20 *  Date: 91/03/09 12:29:49 $
21 *  Contributor:     Lake Stevens Instrument Division$
22 *
23 *  Description:     low level support for gdb debugger. $
24 *
25 *  Considerations:  only works on target hardware $
26 *
27 *  Written by:      Glenn Engel $
28 *  ModuleState:     Experimental $
29 *
30 *  NOTES:           See Below $
31 *
32 *  To enable debugger support, two things need to happen.  One, a
33 *  call to set_debug_traps() is necessary in order to allow any breakpoints
34 *  or error conditions to be properly intercepted and reported to gdb.
35 *  Two, a breakpoint needs to be generated to begin communication.  This
36 *  is most easily accomplished by a call to breakpoint().  Breakpoint()
37 *  simulates a breakpoint by executing a trap #1.  The breakpoint instruction
38 *  is hardwired to trap #1 because not to do so is a compatibility problem--
39 *  there either should be a standard breakpoint instruction, or the protocol
40 *  should be extended to provide some means to communicate which breakpoint
41 *  instruction is in use (or have the stub insert the breakpoint).
42 *
43 *  Some explanation is probably necessary to explain how exceptions are
44 *  handled.  When an exception is encountered the 68000 pushes the current
45 *  program counter and status register onto the supervisor stack and then
46 *  transfers execution to a location specified in it's vector table.
47 *  The handlers for the exception vectors are hardwired to jmp to an address
48 *  given by the relation:  (exception - 256) * 6.  These are decending
49 *  addresses starting from -6, -12, -18, ...  By allowing 6 bytes for
50 *  each entry, a jsr, jmp, bsr, ... can be used to enter the exception
51 *  handler.  Using a jsr to handle an exception has an added benefit of
52 *  allowing a single handler to service several exceptions and use the
53 *  return address as the key differentiation.  The vector number can be
54 *  computed from the return address by [ exception = (addr + 1530) / 6 ].
55 *  The sole purpose of the routine _catchException is to compute the
56 *  exception number and push it on the stack in place of the return address.
57 *  The external function exceptionHandler() is
58 *  used to attach a specific handler to a specific m68k exception.
59 *  For 68020 machines, the ability to have a return address around just
60 *  so the vector can be determined is not necessary because the '020 pushes an
61 *  extra word onto the stack containing the vector offset
62 *
63 *  Because gdb will sometimes write to the stack area to execute function
64 *  calls, this program cannot rely on using the supervisor stack so it
65 *  uses it's own stack area reserved in the int array remcomStack.
66 *
67 *************
68 *
69 *    The following gdb commands are supported:
70 *
71 * command          function                               Return value
72 *
73 *    g             return the value of the CPU registers  hex data or ENN
74 *    G             set the value of the CPU registers     OK or ENN
75 *
76 *    mAA..AA,LLLL  Read LLLL bytes at address AA..AA      hex data or ENN
77 *    MAA..AA,LLLL: Write LLLL bytes at address AA.AA      OK or ENN
78 *
79 *    c             Resume at current address              SNN   ( signal NN)
80 *    cAA..AA       Continue at address AA..AA             SNN
81 *
82 *    s             Step one instruction                   SNN
83 *    sAA..AA       Step one instruction from AA..AA       SNN
84 *
85 *    k             kill
86 *
87 *    ?             What was the last sigval ?             SNN   (signal NN)
88 *
89 * All commands and responses are sent with a packet which includes a
90 * checksum.  A packet consists of
91 *
92 * $<packet info>#<checksum>.
93 *
94 * where
95 * <packet info> :: <characters representing the command or response>
96 * <checksum>    :: < two hex digits computed as modulo 256 sum of <packetinfo>>
97 *
98 * When a packet is received, it is first acknowledged with either '+' or '-'.
99 * '+' indicates a successful transfer.  '-' indicates a failed transfer.
100 *
101 * Example:
102 *
103 * Host:                  Reply:
104 * $m0,10#2a               +$00010203040506070809101112131415#42
105 *
106 ****************************************************************************/
107
108#include <stdio.h>
109#include <string.h>
110#include <setjmp.h>
111
112#include <bsp.h>
113#include <debugport.h>
114
115/************************************************************************
116 *
117 * external low-level support routines
118 */
119typedef void (*ExceptionHook)(int);   /* pointer to function with int parm */
120typedef void (*Function)(void);       /* pointer to a function */
121
122/* assign an exception handler */
123Function exceptionHandler(int vector,  Function handler);
124extern ExceptionHook exceptionHook;  /* hook variable for errors/exceptions */
125
126int putDebugChar(char ch);
127char getDebugChar(void);
128
129/************************/
130/* FORWARD DECLARATIONS */
131/************************/
132static int hex(char ch);
133static void getpacket(char *buffer);
134static void putpacket(char *buffer);
135static char* mem2hex(char *mem, char *buf, int count);
136static char* hex2mem(char *buf, char *mem, int count);
137static void handle_buserror(void);
138static int computeSignal(int exceptionVector);
139static int hexToInt(char **ptr, int *intValue);
140       void handle_exception(int exceptionVector);
141static void initializeRemcomErrorFrame(void);
142
143void set_debug_traps(void);
144void breakpoint(void);
145
146/************************************************************************/
147/* BUFMAX defines the maximum number of characters in inbound/outbound buffers*/
148/* at least NUMREGBYTES*2 are needed for register packets */
149#define BUFMAX 400
150
151static bool initialized = false;  /* boolean flag. != 0 means we've been initialized */
152
153int remote_debug;
154/*  debug >  0 prints ill-formed commands in valid packets & checksum errors */
155
156static const char hexchars[]="0123456789abcdef";
157
158/* there are 180 bytes of registers on a 68020 w/68881      */
159/* many of the fpa registers are 12 byte (96 bit) registers */
160#define NUMREGBYTES 180
161enum regnames {D0,D1,D2,D3,D4,D5,D6,D7,
162               A0,A1,A2,A3,A4,A5,A6,A7,
163               PS,PC,
164               FP0,FP1,FP2,FP3,FP4,FP5,FP6,FP7,
165               FPCONTROL,FPSTATUS,FPIADDR
166              };
167
168
169/* We keep a whole frame cache here.  "Why?", I hear you cry, "doesn't
170   GDB handle that sort of thing?"  Well, yes, I believe the only
171   reason for this cache is to save and restore floating point state
172   (fsave/frestore).  A cleaner way to do this would be to make the
173 fsave data part of the registers which GDB deals with like any
174   other registers.  This should not be a performance problem if the
175   ability to read individual registers is added to the protocol.  */
176
177typedef struct FrameStruct
178{
179    struct FrameStruct  *previous;
180    int       exceptionPC;      /* pc value when this frame created */
181    int       exceptionVector;  /* cpu vector causing exception     */
182    short     frameSize;        /* size of cpu frame in words       */
183    short     sr;               /* for 68000, this not always sr    */
184    int       pc;
185    short     format;
186    int       fsaveHeader;
187    int       morejunk[0];        /* exception frame, fp save... */
188} Frame;
189
190#define FRAMESIZE 500
191int gdbFrameStack[FRAMESIZE];
192static Frame *lastFrame;
193
194/*
195 * these should not be static cuz they can be used outside this module
196 */
197int registers[NUMREGBYTES/4];
198int superStack;
199
200#define STACKSIZE 10000
201int remcomStack[STACKSIZE/sizeof(int)];
202static int* stackPtr = &remcomStack[STACKSIZE/sizeof(int) - 1];
203
204/*
205 * In many cases, the system will want to continue exception processing
206 * when a continue command is given.
207 * oldExceptionHook is a function to invoke in this case.
208 */
209
210static ExceptionHook oldExceptionHook;
211
212#if (defined(__mc68020__) && !defined(__mcpu32__))
213/* the size of the exception stack on the 68020 varies with the type of
214 * exception.  The following table is the number of WORDS used
215 * for each exception format.
216 */
217const short exceptionSize[] = { 4,4,6,4,4,4,4,4,29,10,16,46,12,4,4,4 };
218#endif
219
220#if defined(__mc68332__)
221static const short exceptionSize[] = { 4,4,6,4,4,4,4,4,4,4,4,4,16,4,4,4 };
222#endif
223
224/************* jump buffer used for setjmp/longjmp **************************/
225jmp_buf remcomEnv;
226
227/***************************  ASSEMBLY CODE MACROS *************************/
228/*                                                                         */
229
230#if defined(__HAVE_68881__)
231
232/* do an fsave, then remember the address to begin a restore from */
233#define SAVE_FP_REGS() \
234       __asm__ (" fsave   %a0@-");      \
235       __asm__ (" fmovemx %fp0-%fp7,registers+72");  \
236       __asm__ (" fmoveml %fpcr/%fpsr/%fpi,registers+168");
237
238#define RESTORE_FP_REGS() \
239__asm__ ("                                                 \n\
240    fmoveml  registers+168,%fpcr/%fpsr/%fpi           \n\
241    fmovemx  registers+72,%fp0-%fp7                   \n\
242    cmpl     #-1,%a0@     |  skip frestore flag set ? \n\
243    beq      skip_frestore                            \n\
244    frestore %a0@+                                    \n\
245skip_frestore:                                        \n\
246");
247
248#else
249
250#define SAVE_FP_REGS()
251#define RESTORE_FP_REGS()
252
253#endif /* __HAVE_68881__ */
254
255void return_to_super(void);
256void return_to_user(void);
257
258__asm__ ("\n\
259       .text\n\
260\n\
261       .globl return_to_super\n\
262       .align 4\n\
263return_to_super:\n\
264        movel   registers+60,%sp     /* get new stack pointer */        \n\
265        movel   lastFrame,%a0        /* get last frame info  */         \n\
266        bra     return_to_any\n\
267\n\
268        .globl return_to_user\n\
269        .align 4\n\
270\n\
271return_to_user:\n\
272        movel   registers+60,%a0     /* get usp */                      \n\
273        movel   %a0,%usp             /* set usp */                              \n\
274        movel   superStack,%sp       /* get original stack pointer */        \n\
275\n\
276return_to_any:\n\
277        movel   lastFrame,%a0        /* get last frame info  */              \n\
278        movel   %a0@+,lastFrame      /* link in previous frame     */        \n\
279        addql   #8,%a0               /* skip over pc, vector#*/              \n\
280        movew   %a0@+,%d0            /* get # of words in cpu frame */       \n\
281        addw    %d0,%a0              /* point to end of data        */       \n\
282        addw    %d0,%a0              /* point to end of data        */       \n\
283        movel   %a0,%a1                                                   \n\
284#                                                                       \n\
285# copy the stack frame                                                  \n\
286        subql   #1,%d0\n\
287\n\
288copyUserLoop:                                                               \n\
289        movew   %a1@-,%sp@-                                               \n\
290        dbf     %d0,copyUserLoop                                             \n\
291");
292        RESTORE_FP_REGS()
293__asm__ ("\n\
294        moveml  registers,%d0-%d7/%a0-%a6\n\
295        rte                          /* pop and go! */\n\
296");
297
298#define DISABLE_INTERRUPTS() __asm__ ("   oriw   #0x0700,%sr");
299#define BREAKPOINT()         __asm__ ("   trap   #1");
300
301/* this function is called immediately when a level 7 interrupt occurs */
302/* if the previous interrupt level was 7 then we're already servicing  */
303/* this interrupt and an rte is in order to return to the debugger.    */
304/* For the 68000, the offset for sr is 6 due to the jsr return address */
305__asm__ ("\n\
306        .text\n\
307        .globl _debug_level7\n\
308        .align 4\n\
309\n\
310_debug_level7:\n\
311        movew   %d0,%sp@-\n\
312");
313
314#if (defined(__mc68020__) && !defined(__mcpu32__)) || defined(__mc68332__)
315__asm__ ("\n\
316        movew   %sp@(2),%d0\n\
317");
318#else
319__asm__ ("\n\
320        movew   %sp@(6),%d0\n\
321");
322#endif
323__asm__ ("\n\
324        andiw   #0x700,%d0\n\
325          cmpiw   #0x700,%d0\n\
326          beq     _already7\n\
327        movew   %sp@+,%d0       \n\
328        bra     _catchException\n\
329_already7:\n\
330              movew   %sp@+,%d0\n\
331");
332#if defined (__mc68000__) && !(defined(__mc68020__) && !defined(__mcpu32__))
333__asm__ ("\n\
334        lea     %sp@(4),%sp");       /* pull off 68000 return address */
335#endif
336__asm__ ("\n\
337        rte\n\
338");
339
340extern void _catchException(void);
341
342#if (defined(__mc68020__) && !defined(__mcpu32__)) || defined(__mc68332__)
343/* This function is called when a 68020 exception occurs.  It saves
344 * all the cpu and fpcp regs in the _registers array, creates a frame on a
345 * linked list of frames which has the cpu and fpcp stack frames needed
346 * to properly restore the context of these processors, and invokes
347 * an exception handler (remcom_handler).
348 *
349 * stack on entry:                       stack on exit:
350 *   N bytes of junk                     exception # MSWord
351 *   Exception Format Word               exception # MSWord
352 *   Program counter LSWord
353 *   Program counter MSWord
354 *   Status Register
355 *
356 *
357 */
358__asm__ (" \n\
359        .text\n\
360\n\
361        .globl _catchException\n\
362        .align 4\n\
363_catchException:\n\
364");
365
366DISABLE_INTERRUPTS();
367
368__asm__ ("\n\
369        moveml  %d0-%d7/%a0-%a6,registers /* save registers        */\n\
370        movel   lastFrame,%a0             /* last frame pointer */\n\
371");
372SAVE_FP_REGS();
373__asm__ ("\n\
374        lea     registers,%a5   /* get address of registers     */\n\
375        movew   %sp@,%d1        /* get status register          */\n\
376        movew   %d1,%a5@(66)    /* save sr      */      \n\
377        movel   %sp@(2),%a4     /* save pc in %a4 for later use  */\n\
378        movel   %a4,%a5@(68)    /* save pc in _regisers[]       */\n\
379\n\
380#\n\
381# figure out how many bytes in the stack frame\n\
382#\n\
383        movew   %sp@(6),%d0         /* get '020 exception format        */\n\
384        movew   %d0,%d2         /* make a copy of format word   */\n\
385        andiw   #0xf000,%d0     /* mask off format type         */\n\
386        rolw    #5,%d0          /* rotate into the low byte *2  */\n\
387        lea     exceptionSize,%a1   \n\
388        addw    %d0,%a1         /* index into the table         */\n\
389        movew   %a1@,%d0        /* get number of words in frame */\n\
390        movew   %d0,%d3         /* save it                      */\n\
391        subw    %d0,%a0         /* adjust save pointer          */\n\
392        subw    %d0,%a0         /* adjust save pointer(bytes)   */\n\
393        movel   %a0,%a1         /* copy save pointer            */\n\
394        subql   #1,%d0          /* predecrement loop counter    */\n\
395#\n\
396# copy the frame\n\
397#\n\
398saveFrameLoop:\n\
399              movew   %sp@+,%a1@+\n\
400        dbf     %d0,saveFrameLoop\n\
401#\n\
402# now that the stack has been clenaed,\n\
403# save the %a7 in use at time of exception\n\
404\n\
405        movel   %sp,superStack  /* save supervisor %sp           */\n\
406        andiw   #0x2000,%d1     /* were we in supervisor mode ? */\n\
407        beq     userMode       \n\
408        movel   %a7,%a5@(60)    /* save %a7                  */\n\
409        bra     a7saveDone\n\
410userMode:  \n\
411        movel   %usp,%a1        \n\
412        movel   %a1,%a5@(60)    /* save user stack pointer      */\n\
413a7saveDone:\n\
414\n\
415#\n\
416# save size of frame\n\
417        movew   %d3,%a0@-\n\
418\n\
419#\n\
420# compute exception number\n\
421        andl    #0xfff,%d2        /* mask off vector offset     */\n\
422        lsrw    #2,%d2                /* divide by 4 to get vect num    */\n\
423        movel   %d2,%a0@-       /* save it                      */\n\
424#\n\
425# save pc causing exception\n\
426        movel   %a4,%a0@-\n\
427#\n\
428# save old frame link and set the new value\n\
429        movel   lastFrame,%a1       /* last frame pointer */\n\
430        movel   %a1,%a0@-                   /* save pointer to prev frame       */\n\
431        movel   %a0,lastFrame\n\
432\n\
433        movel   %d2,%sp@-                   /* push exception num           */\n\
434        movel   exceptionHook,%a0  /* get address of handler */\n\
435        jbsr    %a0@            /* and call it */\n\
436        clrl    %sp@            /* replace exception num parm with frame ptr */\n\
437        jbsr     _returnFromException   /* jbsr, but never returns */\n\
438\n\
439");
440
441#else /* mc68000 */
442
443/* This function is called when an exception occurs.  It translates the
444 * return address found on the stack into an exception vector # which
445 * is then handled by either handle_exception or a system handler.
446 * _catchException provides a front end for both.
447 *
448 * stack on entry:                       stack on exit:
449 *   Program counter MSWord              exception # MSWord
450 *   Program counter LSWord              exception # MSWord
451 *   Status Register
452 *   Return Address  MSWord
453 *   Return Address  LSWord
454 */
455__asm__ ("\n\
456        .text\n\
457        .globl _catchException\n\
458        .align 4\n\
459_catchException:\n\
460");
461DISABLE_INTERRUPTS();
462__asm__ ("\n\
463        moveml  %d0-%d7/%a0-%a6,registers  /* save registers               */\n\
464        movel   lastFrame,%a0   /* last frame pointer */\n\
465");
466
467SAVE_FP_REGS();
468__asm__ ("\n\
469        moveq.l #0,%d2\n\
470        movew   %sp@+,%d2\n\
471        lea     registers,%a5    /* get address of registers     */\n\
472\n\
473        moveql  #3,%d3           /* assume a three word frame     */\n\
474\n\
475        cmpiw   #3,%d2           /* bus error or address error ? */\n\
476        bgt     normal           /* if >3 then normal error      */\n\
477        movel   %sp@+,%a0@-      /* copy error info to frame buff*/\n\
478        movel   %sp@+,%a0@-      /* these are never used         */\n\
479        moveql  #7,%d3           /* this is a 7 word frame       */\n\
480     \n\
481normal:   \n\
482        movew   %sp@+,%d1         /* pop status register          */\n\
483        movel   %sp@+,%a4         /* pop program counter          */\n\
484\n\
485        cmpiw   #33,%d2           /* trap #1, breakpoint ? */\n\
486        bne     not_breakpoint\n\
487\n\
488        subql   #2,%a4            /* trap leaves the pc after the trap */\n\
489\n\
490not_breakpoint:\n\
491        movew   %d1,%a5@(66)      /* save sr                    */      \n\
492        movel   %a4,%a5@(68)      /* save pc in _regisers[]             */\n\
493        movel   %a4,%a0@-         /* copy pc to frame buffer      */\n\
494        movew   %d1,%a0@-         /* copy sr to frame buffer      */\n\
495\n\
496        movel   %sp,superStack    /* save supervisor %sp          */\n\
497\n\
498        andiw   #0x2000,%d1      /* were we in supervisor mode ? */\n\
499        beq     userMode       \n\
500        movel   %a7,%a5@(60)      /* save %a7                  */\n\
501        bra     saveDone             \n\
502userMode:\n\
503        movel   %usp,%a1        /* save user stack pointer      */\n\
504        movel   %a1,%a5@(60)      /* save user stack pointer    */\n\
505saveDone:\n\
506\n\
507        movew   %d3,%a0@-         /* push frame size in words     */\n\
508        movel   %d2,%a0@-         /* push vector number           */\n\
509        movel   %a4,%a0@-         /* push exception pc            */\n\
510\n\
511#\n\
512# save old frame link and set the new value\n\
513#\n\
514        movel   lastFrame,%a1   /* last frame pointer */\n\
515        movel   %a1,%a0@-               /* save pointer to prev frame   */\n\
516        movel   %a0,lastFrame\n\
517\n\
518        movel   %d2,%sp@-               /* push exception num           */\n\
519        movel   exceptionHook,%a0  /* get address of handler */\n\
520\n\
521        jbsr    %a0@             /* and call it */\n\
522        clrl    %sp@             /* replace exception num parm with frame ptr */\n\
523        jbsr     _returnFromException   /* jbsr, but never returns */\n\
524");
525#endif
526
527/*
528 * remcomHandler is a front end for handle_exception.  It moves the
529 * stack pointer into an area reserved for debugger use in case the
530 * breakpoint happened in supervisor mode.
531 */
532__asm__ ("remcomHandler:");
533__asm__ ("           addl    #4,%sp");        /* pop off return address     */
534__asm__ ("           movel   %sp@+,%d0");      /* get the exception number   */
535__asm__ ("              movel   stackPtr,%sp"); /* move to remcom stack area  */
536__asm__ ("              movel   %d0,%sp@-");    /* push exception onto stack  */
537__asm__ ("              jbsr    handle_exception");    /* this never returns */
538__asm__ ("           rts");                  /* return */
539
540/*
541 * This is only called from assembly in this file. This file is a self
542 * contained gdb stub.
543 */
544void _returnFromException(Frame *frame);
545
546void _returnFromException(Frame *frame)
547{
548  /* if no passed in frame, use the last one */
549  if (! frame)
550  {
551    frame = lastFrame;
552    frame->frameSize = 4;
553    frame->format = 0;
554    frame->fsaveHeader = -1; /* restore regs, but we dont have fsave info*/
555  }
556
557#if defined(__mc68000__) && !(defined(__mc68020__) && !defined(__mcpu32__))
558  /* a 68000 cannot use the internal info pushed onto a bus error
559   * or address error frame when doing an RTE so don't put this info
560   * onto the stack or the stack will creep every time this happens.
561   */
562  frame->frameSize=3;
563#endif
564
565  /* throw away any frames in the list after this frame */
566  lastFrame = frame;
567
568  frame->sr = registers[(int) PS];
569  frame->pc = registers[(int) PC];
570
571  if (registers[(int) PS] & 0x2000)
572  {
573    /* return to supervisor mode... */
574    return_to_super();
575  }
576  else
577  { /* return to user mode */
578    return_to_user();
579  }
580}
581
582int hex(char ch)
583{
584  if ((ch >= 'a') && (ch <= 'f')) return (ch-'a'+10);
585  if ((ch >= '0') && (ch <= '9')) return (ch-'0');
586  if ((ch >= 'A') && (ch <= 'F')) return (ch-'A'+10);
587  return (-1);
588}
589
590/* scan for the sequence $<data>#<checksum>     */
591void getpacket(char *buffer)
592{
593  unsigned char checksum;
594  unsigned char xmitcsum;
595  int  i;
596  int  count;
597  char ch;
598
599  do {
600    /* wait around for the start character, ignore all other characters */
601    while ((ch = (getDebugChar() & 0x7f)) != '$');
602    checksum = 0;
603    xmitcsum = -1;
604
605    count = 0;
606
607    /* now, read until a # or end of buffer is found */
608    while (count < (BUFMAX - 1)) {
609      ch = getDebugChar() & 0x7f;
610      if (ch == '#') break;
611      checksum = checksum + ch;
612      buffer[count] = ch;
613      count = count + 1;
614    }
615    buffer[count] = 0;
616
617    if (ch == '#') {
618      xmitcsum = hex(getDebugChar() & 0x7f) << 4;
619      xmitcsum += hex(getDebugChar() & 0x7f);
620      if ((remote_debug ) && (checksum != xmitcsum)) {
621        debug_port_printf ("bad checksum.  My count = 0x%x, sent=0x%x. buf=%s\n",
622                           checksum,xmitcsum,buffer);
623      }
624
625      if (checksum != xmitcsum) putDebugChar('-');  /* failed checksum */
626      else {
627        putDebugChar('+');  /* successful transfer */
628        /* if a sequence char is present, reply the sequence ID */
629        if (buffer[2] == ':') {
630          putDebugChar( buffer[0] );
631          putDebugChar( buffer[1] );
632          /* remove sequence chars from buffer */
633          count = strlen(buffer);
634          for (i=3; i <= count; i++) buffer[i-3] = buffer[i];
635        }
636      }
637    }
638  } while (checksum != xmitcsum);
639}
640
641/* send the packet in buffer.  The host get's one chance to read it.
642   This routine does not wait for a positive acknowledge.  */
643
644void
645putpacket(char *buffer)
646{
647  unsigned char checksum;
648  int  count;
649  char ch;
650
651  /*  $<packet info>#<checksum>. */
652  do {
653    putDebugChar('$');
654    checksum = 0;
655    count    = 0;
656
657    while ((ch=buffer[count])) {
658      if (! putDebugChar(ch)) return;
659      checksum += ch;
660      count += 1;
661    }
662
663    putDebugChar('#');
664    putDebugChar(hexchars[checksum >> 4]);
665    putDebugChar(hexchars[checksum % 16]);
666
667  } while (1 == 0);  /* (getDebugChar() != '+'); */
668
669}
670
671char  remcomInBuffer[BUFMAX];
672char  remcomOutBuffer[BUFMAX];
673static short error;
674
675/* convert the memory pointed to by mem into hex, placing result in buf */
676/* return a pointer to the last char put in buf (null) */
677char *mem2hex(char *mem, char *buf, int count)
678{
679  int i;
680  unsigned char ch;
681
682  if (remote_debug)
683    debug_port_printf("mem=0x%x, count=0x%x\n", mem, count);
684
685  for (i=0;i<count;i++) {
686    ch = *mem++;
687    *buf++ = hexchars[ch >> 4];
688    *buf++ = hexchars[ch % 16];
689  }
690  *buf = 0;
691  return(buf);
692}
693
694/* convert the hex array pointed to by buf into binary to be placed in mem */
695/* return a pointer to the character AFTER the last byte written */
696char *hex2mem(char *buf, char *mem, int count)
697{
698  int i;
699  unsigned char ch;
700
701  if (remote_debug)
702    debug_port_printf("mem=0x%x, count=0x%x\n", mem, count);
703
704  for (i=0;i<count;i++) {
705    ch = hex(*buf++) << 4;
706    ch = ch + hex(*buf++);
707    *mem++ = ch;
708  }
709  return(mem);
710}
711
712/* a bus error has occurred, perform a longjmp
713   to return execution and allow handling of the error */
714
715void handle_buserror()
716{
717  longjmp(remcomEnv,1);
718}
719
720/* this function takes the 68000 exception number and attempts to
721   translate this number into a unix compatible signal value */
722int computeSignal(int exceptionVector)
723{
724  int sigval;
725  switch (exceptionVector) {
726    case 2 : sigval = 10; break; /* bus error           */
727    case 3 : sigval = 10; break; /* address error       */
728    case 4 : sigval = 4;  break; /* illegal instruction */
729    case 5 : sigval = 8;  break; /* zero divide         */
730    case 6 : sigval = 8; break; /* chk instruction     */
731    case 7 : sigval = 8; break; /* trapv instruction   */
732    case 8 : sigval = 11; break; /* privilege violation */
733    case 9 : sigval = 5;  break; /* trace trap          */
734    case 10: sigval = 4;  break; /* line 1010 emulator  */
735    case 11: sigval = 4;  break; /* line 1111 emulator  */
736
737      /* Coprocessor protocol violation.  Using a standard MMU or FPU
738         this cannot be triggered by software.  Call it a SIGBUS.  */
739    case 13: sigval = 10;  break;
740
741    case 31: sigval = 2;  break; /* interrupt           */
742    case 33: sigval = 5;  break; /* breakpoint          */
743
744      /* This is a trap #8 instruction.  Apparently it is someone's software
745         convention for some sort of SIGFPE condition.  Whose?  How many
746         people are being screwed by having this code the way it is?
747         Is there a clean solution?  */
748    case 40: sigval = 8;  break; /* floating point err  */
749
750    case 48: sigval = 8;  break; /* floating point err  */
751    case 49: sigval = 8;  break; /* floating point err  */
752    case 50: sigval = 8;  break; /* zero divide         */
753    case 51: sigval = 8;  break; /* underflow           */
754    case 52: sigval = 8;  break; /* operand error       */
755    case 53: sigval = 8;  break; /* overflow            */
756    case 54: sigval = 8;  break; /* NAN                 */
757    default:
758      sigval = 7;         /* "software generated"*/
759  }
760  return (sigval);
761}
762
763/**********************************************/
764/* WHILE WE FIND NICE HEX CHARS, BUILD AN INT */
765/* RETURN NUMBER OF CHARS PROCESSED           */
766/**********************************************/
767int hexToInt(char **ptr, int *intValue)
768{
769  int numChars = 0;
770  int hexValue;
771
772  *intValue = 0;
773
774  while (**ptr)
775  {
776    hexValue = hex(**ptr);
777    if (hexValue >=0)
778    {
779      *intValue = (*intValue <<4) | hexValue;
780      numChars ++;
781    }
782    else
783      break;
784
785    (*ptr)++;
786  }
787
788  return (numChars);
789}
790
791/*
792 * This function does all command procesing for interfacing to gdb.
793 */
794void handle_exception(int exceptionVector)
795{
796  int    sigval;
797  int    addr, length;
798  char * ptr;
799  int    newPC;
800  Frame  *frame;
801
802  if (remote_debug)
803    printf("vector=%d, sr=0x%x, pc=0x%x\n",
804           exceptionVector,
805           registers[ PS ],
806           registers[ PC ]);
807
808  /* reply to host that an exception has occurred */
809  sigval = computeSignal( exceptionVector );
810  remcomOutBuffer[0] = 'S';
811  remcomOutBuffer[1] =  hexchars[sigval >> 4];
812  remcomOutBuffer[2] =  hexchars[sigval % 16];
813  remcomOutBuffer[3] = 0;
814
815  putpacket(remcomOutBuffer);
816
817  while (1==1) {
818    error = 0;
819    remcomOutBuffer[0] = 0;
820    getpacket(remcomInBuffer);
821    switch (remcomInBuffer[0]) {
822      case '?' :   remcomOutBuffer[0] = 'S';
823        remcomOutBuffer[1] =  hexchars[sigval >> 4];
824        remcomOutBuffer[2] =  hexchars[sigval % 16];
825        remcomOutBuffer[3] = 0;
826        break;
827      case 'd' :
828        remote_debug = !(remote_debug);  /* toggle debug flag */
829        debug_port_printf("debug mode ");
830        if (remote_debug)
831        {
832          debug_port_printf("on\n");
833        }
834        else
835        {
836          debug_port_printf("off\n");
837        }
838        break;
839      case 'g' : /* return the value of the CPU registers */
840        mem2hex((char*) registers, remcomOutBuffer, NUMREGBYTES);
841        break;
842      case 'G' : /* set the value of the CPU registers - return OK */
843        hex2mem(&remcomInBuffer[1], (char*) registers, NUMREGBYTES);
844        strcpy(remcomOutBuffer,"OK");
845        break;
846
847        /* mAA..AA,LLLL  Read LLLL bytes at address AA..AA */
848      case 'm' :
849        if (setjmp(remcomEnv) == 0)
850        {
851          exceptionHandler(2,handle_buserror);
852
853          /* TRY TO READ %x,%x.  IF SUCCEED, SET PTR = 0 */
854          ptr = &remcomInBuffer[1];
855          if (hexToInt(&ptr,&addr))
856            if (*(ptr++) == ',')
857              if (hexToInt(&ptr,&length))
858              {
859                ptr = 0;
860                mem2hex((char*) addr, remcomOutBuffer, length);
861              }
862
863          if (ptr)
864          {
865            strcpy(remcomOutBuffer,"E01");
866            if (remote_debug)
867              printf("malformed read memory command: %s",remcomInBuffer);
868          }
869        }
870        else {
871          exceptionHandler(2,_catchException);
872          strcpy(remcomOutBuffer,"E03");
873          if (remote_debug)
874            printf("bus error");
875        }
876
877        /* restore handler for bus error */
878        exceptionHandler(2,_catchException);
879        break;
880
881        /* MAA..AA,LLLL: Write LLLL bytes at address AA.AA return OK */
882      case 'M' :
883        if (setjmp(remcomEnv) == 0) {
884          exceptionHandler(2,handle_buserror);
885
886          /* TRY TO READ '%x,%x:'.  IF SUCCEED, SET PTR = 0 */
887          ptr = &remcomInBuffer[1];
888          if (hexToInt(&ptr,&addr))
889            if (*(ptr++) == ',')
890              if (hexToInt(&ptr,&length))
891                if (*(ptr++) == ':')
892                {
893                  hex2mem(ptr, (char*) addr, length);
894                  ptr = 0;
895                  strcpy(remcomOutBuffer,"OK");
896                }
897          if (ptr)
898          {
899            strcpy(remcomOutBuffer,"E02");
900            if (remote_debug)
901              printf("malformed write memory command: %s",remcomInBuffer);
902                      }
903        }
904        else {
905          exceptionHandler(2,_catchException);
906          strcpy(remcomOutBuffer,"E03");
907          if (remote_debug)
908            printf("bus error");
909        }
910
911        /* restore handler for bus error */
912        exceptionHandler(2,_catchException);
913        break;
914
915        /* cAA..AA    Continue at address AA..AA(optional) */
916        /* sAA..AA   Step one instruction from AA..AA(optional) */
917      case 'c' :
918      case 's' :
919        /* try to read optional parameter, pc unchanged if no parm */
920        ptr = &remcomInBuffer[1];
921        if (hexToInt(&ptr,&addr))
922          registers[ PC ] = addr;
923
924        newPC = registers[ PC];
925
926        /* clear the trace bit */
927        registers[ PS ] &= 0x7fff;
928
929        /* set the trace bit if we're stepping */
930        if (remcomInBuffer[0] == 's') registers[ PS ] |= 0x8000;
931
932        /*
933         * look for newPC in the linked list of exception frames.
934         * if it is found, use the old frame it.  otherwise,
935         * fake up a dummy frame in returnFromException().
936         */
937        if (remote_debug) debug_port_printf("new pc = 0x%x\n",newPC);
938
939        frame = lastFrame;
940        while (frame)
941        {
942          if (remote_debug)
943            debug_port_printf("frame at 0x%x has pc=0x%x, except#=%d\n",
944                              frame,frame->exceptionPC,
945                              (unsigned int) frame->exceptionVector);
946          if (frame->exceptionPC == newPC) break;  /* bingo! a match */
947          /*
948           * for a breakpoint instruction, the saved pc may
949           * be off by two due to re-executing the instruction
950           * replaced by the trap instruction.  Check for this.
951           */
952          if ((frame->exceptionVector == 33) &&
953              (frame->exceptionPC == newPC)) break;
954          if (frame == frame->previous)
955          {
956                  frame = 0; /* no match found */
957                  break;
958          }
959          frame = frame->previous;
960        }
961
962        /*
963         * If we found a match for the PC AND we are not returning
964         * as a result of a breakpoint (33),
965         * trace exception (9), nmi (31), jmp to
966         * the old exception handler as if this code never ran.
967         */
968        if (frame)
969        {
970          if ((frame->exceptionVector != 9)  &&
971              (frame->exceptionVector != 31) &&
972              (frame->exceptionVector != 33))
973          {
974            /*
975             * invoke the previous handler.
976             */
977            if (oldExceptionHook)
978              (*oldExceptionHook) (frame->exceptionVector);
979            newPC = registers[ PC ];    /* pc may have changed  */
980            if (newPC != frame->exceptionPC)
981            {
982              if (remote_debug)
983                debug_port_printf("frame at 0x%x has pc=0x%x, except#=%d\n",
984                                  frame,frame->exceptionPC,
985                                  (unsigned int) frame->exceptionVector);
986              /* re-use the last frame, we're skipping it (longjump?)*/
987              frame = (Frame *) 0;
988              _returnFromException( frame );  /* this is a jump */
989            }
990          }
991        }
992
993          /* if we couldn't find a frame, create one */
994        if (frame == 0)
995        {
996          frame = lastFrame -1 ;
997
998          /* by using a bunch of print commands with breakpoints,
999             it's possible for the frame stack to creep down.  If it creeps
1000             too far, give up and reset it to the top.  Normal use should
1001             not see this happen.
1002             */
1003          if ((unsigned int) (frame-2) < (unsigned int) &gdbFrameStack)
1004          {
1005            initializeRemcomErrorFrame();
1006            frame = lastFrame;
1007          }
1008          frame->previous = lastFrame;
1009          lastFrame = frame;
1010          frame = 0;  /* null so _return... will properly initialize it */
1011        }
1012
1013        _returnFromException( frame ); /* this is a jump */
1014
1015        break;
1016
1017        /* kill the program */
1018      case 'k' :
1019        /* reset the board */
1020        WATCHDOG_TRIGGER();
1021        while (1 == 1);
1022        break;
1023
1024    } /* switch */
1025
1026    /* reply to the request */
1027    putpacket(remcomOutBuffer);
1028  }
1029}
1030
1031void initializeRemcomErrorFrame()
1032{
1033    lastFrame = ((Frame *) &gdbFrameStack[FRAMESIZE-1]) - 1;
1034    lastFrame->previous = lastFrame;
1035}
1036
1037extern void _debug_level7(void);
1038extern void remcomHandler(void);
1039
1040/* this function is used to set up exception handlers for tracing and
1041   breakpoints */
1042void set_debug_traps()
1043{
1044  int exception;
1045
1046  initializeRemcomErrorFrame();
1047  stackPtr  = &remcomStack[STACKSIZE/sizeof(int) - 1];
1048
1049  registers[ PC ] = 0x400;
1050  registers[ PS ] = 0x2700;
1051
1052  for (exception = 2; exception <= 30; exception++)
1053      exceptionHandler(exception,_catchException);
1054
1055  /* level 7 interrupt              */
1056  exceptionHandler(31,_debug_level7);
1057
1058  for (exception = 32; exception <= 47; exception++)
1059    exceptionHandler(exception,_catchException);
1060
1061  /* exclude the unassigned, reserved vector locations */
1062
1063  for (exception = 64; exception <= 255; exception++)
1064    exceptionHandler(exception,_catchException);
1065
1066  if (oldExceptionHook != (ExceptionHook) remcomHandler)
1067  {
1068      oldExceptionHook = exceptionHook;
1069      exceptionHook    = (ExceptionHook) remcomHandler;
1070  }
1071
1072  initialized = true;
1073
1074#if defined(UPDATE_DISPLAY)
1075  UPDATE_DISPLAY("gdb ");
1076#endif
1077}
1078
1079/* This function will generate a breakpoint exception.  It is used at the
1080   beginning of a program to sync up with a debugger and can be used
1081   otherwise as a quick means to stop program execution and "break" into
1082   the debugger. */
1083
1084void breakpoint()
1085{
1086  if (initialized) BREAKPOINT();
1087}
Note: See TracBrowser for help on using the repository browser.