gdbhandler.c 31.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
/*---------------------------------------------------------------------*
 * Copyright (C) 2004 BroadOn Communications Corp.
 *                 
 *  $RCSfile: gdbhandler.c,v $
 *  $Revision: 1.3 $
 *  $Date: 2004/02/17 23:21:53 $
 *
 * Implements the GDB remote serial protocol for the BBPlayer
 * 
 * To do:
 *      - bullet proof mem reads and writes
 *      - bullet proof code against buffer overflows
 *      - implement "G"? (Not needed)
 *      - thread announcement & handling
 *
 *    The following gdb commands are supported:
 *    See gdb/remote.c in gdb source for details
 *
 * command          function                               Return value
 *
 *    Hct...          set thread c = 'c' or 'g'               OK or ENN
 *    g               return the value of the CPU registers   hex data or ENN
 *    Pn=value        set the value of register n to value    OK or ENN
 *
 *    mAA..AA,LLLL    Read LLLL bytes at address AA..AA       hex data or ENN
 *    MAA..AA,LLLL    Write LLLL bytes at address AA.AA       OK or ENN
 *
 *    c               Resume at current address               SNN ( signal NN)
 *    cAA..AA         Continue at address AA..AA              SNN
 *
 *    s               Step one instruction                    SNN
 *    sAA..AA         Step one instruction from AA..AA        SNN
 *
 *    k               kill
 *       
 *    z0,AA..AA,LLLL  Remove(z0)/insert(z1) memory breakpoint 
 *    Z0,AA..AA,LLLL  at address AA..AA of size LLLL          OK or ENN
 * 
 *    Tn              Checks if thread n is still alive       OK or ENN
 *
 *    ?               What was the last sigval ?              SNN (signal NN)
 *
 * Query
 *    qC
 *
 *    qfThreadInfo
 *    qsThreadInfo
 *    qThreadExtraInfo
 *
 *    qSymbol
 *
 * All commands and responses are sent with a packet which includes a
 * checksum.  A packet consists of
 *
 * $<packet info>#<checksum>.
 *
 * where
 * <packet info> :: <characters representing the command or response>
 * <checksum>    :: < two hex digits computed as modulo 256 sum of <packetinfo>>
 *
 * When a packet is received, it is first acknowledged with either '+' or '-'.
 * '+' indicates a successful transfer.  '-' indicates a failed transfer.
 *
 * Example:
 *
 * Host:                  Reply:
 * $m0,10#2a               +$00010203040506070809101112131415#42
 *
 *---------------------------------------------------------------------*/

/* Program tested with GDB 6.0 - compiled with linux as host, 
   mips-linux as target */

#include "ultragdb.h"
#include "os_bb.h"

extern char hexchars[];

/* These variable are used by the gdbIO thread when communicating with GDB */
static char  __gdbInBuffer[__GDB_BUFMAX];   /* Buffer for GDB to BB messages */
static char  __gdbOutBuffer[__GDB_BUFMAX];  /* Buffer for BB  to GDB messages */
/* Table of symbols that we need to lookup the address of */
/* So far, we don't need to look up any symbols */
#if 1
static gdbSymbol* __gdb_symbol_table = NULL;
#else
/* Sample __gdb_symbol_table.
   Note that the table must be terminated by a NULL entry.*/
                                            /* Name */     /* Address */
static gdbSymbol __gdb_symbol_table[] = { { "osRecvMesg",      NULL },
                                          { "__osDisableInt",  NULL },
                                          { NULL,              NULL } };
#endif

extern OSMesgQueue BKmq;
extern int strlen(const char* s);
extern int strcmp(const char *s1, const char *s2);
extern int strncmp(const char *s1, const char *s2, size_t n);
 
