SwDbgSub.cpp 25.4 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
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
 *
 */

// This is the source code for the subprocess forked by the Simple
// Windows Debug Server. It assumes most of the responsibility for the
// debug session, and processes all of the commands sent by clients.

// Disable too-long symbol warnings
#pragma warning ( disable : 4786 )

#include <iostream>
#include <vector>
#include <stdlib.h>
#include <assert.h>
// Must come before windows.h
#include <winsock2.h>
#include <windows.h>
#include "IOBuf.hpp"
#include "libInfo.hpp"
#include "LockableList.hpp"
#include "Message.hpp"
#include "Monitor.hpp"
#include "nt4internals.hpp"

// Uncomment the #define below to get messages on stderr
// #define DEBUGGING

using namespace std;

DWORD pid;
HANDLE procHandle;
IOBuf* ioBuf;

// State flags indicating whether the attach to the remote process
// definitively succeeded or failed
volatile bool attachFailed    = false;
volatile bool attachSucceeded = false;

// State flag indicating whether the target process is suspended.
// Modified by suspend()/resume(), viewed by debug thread, but only
// under cover of the threads lock.
volatile bool suspended       = false;

// State flags indicating whether we are considered to be attached to
// the target process and are therefore queuing up events to be sent
// back to the debug server. These flags are only accessed and
// modified under the cover of the eventLock.
Monitor* eventLock;
// The following is set to true when a client is attached to this process
volatile bool generateDebugEvents = false;
// Pointer to current debug event; non-NULL indicates a debug event is
// waiting to be sent to the client. Main thread sets this to NULL to
// indicate that the event has been consumed; also sets
// passEventToClient, below.
volatile DEBUG_EVENT* curDebugEvent = NULL;
// Set by main thread to indicate whether the most recently posted
// debug event should be passed on to the target process.
volatile bool passEventToClient = true;

void conditionalPostDebugEvent(DEBUG_EVENT* ev, DWORD* continueOrNotHandledFlag) {
  // FIXME: make it possible for the client to enable and disable
  // certain types of events (have to do so in a platform-independent
  // manner)
  switch (ev->dwDebugEventCode) {
  case EXCEPTION_DEBUG_EVENT:
    switch (ev->u.Exception.ExceptionRecord.ExceptionCode) {
    case EXCEPTION_BREAKPOINT:  break;
    case EXCEPTION_SINGLE_STEP: break;
    case EXCEPTION_ACCESS_VIOLATION: break;
    default: return;
    }
  }
  eventLock->lock();
  if (generateDebugEvents) {
    curDebugEvent = ev;
    while (curDebugEvent != NULL) {
      eventLock->wait();
    }
    if (passEventToClient) {
      *continueOrNotHandledFlag = DBG_EXCEPTION_NOT_HANDLED;
    } else {
      *continueOrNotHandledFlag = DBG_CONTINUE;
    }
  }
  eventLock->unlock();
}


//----------------------------------------------------------------------
// Module list
//

vector<LibInfo> libs;

//----------------------------------------------------------------------
// Thread list
//

struct ThreadInfo {
  DWORD tid;
  HANDLE thread;

  ThreadInfo(DWORD tid, HANDLE thread) {
    this->tid = tid;
    this->thread = thread;
  }
};

class ThreadList : public LockableList<ThreadInfo> {
public:
  bool removeByThreadID(DWORD tid) {
    for (InternalListType::iterator iter = internalList.begin();
         iter != internalList.end(); iter++) {
      if ((*iter).tid == tid) {
        internalList.erase(iter);
        return true;
      }
    }
    return false;
  }
  HANDLE threadIDToHandle(DWORD tid) {
    for (InternalListType::iterator iter = internalList.begin();
         iter != internalList.end(); iter++) {
      if ((*iter).tid == tid) {
        return (*iter).thread;
      }
    }
    return NULL;
  }
};

ThreadList threads;

//----------------------------------------------------------------------
// INITIALIZATION AND TERMINATION
//

void
printError(const char* prefix) {
  DWORD detail = GetLastError();
  LPTSTR message;
  FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                FORMAT_MESSAGE_FROM_SYSTEM,
                0,
                detail,
                0,
                (LPTSTR) &message,
                1,
                NULL);
  // FIXME: This is signaling an error: "The handle is invalid." ?
  // Do I have to do all of my WaitForDebugEvent calls from the same thread?
  cerr << prefix << ": " << message << endl;
  LocalFree(message);
}

