Merge "Inline monitor-enter in portable." into dalvik-dev
diff --git a/build/Android.common.mk b/build/Android.common.mk
index 5262ce0..65cb75d 100644
--- a/build/Android.common.mk
+++ b/build/Android.common.mk
@@ -188,6 +188,7 @@
 	src/jdwp/jdwp_expand_buf.cc \
 	src/jdwp/jdwp_handler.cc \
 	src/jdwp/jdwp_main.cc \
+	src/jdwp/jdwp_request.cc \
 	src/jdwp/jdwp_socket.cc \
 	src/jdwp/object_registry.cc \
 	src/jni_internal.cc \
@@ -257,6 +258,7 @@
 	src/utils.cc \
 	src/vector_output_stream.cc \
 	src/verifier/dex_gc_map.cc \
+	src/verifier/instruction_flags.cc \
 	src/verifier/method_verifier.cc \
 	src/verifier/reg_type.cc \
 	src/verifier/reg_type_cache.cc \
diff --git a/src/base/histogram-inl.h b/src/base/histogram-inl.h
index 3ffb9a0..9e3de9f 100644
--- a/src/base/histogram-inl.h
+++ b/src/base/histogram-inl.h
@@ -169,7 +169,7 @@
   double per_1 = per_0 + interval;
   os << Name() << ":\t";
   TimeUnit unit = GetAppropriateTimeUnit(Mean() * kAdjust);
-  os << interval << "% C.I. "
+  os << (interval * 100) << "% C.I. "
      << FormatDuration(Percentile(per_0) * kAdjust, unit);
   os << "-" << FormatDuration(Percentile(per_1) * kAdjust, unit) << " ";
   os << "Avg: " << FormatDuration(Mean() * kAdjust, unit) << " Max: ";
@@ -240,6 +240,13 @@
 
   double value = lower_value + (upper_value - lower_value) *
                                (per - lower_perc) / (upper_perc - lower_perc);
+
+  if (value < min_value_added_) {
+    value = min_value_added_;
+  } else if (value > max_value_added_) {
+    value = max_value_added_;
+  }
+
   return value;
 }
 
diff --git a/src/base/histogram_test.cc b/src/base/histogram_test.cc
index 28812fd..7a6c235 100644
--- a/src/base/histogram_test.cc
+++ b/src/base/histogram_test.cc
@@ -29,7 +29,7 @@
   hist->AddValue(28);
   hist->AddValue(28);
   mean = hist->Mean();
-  EXPECT_EQ(mean, 20.5);
+  EXPECT_EQ(20.5, mean);
 }
 
 TEST(Histtest, VarianceTest) {
@@ -42,7 +42,7 @@
   hist->AddValue(28);
   hist->CreateHistogram();
   variance = hist->Variance();
-  EXPECT_EQ(variance, 64.25);
+  EXPECT_EQ(64.25, variance);
   delete hist;
 }
 
@@ -69,7 +69,7 @@
 
   hist->CreateHistogram();
   PerValue = hist->Percentile(0.50);
-  EXPECT_EQ(static_cast<int>(PerValue * 10), 875);
+  EXPECT_EQ(875, static_cast<int>(PerValue * 10));
 
   delete hist;
 }
@@ -106,7 +106,7 @@
   std::string text;
   std::stringstream stream;
   std::string expected =
-      "UpdateRange:\t0.99% C.I. 1.050us-214.475us Avg: 126.380us Max: 212us\n";
+      "UpdateRange:\t99% C.I. 15us-212us Avg: 126.380us Max: 212us\n";
   hist->PrintConfidenceIntervals(stream, 0.99);
 
   EXPECT_EQ(expected, stream.str());
@@ -152,7 +152,7 @@
   std::string text;
   std::stringstream stream;
   std::string expected =
-      "Reset:\t0.99% C.I. 1.050us-214.475us Avg: 126.380us Max: 212us\n";
+      "Reset:\t99% C.I. 15us-212us Avg: 126.380us Max: 212us\n";
   hist->PrintConfidenceIntervals(stream, 0.99);
 
   EXPECT_EQ(expected, stream.str());
@@ -192,10 +192,9 @@
   hist->AddValue(212);
   hist->CreateHistogram();
   PerValue = hist->Percentile(0.50);
-
   std::stringstream stream;
   std::string expected =
-      "MultipleCreateHist:\t0.99% C.I. 1.050us-214.475us Avg: 126.380us Max: 212us\n";
+      "MultipleCreateHist:\t99% C.I. 15us-212us Avg: 126.380us Max: 212us\n";
   hist->PrintConfidenceIntervals(stream, 0.99);
 
   EXPECT_EQ(expected, stream.str());
@@ -208,16 +207,38 @@
 TEST(Histtest, SingleValue) {
 
   Histogram<uint64_t> *hist = new Histogram<uint64_t>("SingleValue");
-
   hist->AddValue(1);
   hist->CreateHistogram();
-
   std::stringstream stream;
-  std::string expected =
-      "SingleValue:\t0.99% C.I. 0.025us-4.975us Avg: 1us Max: 1us\n";
+  std::string expected = "SingleValue:\t99% C.I. 1us-1us Avg: 1us Max: 1us\n";
   hist->PrintConfidenceIntervals(stream, 0.99);
-  EXPECT_EQ(stream.str(), expected);
+  EXPECT_EQ(expected, stream.str());
+  delete hist;
+}
 
+TEST(Histtest, CappingPercentiles) {
+
+  double per_995;
+  double per_005;
+  Histogram<uint64_t> *hist = new Histogram<uint64_t>("CappingPercentiles");
+  // All values are similar.
+  for (uint64_t idx = 0ull; idx < 150ull; idx++) {
+    hist->AddValue(0);
+  }
+  hist->CreateHistogram();
+  per_995 = hist->Percentile(0.995);
+  EXPECT_EQ(per_995, 0);
+  hist->Reset();
+  for (size_t idx = 0; idx < 200; idx++) {
+    for (uint64_t val = 1ull; val <= 4ull; val++) {
+      hist->AddValue(val);
+    }
+  }
+  hist->CreateHistogram();
+  per_005 = hist->Percentile(0.005);
+  per_995 = hist->Percentile(0.995);
+  EXPECT_EQ(1, per_005);
+  EXPECT_EQ(4, per_995);
   delete hist;
 }
 
@@ -230,15 +251,13 @@
       hist->AddValue(idx * idx_inner);
     }
   }
-
   hist->AddValue(10000);
   hist->CreateHistogram();
-
   std::stringstream stream;
   std::string expected =
-      "SpikyValues:\t0.99% C.I. 0.089us-2541.825us Avg: 95.033us Max: 10000us\n";
+      "SpikyValues:\t99% C.I. 0.089us-2541.825us Avg: 95.033us Max: 10000us\n";
   hist->PrintConfidenceIntervals(stream, 0.99);
-  EXPECT_EQ(stream.str(), expected);
+  EXPECT_EQ(expected, stream.str());
 
   delete hist;
 }
diff --git a/src/debugger.cc b/src/debugger.cc
index 697c7cd..c96bb66 100644
--- a/src/debugger.cc
+++ b/src/debugger.cc
@@ -974,49 +974,46 @@
   return JDWP::ERR_NONE;
 }
 
+template <typename T> void CopyArrayData(mirror::Array* a, JDWP::Request& src, int offset, int count) {
+  DCHECK(a->GetClass()->IsPrimitiveArray());
+
+  T* dst = &(reinterpret_cast<T*>(a->GetRawData(sizeof(T)))[offset * sizeof(T)]);
+  for (int i = 0; i < count; ++i) {
+    *dst++ = src.ReadValue(sizeof(T));
+  }
+}
+
 JDWP::JdwpError Dbg::SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
-                                      const uint8_t* src)
+                                      JDWP::Request& request)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
   JDWP::JdwpError status;
-  mirror::Array* a = DecodeArray(array_id, status);
-  if (a == NULL) {
+  mirror::Array* dst = DecodeArray(array_id, status);
+  if (dst == NULL) {
     return status;
   }
 
-  if (offset < 0 || count < 0 || offset > a->GetLength() || a->GetLength() - offset < count) {
+  if (offset < 0 || count < 0 || offset > dst->GetLength() || dst->GetLength() - offset < count) {
     LOG(WARNING) << __FUNCTION__ << " access out of bounds: offset=" << offset << "; count=" << count;
     return JDWP::ERR_INVALID_LENGTH;
   }
-  std::string descriptor(ClassHelper(a->GetClass()).GetDescriptor());
+  std::string descriptor(ClassHelper(dst->GetClass()).GetDescriptor());
   JDWP::JdwpTag tag = BasicTagFromDescriptor(descriptor.c_str() + 1);
 
   if (IsPrimitiveTag(tag)) {
     size_t width = GetTagWidth(tag);
     if (width == 8) {
-      uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint64_t)))[offset * width]);
-      for (int i = 0; i < count; ++i) {
-        // Handle potentially non-aligned memory access one byte at a time for ARM's benefit.
-        uint64_t value;
-        for (size_t j = 0; j < sizeof(uint64_t); ++j) reinterpret_cast<uint8_t*>(&value)[j] = src[j];
-        src += sizeof(uint64_t);
-        JDWP::Write8BE(&dst, value);
-      }
+      CopyArrayData<uint64_t>(dst, request, offset, count);
     } else if (width == 4) {
-      uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint32_t)))[offset * width]);
-      const uint32_t* src4 = reinterpret_cast<const uint32_t*>(src);
-      for (int i = 0; i < count; ++i) JDWP::Write4BE(&dst, src4[i]);
+      CopyArrayData<uint32_t>(dst, request, offset, count);
     } else if (width == 2) {
-      uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint16_t)))[offset * width]);
-      const uint16_t* src2 = reinterpret_cast<const uint16_t*>(src);
-      for (int i = 0; i < count; ++i) JDWP::Write2BE(&dst, src2[i]);
+      CopyArrayData<uint16_t>(dst, request, offset, count);
     } else {
-      uint8_t* dst = &(reinterpret_cast<uint8_t*>(a->GetRawData(sizeof(uint8_t)))[offset * width]);
-      memcpy(&dst[offset * width], src, count * width);
+      CopyArrayData<uint8_t>(dst, request, offset, count);
     }
   } else {
-    mirror::ObjectArray<mirror::Object>* oa = a->AsObjectArray<mirror::Object>();
+    mirror::ObjectArray<mirror::Object>* oa = dst->AsObjectArray<mirror::Object>();
     for (int i = 0; i < count; ++i) {
-      JDWP::ObjectId id = JDWP::ReadObjectId(&src);
+      JDWP::ObjectId id = request.ReadObjectId();
       mirror::Object* o = gRegistry->Get<mirror::Object*>(id);
       if (o == ObjectRegistry::kInvalidObject) {
         return JDWP::ERR_INVALID_OBJECT;
@@ -2762,7 +2759,7 @@
 }
 
 /*
- * "buf" contains a full JDWP packet, possibly with multiple chunks.  We
+ * "request" contains a full JDWP packet, possibly with multiple chunks.  We
  * need to process each, accumulate the replies, and ship the whole thing
  * back.
  *
@@ -2772,37 +2769,35 @@
  * OLD-TODO: we currently assume that the request and reply include a single
  * chunk.  If this becomes inconvenient we will need to adapt.
  */
-bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
-  CHECK_GE(dataLen, 0);
-
+bool Dbg::DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen) {
   Thread* self = Thread::Current();
   JNIEnv* env = self->GetJniEnv();
 
-  // Create a byte[] corresponding to 'buf'.
-  ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
+  uint32_t type = request.ReadUnsigned32("type");
+  uint32_t length = request.ReadUnsigned32("length");
+
+  // Create a byte[] corresponding to 'request'.
+  size_t request_length = request.size();
+  ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(request_length));
   if (dataArray.get() == NULL) {
-    LOG(WARNING) << "byte[] allocation failed: " << dataLen;
+    LOG(WARNING) << "byte[] allocation failed: " << request_length;
     env->ExceptionClear();
     return false;
   }
-  env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
-
-  const int kChunkHdrLen = 8;
+  env->SetByteArrayRegion(dataArray.get(), 0, request_length, reinterpret_cast<const jbyte*>(request.data()));
+  request.Skip(request_length);
 
   // Run through and find all chunks.  [Currently just find the first.]
   ScopedByteArrayRO contents(env, dataArray.get());
-  jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
-  jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
-  jint offset = kChunkHdrLen;
-  if (offset + length > dataLen) {
-    LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
+  if (length != request_length) {
+    LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, request_length);
     return false;
   }
 
   // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
   ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer,
                                                                  WellKnownClasses::org_apache_harmony_dalvik_ddmc_DdmServer_dispatch,
-                                                                 type, dataArray.get(), offset, length));
+                                                                 type, dataArray.get(), 0, length));
   if (env->ExceptionCheck()) {
     LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
     env->ExceptionDescribe();
@@ -2827,8 +2822,8 @@
    * So we're pretty much stuck with copying data around multiple times.
    */
   ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_data)));
+  jint offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
   length = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_length);
-  offset = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_offset);
   type = env->GetIntField(chunk.get(), WellKnownClasses::org_apache_harmony_dalvik_ddmc_Chunk_type);
 
   VLOG(jdwp) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d", type, replyData.get(), offset, length);
@@ -2836,12 +2831,7 @@
     return false;
   }
 
-  jsize replyLength = env->GetArrayLength(replyData.get());
-  if (offset + length > replyLength) {
-    LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
-    return false;
-  }
-
+  const int kChunkHdrLen = 8;
   uint8_t* reply = new uint8_t[length + kChunkHdrLen];
   if (reply == NULL) {
     LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
@@ -2854,7 +2844,7 @@
   *pReplyBuf = reply;
   *pReplyLen = length + kChunkHdrLen;
 
-  VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", reinterpret_cast<char*>(reply), reply, length);
+  VLOG(jdwp) << StringPrintf("dvmHandleDdm returning type=%.4s %p len=%d", reinterpret_cast<char*>(reply), reply, length);
   return true;
 }
 
diff --git a/src/debugger.h b/src/debugger.h
index d63e44b..321bcf1 100644
--- a/src/debugger.h
+++ b/src/debugger.h
@@ -161,7 +161,7 @@
                                      JDWP::ExpandBuf* pReply)
       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
   static JDWP::JdwpError SetArrayElements(JDWP::ObjectId array_id, int offset, int count,
-                                          const uint8_t* buf)
+                                          JDWP::Request& request)
       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
 
   static JDWP::ObjectId CreateString(const std::string& str)
@@ -371,7 +371,7 @@
   static void DdmSendThreadNotification(Thread* t, uint32_t type)
       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
   static void DdmSetThreadNotification(bool enable);
-  static bool DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen);
+  static bool DdmHandlePacket(JDWP::Request& request, uint8_t** pReplyBuf, int* pReplyLen);
   static void DdmConnected() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
   static void DdmDisconnected() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
   static void DdmSendChunk(uint32_t type, const std::vector<uint8_t>& bytes)
diff --git a/src/disassembler_x86.cc b/src/disassembler_x86.cc
index 38171f6..bda162a 100644
--- a/src/disassembler_x86.cc
+++ b/src/disassembler_x86.cc
@@ -480,6 +480,7 @@
         break;
       case 0xAE:
         if (prefix[0] == 0xF3) {
+          prefix[0] = 0;  // clear prefix now it's served its purpose as part of the opcode
           static const char* xAE_opcodes[] = {"rdfsbase", "rdgsbase", "wrfsbase", "wrgsbase", "unknown-AE", "unknown-AE", "unknown-AE", "unknown-AE"};
           modrm_opcodes = xAE_opcodes;
           reg_is_opcode = true;
@@ -731,7 +732,18 @@
   for (size_t i = 0; begin_instr + i < instr; ++i) {
     hex << StringPrintf("%02X", begin_instr[i]);
   }
-  os << StringPrintf("%p: %22s    \t%-7s ", begin_instr, hex.str().c_str(), opcode.str().c_str()) << args.str() << '\n';
+  std::stringstream prefixed_opcode;
+  switch (prefix[0]) {
+    case 0xF0: prefixed_opcode << "lock "; break;
+    case 0xF2: prefixed_opcode << "repne "; break;
+    case 0xF3: prefixed_opcode << "repe "; break;
+    case 0: break;
+    default: LOG(FATAL) << "Unreachable";
+  }
+  prefixed_opcode << opcode.str();
+  os << StringPrintf("%p: %22s    \t%-7s ", begin_instr, hex.str().c_str(),
+                     prefixed_opcode.str().c_str())
+     << args.str() << '\n';
   return instr - begin_instr;
 }
 