/************************************************************************
 Function: __gdbWriteThreadID
 Args:     char* buf      - Response buffer
           int   threadID - Thread ID
 Purpose:  This function writes the thread ID into the response buffer
           (null-terminated).
 Returns:  char* - Pointer to the character AFTER the last byte written
                   (i.e. position of null-terminator)
************************************************************************/
char* __gdbWriteThreadID(char* buf, int threadID)
{
    /* TODO: does this have to be in big-endian or target order? */
    /* GDB spec says big-endian, BBPlayer also big-endian so we are okay */
    if (buf == NULL) return NULL;
    else return mem2hex((char*) &threadID, buf, sizeof(threadID));
}

/************************************************************************
 Function: gdbWriteThreadList
 Args:     char* ptr     - Response buffer
           u32   limit   - The number of thread ids to report at once
           int   restart - Should we restart the thread list?
 Purpose:  This function writes the list of active thread IDs into the 
           response buffer (null-terminated).  This function will return
           once all active threads IDs or "limit" IDs have been reported.  

           If "restart" is true, then we will start at the begining of 
           the list.  Otherwise, we start where we left off from the 
           previous call.

           The format of the response is:
           m<id1>,<id2>,<id3>,...
           If there are no more thread IDs to report, the list is 
           terminated by a 'l'
 Returns:  Number of threads IDs written.

 TODO: Enhance to check buffer overflow (shouldn't be a problem
       since we are limiting the number of thread IDs reported).
************************************************************************/
int gdbWriteThreadList(char *ptr, u32 limit, int restart)
{
    static OSThread *t = NULL;
    int cnt = 0;
    int isUserThread = 0;
    int tid;
    
    if (ptr == NULL) return 0;

    /* List all thread IDs */
    if (restart)
        t = __gdbGetActiveQueue();

    /* No threads - need to restart */
    if (t == NULL) {
        *ptr++ = 'l';
        *ptr++ = 0;
        return 0;
    }
    
    /* loop through the list of current threads */
    *ptr++ = 'm'; 
    for (; (t != NULL) && (t->priority != -1); t = t->tlnext) 
    {
        isUserThread = __OS_IS_USER_THREAD(t);
        tid = __gdbGetThreadID(t);
        if (gdbShowAllThreadsFlag || isUserThread)
        {

            /* Limit the number of thread IDs that we are reporting
               at once.  We have not reported the current thread
               yet, so the next time we enter this function, we
               will be ready to report it. */
            if (cnt >= limit) return cnt;

            if (cnt > 0)
            {
                /* There was a previous thread */
                *ptr++ = ',';
            } 
            ptr = __gdbWriteThreadID(ptr, tid); /* ptr is now null-terminated */
            cnt++;
        }
         
        if (gdbDebug & GDB_DEBUG_SHOW_INFO)
            GDB_PRINTF("%s: %s Thread %d with id %d\n", gdb_module_name, 
                         isUserThread? "User": "System", cnt, tid);
    }

    /* Set t to NULL so we know that we are done */
    t = NULL;

    return cnt;
}

char* __gdbWriteThreadInfo(char *buf, int threadID)
{
    OSThread *t;
    char* tmp_str;
    char* ptr;
    char  tmp_buf[256];
    int n;

    if (buf == NULL) return NULL;
    /* Find thread */
    t = __gdbIDToThread(threadID);
    if (t == NULL) return NULL;

    ptr = tmp_buf;

    n = sprintf(ptr, "Thread ID %d", (int) t->id);
    ptr += n;

    /* Get priority */
    n = sprintf(ptr, ", Priority %d", (int) t->priority);
    ptr += n;

    /* Get thread state */
    switch (t->state) {
        case OS_STATE_STOPPED:
            tmp_str = "Stopped";
            break;

        case OS_STATE_RUNNABLE:
            tmp_str = "Runnable";
            break;

        case OS_STATE_RUNNING:
            tmp_str = "Running";
            break;

        case OS_STATE_WAITING:
            tmp_str = "Waiting";
            break;

        default:
            tmp_str = "Unknown";
            break;
    }

    n = sprintf(ptr, ", State is %s", tmp_str);
    ptr += n;

    /* Get the RCP (the interrupt mask?) */
    n = sprintf(ptr, ", RCP=0x%x", (int) t->context.rcp);
    ptr += n;
    
    /* ptr should currently be pointing to the null termination */
    /* Convert from text string to hex */
    return mem2hex(tmp_buf, buf, ptr-tmp_buf+1);
}