void
endProcess(bool waitForProcess = true) {
  NT4::unloadNTDLL();
  if (waitForProcess) {
    // Though we're exiting because of an error, do not tear down the
    // target process.
    WaitForSingleObject(procHandle, INFINITE);
  }
  CloseHandle(procHandle);
  exit(0);
}

DWORD WINAPI
debugThreadEntry(void*) {
#ifdef DEBUGGING
  DWORD lastMsgId = 0;
  int count = 0;
#endif

  if (!DebugActiveProcess(pid)) {
    attachFailed = true;
    return 0;
  }

  // Wait for debug events. We keep the information from some of these
  // on the side in anticipation of later queries by the client. NOTE
  // that we leave the process running. The main thread is responsible
  // for suspending and resuming all currently-active threads upon
  // client attach and detach.

  while (true) {
    DEBUG_EVENT ev;
    if (!WaitForDebugEvent(&ev, INFINITE)) {
#ifdef DEBUGGING
      if (++count < 10) {
        // FIXME: This is signaling an error: "The handle is invalid." ?
        // Do I have to do all of my WaitForDebugEvent calls from the same thread?
        printError("WaitForDebugEvent failed");
      }
#endif
    } else {

#ifdef DEBUGGING
      if (ev.dwDebugEventCode != lastMsgId) {
        lastMsgId = ev.dwDebugEventCode;
        count = 0;
        cerr << "Debug thread received event " << ev.dwDebugEventCode << endl;
      } else {
        if (++count < 10) {
          cerr << "Debug thread received event " << ev.dwDebugEventCode << endl;
        }
      }
#endif

      DWORD dbgContinueMode = DBG_CONTINUE;

      switch (ev.dwDebugEventCode) {
      case LOAD_DLL_DEBUG_EVENT:
        conditionalPostDebugEvent(&ev, &dbgContinueMode);
        break;

      case UNLOAD_DLL_DEBUG_EVENT:
        conditionalPostDebugEvent(&ev, &dbgContinueMode);
        break;

      case CREATE_PROCESS_DEBUG_EVENT:
        threads.lock();
        // FIXME: will this deal properly with child processes? If
        // not, is it possible to make it do so?
#ifdef DEBUGGING
        cerr << "CREATE_PROCESS_DEBUG_EVENT " << ev.dwThreadId
             << " " << ev.u.CreateProcessInfo.hThread << endl;
#endif
        if (ev.u.CreateProcessInfo.hThread != NULL) {
          threads.add(ThreadInfo(ev.dwThreadId, ev.u.CreateProcessInfo.hThread));
        }
        threads.unlock();
        break;

      case CREATE_THREAD_DEBUG_EVENT:
        threads.lock();
#ifdef DEBUGGING
        cerr << "CREATE_THREAD_DEBUG_EVENT " << ev.dwThreadId
             << " " << ev.u.CreateThread.hThread << endl;
#endif
        if (suspended) {
          // Suspend this thread before adding it to the thread list
          SuspendThread(ev.u.CreateThread.hThread);
        }
        threads.add(ThreadInfo(ev.dwThreadId, ev.u.CreateThread.hThread));
        threads.unlock();
        break;

      case EXIT_THREAD_DEBUG_EVENT:
        threads.lock();
#ifdef DEBUGGING
        cerr << "EXIT_THREAD_DEBUG_EVENT " << ev.dwThreadId << endl;
#endif
        threads.removeByThreadID(ev.dwThreadId);
        threads.unlock();
        break;

      case EXCEPTION_DEBUG_EVENT:
        //      cerr << "EXCEPTION_DEBUG_EVENT" << endl;
        switch (ev.u.Exception.ExceptionRecord.ExceptionCode) {
        case EXCEPTION_BREAKPOINT:
          //        cerr << "EXCEPTION_BREAKPOINT" << endl;
          if (!attachSucceeded && !attachFailed) {
            attachSucceeded = true;
          }
          break;

        default:
          dbgContinueMode = DBG_EXCEPTION_NOT_HANDLED;
          break;
        }
        conditionalPostDebugEvent(&ev, &dbgContinueMode);
        break;

      case EXIT_PROCESS_DEBUG_EVENT:
        endProcess(false);
        // NOT REACHED
        break;

      default:
#ifdef DEBUGGING
        cerr << "Received debug event " << ev.dwDebugEventCode << endl;
#endif
        break;
      }

      ContinueDebugEvent(ev.dwProcessId, ev.dwThreadId, dbgContinueMode);
    }
  }
}

