File: /usr/src/linux/arch/cris/kernel/kgdb.c

1     /*!**************************************************************************
2     *!
3     *! FILE NAME  : kgdb.c
4     *!
5     *! DESCRIPTION: Implementation of the gdb stub with respect to ETRAX 100.
6     *!              It is a mix of arch/m68k/kernel/kgdb.c and cris_stub.c.
7     *!
8     *!---------------------------------------------------------------------------
9     *! HISTORY
10     *!
11     *! DATE         NAME            CHANGES
12     *! ----         ----            -------
13     *! Apr 26 1999  Hendrik Ruijter Initial version.
14     *! May  6 1999  Hendrik Ruijter Removed call to strlen in libc and removed
15     *!                              struct assignment as it generates calls to
16     *!                              memcpy in libc.
17     *! Jun 17 1999  Hendrik Ruijter Added gdb 4.18 support. 'X', 'qC' and 'qL'.
18     *! Jul 21 1999  Bjorn Wesen     eLinux port
19     *!
20     *! $Log: kgdb.c,v $
21     *! Revision 1.5  2001/04/17 13:58:39  orjanf
22     *! * Renamed CONFIG_KGDB to CONFIG_ETRAX_KGDB.
23     *!
24     *! Revision 1.4  2001/02/23 13:45:19  bjornw
25     *! config.h check
26     *!
27     *! Revision 1.3  2001/01/31 18:08:23  orjanf
28     *! Removed kgdb_handle_breakpoint from being the break 8 handler.
29     *!
30     *! Revision 1.2  2001/01/12 14:22:25  orjanf
31     *! Updated kernel debugging support to work with ETRAX 100LX.
32     *!
33     *! Revision 1.1  2000/07/10 16:25:21  bjornw
34     *! Initial revision
35     *!
36     *! Revision 1.1.1.1  1999/12/03 14:57:31  bjornw
37     *! * Initial version of arch/cris, the latest CRIS architecture with an MMU.
38     *!   Mostly copied from arch/etrax100 with appropriate renames of files.
39     *!   The mm/ subdir is copied from arch/i386.
40     *!   This does not compile yet at all.
41     *!
42     *!
43     *! Revision 1.4  1999/07/22 17:25:25  bjornw
44     *! Dont wait for + in putpacket if we havent hit the initial breakpoint yet. Added a kgdb_init function which sets up the break and irq vectors.
45     *!
46     *! Revision 1.3  1999/07/21 19:51:18  bjornw
47     *! Check if the interrupting char is a ctrl-C, ignore otherwise.
48     *!
49     *! Revision 1.2  1999/07/21 18:09:39  bjornw
50     *! Ported to eLinux architecture, and added some kgdb documentation.
51     *!
52     *!
53     *!---------------------------------------------------------------------------
54     *!
55     *! $Id: kgdb.c,v 1.5 2001/04/17 13:58:39 orjanf Exp $
56     *!
57     *! (C) Copyright 1999, Axis Communications AB, LUND, SWEDEN
58     *!
59     *!**************************************************************************/
60     /* @(#) cris_stub.c 1.3 06/17/99 */
61     
62     /*
63      *  kgdb usage notes:
64      *  -----------------
65      *
66      * If you select CONFIG_ETRAX_KGDB in the configuration, the kernel will be 
67      * built with different gcc flags: "-g" is added to get debug infos, and
68      * "-fomit-frame-pointer" is omitted to make debugging easier. Since the
69      * resulting kernel will be quite big (approx. > 7 MB), it will be stripped
70      * before compresion. Such a kernel will behave just as usually, except if
71      * given a "debug=<device>" command line option. (Only serial devices are
72      * allowed for <device>, i.e. no printers or the like; possible values are
73      * machine depedend and are the same as for the usual debug device, the one
74      * for logging kernel messages.) If that option is given and the device can be
75      * initialized, the kernel will connect to the remote gdb in trap_init(). The
76      * serial parameters are fixed to 8N1 and 115200 bps, for easyness of
77      * implementation.
78      *
79      * To start a debugging session, start that gdb with the debugging kernel
80      * image (the one with the symbols, vmlinux.debug) named on the command line.
81      * This file will be used by gdb to get symbol and debugging infos about the
82      * kernel. Next, select remote debug mode by
83      *    target remote <device>
84      * where <device> is the name of the serial device over which the debugged
85      * machine is connected. Maybe you have to adjust the baud rate by
86      *    set remotebaud <rate>
87      * or also other parameters with stty:
88      *    shell stty ... </dev/...
89      * If the kernel to debug has already booted, it waited for gdb and now
90      * connects, and you'll see a breakpoint being reported. If the kernel isn't
91      * running yet, start it now. The order of gdb and the kernel doesn't matter.
92      * Another thing worth knowing about in the getting-started phase is how to
93      * debug the remote protocol itself. This is activated with
94      *    set remotedebug 1
95      * gdb will then print out each packet sent or received. You'll also get some
96      * messages about the gdb stub on the console of the debugged machine.
97      *
98      * If all that works, you can use lots of the usual debugging techniques on
99      * the kernel, e.g. inspecting and changing variables/memory, setting
100      * breakpoints, single stepping and so on. It's also possible to interrupt the
101      * debugged kernel by pressing C-c in gdb. Have fun! :-)
102      *
103      * The gdb stub is entered (and thus the remote gdb gets control) in the
104      * following situations:
105      *
106      *  - If breakpoint() is called. This is just after kgdb initialization, or if
107      *    a breakpoint() call has been put somewhere into the kernel source.
108      *    (Breakpoints can of course also be set the usual way in gdb.)
109      *    In eLinux, we call breakpoint() in init/main.c after IRQ initialization.
110      *
111      *  - If there is a kernel exception, i.e. bad_super_trap() or die_if_kernel()
112      *    are entered. All the CPU exceptions are mapped to (more or less..., see
113      *    the hard_trap_info array below) appropriate signal, which are reported
114      *    to gdb. die_if_kernel() is usually called after some kind of access
115      *    error and thus is reported as SIGSEGV.
116      *
117      *  - When panic() is called. This is reported as SIGABRT.
118      *
119      *  - If C-c is received over the serial line, which is treated as
120      *    SIGINT.
121      *
122      * Of course, all these signals are just faked for gdb, since there is no
123      * signal concept as such for the kernel. It also isn't possible --obviously--
124      * to set signal handlers from inside gdb, or restart the kernel with a
125      * signal.
126      *
127      * Current limitations:
128      *
129      *  - While the kernel is stopped, interrupts are disabled for safety reasons
130      *    (i.e., variables not changing magically or the like). But this also
131      *    means that the clock isn't running anymore, and that interrupts from the
132      *    hardware may get lost/not be served in time. This can cause some device
133      *    errors...
134      *
135      *  - When single-stepping, only one instruction of the current thread is
136      *    executed, but interrupts are allowed for that time and will be serviced
137      *    if pending. Be prepared for that.
138      *
139      *  - All debugging happens in kernel virtual address space. There's no way to
140      *    access physical memory not mapped in kernel space, or to access user
141      *    space. A way to work around this is using get_user_long & Co. in gdb
142      *    expressions, but only for the current process.
143      *
144      *  - Interrupting the kernel only works if interrupts are currently allowed,
145      *    and the interrupt of the serial line isn't blocked by some other means
146      *    (IPL too high, disabled, ...)
147      *
148      *  - The gdb stub is currently not reentrant, i.e. errors that happen therein
149      *    (e.g. accesing invalid memory) may not be caught correctly. This could
150      *    be removed in future by introducing a stack of struct registers.
151      *
152      */
153     
154     /*
155      *  To enable debugger support, two things need to happen.  One, a
156      *  call to kgdb_init() is necessary in order to allow any breakpoints
157      *  or error conditions to be properly intercepted and reported to gdb.
158      *  Two, a breakpoint needs to be generated to begin communication.  This
159      *  is most easily accomplished by a call to breakpoint(). 
160      *
161      *    The following gdb commands are supported:
162      *
163      * command          function                               Return value
164      *
165      *    g             return the value of the CPU registers  hex data or ENN
166      *    G             set the value of the CPU registers     OK or ENN
167      *
168      *    mAA..AA,LLLL  Read LLLL bytes at address AA..AA      hex data or ENN
169      *    MAA..AA,LLLL: Write LLLL bytes at address AA.AA      OK or ENN
170      *
171      *    c             Resume at current address              SNN   ( signal NN)
172      *    cAA..AA       Continue at address AA..AA             SNN
173      *
174      *    s             Step one instruction                   SNN
175      *    sAA..AA       Step one instruction from AA..AA       SNN
176      *
177      *    k             kill
178      *
179      *    ?             What was the last sigval ?             SNN   (signal NN)
180      *
181      *    bBB..BB	    Set baud rate to BB..BB		   OK or BNN, then sets
182      *							   baud rate
183      *
184      * All commands and responses are sent with a packet which includes a
185      * checksum.  A packet consists of
186      *
187      * $<packet info>#<checksum>.
188      *
189      * where
190      * <packet info> :: <characters representing the command or response>
191      * <checksum>    :: < two hex digits computed as modulo 256 sum of <packetinfo>>
192      *
193      * When a packet is received, it is first acknowledged with either '+' or '-'.
194      * '+' indicates a successful transfer.  '-' indicates a failed transfer.
195      *
196      * Example:
197      *
198      * Host:                  Reply:
199      * $m0,10#2a               +$00010203040506070809101112131415#42
200      *
201      */
202     
203     
204     #include <linux/string.h>
205     #include <linux/signal.h>
206     #include <linux/kernel.h>
207     #include <linux/delay.h>
208     #include <linux/linkage.h>
209     
210     #include <asm/setup.h>
211     #include <asm/ptrace.h>
212     
213     #include <asm/svinto.h>
214     #include <asm/irq.h>
215     
216     static int kgdb_started = 0;
217     
218     /********************************* Register image ****************************/
219     /* Use the order of registers as defined in "AXIS ETRAX CRIS Programmer's
220        Reference", p. 1-1, with the additional register definitions of the
221        ETRAX 100LX in cris-opc.h.
222        There are 16 general 32-bit registers, R0-R15, where R14 is the stack
223        pointer, SP, and R15 is the program counter, PC.
224        There are 16 special registers, P0-P15, where three of the unimplemented
225        registers, P0, P4 and P8, are reserved as zero-registers. A read from
226        any of these registers returns zero and a write has no effect. */
227     
228     typedef
229     struct register_image
230     {
231     	/* Offset */
232     	unsigned int     r0;   /* 0x00 */
233     	unsigned int     r1;   /* 0x04 */
234     	unsigned int     r2;   /* 0x08 */
235     	unsigned int     r3;   /* 0x0C */
236     	unsigned int     r4;   /* 0x10 */
237     	unsigned int     r5;   /* 0x14 */
238     	unsigned int     r6;   /* 0x18 */
239     	unsigned int     r7;   /* 0x1C */
240     	unsigned int     r8;   /* 0x20 Frame pointer */
241     	unsigned int     r9;   /* 0x24 */
242     	unsigned int    r10;   /* 0x28 */
243     	unsigned int    r11;   /* 0x2C */
244     	unsigned int    r12;   /* 0x30 */
245     	unsigned int    r13;   /* 0x34 */
246     	unsigned int     sp;   /* 0x38 Stack pointer */
247     	unsigned int     pc;   /* 0x3C Program counter */
248     
249             unsigned char    p0;   /* 0x40 8-bit zero-register */
250     	unsigned char    vr;   /* 0x41 Version register */
251     
252             unsigned short   p4;   /* 0x42 16-bit zero-register */
253     	unsigned short  ccr;   /* 0x44 Condition code register */
254     	
255     	unsigned int    mof;   /* 0x46 Multiply overflow register */
256     	
257             unsigned int     p8;   /* 0x4A 32-bit zero-register */
258     	unsigned int    ibr;   /* 0x4E Interrupt base register */
259     	unsigned int    irp;   /* 0x52 Interrupt return pointer */
260     	unsigned int    srp;   /* 0x56 Subroutine return pointer */
261     	unsigned int    bar;   /* 0x5A Breakpoint address register */
262     	unsigned int   dccr;   /* 0x5E Double condition code register */
263     	unsigned int    brp;   /* 0x62 Breakpoint return pointer (pc in caller) */
264     	unsigned int    usp;   /* 0x66 User mode stack pointer */
265     } registers;
266     
267     /************** Prototypes for local library functions ***********************/
268     
269     /* Copy of strcpy from libc. */
270     static char *gdb_cris_strcpy (char *s1, const char *s2);
271     
272     /* Copy of strlen from libc. */
273     static int gdb_cris_strlen (const char *s);
274     
275     /* Copy of memchr from libc. */
276     static void *gdb_cris_memchr (const void *s, int c, int n);
277     
278     /* Copy of strtol from libc. Does only support base 16. */
279     static int gdb_cris_strtol (const char *s, char **endptr, int base);
280     
281     /********************** Prototypes for local functions. **********************/
282     /* Copy the content of a register image into another. The size n is
283        the size of the register image. Due to struct assignment generation of
284        memcpy in libc. */
285     static void copy_registers (registers *dptr, registers *sptr, int n);
286     
287     /* Copy the stored registers from the stack. Put the register contents
288        of thread thread_id in the struct reg. */
289     static void copy_registers_from_stack (int thread_id, registers *reg);
290     
291     /* Copy the registers to the stack. Put the register contents of thread
292        thread_id from struct reg to the stack. */
293     static void copy_registers_to_stack (int thread_id, registers *reg);
294     
295     /* Write a value to a specified register regno in the register image
296        of the current thread. */
297     static int write_register (int regno, char *val);
298     
299     /* Write a value to a specified register in the stack of a thread other
300        than the current thread. */
301     static write_stack_register (int thread_id, int regno, char *valptr);
302     
303     /* Read a value from a specified register in the register image. Returns the
304        status of the read operation. The register value is returned in valptr. */
305     static int read_register (char regno, unsigned int *valptr);
306     
307     /* Serial port, reads one character. ETRAX 100 specific. from debugport.c */
308     int getDebugChar (void);
309     
310     /* Serial port, writes one character. ETRAX 100 specific. from debugport.c */
311     void putDebugChar (int val);
312     
313     void enableDebugIRQ (void);
314     
315     /* Returns the character equivalent of a nibble, bit 7, 6, 5, and 4 of a byte,
316        represented by int x. */
317     static char highhex (int x);
318     
319     /* Returns the character equivalent of a nibble, bit 3, 2, 1, and 0 of a byte,
320        represented by int x. */
321     static char lowhex (int x);
322     
323     /* Returns the integer equivalent of a hexadecimal character. */
324     static int hex (char ch);
325     
326     /* Convert the memory, pointed to by mem into hexadecimal representation.
327        Put the result in buf, and return a pointer to the last character
328        in buf (null). */
329     static char *mem2hex (char *buf, unsigned char *mem, int count);
330     
331     /* Convert the array, in hexadecimal representation, pointed to by buf into
332        binary representation. Put the result in mem, and return a pointer to
333        the character after the last byte written. */
334     static unsigned char *hex2mem (unsigned char *mem, char *buf, int count);
335     
336     /* Put the content of the array, in binary representation, pointed to by buf
337        into memory pointed to by mem, and return a pointer to
338        the character after the last byte written. */
339     static unsigned char *bin2mem (unsigned char *mem, unsigned char *buf, int count);
340     
341     /* Await the sequence $<data>#<checksum> and store <data> in the array buffer
342        returned. */
343     static void getpacket (char *buffer);
344     
345     /* Send $<data>#<checksum> from the <data> in the array buffer. */
346     static void putpacket (char *buffer);
347     
348     /* Build and send a response packet in order to inform the host the
349        stub is stopped. */
350     static void stub_is_stopped (int sigval);
351     
352     /* All expected commands are sent from remote.c. Send a response according
353        to the description in remote.c. */
354     static void handle_exception (int sigval);
355     
356     /* Performs a complete re-start from scratch. ETRAX specific. */
357     static void kill_restart (void);
358     
359     /******************** Prototypes for global functions. ***********************/
360     
361     /* The string str is prepended with the GDB printout token and sent. */
362     void putDebugString (const unsigned char *str, int length); /* used by etrax100ser.c */
363     
364     /* The hook for both static (compiled) and dynamic breakpoints set by GDB.
365        ETRAX 100 specific. */
366     void handle_breakpoint (void);                          /* used by irq.c */
367     
368     /* The hook for an interrupt generated by GDB. ETRAX 100 specific. */
369     void handle_interrupt (void);                           /* used by irq.c */
370     
371     /* A static breakpoint to be used at startup. */
372     void breakpoint (void);                                 /* called by init/main.c */
373     
374     /* From osys_int.c, executing_task contains the number of the current
375        executing task in osys. Does not know of object-oriented threads. */
376     extern unsigned char executing_task;
377     
378     /* The number of characters used for a 64 bit thread identifier. */
379     #define HEXCHARS_IN_THREAD_ID 16
380     
381     /* Avoid warning as the internal_stack is not used in the C-code. */
382     #define USEDVAR(name)    { if (name) { ; } }
383     #define USEDFUN(name) { void (*pf)(void) = (void *)name; USEDVAR(pf) }
384     
385     /********************************** Packet I/O ******************************/
386     /* BUFMAX defines the maximum number of characters in
387        inbound/outbound buffers */
388     #define BUFMAX 512
389     
390     /* Run-length encoding maximum length. Send 64 at most. */
391     #define RUNLENMAX 64
392     
393     /* Definition of all valid hexadecimal characters */
394     static const char hexchars[] = "0123456789abcdef";
395     
396     /* The inbound/outbound buffers used in packet I/O */
397     static char remcomInBuffer[BUFMAX];
398     static char remcomOutBuffer[BUFMAX];
399     
400     /* Error and warning messages. */
401     enum error_type
402     {
403     	SUCCESS, E01, E02, E03, E04, E05, E06, E07
404     };
405     static char *error_message[] =
406     {
407     	"",
408     	"E01 Set current or general thread - H[c,g] - internal error.",
409     	"E02 Change register content - P - cannot change read-only register.",
410     	"E03 Thread is not alive.", /* T, not used. */
411     	"E04 The command is not supported - [s,C,S,!,R,d,r] - internal error.",
412     	"E05 Change register content - P - the register is not implemented..",
413     	"E06 Change memory content - M - internal error.",
414     	"E07 Change register content - P - the register is not stored on the stack"
415     };
416     /********************************* Register image ****************************/
417     /* Use the order of registers as defined in "AXIS ETRAX CRIS Programmer's
418        Reference", p. 1-1, with the additional register definitions of the
419        ETRAX 100LX in cris-opc.h.
420        There are 16 general 32-bit registers, R0-R15, where R14 is the stack
421        pointer, SP, and R15 is the program counter, PC.
422        There are 16 special registers, P0-P15, where three of the unimplemented
423        registers, P0, P4 and P8, are reserved as zero-registers. A read from
424        any of these registers returns zero and a write has no effect. */
425     enum register_name
426     {
427     	R0,  R1,   R2,  R3,
428     	R4,  R5,   R6,  R7,
429     	R8,  R9,   R10, R11,
430     	R12, R13,  SP,  PC,
431     	P0,  VR,   P2,  P3,
432     	P4,  CCR,  P6,  MOF,
433     	P8,  IBR,  IRP, SRP,
434     	BAR, DCCR, BRP, USP
435     };
436     
437     /* The register sizes of the registers in register_name. An unimplemented register
438        is designated by size 0 in this array. */
439     static int register_size[] =
440     {
441     	4, 4, 4, 4,
442     	4, 4, 4, 4,
443     	4, 4, 4, 4,
444     	4, 4, 4, 4,
445     	1, 1, 0, 0,
446     	2, 2, 0, 4,
447     	4, 4, 4, 4,
448     	4, 4, 4, 4
449     };
450     
451     /* Contains the register image of the executing thread in the assembler
452        part of the code in order to avoid horrible addressing modes. */
453     static registers reg;
454     
455     /* FIXME: Should this be used? Delete otherwise. */
456     /* Contains the assumed consistency state of the register image. Uses the
457        enum error_type for state information. */
458     static int consistency_status = SUCCESS;
459     
460     /********************************** Handle exceptions ************************/
461     /* The variable reg contains the register image associated with the
462        current_thread_c variable. It is a complete register image created at
463        entry. The reg_g contains a register image of a task where the general
464        registers are taken from the stack and all special registers are taken
465        from the executing task. It is associated with current_thread_g and used
466        in order to provide access mainly for 'g', 'G' and 'P'.
467     */
468     
469     /* Need two task id pointers in order to handle Hct and Hgt commands. */
470     static int current_thread_c = 0;
471     static int current_thread_g = 0;
472     
473     /* Need two register images in order to handle Hct and Hgt commands. The
474        variable reg_g is in addition to reg above. */
475     static registers reg_g;
476     
477     /********************************** Breakpoint *******************************/
478     /* Use an internal stack in the breakpoint and interrupt response routines */
479     #define INTERNAL_STACK_SIZE 1024
480     static char internal_stack[INTERNAL_STACK_SIZE];
481     
482     /* Due to the breakpoint return pointer, a state variable is needed to keep
483        track of whether it is a static (compiled) or dynamic (gdb-invoked)
484        breakpoint to be handled. A static breakpoint uses the content of register
485        BRP as it is whereas a dynamic breakpoint requires subtraction with 2
486        in order to execute the instruction. The first breakpoint is static. */
487     static unsigned char is_dyn_brkp = 0;
488     
489     /********************************* String library ****************************/
490     /* Single-step over library functions creates trap loops. */
491     
492     /* Copy char s2[] to s1[]. */
493     static char*
494     gdb_cris_strcpy (char *s1, const char *s2)
495     {
496     	char *s = s1;
497     	
498     	for (s = s1; (*s++ = *s2++) != '\0'; )
499     		;
500     	return (s1);
501     }
502     
503     /* Find length of s[]. */
504     static int
505     gdb_cris_strlen (const char *s)
506     {
507     	const char *sc;
508     	
509     	for (sc = s; *sc != '\0'; sc++)
510     		;
511     	return (sc - s);
512     }
513     
514     /* Find first occurrence of c in s[n]. */
515     static void*
516     gdb_cris_memchr (const void *s, int c, int n)
517     {
518     	const unsigned char uc = c;
519     	const unsigned char *su;
520     	
521     	for (su = s; 0 < n; ++su, --n)
522     		if (*su == uc)
523     			return ((void *)su);
524     	return (NULL);
525     }
526     /******************************* Standard library ****************************/
527     /* Single-step over library functions creates trap loops. */
528     /* Convert string to long. */
529     static int
530     gdb_cris_strtol (const char *s, char **endptr, int base)
531     {
532     	char *s1;
533     	char *sd;
534     	int x = 0;
535     	
536     	for (s1 = (char*)s; (sd = gdb_cris_memchr(hexchars, *s1, base)) != NULL; ++s1)
537     		x = x * base + (sd - hexchars);
538             
539             if (endptr)
540             {
541                     /* Unconverted suffix is stored in endptr unless endptr is NULL. */
542                     *endptr = s1;
543             }
544             
545     	return x;
546     }
547     
548     int
549     double_this(int x)
550     {
551             return 2 * x;
552     }
553     
554     /********************************* Register image ****************************/
555     /* Copy the content of a register image into another. The size n is
556        the size of the register image. Due to struct assignment generation of
557        memcpy in libc. */
558     static void
559     copy_registers (registers *dptr, registers *sptr, int n)
560     {
561     	unsigned char *dreg;
562     	unsigned char *sreg;
563     	
564     	for (dreg = (unsigned char*)dptr, sreg = (unsigned char*)sptr; n > 0; n--)
565     		*dreg++ = *sreg++;
566     }
567     
568     #ifdef PROCESS_SUPPORT
569     /* Copy the stored registers from the stack. Put the register contents
570        of thread thread_id in the struct reg. */
571     static void
572     copy_registers_from_stack (int thread_id, registers *regptr)
573     {
574     	int j;
575     	stack_registers *s = (stack_registers *)stack_list[thread_id];
576     	unsigned int *d = (unsigned int *)regptr;
577     	
578     	for (j = 13; j >= 0; j--)
579     		*d++ = s->r[j];
580     	regptr->sp = (unsigned int)stack_list[thread_id];
581     	regptr->pc = s->pc;
582     	regptr->dccr = s->dccr;
583     	regptr->srp = s->srp;
584     }
585     
586     /* Copy the registers to the stack. Put the register contents of thread
587        thread_id from struct reg to the stack. */
588     static void
589     copy_registers_to_stack (int thread_id, registers *regptr)
590     {
591     	int i;
592     	stack_registers *d = (stack_registers *)stack_list[thread_id];
593     	unsigned int *s = (unsigned int *)regptr;
594     	
595     	for (i = 0; i < 14; i++) {
596     		d->r[i] = *s++;
597     	}
598     	d->pc = regptr->pc;
599     	d->dccr = regptr->dccr;
600     	d->srp = regptr->srp;
601     }
602     #endif
603     
604     /* Write a value to a specified register in the register image of the current
605        thread. Returns status code SUCCESS, E02 or E05. */
606     static int
607     write_register (int regno, char *val)
608     {
609     	int status = SUCCESS;
610     	registers *current_reg = &reg;
611     
612             if (regno >= R0 && regno <= PC) {
613     		/* 32-bit register with simple offset. */
614     		hex2mem ((unsigned char *)current_reg + regno * sizeof(unsigned int),
615     			 val, sizeof(unsigned int));
616     	}
617             else if (regno == P0 || regno == VR || regno == P4 || regno == P8) {
618     		/* Do not support read-only registers. */
619     		status = E02;
620     	}
621             else if (regno == CCR) {
622     		/* 16 bit register with complex offset. (P4 is read-only, P6 is not implemented, 
623                        and P7 (MOF) is 32 bits in ETRAX 100LX. */
624     		hex2mem ((unsigned char *)&(current_reg->ccr) + (regno-CCR) * sizeof(unsigned short),
625     			 val, sizeof(unsigned short));
626     	}
627     	else if (regno >= MOF && regno <= USP) {
628     		/* 32 bit register with complex offset.  (P8 has been taken care of.) */
629     		hex2mem ((unsigned char *)&(current_reg->ibr) + (regno-IBR) * sizeof(unsigned int),
630     			 val, sizeof(unsigned int));
631     	} 
632             else {
633     		/* Do not support nonexisting or unimplemented registers (P2, P3, and P6). */
634     		status = E05;
635     	}
636     	return status;
637     }
638     
639     #ifdef PROCESS_SUPPORT
640     /* Write a value to a specified register in the stack of a thread other
641        than the current thread. Returns status code SUCCESS or E07. */
642     static int
643     write_stack_register (int thread_id, int regno, char *valptr)
644     {
645     	int status = SUCCESS;
646     	stack_registers *d = (stack_registers *)stack_list[thread_id];
647     	unsigned int val;
648     	
649     	hex2mem ((unsigned char *)&val, valptr, sizeof(unsigned int));
650     	if (regno >= R0 && regno < SP) {
651     		d->r[regno] = val;
652     	}
653     	else if (regno == SP) {
654     		stack_list[thread_id] = val;
655     	}
656     	else if (regno == PC) {
657     		d->pc = val;
658     	}
659     	else if (regno == SRP) {
660     		d->srp = val;
661     	}
662     	else if (regno == DCCR) {
663     		d->dccr = val;
664     	}
665     	else {
666     		/* Do not support registers in the current thread. */
667     		status = E07;
668     	}
669     	return status;
670     }
671     #endif
672     
673     /* Read a value from a specified register in the register image. Returns the
674        value in the register or -1 for non-implemented registers.
675        Should check consistency_status after a call which may be E05 after changes
676        in the implementation. */
677     static int
678     read_register (char regno, unsigned int *valptr)
679     {
680     	registers *current_reg = &reg;
681     
682     	if (regno >= R0 && regno <= PC) {
683     		/* 32-bit register with simple offset. */
684     		*valptr = *(unsigned int *)((char *)current_reg + regno * sizeof(unsigned int));
685                     return SUCCESS;
686     	}
687     	else if (regno == P0 || regno == VR) {
688     		/* 8 bit register with complex offset. */
689     		*valptr = (unsigned int)(*(unsigned char *)
690                                              ((char *)&(current_reg->p0) + (regno-P0) * sizeof(char)));
691                     return SUCCESS;
692     	}
693     	else if (regno == P4 || regno == CCR) {
694     		/* 16 bit register with complex offset. */
695     		*valptr = (unsigned int)(*(unsigned short *)
696                                              ((char *)&(current_reg->p4) + (regno-P4) * sizeof(unsigned short)));
697                     return SUCCESS;
698     	}
699     	else if (regno >= MOF && regno <= USP) {
700     		/* 32 bit register with complex offset. */
701     		*valptr = *(unsigned int *)((char *)&(current_reg->p8)
702                                                 + (regno-P8) * sizeof(unsigned int));
703                     return SUCCESS;
704     	}
705     	else {
706     		/* Do not support nonexisting or unimplemented registers (P2, P3, and P6). */
707     		consistency_status = E05;
708     		return E05;
709     	}
710     }
711     
712     /********************************** Packet I/O ******************************/
713     /* Returns the character equivalent of a nibble, bit 7, 6, 5, and 4 of a byte,
714        represented by int x. */
715     static inline char
716     highhex(int x)
717     {
718     	return hexchars[(x >> 4) & 0xf];
719     }
720     
721     /* Returns the character equivalent of a nibble, bit 3, 2, 1, and 0 of a byte,
722        represented by int x. */
723     static inline char
724     lowhex(int x)
725     {
726     	return hexchars[x & 0xf];
727     }
728     
729     /* Returns the integer equivalent of a hexadecimal character. */
730     static int
731     hex (char ch)
732     {
733     	if ((ch >= 'a') && (ch <= 'f'))
734     		return (ch - 'a' + 10);
735     	if ((ch >= '0') && (ch <= '9'))
736     		return (ch - '0');
737     	if ((ch >= 'A') && (ch <= 'F'))
738     		return (ch - 'A' + 10);
739     	return (-1);
740     }
741     
742     /* Convert the memory, pointed to by mem into hexadecimal representation.
743        Put the result in buf, and return a pointer to the last character
744        in buf (null). */
745     
746     static int do_printk = 0;
747     
748     static char *
749     mem2hex(char *buf, unsigned char *mem, int count)
750     {
751     	int i;
752     	int ch;
753             
754             if (mem == NULL) {
755                     /* Bogus read from m0. FIXME: What constitutes a valid address? */
756                     for (i = 0; i < count; i++) {
757                             *buf++ = '0';
758                             *buf++ = '0';
759                     }
760             } else {
761                     /* Valid mem address. */
762                     for (i = 0; i < count; i++) {
763                             ch = *mem++;
764                             *buf++ = highhex (ch);
765                             *buf++ = lowhex (ch);
766                     }
767             }
768             
769             /* Terminate properly. */
770     	*buf = '\0';
771     	return (buf);
772     }
773     
774     /* Convert the array, in hexadecimal representation, pointed to by buf into
775        binary representation. Put the result in mem, and return a pointer to
776        the character after the last byte written. */
777     static unsigned char*
778     hex2mem (unsigned char *mem, char *buf, int count)
779     {
780     	int i;
781     	unsigned char ch;
782     	for (i = 0; i < count; i++) {
783     		ch = hex (*buf++) << 4;
784     		ch = ch + hex (*buf++);
785     		*mem++ = ch;
786     	}
787     	return (mem);
788     }
789     
790     /* Put the content of the array, in binary representation, pointed to by buf
791        into memory pointed to by mem, and return a pointer to the character after
792        the last byte written.
793        Gdb will escape $, #, and the escape char (0x7d). */
794     static unsigned char*
795     bin2mem (unsigned char *mem, unsigned char *buf, int count)
796     {
797     	int i;
798     	unsigned char *next;
799     	for (i = 0; i < count; i++) {
800     		/* Check for any escaped characters. Be paranoid and
801     		   only unescape chars that should be escaped. */
802     		if (*buf == 0x7d) {
803     			next = buf + 1;
804     			if (*next == 0x3 || *next == 0x4 || *next == 0x5D) /* #, $, ESC */
805     				{
806     					buf++;
807     					*buf += 0x20;
808     				}
809     		}
810     		*mem++ = *buf++;
811     	}
812     	return (mem);
813     }
814     
815     /* Await the sequence $<data>#<checksum> and store <data> in the array buffer
816        returned. */
817     static void
818     getpacket (char *buffer)
819     {
820     	unsigned char checksum;
821     	unsigned char xmitcsum;
822     	int i;
823     	int count;
824     	char ch;
825     	do {
826     		while ((ch = getDebugChar ()) != '$')
827     			/* Wait for the start character $ and ignore all other characters */;
828     		checksum = 0;
829     		xmitcsum = -1;
830     		count = 0;
831     		/* Read until a # or the end of the buffer is reached */
832     		while (count < BUFMAX) {
833     			ch = getDebugChar ();
834     			if (ch == '#')
835     				break;
836     			checksum = checksum + ch;
837     			buffer[count] = ch;
838     			count = count + 1;
839     		}
840     		buffer[count] = '\0';
841     		
842     		if (ch == '#') {
843     			xmitcsum = hex (getDebugChar ()) << 4;
844     			xmitcsum += hex (getDebugChar ());
845     			if (checksum != xmitcsum) {
846     				/* Wrong checksum */
847     				putDebugChar ('-');
848     			}
849     			else {
850     				/* Correct checksum */
851     				putDebugChar ('+');
852     				/* If sequence characters are received, reply with them */
853     				if (buffer[2] == ':') {
854     					putDebugChar (buffer[0]);
855     					putDebugChar (buffer[1]);
856     					/* Remove the sequence characters from the buffer */
857     					count = gdb_cris_strlen (buffer);
858     					for (i = 3; i <= count; i++)
859     						buffer[i - 3] = buffer[i];
860     				}
861     			}
862     		}
863     	} while (checksum != xmitcsum);
864     }
865     
866     /* Send $<data>#<checksum> from the <data> in the array buffer. */
867     
868     static void
869     putpacket(char *buffer)
870     {
871     	int checksum;
872     	int runlen;
873     	int encode;
874     	
875     	do {
876     		char *src = buffer;
877     		putDebugChar ('$');
878     		checksum = 0;
879     		while (*src) {
880     			/* Do run length encoding */
881     			putDebugChar (*src);
882     			checksum += *src;
883     			runlen = 0;
884     			while (runlen < RUNLENMAX && *src == src[runlen]) {
885     				runlen++;
886     			}
887     			if (runlen > 3) {
888     				/* Got a useful amount */
889     				putDebugChar ('*');
890     				checksum += '*';
891     				encode = runlen + ' ' - 4;
892     				putDebugChar (encode);
893     				checksum += encode;
894     				src += runlen;
895     			}
896     			else {
897     				src++;
898     			}
899     		}
900     		putDebugChar ('#');
901     		putDebugChar (highhex (checksum));
902     		putDebugChar (lowhex (checksum));
903     	} while(kgdb_started && (getDebugChar() != '+'));
904     }
905     
906     /* The string str is prepended with the GDB printout token and sent. Required
907        in traditional implementations. */
908     void
909     putDebugString (const unsigned char *str, int length)
910     {
911             remcomOutBuffer[0] = 'O';
912             mem2hex(&remcomOutBuffer[1], (unsigned char *)str, length);
913             putpacket(remcomOutBuffer);
914     }
915     
916     /********************************** Handle exceptions ************************/
917     /* Build and send a response packet in order to inform the host the
918        stub is stopped. TAAn...:r...;n...:r...;n...:r...;
919                         AA = signal number
920                         n... = register number (hex)
921                         r... = register contents
922                         n... = `thread'
923                         r... = thread process ID.  This is a hex integer.
924                         n... = other string not starting with valid hex digit.
925                         gdb should ignore this n,r pair and go on to the next.
926                         This way we can extend the protocol. */
927     static void
928     stub_is_stopped(int sigval)
929     {
930     	char *ptr = remcomOutBuffer;
931     	int regno;
932     
933     	unsigned int reg_cont;
934     	int status;
935             
936     	/* Send trap type (converted to signal) */
937     
938     	*ptr++ = 'T';	
939     	*ptr++ = highhex (sigval);
940     	*ptr++ = lowhex (sigval);
941     
942     	/* Send register contents. We probably only need to send the
943     	 * PC, frame pointer and stack pointer here. Other registers will be
944     	 * explicitely asked for. But for now, send all. 
945     	 */
946     	
947     	for (regno = R0; regno <= USP; regno++) {
948     		/* Store n...:r...; for the registers in the buffer. */
949     
950                     status = read_register (regno, &reg_cont);
951                     
952     		if (status == SUCCESS) {
953                             
954                             *ptr++ = highhex (regno);
955                             *ptr++ = lowhex (regno);
956                             *ptr++ = ':';
957     
958                             ptr = mem2hex(ptr, (unsigned char *)&reg_cont,
959                                           register_size[regno]);
960                             *ptr++ = ';';
961                     }
962                     
963     	}
964     
965     #ifdef PROCESS_SUPPORT
966     	/* Store the registers of the executing thread. Assume that both step,
967     	   continue, and register content requests are with respect to this
968     	   thread. The executing task is from the operating system scheduler. */
969     
970     	current_thread_c = executing_task;
971     	current_thread_g = executing_task;
972     
973     	/* A struct assignment translates into a libc memcpy call. Avoid
974     	   all libc functions in order to prevent recursive break points. */
975     	copy_registers (&reg_g, &reg, sizeof(registers));
976     
977     	/* Store thread:r...; with the executing task TID. */
978     	gdb_cris_strcpy (&remcomOutBuffer[pos], "thread:");
979     	pos += gdb_cris_strlen ("thread:");
980     	remcomOutBuffer[pos++] = highhex (executing_task);
981     	remcomOutBuffer[pos++] = lowhex (executing_task);
982     	gdb_cris_strcpy (&remcomOutBuffer[pos], ";");
983     #endif
984     
985     	/* null-terminate and send it off */
986     
987     	*ptr = 0;
988     
989     	putpacket (remcomOutBuffer);
990     }
991     
992     /* All expected commands are sent from remote.c. Send a response according
993        to the description in remote.c. */
994     static void
995     handle_exception (int sigval)
996     {
997     	/* Avoid warning of not used. */
998     
999     	USEDFUN(handle_exception);
1000     	USEDVAR(internal_stack[0]);
1001     
1002     	/* Send response. */
1003     
1004     	stub_is_stopped (sigval);
1005     
1006     	for (;;) {
1007     		remcomOutBuffer[0] = '\0';
1008     		getpacket (remcomInBuffer);
1009     		switch (remcomInBuffer[0]) {
1010     			case 'g':
1011     				/* Read registers: g
1012     				   Success: Each byte of register data is described by two hex digits.
1013     				   Registers are in the internal order for GDB, and the bytes
1014     				   in a register  are in the same order the machine uses.
1015     				   Failure: void. */
1016     				
1017     				{
1018     #ifdef PROCESS_SUPPORT
1019     					/* Use the special register content in the executing thread. */
1020     					copy_registers (&reg_g, &reg, sizeof(registers));
1021     					/* Replace the content available on the stack. */
1022     					if (current_thread_g != executing_task) {
1023     						copy_registers_from_stack (current_thread_g, &reg_g);
1024     					}
1025     					mem2hex ((unsigned char *)remcomOutBuffer, (unsigned char *)&reg_g, sizeof(registers));
1026     #else
1027     					mem2hex(remcomOutBuffer, (char *)&reg, sizeof(registers));
1028     #endif
1029     				}
1030     				break;
1031     				
1032     			case 'G':
1033     				/* Write registers. GXX..XX
1034     				   Each byte of register data  is described by two hex digits.
1035     				   Success: OK
1036     				   Failure: void. */
1037     #ifdef PROCESS_SUPPORT
1038     				hex2mem ((unsigned char *)&reg_g, &remcomInBuffer[1], sizeof(registers));
1039     				if (current_thread_g == executing_task) {
1040     					copy_registers (&reg, &reg_g, sizeof(registers));
1041     				}
1042     				else {
1043     					copy_registers_to_stack(current_thread_g, &reg_g);
1044     				}
1045     #else
1046     				hex2mem((char *)&reg, &remcomInBuffer[1], sizeof(registers));
1047     #endif
1048     				gdb_cris_strcpy (remcomOutBuffer, "OK");
1049     				break;
1050     				
1051     			case 'P':
1052     				/* Write register. Pn...=r...
1053     				   Write register n..., hex value without 0x, with value r...,
1054     				   which contains a hex value without 0x and two hex digits
1055     				   for each byte in the register (target byte order). P1f=11223344 means
1056     				   set register 31 to 44332211.
1057     				   Success: OK
1058     				   Failure: E02, E05 */
1059     				{
1060     					char *suffix;
1061     					int regno = gdb_cris_strtol (&remcomInBuffer[1], &suffix, 16);
1062     					int status;
1063     #ifdef PROCESS_SUPPORT
1064     					if (current_thread_g =! executing_task)
1065     						status = write_stack_register (current_thread_g, regno, suffix+1);
1066     					else
1067     #endif
1068     						status = write_register (regno, suffix+1);
1069     
1070     					switch (status) {
1071     						case E02:
1072     							/* Do not support read-only registers. */
1073     							gdb_cris_strcpy (remcomOutBuffer, error_message[E02]);
1074     							break;
1075     						case E05:
1076     							/* Do not support non-existing registers. */
1077     							gdb_cris_strcpy (remcomOutBuffer, error_message[E05]);
1078     							break;
1079     						case E07:
1080     							/* Do not support non-existing registers on the stack. */
1081     							gdb_cris_strcpy (remcomOutBuffer, error_message[E07]);
1082     							break;
1083     						default:
1084     							/* Valid register number. */
1085     							gdb_cris_strcpy (remcomOutBuffer, "OK");
1086     							break;
1087     					}
1088     				}
1089     				break;
1090     				
1091     			case 'm':
1092     				/* Read from memory. mAA..AA,LLLL
1093     				   AA..AA is the address and LLLL is the length.
1094     				   Success: XX..XX is the memory content.  Can be fewer bytes than
1095     				   requested if only part of the data may be read. m6000120a,6c means
1096     				   retrieve 108 byte from base address 6000120a.
1097     				   Failure: void. */
1098     				{
1099                                             char *suffix;
1100     					unsigned char *addr = (unsigned char *)gdb_cris_strtol(&remcomInBuffer[1],
1101                                                                                                    &suffix, 16);                                        int length = gdb_cris_strtol(suffix+1, 0, 16);
1102                                             
1103                                             mem2hex(remcomOutBuffer, addr, length);
1104                                     }
1105     				break;
1106     				
1107     			case 'X':
1108     				/* Write to memory. XAA..AA,LLLL:XX..XX
1109     				   AA..AA is the start address,  LLLL is the number of bytes, and
1110     				   XX..XX is the binary data.
1111     				   Success: OK
1112     				   Failure: void. */
1113     			case 'M':
1114     				/* Write to memory. MAA..AA,LLLL:XX..XX
1115     				   AA..AA is the start address,  LLLL is the number of bytes, and
1116     				   XX..XX is the hexadecimal data.
1117     				   Success: OK
1118     				   Failure: void. */
1119     				{
1120     					char *lenptr;
1121     					char *dataptr;
1122     					unsigned char *addr = (unsigned char *)gdb_cris_strtol(&remcomInBuffer[1],
1123     										      &lenptr, 16);
1124     					int length = gdb_cris_strtol(lenptr+1, &dataptr, 16);
1125     					if (*lenptr == ',' && *dataptr == ':') {
1126     						if (remcomInBuffer[0] == 'M') {
1127     							hex2mem(addr, dataptr + 1, length);
1128     						}
1129     						else /* X */ {
1130     							bin2mem(addr, dataptr + 1, length);
1131     						}
1132     						gdb_cris_strcpy (remcomOutBuffer, "OK");
1133     					}
1134     					else {
1135     						gdb_cris_strcpy (remcomOutBuffer, error_message[E06]);
1136     					}
1137     				}
1138     				break;
1139     				
1140     			case 'c':
1141     				/* Continue execution. cAA..AA
1142     				   AA..AA is the address where execution is resumed. If AA..AA is
1143     				   omitted, resume at the present address.
1144     				   Success: return to the executing thread.
1145     				   Failure: will never know. */
1146     				if (remcomInBuffer[1] != '\0') {
1147     					reg.pc = gdb_cris_strtol (&remcomInBuffer[1], 0, 16);
1148     				}
1149     				enableDebugIRQ();
1150     				return;
1151     				
1152     			case 's':
1153     				/* Step. sAA..AA
1154     				   AA..AA is the address where execution is resumed. If AA..AA is
1155     				   omitted, resume at the present address. Success: return to the
1156     				   executing thread. Failure: will never know.
1157     				   
1158     				   Should never be invoked. The single-step is implemented on
1159     				   the host side. If ever invoked, it is an internal error E04. */
1160     				gdb_cris_strcpy (remcomOutBuffer, error_message[E04]);
1161     				putpacket (remcomOutBuffer);
1162     				return;
1163     				
1164     			case '?':
1165     				/* The last signal which caused a stop. ?
1166     				   Success: SAA, where AA is the signal number.
1167     				   Failure: void. */
1168     				remcomOutBuffer[0] = 'S';
1169     				remcomOutBuffer[1] = highhex (sigval);
1170     				remcomOutBuffer[2] = lowhex (sigval);
1171     				remcomOutBuffer[3] = 0;
1172     				break;
1173     				
1174     			case 'D':
1175     				/* Detach from host. D
1176     				   Success: OK, and return to the executing thread.
1177     				   Failure: will never know */
1178     				putpacket ("OK");
1179     				return;
1180     				
1181     			case 'k':
1182     			case 'r':
1183     				/* kill request or reset request.
1184     				   Success: restart of target.
1185     				   Failure: will never know. */
1186     				kill_restart ();
1187     				break;
1188     				
1189     			case 'C':
1190     			case 'S':
1191     			case '!':
1192     			case 'R':
1193     			case 'd':
1194     				/* Continue with signal sig. Csig;AA..AA
1195     				   Step with signal sig. Ssig;AA..AA
1196     				   Use the extended remote protocol. !
1197     				   Restart the target system. R0
1198     				   Toggle debug flag. d
1199     				   Search backwards. tAA:PP,MM
1200     				   Not supported: E04 */
1201     				gdb_cris_strcpy (remcomOutBuffer, error_message[E04]);
1202     				break;
1203     #ifdef PROCESS_SUPPORT
1204     
1205     			case 'T':
1206     				/* Thread alive. TXX
1207     				   Is thread XX alive?
1208     				   Success: OK, thread XX is alive.
1209     				   Failure: E03, thread XX is dead. */
1210     				{
1211     					int thread_id = (int)gdb_cris_strtol (&remcomInBuffer[1], 0, 16);
1212     					/* Cannot tell whether it is alive or not. */
1213     					if (thread_id >= 0 && thread_id < number_of_tasks)
1214     						gdb_cris_strcpy (remcomOutBuffer, "OK");
1215     				}
1216     				break;
1217     								
1218     			case 'H':
1219     				/* Set thread for subsequent operations: Hct
1220     				   c = 'c' for thread used in step and continue;
1221     				   t can be -1 for all threads.
1222     				   c = 'g' for thread used in other  operations.
1223     				   t = 0 means pick any thread.
1224     				   Success: OK
1225     				   Failure: E01 */
1226     				{
1227     					int thread_id = gdb_cris_strtol (&remcomInBuffer[2], 0, 16);
1228     					if (remcomInBuffer[1] == 'c') {
1229     						/* c = 'c' for thread used in step and continue */
1230     						/* Do not change current_thread_c here. It would create a mess in
1231     						   the scheduler. */
1232     						gdb_cris_strcpy (remcomOutBuffer, "OK");
1233     					}
1234     					else if (remcomInBuffer[1] == 'g') {
1235     						/* c = 'g' for thread used in other  operations.
1236     						   t = 0 means pick any thread. Impossible since the scheduler does
1237     						   not allow that. */
1238     						if (thread_id >= 0 && thread_id < number_of_tasks) {
1239     							current_thread_g = thread_id;
1240     							gdb_cris_strcpy (remcomOutBuffer, "OK");
1241     						}
1242     						else {
1243     							/* Not expected - send an error message. */
1244     							gdb_cris_strcpy (remcomOutBuffer, error_message[E01]);
1245     						}
1246     					}
1247     					else {
1248     						/* Not expected - send an error message. */
1249     						gdb_cris_strcpy (remcomOutBuffer, error_message[E01]);
1250     					}
1251     				}
1252     				break;
1253     				
1254     			case 'q':
1255     			case 'Q':
1256     				/* Query of general interest. qXXXX
1257     				   Set general value XXXX. QXXXX=yyyy */
1258     				{
1259     					int pos;
1260     					int nextpos;
1261     					int thread_id;
1262     					
1263     					switch (remcomInBuffer[1]) {
1264     						case 'C':
1265     							/* Identify the remote current thread. */
1266     							gdb_cris_strcpy (&remcomOutBuffer[0], "QC");
1267     							remcomOutBuffer[2] = highhex (current_thread_c);
1268     							remcomOutBuffer[3] = lowhex (current_thread_c);
1269     							remcomOutBuffer[4] = '\0';
1270     							break;
1271     						case 'L':
1272     							gdb_cris_strcpy (&remcomOutBuffer[0], "QM");
1273     							/* Reply with number of threads. */
1274     							if (os_is_started()) {
1275     								remcomOutBuffer[2] = highhex (number_of_tasks);
1276     								remcomOutBuffer[3] = lowhex (number_of_tasks);
1277     							}
1278     							else {
1279     								remcomOutBuffer[2] = highhex (0);
1280     								remcomOutBuffer[3] = lowhex (1);
1281     							}
1282     							/* Done with the reply. */
1283     							remcomOutBuffer[4] = lowhex (1);
1284     							pos = 5;
1285     							/* Expects the argument thread id. */
1286     							for (; pos < (5 + HEXCHARS_IN_THREAD_ID); pos++)
1287     								remcomOutBuffer[pos] = remcomInBuffer[pos];
1288     							/* Reply with the thread identifiers. */
1289     							if (os_is_started()) {
1290     								/* Store the thread identifiers of all tasks. */
1291     								for (thread_id = 0; thread_id < number_of_tasks; thread_id++) {
1292     									nextpos = pos + HEXCHARS_IN_THREAD_ID - 1;
1293     									for (; pos < nextpos; pos ++)
1294     										remcomOutBuffer[pos] = lowhex (0);
1295     									remcomOutBuffer[pos++] = lowhex (thread_id);
1296     								}
1297     							}
1298     							else {
1299     								/* Store the thread identifier of the boot task. */
1300     								nextpos = pos + HEXCHARS_IN_THREAD_ID - 1;
1301     								for (; pos < nextpos; pos ++)
1302     									remcomOutBuffer[pos] = lowhex (0);
1303     								remcomOutBuffer[pos++] = lowhex (current_thread_c);
1304     							}
1305     							remcomOutBuffer[pos] = '\0';
1306     							break;
1307     						default:
1308     							/* Not supported: "" */
1309     							/* Request information about section offsets: qOffsets. */
1310     							remcomOutBuffer[0] = 0;
1311     							break;
1312     					}
1313     				}
1314     				break;
1315     #endif /* PROCESS_SUPPORT */
1316     				
1317     			default:
1318     				/* The stub should ignore other request and send an empty
1319     				   response ($#<checksum>). This way we can extend the protocol and GDB
1320     				   can tell whether the stub it is talking to uses the old or the new. */
1321     				remcomOutBuffer[0] = 0;
1322     				break;
1323     		}
1324     		putpacket(remcomOutBuffer);
1325     	}
1326     }
1327     
1328     /* The jump is to the address 0x00000002. Performs a complete re-start
1329        from scratch. */
1330     static void
1331     kill_restart ()
1332     {
1333     	__asm__ volatile ("jump 2");
1334     }
1335     
1336     /********************************** Breakpoint *******************************/
1337     /* The hook for both a static (compiled) and a dynamic breakpoint set by GDB.
1338        An internal stack is used by the stub. The register image of the caller is
1339        stored in the structure register_image.
1340        Interactive communication with the host is handled by handle_exception and
1341        finally the register image is restored. */
1342     
1343     void kgdb_handle_breakpoint(void);
1344     
1345     asm ("
1346       .global _kgdb_handle_breakpoint
1347     _kgdb_handle_breakpoint:
1348     ;;
1349     ;; Response to the break-instruction
1350     ;;
1351     ;; Create a register image of the caller
1352     ;;
1353       move     dccr,[_reg+0x5E] ; Save the flags in DCCR before disable interrupts
1354       di                        ; Disable interrupts
1355       move.d   r0,[_reg]        ; Save R0
1356       move.d   r1,[_reg+0x04]   ; Save R1
1357       move.d   r2,[_reg+0x08]   ; Save R2
1358       move.d   r3,[_reg+0x0C]   ; Save R3
1359       move.d   r4,[_reg+0x10]   ; Save R4
1360       move.d   r5,[_reg+0x14]   ; Save R5
1361       move.d   r6,[_reg+0x18]   ; Save R6
1362       move.d   r7,[_reg+0x1C]   ; Save R7
1363       move.d   r8,[_reg+0x20]   ; Save R8
1364       move.d   r9,[_reg+0x24]   ; Save R9
1365       move.d   r10,[_reg+0x28]  ; Save R10
1366       move.d   r11,[_reg+0x2C]  ; Save R11
1367       move.d   r12,[_reg+0x30]  ; Save R12
1368       move.d   r13,[_reg+0x34]  ; Save R13
1369       move.d   sp,[_reg+0x38]   ; Save SP (R14)
1370     ;; Due to the old assembler-versions BRP might not be recognized
1371       .word 0xE670              ; move brp,r0
1372       subq     2,r0             ; Set to address of previous instruction.
1373       move.d   r0,[_reg+0x3c]   ; Save the address in PC (R15)
1374       clear.b  [_reg+0x40]      ; Clear P0
1375       move     vr,[_reg+0x41]   ; Save special register P1
1376       clear.w  [_reg+0x42]      ; Clear P4
1377       move     ccr,[_reg+0x44]  ; Save special register CCR
1378       move     mof,[_reg+0x46]  ; P7
1379       clear.d  [_reg+0x4A]      ; Clear P8
1380       move     ibr,[_reg+0x4E]  ; P9,
1381       move     irp,[_reg+0x52]  ; P10,
1382       move     srp,[_reg+0x56]  ; P11,
1383       move     dtp0,[_reg+0x5A] ; P12, register BAR, assembler might not know BAR
1384                                 ; P13, register DCCR already saved
1385     ;; Due to the old assembler-versions BRP might not be recognized
1386       .word 0xE670              ; move brp,r0
1387     ;; Static (compiled) breakpoints must return to the next instruction in order
1388     ;; to avoid infinite loops. Dynamic (gdb-invoked) must restore the instruction
1389     ;; in order to execute it when execution is continued.
1390       test.b   [_is_dyn_brkp]    ; Is this a dynamic breakpoint?
1391       beq      is_static         ; No, a static breakpoint
1392       nop
1393       subq     2,r0              ; rerun the instruction the break replaced
1394     is_static:
1395       moveq    1,r1
1396       move.b   r1,[_is_dyn_brkp] ; Set the state variable to dynamic breakpoint
1397       move.d   r0,[_reg+0x62]    ; Save the return address in BRP
1398       move     usp,[_reg+0x66]   ; USP
1399     ;;
1400     ;; Handle the communication
1401     ;;
1402       move.d   _internal_stack+1020,sp ; Use the internal stack which grows upward
1403       moveq    5,r10                   ; SIGTRAP
1404       jsr      _handle_exception       ; Interactive routine
1405     ;;
1406     ;; Return to the caller
1407     ;;
1408        move.d  [_reg],r0         ; Restore R0
1409        move.d  [_reg+0x04],r1    ; Restore R1
1410        move.d  [_reg+0x08],r2    ; Restore R2
1411        move.d  [_reg+0x0C],r3    ; Restore R3
1412        move.d  [_reg+0x10],r4    ; Restore R4
1413        move.d  [_reg+0x14],r5    ; Restore R5
1414        move.d  [_reg+0x18],r6    ; Restore R6
1415        move.d  [_reg+0x1C],r7    ; Restore R7
1416        move.d  [_reg+0x20],r8    ; Restore R8
1417        move.d  [_reg+0x24],r9    ; Restore R9
1418        move.d  [_reg+0x28],r10   ; Restore R10
1419        move.d  [_reg+0x2C],r11   ; Restore R11
1420        move.d  [_reg+0x30],r12   ; Restore R12
1421        move.d  [_reg+0x34],r13   ; Restore R13
1422     ;;
1423     ;; FIXME: Which registers should be restored?
1424     ;;
1425        move.d  [_reg+0x38],sp    ; Restore SP (R14)
1426        move    [_reg+0x56],srp   ; Restore the subroutine return pointer.
1427        move    [_reg+0x5E],dccr  ; Restore DCCR
1428        move    [_reg+0x66],usp   ; Restore USP
1429        jump    [_reg+0x62]       ; A jump to the content in register BRP works.
1430        nop                       ;
1431     ");
1432     
1433     /* The hook for an interrupt generated by GDB. An internal stack is used
1434        by the stub. The register image of the caller is stored in the structure
1435        register_image. Interactive communication with the host is handled by
1436        handle_exception and finally the register image is restored. Due to the
1437        old assembler which does not recognise the break instruction and the
1438        breakpoint return pointer hex-code is used. */
1439     
1440     void kgdb_handle_serial(void);
1441     
1442     asm ("
1443       .global _kgdb_handle_serial
1444     _kgdb_handle_serial:
1445     ;;
1446     ;; Response to a serial interrupt
1447     ;;
1448     
1449       move     dccr,[_reg+0x5E] ; Save the flags in DCCR
1450       di                        ; Disable interrupts
1451       move.d   r0,[_reg]        ; Save R0
1452       move.d   r1,[_reg+0x04]   ; Save R1
1453       move.d   r2,[_reg+0x08]   ; Save R2
1454       move.d   r3,[_reg+0x0C]   ; Save R3
1455       move.d   r4,[_reg+0x10]   ; Save R4
1456       move.d   r5,[_reg+0x14]   ; Save R5
1457       move.d   r6,[_reg+0x18]   ; Save R6
1458       move.d   r7,[_reg+0x1C]   ; Save R7
1459       move.d   r8,[_reg+0x20]   ; Save R8
1460       move.d   r9,[_reg+0x24]   ; Save R9
1461       move.d   r10,[_reg+0x28]  ; Save R10
1462       move.d   r11,[_reg+0x2C]  ; Save R11
1463       move.d   r12,[_reg+0x30]  ; Save R12
1464       move.d   r13,[_reg+0x34]  ; Save R13
1465       move.d   sp,[_reg+0x38]   ; Save SP (R14)
1466       move     irp,[_reg+0x3c]  ; Save the address in PC (R15)
1467       clear.b  [_reg+0x40]      ; Clear P0
1468       move     vr,[_reg+0x41]   ; Save special register P1,
1469       clear.w  [_reg+0x42]      ; Clear P4
1470       move     ccr,[_reg+0x44]  ; Save special register CCR
1471       move     mof,[_reg+0x46]  ; P7
1472       clear.d  [_reg+0x4A]      ; Clear P8
1473       move     ibr,[_reg+0x4E]  ; P9,
1474       move     irp,[_reg+0x52]  ; P10,
1475       move     srp,[_reg+0x56]  ; P11,
1476       move     dtp0,[_reg+0x5A] ; P12, register BAR, assembler might not know BAR
1477                                 ; P13, register DCCR already saved
1478     ;; Due to the old assembler-versions BRP might not be recognized
1479       .word 0xE670              ; move brp,r0
1480       move.d   r0,[_reg+0x62]   ; Save the return address in BRP
1481       move     usp,[_reg+0x66]  ; USP
1482     
1483     ;; get the serial character (from debugport.c) and check if its a ctrl-c
1484     
1485       jsr _getDebugChar
1486       cmp.b 3, r10
1487       bne goback
1488       nop
1489     
1490     ;;
1491     ;; Handle the communication
1492     ;;
1493       move.d   _internal_stack+1020,sp ; Use the internal stack
1494       moveq    2,r10                   ; SIGINT
1495       jsr      _handle_exception       ; Interactive routine
1496     
1497     goback:
1498     ;;
1499     ;; Return to the caller
1500     ;;
1501        move.d  [_reg],r0         ; Restore R0
1502        move.d  [_reg+0x04],r1    ; Restore R1
1503        move.d  [_reg+0x08],r2    ; Restore R2
1504        move.d  [_reg+0x0C],r3    ; Restore R3
1505        move.d  [_reg+0x10],r4    ; Restore R4
1506        move.d  [_reg+0x14],r5    ; Restore R5
1507        move.d  [_reg+0x18],r6    ; Restore R6
1508        move.d  [_reg+0x1C],r7    ; Restore R7
1509        move.d  [_reg+0x20],r8    ; Restore R8
1510        move.d  [_reg+0x24],r9    ; Restore R9
1511        move.d  [_reg+0x28],r10   ; Restore R10
1512        move.d  [_reg+0x2C],r11   ; Restore R11
1513        move.d  [_reg+0x30],r12   ; Restore R12
1514        move.d  [_reg+0x34],r13   ; Restore R13
1515     ;;
1516     ;; FIXME: Which registers should be restored?
1517     ;;
1518        move.d  [_reg+0x38],sp    ; Restore SP (R14)
1519        move    [_reg+0x56],srp   ; Restore the subroutine return pointer.
1520        move    [_reg+0x5E],dccr  ; Restore DCCR
1521        move    [_reg+0x66],usp   ; Restore USP
1522        reti                      ; Return from the interrupt routine
1523        nop
1524     ");
1525     
1526     /* Use this static breakpoint in the start-up only. */
1527     
1528     void
1529     breakpoint(void)
1530     {
1531     	kgdb_started = 1;
1532     	is_dyn_brkp = 0;     /* This is a static, not a dynamic breakpoint. */
1533     	__asm__ volatile ("break 8"); /* Jump to handle_breakpoint. */
1534     }
1535     
1536     /* initialize kgdb. doesn't break into the debugger, but sets up irq and ports */
1537     
1538     void
1539     kgdb_init(void)
1540     {
1541     	/* could initialize debug port as well but it's done in head.S already... */
1542     
1543             /* breakpoint handler is now set in irq.c */
1544     	set_int_vector(8, kgdb_handle_serial, 0);
1545     	
1546     	enableDebugIRQ();
1547     }
1548     
1549     /****************************** End of file **********************************/
1550