char* __gdbWriteSignal(char *buf, int sigval) 
{
    if (buf == NULL) return NULL;

    *buf++ =  hexchars[sigval >> 4];
    *buf++ =  hexchars[sigval % 16];
    *buf = 0;
    return buf;
}

char* __gdbWriteSRThreadID(char *buf, int threadID) 
{
    if (buf == NULL) return NULL;

    *buf++ = 't';
    *buf++ = 'h';
    *buf++ = 'r';
    *buf++ = 'e';
    *buf++ = 'a';
    *buf++ = 'd';

    *buf++ = ':';

    buf = __gdbWriteThreadID(buf, threadID);
    *buf++ = ';';
    *buf = 0;
    return buf;
}

char* __gdbStartThreadSignalReply(char *buf, int sigval) 
{
    if (buf == NULL) return NULL;

    *buf++ = 'T';
    buf = __gdbWriteSignal(buf, sigval);
    return buf;
}

void gdbWriteSignalReply(char *buf, int sigval)
{
    if (buf == NULL) return;

    *buf++ = 'S';
    __gdbWriteSignal(buf, sigval);
}

void gdbWriteThreadSignalReply(char *buf, int sigval, int threadID) 
{
    if (buf == NULL) return;

    *buf++ = 'T';
    buf = __gdbWriteSignal(buf, sigval);
    buf = __gdbWriteSRThreadID(buf, threadID);
}

/**************** GDB Symbol Functions **************/

void gdbQuerySymbol(char* buf, gdbSymbol *symbol)
{
    if (buf == NULL) return;

    if ((symbol == NULL) || (symbol->name == NULL))
    {
        /* Done with querying */
        strcpy(buf, GDB_RESP_STATUS_OK);
    }
    else 
    {
        /* Query symbol */
        strcpy(buf, "qSymbol:");
        /* Symbol name need to be in hex */
        mem2hex(symbol->name, &buf[8], strlen(symbol->name));
    }
}

/* Temporary symbol name */
static char __gdb_gt_symname[256];

int gdbAddSymbol(char* hex_symname, gdbSymbol *symbol, u32 addr)
{
    char* tmp;
    int   len;

    if (hex_symname == NULL) return 0;
    if (symbol == NULL) return 0;

    len = strlen(hex_symname)/2;
    if (len >= sizeof(__gdb_gt_symname))  /* Save one character for null-termination */
    {
        /* Argh, we are not prepared to handle symbols with such long names.
           reject with error */
        if (gdbDebug & GDB_DEBUG_SHOW_ERROR)
            GDB_PRINTF("%s: GDB symbol name too long: length=%d, max=%d\n",
                         gdb_module_name, len, sizeof(__gdb_gt_symname));
        return 0;
    }

    tmp = hex2mem(hex_symname, __gdb_gt_symname, len);
    *tmp = 0; /* Null terminate */
    if (gdbDebug & GDB_DEBUG_SHOW_INFO)
        GDB_PRINTF("%s: Address of %s is 0x%x\n", gdb_module_name, __gdb_gt_symname, addr);

    /* Verify that this is the symbol we are looking for */
    if (strcmp(__gdb_gt_symname, symbol->name) == 0) 
    {
        symbol->addr = addr;
        return 1;
    }
    else 
    {
        /* Hmmm, we didn't request this symbol */
        if (gdbDebug & GDB_DEBUG_SHOW_ERROR)
            GDB_PRINTF("%s: Did not request address for %s, requested address of %s\n",
                         gdb_module_name, __gdb_gt_symname, symbol->name);
        /* Let's ignore this response */
        return 0;
    }
}