bool
attachToProcess() {
  // Create event lock
  eventLock = new Monitor();

  // Get a process handle for later
  procHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
  if (procHandle == NULL) {
    return false;
  }

  // Start up the debug thread
  DWORD debugThreadId;
  if (CreateThread(NULL, 0, &debugThreadEntry, NULL, 0, &debugThreadId) == NULL) {
    // Failed to make background debug thread. Fail.
    return false;
  }

  while ((!attachSucceeded) && (!attachFailed)) {
    Sleep(1);
  }

  if (attachFailed) {
    return false;
  }

  assert(attachSucceeded);

  return true;
}

bool
readMessage(Message* msg) {
  DWORD numRead;
  if (!ReadFile(GetStdHandle(STD_INPUT_HANDLE),
                msg,
                sizeof(Message),
                &numRead,
                NULL)) {
    return false;
  }
  if (numRead != sizeof(Message)) {
    return false;
  }
  // For "poke" messages, must follow up by reading raw data
  if (msg->type == Message::POKE) {
    char* dataBuf = new char[msg->pokeArg.numBytes];
    if (dataBuf == NULL) {
      return false;
    }
    if (!ReadFile(GetStdHandle(STD_INPUT_HANDLE),
                  dataBuf,
                  msg->pokeArg.numBytes,
                  &numRead,
                  NULL)) {
      delete[] dataBuf;
      return false;
    }
    if (numRead != msg->pokeArg.numBytes) {
      delete[] dataBuf;
      return false;
    }
    msg->pokeArg.data = (void *) dataBuf;
  }
  return true;
}

void
handlePeek(Message* msg) {
#ifdef DEBUGGING
  cerr << "Entering handlePeek()" << endl;
#endif

  char* memBuf = new char[msg->peekArg.numBytes];
  if (memBuf == NULL) {
    ioBuf->writeString("B");
    ioBuf->writeBinChar(0);
    ioBuf->flush();
    delete[] memBuf;
    return;
  }

  // Try fast case first
  DWORD numRead;
  BOOL res = ReadProcessMemory(procHandle,
                               (LPCVOID) msg->peekArg.address,
                               memBuf,
                               msg->peekArg.numBytes,
                               &numRead);
  if (res && (numRead == msg->peekArg.numBytes)) {

    // OK, complete success. Phew.
#ifdef DEBUGGING
    cerr << "Peek success case" << endl;
#endif
    ioBuf->writeString("B");
    ioBuf->writeBinChar(1);
    ioBuf->writeBinUnsignedInt(numRead);
    ioBuf->writeBinChar(1);
    ioBuf->writeBinBuf(memBuf, numRead);
  } else {
#ifdef DEBUGGING
    cerr << "*** Peek slow case ***" << endl;
#endif

    ioBuf->writeString("B");
    ioBuf->writeBinChar(1);

    // Use VirtualQuery to speed things up a bit
    DWORD numLeft = msg->peekArg.numBytes;
    char* curAddr = (char*) msg->peekArg.address;
    while (numLeft > 0) {
      MEMORY_BASIC_INFORMATION memInfo;
      VirtualQueryEx(procHandle, curAddr, &memInfo, sizeof(memInfo));
      DWORD numToRead = memInfo.RegionSize;
      if (numToRead > numLeft) {
        numToRead = numLeft;
      }
      DWORD numRead;
      if (memInfo.State == MEM_COMMIT) {
        // Read the process memory at this address for this length
        // FIXME: should check the result of this read
        ReadProcessMemory(procHandle, curAddr, memBuf,
                          numToRead, &numRead);
        // Write this out
#ifdef DEBUGGING
        cerr << "*** Writing " << numToRead << " bytes as mapped ***" << endl;
#endif
        ioBuf->writeBinUnsignedInt(numToRead);
        ioBuf->writeBinChar(1);
        ioBuf->writeBinBuf(memBuf, numToRead);
      } else {
        // Indicate region is free
#ifdef DEBUGGING
        cerr << "*** Writing " << numToRead << " bytes as unmapped ***" << endl;
#endif
        ioBuf->writeBinUnsignedInt(numToRead);
        ioBuf->writeBinChar(0);
      }
      curAddr += numToRead;
      numLeft -= numToRead;
    }
  }

  ioBuf->flush();
  delete[] memBuf;
#ifdef DEBUGGING
  cerr << "Exiting handlePeek()" << endl;
#endif
}