diff --git a/src/jdwp/jdwp.h b/src/jdwp/jdwp.h
index 981a732..d3b6c1b 100644
--- a/src/jdwp/jdwp.h
+++ b/src/jdwp/jdwp.h
@@ -95,9 +95,9 @@
 
 struct JdwpEvent;
 struct JdwpNetState;
-struct JdwpReqHeader;
 struct JdwpTransport;
 struct ModBasket;
+struct Request;
 
 /*
  * State for JDWP functions.
@@ -225,13 +225,7 @@
   void DdmSendChunkV(uint32_t type, const iovec* iov, int iov_count)
       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
 
-  /*
-   * Process a request from the debugger.
-   *
-   * "buf" points past the header, to the content of the message.  "dataLen"
-   * can therefore be zero.
-   */
-  void ProcessRequest(const JdwpReqHeader* pHeader, const uint8_t* buf, int dataLen, ExpandBuf* pReply);
+  bool HandlePacket();
 
   /*
    * Send an event, formatted into "pReq", to the debugger.
@@ -278,6 +272,7 @@
 
  private:
   explicit JdwpState(const JdwpOptions* options);
+  void ProcessRequest(Request& request, ExpandBuf* pReply);
   bool InvokeInProgress();
   bool IsConnected();
   void SuspendByPolicy(JdwpSuspendPolicy suspend_policy, JDWP::ObjectId thread_self_id)
@@ -351,6 +346,91 @@
   int exit_status_;
 };
 
+std::string DescribeField(const FieldId& field_id) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
+std::string DescribeMethod(const MethodId& method_id) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
+std::string DescribeRefTypeId(const RefTypeId& ref_type_id) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
+
+class Request {
+ public:
+  Request(const uint8_t* bytes, uint32_t available);
+  ~Request();
+
+  std::string ReadUtf8String();
+
+  // Helper function: read a variable-width value from the input buffer.
+  uint64_t ReadValue(size_t width);
+
+  int32_t ReadSigned32(const char* what);
+
+  uint32_t ReadUnsigned32(const char* what);
+
+  FieldId ReadFieldId() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
+
+  MethodId ReadMethodId() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
+
+  ObjectId ReadObjectId(const char* specific_kind);
+
+  ObjectId ReadArrayId();
+
+  ObjectId ReadObjectId();
+
+  ObjectId ReadThreadId();
+
+  ObjectId ReadThreadGroupId();
+
+  RefTypeId ReadRefTypeId() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
+
+  FrameId ReadFrameId();
+
+  template <typename T> T ReadEnum1(const char* specific_kind) {
+    T value = static_cast<T>(Read1());
+    VLOG(jdwp) << "    " << specific_kind << " " << value;
+    return value;
+  }
+
+  JdwpTag ReadTag();
+
+  JdwpTypeTag ReadTypeTag();
+
+  JdwpLocation ReadLocation() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
+
+  JdwpModKind ReadModKind();
+
+  //
+  // Return values from this JDWP packet's header.
+  //
+  size_t GetLength() { return byte_count_; }
+  uint32_t GetId() { return id_; }
+  uint8_t GetCommandSet() { return command_set_; }
+  uint8_t GetCommand() { return command_; }
+
+  // Returns the number of bytes remaining.
+  size_t size() { return end_ - p_; }
+
+  // Returns a pointer to the next byte.
+  const uint8_t* data() { return p_; }
+
+  void Skip(size_t count) { p_ += count; }
+
+  void CheckConsumed();
+
+ private:
+  uint8_t Read1();
+  uint16_t Read2BE();
+  uint32_t Read4BE();
+  uint64_t Read8BE();
+
+  uint32_t byte_count_;
+  uint32_t id_;
+  uint8_t command_set_;
+  uint8_t command_;
+
+  const uint8_t* p_;
+  const uint8_t* end_;
+
+  DISALLOW_COPY_AND_ASSIGN(Request);
+};
+
 }  // namespace JDWP
 
 }  // namespace art
diff --git a/src/jdwp/jdwp_adb.cc b/src/jdwp/jdwp_adb.cc
index 27f9aaa..8734077 100644
--- a/src/jdwp/jdwp_adb.cc
+++ b/src/jdwp/jdwp_adb.cc
@@ -22,7 +22,6 @@
 
 #include "base/logging.h"
 #include "base/stringprintf.h"
-#include "jdwp/jdwp_handler.h"
 #include "jdwp/jdwp_priv.h"
 
 #ifdef HAVE_ANDROID_OS
@@ -46,8 +45,6 @@
  *    JDWP-handshake, etc...
  */
 
-#define kInputBufferSize    8192
-
 #define kJdwpControlName    "\0jdwp-control"
 #define kJdwpControlNameLen (sizeof(kJdwpControlName)-1)
 
@@ -61,9 +58,6 @@
   bool                shuttingDown;
   int                 wakeFds[2];
 
-  size_t inputCount;
-  unsigned char       inputBuffer[kInputBufferSize];
-
   socklen_t           controlAddrLen;
   union {
     sockaddr_un  controlAddrUn;
@@ -77,8 +71,6 @@
     wakeFds[0] = -1;
     wakeFds[1] = -1;
 
-    inputCount = 0;
-
     controlAddr.controlAddrUn.sun_family = AF_UNIX;
     controlAddrLen = sizeof(controlAddr.controlAddrUn.sun_family) + kJdwpControlNameLen;
     memcpy(controlAddr.controlAddrUn.sun_path, kJdwpControlName, kJdwpControlNameLen);
@@ -386,77 +378,6 @@
 }
 
 /*
- * Consume bytes from the buffer.
- *
- * This would be more efficient with a circular buffer.  However, we're
- * usually only going to find one packet, which is trivial to handle.
- */
-static void consumeBytes(JdwpNetState* netState, size_t count) {
-  CHECK_GT(count, 0U);
-  CHECK_LE(count, netState->inputCount);
-
-  if (count == netState->inputCount) {
-    netState->inputCount = 0;
-    return;
-  }
-
-  memmove(netState->inputBuffer, netState->inputBuffer + count, netState->inputCount - count);
-  netState->inputCount -= count;
-}
-
-/*
- * Handle a packet.  Returns "false" if we encounter a connection-fatal error.
- */
-static bool handlePacket(JdwpState* state) {
-  JdwpNetState* netState = state->netState;
-  const unsigned char* buf = netState->inputBuffer;
-  JdwpReqHeader hdr;
-  uint32_t length, id;
-  uint8_t flags, cmdSet, cmd;
-  int dataLen;
-
-  cmd = cmdSet = 0;       // shut up gcc
-
-  length = Read4BE(&buf);
-  id = Read4BE(&buf);
-  flags = Read1(&buf);
-  if ((flags & kJDWPFlagReply) != 0) {
-    LOG(FATAL) << "reply?!";
-  } else {
-    cmdSet = Read1(&buf);
-    cmd = Read1(&buf);
-  }
-
-  CHECK_LE(length, netState->inputCount);
-  dataLen = length - (buf - netState->inputBuffer);
-
-  ExpandBuf* pReply = expandBufAlloc();
-
-  hdr.length = length;
-  hdr.id = id;
-  hdr.cmdSet = cmdSet;
-  hdr.cmd = cmd;
-  state->ProcessRequest(&hdr, buf, dataLen, pReply);
-  if (expandBufGetLength(pReply) > 0) {
-    ssize_t cc = netState->writePacket(pReply);
-
-    if (cc != (ssize_t) expandBufGetLength(pReply)) {
-      PLOG(ERROR) << "Failed sending reply to debugger";
-      expandBufFree(pReply);
-      return false;
-    }
-  } else {
-    LOG(WARNING) << "No reply created for set=" << cmdSet << " cmd=" << cmd;
-  }
-  expandBufFree(pReply);
-
-  VLOG(jdwp) << "----------";
-
-  consumeBytes(netState, length);
-  return true;
-}
-
-/*
  * Process incoming data.  If no data is available, this will block until
  * some arrives.
  *
@@ -605,7 +526,7 @@
       goto fail;
     }
 
-    consumeBytes(netState, kMagicHandshakeLen);
+    netState->ConsumeBytes(kMagicHandshakeLen);
     netState->awaitingHandshake = false;
     VLOG(jdwp) << "+++ handshake complete";
     return true;
@@ -614,7 +535,7 @@
   /*
    * Handle this packet.
    */
-  return handlePacket(state);
+  return state->HandlePacket();
 
  fail:
   closeConnection(state);
@@ -640,7 +561,7 @@
 
   errno = 0;
 
-  ssize_t cc = netState->writePacket(pReq);
+  ssize_t cc = netState->WritePacket(pReq);
 
   if (cc != (ssize_t) expandBufGetLength(pReq)) {
     PLOG(ERROR) << "Failed sending req to debugger (" << cc << " of " << expandBufGetLength(pReq) << ")";
@@ -672,7 +593,7 @@
     expected += iov[i].iov_len;
   }
 
-  ssize_t actual = netState->writeBufferedPacket(iov, iov_count);
+  ssize_t actual = netState->WriteBufferedPacket(iov, iov_count);
   if ((size_t)actual != expected) {
     PLOG(ERROR) << "Failed sending b-req to debugger (" << actual << " of " << expected << ")";
     return false;
diff --git a/src/jdwp/jdwp_bits.h b/src/jdwp/jdwp_bits.h
index f40fe09..2a3c775 100644
--- a/src/jdwp/jdwp_bits.h
+++ b/src/jdwp/jdwp_bits.h
@@ -32,40 +32,6 @@
   return (pSrc[0] << 24) | (pSrc[1] << 16) | (pSrc[2] << 8) | pSrc[3];
 }
 
-static inline uint8_t Read1(unsigned const char** ppSrc) {
-  return *(*ppSrc)++;
-}
-
-static inline uint16_t Read2BE(unsigned char const** ppSrc) {
-  const unsigned char* pSrc = *ppSrc;
-  *ppSrc = pSrc + 2;
-  return pSrc[0] << 8 | pSrc[1];
-}
-
-static inline uint32_t Read4BE(unsigned char const** ppSrc) {
-  const unsigned char* pSrc = *ppSrc;
-  uint32_t result = pSrc[0] << 24;
-  result |= pSrc[1] << 16;
-  result |= pSrc[2] << 8;
-  result |= pSrc[3];
-  *ppSrc = pSrc + 4;
-  return result;
-}
-
-static inline uint64_t Read8BE(unsigned char const** ppSrc) {
-  const unsigned char* pSrc = *ppSrc;
-  uint32_t high = pSrc[0];
-  high = (high << 8) | pSrc[1];
-  high = (high << 8) | pSrc[2];
-  high = (high << 8) | pSrc[3];
-  uint32_t low = pSrc[4];
-  low = (low << 8) | pSrc[5];
-  low = (low << 8) | pSrc[6];
-  low = (low << 8) | pSrc[7];
-  *ppSrc = pSrc + 8;
-  return ((uint64_t) high << 32) | (uint64_t) low;
-}
-
 static inline void Append1BE(std::vector<uint8_t>& bytes, uint8_t value) {
   bytes.push_back(value);
 }
diff --git a/src/jdwp/jdwp_event.cc b/src/jdwp/jdwp_event.cc
index 4423058..eb385fc 100644
--- a/src/jdwp/jdwp_event.cc
+++ b/src/jdwp/jdwp_event.cc
@@ -26,7 +26,6 @@
 #include "debugger.h"
 #include "jdwp/jdwp_constants.h"
 #include "jdwp/jdwp_expand_buf.h"
-#include "jdwp/jdwp_handler.h"
 #include "jdwp/jdwp_priv.h"
 #include "thread-inl.h"
 
diff --git a/src/jdwp/jdwp_handler.cc b/src/jdwp/jdwp_handler.cc
index bc7c4d9..8ef146c 100644
--- a/src/jdwp/jdwp_handler.cc
+++ b/src/jdwp/jdwp_handler.cc
@@ -14,19 +14,6 @@
  * limitations under the License.
  */
 
-/*
- * Handle messages from debugger.
- *
- * GENERAL NOTE: we're not currently testing the message length for
- * correctness.  This is usually a bad idea, but here we can probably
- * get away with it so long as the debugger isn't broken.  We can
- * change the "read" macros to use "dataLen" to avoid wandering into
- * bad territory, and have a single "is dataLen correct" check at the
- * end of each function.  Not needed at this time.
- */
-
-#include "jdwp/jdwp_handler.h"
-
 #include <stdlib.h>
 #include <string.h>
 #include <unistd.h>