/************************************************************************
 Function: gdbProcSetThreadPkt
 Args: 	   char* ptr  - Breakpoint command (format: type,address,length)
           char* resp - Response buffer
 Purpose:  This function parses the GDB set thread command and set
           the current thread. This function will also write to the 
           response buffer (null-terminated)
           the status to be sent to GDB:
           OK  - If the operation was successful
           ENN - If there was an error
************************************************************************/
void gdbProcSetThreadPkt(char* ptr, char *resp)
{
    /* Hct... set thread for continue/step 
       or
       Hgt... set thread for general (other operations) 
       t = thread id, -1 for all threads, 0 for any thread
    */
    
    int tid;
    char ch = ptr[0];
    

    if (ch == 'g' || ch == 'c') {                
        ptr++;
        if (hexToInt(&ptr, &tid))    /* get thread id */
        {
            int res = -1;

            if (gdbDebug & GDB_DEBUG_SHOW_INFO)
                GDB_PRINTF("%s: set thread - thread id %d\n", 
                           gdb_module_name, tid);
            
            if (ch == 'g') {
                res = __gdbSetRequestedThread(&__gdb_curThread, tid);
            }
            else if (ch == 'c')
            {
                res = __gdbSetRequestedThread(&__gdb_curRunThread, tid);
            }
            
            if (res >= 0)
            {
                strcpy(resp, GDB_RESP_STATUS_OK);
            } else {
                if (gdbDebug & GDB_DEBUG_SHOW_ERROR)
                    GDB_PRINTF("%s: set thread - thread %d not found\n", 
                               gdb_module_name, tid);
                strcpy(resp, GDB_RESP_ERR_NO_THREAD);
            }
        }
        else {
            if (gdbDebug & GDB_DEBUG_SHOW_ERROR)
                GDB_PRINTF("%s: set thread - no thread id\n", gdb_module_name);
        }
    }              
    else {
        if (gdbDebug & GDB_DEBUG_SHOW_ERROR)
            GDB_PRINTF("%s: set thread - unknown option %c\n", 
                       gdb_module_name, ch);
    }
}

/************************************************************************
 Function: gdbProcBreakPkt
 Args: 	   char  cmd  - GDB Packet Command 
           char* ptr  - Breakpoint command (format: type,address,length)
           char* resp - Response buffer
 Purpose:  This function parses the GDB breakpoint commands and sets
           the specified register for the current thread.  This function
           will also write to the response buffer (null-terminated)
           the status to be sent to GDB:
           OK  - If the operation was successful
           ENN - If there was an error
 TODO:     Add support for watchpoints
************************************************************************/
void gdbProcBreakPkt(char cmd, char* ptr, char *resp)
{
    int type, addr, length;

    if ((ptr == NULL) || (resp == NULL)) return;

    if (hexToInt(&ptr, &type)
        && (*ptr++ == ',')
        && hexToInt(&ptr, &addr)
        && (*ptr++ == ',')
        && hexToInt(&ptr, &length))
    {
        int res = -1;
        /* Verify addr is a valid address 
           (Assume that the addresses from GDB are virtual) */
        
        if (gdbDebug & GDB_DEBUG_SHOW_INFO)
            GDB_PRINTF("%s: Set/clear breakpoint at 0x%x\n", 
                       gdb_module_name, addr);
        
        if (osVirtualToPhysical( (void*) addr) == -1)
        {
            if (gdbDebug & GDB_DEBUG_SHOW_ERROR)
                GDB_PRINTF("%s: Cannot set/clear breakpoint - "
                           "invalid address 0x%x\n", 
                           gdb_module_name, addr);
            strcpy(resp, GDB_RESP_ERR_INVALID_ADDR); 
            return;
        }
        
        switch (type)
        {
            case (GDB_BREAKPT_MEMORY): 
                /* 0 = Memory   breakpoint */
                /* Used with GDB "break" */
                
                /* Need to make sure that GDB doesn't try
                   to send a breakpoint on this thread */
                if (cmd == 'z')
                    res = gdbRemoveBreakpoint(type, (u32*) addr, length);
                else res = gdbInsertBreakpoint(type, (u32*) addr, length);
                break;
                
            case (GDB_BREAKPT_HARDWARE): 
                /* 1 = Hardware breakpoint */
                /* Used with GDB "hbreak" */
                break;
                
            case (GDB_WATCHPT_WRITE): 
                /* 2 = Write  watchpoint */
                break;

            case (GDB_WATCHPT_READ): 
                /* 3 = Read   watchpoint */
                break;

            case (GDB_WATCHPT_ACCESS): 
                /* 4 = Access watchpoint */
                break;

            default: 
                /* Unknown type */
                if (gdbDebug & GDB_DEBUG_SHOW_ERROR)
                    GDB_PRINTF("%s: unknown breakpoint type %c\n", 
                               gdb_module_name, type);
                break;        
        }

        if (res >= 0)
            strcpy(resp, GDB_RESP_STATUS_OK);
        else {
            if (gdbDebug & GDB_DEBUG_SHOW_ERROR)
                GDB_PRINTF("%s: Cannot set/clear breakpoint at address 0x%x (Error code %d)\n",
                           gdb_module_name, addr, res);
            if (res == GDB_ERROR_NO_MORE_IDS)
                /* No more slots */
                strcpy(resp, GDB_RESP_ERR_NO_MORE_SLOTS);
            else strcpy(resp, GDB_RESP_ERR_OP_FAILED);
        }
    }
    else strcpy(resp, GDB_RESP_ERR_PKT_FORMAT);
}
    