void
handlePoke(Message* msg) {
#ifdef DEBUGGING
  cerr << "Entering handlePoke()" << endl;
#endif
  DWORD numWritten;
  BOOL res = WriteProcessMemory(procHandle,
                                (LPVOID) msg->pokeArg.address,
                                msg->pokeArg.data,
                                msg->pokeArg.numBytes,
                                &numWritten);
  if (res && (numWritten == msg->pokeArg.numBytes)) {
    // Success
    ioBuf->writeBoolAsInt(true);
#ifdef DEBUGGING
    cerr << " (Succeeded)" << endl;
#endif
  } else {
    // Failure
    ioBuf->writeBoolAsInt(false);
#ifdef DEBUGGING
    cerr << " (Failed)" << endl;
#endif
  }
  ioBuf->writeEOL();
  ioBuf->flush();
  // We clean up the data
  char* dataBuf = (char*) msg->pokeArg.data;
  delete[] dataBuf;
#ifdef DEBUGGING
  cerr << "Exiting handlePoke()" << endl;
#endif
}

bool
suspend() {
  if (suspended) {
    return false;
  }
  // Before we suspend, we must take a snapshot of the loaded module
  // names and base addresses, since acquiring this snapshot requires
  // starting and exiting a thread in the remote process (at least on
  // NT 4).
  libs.clear();
#ifdef DEBUGGING
  cerr << "Starting suspension" << endl;
#endif
  libInfo(pid, libs);
#ifdef DEBUGGING
  cerr << "  Got lib info" << endl;
#endif
  threads.lock();
#ifdef DEBUGGING
  cerr << "  Got thread lock" << endl;
#endif
  suspended = true;
  int j = 0;
  for (int i = 0; i < threads.size(); i++) {
    j++;
    SuspendThread(threads.get(i).thread);
  }
#ifdef DEBUGGING
  cerr << "Suspended " << j << " threads" << endl;
#endif
  threads.unlock();
  return true;
}

bool
resume() {
  if (!suspended) {
    return false;
  }
  threads.lock();
  suspended = false;
  for (int i = 0; i < threads.size(); i++) {
    ResumeThread(threads.get(i).thread);
  }
  threads.unlock();
#ifdef DEBUGGING
  cerr << "Resumed process" << endl;
#endif
  return true;
}