@@ -50,138 +37,21 @@
 
 namespace JDWP {
 
-static std::string DescribeField(const FieldId& field_id)
-    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
+std::string DescribeField(const FieldId& field_id) {
   return StringPrintf("%#x (%s)", field_id, Dbg::GetFieldName(field_id).c_str());
 }
 
-static std::string DescribeMethod(const MethodId& method_id)
-    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
+std::string DescribeMethod(const MethodId& method_id) {
   return StringPrintf("%#x (%s)", method_id, Dbg::GetMethodName(method_id).c_str());
 }
 
-static std::string DescribeRefTypeId(const RefTypeId& ref_type_id)
-    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
+std::string DescribeRefTypeId(const RefTypeId& ref_type_id) {
   std::string signature("unknown");
   Dbg::GetSignature(ref_type_id, signature);
   return StringPrintf("%#llx (%s)", ref_type_id, signature.c_str());
 }
 
-/*
- * Helper function: read a variable-width value from the input buffer.
- */
-static uint64_t ReadValue(const uint8_t** pBuf, size_t width) {
-  uint64_t value = -1;
-  switch (width) {
-  case 1:     value = Read1(pBuf); break;
-  case 2:     value = Read2BE(pBuf); break;
-  case 4:     value = Read4BE(pBuf); break;
-  case 8:     value = Read8BE(pBuf); break;
-  default:    LOG(FATAL) << width; break;
-  }
-  return value;
-}
-
-static int32_t ReadSigned32(const char* what, const uint8_t** pBuf) {
-  int32_t value = static_cast<int32_t>(Read4BE(pBuf));
-  VLOG(jdwp) << "    " << what << " " << value;
-  return value;
-}
-
-uint32_t ReadUnsigned32(const char* what, const uint8_t** pBuf) {
-  uint32_t value = Read4BE(pBuf);
-  VLOG(jdwp) << "    " << what << " " << value;
-  return value;
-}
-
-static FieldId ReadFieldId(const uint8_t** pBuf) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  FieldId id = Read4BE(pBuf);
-  VLOG(jdwp) << "    field id " << DescribeField(id);
-  return id;
-}
-
-static MethodId ReadMethodId(const uint8_t** pBuf) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  MethodId id = Read4BE(pBuf);
-  VLOG(jdwp) << "    method id " << DescribeMethod(id);
-  return id;
-}
-
-static ObjectId ReadObjectId(const char* specific_kind, const uint8_t** pBuf) {
-  ObjectId id = Read8BE(pBuf);
-  VLOG(jdwp) << StringPrintf("    %s id %#llx", specific_kind, id);
-  return id;
-}
-
-static ObjectId ReadArrayId(const uint8_t** pBuf) {
-  return ReadObjectId("array", pBuf);
-}
-
-ObjectId ReadObjectId(const uint8_t** pBuf) {
-  return ReadObjectId("object", pBuf);
-}
-
-static ObjectId ReadThreadId(const uint8_t** pBuf) {
-  return ReadObjectId("thread", pBuf);
-}
-
-static ObjectId ReadThreadGroupId(const uint8_t** pBuf) {
-  return ReadObjectId("thread group", pBuf);
-}
-
-static RefTypeId ReadRefTypeId(const uint8_t** pBuf) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  RefTypeId id = Read8BE(pBuf);
-  VLOG(jdwp) << "    ref type id " << DescribeRefTypeId(id);
-  return id;
-}
-
-static FrameId ReadFrameId(const uint8_t** pBuf) {
-  FrameId id = Read8BE(pBuf);
-  VLOG(jdwp) << "    frame id " << id;
-  return id;
-}
-
-static JdwpTag ReadTag(const uint8_t** pBuf) {
-  JdwpTag tag = static_cast<JdwpTag>(Read1(pBuf));
-  VLOG(jdwp) << "    tag " << tag;
-  return tag;
-}
-
-static JdwpTypeTag ReadTypeTag(const uint8_t** pBuf) {
-  JdwpTypeTag tag = static_cast<JdwpTypeTag>(Read1(pBuf));
-  VLOG(jdwp) << "    type tag " << tag;
-  return tag;
-}
-
-static JdwpLocation ReadLocation(const uint8_t** pBuf) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  JdwpLocation location;
-  memset(&location, 0, sizeof(location)); // Allows memcmp(3) later.
-  location.type_tag = ReadTypeTag(pBuf);
-  location.class_id = ReadObjectId(pBuf);
-  location.method_id = ReadMethodId(pBuf);
-  location.dex_pc = Read8BE(pBuf);
-  VLOG(jdwp) << "    location " << location;
-  return location;
-}
-
-static std::string ReadUtf8String(unsigned char const** ppSrc) {
-  uint32_t length = Read4BE(ppSrc);
-  std::string s;
-  s.resize(length);
-  memcpy(&s[0], *ppSrc, length);
-  (*ppSrc) += length;
-  VLOG(jdwp) << "    string \"" << s << "\"";
-  return s;
-}
-
-static JdwpModKind ReadModKind(const uint8_t** pBuf) {
-  JdwpModKind mod_kind = static_cast<JdwpModKind>(Read1(pBuf));
-  VLOG(jdwp) << "    mod kind " << mod_kind;
-  return mod_kind;
-}
-
-/*
- * Helper function: write a variable-width value into the output input buffer.
- */
+// Helper function: write a variable-width value into the output input buffer.
 static void WriteValue(ExpandBuf* pReply, int width, uint64_t value) {
   switch (width) {
   case 1:     expandBufAdd1(pReply, value); break;
@@ -221,13 +91,13 @@
  * If "is_constructor" is set, this returns "object_id" rather than the
  * expected-to-be-void return value of the called function.
  */
-static JdwpError FinishInvoke(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply,
+static JdwpError FinishInvoke(JdwpState*, Request& request, ExpandBuf* pReply,
                               ObjectId thread_id, ObjectId object_id,
                               RefTypeId class_id, MethodId method_id, bool is_constructor)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
   CHECK(!is_constructor || object_id != 0);
 
-  int32_t arg_count = ReadSigned32("argument count", &buf);
+  int32_t arg_count = request.ReadSigned32("argument count");
 
   VLOG(jdwp) << StringPrintf("    --> thread_id=%#llx object_id=%#llx", thread_id, object_id);
   VLOG(jdwp) << StringPrintf("        class_id=%#llx method_id=%x %s.%s", class_id,
@@ -238,13 +108,13 @@
   UniquePtr<JdwpTag[]> argTypes(arg_count > 0 ? new JdwpTag[arg_count] : NULL);
   UniquePtr<uint64_t[]> argValues(arg_count > 0 ? new uint64_t[arg_count] : NULL);
   for (int32_t i = 0; i < arg_count; ++i) {
-    argTypes[i] = ReadTag(&buf);
+    argTypes[i] = request.ReadTag();
     size_t width = Dbg::GetTagWidth(argTypes[i]);
-    argValues[i] = ReadValue(&buf, width);
+    argValues[i] = request.ReadValue(width);
     VLOG(jdwp) << "          " << argTypes[i] << StringPrintf("(%zd): %#llx", width, argValues[i]);
   }
 
-  uint32_t options = Read4BE(&buf);  /* enum InvokeOptions bit flags */
+  uint32_t options = request.ReadUnsigned32("InvokeOptions bit flags");
   VLOG(jdwp) << StringPrintf("        options=0x%04x%s%s", options,
                              (options & INVOKE_SINGLE_THREADED) ? " (SINGLE_THREADED)" : "",
                              (options & INVOKE_NONVIRTUAL) ? " (NONVIRTUAL)" : "");
@@ -288,7 +158,7 @@
   return err;
 }
 
-static JdwpError VM_Version(JdwpState*, const uint8_t*, int, ExpandBuf* pReply)
+static JdwpError VM_Version(JdwpState*, Request&, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
   // Text information on runtime version.
   std::string version(StringPrintf("Android Runtime %s", Runtime::Current()->GetVersion()));
@@ -312,9 +182,9 @@
  * referenceTypeID.  We need to send back more than one if the class has
  * been loaded by multiple class loaders.
  */
-static JdwpError VM_ClassesBySignature(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError VM_ClassesBySignature(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  std::string classDescriptor(ReadUtf8String(&buf));
+  std::string classDescriptor(request.ReadUtf8String());
 
   std::vector<RefTypeId> ids;
   Dbg::FindLoadedClassBySignature(classDescriptor.c_str(), ids);
@@ -344,7 +214,7 @@
  * We exclude ourselves from the list, because we don't allow ourselves
  * to be suspended, and that violates some JDWP expectations.
  */
-static JdwpError VM_AllThreads(JdwpState*, const uint8_t*, int, ExpandBuf* pReply)
+static JdwpError VM_AllThreads(JdwpState*, Request&, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
   std::vector<ObjectId> thread_ids;
   Dbg::GetThreads(0, thread_ids);
@@ -360,7 +230,7 @@
 /*
  * List all thread groups that do not have a parent.
  */
-static JdwpError VM_TopLevelThreadGroups(JdwpState*, const uint8_t*, int, ExpandBuf* pReply)
+static JdwpError VM_TopLevelThreadGroups(JdwpState*, Request&, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
   /*
    * TODO: maintain a list of parentless thread groups in the VM.
@@ -381,7 +251,7 @@
  *
  * All IDs are 8 bytes.
  */
-static JdwpError VM_IDSizes(JdwpState*, const uint8_t*, int, ExpandBuf* pReply)
+static JdwpError VM_IDSizes(JdwpState*, Request&, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
   expandBufAdd4BE(pReply, sizeof(FieldId));
   expandBufAdd4BE(pReply, sizeof(MethodId));
@@ -391,7 +261,7 @@
   return ERR_NONE;
 }
 
-static JdwpError VM_Dispose(JdwpState*, const uint8_t*, int, ExpandBuf*)
+static JdwpError VM_Dispose(JdwpState*, Request&, ExpandBuf*)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
   Dbg::Disposed();
   return ERR_NONE;
@@ -403,7 +273,7 @@
  *
  * This needs to increment the "suspend count" on all threads.
  */
-static JdwpError VM_Suspend(JdwpState*, const uint8_t*, int, ExpandBuf*)
+static JdwpError VM_Suspend(JdwpState*, Request&, ExpandBuf*)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
   Thread* self = Thread::Current();
   self->TransitionFromRunnableToSuspended(kWaitingForDebuggerSuspension);
@@ -415,15 +285,15 @@
 /*
  * Resume execution.  Decrements the "suspend count" of all threads.
  */
-static JdwpError VM_Resume(JdwpState*, const uint8_t*, int, ExpandBuf*)
+static JdwpError VM_Resume(JdwpState*, Request&, ExpandBuf*)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
   Dbg::ResumeVM();
   return ERR_NONE;
 }
 
-static JdwpError VM_Exit(JdwpState* state, const uint8_t* buf, int, ExpandBuf*)
+static JdwpError VM_Exit(JdwpState* state, Request& request, ExpandBuf*)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  uint32_t exit_status = ReadUnsigned32("exit_status", &buf);
+  uint32_t exit_status = request.ReadUnsigned32("exit_status");
   state->ExitAfterReplying(exit_status);
   return ERR_NONE;
 }
@@ -434,9 +304,9 @@
  * (Ctrl-Shift-I in Eclipse on an array of objects causes it to create the
  * string "java.util.Arrays".)
  */
-static JdwpError VM_CreateString(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError VM_CreateString(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  std::string str(ReadUtf8String(&buf));
+  std::string str(request.ReadUtf8String());
   ObjectId stringId = Dbg::CreateString(str);
   if (stringId == 0) {
     return ERR_OUT_OF_MEMORY;
@@ -445,7 +315,7 @@
   return ERR_NONE;
 }
 
-static JdwpError VM_ClassPaths(JdwpState*, const uint8_t*, int, ExpandBuf* pReply)
+static JdwpError VM_ClassPaths(JdwpState*, Request&, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
   expandBufAddUtf8String(pReply, "/");
 
@@ -466,18 +336,18 @@
   return ERR_NONE;
 }
 
-static JdwpError VM_DisposeObjects(JdwpState*, const uint8_t* buf, int, ExpandBuf*)
+static JdwpError VM_DisposeObjects(JdwpState*, Request& request, ExpandBuf*)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  size_t object_count = ReadUnsigned32("object_count", &buf);
+  size_t object_count = request.ReadUnsigned32("object_count");
   for (size_t i = 0; i < object_count; ++i) {
-    ObjectId object_id = ReadObjectId(&buf);
-    uint32_t reference_count = ReadUnsigned32("reference_count", &buf);
+    ObjectId object_id = request.ReadObjectId();
+    uint32_t reference_count = request.ReadUnsigned32("reference_count");
     Dbg::DisposeObject(object_id, reference_count);
   }
   return ERR_NONE;
 }
 
-static JdwpError VM_Capabilities(JdwpState*, const uint8_t*, int, ExpandBuf* reply)
+static JdwpError VM_Capabilities(JdwpState*, Request&, ExpandBuf* reply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
   expandBufAdd1(reply, false);   // canWatchFieldModification
   expandBufAdd1(reply, false);   // canWatchFieldAccess
@@ -489,11 +359,11 @@
   return ERR_NONE;
 }
 
-static JdwpError VM_CapabilitiesNew(JdwpState*, const uint8_t*, int, ExpandBuf* reply)
+static JdwpError VM_CapabilitiesNew(JdwpState*, Request& request, ExpandBuf* reply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
 
   // The first few capabilities are the same as those reported by the older call.
-  VM_Capabilities(NULL, NULL, 0, reply);
+  VM_Capabilities(NULL, request, reply);
 
   expandBufAdd1(reply, false);   // canRedefineClasses
   expandBufAdd1(reply, false);   // canAddMethod
@@ -548,25 +418,25 @@
   return ERR_NONE;
 }
 
-static JdwpError VM_AllClasses(JdwpState*, const uint8_t*, int, ExpandBuf* pReply)
+static JdwpError VM_AllClasses(JdwpState*, Request&, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
   return VM_AllClassesImpl(pReply, true, false);
 }
 
-static JdwpError VM_AllClassesWithGeneric(JdwpState*, const uint8_t*, int, ExpandBuf* pReply)
+static JdwpError VM_AllClassesWithGeneric(JdwpState*, Request&, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
   return VM_AllClassesImpl(pReply, true, true);
 }
 
-static JdwpError VM_InstanceCounts(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError VM_InstanceCounts(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  int32_t class_count = ReadSigned32("class count", &buf);
+  int32_t class_count = request.ReadSigned32("class count");
   if (class_count < 0) {
     return ERR_ILLEGAL_ARGUMENT;
   }
   std::vector<RefTypeId> class_ids;
   for (int32_t i = 0; i < class_count; ++i) {
-    class_ids.push_back(ReadRefTypeId(&buf));
+    class_ids.push_back(request.ReadRefTypeId());
   }
 
   std::vector<uint64_t> counts;
@@ -582,22 +452,22 @@
   return ERR_NONE;
 }
 
-static JdwpError RT_Modifiers(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError RT_Modifiers(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  RefTypeId refTypeId = ReadRefTypeId(&buf);
+  RefTypeId refTypeId = request.ReadRefTypeId();
   return Dbg::GetModifiers(refTypeId, pReply);
 }
 
 /*
  * Get values from static fields in a reference type.
  */
-static JdwpError RT_GetValues(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError RT_GetValues(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  RefTypeId refTypeId = ReadRefTypeId(&buf);
-  int32_t field_count = ReadSigned32("field count", &buf);
+  RefTypeId refTypeId = request.ReadRefTypeId();
+  int32_t field_count = request.ReadSigned32("field count");
   expandBufAdd4BE(pReply, field_count);
   for (int32_t i = 0; i < field_count; ++i) {
-    FieldId fieldId = ReadFieldId(&buf);
+    FieldId fieldId = request.ReadFieldId();
     JdwpError status = Dbg::GetStaticFieldValue(refTypeId, fieldId, pReply);
     if (status != ERR_NONE) {
       return status;
@@ -609,9 +479,9 @@
 /*
  * Get the name of the source file in which a reference type was declared.
  */
-static JdwpError RT_SourceFile(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError RT_SourceFile(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  RefTypeId refTypeId = ReadRefTypeId(&buf);
+  RefTypeId refTypeId = request.ReadRefTypeId();
   std::string source_file;
   JdwpError status = Dbg::GetSourceFile(refTypeId, source_file);
   if (status != ERR_NONE) {
@@ -624,9 +494,9 @@
 /*
  * Return the current status of the reference type.
  */
-static JdwpError RT_Status(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError RT_Status(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  RefTypeId refTypeId = ReadRefTypeId(&buf);
+  RefTypeId refTypeId = request.ReadRefTypeId();
   JDWP::JdwpTypeTag type_tag;
   uint32_t class_status;
   JDWP::JdwpError status = Dbg::GetClassInfo(refTypeId, &type_tag, &class_status, NULL);
@@ -640,18 +510,18 @@
 /*
  * Return interfaces implemented directly by this class.
  */
-static JdwpError RT_Interfaces(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError RT_Interfaces(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  RefTypeId refTypeId = ReadRefTypeId(&buf);
+  RefTypeId refTypeId = request.ReadRefTypeId();
   return Dbg::OutputDeclaredInterfaces(refTypeId, pReply);
 }
 
 /*
  * Return the class object corresponding to this type.
  */
-static JdwpError RT_ClassObject(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError RT_ClassObject(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  RefTypeId refTypeId = ReadRefTypeId(&buf);
+  RefTypeId refTypeId = request.ReadRefTypeId();
   ObjectId class_object_id;
   JdwpError status = Dbg::GetClassObject(refTypeId, class_object_id);
   if (status != ERR_NONE) {
@@ -667,16 +537,15 @@
  *
  * JDB seems interested, but DEX files don't currently support this.
  */
-static JdwpError RT_SourceDebugExtension(JdwpState*, const uint8_t*, int, ExpandBuf*)
+static JdwpError RT_SourceDebugExtension(JdwpState*, Request&, ExpandBuf*)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
   /* referenceTypeId in, string out */
   return ERR_ABSENT_INFORMATION;
 }
 
-static JdwpError RT_Signature(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply,
-                              bool with_generic)
+static JdwpError RT_Signature(JdwpState*, Request& request, ExpandBuf* pReply, bool with_generic)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  RefTypeId refTypeId = ReadRefTypeId(&buf);
+  RefTypeId refTypeId = request.ReadRefTypeId();
 
   std::string signature;
   JdwpError status = Dbg::GetSignature(refTypeId, signature);
@@ -690,24 +559,23 @@
   return ERR_NONE;
 }
 
-static JdwpError RT_Signature(JdwpState* state, const uint8_t* buf, int dataLen, ExpandBuf* pReply)
+static JdwpError RT_Signature(JdwpState* state, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  return RT_Signature(state, buf, dataLen, pReply, false);
+  return RT_Signature(state, request, pReply, false);
 }
 
-static JdwpError RT_SignatureWithGeneric(JdwpState* state, const uint8_t* buf, int dataLen,
-                                         ExpandBuf* pReply)
+static JdwpError RT_SignatureWithGeneric(JdwpState* state, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  return RT_Signature(state, buf, dataLen, pReply, true);
+  return RT_Signature(state, request, pReply, true);
 }
 
 /*
  * Return the instance of java.lang.ClassLoader that loaded the specified
  * reference type, or null if it was loaded by the system loader.
  */
-static JdwpError RT_ClassLoader(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError RT_ClassLoader(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  RefTypeId refTypeId = ReadRefTypeId(&buf);
+  RefTypeId refTypeId = request.ReadRefTypeId();
   return Dbg::GetClassLoader(refTypeId, pReply);
 }
 
@@ -715,16 +583,16 @@
  * Given a referenceTypeId, return a block of stuff that describes the
  * fields declared by a class.
  */
-static JdwpError RT_FieldsWithGeneric(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError RT_FieldsWithGeneric(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  RefTypeId refTypeId = ReadRefTypeId(&buf);
+  RefTypeId refTypeId = request.ReadRefTypeId();
   return Dbg::OutputDeclaredFields(refTypeId, true, pReply);
 }
 
 // Obsolete equivalent of FieldsWithGeneric, without the generic type information.
-static JdwpError RT_Fields(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError RT_Fields(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  RefTypeId refTypeId = ReadRefTypeId(&buf);
+  RefTypeId refTypeId = request.ReadRefTypeId();
   return Dbg::OutputDeclaredFields(refTypeId, false, pReply);
 }
 
@@ -732,23 +600,23 @@
  * Given a referenceTypeID, return a block of goodies describing the
  * methods declared by a class.
  */
-static JdwpError RT_MethodsWithGeneric(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError RT_MethodsWithGeneric(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  RefTypeId refTypeId = ReadRefTypeId(&buf);
+  RefTypeId refTypeId = request.ReadRefTypeId();
   return Dbg::OutputDeclaredMethods(refTypeId, true, pReply);
 }
 
 // Obsolete equivalent of MethodsWithGeneric, without the generic type information.
-static JdwpError RT_Methods(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError RT_Methods(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  RefTypeId refTypeId = ReadRefTypeId(&buf);
+  RefTypeId refTypeId = request.ReadRefTypeId();
   return Dbg::OutputDeclaredMethods(refTypeId, false, pReply);
 }
 
-static JdwpError RT_Instances(JdwpState*, const uint8_t* buf, int, ExpandBuf* reply)
+static JdwpError RT_Instances(JdwpState*, Request& request, ExpandBuf* reply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  RefTypeId class_id = ReadRefTypeId(&buf);
-  int32_t max_count = ReadSigned32("max count", &buf);
+  RefTypeId class_id = request.ReadRefTypeId();
+  int32_t max_count = request.ReadSigned32("max count");
   if (max_count < 0) {
     return ERR_ILLEGAL_ARGUMENT;
   }
@@ -765,9 +633,9 @@
 /*
  * Return the immediate superclass of a class.
  */
-static JdwpError CT_Superclass(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError CT_Superclass(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  RefTypeId class_id = ReadRefTypeId(&buf);
+  RefTypeId class_id = request.ReadRefTypeId();
   RefTypeId superClassId;
   JdwpError status = Dbg::GetSuperclass(class_id, superClassId);
   if (status != ERR_NONE) {
@@ -780,18 +648,18 @@
 /*
  * Set static class values.
  */
-static JdwpError CT_SetValues(JdwpState* , const uint8_t* buf, int, ExpandBuf*)
+static JdwpError CT_SetValues(JdwpState* , Request& request, ExpandBuf*)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  RefTypeId class_id = ReadRefTypeId(&buf);
-  int32_t values_count = ReadSigned32("values count", &buf);
+  RefTypeId class_id = request.ReadRefTypeId();
+  int32_t values_count = request.ReadSigned32("values count");
 
   UNUSED(class_id);
 
   for (int32_t i = 0; i < values_count; ++i) {
-    FieldId fieldId = ReadFieldId(&buf);
+    FieldId fieldId = request.ReadFieldId();
     JDWP::JdwpTag fieldTag = Dbg::GetStaticFieldBasicTag(fieldId);
     size_t width = Dbg::GetTagWidth(fieldTag);
-    uint64_t value = ReadValue(&buf, width);
+    uint64_t value = request.ReadValue(width);
 
     VLOG(jdwp) << "    --> field=" << fieldId << " tag=" << fieldTag << " --> " << value;
     JdwpError status = Dbg::SetStaticFieldValue(fieldId, value, width);
@@ -809,14 +677,13 @@
  * Example: Eclipse sometimes uses java/lang/Class.forName(String s) on
  * values in the "variables" display.
  */
-static JdwpError CT_InvokeMethod(JdwpState* state, const uint8_t* buf, int dataLen,
-                                 ExpandBuf* pReply)
+static JdwpError CT_InvokeMethod(JdwpState* state, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  RefTypeId class_id = ReadRefTypeId(&buf);
-  ObjectId thread_id = ReadThreadId(&buf);
-  MethodId method_id = ReadMethodId(&buf);
+  RefTypeId class_id = request.ReadRefTypeId();
+  ObjectId thread_id = request.ReadThreadId();
+  MethodId method_id = request.ReadMethodId();
 
-  return FinishInvoke(state, buf, dataLen, pReply, thread_id, 0, class_id, method_id, false);
+  return FinishInvoke(state, request, pReply, thread_id, 0, class_id, method_id, false);
 }
 
 /*
@@ -826,12 +693,11 @@
  * Example: in IntelliJ, create a watch on "new String(myByteArray)" to
  * see the contents of a byte[] as a string.
  */
-static JdwpError CT_NewInstance(JdwpState* state, const uint8_t* buf, int dataLen,
-                                ExpandBuf* pReply)
+static JdwpError CT_NewInstance(JdwpState* state, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  RefTypeId class_id = ReadRefTypeId(&buf);
-  ObjectId thread_id = ReadThreadId(&buf);
-  MethodId method_id = ReadMethodId(&buf);
+  RefTypeId class_id = request.ReadRefTypeId();
+  ObjectId thread_id = request.ReadThreadId();
+  MethodId method_id = request.ReadMethodId();
 
   ObjectId object_id;
   JdwpError status = Dbg::CreateObject(class_id, object_id);
@@ -841,16 +707,16 @@
   if (object_id == 0) {
     return ERR_OUT_OF_MEMORY;
   }
-  return FinishInvoke(state, buf, dataLen, pReply, thread_id, object_id, class_id, method_id, true);
+  return FinishInvoke(state, request, pReply, thread_id, object_id, class_id, method_id, true);
 }
 
 /*
  * Create a new array object of the requested type and length.
  */
-static JdwpError AT_newInstance(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError AT_newInstance(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  RefTypeId arrayTypeId = ReadRefTypeId(&buf);
-  int32_t length = ReadSigned32("length", &buf);
+  RefTypeId arrayTypeId = request.ReadRefTypeId();
+  int32_t length = request.ReadSigned32("length");
 
   ObjectId object_id;
   JdwpError status = Dbg::CreateArrayObject(arrayTypeId, length, object_id);
@@ -868,21 +734,21 @@
 /*
  * Return line number information for the method, if present.
  */
-static JdwpError M_LineTable(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError M_LineTable(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  RefTypeId refTypeId = ReadRefTypeId(&buf);
-  MethodId method_id = ReadMethodId(&buf);
+  RefTypeId refTypeId = request.ReadRefTypeId();
+  MethodId method_id = request.ReadMethodId();
 
   Dbg::OutputLineTable(refTypeId, method_id, pReply);
 
   return ERR_NONE;
 }
 
-static JdwpError M_VariableTable(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply,
+static JdwpError M_VariableTable(JdwpState*, Request& request, ExpandBuf* pReply,
                                  bool generic)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  RefTypeId class_id = ReadRefTypeId(&buf);
-  MethodId method_id = ReadMethodId(&buf);
+  RefTypeId class_id = request.ReadRefTypeId();
+  MethodId method_id = request.ReadMethodId();
 
   // We could return ERR_ABSENT_INFORMATION here if the DEX file was built without local variable
   // information. That will cause Eclipse to make a best-effort attempt at displaying local
@@ -892,22 +758,20 @@
   return ERR_NONE;
 }
 
-static JdwpError M_VariableTable(JdwpState* state, const uint8_t* buf, int dataLen,
-                                 ExpandBuf* pReply)
+static JdwpError M_VariableTable(JdwpState* state, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  return M_VariableTable(state, buf, dataLen, pReply, false);
+  return M_VariableTable(state, request, pReply, false);
 }
 
-static JdwpError M_VariableTableWithGeneric(JdwpState* state, const uint8_t* buf, int dataLen,
-                                            ExpandBuf* pReply)
+static JdwpError M_VariableTableWithGeneric(JdwpState* state, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  return M_VariableTable(state, buf, dataLen, pReply, true);
+  return M_VariableTable(state, request, pReply, true);
 }
 
-static JdwpError M_Bytecodes(JdwpState*, const uint8_t* buf, int, ExpandBuf* reply)
+static JdwpError M_Bytecodes(JdwpState*, Request& request, ExpandBuf* reply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  RefTypeId class_id = ReadRefTypeId(&buf);
-  MethodId method_id = ReadMethodId(&buf);
+  RefTypeId class_id = request.ReadRefTypeId();
+  MethodId method_id = request.ReadMethodId();
 
   std::vector<uint8_t> bytecodes;
   JdwpError rc = Dbg::GetBytecodes(class_id, method_id, bytecodes);
@@ -930,23 +794,23 @@
  * This can get called on different things, e.g. thread_id gets
  * passed in here.
  */
-static JdwpError OR_ReferenceType(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError OR_ReferenceType(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId object_id = ReadObjectId(&buf);
+  ObjectId object_id = request.ReadObjectId();
   return Dbg::GetReferenceType(object_id, pReply);
 }
 
 /*
  * Get values from the fields of an object.
  */
-static JdwpError OR_GetValues(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError OR_GetValues(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId object_id = ReadObjectId(&buf);
-  int32_t field_count = ReadSigned32("field count", &buf);
+  ObjectId object_id = request.ReadObjectId();
+  int32_t field_count = request.ReadSigned32("field count");
 
   expandBufAdd4BE(pReply, field_count);
   for (int32_t i = 0; i < field_count; ++i) {
-    FieldId fieldId = ReadFieldId(&buf);
+    FieldId fieldId = request.ReadFieldId();
     JdwpError status = Dbg::GetFieldValue(object_id, fieldId, pReply);
     if (status != ERR_NONE) {
       return status;
@@ -959,17 +823,17 @@
 /*
  * Set values in the fields of an object.
  */
-static JdwpError OR_SetValues(JdwpState*, const uint8_t* buf, int, ExpandBuf*)
+static JdwpError OR_SetValues(JdwpState*, Request& request, ExpandBuf*)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId object_id = ReadObjectId(&buf);
-  int32_t field_count = ReadSigned32("field count", &buf);
+  ObjectId object_id = request.ReadObjectId();
+  int32_t field_count = request.ReadSigned32("field count");
 
   for (int32_t i = 0; i < field_count; ++i) {
-    FieldId fieldId = ReadFieldId(&buf);
+    FieldId fieldId = request.ReadFieldId();
 
     JDWP::JdwpTag fieldTag = Dbg::GetFieldBasicTag(fieldId);
     size_t width = Dbg::GetTagWidth(fieldTag);
-    uint64_t value = ReadValue(&buf, width);
+    uint64_t value = request.ReadValue(width);
 
     VLOG(jdwp) << "    --> fieldId=" << fieldId << " tag=" << fieldTag << "(" << width << ") value=" << value;
     JdwpError status = Dbg::SetFieldValue(object_id, fieldId, value, width);
@@ -981,9 +845,9 @@
   return ERR_NONE;
 }
 
-static JdwpError OR_MonitorInfo(JdwpState*, const uint8_t* buf, int, ExpandBuf* reply)
+static JdwpError OR_MonitorInfo(JdwpState*, Request& request, ExpandBuf* reply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId object_id = ReadObjectId(&buf);
+  ObjectId object_id = request.ReadObjectId();
   return Dbg::GetMonitorInfo(object_id, reply);
 }
 
@@ -998,42 +862,41 @@
  * object), it will try to invoke the object's toString() function.  This
  * feature becomes crucial when examining ArrayLists with Eclipse.
  */
-static JdwpError OR_InvokeMethod(JdwpState* state, const uint8_t* buf, int dataLen,
-                                 ExpandBuf* pReply)
+static JdwpError OR_InvokeMethod(JdwpState* state, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId object_id = ReadObjectId(&buf);
-  ObjectId thread_id = ReadThreadId(&buf);
-  RefTypeId class_id = ReadRefTypeId(&buf);
-  MethodId method_id = ReadMethodId(&buf);
+  ObjectId object_id = request.ReadObjectId();
+  ObjectId thread_id = request.ReadThreadId();
+  RefTypeId class_id = request.ReadRefTypeId();
+  MethodId method_id = request.ReadMethodId();
 
-  return FinishInvoke(state, buf, dataLen, pReply, thread_id, object_id, class_id, method_id, false);
+  return FinishInvoke(state, request, pReply, thread_id, object_id, class_id, method_id, false);
 }
 
-static JdwpError OR_DisableCollection(JdwpState*, const uint8_t* buf, int, ExpandBuf*)
+static JdwpError OR_DisableCollection(JdwpState*, Request& request, ExpandBuf*)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId object_id = ReadObjectId(&buf);
+  ObjectId object_id = request.ReadObjectId();
   return Dbg::DisableCollection(object_id);
 }
 
-static JdwpError OR_EnableCollection(JdwpState*, const uint8_t* buf, int, ExpandBuf*)
+static JdwpError OR_EnableCollection(JdwpState*, Request& request, ExpandBuf*)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId object_id = ReadObjectId(&buf);
+  ObjectId object_id = request.ReadObjectId();
   return Dbg::EnableCollection(object_id);
 }
 
-static JdwpError OR_IsCollected(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError OR_IsCollected(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId object_id = ReadObjectId(&buf);
+  ObjectId object_id = request.ReadObjectId();
   bool is_collected;
   JdwpError rc = Dbg::IsCollected(object_id, is_collected);
   expandBufAdd1(pReply, is_collected ? 1 : 0);
   return rc;
 }
 
-static JdwpError OR_ReferringObjects(JdwpState*, const uint8_t* buf, int, ExpandBuf* reply)
+static JdwpError OR_ReferringObjects(JdwpState*, Request& request, ExpandBuf* reply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId object_id = ReadObjectId(&buf);
-  int32_t max_count = ReadSigned32("max count", &buf);
+  ObjectId object_id = request.ReadObjectId();
+  int32_t max_count = request.ReadSigned32("max count");
   if (max_count < 0) {
     return ERR_ILLEGAL_ARGUMENT;
   }
@@ -1050,9 +913,9 @@
 /*
  * Return the string value in a string object.
  */
-static JdwpError SR_Value(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError SR_Value(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId stringObject = ReadObjectId(&buf);
+  ObjectId stringObject = request.ReadObjectId();
   std::string str(Dbg::StringToUtf8(stringObject));
 
   VLOG(jdwp) << StringPrintf("    --> %s", PrintableString(str).c_str());
@@ -1065,9 +928,9 @@
 /*
  * Return a thread's name.
  */
-static JdwpError TR_Name(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError TR_Name(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId thread_id = ReadThreadId(&buf);
+  ObjectId thread_id = request.ReadThreadId();
 
   std::string name;
   JdwpError error = Dbg::GetThreadName(thread_id, name);
@@ -1086,9 +949,9 @@
  * It's supposed to remain suspended even if interpreted code wants to
  * resume it; only the JDI is allowed to resume it.
  */
-static JdwpError TR_Suspend(JdwpState*, const uint8_t* buf, int, ExpandBuf*)
+static JdwpError TR_Suspend(JdwpState*, Request& request, ExpandBuf*)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId thread_id = ReadThreadId(&buf);
+  ObjectId thread_id = request.ReadThreadId();
 
   if (thread_id == Dbg::GetThreadSelfId()) {
     LOG(INFO) << "  Warning: ignoring request to suspend self";
@@ -1105,9 +968,9 @@
 /*
  * Resume the specified thread.
  */
-static JdwpError TR_Resume(JdwpState*, const uint8_t* buf, int, ExpandBuf*)
+static JdwpError TR_Resume(JdwpState*, Request& request, ExpandBuf*)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId thread_id = ReadThreadId(&buf);
+  ObjectId thread_id = request.ReadThreadId();
 
   if (thread_id == Dbg::GetThreadSelfId()) {
     LOG(INFO) << "  Warning: ignoring request to resume self";
@@ -1121,9 +984,9 @@
 /*
  * Return status of specified thread.
  */
-static JdwpError TR_Status(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError TR_Status(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId thread_id = ReadThreadId(&buf);
+  ObjectId thread_id = request.ReadThreadId();
 
   JDWP::JdwpThreadStatus threadStatus;
   JDWP::JdwpSuspendStatus suspendStatus;
@@ -1143,9 +1006,9 @@
 /*
  * Return the thread group that the specified thread is a member of.
  */
-static JdwpError TR_ThreadGroup(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError TR_ThreadGroup(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId thread_id = ReadThreadId(&buf);
+  ObjectId thread_id = request.ReadThreadId();
   return Dbg::GetThreadGroup(thread_id, pReply);
 }
 
@@ -1155,11 +1018,11 @@
  * If the thread isn't suspended, the error code isn't defined, but should
  * be THREAD_NOT_SUSPENDED.
  */
-static JdwpError TR_Frames(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError TR_Frames(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId thread_id = ReadThreadId(&buf);
-  uint32_t start_frame = ReadUnsigned32("start frame", &buf);
-  uint32_t length = ReadUnsigned32("length", &buf);
+  ObjectId thread_id = request.ReadThreadId();
+  uint32_t start_frame = request.ReadUnsigned32("start frame");
+  uint32_t length = request.ReadUnsigned32("length");
 
   size_t actual_frame_count;
   JdwpError error = Dbg::GetThreadFrameCount(thread_id, actual_frame_count);
@@ -1187,9 +1050,9 @@
 /*
  * Returns the #of frames on the specified thread, which must be suspended.
  */
-static JdwpError TR_FrameCount(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError TR_FrameCount(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId thread_id = ReadThreadId(&buf);
+  ObjectId thread_id = request.ReadThreadId();
 
   size_t frame_count;
   JdwpError rc = Dbg::GetThreadFrameCount(thread_id, frame_count);
@@ -1201,9 +1064,9 @@
   return ERR_NONE;
 }
 
-static JdwpError TR_OwnedMonitors(const uint8_t* buf, ExpandBuf* reply, bool with_stack_depths)
+static JdwpError TR_OwnedMonitors(Request& request, ExpandBuf* reply, bool with_stack_depths)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId thread_id = ReadThreadId(&buf);
+  ObjectId thread_id = request.ReadThreadId();
 
   std::vector<ObjectId> monitors;
   std::vector<uint32_t> stack_depths;
@@ -1225,19 +1088,19 @@
   return ERR_NONE;
 }
 
-static JdwpError TR_OwnedMonitors(JdwpState*, const uint8_t* buf, int, ExpandBuf* reply)
+static JdwpError TR_OwnedMonitors(JdwpState*, Request& request, ExpandBuf* reply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  return TR_OwnedMonitors(buf, reply, false);
+  return TR_OwnedMonitors(request, reply, false);
 }
 
-static JdwpError TR_OwnedMonitorsStackDepthInfo(JdwpState*, const uint8_t* buf, int, ExpandBuf* reply)
+static JdwpError TR_OwnedMonitorsStackDepthInfo(JdwpState*, Request& request, ExpandBuf* reply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  return TR_OwnedMonitors(buf, reply, true);
+  return TR_OwnedMonitors(request, reply, true);
 }
 
-static JdwpError TR_CurrentContendedMonitor(JdwpState*, const uint8_t* buf, int, ExpandBuf* reply)
+static JdwpError TR_CurrentContendedMonitor(JdwpState*, Request& request, ExpandBuf* reply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId thread_id = ReadThreadId(&buf);
+  ObjectId thread_id = request.ReadThreadId();
 
   ObjectId contended_monitor;
   JdwpError rc = Dbg::GetContendedMonitor(thread_id, contended_monitor);
@@ -1247,9 +1110,9 @@
   return WriteTaggedObject(reply, contended_monitor);
 }
 
-static JdwpError TR_Interrupt(JdwpState*, const uint8_t* buf, int, ExpandBuf* reply)
+static JdwpError TR_Interrupt(JdwpState*, Request& request, ExpandBuf* reply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId thread_id = ReadThreadId(&buf);
+  ObjectId thread_id = request.ReadThreadId();
   return Dbg::Interrupt(thread_id);
 }
 
@@ -1259,9 +1122,9 @@
  * (The thread *might* still be running -- it might not have examined
  * its suspend count recently.)
  */
-static JdwpError TR_DebugSuspendCount(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError TR_DebugSuspendCount(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId thread_id = ReadThreadId(&buf);
+  ObjectId thread_id = request.ReadThreadId();
   return Dbg::GetThreadDebugSuspendCount(thread_id, pReply);
 }
 
@@ -1270,9 +1133,9 @@
  *
  * The Eclipse debugger recognizes "main" and "system" as special.
  */
-static JdwpError TGR_Name(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError TGR_Name(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId thread_group_id = ReadThreadGroupId(&buf);
+  ObjectId thread_group_id = request.ReadThreadGroupId();
 
   expandBufAddUtf8String(pReply, Dbg::GetThreadGroupName(thread_group_id));
 
@@ -1283,9 +1146,9 @@
  * Returns the thread group -- if any -- that contains the specified
  * thread group.
  */
-static JdwpError TGR_Parent(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError TGR_Parent(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId thread_group_id = ReadThreadGroupId(&buf);
+  ObjectId thread_group_id = request.ReadThreadGroupId();
 
   ObjectId parentGroup = Dbg::GetThreadGroupParent(thread_group_id);
   expandBufAddObjectId(pReply, parentGroup);
@@ -1297,9 +1160,9 @@
  * Return the active threads and thread groups that are part of the
  * specified thread group.
  */
-static JdwpError TGR_Children(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError TGR_Children(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId thread_group_id = ReadThreadGroupId(&buf);
+  ObjectId thread_group_id = request.ReadThreadGroupId();
 
   std::vector<ObjectId> thread_ids;
   Dbg::GetThreads(thread_group_id, thread_ids);
@@ -1321,9 +1184,9 @@
 /*
  * Return the #of components in the array.
  */
-static JdwpError AR_Length(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError AR_Length(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId array_id = ReadArrayId(&buf);
+  ObjectId array_id = request.ReadArrayId();
 
   int length;
   JdwpError status = Dbg::GetArrayLength(array_id, length);
@@ -1340,28 +1203,28 @@
 /*
  * Return the values from an array.
  */
-static JdwpError AR_GetValues(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError AR_GetValues(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId array_id = ReadArrayId(&buf);
-  uint32_t offset = ReadUnsigned32("offset", &buf);
-  uint32_t length = ReadUnsigned32("length", &buf);
+  ObjectId array_id = request.ReadArrayId();
+  uint32_t offset = request.ReadUnsigned32("offset");
+  uint32_t length = request.ReadUnsigned32("length");
   return Dbg::OutputArray(array_id, offset, length, pReply);
 }
 
 /*
  * Set values in an array.
  */
-static JdwpError AR_SetValues(JdwpState*, const uint8_t* buf, int, ExpandBuf*)
+static JdwpError AR_SetValues(JdwpState*, Request& request, ExpandBuf*)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId array_id = ReadArrayId(&buf);
-  uint32_t offset = ReadUnsigned32("offset", &buf);
-  uint32_t length = ReadUnsigned32("length", &buf);
-  return Dbg::SetArrayElements(array_id, offset, length, buf);
+  ObjectId array_id = request.ReadArrayId();
+  uint32_t offset = request.ReadUnsigned32("offset");
+  uint32_t count = request.ReadUnsigned32("count");
+  return Dbg::SetArrayElements(array_id, offset, count, request);
 }
 
-static JdwpError CLR_VisibleClasses(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError CLR_VisibleClasses(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ReadObjectId(&buf);  // classLoaderObject
+  request.ReadObjectId();  // classLoaderObject
   // TODO: we should only return classes which have the given class loader as a defining or
   // initiating loader. The former would be easy; the latter is hard, because we don't have
   // any such notion.
@@ -1373,23 +1236,17 @@
  *
  * Reply with a requestID.
  */
-static JdwpError ER_Set(JdwpState* state, const uint8_t* buf, int dataLen, ExpandBuf* pReply)
+static JdwpError ER_Set(JdwpState* state, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  const uint8_t* origBuf = buf;
-
-  uint8_t eventKind = Read1(&buf);
-  uint8_t suspend_policy = Read1(&buf);
-  int32_t modifier_count = ReadSigned32("modifier count", &buf);
-
-  VLOG(jdwp) << "  Set(kind=" << JdwpEventKind(eventKind)
-               << " suspend=" << JdwpSuspendPolicy(suspend_policy)
-               << " mods=" << modifier_count << ")";
+  JdwpEventKind event_kind = request.ReadEnum1<JdwpEventKind>("event kind");
+  JdwpSuspendPolicy suspend_policy = request.ReadEnum1<JdwpSuspendPolicy>("suspend policy");
+  int32_t modifier_count = request.ReadSigned32("modifier count");
 
   CHECK_LT(modifier_count, 256);    /* reasonableness check */
 
   JdwpEvent* pEvent = EventAlloc(modifier_count);
-  pEvent->eventKind = static_cast<JdwpEventKind>(eventKind);
-  pEvent->suspend_policy = static_cast<JdwpSuspendPolicy>(suspend_policy);
+  pEvent->eventKind = event_kind;
+  pEvent->suspend_policy = suspend_policy;
   pEvent->modCount = modifier_count;
 
   /*
@@ -1398,12 +1255,12 @@
    */
   for (int32_t i = 0; i < modifier_count; ++i) {
     JdwpEventMod& mod = pEvent->mods[i];
-    mod.modKind = ReadModKind(&buf);
+    mod.modKind = request.ReadModKind();
     switch (mod.modKind) {
     case MK_COUNT:
       {
         // Report once, when "--count" reaches 0.
-        uint32_t count = ReadUnsigned32("count", &buf);
+        uint32_t count = request.ReadUnsigned32("count");
         if (count == 0) {
           return ERR_INVALID_COUNT;
         }
@@ -1413,21 +1270,21 @@
     case MK_CONDITIONAL:
       {
         // Conditional on expression.
-        uint32_t exprId = ReadUnsigned32("expr id", &buf);
+        uint32_t exprId = request.ReadUnsigned32("expr id");
         mod.conditional.exprId = exprId;
       }
       break;
     case MK_THREAD_ONLY:
       {
         // Only report events in specified thread.
-        ObjectId thread_id = ReadThreadId(&buf);
+        ObjectId thread_id = request.ReadThreadId();
         mod.threadOnly.threadId = thread_id;
       }
       break;
     case MK_CLASS_ONLY:
       {
         // For ClassPrepare, MethodEntry.
-        RefTypeId class_id = ReadRefTypeId(&buf);
+        RefTypeId class_id = request.ReadRefTypeId();
         mod.classOnly.refTypeId = class_id;
       }
       break;
@@ -1435,7 +1292,7 @@
       {
         // Restrict events to matching classes.
         // pattern is "java.foo.*", we want "java/foo/*".
-        std::string pattern(ReadUtf8String(&buf));
+        std::string pattern(request.ReadUtf8String());
         std::replace(pattern.begin(), pattern.end(), '.', '/');
         mod.classMatch.classPattern = strdup(pattern.c_str());
       }
@@ -1444,7 +1301,7 @@
       {
         // Restrict events to non-matching classes.
         // pattern is "java.foo.*", we want "java/foo/*".
-        std::string pattern(ReadUtf8String(&buf));
+        std::string pattern(request.ReadUtf8String());
         std::replace(pattern.begin(), pattern.end(), '.', '/');
         mod.classExclude.classPattern = strdup(pattern.c_str());
       }
@@ -1452,29 +1309,23 @@
     case MK_LOCATION_ONLY:
       {
         // Restrict certain events based on location.
-        JdwpLocation location = ReadLocation(&buf);
+        JdwpLocation location = request.ReadLocation();
         mod.locationOnly.loc = location;
       }
       break;
     case MK_EXCEPTION_ONLY:
       {
         // Modifies EK_EXCEPTION events,
-        RefTypeId exceptionOrNull = ReadRefTypeId(&buf); // null => all exceptions.
-        uint8_t caught = Read1(&buf);
-        uint8_t uncaught = Read1(&buf);
-        VLOG(jdwp) << StringPrintf("    ExceptionOnly: type=%#llx(%s) caught=%d uncaught=%d",
-            exceptionOrNull, (exceptionOrNull == 0) ? "null" : Dbg::GetClassName(exceptionOrNull).c_str(), caught, uncaught);
-
-        mod.exceptionOnly.refTypeId = exceptionOrNull;
-        mod.exceptionOnly.caught = caught;
-        mod.exceptionOnly.uncaught = uncaught;
+        mod.exceptionOnly.refTypeId = request.ReadRefTypeId(); // null => all exceptions.
+        mod.exceptionOnly.caught = request.ReadEnum1<uint8_t>("caught");
+        mod.exceptionOnly.uncaught = request.ReadEnum1<uint8_t>("uncaught");
       }
       break;
     case MK_FIELD_ONLY:
       {
         // For field access/modification events.
-        RefTypeId declaring = ReadRefTypeId(&buf);
-        FieldId fieldId = ReadFieldId(&buf);
+        RefTypeId declaring = request.ReadRefTypeId();
+        FieldId fieldId = request.ReadFieldId();
         mod.fieldOnly.refTypeId = declaring;
         mod.fieldOnly.fieldId = fieldId;
       }
@@ -1482,9 +1333,9 @@
     case MK_STEP:
       {
         // For use with EK_SINGLE_STEP.
-        ObjectId thread_id = ReadThreadId(&buf);
-        uint32_t size = Read4BE(&buf);
-        uint32_t depth = Read4BE(&buf);
+        ObjectId thread_id = request.ReadThreadId();
+        uint32_t size = request.ReadUnsigned32("step size");
+        uint32_t depth = request.ReadUnsigned32("step depth");
         VLOG(jdwp) << StringPrintf("    Step: thread=%#llx", thread_id)
                      << " size=" << JdwpStepSize(size) << " depth=" << JdwpStepDepth(depth);
 
@@ -1496,7 +1347,7 @@
     case MK_INSTANCE_ONLY:
       {
         // Report events related to a specific object.
-        ObjectId instance = ReadObjectId(&buf);
+        ObjectId instance = request.ReadObjectId();
         mod.instanceOnly.objectId = instance;
       }
       break;
@@ -1507,14 +1358,6 @@
   }
 
   /*
-   * Make sure we consumed all data.  It is possible that the remote side
-   * has sent us bad stuff, but for now we blame ourselves.
-   */
-  if (buf != origBuf + dataLen) {
-    LOG(WARNING) << "GLITCH: dataLen is " << dataLen << ", we have consumed " << (buf - origBuf);
-  }
-
-  /*
    * We reply with an integer "requestID".
    */
   uint32_t requestId = state->NextEventSerial();
@@ -1534,35 +1377,30 @@
   return err;
 }
 
-/*
- * Clear an event.  Failure to find an event with a matching ID is a no-op
- * and does not return an error.
- */
-static JdwpError ER_Clear(JdwpState* state, const uint8_t* buf, int, ExpandBuf*)
+static JdwpError ER_Clear(JdwpState* state, Request& request, ExpandBuf*)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  uint8_t eventKind = Read1(&buf);
-  uint32_t requestId = Read4BE(&buf);
+  request.ReadEnum1<JdwpEventKind>("event kind");
+  uint32_t requestId = request.ReadUnsigned32("request id");
 
-  VLOG(jdwp) << StringPrintf("  Req to clear eventKind=%d requestId=%#x", eventKind, requestId);
-
+  // Failure to find an event with a matching ID is a no-op
+  // and does not return an error.
   state->UnregisterEventById(requestId);
-
   return ERR_NONE;
 }
 
 /*
  * Return the values of arguments and local variables.
  */
-static JdwpError SF_GetValues(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError SF_GetValues(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId thread_id = ReadThreadId(&buf);
-  FrameId frame_id = ReadFrameId(&buf);
-  int32_t slot_count = ReadSigned32("slot count", &buf);
+  ObjectId thread_id = request.ReadThreadId();
+  FrameId frame_id = request.ReadFrameId();
+  int32_t slot_count = request.ReadSigned32("slot count");
 
   expandBufAdd4BE(pReply, slot_count);     /* "int values" */
   for (int32_t i = 0; i < slot_count; ++i) {
-    uint32_t slot = ReadUnsigned32("slot", &buf);
-    JDWP::JdwpTag reqSigByte = ReadTag(&buf);
+    uint32_t slot = request.ReadUnsigned32("slot");
+    JDWP::JdwpTag reqSigByte = request.ReadTag();
 
     VLOG(jdwp) << "    --> slot " << slot << " " << reqSigByte;
 
@@ -1577,17 +1415,17 @@
 /*
  * Set the values of arguments and local variables.
  */
-static JdwpError SF_SetValues(JdwpState*, const uint8_t* buf, int, ExpandBuf*)
+static JdwpError SF_SetValues(JdwpState*, Request& request, ExpandBuf*)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId thread_id = ReadThreadId(&buf);
-  FrameId frame_id = ReadFrameId(&buf);
-  int32_t slot_count = ReadSigned32("slot count", &buf);
+  ObjectId thread_id = request.ReadThreadId();
+  FrameId frame_id = request.ReadFrameId();
+  int32_t slot_count = request.ReadSigned32("slot count");
 
   for (int32_t i = 0; i < slot_count; ++i) {
-    uint32_t slot = ReadUnsigned32("slot", &buf);
-    JDWP::JdwpTag sigByte = ReadTag(&buf);
+    uint32_t slot = request.ReadUnsigned32("slot");
+    JDWP::JdwpTag sigByte = request.ReadTag();
     size_t width = Dbg::GetTagWidth(sigByte);
-    uint64_t value = ReadValue(&buf, width);
+    uint64_t value = request.ReadValue(width);
 
     VLOG(jdwp) << "    --> slot " << slot << " " << sigByte << " " << value;
     Dbg::SetLocalValue(thread_id, frame_id, slot, sigByte, value, width);
@@ -1596,10 +1434,10 @@
   return ERR_NONE;
 }
 
-static JdwpError SF_ThisObject(JdwpState*, const uint8_t* buf, int, ExpandBuf* reply)
+static JdwpError SF_ThisObject(JdwpState*, Request& request, ExpandBuf* reply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  ObjectId thread_id = ReadThreadId(&buf);
-  FrameId frame_id = ReadFrameId(&buf);
+  ObjectId thread_id = request.ReadThreadId();
+  FrameId frame_id = request.ReadFrameId();
 
   ObjectId object_id;
   JdwpError rc = Dbg::GetThisObject(thread_id, frame_id, &object_id);
@@ -1617,35 +1455,28 @@
  * reused, whereas ClassIds can be recycled like any other object.  (Either
  * that, or I have no idea what this is for.)
  */
-static JdwpError COR_ReflectedType(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply)
+static JdwpError COR_ReflectedType(JdwpState*, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
-  RefTypeId class_object_id = ReadRefTypeId(&buf);
+  RefTypeId class_object_id = request.ReadRefTypeId();
   return Dbg::GetReflectedType(class_object_id, pReply);
 }
 
 /*
  * Handle a DDM packet with a single chunk in it.
  */
-static JdwpError DDM_Chunk(JdwpState* state, const uint8_t* buf, int dataLen, ExpandBuf* pReply)
+static JdwpError DDM_Chunk(JdwpState* state, Request& request, ExpandBuf* pReply)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
+  state->NotifyDdmsActive();
   uint8_t* replyBuf = NULL;
   int replyLen = -1;
-
-  VLOG(jdwp) << StringPrintf("  Handling DDM packet (%.4s)", buf);
-
-  state->NotifyDdmsActive();
-
-  /*
-   * If they want to send something back, we copy it into the buffer.
-   * A no-copy approach would be nicer.
-   *
-   * TODO: consider altering the JDWP stuff to hold the packet header
-   * in a separate buffer.  That would allow us to writev() DDM traffic
-   * instead of copying it into the expanding buffer.  The reduction in
-   * heap requirements is probably more valuable than the efficiency.
-   */
-  if (Dbg::DdmHandlePacket(buf, dataLen, &replyBuf, &replyLen)) {
-    CHECK(replyLen > 0 && replyLen < 1*1024*1024);
+  if (Dbg::DdmHandlePacket(request, &replyBuf, &replyLen)) {
+    // If they want to send something back, we copy it into the buffer.
+    // TODO: consider altering the JDWP stuff to hold the packet header
+    // in a separate buffer.  That would allow us to writev() DDM traffic
+    // instead of copying it into the expanding buffer.  The reduction in
+    // heap requirements is probably more valuable than the efficiency.
+    CHECK_GT(replyLen, 0);
+    CHECK_LT(replyLen, 1*1024*1024);
     memcpy(expandBufAddSpace(pReply, replyLen), replyBuf, replyLen);
     free(replyBuf);
   }
@@ -1655,13 +1486,13 @@
 /*
  * Handler map decl.
  */
-typedef JdwpError (*JdwpRequestHandler)(JdwpState* state, const uint8_t* buf, int dataLen, ExpandBuf* reply);
+typedef JdwpError (*JdwpRequestHandler)(JdwpState* state, Request& request, ExpandBuf* reply);
 
 struct JdwpHandlerMap {
-  uint8_t  cmdSet;
-  uint8_t  cmd;
-  JdwpRequestHandler  func;
-  const char* descr;
+  uint8_t cmdSet;
+  uint8_t cmd;
+  JdwpRequestHandler func;
+  const char* name;
 };
 
 /*
@@ -1670,7 +1501,7 @@
  * Command sets 0-63 are incoming requests, 64-127 are outbound requests,
  * and 128-256 are vendor-defined.
  */
-static const JdwpHandlerMap gHandlerMap[] = {
+static const JdwpHandlerMap gHandlers[] = {
   /* VirtualMachine command set (1) */
   { 1,    1,  VM_Version,               "VirtualMachine.Version" },
   { 1,    2,  VM_ClassesBySignature,    "VirtualMachine.ClassesBySignature" },
@@ -1798,20 +1629,20 @@
   { 199,  1,  DDM_Chunk,        "DDM.Chunk" },
 };
 
-static const char* GetCommandName(size_t cmdSet, size_t cmd) {
-  for (size_t i = 0; i < arraysize(gHandlerMap); ++i) {
-    if (gHandlerMap[i].cmdSet == cmdSet && gHandlerMap[i].cmd == cmd) {
-      return gHandlerMap[i].descr;
+static const char* GetCommandName(Request& request) {
+  for (size_t i = 0; i < arraysize(gHandlers); ++i) {
+    if (gHandlers[i].cmdSet == request.GetCommandSet() && gHandlers[i].cmd == request.GetCommand()) {
+      return gHandlers[i].name;
     }
   }
   return "?UNKNOWN?";
 }
 
-static std::string DescribeCommand(const JdwpReqHeader* pHeader, int dataLen) {
+static std::string DescribeCommand(Request& request) {
   std::string result;
   result += "REQUEST: ";
-  result += GetCommandName(pHeader->cmdSet, pHeader->cmd);
-  result += StringPrintf(" (length=%d id=0x%06x)", dataLen, pHeader->id);
+  result += GetCommandName(request);
+  result += StringPrintf(" (length=%d id=0x%06x)", request.GetLength(), request.GetId());
   return result;
 }
 
@@ -1820,10 +1651,10 @@
  *
  * On entry, the JDWP thread is in VMWAIT.
  */
-void JdwpState::ProcessRequest(const JdwpReqHeader* pHeader, const uint8_t* buf, int dataLen, ExpandBuf* pReply) {
+void JdwpState::ProcessRequest(Request& request, ExpandBuf* pReply) {
   JdwpError result = ERR_NONE;
 
-  if (pHeader->cmdSet != kJDWPDdmCmdSet) {
+  if (request.GetCommandSet() != kJDWPDdmCmdSet) {
     /*
      * Activity from a debugger, not merely ddms.  Mark us as having an
      * active debugger session, and zero out the last-activity timestamp
@@ -1861,16 +1692,19 @@
   expandBufAddSpace(pReply, kJDWPHeaderLen);
 
   size_t i;
-  for (i = 0; i < arraysize(gHandlerMap); ++i) {
-    if (gHandlerMap[i].cmdSet == pHeader->cmdSet && gHandlerMap[i].cmd == pHeader->cmd && gHandlerMap[i].func != NULL) {
-      VLOG(jdwp) << DescribeCommand(pHeader, dataLen);
-      result = (*gHandlerMap[i].func)(this, buf, dataLen, pReply);
+  for (i = 0; i < arraysize(gHandlers); ++i) {
+    if (gHandlers[i].cmdSet == request.GetCommandSet() && gHandlers[i].cmd == request.GetCommand() && gHandlers[i].func != NULL) {
+      VLOG(jdwp) << DescribeCommand(request);
+      result = (*gHandlers[i].func)(this, request, pReply);
+      if (result == ERR_NONE) {
+        request.CheckConsumed();
+      }
       break;
     }
   }
-  if (i == arraysize(gHandlerMap)) {
-    LOG(ERROR) << "Command not implemented: " << DescribeCommand(pHeader, dataLen);
-    LOG(ERROR) << HexDump(buf, dataLen);
+  if (i == arraysize(gHandlers)) {
+    LOG(ERROR) << "Command not implemented: " << DescribeCommand(request);
+    LOG(ERROR) << HexDump(request.data(), request.size());
     result = ERR_NOT_IMPLEMENTED;
   }
 
@@ -1880,7 +1714,7 @@
    * If we encountered an error, only send the header back.
    */
   uint8_t* replyBuf = expandBufGetBuffer(pReply);
-  Set4BE(replyBuf + 4, pHeader->id);
+  Set4BE(replyBuf + 4, request.GetId());
   Set1(replyBuf + 8, kJDWPFlagReply);
   Set2BE(replyBuf + 9, result);
   if (result == ERR_NONE) {
@@ -1889,17 +1723,21 @@
     Set4BE(replyBuf + 0, kJDWPHeaderLen);
   }
 
+  CHECK_GT(expandBufGetLength(pReply), 0U) << GetCommandName(request) << " " << request.GetId();
+
   size_t respLen = expandBufGetLength(pReply) - kJDWPHeaderLen;
-  VLOG(jdwp) << "REPLY: " << GetCommandName(pHeader->cmdSet, pHeader->cmd) << " " << result << " (length=" << respLen << ")";
+  VLOG(jdwp) << "REPLY: " << GetCommandName(request) << " " << result << " (length=" << respLen << ")";
   if (false) {
     VLOG(jdwp) << HexDump(expandBufGetBuffer(pReply) + kJDWPHeaderLen, respLen);
   }
 
+  VLOG(jdwp) << "----------";
+
   /*
    * Update last-activity timestamp.  We really only need this during
    * the initial setup.  Only update if this is a non-DDMS packet.
    */
-  if (pHeader->cmdSet != kJDWPDdmCmdSet) {
+  if (request.GetCommandSet() != kJDWPDdmCmdSet) {
     QuasiAtomic::Write64(&last_activity_time_ms_, MilliTime());
   }
 
diff --git a/src/jdwp/jdwp_handler.h b/src/jdwp/jdwp_handler.h
deleted file mode 100644
index c296e88..0000000
--- a/src/jdwp/jdwp_handler.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-/*
- * Handle requests.
- */
-#ifndef ART_JDWP_JDWPHANDLER_H_
-#define ART_JDWP_JDWPHANDLER_H_
-
-#include "jdwp_expand_buf.h"
-
-namespace art {
-
-namespace JDWP {
-
-/*
- * JDWP message header for a request.
- */
-struct JdwpReqHeader {
-  uint32_t length;
-  uint32_t id;
-  uint8_t cmdSet;
-  uint8_t cmd;
-};
-
-}  // namespace JDWP
-
-}  // namespace art
-
-#endif  // ART_JDWP_JDWPHANDLER_H_
diff --git a/src/jdwp/jdwp_main.cc b/src/jdwp/jdwp_main.cc
index cbac920..4a18d48 100644
--- a/src/jdwp/jdwp_main.cc
+++ b/src/jdwp/jdwp_main.cc
@@ -37,12 +37,26 @@
  */
 JdwpNetStateBase::JdwpNetStateBase() : socket_lock_("JdwpNetStateBase lock") {
   clientSock = -1;
+  inputCount = 0;
+}
+
+void JdwpNetStateBase::ConsumeBytes(size_t count) {
+  CHECK_GT(count, 0U);
+  CHECK_LE(count, inputCount);
+
+  if (count == inputCount) {
+    inputCount = 0;
+    return;
+  }
+
+  memmove(inputBuffer, inputBuffer + count, inputCount - count);
+  inputCount -= count;
 }
 
 /*
  * Write a packet. Grabs a mutex to assure atomicity.
  */
-ssize_t JdwpNetStateBase::writePacket(ExpandBuf* pReply) {
+ssize_t JdwpNetStateBase::WritePacket(ExpandBuf* pReply) {
   MutexLock mu(Thread::Current(), socket_lock_);
   return write(clientSock, expandBufGetBuffer(pReply), expandBufGetLength(pReply));
 }
@@ -50,7 +64,7 @@
 /*
  * Write a buffered packet. Grabs a mutex to assure atomicity.
  */
-ssize_t JdwpNetStateBase::writeBufferedPacket(const iovec* iov, int iov_count) {
+ssize_t JdwpNetStateBase::WriteBufferedPacket(const iovec* iov, int iov_count) {
   MutexLock mu(Thread::Current(), socket_lock_);
   return writev(clientSock, iov, iov_count);
 }
@@ -268,6 +282,24 @@
   return IsConnected();
 }
 
+// Returns "false" if we encounter a connection-fatal error.
+bool JdwpState::HandlePacket() {
+  JdwpNetStateBase* netStateBase = reinterpret_cast<JdwpNetStateBase*>(netState);
+  JDWP::Request request(netStateBase->inputBuffer, netStateBase->inputCount);
+
+  ExpandBuf* pReply = expandBufAlloc();
+  ProcessRequest(request, pReply);
+  ssize_t cc = netStateBase->WritePacket(pReply);
+  if (cc != (ssize_t) expandBufGetLength(pReply)) {
+    PLOG(ERROR) << "Failed sending reply to debugger";
+    expandBufFree(pReply);
+    return false;
+  }
+  expandBufFree(pReply);
+  netStateBase->ConsumeBytes(request.GetLength());
+  return true;
+}
+
 /*
  * Entry point for JDWP thread.  The thread was created through the VM
  * mechanisms, so there is a java/lang/Thread associated with us.
diff --git a/src/jdwp/jdwp_priv.h b/src/jdwp/jdwp_priv.h
index cead61a..c03ad2a 100644
--- a/src/jdwp/jdwp_priv.h
+++ b/src/jdwp/jdwp_priv.h
@@ -76,9 +76,15 @@
  public:
   int clientSock;     /* active connection to debugger */
 
+  enum { kInputBufferSize = 8192 };
+
+  unsigned char inputBuffer[kInputBufferSize];
+  size_t inputCount;
+
   JdwpNetStateBase();
-  ssize_t writePacket(ExpandBuf* pReply);
-  ssize_t writeBufferedPacket(const iovec* iov, int iov_count);
+  void ConsumeBytes(size_t byte_count);
+  ssize_t WritePacket(ExpandBuf* pReply);
+  ssize_t WriteBufferedPacket(const iovec* iov, int iov_count);
 
  private:
   // Used to serialize writes to the socket.
diff --git a/src/jdwp/jdwp_request.cc b/src/jdwp/jdwp_request.cc
new file mode 100644
index 0000000..440b51b
--- /dev/null
+++ b/src/jdwp/jdwp_request.cc
@@ -0,0 +1,183 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "jdwp/jdwp.h"
+
+#include "base/stringprintf.h"
+#include "jdwp/jdwp_priv.h"
+
+namespace art {
+
+namespace JDWP {
+
+Request::Request(const uint8_t* bytes, uint32_t available) : p_(bytes) {
+  byte_count_ = Read4BE();
+  end_ =  bytes + byte_count_;
+  CHECK_LE(byte_count_, available);
+
+  id_ = Read4BE();
+  int8_t flags = Read1();
+  if ((flags & kJDWPFlagReply) != 0) {
+    LOG(FATAL) << "reply?!";
+  }
+
+  command_set_ = Read1();
+  command_ = Read1();
+}
+
+Request::~Request() {
+}
+
+void Request::CheckConsumed() {
+  if (p_ < end_) {
+    CHECK(p_ == end_) << "read too few bytes: " << (end_ - p_);
+  } else if (p_ > end_) {
+    CHECK(p_ == end_) << "read too many bytes: " << (p_ - end_);
+  }
+}
+
+std::string Request::ReadUtf8String() {
+  uint32_t length = Read4BE();
+  std::string s;
+  s.resize(length);
+  memcpy(&s[0], p_, length);
+  p_ += length;
+  VLOG(jdwp) << "    string \"" << s << "\"";
+  return s;
+}
+
+// Helper function: read a variable-width value from the input buffer.
+uint64_t Request::ReadValue(size_t width) {
+  uint64_t value = -1;
+  switch (width) {
+    case 1: value = Read1(); break;
+    case 2: value = Read2BE(); break;
+    case 4: value = Read4BE(); break;
+    case 8: value = Read8BE(); break;
+    default: LOG(FATAL) << width; break;
+  }
+  return value;
+}
+
+int32_t Request::ReadSigned32(const char* what) {
+  int32_t value = static_cast<int32_t>(Read4BE());
+  VLOG(jdwp) << "    " << what << " " << value;
+  return value;
+}
+
+uint32_t Request::ReadUnsigned32(const char* what) {
+  uint32_t value = Read4BE();
+  VLOG(jdwp) << "    " << what << " " << value;
+  return value;
+}
+
+FieldId Request::ReadFieldId() {
+  FieldId id = Read4BE();
+  VLOG(jdwp) << "    field id " << DescribeField(id);
+  return id;
+}
+
+MethodId Request::ReadMethodId() {
+  MethodId id = Read4BE();
+  VLOG(jdwp) << "    method id " << DescribeMethod(id);
+  return id;
+}
+
+ObjectId Request::ReadObjectId(const char* specific_kind) {
+  ObjectId id = Read8BE();
+  VLOG(jdwp) << StringPrintf("    %s id %#llx", specific_kind, id);
+  return id;
+}
+
+ObjectId Request::ReadArrayId() {
+  return ReadObjectId("array");
+}
+
+ObjectId Request::ReadObjectId() {
+  return ReadObjectId("object");
+}
+
+ObjectId Request::ReadThreadId() {
+  return ReadObjectId("thread");
+}
+
+ObjectId Request::ReadThreadGroupId() {
+  return ReadObjectId("thread group");
+}
+
+RefTypeId Request::ReadRefTypeId() {
+  RefTypeId id = Read8BE();
+  VLOG(jdwp) << "    ref type id " << DescribeRefTypeId(id);
+  return id;
+}
+
+FrameId Request::ReadFrameId() {
+  FrameId id = Read8BE();
+  VLOG(jdwp) << "    frame id " << id;
+  return id;
+}
+
+JdwpTag Request::ReadTag() {
+  return ReadEnum1<JdwpTag>("tag");
+}
+
+JdwpTypeTag Request::ReadTypeTag() {
+  return ReadEnum1<JdwpTypeTag>("type tag");
+}
+
+JdwpLocation Request::ReadLocation() {
+  JdwpLocation location;
+  memset(&location, 0, sizeof(location)); // Allows memcmp(3) later.
+  location.type_tag = ReadTypeTag();
+  location.class_id = ReadObjectId("class");
+  location.method_id = ReadMethodId();
+  location.dex_pc = Read8BE();
+  VLOG(jdwp) << "    location " << location;
+  return location;
+}
+
+JdwpModKind Request::ReadModKind() {
+  return ReadEnum1<JdwpModKind>("mod kind");
+}
+
+uint8_t Request::Read1() {
+  return *p_++;
+}
+
+uint16_t Request::Read2BE() {
+  uint16_t result = p_[0] << 8 | p_[1];
+  p_ += 2;
+  return result;
+}
+
+uint32_t Request::Read4BE() {
+  uint32_t result = p_[0] << 24;
+  result |= p_[1] << 16;
+  result |= p_[2] << 8;
+  result |= p_[3];
+  p_ += 4;
+  return result;
+}
+
+uint64_t Request::Read8BE() {
+  uint64_t high = Read4BE();
+  uint64_t low = Read4BE();
+  return (high << 32) | low;
+}
+
+}  // namespace JDWP
+
+}  // namespace art
diff --git a/src/jdwp/jdwp_socket.cc b/src/jdwp/jdwp_socket.cc
index eb1506c..43906ef 100644
--- a/src/jdwp/jdwp_socket.cc
+++ b/src/jdwp/jdwp_socket.cc
@@ -28,14 +28,11 @@
 
 #include "base/logging.h"
 #include "base/stringprintf.h"
-#include "jdwp/jdwp_handler.h"
 #include "jdwp/jdwp_priv.h"
 
 #define kBasePort           8000
 #define kMaxPort            8040
 
-#define kInputBufferSize    8192
-
 namespace art {
 
 namespace JDWP {
@@ -59,10 +56,6 @@
 
   bool    awaitingHandshake;  /* waiting for "JDWP-Handshake" */
 
-  /* pending data from the network; would be more efficient as circular buf */
-  unsigned char  inputBuffer[kInputBufferSize];
-  size_t inputCount;
-
   JdwpNetState() {
     listenPort  = 0;
     listenSock  = -1;
@@ -70,8 +63,6 @@
     wakePipe[1] = -1;
 
     awaitingHandshake = false;
-
-    inputCount = 0;
   }
 };
 
@@ -444,83 +435,6 @@
 }
 
 /*
- * Consume bytes from the buffer.
- *
- * This would be more efficient with a circular buffer.  However, we're
- * usually only going to find one packet, which is trivial to handle.
- */
-static void consumeBytes(JdwpNetState* netState, size_t count) {
-  CHECK_GT(count, 0U);
-  CHECK_LE(count, netState->inputCount);
-
-  if (count == netState->inputCount) {
-    netState->inputCount = 0;
-    return;
-  }
-
-  memmove(netState->inputBuffer, netState->inputBuffer + count, netState->inputCount - count);
-  netState->inputCount -= count;
-}
-
-/*
- * Handle a packet.  Returns "false" if we encounter a connection-fatal error.
- */
-static bool handlePacket(JdwpState* state) {
-  JdwpNetState* netState = state->netState;
-  const unsigned char* buf = netState->inputBuffer;
-  uint8_t cmdSet, cmd;
-  bool reply;
-
-  cmd = cmdSet = 0;       // shut up gcc
-
-  uint32_t length = Read4BE(&buf);
-  uint32_t id = Read4BE(&buf);
-  int8_t flags = Read1(&buf);
-  if ((flags & kJDWPFlagReply) != 0) {
-    reply = true;
-    Read2BE(&buf);  // error
-  } else {
-    reply = false;
-    cmdSet = Read1(&buf);
-    cmd = Read1(&buf);
-  }
-
-  CHECK_LE(length, netState->inputCount);
-  int dataLen = length - (buf - netState->inputBuffer);
-
-  if (!reply) {
-    ExpandBuf* pReply = expandBufAlloc();
-
-    JdwpReqHeader hdr;
-    hdr.length = length;
-    hdr.id = id;
-    hdr.cmdSet = cmdSet;
-    hdr.cmd = cmd;
-    state->ProcessRequest(&hdr, buf, dataLen, pReply);
-    if (expandBufGetLength(pReply) > 0) {
-      ssize_t cc = netState->writePacket(pReply);
-
-      if (cc != (ssize_t) expandBufGetLength(pReply)) {
-        PLOG(ERROR) << "Failed sending reply to debugger";
-        expandBufFree(pReply);
-        return false;
-      }
-    } else {
-      LOG(WARNING) << "No reply created for set=" << cmdSet << " cmd=" << cmd;
-    }
-    expandBufFree(pReply);
-  } else {
-    LOG(ERROR) << "reply?!";
-    DCHECK(false);
-  }
-
-  VLOG(jdwp) << "----------";
-
-  consumeBytes(netState, length);
-  return true;
-}
-
-/*
  * Process incoming data.  If no data is available, this will block until
  * some arrives.
  *
@@ -673,7 +587,7 @@
       goto fail;
     }
 
-    consumeBytes(netState, kMagicHandshakeLen);
+    netState->ConsumeBytes(kMagicHandshakeLen);
     netState->awaitingHandshake = false;
     VLOG(jdwp) << "+++ handshake complete";
     return true;
@@ -682,7 +596,7 @@
   /*
    * Handle this packet.
    */
-  return handlePacket(state);
+  return state->HandlePacket();
 
  fail:
   closeConnection(state);
@@ -708,7 +622,7 @@
   }
 
   errno = 0;
-  ssize_t cc = netState->writePacket(pReq);
+  ssize_t cc = netState->WritePacket(pReq);
 
   if (cc != (ssize_t) expandBufGetLength(pReq)) {
     PLOG(ERROR) << "Failed sending req to debugger (" << cc << " of " << expandBufGetLength(pReq) << ")";
@@ -740,7 +654,7 @@
     expected += iov[i].iov_len;
   }
 
-  ssize_t actual = netState->writeBufferedPacket(iov, iov_count);
+  ssize_t actual = netState->WriteBufferedPacket(iov, iov_count);
 
   if ((size_t)actual != expected) {
     PLOG(ERROR) << "Failed sending b-req to debugger (" << actual << " of " << expected << ")";
diff --git a/src/oat/runtime/support_deoptimize.cc b/src/oat/runtime/support_deoptimize.cc
index 0d88c52..c77d034 100644
--- a/src/oat/runtime/support_deoptimize.cc
+++ b/src/oat/runtime/support_deoptimize.cc
@@ -51,11 +51,10 @@
       CHECK(code_item != NULL);
       uint16_t num_regs =  code_item->registers_size_;
       shadow_frame_ = ShadowFrame::Create(num_regs, NULL, m, GetDexPc());
-      std::vector<int32_t> kinds =
-          verifier::MethodVerifier::DescribeVRegs(m->GetDexMethodIndex(), &mh.GetDexFile(),
-                                                  mh.GetDexCache(), mh.GetClassLoader(),
-                                                  mh.GetClassDefIndex(), code_item, m,
-                                                  m->GetAccessFlags(), GetDexPc());
+      std::vector<int32_t> kinds = DescribeVRegs(m->GetDexMethodIndex(), &mh.GetDexFile(),
+                                                 mh.GetDexCache(), mh.GetClassLoader(),
+                                                 mh.GetClassDefIndex(), code_item, m,
+                                                 m->GetAccessFlags(), GetDexPc());
       for(uint16_t reg = 0; reg < num_regs; reg++) {
         VRegKind kind = static_cast<VRegKind>(kinds.at(reg * 2));
         switch (kind) {
@@ -72,6 +71,22 @@
       }
       return false;  // Stop now we have built the shadow frame.
     }
+
+    std::vector<int32_t> DescribeVRegs(uint32_t dex_method_idx,
+                                       const DexFile* dex_file,
+                                       mirror::DexCache* dex_cache,
+                                       mirror::ClassLoader* class_loader,
+                                       uint32_t class_def_idx,
+                                       const DexFile::CodeItem* code_item,
+                                       mirror::AbstractMethod* method,
+                                       uint32_t method_access_flags, uint32_t dex_pc)
+        SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
+      verifier::MethodVerifier verifier(dex_file, dex_cache, class_loader, class_def_idx, code_item,
+                                        dex_method_idx, method, method_access_flags, true);
+      verifier.Verify();
+      return verifier.DescribeVRegs(dex_pc);
+    }
+
     ShadowFrame* shadow_frame_;
     uint32_t runtime_frames_;
   } visitor(self, self->GetLongJumpContext());
diff --git a/src/oatdump.cc b/src/oatdump.cc
index 3fe62bc..4063d70 100644
--- a/src/oatdump.cc
+++ b/src/oatdump.cc
@@ -585,14 +585,22 @@
                         uint32_t dex_method_idx, const DexFile* dex_file,
                         uint32_t class_def_idx, const DexFile::CodeItem* code_item,
                         uint32_t method_access_flags, uint32_t dex_pc) {
+    static UniquePtr<verifier::MethodVerifier> verifier;
+    static const DexFile* verified_dex_file = NULL;
+    static uint32_t verified_dex_method_idx = DexFile::kDexNoIndex;
+    if (dex_file != verified_dex_file || verified_dex_method_idx != dex_method_idx) {
+      ScopedObjectAccess soa(Thread::Current());
+      mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(*dex_file);
+      mirror::ClassLoader* class_loader = NULL;
+      verifier.reset(new verifier::MethodVerifier(dex_file, dex_cache, class_loader, class_def_idx,
+                                                  code_item, dex_method_idx, NULL,
+                                                  method_access_flags, true));
+      verifier->Verify();
+      verified_dex_file = dex_file;
+      verified_dex_method_idx = dex_method_idx;
+    }
+    std::vector<int32_t> kinds = verifier->DescribeVRegs(dex_pc);
     bool first = true;
-    ScopedObjectAccess soa(Thread::Current());
-    mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(*dex_file);
-    mirror::ClassLoader* class_loader = NULL;
-    std::vector<int32_t> kinds =
-        verifier::MethodVerifier::DescribeVRegs(dex_method_idx, dex_file, dex_cache,
-                                                class_loader, class_def_idx, code_item, NULL,
-                                                method_access_flags, dex_pc);
     for (size_t reg = 0; reg < code_item->registers_size_; reg++) {
       VRegKind kind = static_cast<VRegKind>(kinds.at(reg * 2));
       if (kind != kUndefined) {
diff --git a/src/thread.cc b/src/thread.cc
index d0401b6..0d3c5b9 100644
--- a/src/thread.cc
+++ b/src/thread.cc
@@ -624,9 +624,9 @@
         }
         // IsSuspended on the current thread will fail as the current thread is changed into
         // Runnable above. As the suspend count is now raised if this is the current thread
-        // it will self suspend on transition to Runnable, making it hard to work with. Its simpler
+        // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
         // to just explicitly handle the current thread in the callers to this code.
-        CHECK_NE(thread, soa.Self()) << "Attempt to suspend for debugger the current thread";
+        CHECK_NE(thread, soa.Self()) << "Attempt to suspend the current thread for the debugger";
         // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
         // count, or else we've waited and it has self suspended) or is the current thread, we're
         // done.
diff --git a/src/verifier/instruction_flags.cc b/src/verifier/instruction_flags.cc
new file mode 100644
index 0000000..823edde
--- /dev/null
+++ b/src/verifier/instruction_flags.cc
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "instruction_flags.h"
+
+#include <string.h>
+
+namespace art {
+namespace verifier {
+
+std::string InstructionFlags::ToString() const {
+  char encoding[6];
+  if (!IsOpcode()) {
+    strncpy(encoding, "XXXXX", sizeof(encoding));
+  } else {
+    strncpy(encoding, "-----", sizeof(encoding));
+    if (IsInTry())        encoding[kInTry] = 'T';
+    if (IsBranchTarget()) encoding[kBranchTarget] = 'B';
+    if (IsGcPoint())      encoding[kGcPoint] = 'G';
+    if (IsVisited())      encoding[kVisited] = 'V';
+    if (IsChanged())      encoding[kChanged] = 'C';
+  }
+  return encoding;
+}
+
+}  // namespace verifier
+}  // namespace art
diff --git a/src/verifier/instruction_flags.h b/src/verifier/instruction_flags.h
new file mode 100644
index 0000000..7f0d240
--- /dev/null
+++ b/src/verifier/instruction_flags.h
@@ -0,0 +1,116 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ART_SRC_VERIFIER_METHOD_INSTRUCTION_FLAGS_H_
+#define ART_SRC_VERIFIER_METHOD_INSTRUCTION_FLAGS_H_
+
+#include "base/logging.h"
+
+#include <stdint.h>
+#include <string>
+
+namespace art {
+namespace verifier {
+
+class InstructionFlags {
+ public:
+  InstructionFlags() : length_(0), flags_(0) {}
+
+  void SetLengthInCodeUnits(size_t length) {
+    DCHECK_LT(length, 65536u);
+    length_ = length;
+  }
+  size_t GetLengthInCodeUnits() {
+    return length_;
+  }
+  bool IsOpcode() const {
+    return length_ != 0;
+  }
+
+  void SetInTry() {
+    flags_ |= 1 << kInTry;
+  }
+  void ClearInTry() {
+    flags_ &= ~(1 << kInTry);
+  }
+  bool IsInTry() const {
+    return (flags_ & (1 << kInTry)) != 0;
+  }
+
+  void SetBranchTarget() {
+    flags_ |= 1 << kBranchTarget;
+  }
+  void ClearBranchTarget() {
+    flags_ &= ~(1 << kBranchTarget);
+  }
+  bool IsBranchTarget() const {
+    return (flags_ & (1 << kBranchTarget)) != 0;
+  }
+
+  void SetGcPoint() {
+    flags_ |= 1 << kGcPoint;
+  }
+  void ClearGcPoint() {
+    flags_ &= ~(1 << kGcPoint);
+  }
+  bool IsGcPoint() const {
+    return (flags_ & (1 << kGcPoint)) != 0;
+  }
+
+  void SetVisited() {
+    flags_ |= 1 << kVisited;
+  }
+  void ClearVisited() {
+    flags_ &= ~(1 << kVisited);
+  }
+  bool IsVisited() const {
+    return (flags_ & (1 << kVisited)) != 0;
+  }
+
+  void SetChanged() {
+    flags_ |= 1 << kChanged;
+  }
+  void ClearChanged() {
+    flags_ &= ~(1 << kChanged);
+  }
+  bool IsChanged() const {
+    return (flags_ & (1 << kChanged)) != 0;
+  }
+
+  bool IsVisitedOrChanged() const {
+    return IsVisited() || IsChanged();
+  }
+
+  std::string ToString() const;
+
+ private:
+  enum {
+    kInTry,
+    kBranchTarget,
+    kGcPoint,
+    kVisited,
+    kChanged,
+  };
+
+  // Size of instruction in code units.
+  uint16_t length_;
+  uint8_t flags_;
+};
+
+}  // namespace verifier
+}  // namespace art
+
+#endif  // ART_SRC_VERIFIER_METHOD_INSTRUCTION_FLAGS_H_
diff --git a/src/verifier/method_verifier.cc b/src/verifier/method_verifier.cc
index bcac374..56344cf 100644
--- a/src/verifier/method_verifier.cc
+++ b/src/verifier/method_verifier.cc
@@ -50,105 +50,7 @@
 
 static const bool gDebugVerify = false;
 
-class InsnFlags {
- public:
-  InsnFlags() : length_(0), flags_(0) {}
-
-  void SetLengthInCodeUnits(size_t length) {
-    CHECK_LT(length, 65536u);
-    length_ = length;
-  }
-  size_t GetLengthInCodeUnits() {
-    return length_;
-  }
-  bool IsOpcode() const {
-    return length_ != 0;
-  }
-
-  void SetInTry() {
-    flags_ |= 1 << kInTry;
-  }
-  void ClearInTry() {
-    flags_ &= ~(1 << kInTry);
-  }
-  bool IsInTry() const {
-    return (flags_ & (1 << kInTry)) != 0;
-  }
-
-  void SetBranchTarget() {
-    flags_ |= 1 << kBranchTarget;
-  }
-  void ClearBranchTarget() {
-    flags_ &= ~(1 << kBranchTarget);
-  }
-  bool IsBranchTarget() const {
-    return (flags_ & (1 << kBranchTarget)) != 0;
-  }
-
-  void SetGcPoint() {
-    flags_ |= 1 << kGcPoint;
-  }
-  void ClearGcPoint() {
-    flags_ &= ~(1 << kGcPoint);
-  }
-  bool IsGcPoint() const {
-    return (flags_ & (1 << kGcPoint)) != 0;
-  }
-
-  void SetVisited() {
-    flags_ |= 1 << kVisited;
-  }
-  void ClearVisited() {
-    flags_ &= ~(1 << kVisited);
-  }
-  bool IsVisited() const {
-    return (flags_ & (1 << kVisited)) != 0;
-  }
-
-  void SetChanged() {
-    flags_ |= 1 << kChanged;
-  }
-  void ClearChanged() {
-    flags_ &= ~(1 << kChanged);
-  }
-  bool IsChanged() const {
-    return (flags_ & (1 << kChanged)) != 0;
-  }
-
-  bool IsVisitedOrChanged() const {
-    return IsVisited() || IsChanged();
-  }
-
-  std::string Dump() {
-    char encoding[6];
-    if (!IsOpcode()) {
-      strncpy(encoding, "XXXXX", sizeof(encoding));
-    } else {
-      strncpy(encoding, "-----", sizeof(encoding));
-      if (IsInTry())        encoding[kInTry] = 'T';
-      if (IsBranchTarget()) encoding[kBranchTarget] = 'B';
-      if (IsGcPoint())      encoding[kGcPoint] = 'G';
-      if (IsVisited())      encoding[kVisited] = 'V';
-      if (IsChanged())      encoding[kChanged] = 'C';
-    }
-    return std::string(encoding);
-  }
-
- private:
-  enum {
-    kInTry,
-    kBranchTarget,
-    kGcPoint,
-    kVisited,
-    kChanged,
-  };
-
-  // Size of instruction in code units
-  uint16_t length_;
-  uint8_t flags_;
-};
-
-void PcToRegisterLineTable::Init(RegisterTrackingMode mode, InsnFlags* flags,
+void PcToRegisterLineTable::Init(RegisterTrackingMode mode, InstructionFlags* flags,
                                  uint32_t insns_size, uint16_t registers_size,
                                  MethodVerifier* verifier) {
   DCHECK_GT(insns_size, 0U);
@@ -357,20 +259,6 @@
   verifier.Dump(os);
 }
 
-std::vector<int32_t> MethodVerifier::DescribeVRegs(uint32_t dex_method_idx,
-                                                   const DexFile* dex_file,
-                                                   mirror::DexCache* dex_cache,
-                                                   mirror::ClassLoader* class_loader,
-                                                   uint32_t class_def_idx,
-                                                   const DexFile::CodeItem* code_item,
-                                                   mirror::AbstractMethod* method,
-                                                   uint32_t method_access_flags, uint32_t dex_pc) {
-  MethodVerifier verifier(dex_file, dex_cache, class_loader, class_def_idx, code_item,
-                          dex_method_idx, method, method_access_flags, true);
-  verifier.Verify();
-  return verifier.DescribeVRegs(dex_pc);
-}
-
 MethodVerifier::MethodVerifier(const DexFile* dex_file, mirror::DexCache* dex_cache,
                                mirror::ClassLoader* class_loader, uint32_t class_def_idx,
                                const DexFile::CodeItem* code_item,
@@ -435,7 +323,7 @@
     return false;
   }
   // Allocate and initialize an array to hold instruction data.
-  insn_flags_.reset(new InsnFlags[code_item_->insns_size_in_code_units_]());
+  insn_flags_.reset(new InstructionFlags[code_item_->insns_size_in_code_units_]());
   // Run through the instructions and see if the width checks out.
   bool result = ComputeWidthsAndCountOps();
   // Flag instructions guarded by a "try" block and check exception handlers.
@@ -1109,7 +997,7 @@
     if (reg_line != NULL) {
       indent_os << reg_line->Dump() << "\n";
     }
-    indent_os << StringPrintf("0x%04zx", dex_pc) << ": " << insn_flags_[dex_pc].Dump() << " ";
+    indent_os << StringPrintf("0x%04zx", dex_pc) << ": " << insn_flags_[dex_pc].ToString() << " ";
     const bool kDumpHexOfInstruction = false;
     if (kDumpHexOfInstruction) {
       indent_os << inst->DumpHex(5) << " ";
@@ -3228,7 +3116,7 @@
   return true;
 }
 
-InsnFlags* MethodVerifier::CurrentInsnFlags() {
+InstructionFlags* MethodVerifier::CurrentInsnFlags() {
   return &insn_flags_[work_insn_idx_];
 }
 
@@ -3421,7 +3309,7 @@
       result.push_back(kUndefined);
       result.push_back(0);
     } else {
-      CHECK(type.IsNonZeroReferenceTypes()) << type;
+      CHECK(type.IsNonZeroReferenceTypes());
       result.push_back(kReferenceVReg);
       result.push_back(0);
     }
diff --git a/src/verifier/method_verifier.h b/src/verifier/method_verifier.h
index a36a1f9..4939217 100644
--- a/src/verifier/method_verifier.h
+++ b/src/verifier/method_verifier.h
@@ -17,8 +17,6 @@
 #ifndef ART_SRC_VERIFIER_METHOD_VERIFIER_H_
 #define ART_SRC_VERIFIER_METHOD_VERIFIER_H_
 
-#include <deque>
-#include <limits>
 #include <set>
 #include <vector>
 
@@ -28,6 +26,7 @@
 #include "compiler.h"
 #include "dex_file.h"
 #include "dex_instruction.h"
+#include "instruction_flags.h"
 #include "mirror/object.h"
 #include "reg_type.h"
 #include "reg_type_cache.h"
@@ -48,7 +47,6 @@
 namespace verifier {
 
 class MethodVerifier;
-class InsnFlags;
 class DexPcToReferenceMap;
 
 /*
@@ -125,7 +123,7 @@
   // Initialize the RegisterTable. Every instruction address can have a different set of information
   // about what's in which register, but for verification purposes we only need to store it at
   // branch target addresses (because we merge into that).
-  void Init(RegisterTrackingMode mode, InsnFlags* flags, uint32_t insns_size,
+  void Init(RegisterTrackingMode mode, InstructionFlags* flags, uint32_t insns_size,
             uint16_t registers_size, MethodVerifier* verifier);
 
   RegisterLine* GetLine(size_t idx) {
@@ -147,7 +145,6 @@
 #if defined(ART_USE_LLVM_COMPILER)
   typedef greenland::InferredRegCategoryMap InferredRegCategoryMap;
 #endif
-
  public:
   enum FailureKind {
     kNoFailure,
@@ -169,15 +166,6 @@
                                   mirror::AbstractMethod* method, uint32_t method_access_flags)
       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
 
-  static std::vector<int32_t> DescribeVRegs(uint32_t dex_method_idx,
-                                            const DexFile* dex_file, mirror::DexCache* dex_cache,
-                                            mirror::ClassLoader* class_loader,
-                                            uint32_t class_def_idx,
-                                            const DexFile::CodeItem* code_item,
-                                            mirror::AbstractMethod* method,
-                                            uint32_t method_access_flags, uint32_t dex_pc)
-      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
-
   uint8_t EncodePcToReferenceMapData() const;
 
   uint32_t DexFileVersion() const {
@@ -228,14 +216,21 @@
     return can_load_classes_;
   }
 
- private:
-  explicit MethodVerifier(const DexFile* dex_file, mirror::DexCache* dex_cache,
-                          mirror::ClassLoader* class_loader, uint32_t class_def_idx,
-                          const DexFile::CodeItem* code_item,
-                          uint32_t method_idx, mirror::AbstractMethod* method, uint32_t access_flags,
-                          bool can_load_classes)
+  MethodVerifier(const DexFile* dex_file, mirror::DexCache* dex_cache,
+                 mirror::ClassLoader* class_loader, uint32_t class_def_idx,
+                 const DexFile::CodeItem* code_item,
+                 uint32_t method_idx, mirror::AbstractMethod* method,
+                 uint32_t access_flags, bool can_load_classes)
           SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
 
+  // Run verification on the method. Returns true if verification completes and false if the input
+  // has an irrecoverable corruption.
+  bool Verify() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
+
+  // Describe VRegs at the given dex pc.
+  std::vector<int32_t> DescribeVRegs(uint32_t dex_pc);
+
+ private:
   // Adds the given string to the beginning of the last failure message.
   void PrependToLastFailMessage(std::string);
 
@@ -260,10 +255,6 @@
                                   mirror::AbstractMethod* method, uint32_t method_access_flags)
           SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
 
-  // Run verification on the method. Returns true if verification completes and false if the input
-  // has an irrecoverable corruption.
-  bool Verify() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
-
   void FindLocksAtDexPc() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
 
   /*
@@ -597,10 +588,7 @@
   // Compute sizes for GC map data
   void ComputeGcMapSizes(size_t* gc_points, size_t* ref_bitmap_bits, size_t* log2_max_gc_pc);
 
-  // Describe VRegs at the given dex pc.
-  std::vector<int32_t> DescribeVRegs(uint32_t dex_pc) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
-
-  InsnFlags* CurrentInsnFlags();
+  InstructionFlags* CurrentInsnFlags();
 
   // All the GC maps that the verifier has created
   typedef SafeMap<const Compiler::MethodReference, const std::vector<uint8_t>*> DexGcMapTable;
@@ -652,7 +640,8 @@
   mirror::ClassLoader* class_loader_ GUARDED_BY(Locks::mutator_lock_);
   uint32_t class_def_idx_;  // The class def index of the declaring class of the method.
   const DexFile::CodeItem* code_item_;  // The code item containing the code for the method.
-  UniquePtr<InsnFlags[]> insn_flags_;  // Instruction widths and flags, one entry per code unit.
+  // Instruction widths and flags, one entry per code unit.
+  UniquePtr<InstructionFlags[]> insn_flags_;
 
   // The dex PC of a FindLocksAtDexPc request, -1 otherwise.
   uint32_t interesting_dex_pc_;