/************************************************************************
 Function: gdbProcPacket
 Purpose:  This function retrieves one GDB packet, processes it, and sends
           the appropriate response back to GDB.
************************************************************************/
void gdbProcPacket()
{
    static gdbSymbol *cur_symbol = NULL;
    OSThread  *t;
    int       addr, length, tid;
    int       sigval = 0;
    char      *ptr;
    char      cmd;

    __gdbOutBuffer[0] = 0;

    /* __gdbGetPacket retrieves one packet and places it in __gdbInBuffer
       __gdbGetPacket will make sure that the packet is null-terminated */
    if (gdbDebug & GDB_DEBUG_SHOW_INFO)
        GDB_PRINTF("%s: Waiting for GDB packet\n", gdb_module_name); 
    __gdbGetPacket(__gdbInBuffer, __GDB_BUFMAX, &sigval);

    if (sigval != 0)
    {
        /* Got an interrupt signal from GDB */
        if (gdbDebug & GDB_DEBUG_SHOW_INFO)
            GDB_PRINTF("%s: Got signal %d from GDB\n", gdb_module_name, sigval);
        gdbStopUserThread(GDB_ALL_THREADS);
        gdbWriteThreadSignalReply(__gdbOutBuffer, sigval, __gdbGetCurrentThreadID());
        __gdbPutPacket(__gdbOutBuffer);
        return;
    }

    if (gdbStopUserThreadsFlag)
    {
        /* Make sure user threads are stopped when interacting with GDB */
        gdbStopUserThread(GDB_ALL_THREADS);
    }

    if (gdbDebug & GDB_DEBUG_SHOW_PACKET)
        GDB_PRINTF("%s: received packet: %s\n", gdb_module_name, __gdbInBuffer);

    cmd = __gdbInBuffer[0];
    switch(cmd) {
        case ('H'): /* Set Thread */
            /* Hct... set thread for continue/step 
               or
               Hgt... set thread for general (other operations) 
               t = thread id, -1 for all threads, 0 for any thread
            */

            /* GDB usually connects with Hc-1 */
            ptr = &__gdbInBuffer[1];
            gdbProcSetThreadPkt(ptr, __gdbOutBuffer);            
            break;

        case ('T'): /* Find out if thread is alive */
            ptr = &__gdbInBuffer[1];
            if (hexToInt(&ptr, &tid))    /* get thread id */
            {
                t = __gdbIDToThread(tid);
                if (t) {
                    strcpy(__gdbOutBuffer, GDB_RESP_STATUS_OK);
                } else {
                    if (gdbDebug & GDB_DEBUG_SHOW_ERROR)
                        GDB_PRINTF("%s: thread status - thread %d not found\n", 
                                     gdb_module_name, tid);
                    strcpy(__gdbOutBuffer, GDB_RESP_ERR_NO_THREAD);
                }
            }
            else {
                if (gdbDebug & GDB_DEBUG_SHOW_ERROR)
                    GDB_PRINTF("%s: thread state - no thread id\n", gdb_module_name);
            }
            break;            

        case ('q'): /* General Query */
            /* Used for many of the GDB "info ..." commands */
            ptr = &__gdbInBuffer[1];
            if (strcmp(ptr, "C") == 0)
            {
                /* Return the current thread id */
                __gdbOutBuffer[0] = 'Q';
                __gdbOutBuffer[1] = 'C';
                __gdbWriteThreadID(&__gdbOutBuffer[2], __gdbGetCurrentThreadID());
            }
            else if (strcmp(ptr, "fThreadInfo") == 0)
            {
                /* Return a list of active thread ids (first query) */
                int n = gdbWriteThreadList(__gdbOutBuffer, __GDB_THREAD_LIST_LIMIT, 1);
                if (gdbDebug & GDB_DEBUG_SHOW_INFO)
                    GDB_PRINTF("%s: thread info - %d threads found\n", gdb_module_name, n);
            }
            else if (strcmp(ptr, "sThreadInfo") == 0)
            {
                /* Return a list of active thread ids (subsequent queries) */
                int n = gdbWriteThreadList(__gdbOutBuffer, __GDB_THREAD_LIST_LIMIT, 0);
                if ((n > 0) && (gdbDebug & GDB_DEBUG_SHOW_INFO))
                    GDB_PRINTF("%s: thread info - %d more threads found\n", gdb_module_name, n);
            }
            else if (strncmp(ptr, "ThreadExtraInfo", 15) == 0)
            {
                if (gdbDebug & GDB_DEBUG_SHOW_INFO) 
                    GDB_PRINTF("%s: extra thread info\n", gdb_module_name);

                /* Extra thread info */
                /* Format: qThreadExtraInfo,id */
                ptr+=15; /* Skip over ThreadExtraInfo */
                if ((*ptr++ == ',') 
                    && hexToInt(&ptr, &tid))
                {
                    __gdbWriteThreadInfo(__gdbOutBuffer, tid);
                }
            }
            else if (strncmp(ptr, "L", 1) == 0)
            {
                /* Obtain thread infomation from RTOS */
                /* Format: qLstartflagthreadcountnextthread */
                ptr+=1; /* Skip over L */
            }
            else if (strncmp(ptr, "CRC:", 4) == 0)
            {
                /* Compute CRC of memory block */
                /* Format: qCRC:addr,length */
                ptr+=4; /* Skip over CRC: */
            }
            else if (strcmp(ptr, "Offsets") == 0)
            {
                /* Query section offsets */
            }
            else if (strncmp(ptr, "P", 1) == 0)
            {
                /* Thread info request */
                /* Format: qPmodethreadid */
                ptr+=1; /* Skip over P */
            }
            else if (strncmp(ptr, "Rcmd", 4) == 0)
            {
                /* Executes remote command */
                /* Format: qRcmd,command */
                ptr+=4; /* Skip over Rcmd */
            }
            else if (strncmp(ptr, "Symbol:", 7) == 0)
            {
                /* Symbol Lookup */
                /* Format: qSymbol::
                    or     qSymbol:sym_value:sym_name */
                ptr+=7; /* Skip over Symbol: */

                if (*ptr == ':') {
                    /* Ask about osRecvMsg */
                    ptr++;
                    if (*ptr == 0) {
                        /* qSymbol:: */
                        if (__gdb_symbol_table)
                            cur_symbol = &__gdb_symbol_table[0];
                        if (cur_symbol != NULL)
                        {
                            gdbQuerySymbol(__gdbOutBuffer, cur_symbol);
                            break;
                        }
                    }
                    else {
                        /* qSymbol::sym_name */
                        /* Wasn't able to get the address for symbol */
                        gdbAddSymbol(ptr, cur_symbol, 0);
                        if (cur_symbol != NULL)
                        {
                            cur_symbol++;
                            gdbQuerySymbol(__gdbOutBuffer, cur_symbol);
                            break;
                        }
                    }
                }
                else {
                    /* qSymbol:sym_value:sym_name */
                    if (hexToInt(&ptr, &addr)
                        && (*ptr++ == ':'))
                    {
                        gdbAddSymbol(ptr, cur_symbol, addr);
                        if (cur_symbol != NULL)
                        {
                            cur_symbol++;
                            gdbQuerySymbol(__gdbOutBuffer, cur_symbol);
                            break;
                        }
                    }                       
                }

                /* Reply OK if we haven't broken out of the switch */
                strcpy(__gdbOutBuffer, GDB_RESP_STATUS_OK);
            }            
            else 
            {
                if (gdbDebug & GDB_DEBUG_SHOW_ERROR)
                    GDB_PRINTF("%s: unknown query %s\n", gdb_module_name, ptr);
            }
            
            break;

        case ('?'): /* Last Signal */
            /* Indicates the reason the program was halted */
            /* Seen when GDB connects */
            gdbWriteThreadSignalReply(__gdbOutBuffer, sigval, __gdbGetCurrentThreadID());
            break;

        case ('g'): /* Read general registers */
            /* Used by GDB to determine thread state and stack backtrace */
            gdbAssembleRegisters(__gdbOutBuffer);
            break;

        case ('P'): /* Pn=value - Write register */
            /* Used by GDB when user sets a register, calls a function */
            /* E.g for setting a register: set $v0=1 */
            ptr = &__gdbInBuffer[1];
            gdbProcSetRegisterPkt(ptr, __gdbOutBuffer);
            break;

        case ('G'): /* Set general registers */
            /* Should we support this? */
            /* Used by GDB when P command not supported? */
            break;

        case ('z'): /* ztype,addr,length - Remove breakpoint or watchpoint */
        case ('Z'): /* Ztype,addr,length - Insert breakpoint or watchpoint */
            /* Parse for type, addr, and length */
            ptr = &__gdbInBuffer[1];
            gdbProcBreakPkt(cmd, ptr, __gdbOutBuffer);
            break;

        case ('c'):   /* cAA..AA    Continue at address AA..AA(optional) */
            /* Used by GDB for continue/step/next etc */
            ptr = &__gdbInBuffer[1];
            if (hexToInt(&ptr, &addr))
            {
                /* Continue thread at given address */
                gdbRunThread(__gdb_curRunThread, KK_VADDR, addr);
            }
            else
            {
                /* Continue thread */
                gdbRunThread(__gdb_curRunThread, 0, 0);
            }

            /* ### need to flush the cache !*/

            /* Check flag to see if we are going to sync with another thread */
            if (gdbWaitToSendBreakFlag)
            {
                /* Send message that we are waiting for a breakpoint to happen */
                if (gdbDebug & GDB_DEBUG_SHOW_INFO)
                    GDB_PRINTF("%s: waiting for target to halt\n", gdb_module_name);
                
                if (osSendMesg(&BKmq, NULL, OS_MESG_NOBLOCK) < 0)
                    if (gdbDebug & GDB_DEBUG_SHOW_ERROR)
                        GDB_PRINTF("%s: Unable to send message that we are waiting"
                                     "for target to halt\n", gdb_module_name);
            }

            /* Do not need to send packet - just return */
            return;
              
       case ('s'):   /* sAA..AA    Step at address AA..AA(optional) */
            /* Not observed in GDB with target="mips-linux"
               If SOFTWARE_SINGLE_STEP_P() is defined to be 1, GDB will automatically 
                  insert/remove breakpoints for stepping and will not use 's'.
               To use 's' for stepping, define SOFTWARE_SINGLE_STEP_P() to be 0
            */
            ptr = &__gdbInBuffer[1];
            if (hexToInt(&ptr, &addr))
            {
                /* Step thread at given address */
                gdbRunThread(__gdb_curRunThread, KK_VADDR | KK_STEP, addr);
            }
            else
            {
                /* Step thread */
                gdbRunThread(__gdb_curRunThread, KK_STEP, 0);
            }

            /* ### need to flush the cache !*/

            /* Check flag to see if we are going to sync with another thread */
            if (gdbWaitToSendBreakFlag)
            {
                /* Send message that we are waiting for a breakpoint to happen */
                if (gdbDebug & GDB_DEBUG_SHOW_INFO)
                    GDB_PRINTF("%s: waiting for target to halt\n", gdb_module_name);
                
                if (osSendMesg(&BKmq, NULL, OS_MESG_NOBLOCK) < 0)
                    if (gdbDebug & GDB_DEBUG_SHOW_ERROR)
                        GDB_PRINTF("%s: Unable to send message that we are waiting"
                                     " for target to halt\n", gdb_module_name);
            }

            /* Do not need to send packet - just return */
            return;

       case ('D'):
            /* GDB detaching - let's clear all breakpoints and resume the program */           
            gdbRemoveAllBreakpoints();
            gdbRunThread(GDB_ALL_THREADS, 0, 0);
            break;
             
       case ('M'):
            /* MAA..AA,LLLL: Write LLLL bytes at addr AA.AA return
               OK */
            /* Try to read '%x,%x:'.  */

            /* Used by GDB when user types: set <variable>=<value> */
            /* E.g: set gdbDebug=0 */
            ptr = &__gdbInBuffer[1];            
            if (hexToInt(&ptr, &addr)
                && *ptr++ == ','
                && hexToInt(&ptr, &length)
                && *ptr++ == ':')
            {
                /* Verify addr is a valid address (we are assuming that the 
                   addresses from GDB are virtual addresses)
                   then write value from buffer (ptr) into addr */
                if ((osVirtualToPhysical((void*) addr) != -1) &&
                    hex2mem(ptr, (char *)addr, length)) 
                {
                    /* Let's use the GDB versions so users can put breakpoints
                       in the os versions without affecting us */
                    gdbWritebackDCache((void *)addr, length);
                    gdbInvalICache((void *)addr, length);
                    strcpy(__gdbOutBuffer, GDB_RESP_STATUS_OK);
                } else
                    strcpy(__gdbOutBuffer, GDB_RESP_ERR_INVALID_ADDR);
            }
            else
                strcpy(__gdbOutBuffer, GDB_RESP_ERR_PKT_FORMAT);
            break;
            
        case ('m'):   /* mAA..AA,LLLL  Read LLLL bytes at address AA..AA */
            /* Try to read %x,%x.  */

            /* ### need to handle read fault! */
            ptr = &__gdbInBuffer[1];
            
            if (hexToInt(&ptr, &addr)
                && *ptr++ == ','
                && hexToInt(&ptr, &length))
            {
                /* Verify addr is a valid address (we are assuming that the 
                   addresses from GDB are virtual addresses)
                   then copy value from addr to __gdbOutBuffer */
                if ((osVirtualToPhysical((void*) addr) != -1) &&
                    mem2hex((char *)addr, __gdbOutBuffer, length))
                {
                    /* Success - Nothing to do */
                }
                else {
                    strcpy (__gdbOutBuffer, GDB_RESP_ERR_INVALID_ADDR);
                }
            }
            else
                strcpy(__gdbOutBuffer, GDB_RESP_ERR_PKT_FORMAT);

            break;

        case ('k'):
            /* Kill the program */
            /* For now, let's just stop the user threads */
            gdbStopUserThread(GDB_ALL_THREADS);
            break;

        default:
            /* Unsupported command - will respond with empty 
               packet (i.e. $#00) */
            if (gdbDebug & GDB_DEBUG_SHOW_ERROR)
                GDB_PRINTF("%s: unsupported command %s\n", 
                           gdb_module_name, __gdbInBuffer);
            break;
        
    }

    __gdbPutPacket(__gdbOutBuffer);
}