int
main(int argc, char **argv)
{
  if (argc != 2) {
    // Should only be used by performing CreateProcess within SwDbgSrv
    exit(1);
  }

  if (sscanf(argv[1], "%u", &pid) != 1) {
    exit(1);
  }

  // Try to attach to process
  if (!attachToProcess()) {
    // Attach failed. Notify parent by writing result to stdout file
    // handle.
    char res = 0;
    DWORD numBytes;
    WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), &res, sizeof(res),
              &numBytes, NULL);
    exit(1);
  }

  // Server is expecting success result back.
  char res = 1;
  DWORD numBytes;
  WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), &res, sizeof(res),
            &numBytes, NULL);

  // Initialize our I/O buffer
  ioBuf = new IOBuf(32768, 131072);
  ioBuf->setOutputFileHandle(GetStdHandle(STD_OUTPUT_HANDLE));

  // At this point we are attached. Enter our main loop which services
  // requests from the server. Note that in order to handle attach/
  // detach properly (i.e., resumption of process upon "detach") we
  // will need another thread which handles debug events.
  while (true) {
    // Read a message from the server
    Message msg;
    if (!readMessage(&msg)) {
      endProcess();
    }

#ifdef DEBUGGING
    cerr << "Main thread read message: " << msg.type << endl;
#endif

    switch (msg.type) {
    // ATTACH and DETACH messages MUST come in pairs
    case Message::ATTACH:
      suspend();
      eventLock->lock();
      generateDebugEvents = true;
      eventLock->unlock();
      break;

    case Message::DETACH:
      eventLock->lock();
      generateDebugEvents = false;
      // Flush remaining event if any
      if (curDebugEvent != NULL) {
        curDebugEvent = NULL;
        eventLock->notifyAll();
      }
      eventLock->unlock();
      resume();
      break;

    case Message::LIBINFO:
      {
        if (!suspended) {
          ioBuf->writeInt(0);
        } else {
          // Send back formatted text
          ioBuf->writeInt(libs.size());
          for (int i = 0; i < libs.size(); i++) {
            ioBuf->writeSpace();
            ioBuf->writeInt(1);
            ioBuf->writeSpace();
            ioBuf->writeInt(libs[i].name.size());
            ioBuf->writeSpace();
            ioBuf->writeString(libs[i].name.c_str());
            ioBuf->writeSpace();
            ioBuf->writeAddress(libs[i].base);
          }
        }
        ioBuf->writeEOL();
        ioBuf->flush();
        break;
      }

    case Message::PEEK:
      handlePeek(&msg);
      break;

    case Message::POKE:
      handlePoke(&msg);
      break;

    case Message::THREADLIST:
      {
        if (!suspended) {
          ioBuf->writeInt(0);
        } else {
          threads.lock();
          ioBuf->writeInt(threads.size());
          for (int i = 0; i < threads.size(); i++) {
            ioBuf->writeSpace();
            ioBuf->writeAddress((void*) threads.get(i).thread);
          }
          threads.unlock();
        }
        ioBuf->writeEOL();
        ioBuf->flush();
        break;
      }

    case Message::DUPHANDLE:
      {
        HANDLE dup;
        if (DuplicateHandle(procHandle,
                            msg.handleArg.handle,
                            GetCurrentProcess(),
                            &dup,
                            0,
                            FALSE,
                            DUPLICATE_SAME_ACCESS)) {
          ioBuf->writeBoolAsInt(true);
          ioBuf->writeSpace();
          ioBuf->writeAddress((void*) dup);
        } else {
          ioBuf->writeBoolAsInt(false);
        }
        ioBuf->writeEOL();
        ioBuf->flush();
        break;
      }

    case Message::CLOSEHANDLE:
      {
        CloseHandle(msg.handleArg.handle);
        break;
      }

    case Message::GETCONTEXT:
      {
        if (!suspended) {
          ioBuf->writeBoolAsInt(false);
        } else {
          CONTEXT context;
          context.ContextFlags = CONTEXT_FULL | CONTEXT_DEBUG_REGISTERS;
          if (GetThreadContext(msg.handleArg.handle, &context)) {
            ioBuf->writeBoolAsInt(true);
            // EAX, EBX, ECX, EDX, ESI, EDI, EBP, ESP, EIP, DS, ES, FS, GS,
            // CS, SS, EFLAGS, DR0, DR1, DR2, DR3, DR6, DR7
            // See README-commands.txt
            ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Eax);
            ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Ebx);
            ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Ecx);
            ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Edx);
            ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Esi);
            ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Edi);
            ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Ebp);
            ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Esp);
            ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Eip);
            ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.SegDs);
            ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.SegEs);
            ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.SegFs);
            ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.SegGs);
            ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.SegCs);
            ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.SegSs);
            ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.EFlags);
            ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Dr0);
            ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Dr1);
            ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Dr2);
            ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Dr3);
            ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Dr6);
            ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Dr7);
          } else {
            ioBuf->writeBoolAsInt(false);
          }
        }
        ioBuf->writeEOL();
        ioBuf->flush();
        break;
      }

    case Message::SETCONTEXT:
      {
        if (!suspended) {
          ioBuf->writeBoolAsInt(false);
        } else {
          CONTEXT context;
          context.ContextFlags = CONTEXT_FULL | CONTEXT_DEBUG_REGISTERS;
          context.Eax    = msg.setContextArg.Eax;
          context.Ebx    = msg.setContextArg.Ebx;
          context.Ecx    = msg.setContextArg.Ecx;
          context.Edx    = msg.setContextArg.Edx;
          context.Esi    = msg.setContextArg.Esi;
          context.Edi    = msg.setContextArg.Edi;
          context.Ebp    = msg.setContextArg.Ebp;
          context.Esp    = msg.setContextArg.Esp;
          context.Eip    = msg.setContextArg.Eip;
          context.SegDs  = msg.setContextArg.Ds;
          context.SegEs  = msg.setContextArg.Es;
          context.SegFs  = msg.setContextArg.Fs;
          context.SegGs  = msg.setContextArg.Gs;
          context.SegCs  = msg.setContextArg.Cs;
          context.SegSs  = msg.setContextArg.Ss;
          context.EFlags = msg.setContextArg.EFlags;
          context.Dr0    = msg.setContextArg.Dr0;
          context.Dr1    = msg.setContextArg.Dr1;
          context.Dr2    = msg.setContextArg.Dr2;
          context.Dr3    = msg.setContextArg.Dr3;
          context.Dr6    = msg.setContextArg.Dr6;
          context.Dr7    = msg.setContextArg.Dr7;
          if (SetThreadContext(msg.setContextArg.handle, &context)) {
            ioBuf->writeBoolAsInt(true);
          } else {
            ioBuf->writeBoolAsInt(false);
          }
        }
        ioBuf->writeEOL();
        ioBuf->flush();
        break;
      }

    case Message::SELECTORENTRY:
      {
        LDT_ENTRY entry;

        if (GetThreadSelectorEntry(msg.selectorArg.handle,
                                   msg.selectorArg.selector,
                                   &entry)) {
          ioBuf->writeBoolAsInt(true);
          ioBuf->writeSpace(); ioBuf->writeAddress((void*) entry.LimitLow);
          ioBuf->writeSpace(); ioBuf->writeAddress((void*) entry.BaseLow);
          ioBuf->writeSpace(); ioBuf->writeAddress((void*) entry.HighWord.Bytes.BaseMid);
          ioBuf->writeSpace(); ioBuf->writeAddress((void*) entry.HighWord.Bytes.Flags1);
          ioBuf->writeSpace(); ioBuf->writeAddress((void*) entry.HighWord.Bytes.Flags2);
          ioBuf->writeSpace(); ioBuf->writeAddress((void*) entry.HighWord.Bytes.BaseHi);
        } else {
          ioBuf->writeBoolAsInt(false);
        }

        ioBuf->writeEOL();
        ioBuf->flush();
        break;
      }

    case Message::SUSPEND:
      suspend();
      break;

    case Message::RESUME:
      resume();
      break;

    case Message::POLLEVENT:
      eventLock->lock();
      if (curDebugEvent == NULL) {
        ioBuf->writeBoolAsInt(false);
      } else {
        ioBuf->writeBoolAsInt(true);
        ioBuf->writeSpace();
        threads.lock();
        ioBuf->writeAddress((void*) threads.threadIDToHandle(curDebugEvent->dwThreadId));
        threads.unlock();
        ioBuf->writeSpace();
        ioBuf->writeUnsignedInt(curDebugEvent->dwDebugEventCode);
        // Figure out what else to write
        switch (curDebugEvent->dwDebugEventCode) {
        case LOAD_DLL_DEBUG_EVENT:
          ioBuf->writeSpace();
          ioBuf->writeAddress(curDebugEvent->u.LoadDll.lpBaseOfDll);
          break;

        case UNLOAD_DLL_DEBUG_EVENT:
          ioBuf->writeSpace();
          ioBuf->writeAddress(curDebugEvent->u.UnloadDll.lpBaseOfDll);
          break;

        case EXCEPTION_DEBUG_EVENT:
          {
            DWORD code = curDebugEvent->u.Exception.ExceptionRecord.ExceptionCode;
            ioBuf->writeSpace();
            ioBuf->writeUnsignedInt(code);
            ioBuf->writeSpace();
            ioBuf->writeAddress(curDebugEvent->u.Exception.ExceptionRecord.ExceptionAddress);
            switch (curDebugEvent->u.Exception.ExceptionRecord.ExceptionCode) {
            case EXCEPTION_ACCESS_VIOLATION:
              ioBuf->writeSpace();
              ioBuf->writeBoolAsInt(curDebugEvent->u.Exception.ExceptionRecord.ExceptionInformation[0] != 0);
              ioBuf->writeSpace();
              ioBuf->writeAddress((void*) curDebugEvent->u.Exception.ExceptionRecord.ExceptionInformation[1]);
              break;

            default:
              break;
            }
            break;
          }

        default:
          break;
        }
      }
      eventLock->unlock();
      ioBuf->writeEOL();
      ioBuf->flush();
      break;

    case Message::CONTINUEEVENT:
      eventLock->lock();
      if (curDebugEvent == NULL) {
        ioBuf->writeBoolAsInt(false);
      } else {
        curDebugEvent = NULL;
        passEventToClient = msg.boolArg.val;
        ioBuf->writeBoolAsInt(true);
        eventLock->notify();
      }
      eventLock->unlock();
      ioBuf->writeEOL();
      ioBuf->flush();
      break;
    }
  }

  endProcess();

  // NOT REACHED
  return 0;
}