Merge "[LLVM] Fix parameter bug in throwing ArrayIndexOutOfBoundsException." into ics-mr1-plus-art
diff --git a/src/class_linker.cc b/src/class_linker.cc
index 47beadb..f891913 100644
--- a/src/class_linker.cc
+++ b/src/class_linker.cc
@@ -844,7 +844,7 @@
   OatFile* oat_file = OpenOat(space);
   CHECK(oat_file != NULL) << "Failed to open oat file for image";
   CHECK_EQ(oat_file->GetOatHeader().GetImageFileLocationChecksum(), 0U);
-  CHECK(oat_file->GetOatHeader().GetImageFileLocation() == "");
+  CHECK(oat_file->GetOatHeader().GetImageFileLocation().empty());
   Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
   ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
 
diff --git a/src/compiler/codegen/MethodBitcode.cc b/src/compiler/codegen/MethodBitcode.cc
index 66823c2..ad9b020 100644
--- a/src/compiler/codegen/MethodBitcode.cc
+++ b/src/compiler/codegen/MethodBitcode.cc
@@ -29,7 +29,7 @@
 #include <llvm/Support/Casting.h>
 #include <llvm/Support/InstIterator.h>
 
-const char* labelFormat = "L0x%x_%d";
+static const char* kLabelFormat = "L0x%x_%d";
 
 namespace art {
 extern const RegLocation badLoc;
@@ -345,7 +345,7 @@
       break;
     }
   }
-  DCHECK(index != -1) << "Corrupt shadowMap";
+  DCHECK_NE(index, -1) << "Corrupt shadowMap";
   greenland::IntrinsicHelper::IntrinsicId id =
       greenland::IntrinsicHelper::SetShadowFrameEntry;
   llvm::Function* func = cUnit->intrinsic_helper->GetIntrinsicFunction(id);
@@ -1341,7 +1341,7 @@
     bool entryBlock = (bb->blockType == kEntryBlock);
     llvm::BasicBlock* llvmBB =
         llvm::BasicBlock::Create(*cUnit->context, entryBlock ? "entry" :
-                                 StringPrintf(labelFormat, offset, bb->id),
+                                 StringPrintf(kLabelFormat, offset, bb->id),
                                  cUnit->func);
     if (entryBlock) {
         cUnit->entryBB = llvmBB;
@@ -1443,17 +1443,16 @@
   DCHECK(val != NULL);
   SafeMap<llvm::Value*, RegLocation>::iterator it = cUnit->locMap.find(val);
   if (it == cUnit->locMap.end()) {
-    const char* valName = val->getName().str().c_str();
-    DCHECK(valName != NULL);
-    DCHECK(strlen(valName) > 0);
+    std::string valName(val->getName().str());
+    DCHECK(!valName.empty());
     if (valName[0] == 'v') {
       int baseSReg = INVALID_SREG;
-      sscanf(valName, "v%d_", &baseSReg);
+      sscanf(valName.c_str(), "v%d_", &baseSReg);
       res = cUnit->regLocation[baseSReg];
       cUnit->locMap.Put(val, res);
     } else {
       UNIMPLEMENTED(WARNING) << "Need to handle llvm temps";
-      DCHECK(valName[0] == 't');
+      DCHECK_EQ(valName[0], 't');
     }
   } else {
     res = it->second;
@@ -1628,7 +1627,7 @@
 
 void cvtCopy(CompilationUnit* cUnit, llvm::CallInst* callInst)
 {
-  DCHECK(callInst->getNumArgOperands() == 1);
+  DCHECK_EQ(callInst->getNumArgOperands(), 1);
   RegLocation rlSrc = getLoc(cUnit, callInst->getArgOperand(0));
   RegLocation rlDest = getLoc(cUnit, callInst);
   if (rlSrc.wide) {
@@ -1641,7 +1640,7 @@
 // Note: Immediate arg is a ConstantInt regardless of result type
 void cvtConst(CompilationUnit* cUnit, llvm::CallInst* callInst)
 {
-  DCHECK(callInst->getNumArgOperands() == 1);
+  DCHECK_EQ(callInst->getNumArgOperands(), 1);
   llvm::ConstantInt* src =
       llvm::dyn_cast<llvm::ConstantInt>(callInst->getArgOperand(0));
   uint64_t immval = src->getZExtValue();
@@ -1659,7 +1658,7 @@
 
 void cvtConstString(CompilationUnit* cUnit, llvm::CallInst* callInst)
 {
-  DCHECK(callInst->getNumArgOperands() == 1);
+  DCHECK_EQ(callInst->getNumArgOperands(), 1);
   llvm::ConstantInt* stringIdxVal =
       llvm::dyn_cast<llvm::ConstantInt>(callInst->getArgOperand(0));
   uint32_t stringIdx = stringIdxVal->getZExtValue();
@@ -1733,7 +1732,7 @@
   if (!isEntry) {
     const char* blockName = bb->getName().str().c_str();
     int dummy;
-    sscanf(blockName, labelFormat, &blockLabel->operands[0], &dummy);
+    sscanf(blockName, kLabelFormat, &blockLabel->operands[0], &dummy);
   }
   // Set the label kind
   blockLabel->opcode = kPseudoNormalBlockLabel;
diff --git a/src/compiler/codegen/MethodCodegenDriver.cc b/src/compiler/codegen/MethodCodegenDriver.cc
index 7898ddb..a07e569 100644
--- a/src/compiler/codegen/MethodCodegenDriver.cc
+++ b/src/compiler/codegen/MethodCodegenDriver.cc
@@ -1020,7 +1020,7 @@
     return;
   }
   DCHECK_EQ(bb->startOffset, 0);
-  DCHECK(bb->firstMIRInsn != 0);
+  DCHECK(bb->firstMIRInsn != NULL);
 
   /* Get the first instruction */
   MIR* mir = bb->firstMIRInsn;
diff --git a/src/compiler/codegen/Ralloc.h b/src/compiler/codegen/Ralloc.h
index ec47e22..d1518e8 100644
--- a/src/compiler/codegen/Ralloc.h
+++ b/src/compiler/codegen/Ralloc.h
@@ -50,14 +50,12 @@
 }
 
 
-inline bool oatLiveOut(CompilationUnit* cUnit, int sReg)
-{
+inline bool oatLiveOut(CompilationUnit* cUnit, int sReg) {
   //For now.
   return true;
 }
 
-inline int oatSSASrc(MIR* mir, int num)
-{
+inline int oatSSASrc(MIR* mir, int num) {
   DCHECK_GT(mir->ssaRep->numUses, num);
   return mir->ssaRep->uses[num];
 }
diff --git a/src/compiler/codegen/RallocUtil.cc b/src/compiler/codegen/RallocUtil.cc
index 074fd26..affb545 100644
--- a/src/compiler/codegen/RallocUtil.cc
+++ b/src/compiler/codegen/RallocUtil.cc
@@ -1003,7 +1003,7 @@
 }
 extern RegLocation oatGetRawDest(CompilationUnit* cUnit, MIR* mir)
 {
-  DCHECK(mir->ssaRep->numDefs > 0);
+  DCHECK_GT(mir->ssaRep->numDefs, 0);
   RegLocation res = cUnit->regLocation[mir->ssaRep->defs[0]];
   DCHECK(!res.wide || mir->ssaRep->numDefs == 2);
   return res;
diff --git a/src/compiler/codegen/arm/Assemble.cc b/src/compiler/codegen/arm/Assemble.cc
index 86517fa..ede3f61 100644
--- a/src/compiler/codegen/arm/Assemble.cc
+++ b/src/compiler/codegen/arm/Assemble.cc
@@ -1305,7 +1305,7 @@
           break;
         case kFmtDfp: {
           DCHECK(DOUBLEREG(operand));
-          DCHECK((operand & 0x1) == 0);
+          DCHECK_EQ((operand & 0x1), 0U);
           int regName = (operand & FP_REG_MASK) >> 1;
           /* Snag the 1-bit slice and position it */
           value = ((regName & 0x10) >> 4) << encoder->fieldLoc[i].end;
diff --git a/src/compiler/codegen/arm/Thumb2/Factory.cc b/src/compiler/codegen/arm/Thumb2/Factory.cc
index c9dbe62..c6cb220 100644
--- a/src/compiler/codegen/arm/Thumb2/Factory.cc
+++ b/src/compiler/codegen/arm/Thumb2/Factory.cc
@@ -660,7 +660,7 @@
     } else {
       DCHECK(DOUBLEREG(rDest));
       DCHECK((size == kLong) || (size == kDouble));
-      DCHECK((rDest & 0x1) == 0);
+      DCHECK_EQ((rDest & 0x1), 0);
       opcode = kThumb2Vldrd;
       size = kDouble;
     }
@@ -725,7 +725,7 @@
     } else {
       DCHECK(DOUBLEREG(rSrc));
       DCHECK((size == kLong) || (size == kDouble));
-      DCHECK((rSrc & 0x1) == 0);
+      DCHECK_EQ((rSrc & 0x1), 0);
       opcode = kThumb2Vstrd;
       size = kDouble;
     }
diff --git a/src/compiler/codegen/mips/Assemble.cc b/src/compiler/codegen/mips/Assemble.cc
index 39ad36b..25e13d7 100644
--- a/src/compiler/codegen/mips/Assemble.cc
+++ b/src/compiler/codegen/mips/Assemble.cc
@@ -674,7 +674,7 @@
           break;
         case kFmtDfp: {
           DCHECK(DOUBLEREG(operand));
-          DCHECK((operand & 0x1) == 0);
+          DCHECK_EQ((operand & 0x1), 0U);
           value = ((operand & FP_REG_MASK) << encoder->fieldLoc[i].start) &
               ((1 << (encoder->fieldLoc[i].end + 1)) - 1);
           bits |= value;
diff --git a/src/compiler/codegen/mips/Codegen.h b/src/compiler/codegen/mips/Codegen.h
index 6add82a..106c030 100644
--- a/src/compiler/codegen/mips/Codegen.h
+++ b/src/compiler/codegen/mips/Codegen.h
@@ -67,12 +67,11 @@
  * Must use a core register for data types narrower than word (due
  * to possible unaligned load/store.
  */
-inline RegisterClass oatRegClassBySize(OpSize size)
-{
+inline RegisterClass oatRegClassBySize(OpSize size) {
   return (size == kUnsignedHalf ||
           size == kSignedHalf ||
           size == kUnsignedByte ||
-          size == kSignedByte ) ? kCoreReg : kAnyReg;
+          size == kSignedByte) ? kCoreReg : kAnyReg;
 }
 
 /*
@@ -84,7 +83,7 @@
  */
 #if __BYTE_ORDER == __LITTLE_ENDIAN
 inline s4 s4FromSwitchData(const void* switchData) {
-  return *(s4*) switchData;
+  return *reinterpret_cast<const s4*>(switchData);
 }
 #else
 inline s4 s4FromSwitchData(const void* switchData) {
diff --git a/src/compiler/codegen/x86/X86/Factory.cc b/src/compiler/codegen/x86/X86/Factory.cc
index 8b02aed..0a02c53 100644
--- a/src/compiler/codegen/x86/X86/Factory.cc
+++ b/src/compiler/codegen/x86/X86/Factory.cc
@@ -58,7 +58,7 @@
 {
   int opcode;
   /* must be both DOUBLE or both not DOUBLE */
-  DCHECK_EQ(DOUBLEREG(rDest),DOUBLEREG(rSrc));
+  DCHECK_EQ(DOUBLEREG(rDest), DOUBLEREG(rSrc));
   if (DOUBLEREG(rDest)) {
     opcode = kX86MovsdRR;
   } else {
@@ -73,7 +73,7 @@
       opcode = kX86MovdrxRR;
     }
   }
-  DCHECK((EncodingMap[opcode].flags & IS_BINARY_OP) != 0);
+  DCHECK_NE((EncodingMap[opcode].flags & IS_BINARY_OP), 0);
   LIR* res = rawLIR(cUnit, cUnit->currentDalvikOffset, opcode, rDest, rSrc);
   if (rDest == rSrc) {
     res->flags.isNop = true;
diff --git a/src/debugger.cc b/src/debugger.cc
index 29cb965..1dbcccc 100644
--- a/src/debugger.cc
+++ b/src/debugger.cc
@@ -952,9 +952,9 @@
     memset(&location, 0, sizeof(location));
   } else {
     Class* c = m->GetDeclaringClass();
-    location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
-    location.classId = gRegistry->Add(c);
-    location.methodId = ToMethodId(m);
+    location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
+    location.class_id = gRegistry->Add(c);
+    location.method_id = ToMethodId(m);
     location.dex_pc = m->IsNative() ? -1 : m->ToDexPC(native_pc);
   }
 }
@@ -1736,9 +1736,9 @@
   Class* c = m->GetDeclaringClass();
 
   JDWP::JdwpLocation location;
-  location.typeTag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
-  location.classId = gRegistry->Add(c);
-  location.methodId = ToMethodId(m);
+  location.type_tag = c->IsInterface() ? JDWP::TT_INTERFACE : JDWP::TT_CLASS;
+  location.class_id = gRegistry->Add(c);
+  location.method_id = ToMethodId(m);
   location.dex_pc = m->IsNative() ? -1 : dex_pc;
 
   // Note we use "NoReg" so we don't keep track of references that are
@@ -1905,14 +1905,14 @@
 
 void Dbg::WatchLocation(const JDWP::JdwpLocation* location) {
   MutexLock mu(gBreakpointsLock);
-  Method* m = FromMethodId(location->methodId);
+  Method* m = FromMethodId(location->method_id);
   gBreakpoints.push_back(Breakpoint(m, location->dex_pc));
   VLOG(jdwp) << "Set breakpoint #" << (gBreakpoints.size() - 1) << ": " << gBreakpoints[gBreakpoints.size() - 1];
 }
 
 void Dbg::UnwatchLocation(const JDWP::JdwpLocation* location) {
   MutexLock mu(gBreakpointsLock);
-  Method* m = FromMethodId(location->methodId);
+  Method* m = FromMethodId(location->method_id);
   for (size_t i = 0; i < gBreakpoints.size(); ++i) {
     if (gBreakpoints[i].method == m && gBreakpoints[i].dex_pc == location->dex_pc) {
       VLOG(jdwp) << "Removed breakpoint #" << i << ": " << gBreakpoints[i];
diff --git a/src/disassembler_arm.cc b/src/disassembler_arm.cc
index b5ef6a5..0472531 100644
--- a/src/disassembler_arm.cc
+++ b/src/disassembler_arm.cc
@@ -93,7 +93,7 @@
 };
 
 struct ArmRegister {
-  ArmRegister(uint32_t r) : r(r) { CHECK_LE(r, 15U); }
+  explicit ArmRegister(uint32_t r) : r(r) { CHECK_LE(r, 15U); }
   ArmRegister(uint32_t instruction, uint32_t at_bit) : r((instruction >> at_bit) & 0xf) { CHECK_LE(r, 15U); }
   uint32_t r;
 };
@@ -115,7 +115,7 @@
 };
 
 struct Rm {
-  Rm(uint32_t instruction) : shift((instruction >> 4) & 0xff), rm(instruction & 0xf) {}
+  explicit Rm(uint32_t instruction) : shift((instruction >> 4) & 0xff), rm(instruction & 0xf) {}
   uint32_t shift;
   ArmRegister rm;
 };
@@ -128,7 +128,7 @@
 }
 
 struct ShiftedImmediate {
-  ShiftedImmediate(uint32_t instruction) {
+  explicit ShiftedImmediate(uint32_t instruction) {
     uint32_t rotate = ((instruction >> 8) & 0xf);
     uint32_t imm = (instruction & 0xff);
     value = (imm >> (2 * rotate)) | (imm << (32 - (2 * rotate)));
@@ -141,7 +141,7 @@
 }
 
 struct RegisterList {
-  RegisterList(uint32_t instruction) : register_list(instruction & 0xffff) {}
+  explicit RegisterList(uint32_t instruction) : register_list(instruction & 0xffff) {}
   uint32_t register_list;
 };
 std::ostream& operator<<(std::ostream& os, const RegisterList& rhs) {
diff --git a/src/jdwp/jdwp.h b/src/jdwp/jdwp.h
index 4e9b0a0..7940566 100644
--- a/src/jdwp/jdwp.h
+++ b/src/jdwp/jdwp.h
@@ -73,9 +73,9 @@
  * Holds a JDWP "location".
  */
 struct JdwpLocation {
-  JdwpTypeTag typeTag;
-  RefTypeId classId;
-  MethodId methodId;
+  JdwpTypeTag type_tag;
+  RefTypeId class_id;
+  MethodId method_id;
   uint64_t dex_pc;
 };
 std::ostream& operator<<(std::ostream& os, const JdwpLocation& rhs);
@@ -274,9 +274,9 @@
                           int* pMatchCount) EXCLUSIVE_LOCKS_REQUIRED(event_list_lock_);
   void UnregisterEvent(JdwpEvent* pEvent) EXCLUSIVE_LOCKS_REQUIRED(event_list_lock_);
 
-public: // TODO: fix privacy
+ public: // TODO: fix privacy
   const JdwpOptions* options_;
-private:
+ private:
 
   /* wait for creation of the JDWP thread */
   Mutex thread_start_lock_;
@@ -285,15 +285,15 @@
   volatile int32_t debug_thread_started_;
   pthread_t pthread_;
   Thread* thread_;
-public: // TODO: fix privacy
+ public: // TODO: fix privacy
   ObjectId debugThreadId;
-private:
+ private:
   bool run;
 
   const JdwpTransport* transport;
-public: // TODO: fix privacy
+ public: // TODO: fix privacy
   JdwpNetState* netState;
-private:
+ private:
 
   /* for wait-for-debugger */
   Mutex attach_lock_;
@@ -310,11 +310,11 @@
   /*
    * Events requested by the debugger (breakpoints, class prep, etc).
    */
-public: // TODO: fix privacy
+ public: // TODO: fix privacy
   Mutex event_list_lock_;
   JdwpEvent* event_list_ GUARDED_BY(event_list_lock_); // Linked list of events.
   int event_list_size_ GUARDED_BY(event_list_lock_); // Number of elements in event_list_.
-private:
+ private:
 
   /*
    * Synchronize suspension of event thread (to avoid receiving "resume"
@@ -327,9 +327,8 @@
   /*
    * DDM support.
    */
-public: // TODO: fix privacy
+ public: // TODO: fix privacy
   bool ddmActive;
-private:
 };
 
 }  // namespace JDWP
diff --git a/src/jdwp/jdwp_adb.cc b/src/jdwp/jdwp_adb.cc
index 096ebc7..4577b59 100644
--- a/src/jdwp/jdwp_adb.cc
+++ b/src/jdwp/jdwp_adb.cc
@@ -48,9 +48,6 @@
 
 #define kInputBufferSize    8192
 
-#define kMagicHandshake     "JDWP-Handshake"
-#define kMagicHandshakeLen  (sizeof(kMagicHandshake)-1)
-
 #define kJdwpControlName    "\0jdwp-control"
 #define kJdwpControlNameLen (sizeof(kJdwpControlName)-1)
 
@@ -64,7 +61,7 @@
   bool                shuttingDown;
   int                 wakeFds[2];
 
-  int                 inputCount;
+  size_t inputCount;
   unsigned char       inputBuffer[kInputBufferSize];
 
   socklen_t           controlAddrLen;
@@ -382,12 +379,12 @@
  */
 static bool haveFullPacket(JdwpNetState* netState) {
   if (netState->awaitingHandshake) {
-    return (netState->inputCount >= (int) kMagicHandshakeLen);
+    return (netState->inputCount >= kMagicHandshakeLen);
   }
   if (netState->inputCount < 4) {
     return false;
   }
-  long length = Get4BE(netState->inputBuffer);
+  uint32_t length = Get4BE(netState->inputBuffer);
   return (netState->inputCount >= length);
 }
 
@@ -397,8 +394,8 @@
  * 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, int count) {
-  CHECK_GT(count, 0);
+static void consumeBytes(JdwpNetState* netState, size_t count) {
+  CHECK_GT(count, 0U);
   CHECK_LE(count, netState->inputCount);
 
   if (count == netState->inputCount) {
@@ -437,7 +434,7 @@
     cmd = Read1(&buf);
   }
 
-  CHECK_LE((int) length, netState->inputCount);
+  CHECK_LE(length, netState->inputCount);
   dataLen = length - (buf - netState->inputBuffer);
 
   if (!reply) {
diff --git a/src/jdwp/jdwp_event.cc b/src/jdwp/jdwp_event.cc
index a92590d..f398066 100644
--- a/src/jdwp/jdwp_event.cc
+++ b/src/jdwp/jdwp_event.cc
@@ -711,10 +711,10 @@
 
   memset(&basket, 0, sizeof(basket));
   basket.pLoc = pLoc;
-  basket.classId = pLoc->classId;
+  basket.classId = pLoc->class_id;
   basket.thisPtr = thisPtr;
   basket.threadId = Dbg::GetThreadSelfId();
-  basket.className = Dbg::GetClassName(pLoc->classId);
+  basket.className = Dbg::GetClassName(pLoc->class_id);
 
   /*
    * On rare occasions we may need to execute interpreted code in the VM
@@ -766,7 +766,7 @@
     }
     if (match_count != 0) {
       VLOG(jdwp) << "EVENT: " << match_list[0]->eventKind << "(" << match_count << " total) "
-                 << basket.className << "." << Dbg::GetMethodName(pLoc->classId, pLoc->methodId)
+                 << basket.className << "." << Dbg::GetMethodName(pLoc->class_id, pLoc->method_id)
                  << StringPrintf(" thread=%#llx dex_pc=%#llx)", basket.threadId, pLoc->dex_pc);
 
       suspend_policy = scanSuspendPolicy(match_list, match_count);
@@ -904,18 +904,17 @@
  * up the debugger.
  */
 bool JdwpState::PostException(const JdwpLocation* pThrowLoc,
-    ObjectId exceptionId, RefTypeId exceptionClassId,
-    const JdwpLocation* pCatchLoc, ObjectId thisPtr)
-{
+                              ObjectId exceptionId, RefTypeId exceptionClassId,
+                              const JdwpLocation* pCatchLoc, ObjectId thisPtr) {
   ModBasket basket;
 
   memset(&basket, 0, sizeof(basket));
   basket.pLoc = pThrowLoc;
-  basket.classId = pThrowLoc->classId;
+  basket.classId = pThrowLoc->class_id;
   basket.threadId = Dbg::GetThreadSelfId();
   basket.className = Dbg::GetClassName(basket.classId);
   basket.excepClassId = exceptionClassId;
-  basket.caught = (pCatchLoc->classId != 0);
+  basket.caught = (pCatchLoc->class_id != 0);
   basket.thisPtr = thisPtr;
 
   /* don't try to post an exception caused by the debugger */
@@ -938,7 +937,7 @@
                  << StringPrintf(" exceptId=%#llx", exceptionId)
                  << " caught=" << basket.caught << ")"
                  << "  throw: " << *pThrowLoc;
-      if (pCatchLoc->classId == 0) {
+      if (pCatchLoc->class_id == 0) {
         VLOG(jdwp) << "  catch: (not caught)";
       } else {
         VLOG(jdwp) << "  catch: " << *pCatchLoc;
diff --git a/src/jdwp/jdwp_handler.cc b/src/jdwp/jdwp_handler.cc
index 05fc979..f873da2 100644
--- a/src/jdwp/jdwp_handler.cc
+++ b/src/jdwp/jdwp_handler.cc
@@ -49,9 +49,9 @@
  */
 static void jdwpReadLocation(const uint8_t** pBuf, JdwpLocation* pLoc) {
   memset(pLoc, 0, sizeof(*pLoc));     /* allows memcmp() later */
-  pLoc->typeTag = ReadTypeTag(pBuf);
-  pLoc->classId = ReadObjectId(pBuf);
-  pLoc->methodId = ReadMethodId(pBuf);
+  pLoc->type_tag = ReadTypeTag(pBuf);
+  pLoc->class_id = ReadObjectId(pBuf);
+  pLoc->method_id = ReadMethodId(pBuf);
   pLoc->dex_pc = Read8BE(pBuf);
 }
 
@@ -59,9 +59,9 @@
  * Helper function: write a "location" into the reply buffer.
  */
 void AddLocation(ExpandBuf* pReply, const JdwpLocation* pLoc) {
-  expandBufAdd1(pReply, pLoc->typeTag);
-  expandBufAddObjectId(pReply, pLoc->classId);
-  expandBufAddMethodId(pReply, pLoc->methodId);
+  expandBufAdd1(pReply, pLoc->type_tag);
+  expandBufAddObjectId(pReply, pLoc->class_id);
+  expandBufAddMethodId(pReply, pLoc->method_id);
   expandBufAdd8BE(pReply, pLoc->dex_pc);
 }
 
@@ -96,20 +96,18 @@
 /*
  * Common code for *_InvokeMethod requests.
  *
- * If "is_constructor" is set, this returns "objectId" rather than the
+ * 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,
-    ObjectId threadId, ObjectId objectId, RefTypeId classId, MethodId methodId,
-    bool is_constructor)
-{
-  CHECK(!is_constructor || objectId != 0);
+static JdwpError finishInvoke(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply,
+                              ObjectId thread_id, ObjectId object_id,
+                              RefTypeId class_id, MethodId method_id, bool is_constructor) {
+  CHECK(!is_constructor || object_id != 0);
 
   uint32_t arg_count = Read4BE(&buf);
 
-  VLOG(jdwp) << StringPrintf("    --> threadId=%#llx objectId=%#llx", threadId, objectId);
-  VLOG(jdwp) << StringPrintf("        classId=%#llx methodId=%x %s.%s", classId, methodId, Dbg::GetClassName(classId).c_str(), Dbg::GetMethodName(classId, methodId).c_str());
+  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, method_id, Dbg::GetClassName(class_id).c_str(), Dbg::GetMethodName(class_id, method_id).c_str());
   VLOG(jdwp) << StringPrintf("        %d args:", arg_count);
 
   UniquePtr<JdwpTag[]> argTypes(arg_count > 0 ? new JdwpTag[arg_count] : NULL);
@@ -127,7 +125,7 @@
   JdwpTag resultTag;
   uint64_t resultValue;
   ObjectId exceptObjId;
-  JdwpError err = Dbg::InvokeMethod(threadId, objectId, classId, methodId, arg_count, argValues.get(), argTypes.get(), options, &resultTag, &resultValue, &exceptObjId);
+  JdwpError err = Dbg::InvokeMethod(thread_id, object_id, class_id, method_id, arg_count, argValues.get(), argTypes.get(), options, &resultTag, &resultValue, &exceptObjId);
   if (err != ERR_NONE) {
     return err;
   }
@@ -137,7 +135,7 @@
       // If we invoked a constructor (which actually returns void), return the receiver,
       // unless we threw, in which case we return NULL.
       resultTag = JT_OBJECT;
-      resultValue = (exceptObjId == 0) ? objectId : 0;
+      resultValue = (exceptObjId == 0) ? object_id : 0;
     }
 
     size_t width = Dbg::GetTagWidth(resultTag);
@@ -600,9 +598,9 @@
  * Return the immediate superclass of a class.
  */
 static JdwpError handleCT_Superclass(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply) {
-  RefTypeId classId = ReadRefTypeId(&buf);
+  RefTypeId class_id = ReadRefTypeId(&buf);
   RefTypeId superClassId;
-  JdwpError status = Dbg::GetSuperclass(classId, superClassId);
+  JdwpError status = Dbg::GetSuperclass(class_id, superClassId);
   if (status != ERR_NONE) {
     return status;
   }
@@ -614,10 +612,10 @@
  * Set static class values.
  */
 static JdwpError handleCT_SetValues(JdwpState* , const uint8_t* buf, int, ExpandBuf*) {
-  RefTypeId classId = ReadRefTypeId(&buf);
+  RefTypeId class_id = ReadRefTypeId(&buf);
   uint32_t values = Read4BE(&buf);
 
-  VLOG(jdwp) << StringPrintf("  Req to set %d values in classId=%#llx", values, classId);
+  VLOG(jdwp) << StringPrintf("  Req to set %d values in class_id=%#llx", values, class_id);
 
   for (uint32_t i = 0; i < values; i++) {
     FieldId fieldId = ReadFieldId(&buf);
@@ -642,11 +640,11 @@
  * values in the "variables" display.
  */
 static JdwpError handleCT_InvokeMethod(JdwpState* state, const uint8_t* buf, int dataLen, ExpandBuf* pReply) {
-  RefTypeId classId = ReadRefTypeId(&buf);
-  ObjectId threadId = ReadObjectId(&buf);
-  MethodId methodId = ReadMethodId(&buf);
+  RefTypeId class_id = ReadRefTypeId(&buf);
+  ObjectId thread_id = ReadObjectId(&buf);
+  MethodId method_id = ReadMethodId(&buf);
 
-  return finishInvoke(state, buf, dataLen, pReply, threadId, 0, classId, methodId, false);
+  return finishInvoke(state, buf, dataLen, pReply, thread_id, 0, class_id, method_id, false);
 }
 
 /*
@@ -657,20 +655,20 @@
  * see the contents of a byte[] as a string.
  */
 static JdwpError handleCT_NewInstance(JdwpState* state, const uint8_t* buf, int dataLen, ExpandBuf* pReply) {
-  RefTypeId classId = ReadRefTypeId(&buf);
-  ObjectId threadId = ReadObjectId(&buf);
-  MethodId methodId = ReadMethodId(&buf);
+  RefTypeId class_id = ReadRefTypeId(&buf);
+  ObjectId thread_id = ReadObjectId(&buf);
+  MethodId method_id = ReadMethodId(&buf);
 
-  VLOG(jdwp) << "Creating instance of " << Dbg::GetClassName(classId);
-  ObjectId objectId;
-  JdwpError status = Dbg::CreateObject(classId, objectId);
+  VLOG(jdwp) << "Creating instance of " << Dbg::GetClassName(class_id);
+  ObjectId object_id;
+  JdwpError status = Dbg::CreateObject(class_id, object_id);
   if (status != ERR_NONE) {
     return status;
   }
-  if (objectId == 0) {
+  if (object_id == 0) {
     return ERR_OUT_OF_MEMORY;
   }
-  return finishInvoke(state, buf, dataLen, pReply, threadId, objectId, classId, methodId, true);
+  return finishInvoke(state, buf, dataLen, pReply, thread_id, object_id, class_id, method_id, true);
 }
 
 /*
@@ -681,16 +679,16 @@
   uint32_t length = Read4BE(&buf);
 
   VLOG(jdwp) << "Creating array " << Dbg::GetClassName(arrayTypeId) << "[" << length << "]";
-  ObjectId objectId;
-  JdwpError status = Dbg::CreateArrayObject(arrayTypeId, length, objectId);
+  ObjectId object_id;
+  JdwpError status = Dbg::CreateArrayObject(arrayTypeId, length, object_id);
   if (status != ERR_NONE) {
     return status;
   }
-  if (objectId == 0) {
+  if (object_id == 0) {
     return ERR_OUT_OF_MEMORY;
   }
   expandBufAdd1(pReply, JT_ARRAY);
-  expandBufAddObjectId(pReply, objectId);
+  expandBufAddObjectId(pReply, object_id);
   return ERR_NONE;
 }
 
@@ -699,26 +697,26 @@
  */
 static JdwpError handleM_LineTable(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply) {
   RefTypeId refTypeId = ReadRefTypeId(&buf);
-  MethodId methodId = ReadMethodId(&buf);
+  MethodId method_id = ReadMethodId(&buf);
 
-  VLOG(jdwp) << "  Req for line table in " << Dbg::GetClassName(refTypeId) << "." << Dbg::GetMethodName(refTypeId,methodId);
+  VLOG(jdwp) << "  Req for line table in " << Dbg::GetClassName(refTypeId) << "." << Dbg::GetMethodName(refTypeId, method_id);
 
-  Dbg::OutputLineTable(refTypeId, methodId, pReply);
+  Dbg::OutputLineTable(refTypeId, method_id, pReply);
 
   return ERR_NONE;
 }
 
 static JdwpError handleM_VariableTable(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply, bool generic) {
-  RefTypeId classId = ReadRefTypeId(&buf);
-  MethodId methodId = ReadMethodId(&buf);
+  RefTypeId class_id = ReadRefTypeId(&buf);
+  MethodId method_id = ReadMethodId(&buf);
 
-  VLOG(jdwp) << StringPrintf("  Req for LocalVarTab in class=%s method=%s", Dbg::GetClassName(classId).c_str(), Dbg::GetMethodName(classId, methodId).c_str());
+  VLOG(jdwp) << StringPrintf("  Req for LocalVarTab in class=%s method=%s", Dbg::GetClassName(class_id).c_str(), Dbg::GetMethodName(class_id, method_id).c_str());
 
   // 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
   // variables anonymously. However, the attempt isn't very good, so we're probably better off just
   // not showing anything.
-  Dbg::OutputVariableTable(classId, methodId, generic, pReply);
+  Dbg::OutputVariableTable(class_id, method_id, generic, pReply);
   return ERR_NONE;
 }
 
@@ -734,29 +732,29 @@
  * Given an object reference, return the runtime type of the object
  * (class or array).
  *
- * This can get called on different things, e.g. threadId gets
+ * This can get called on different things, e.g. thread_id gets
  * passed in here.
  */
 static JdwpError handleOR_ReferenceType(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply) {
-  ObjectId objectId = ReadObjectId(&buf);
-  VLOG(jdwp) << StringPrintf("  Req for type of objectId=%#llx", objectId);
-  return Dbg::GetReferenceType(objectId, pReply);
+  ObjectId object_id = ReadObjectId(&buf);
+  VLOG(jdwp) << StringPrintf("  Req for type of object_id=%#llx", object_id);
+  return Dbg::GetReferenceType(object_id, pReply);
 }
 
 /*
  * Get values from the fields of an object.
  */
 static JdwpError handleOR_GetValues(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply) {
-  ObjectId objectId = ReadObjectId(&buf);
+  ObjectId object_id = ReadObjectId(&buf);
   uint32_t field_count = Read4BE(&buf);
 
-  VLOG(jdwp) << StringPrintf("  Req for %d fields from objectId=%#llx", field_count, objectId);
+  VLOG(jdwp) << StringPrintf("  Req for %d fields from object_id=%#llx", field_count, object_id);
 
   expandBufAdd4BE(pReply, field_count);
 
   for (uint32_t i = 0; i < field_count; i++) {
     FieldId fieldId = ReadFieldId(&buf);
-    JdwpError status = Dbg::GetFieldValue(objectId, fieldId, pReply);
+    JdwpError status = Dbg::GetFieldValue(object_id, fieldId, pReply);
     if (status != ERR_NONE) {
       return status;
     }
@@ -769,10 +767,10 @@
  * Set values in the fields of an object.
  */
 static JdwpError handleOR_SetValues(JdwpState*, const uint8_t* buf, int, ExpandBuf*) {
-  ObjectId objectId = ReadObjectId(&buf);
+  ObjectId object_id = ReadObjectId(&buf);
   uint32_t field_count = Read4BE(&buf);
 
-  VLOG(jdwp) << StringPrintf("  Req to set %d fields in objectId=%#llx", field_count, objectId);
+  VLOG(jdwp) << StringPrintf("  Req to set %d fields in object_id=%#llx", field_count, object_id);
 
   for (uint32_t i = 0; i < field_count; i++) {
     FieldId fieldId = ReadFieldId(&buf);
@@ -782,7 +780,7 @@
     uint64_t value = jdwpReadValue(&buf, width);
 
     VLOG(jdwp) << "    --> fieldId=" << fieldId << " tag=" << fieldTag << "(" << width << ") value=" << value;
-    JdwpError status = Dbg::SetFieldValue(objectId, fieldId, value, width);
+    JdwpError status = Dbg::SetFieldValue(object_id, fieldId, value, width);
     if (status != ERR_NONE) {
       return status;
     }
@@ -803,12 +801,12 @@
  * feature becomes crucial when examining ArrayLists with Eclipse.
  */
 static JdwpError handleOR_InvokeMethod(JdwpState* state, const uint8_t* buf, int dataLen, ExpandBuf* pReply) {
-  ObjectId objectId = ReadObjectId(&buf);
-  ObjectId threadId = ReadObjectId(&buf);
-  RefTypeId classId = ReadRefTypeId(&buf);
-  MethodId methodId = ReadMethodId(&buf);
+  ObjectId object_id = ReadObjectId(&buf);
+  ObjectId thread_id = ReadObjectId(&buf);
+  RefTypeId class_id = ReadRefTypeId(&buf);
+  MethodId method_id = ReadMethodId(&buf);
 
-  return finishInvoke(state, buf, dataLen, pReply, threadId, objectId, classId, methodId, false);
+  return finishInvoke(state, buf, dataLen, pReply, thread_id, object_id, class_id, method_id, false);
 }
 
 /*
@@ -831,10 +829,10 @@
  * Determine whether an object has been garbage collected.
  */
 static JdwpError handleOR_IsCollected(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply) {
-  ObjectId objectId;
+  ObjectId object_id;
 
-  objectId = ReadObjectId(&buf);
-  VLOG(jdwp) << StringPrintf("  Req IsCollected(%#llx)", objectId);
+  object_id = ReadObjectId(&buf);
+  VLOG(jdwp) << StringPrintf("  Req IsCollected(%#llx)", object_id);
 
   // TODO: currently returning false; must integrate with GC
   expandBufAdd1(pReply, 0);
@@ -860,14 +858,14 @@
  * Return a thread's name.
  */
 static JdwpError handleTR_Name(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply) {
-  ObjectId threadId = ReadObjectId(&buf);
+  ObjectId thread_id = ReadObjectId(&buf);
 
-  VLOG(jdwp) << StringPrintf("  Req for name of thread %#llx", threadId);
+  VLOG(jdwp) << StringPrintf("  Req for name of thread %#llx", thread_id);
   std::string name;
-  if (!Dbg::GetThreadName(threadId, name)) {
+  if (!Dbg::GetThreadName(thread_id, name)) {
     return ERR_INVALID_THREAD;
   }
-  VLOG(jdwp) << StringPrintf("  Name of thread %#llx is \"%s\"", threadId, name.c_str());
+  VLOG(jdwp) << StringPrintf("  Name of thread %#llx is \"%s\"", thread_id, name.c_str());
   expandBufAddUtf8String(pReply, name);
 
   return ERR_NONE;
@@ -880,14 +878,14 @@
  * resume it; only the JDI is allowed to resume it.
  */
 static JdwpError handleTR_Suspend(JdwpState*, const uint8_t* buf, int, ExpandBuf*) {
-  ObjectId threadId = ReadObjectId(&buf);
+  ObjectId thread_id = ReadObjectId(&buf);
 
-  if (threadId == Dbg::GetThreadSelfId()) {
+  if (thread_id == Dbg::GetThreadSelfId()) {
     LOG(INFO) << "  Warning: ignoring request to suspend self";
     return ERR_THREAD_NOT_SUSPENDED;
   }
-  VLOG(jdwp) << StringPrintf("  Req to suspend thread %#llx", threadId);
-  Dbg::SuspendThread(threadId);
+  VLOG(jdwp) << StringPrintf("  Req to suspend thread %#llx", thread_id);
+  Dbg::SuspendThread(thread_id);
   return ERR_NONE;
 }
 
@@ -895,14 +893,14 @@
  * Resume the specified thread.
  */
 static JdwpError handleTR_Resume(JdwpState*, const uint8_t* buf, int, ExpandBuf*) {
-  ObjectId threadId = ReadObjectId(&buf);
+  ObjectId thread_id = ReadObjectId(&buf);
 
-  if (threadId == Dbg::GetThreadSelfId()) {
+  if (thread_id == Dbg::GetThreadSelfId()) {
     LOG(INFO) << "  Warning: ignoring request to resume self";
     return ERR_NONE;
   }
-  VLOG(jdwp) << StringPrintf("  Req to resume thread %#llx", threadId);
-  Dbg::ResumeThread(threadId);
+  VLOG(jdwp) << StringPrintf("  Req to resume thread %#llx", thread_id);
+  Dbg::ResumeThread(thread_id);
   return ERR_NONE;
 }
 
@@ -910,13 +908,13 @@
  * Return status of specified thread.
  */
 static JdwpError handleTR_Status(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply) {
-  ObjectId threadId = ReadObjectId(&buf);
+  ObjectId thread_id = ReadObjectId(&buf);
 
-  VLOG(jdwp) << StringPrintf("  Req for status of thread %#llx", threadId);
+  VLOG(jdwp) << StringPrintf("  Req for status of thread %#llx", thread_id);
 
   JDWP::JdwpThreadStatus threadStatus;
   JDWP::JdwpSuspendStatus suspendStatus;
-  if (!Dbg::GetThreadStatus(threadId, &threadStatus, &suspendStatus)) {
+  if (!Dbg::GetThreadStatus(thread_id, &threadStatus, &suspendStatus)) {
     return ERR_INVALID_THREAD;
   }
 
@@ -932,8 +930,8 @@
  * Return the thread group that the specified thread is a member of.
  */
 static JdwpError handleTR_ThreadGroup(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply) {
-  ObjectId threadId = ReadObjectId(&buf);
-  return Dbg::GetThreadGroup(threadId, pReply);
+  ObjectId thread_id = ReadObjectId(&buf);
+  return Dbg::GetThreadGroup(thread_id, pReply);
 }
 
 /*
@@ -943,21 +941,21 @@
  * be THREAD_NOT_SUSPENDED.
  */
 static JdwpError handleTR_Frames(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply) {
-  ObjectId threadId = ReadObjectId(&buf);
+  ObjectId thread_id = ReadObjectId(&buf);
   uint32_t start_frame = Read4BE(&buf);
   uint32_t length = Read4BE(&buf);
 
-  if (!Dbg::ThreadExists(threadId)) {
+  if (!Dbg::ThreadExists(thread_id)) {
     return ERR_INVALID_THREAD;
   }
-  if (!Dbg::IsSuspended(threadId)) {
-    LOG(WARNING) << StringPrintf("  Rejecting req for frames in running thread %#llx", threadId);
+  if (!Dbg::IsSuspended(thread_id)) {
+    LOG(WARNING) << StringPrintf("  Rejecting req for frames in running thread %#llx", thread_id);
     return ERR_THREAD_NOT_SUSPENDED;
   }
 
-  size_t actual_frame_count = Dbg::GetThreadFrameCount(threadId);
+  size_t actual_frame_count = Dbg::GetThreadFrameCount(thread_id);
 
-  VLOG(jdwp) << StringPrintf("  Request for frames: threadId=%#llx start=%d length=%d [count=%zd]", threadId, start_frame, length, actual_frame_count);
+  VLOG(jdwp) << StringPrintf("  Request for frames: thread_id=%#llx start=%d length=%d [count=%zd]", thread_id, start_frame, length, actual_frame_count);
   if (actual_frame_count <= 0) {
     return ERR_THREAD_NOT_SUSPENDED;    /* == 0 means 100% native */
   }
@@ -978,7 +976,7 @@
     JdwpLocation loc;
     // TODO: switch to GetThreadFrames so we don't have to search for each frame
     // even though we only want them in order.
-    Dbg::GetThreadFrame(threadId, i, &frame_id, &loc);
+    Dbg::GetThreadFrame(thread_id, i, &frame_id, &loc);
 
     expandBufAdd8BE(pReply, frame_id);
     AddLocation(pReply, &loc);
@@ -993,17 +991,17 @@
  * Returns the #of frames on the specified thread, which must be suspended.
  */
 static JdwpError handleTR_FrameCount(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply) {
-  ObjectId threadId = ReadObjectId(&buf);
+  ObjectId thread_id = ReadObjectId(&buf);
 
-  if (!Dbg::ThreadExists(threadId)) {
+  if (!Dbg::ThreadExists(thread_id)) {
     return ERR_INVALID_THREAD;
   }
-  if (!Dbg::IsSuspended(threadId)) {
-    LOG(WARNING) << StringPrintf("  Rejecting req for frames in running thread %#llx", threadId);
+  if (!Dbg::IsSuspended(thread_id)) {
+    LOG(WARNING) << StringPrintf("  Rejecting req for frames in running thread %#llx", thread_id);
     return ERR_THREAD_NOT_SUSPENDED;
   }
 
-  int frame_count = Dbg::GetThreadFrameCount(threadId);
+  int frame_count = Dbg::GetThreadFrameCount(thread_id);
   if (frame_count < 0) {
     return ERR_INVALID_THREAD;
   }
@@ -1016,7 +1014,7 @@
  * Get the monitor that the thread is waiting on.
  */
 static JdwpError handleTR_CurrentContendedMonitor(JdwpState*, const uint8_t* buf, int, ExpandBuf*) {
-  ReadObjectId(&buf);  // threadId
+  ReadObjectId(&buf);  // thread_id
 
   // TODO: create an Object to represent the monitor (we're currently
   // just using a raw Monitor struct in the VM)
@@ -1031,8 +1029,8 @@
  * its suspend count recently.)
  */
 static JdwpError handleTR_SuspendCount(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply) {
-  ObjectId threadId = ReadObjectId(&buf);
-  return Dbg::GetThreadSuspendCount(threadId, pReply);
+  ObjectId thread_id = ReadObjectId(&buf);
+  return Dbg::GetThreadSuspendCount(thread_id, pReply);
 }
 
 /*
@@ -1198,16 +1196,16 @@
       break;
     case MK_THREAD_ONLY:    /* only report events in specified thread */
       {
-        ObjectId threadId = ReadObjectId(&buf);
-        VLOG(jdwp) << StringPrintf("    ThreadOnly: %#llx", threadId);
-        mod.threadOnly.threadId = threadId;
+        ObjectId thread_id = ReadObjectId(&buf);
+        VLOG(jdwp) << StringPrintf("    ThreadOnly: %#llx", thread_id);
+        mod.threadOnly.threadId = thread_id;
       }
       break;
     case MK_CLASS_ONLY:     /* for ClassPrepare, MethodEntry */
       {
-        RefTypeId classId = ReadRefTypeId(&buf);
-        VLOG(jdwp) << StringPrintf("    ClassOnly: %#llx (%s)", classId, Dbg::GetClassName(classId).c_str());
-        mod.classOnly.refTypeId = classId;
+        RefTypeId class_id = ReadRefTypeId(&buf);
+        VLOG(jdwp) << StringPrintf("    ClassOnly: %#llx (%s)", class_id, Dbg::GetClassName(class_id).c_str());
+        mod.classOnly.refTypeId = class_id;
       }
       break;
     case MK_CLASS_MATCH:    /* restrict events to matching classes */
@@ -1263,16 +1261,16 @@
       break;
     case MK_STEP:           /* for use with EK_SINGLE_STEP */
       {
-        ObjectId threadId;
+        ObjectId thread_id;
         uint32_t size, depth;
 
-        threadId = ReadObjectId(&buf);
+        thread_id = ReadObjectId(&buf);
         size = Read4BE(&buf);
         depth = Read4BE(&buf);
-        VLOG(jdwp) << StringPrintf("    Step: thread=%#llx", threadId)
+        VLOG(jdwp) << StringPrintf("    Step: thread=%#llx", thread_id)
                      << " size=" << JdwpStepSize(size) << " depth=" << JdwpStepDepth(depth);
 
-        mod.step.threadId = threadId;
+        mod.step.threadId = thread_id;
         mod.step.size = size;
         mod.step.depth = depth;
       }
@@ -1338,11 +1336,11 @@
  * Return the values of arguments and local variables.
  */
 static JdwpError handleSF_GetValues(JdwpState*, const uint8_t* buf, int, ExpandBuf* pReply) {
-  ObjectId threadId = ReadObjectId(&buf);
+  ObjectId thread_id = ReadObjectId(&buf);
   FrameId frame_id = ReadFrameId(&buf);
   uint32_t slots = Read4BE(&buf);
 
-  VLOG(jdwp) << StringPrintf("  Req for %d slots in threadId=%#llx frame_id=%#llx", slots, threadId, frame_id);
+  VLOG(jdwp) << StringPrintf("  Req for %d slots in thread_id=%#llx frame_id=%#llx", slots, thread_id, frame_id);
 
   expandBufAdd4BE(pReply, slots);     /* "int values" */
   for (uint32_t i = 0; i < slots; i++) {
@@ -1353,7 +1351,7 @@
 
     size_t width = Dbg::GetTagWidth(reqSigByte);
     uint8_t* ptr = expandBufAddSpace(pReply, width+1);
-    Dbg::GetLocalValue(threadId, frame_id, slot, reqSigByte, ptr, width);
+    Dbg::GetLocalValue(thread_id, frame_id, slot, reqSigByte, ptr, width);
   }
 
   return ERR_NONE;
@@ -1363,11 +1361,11 @@
  * Set the values of arguments and local variables.
  */
 static JdwpError handleSF_SetValues(JdwpState*, const uint8_t* buf, int, ExpandBuf*) {
-  ObjectId threadId = ReadObjectId(&buf);
+  ObjectId thread_id = ReadObjectId(&buf);
   FrameId frame_id = ReadFrameId(&buf);
   uint32_t slots = Read4BE(&buf);
 
-  VLOG(jdwp) << StringPrintf("  Req to set %d slots in threadId=%#llx frame_id=%#llx", slots, threadId, frame_id);
+  VLOG(jdwp) << StringPrintf("  Req to set %d slots in thread_id=%#llx frame_id=%#llx", slots, thread_id, frame_id);
 
   for (uint32_t i = 0; i < slots; i++) {
     uint32_t slot = Read4BE(&buf);
@@ -1376,7 +1374,7 @@
     uint64_t value = jdwpReadValue(&buf, width);
 
     VLOG(jdwp) << "    --> slot " << slot << " " << sigByte << " " << value;
-    Dbg::SetLocalValue(threadId, frame_id, slot, sigByte, value, width);
+    Dbg::SetLocalValue(thread_id, frame_id, slot, sigByte, value, width);
   }
 
   return ERR_NONE;
@@ -1560,7 +1558,7 @@
   { 11,   8,  NULL, "ThreadReference.OwnedMonitors" },
   { 11,   9,  handleTR_CurrentContendedMonitor, "ThreadReference.CurrentContendedMonitor" },
   { 11,   10, NULL, "ThreadReference.Stop" },
-  { 11,   11, NULL,"ThreadReference.Interrupt" },
+  { 11,   11, NULL, "ThreadReference.Interrupt" },
   { 11,   12, handleTR_SuspendCount,  "ThreadReference.SuspendCount" },
   { 11,   13, NULL, "ThreadReference.OwnedMonitorsStackDepthInfo" },
   { 11,   14, NULL, "ThreadReference.ForceEarlyReturn" },
@@ -1590,7 +1588,7 @@
   { 16,   4,  NULL, "StackFrame.PopFrames" },
 
   /* ClassObjectReference command set (17) */
-  { 17,   1,  handleCOR_ReflectedType,"ClassObjectReference.ReflectedType" },
+  { 17,   1,  handleCOR_ReflectedType, "ClassObjectReference.ReflectedType" },
 
   /* Event command set (64) */
   { 64,  100, NULL, "Event.Composite" }, // sent from VM to debugger, never received by VM
@@ -1599,7 +1597,7 @@
 };
 
 static const char* GetCommandName(size_t cmdSet, size_t cmd) {
-  for (int i = 0; i < (int) arraysize(gHandlerMap); i++) {
+  for (size_t i = 0; i < arraysize(gHandlerMap); ++i) {
     if (gHandlerMap[i].cmdSet == cmdSet && gHandlerMap[i].cmd == cmd) {
       return gHandlerMap[i].descr;
     }
diff --git a/src/jdwp/jdwp_main.cc b/src/jdwp/jdwp_main.cc
index fb24e29..20b770f 100644
--- a/src/jdwp/jdwp_main.cc
+++ b/src/jdwp/jdwp_main.cc
@@ -438,14 +438,14 @@
 
 std::ostream& operator<<(std::ostream& os, const JdwpLocation& rhs) {
   os << "JdwpLocation["
-     << Dbg::GetClassName(rhs.classId) << "." << Dbg::GetMethodName(rhs.classId, rhs.methodId)
-     << "@" << StringPrintf("%#llx", rhs.dex_pc) << " " << rhs.typeTag << "]";
+     << Dbg::GetClassName(rhs.class_id) << "." << Dbg::GetMethodName(rhs.class_id, rhs.method_id)
+     << "@" << StringPrintf("%#llx", rhs.dex_pc) << " " << rhs.type_tag << "]";
   return os;
 }
 
 bool operator==(const JdwpLocation& lhs, const JdwpLocation& rhs) {
-  return lhs.dex_pc == rhs.dex_pc && lhs.methodId == rhs.methodId &&
-      lhs.classId == rhs.classId && lhs.typeTag == rhs.typeTag;
+  return lhs.dex_pc == rhs.dex_pc && lhs.method_id == rhs.method_id &&
+      lhs.class_id == rhs.class_id && lhs.type_tag == rhs.type_tag;
 }
 
 bool operator!=(const JdwpLocation& lhs, const JdwpLocation& rhs) {
diff --git a/src/jdwp/jdwp_priv.h b/src/jdwp/jdwp_priv.h
index 7a6a528..98ae3b9 100644
--- a/src/jdwp/jdwp_priv.h
+++ b/src/jdwp/jdwp_priv.h
@@ -32,6 +32,9 @@
 #define kJDWPHeaderLen  11
 #define kJDWPFlagReply  0x80
 
+#define kMagicHandshake     "JDWP-Handshake"
+#define kMagicHandshakeLen  (sizeof(kMagicHandshake)-1)
+
 /* DDM support */
 #define kJDWPDdmCmdSet  199     /* 0xc7, or 'G'+128 */
 #define kJDWPDdmCmd     1
diff --git a/src/jdwp/jdwp_socket.cc b/src/jdwp/jdwp_socket.cc
index 01eba12..4424e7b 100644
--- a/src/jdwp/jdwp_socket.cc
+++ b/src/jdwp/jdwp_socket.cc
@@ -38,9 +38,6 @@
 
 #define kInputBufferSize    8192
 
-#define kMagicHandshake     "JDWP-Handshake"
-#define kMagicHandshakeLen  (sizeof(kMagicHandshake)-1)
-
 namespace art {
 
 namespace JDWP {
@@ -55,29 +52,29 @@
  * We only talk to one debugger at a time.
  */
 struct JdwpNetState : public JdwpNetStateBase {
-    uint16_t listenPort;
-    int     listenSock;         /* listen for connection from debugger */
-    int     wakePipe[2];        /* break out of select */
+  uint16_t listenPort;
+  int     listenSock;         /* listen for connection from debugger */
+  int     wakePipe[2];        /* break out of select */
 
-    in_addr remoteAddr;
-    uint16_t remotePort;
+  in_addr remoteAddr;
+  uint16_t remotePort;
 
-    bool    awaitingHandshake;  /* waiting for "JDWP-Handshake" */
+  bool    awaitingHandshake;  /* waiting for "JDWP-Handshake" */
 
-    /* pending data from the network; would be more efficient as circular buf */
-    unsigned char  inputBuffer[kInputBufferSize];
-    int     inputCount;
+  /* pending data from the network; would be more efficient as circular buf */
+  unsigned char  inputBuffer[kInputBufferSize];
+  size_t inputCount;
 
-    JdwpNetState() {
-        listenPort  = 0;
-        listenSock  = -1;
-        wakePipe[0] = -1;
-        wakePipe[1] = -1;
+  JdwpNetState() {
+    listenPort  = 0;
+    listenSock  = -1;
+    wakePipe[0] = -1;
+    wakePipe[1] = -1;
 
-        awaitingHandshake = false;
+    awaitingHandshake = false;
 
-        inputCount = 0;
-    }
+    inputCount = 0;
+  }
 };
 
 static JdwpNetState* netStartup(uint16_t port, bool probe);
@@ -265,62 +262,15 @@
 }
 
 /*
- * Returns "true" if the fd is ready, "false" if not.
- */
-#if 0
-static bool isFdReadable(int sock)
-{
-    fd_set readfds;
-    timeval tv;
-    int count;
-
-    FD_ZERO(&readfds);
-    FD_SET(sock, &readfds);
-
-    tv.tv_sec = 0;
-    tv.tv_usec = 0;
-    count = select(sock+1, &readfds, NULL, NULL, &tv);
-    if (count <= 0)
-        return false;
-
-    if (FD_ISSET(sock, &readfds))   /* make sure it's our fd */
-        return true;
-
-  LOG(ERROR) << "WEIRD: odd behavior in select (count=" << count << ")";
-  return false;
-}
-#endif
-
-#if 0
-/*
- * Check to see if we have a pending connection from the debugger.
- *
- * Returns true on success (meaning a connection is available).
- */
-static bool checkConnection(JdwpState* state) {
-    JdwpNetState* netState = state->netState;
-
-    CHECK_GE(netState->listenSock, 0);
-    /* not expecting to be called when debugger is actively connected */
-    CHECK_LT(netState->clientSock, 0);
-
-    if (!isFdReadable(netState->listenSock))
-        return false;
-    return true;
-}
-#endif
-
-/*
  * Disable the TCP Nagle algorithm, which delays transmission of outbound
  * packets until the previous transmissions have been acked.  JDWP does a
  * lot of back-and-forth with small packets, so this may help.
  */
-static int setNoDelay(int fd)
-{
-    int on = 1;
-    int cc = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));
-    CHECK_EQ(cc, 0);
-    return cc;
+static int setNoDelay(int fd) {
+  int on = 1;
+  int cc = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));
+  CHECK_EQ(cc, 0);
+  return cc;
 }
 
 /*
@@ -328,8 +278,7 @@
  * If that's not desirable, use checkConnection() to make sure something
  * is pending.
  */
-static bool acceptConnection(JdwpState* state)
-{
+static bool acceptConnection(JdwpState* state) {
   JdwpNetState* netState = state->netState;
   union {
     sockaddr_in  addrInet;
@@ -487,12 +436,12 @@
  */
 static bool haveFullPacket(JdwpNetState* netState) {
   if (netState->awaitingHandshake) {
-    return (netState->inputCount >= (int) kMagicHandshakeLen);
+    return (netState->inputCount >= kMagicHandshakeLen);
   }
   if (netState->inputCount < 4) {
     return false;
   }
-  long length = Get4BE(netState->inputBuffer);
+  uint32_t length = Get4BE(netState->inputBuffer);
   return (netState->inputCount >= length);
 }
 
@@ -502,8 +451,8 @@
  * 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, int count) {
-  CHECK_GT(count, 0);
+static void consumeBytes(JdwpNetState* netState, size_t count) {
+  CHECK_GT(count, 0U);
   CHECK_LE(count, netState->inputCount);
 
   if (count == netState->inputCount) {
@@ -516,58 +465,19 @@
 }
 
 /*
- * Dump the contents of a packet to stdout.
- */
-#if 0
-static void dumpPacket(const unsigned char* packetBuf) {
-  const unsigned char* buf = packetBuf;
-  uint32_t length, id;
-  uint8_t flags, cmdSet, cmd;
-  uint16_t error;
-  bool reply;
-  int dataLen;
-
-  cmd = cmdSet = 0xcc;
-
-  length = Read4BE(&buf);
-  id = Read4BE(&buf);
-  flags = Read1(&buf);
-  if ((flags & kJDWPFlagReply) != 0) {
-    reply = true;
-    error = Read2BE(&buf);
-  } else {
-    reply = false;
-    cmdSet = Read1(&buf);
-    cmd = Read1(&buf);
-  }
-
-  dataLen = length - (buf - packetBuf);
-
-  VLOG(jdwp) << StringPrintf("--- %s: dataLen=%u id=0x%08x flags=0x%02x cmd=%d/%d",
-                             reply ? "reply" : "req", dataLen, id, flags, cmdSet, cmd);
-  VLOG(jdwp) << HexDump(buf, dataLen);
-}
-#endif
-
-/*
  * 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;
+  uint8_t cmdSet, cmd;
   bool reply;
-  int dataLen;
 
   cmd = cmdSet = 0;       // shut up gcc
 
-  /*dumpPacket(netState->inputBuffer);*/
-
-  length = Read4BE(&buf);
-  id = Read4BE(&buf);
-  flags = Read1(&buf);
+  uint32_t length = Read4BE(&buf);
+  uint32_t id = Read4BE(&buf);
+  int8_t flags = Read1(&buf);
   if ((flags & kJDWPFlagReply) != 0) {
     reply = true;
     Read2BE(&buf);  // error
@@ -577,12 +487,13 @@
     cmd = Read1(&buf);
   }
 
-  CHECK_LE((int) length, netState->inputCount);
-  dataLen = length - (buf - netState->inputBuffer);
+  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;
diff --git a/src/jni_internal.cc b/src/jni_internal.cc
index ed46837..f3ef3ef 100644
--- a/src/jni_internal.cc
+++ b/src/jni_internal.cc
@@ -93,7 +93,7 @@
     return NULL;
   }
 
-  DCHECK((reinterpret_cast<uintptr_t>(obj) & 0xffff0000) != 0xebad0000);
+  DCHECK_NE((reinterpret_cast<uintptr_t>(obj) & 0xffff0000), 0xebad0000);
 
   JNIEnvExt* env = reinterpret_cast<JNIEnvExt*>(public_env);
   IndirectReferenceTable& locals = env->locals;
diff --git a/src/logging.h b/src/logging.h
index 585cc6d..94dd2c6 100644
--- a/src/logging.h
+++ b/src/logging.h
@@ -254,7 +254,7 @@
 template<typename T>
 class ToStr {
  public:
-  ToStr(const T& value) {
+  explicit ToStr(const T& value) {
     std::ostringstream os;
     os << value;
     s_ = os.str();
diff --git a/src/mark_sweep.h b/src/mark_sweep.h
index 43ed9b6..7b0272c 100644
--- a/src/mark_sweep.h
+++ b/src/mark_sweep.h
@@ -30,7 +30,7 @@
 
 class MarkSweep {
  public:
-  MarkSweep(MarkStack* mark_stack);
+  explicit MarkSweep(MarkStack* mark_stack);
 
   ~MarkSweep();
 
diff --git a/src/oat/jni/jni_compiler.cc b/src/oat/jni/jni_compiler.cc
index 625580c..4916072 100644
--- a/src/oat/jni/jni_compiler.cc
+++ b/src/oat/jni/jni_compiler.cc
@@ -179,7 +179,8 @@
 CompiledMethod* ArtJniCompileMethodInternal(Compiler& compiler,
                                             uint32_t access_flags, uint32_t method_idx,
                                             const DexFile& dex_file) {
-  CHECK((access_flags & kAccNative) != 0);
+  const bool is_native = (access_flags & kAccNative) != 0;
+  CHECK(is_native);
   const bool is_static = (access_flags & kAccStatic) != 0;
   const bool is_synchronized = (access_flags & kAccSynchronized) != 0;
   const char* shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
diff --git a/src/oat/runtime/oat_support_entrypoints.h b/src/oat/runtime/oat_support_entrypoints.h
index edf5575..a235e4f 100644
--- a/src/oat/runtime/oat_support_entrypoints.h
+++ b/src/oat/runtime/oat_support_entrypoints.h
@@ -20,8 +20,8 @@
 #include "runtime.h"
 
 #define ENTRYPOINT_OFFSET(x) \
-  (static_cast<uintptr_t>(OFFSETOF_MEMBER(Thread, entrypoints_)) + \
-   static_cast<uintptr_t>(OFFSETOF_MEMBER(EntryPoints, x)))
+    (static_cast<uintptr_t>(OFFSETOF_MEMBER(Thread, entrypoints_)) + \
+        static_cast<uintptr_t>(OFFSETOF_MEMBER(EntryPoints, x)))
 
 namespace art {
 
diff --git a/src/oat/runtime/support_jni.cc b/src/oat/runtime/support_jni.cc
index fb8b2e0..ff19a4c 100644
--- a/src/oat/runtime/support_jni.cc
+++ b/src/oat/runtime/support_jni.cc
@@ -112,7 +112,7 @@
         arg_ptr = sp + 10;  // skip to out arguments plus 2 slots as long must be aligned
         reg_num = -1;
       } else {
-        DCHECK(reg_num == -1);
+        DCHECK_EQ(reg_num, -1);
         if ((reinterpret_cast<intptr_t>(arg_ptr) & 7) == 4) {
           arg_ptr += 3;  // unaligned, pad and move through stack arguments
         } else {
@@ -127,7 +127,7 @@
         arg_ptr = sp + 8;  // skip to outgoing stack arguments
         reg_num = -1;
       } else {
-        DCHECK(reg_num == -1);
+        DCHECK_EQ(reg_num, -1);
         arg_ptr++;  // move through stack arguments
       }
     }
diff --git a/src/oat/runtime/x86/stub_x86.cc b/src/oat/runtime/x86/stub_x86.cc
index cd03455..a9db314 100644
--- a/src/oat/runtime/x86/stub_x86.cc
+++ b/src/oat/runtime/x86/stub_x86.cc
@@ -57,15 +57,15 @@
   __ popl(EBP);  // Restore callee saves.
   __ popl(ESI);
   // Swap EDI callee save with code pointer
-  __ xchgl(EDI, Address(ESP,0));
+  __ xchgl(EDI, Address(ESP, 0));
   // Tail call to intended method.
   __ ret();
 #else // ART_USE_LLVM_COMPILER
   __ pushl(EBP);
   __ movl(EBP, ESP);          // save ESP
   __ subl(ESP, Immediate(8));  // Align stack
-  __ movl(EAX, Address(EBP,8));  // Method* called
-  __ leal(EDX, Address(EBP,8));  // Method** called_addr
+  __ movl(EAX, Address(EBP, 8));  // Method* called
+  __ leal(EDX, Address(EBP, 8));  // Method** called_addr
   __ pushl(Immediate(type));  // pass is_static
   __ fs()->pushl(Address::Absolute(Thread::SelfOffset()));  // pass thread
   __ pushl(EDX);  // pass called_addr
@@ -132,7 +132,7 @@
   __ subl(ESP, Immediate(12));  // Align stack
   __ pushl(ESP);  // pass sp (not use)
   __ fs()->pushl(Address::Absolute(Thread::SelfOffset()));  // pass thread*
-  __ pushl(Address(EBP,8));  // pass method
+  __ pushl(Address(EBP, 8));  // pass method
   // Call to throw AbstractMethodError.
   __ Call(ThreadOffset(ENTRYPOINT_OFFSET(pThrowAbstractMethodErrorFromCode)),
           X86ManagedRegister::FromCpuRegister(ECX));
diff --git a/src/oat_file.cc b/src/oat_file.cc
index 81e88dd..7762825 100644
--- a/src/oat_file.cc
+++ b/src/oat_file.cc
@@ -188,7 +188,7 @@
 
 #else
   oat = map->Begin() + oat_header.GetElfImageTableOffset();
-  CHECK((reinterpret_cast<uintptr_t>(oat) & 0x3) == 0);
+  CHECK_EQ((reinterpret_cast<uintptr_t>(oat) & 0x3), 0);
 
   for (uint32_t i = 0, end = oat_header.GetElfImageCount(); i < end; ++i) {
     uint32_t elf_offset = *reinterpret_cast<const uint32_t*>(oat);
diff --git a/src/oat_writer.cc b/src/oat_writer.cc
index d79e61b..852320d 100644
--- a/src/oat_writer.cc
+++ b/src/oat_writer.cc
@@ -885,7 +885,7 @@
 
 void OatWriter::OatElfImage::SetElfOffset(uint32_t offset) {
   DCHECK_NE(offset, 0U);
-  DCHECK((offset & 0x3LU) == 0);
+  DCHECK_EQ((offset & 0x3LU), 0U);
   elf_offset_ = offset;
 }
 
diff --git a/src/runtime_linux.cc b/src/runtime_linux.cc
index 88a4a25..a84dfc9 100644
--- a/src/runtime_linux.cc
+++ b/src/runtime_linux.cc
@@ -127,7 +127,7 @@
 }
 
 struct UContext {
-  UContext(void* raw_context) : context(reinterpret_cast<ucontext_t*>(raw_context)->uc_mcontext) {}
+  explicit UContext(void* raw_context) : context(reinterpret_cast<ucontext_t*>(raw_context)->uc_mcontext) {}
 
   void Dump(std::ostream& os) {
     // TODO: support non-x86 hosts (not urgent because this code doesn't run on targets).
diff --git a/src/runtime_support.cc b/src/runtime_support.cc
index 06908c9..37be5f7 100644
--- a/src/runtime_support.cc
+++ b/src/runtime_support.cc
@@ -20,11 +20,11 @@
 #include "well_known_classes.h"
 
 double art_l2d(int64_t l) {
-  return (double) l;
+  return static_cast<double>(l);
 }
 
 float art_l2f(int64_t l) {
-  return (float) l;
+  return static_cast<float>(l);
 }
 
 /*
@@ -32,58 +32,58 @@
  * target doesn't support this normally, use these.
  */
 int64_t art_d2l(double d) {
-  static const double kMaxLong = (double) (int64_t) 0x7fffffffffffffffULL;
-  static const double kMinLong = (double) (int64_t) 0x8000000000000000ULL;
+  static const double kMaxLong = static_cast<double>(static_cast<int64_t>(0x7fffffffffffffffULL));
+  static const double kMinLong = static_cast<double>(static_cast<int64_t>(0x8000000000000000ULL));
   if (d >= kMaxLong) {
-    return (int64_t) 0x7fffffffffffffffULL;
+    return 0x7fffffffffffffffULL;
   } else if (d <= kMinLong) {
-    return (int64_t) 0x8000000000000000ULL;
+    return 0x8000000000000000ULL;
   } else if (d != d)  { // NaN case
     return 0;
   } else {
-    return (int64_t) d;
+    return static_cast<int64_t>(d);
   }
 }
 
 int64_t art_f2l(float f) {
-  static const float kMaxLong = (float) (int64_t) 0x7fffffffffffffffULL;
-  static const float kMinLong = (float) (int64_t) 0x8000000000000000ULL;
+  static const float kMaxLong = static_cast<float>(static_cast<int64_t>(0x7fffffffffffffffULL));
+  static const float kMinLong = static_cast<float>(static_cast<int64_t>(0x8000000000000000ULL));
   if (f >= kMaxLong) {
-    return (int64_t) 0x7fffffffffffffffULL;
+    return 0x7fffffffffffffffULL;
   } else if (f <= kMinLong) {
-    return (int64_t) 0x8000000000000000ULL;
+    return 0x8000000000000000ULL;
   } else if (f != f) { // NaN case
     return 0;
   } else {
-    return (int64_t) f;
+    return static_cast<int64_t>(f);
   }
 }
 
 int32_t art_d2i(double d) {
-  static const double kMaxInt = (double) (int32_t) 0x7fffffffUL;
-  static const double kMinInt = (double) (int32_t) 0x80000000UL;
+  static const double kMaxInt = static_cast<double>(0x7fffffffUL);
+  static const double kMinInt = static_cast<double>(0x80000000UL);
   if (d >= kMaxInt) {
-    return (int32_t) 0x7fffffffUL;
+    return 0x7fffffffUL;
   } else if (d <= kMinInt) {
-    return (int32_t) 0x80000000UL;
+    return 0x80000000UL;
   } else if (d != d)  { // NaN case
     return 0;
   } else {
-    return (int32_t) d;
+    return static_cast<int32_t>(d);
   }
 }
 
 int32_t art_f2i(float f) {
-  static const float kMaxInt = (float) (int32_t) 0x7fffffffUL;
-  static const float kMinInt = (float) (int32_t) 0x80000000UL;
+  static const float kMaxInt = static_cast<float>(0x7fffffffUL);
+  static const float kMinInt = static_cast<float>(0x80000000UL);
   if (f >= kMaxInt) {
-    return (int32_t) 0x7fffffffUL;
+    return 0x7fffffffUL;
   } else if (f <= kMinInt) {
-    return (int32_t) 0x80000000UL;
+    return 0x80000000UL;
   } else if (f != f) { // NaN case
     return 0;
   } else {
-    return (int32_t) f;
+    return static_cast<int32_t>(f);
   }
 }
 
diff --git a/src/safe_map.h b/src/safe_map.h
index 0af158f..6df05e2 100644
--- a/src/safe_map.h
+++ b/src/safe_map.h
@@ -1,3 +1,19 @@
+/*
+ * Copyright (C) 2012 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_SAFE_MAP_H_
 #define ART_SRC_SAFE_MAP_H_
 
@@ -20,7 +36,10 @@
   typedef typename ::std::map<K, V, Comparator>::size_type size_type;
   typedef typename ::std::map<K, V, Comparator>::value_type value_type;
 
-  Self& operator=(const Self& rhs) { map_ = rhs.map_; return *this; }
+  Self& operator=(const Self& rhs) {
+    map_ = rhs.map_;
+    return *this;
+  }
 
   iterator begin() { return map_.begin(); }
   const_iterator begin() const { return map_.begin(); }
diff --git a/src/verifier/reg_type_cache.h b/src/verifier/reg_type_cache.h
index 51eccd5..ca0ada6 100644
--- a/src/verifier/reg_type_cache.h
+++ b/src/verifier/reg_type_cache.h
@@ -60,10 +60,10 @@
   const RegType& JavaLangString() { return From(RegType::kRegTypeReference, NULL, "Ljava/lang/String;"); }
   const RegType& JavaLangThrowable() { return From(RegType::kRegTypeReference, NULL, "Ljava/lang/Throwable;"); }
 
-  const RegType& Undefined(){ return FromType(RegType::kRegTypeUndefined); }
-  const RegType& Conflict() { return FromType(RegType::kRegTypeConflict); }
-  const RegType& ConstLo()  { return FromType(RegType::kRegTypeConstLo); }
-  const RegType& Zero()     { return FromCat1Const(0); }
+  const RegType& Undefined() { return FromType(RegType::kRegTypeUndefined); }
+  const RegType& Conflict()  { return FromType(RegType::kRegTypeConflict); }
+  const RegType& ConstLo()   { return FromType(RegType::kRegTypeConstLo); }
+  const RegType& Zero()      { return FromCat1Const(0); }
 
   const RegType& Uninitialized(const RegType& type, uint32_t allocation_pc);
   // Create an uninitialized 'this' argument for the given type.
diff --git a/test/023-many-interfaces/iface-gen.c b/test/023-many-interfaces/iface-gen.c
index 1e3284a..9eb17f2 100644
--- a/test/023-many-interfaces/iface-gen.c
+++ b/test/023-many-interfaces/iface-gen.c
@@ -16,7 +16,7 @@
     for (i = 0; i < count; i++) {
         char nameBuf[32];
 
-        sprintf(nameBuf, "src/Interface%03d.java", i);
+        snprintf(nameBuf, sizeof(nameBuf), "src/Interface%03d.java", i);
         fp = fopen(nameBuf, "w");
         if (fp == NULL) {
             fprintf(stderr, "ERROR: unable to open %s\n", nameBuf);
diff --git a/tools/cpplint.py b/tools/cpplint.py
index 73a4644..526b955 100755
--- a/tools/cpplint.py
+++ b/tools/cpplint.py
@@ -150,6 +150,7 @@
   'build/class',
   'build/deprecated',
   'build/endif_comment',
+  'build/explicit_make_pair',
   'build/forward_decl',
   'build/header_guard',
   'build/include',
@@ -210,11 +211,11 @@
 # flag. By default all errors are on, so only add here categories that should be
 # off by default (i.e., categories that must be enabled by the --filter= flags).
 # All entries here should start with a '-' or '+', as in the --filter= flag.
-_DEFAULT_FILTERS = [ '-build/include_alpha' ]
+_DEFAULT_FILTERS = ['-build/include_alpha']
 
 # We used to check for high-bit characters, but after much discussion we
 # decided those were OK, as long as they were in UTF-8 and didn't represent
-# hard-coded international strings, which belong in a seperate i18n file.
+# hard-coded international strings, which belong in a separate i18n file.
 
 # Headers that we consider STL headers.
 _STL_HEADERS = frozenset([
@@ -235,11 +236,11 @@
     'cstdio', 'cstdlib', 'cstring', 'ctime', 'cwchar', 'cwctype',
     'defalloc.h', 'deque.h', 'editbuf.h', 'exception', 'fstream',
     'fstream.h', 'hashtable.h', 'heap.h', 'indstream.h', 'iomanip',
-    'iomanip.h', 'ios', 'iosfwd', 'iostream', 'iostream.h', 'istream.h',
-    'iterator.h', 'limits', 'map.h', 'multimap.h', 'multiset.h',
-    'numeric', 'ostream.h', 'parsestream.h', 'pfstream.h', 'PlotFile.h',
-    'procbuf.h', 'pthread_alloc.h', 'rope', 'rope.h', 'ropeimpl.h',
-    'SFile.h', 'slist', 'slist.h', 'stack.h', 'stdexcept',
+    'iomanip.h', 'ios', 'iosfwd', 'iostream', 'iostream.h', 'istream',
+    'istream.h', 'iterator.h', 'limits', 'map.h', 'multimap.h', 'multiset.h',
+    'numeric', 'ostream', 'ostream.h', 'parsestream.h', 'pfstream.h',
+    'PlotFile.h', 'procbuf.h', 'pthread_alloc.h', 'rope', 'rope.h',
+    'ropeimpl.h', 'SFile.h', 'slist', 'slist.h', 'stack.h', 'stdexcept',
     'stdiostream.h', 'streambuf.h', 'stream.h', 'strfile.h', 'string',
     'strstream', 'strstream.h', 'tempbuf.h', 'tree.h', 'typeinfo', 'valarray',
     ])
@@ -310,9 +311,9 @@
     error: function, an error handler.
   """
   # FIXME(adonovan): "NOLINT(" is misparsed as NOLINT(*).
-  m = _RE_SUPPRESSION.search(raw_line)
-  if m:
-    category = m.group(1)
+  matched = _RE_SUPPRESSION.search(raw_line)
+  if matched:
+    category = matched.group(1)
     if category in (None, '(*)'):  # => "suppress all"
       _error_suppressions.setdefault(None, set()).add(linenum)
     else:
@@ -322,7 +323,7 @@
           _error_suppressions.setdefault(category, set()).add(linenum)
         else:
           error(filename, linenum, 'readability/nolint', 5,
-            'Unknown NOLINT error category: %s' % category)
+                'Unknown NOLINT error category: %s' % category)
 
 
 def ResetNolintSuppressions():
@@ -404,7 +405,7 @@
     self._last_header = ''
 
   def CanonicalizeAlphabeticalOrder(self, header_path):
-    """Returns a path canonicalized for alphabetical comparisson.
+    """Returns a path canonicalized for alphabetical comparison.
 
     - replaces "-" with "_" so they both cmp the same.
     - removes '-inl' since we don't require them to be after the main header.
@@ -662,7 +663,7 @@
                 self.current_function, self.lines_in_function, trigger))
 
   def End(self):
-    """Stop analizing function body."""
+    """Stop analyzing function body."""
     self.in_a_function = False
 
 
@@ -712,16 +713,18 @@
         prefix = os.path.commonprefix([root_dir, project_dir])
         return fullname[len(prefix) + 1:]
 
-      # Not SVN? Try to find a git or hg top level directory by searching up
-      # from the current path.
+      # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by
+      # searching up from the current path.
       root_dir = os.path.dirname(fullname)
       while (root_dir != os.path.dirname(root_dir) and
              not os.path.exists(os.path.join(root_dir, ".git")) and
-             not os.path.exists(os.path.join(root_dir, ".hg"))):
+             not os.path.exists(os.path.join(root_dir, ".hg")) and
+             not os.path.exists(os.path.join(root_dir, ".svn"))):
         root_dir = os.path.dirname(root_dir)
 
       if (os.path.exists(os.path.join(root_dir, ".git")) or
-          os.path.exists(os.path.join(root_dir, ".hg"))):
+          os.path.exists(os.path.join(root_dir, ".hg")) or
+          os.path.exists(os.path.join(root_dir, ".svn"))):
         prefix = os.path.commonprefix([root_dir, project_dir])
         return fullname[len(prefix) + 1:]
 
@@ -760,8 +763,7 @@
 
 
 def _ShouldPrintError(category, confidence, linenum):
-  """Returns true iff confidence >= verbose, category passes
-  filter and is not NOLINT-suppressed."""
+  """If confidence >= verbose, category passes filter and is not suppressed."""
 
   # There are three ways we might decide not to print an error message:
   # a "NOLINT(category)" comment appears in the source,
@@ -913,7 +915,7 @@
   """
   commentpos = line.find('//')
   if commentpos != -1 and not IsCppString(line[:commentpos]):
-    line = line[:commentpos]
+    line = line[:commentpos].rstrip()
   # get rid of /* ... */
   return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
 
@@ -966,7 +968,7 @@
 def CloseExpression(clean_lines, linenum, pos):
   """If input points to ( or { or [, finds the position that closes it.
 
-  If lines[linenum][pos] points to a '(' or '{' or '[', finds the the
+  If lines[linenum][pos] points to a '(' or '{' or '[', finds the
   linenum/pos that correspond to the closing of the expression.
 
   Args:
@@ -1069,12 +1071,18 @@
       endif = line
       endif_linenum = linenum
 
-  if not ifndef or not define or ifndef != define:
+  if not ifndef:
     error(filename, 0, 'build/header_guard', 5,
           'No #ifndef header guard found, suggested CPP variable is: %s' %
           cppvar)
     return
 
+  if not define:
+    error(filename, 0, 'build/header_guard', 5,
+          'No #define header guard found, suggested CPP variable is: %s' %
+          cppvar)
+    return
+
   # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__
   # for backward compatibility.
   if ifndef != cppvar:
@@ -1087,6 +1095,12 @@
     error(filename, ifndef_linenum, 'build/header_guard', error_level,
           '#ifndef header guard has wrong style, please use: %s' % cppvar)
 
+  if define != ifndef:
+    error(filename, 0, 'build/header_guard', 5,
+          '#ifndef and #define don\'t match, suggested CPP variable is: %s' %
+          cppvar)
+    return
+
   if endif != ('#endif  // %s' % cppvar):
     error_level = 0
     if endif != ('#endif  // %s' % (cppvar + '_')):
@@ -1248,7 +1262,7 @@
 class _ClassInfo(object):
   """Stores information about a class."""
 
-  def __init__(self, name, linenum):
+  def __init__(self, name, clean_lines, linenum):
     self.name = name
     self.linenum = linenum
     self.seen_open_brace = False
@@ -1257,6 +1271,20 @@
     self.has_virtual_destructor = False
     self.brace_depth = 0
 
+    # Try to find the end of the class.  This will be confused by things like:
+    #   class A {
+    #   } *x = { ...
+    #
+    # But it's still good enough for CheckSectionSpacing.
+    self.last_line = 0
+    depth = 0
+    for i in range(linenum, clean_lines.NumLines()):
+      line = clean_lines.lines[i]
+      depth += line.count('{') - line.count('}')
+      if not depth:
+        self.last_line = i
+        break
+
 
 class _ClassState(object):
   """Holds the current state of the parse relating to class declarations.
@@ -1378,11 +1406,16 @@
   # style guidelines, but it seems to perform well enough in testing
   # to be a worthwhile addition to the checks.
   classinfo_stack = class_state.classinfo_stack
-  # Look for a class declaration
+  # Look for a class declaration. The regexp accounts for decorated classes
+  # such as in:
+  # class LOCKABLE API Object {
+  # };
   class_decl_match = Match(
-      r'\s*(template\s*<[\w\s<>,:]*>\s*)?(class|struct)\s+(\w+(::\w+)*)', line)
+      r'\s*(template\s*<[\w\s<>,:]*>\s*)?'
+      '(class|struct)\s+([A-Z_]+\s+)*(\w+(::\w+)*)', line)
   if class_decl_match:
-    classinfo_stack.append(_ClassInfo(class_decl_match.group(3), linenum))
+    classinfo_stack.append(_ClassInfo(
+        class_decl_match.group(4), clean_lines, linenum))
 
   # Everything else in this function uses the top of the stack if it's
   # not empty.
@@ -1412,12 +1445,12 @@
 
   # Look for single-argument constructors that aren't marked explicit.
   # Technically a valid construct, but against style.
-  args = Match(r'(?<!explicit)\s+%s\s*\(([^,()]+)\)'
+  args = Match(r'\s+(?:inline\s+)?%s\s*\(([^,()]+)\)'
                % re.escape(base_classname),
                line)
   if (args and
       args.group(1) != 'void' and
-      not Match(r'(const\s+)?%s\s*&' % re.escape(base_classname),
+      not Match(r'(const\s+)?%s\s*(?:<\w+>\s*)?&' % re.escape(base_classname),
                 args.group(1).strip())):
     error(filename, linenum, 'runtime/explicit', 5,
           'Single-argument constructors should be marked explicit.')
@@ -1508,8 +1541,14 @@
     # If the ) is followed only by a newline or a { + newline, assume it's
     # part of a control statement (if/while/etc), and don't complain
     if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
-      error(filename, linenum, 'whitespace/parens', 2,
-            'Extra space before )')
+      # If the closing parenthesis is preceded by only whitespaces,
+      # try to give a more descriptive error message.
+      if Search(r'^\s+\)', fncall):
+        error(filename, linenum, 'whitespace/parens', 2,
+              'Closing ) should be moved to the previous line')
+      else:
+        error(filename, linenum, 'whitespace/parens', 2,
+              'Extra space before )')
 
 
 def IsBlankLine(line):
@@ -1540,7 +1579,7 @@
   Trivial bodies are unchecked, so constructors with huge initializer lists
   may be missed.
   Blank/comment lines are not counted so as to avoid encouraging the removal
-  of vertical space and commments just to get through a lint check.
+  of vertical space and comments just to get through a lint check.
   NOLINT *on the last line of a function* disables this check.
 
   Args:
@@ -1636,8 +1675,8 @@
   Things we check for: spaces around operators, spaces after
   if/for/while/switch, no spaces around parens in function calls, two
   spaces between code and comment, don't start a block with a blank
-  line, don't end a function with a blank line, don't have too many
-  blank lines in a row.
+  line, don't end a function with a blank line, don't add a blank line
+  after public/protected/private, don't have too many blank lines in a row.
 
   Args:
     filename: The name of the current file.
@@ -1664,7 +1703,7 @@
         and prev_line[:prevbrace].find('namespace') == -1):
       # OK, we have a blank line at the start of a code block.  Before we
       # complain, we check if it is an exception to the rule: The previous
-      # non-empty line has the paramters of a function header that are indented
+      # non-empty line has the parameters of a function header that are indented
       # 4 spaces (because they did not fit in a 80 column line when placed on
       # the same line as the function name).  We also check for the case where
       # the previous line is indented 6 spaces, which may happen when the
@@ -1715,6 +1754,11 @@
         error(filename, linenum, 'whitespace/blank_line', 3,
               'Blank line at the end of a code block.  Is this needed?')
 
+    matched = Match(r'\s*(public|protected|private):', prev_line)
+    if matched:
+      error(filename, linenum, 'whitespace/blank_line', 3,
+            'Do not leave a blank line after "%s:"' % matched.group(1))
+
   # Next, we complain if there's a comment too near the text
   commentpos = line.find('//')
   if commentpos != -1:
@@ -1824,13 +1868,22 @@
     error(filename, linenum, 'whitespace/comma', 3,
           'Missing space after ,')
 
+  # You should always have a space after a semicolon
+  # except for few corner cases
+  # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
+  # space after ;
+  if Search(r';[^\s};\\)/]', line):
+    error(filename, linenum, 'whitespace/semicolon', 3,
+          'Missing space after ;')
+
   # Next we will look for issues with function calls.
   CheckSpacingForFunctionCall(filename, line, linenum, error)
 
-  # Except after an opening paren, you should have spaces before your braces.
-  # And since you should never have braces at the beginning of a line, this is
-  # an easy test.
-  if Search(r'[^ (]{', line):
+  # Except after an opening paren, or after another opening brace (in case of
+  # an initializer list, for instance), you should have spaces before your
+  # braces. And since you should never have braces at the beginning of a line,
+  # this is an easy test.
+  if Search(r'[^ ({]{', line):
     error(filename, linenum, 'whitespace/braces', 5,
           'Missing space before {')
 
@@ -1862,6 +1915,58 @@
           'statement, use { } instead.')
 
 
+def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
+  """Checks for additional blank line issues related to sections.
+
+  Currently the only thing checked here is blank line before protected/private.
+
+  Args:
+    filename: The name of the current file.
+    clean_lines: A CleansedLines instance containing the file.
+    class_info: A _ClassInfo objects.
+    linenum: The number of the line to check.
+    error: The function to call with any errors found.
+  """
+  # Skip checks if the class is small, where small means 25 lines or less.
+  # 25 lines seems like a good cutoff since that's the usual height of
+  # terminals, and any class that can't fit in one screen can't really
+  # be considered "small".
+  #
+  # Also skip checks if we are on the first line.  This accounts for
+  # classes that look like
+  #   class Foo { public: ... };
+  #
+  # If we didn't find the end of the class, last_line would be zero,
+  # and the check will be skipped by the first condition.
+  if (class_info.last_line - class_info.linenum <= 24 or
+      linenum <= class_info.linenum):
+    return
+
+  matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])
+  if matched:
+    # Issue warning if the line before public/protected/private was
+    # not a blank line, but don't do this if the previous line contains
+    # "class" or "struct".  This can happen two ways:
+    #  - We are at the beginning of the class.
+    #  - We are forward-declaring an inner class that is semantically
+    #    private, but needed to be public for implementation reasons.
+    prev_line = clean_lines.lines[linenum - 1]
+    if (not IsBlankLine(prev_line) and
+        not Search(r'\b(class|struct)\b', prev_line)):
+      # Try a bit harder to find the beginning of the class.  This is to
+      # account for multi-line base-specifier lists, e.g.:
+      #   class Derived
+      #       : public Base {
+      end_class_head = class_info.linenum
+      for i in range(class_info.linenum, linenum):
+        if Search(r'\{\s*$', clean_lines.lines[i]):
+          end_class_head = i
+          break
+      if end_class_head < linenum - 1:
+        error(filename, linenum, 'whitespace/blank_line', 3,
+              '"%s:" should be preceded by a blank line' % matched.group(1))
+
+
 def GetPreviousNonBlankLine(clean_lines, linenum):
   """Return the most recent non-blank line and its line number.
 
@@ -2039,17 +2144,18 @@
   """
   if isinstance(line, unicode):
     width = 0
-    for c in unicodedata.normalize('NFC', line):
-      if unicodedata.east_asian_width(c) in ('W', 'F'):
+    for uc in unicodedata.normalize('NFC', line):
+      if unicodedata.east_asian_width(uc) in ('W', 'F'):
         width += 2
-      elif not unicodedata.combining(c):
+      elif not unicodedata.combining(uc):
         width += 1
     return width
   else:
     return len(line)
 
 
-def CheckStyle(filename, clean_lines, linenum, file_extension, error):
+def CheckStyle(filename, clean_lines, linenum, file_extension, class_state,
+               error):
   """Checks rules from the 'C++ style rules' section of cppguide.html.
 
   Most of these rules are hard to test (naming, comment style), but we
@@ -2119,8 +2225,12 @@
   #
   # URLs can be long too.  It's possible to split these, but it makes them
   # harder to cut&paste.
+  #
+  # The "$Id:...$" comment may also get very long without it being the
+  # developers fault.
   if (not line.startswith('#include') and not is_header_guard and
-      not Match(r'^\s*//.*http(s?)://\S*$', line)):
+      not Match(r'^\s*//.*http(s?)://\S*$', line) and
+      not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
     line_width = GetLineWidth(line)
     if line_width > 100:
       error(filename, linenum, 'whitespace/line_length', 4,
@@ -2145,6 +2255,9 @@
   CheckBraces(filename, clean_lines, linenum, error)
   CheckSpacing(filename, clean_lines, linenum, error)
   CheckCheck(filename, clean_lines, linenum, error)
+  if class_state and class_state.classinfo_stack:
+    CheckSectionSpacing(filename, clean_lines,
+                        class_state.classinfo_stack[-1], linenum, error)
 
 
 _RE_PATTERN_INCLUDE_NEW_STYLE = re.compile(r'#include +"[^/]+\.h"')
@@ -2330,6 +2443,63 @@
         error(filename, linenum, 'readability/streams', 3,
               'Streams are highly discouraged.')
 
+
+def _GetTextInside(text, start_pattern):
+  """Retrieves all the text between matching open and close parentheses.
+
+  Given a string of lines and a regular expression string, retrieve all the text
+  following the expression and between opening punctuation symbols like
+  (, [, or {, and the matching close-punctuation symbol. This properly nested
+  occurrences of the punctuations, so for the text like
+    printf(a(), b(c()));
+  a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
+  start_pattern must match string having an open punctuation symbol at the end.
+
+  Args:
+    text: The lines to extract text. Its comments and strings must be elided.
+           It can be single line and can span multiple lines.
+    start_pattern: The regexp string indicating where to start extracting
+                   the text.
+  Returns:
+    The extracted text.
+    None if either the opening string or ending punctuation could not be found.
+  """
+  # TODO(sugawarayu): Audit cpplint.py to see what places could be profitably
+  # rewritten to use _GetTextInside (and use inferior regexp matching today).
+
+  # Give opening punctuations to get the matching close-punctuations.
+  matching_punctuation = {'(': ')', '{': '}', '[': ']'}
+  closing_punctuation = set(matching_punctuation.itervalues())
+
+  # Find the position to start extracting text.
+  match = re.search(start_pattern, text, re.M)
+  if not match:  # start_pattern not found in text.
+    return None
+  start_position = match.end(0)
+
+  assert start_position > 0, (
+      'start_pattern must ends with an opening punctuation.')
+  assert text[start_position - 1] in matching_punctuation, (
+      'start_pattern must ends with an opening punctuation.')
+  # Stack of closing punctuations we expect to have in text after position.
+  punctuation_stack = [matching_punctuation[text[start_position - 1]]]
+  position = start_position
+  while punctuation_stack and position < len(text):
+    if text[position] == punctuation_stack[-1]:
+      punctuation_stack.pop()
+    elif text[position] in closing_punctuation:
+      # A closing punctuation without matching opening punctuations.
+      return None
+    elif text[position] in matching_punctuation:
+      punctuation_stack.append(matching_punctuation[text[position]])
+    position += 1
+  if punctuation_stack:
+    # Opening punctuations left without matching close-punctuations.
+    return None
+  # punctuations match.
+  return text[start_position:position - 1]
+
+
 def CheckLanguage(filename, clean_lines, linenum, file_extension, include_state,
                   error):
   """Checks rules from the 'C++ language rules' section of cppguide.html.
@@ -2375,7 +2545,7 @@
   # These are complicated re's.  They try to capture the following:
   # paren (for fn-prototype start), typename, &, varname.  For the const
   # version, we're willing for const to be before typename or after
-  # Don't check the implemention on same line.
+  # Don't check the implementation on same line.
   fnline = line.split('{', 1)[0]
   if (len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) >
       len(re.findall(r'\([^()]*\bconst\s+(?:typename\s+)?(?:struct\s+)?'
@@ -2402,9 +2572,12 @@
   if match:
     # gMock methods are defined using some variant of MOCK_METHODx(name, type)
     # where type may be float(), int(string), etc.  Without context they are
-    # virtually indistinguishable from int(x) casts.
+    # virtually indistinguishable from int(x) casts. Likewise, gMock's
+    # MockCallback takes a template parameter of the form return_type(arg_type),
+    # which looks much like the cast we're trying to detect.
     if (match.group(1) is None and  # If new operator, then this isn't a cast
-        not Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line)):
+        not (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
+             Match(r'^\s*MockCallback<.*>', line))):
       error(filename, linenum, 'readability/casting', 4,
             'Using deprecated casting style.  '
             'Use static_cast<%s>(...) instead' %
@@ -2412,11 +2585,19 @@
 
   CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
                   'static_cast',
-                  r'\((int|float|double|bool|char|u?int(16|32|64))\)',
-                  error)
-  # This doesn't catch all cases.  Consider (const char * const)"hello".
-  CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
-                  'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error)
+                  r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)
+
+  # This doesn't catch all cases. Consider (const char * const)"hello".
+  #
+  # (char *) "foo" should always be a const_cast (reinterpret_cast won't
+  # compile).
+  if CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
+                     'const_cast', r'\((char\s?\*+\s?)\)\s*"', error):
+    pass
+  else:
+    # Check pointer casts for other than string constants
+    CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
+                    'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error)
 
   # In addition, we look for people taking the address of a cast.  This
   # is dangerous -- casts can assign to temporaries, so the pointer doesn't
@@ -2515,11 +2696,19 @@
   # Check for potential format string bugs like printf(foo).
   # We constrain the pattern not to pick things like DocidForPrintf(foo).
   # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
-  match = re.search(r'\b((?:string)?printf)\s*\(([\w.\->()]+)\)', line, re.I)
-  if match:
-    error(filename, linenum, 'runtime/printf', 4,
-          'Potential format string bug. Do %s("%%s", %s) instead.'
-          % (match.group(1), match.group(2)))
+  # TODO(sugawarayu): Catch the following case. Need to change the calling
+  # convention of the whole function to process multiple line to handle it.
+  #   printf(
+  #       boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);
+  printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(')
+  if printf_args:
+    match = Match(r'([\w.\->()]+)$', printf_args)
+    if match:
+      function_name = re.search(r'\b((?:string)?printf)\s*\(',
+                                line, re.I).group(1)
+      error(filename, linenum, 'runtime/printf', 4,
+            'Potential format string bug. Do %s("%%s", %s) instead.'
+            % (function_name, match.group(1)))
 
   # Check for potential memset bugs like memset(buf, sizeof(buf), 0).
   match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
@@ -2561,7 +2750,7 @@
       if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
       # A catch all for tricky sizeof cases, including 'sizeof expression',
       # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
-      # requires skipping the next token becasue we split on ' ' and '*'.
+      # requires skipping the next token because we split on ' ' and '*'.
       if tok.startswith('sizeof'):
         skip_next = True
         continue
@@ -2582,7 +2771,13 @@
       line)
   if match and linenum + 1 < clean_lines.NumLines():
     next_line = clean_lines.elided[linenum + 1]
-    if not Search(r'^\s*};', next_line):
+    # We allow some, but not all, declarations of variables to be present
+    # in the statement that defines the class.  The [\w\*,\s]* fragment of
+    # the regular expression below allows users to declare instances of
+    # the class or pointers to instances, but not less common types such
+    # as function pointers or arrays.  It's a tradeoff between allowing
+    # reasonable code and avoiding trying to parse more C++ using regexps.
+    if not Search(r'^\s*}[\w\*,\s]*;', next_line):
       error(filename, linenum, 'readability/constructors', 3,
             match.group(1) + ' should be the last thing in the class')
 
@@ -2610,20 +2805,24 @@
     line: The line of code to check.
     raw_line: The raw line of code to check, with comments.
     cast_type: The string for the C++ cast to recommend.  This is either
-      reinterpret_cast or static_cast, depending.
+      reinterpret_cast, static_cast, or const_cast, depending.
     pattern: The regular expression used to find C-style casts.
     error: The function to call with any errors found.
+
+  Returns:
+    True if an error was emitted.
+    False otherwise.
   """
   match = Search(pattern, line)
   if not match:
-    return
+    return False
 
   # e.g., sizeof(int)
   sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1])
   if sizeof_match:
     error(filename, linenum, 'runtime/sizeof', 1,
           'Using sizeof(type).  Use sizeof(varname) instead if possible')
-    return
+    return True
 
   remainder = line[match.end(0):]
 
@@ -2634,24 +2833,28 @@
   # eg, void foo(int); or void foo(int) const;
   # The equals check is for function pointer assignment.
   # eg, void *(*foo)(int) = ...
+  # The > is for MockCallback<...> ...
   #
   # Right now, this will only catch cases where there's a single argument, and
   # it's unnamed.  It should probably be expanded to check for multiple
   # arguments with some unnamed.
-  function_match = Match(r'\s*(\)|=|(const)?\s*(;|\{|throw\(\)))', remainder)
+  function_match = Match(r'\s*(\)|=|(const)?\s*(;|\{|throw\(\)|>))', remainder)
   if function_match:
     if (not function_match.group(3) or
         function_match.group(3) == ';' or
-        raw_line.find('/*') < 0):
+        ('MockCallback<' not in raw_line and
+         '/*' not in raw_line)):
       error(filename, linenum, 'readability/function', 3,
             'All parameters should be named in a function')
-    return
+    return True
 
   # At this point, all that should be left is actual casts.
   error(filename, linenum, 'readability/casting', 4,
         'Using C-style cast.  Use %s<%s>(...) instead' %
         (cast_type, match.group(1)))
 
+  return True
+
 
 _HEADERS_CONTAINING_TEMPLATES = (
     ('<deque>', ('deque',)),
@@ -2690,11 +2893,6 @@
     ('<slist>', ('slist',)),
     )
 
-_HEADERS_ACCEPTED_BUT_NOT_PROMOTED = {
-    # We can trust with reasonable confidence that map gives us pair<>, too.
-    'pair<>': ('map', 'multimap', 'hash_map', 'hash_multimap')
-}
-
 _RE_PATTERN_STRING = re.compile(r'\bstring\b')
 
 _re_pattern_algorithm_header = []
@@ -2827,11 +3025,11 @@
       continue
 
     # String is special -- it is a non-templatized type in STL.
-    m = _RE_PATTERN_STRING.search(line)
-    if m:
+    matched = _RE_PATTERN_STRING.search(line)
+    if matched:
       # Don't warn about strings in non-STL namespaces:
       # (We check only the first match per line; good enough.)
-      prefix = line[:m.start()]
+      prefix = line[:matched.start()]
       if prefix.endswith('std::') or not prefix.endswith('::'):
         required['<string>'] = (linenum, 'string')
 
@@ -2856,7 +3054,7 @@
   header_found = False
 
   # Use the absolute path so that matching works properly.
-  abs_filename = os.path.abspath(filename)
+  abs_filename = FileInfo(filename).FullName()
 
   # For Emacs's flymake.
   # If cpplint is invoked from Emacs's flymake, a temporary file is generated
@@ -2869,7 +3067,8 @@
 
   # include_state is modified during iteration, so we iterate over a copy of
   # the keys.
-  for header in include_state.keys():  #NOLINT
+  header_keys = include_state.keys()
+  for header in header_keys:
     (same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
     fullpath = common_path + header
     if same_module and UpdateIncludeState(fullpath, include_state, io):
@@ -2886,19 +3085,40 @@
   # All the lines have been processed, report the errors found.
   for required_header_unstripped in required:
     template = required[required_header_unstripped][1]
-    if template in _HEADERS_ACCEPTED_BUT_NOT_PROMOTED:
-      headers = _HEADERS_ACCEPTED_BUT_NOT_PROMOTED[template]
-      if [True for header in headers if header in include_state]:
-        continue
     if required_header_unstripped.strip('<>"') not in include_state:
       error(filename, required[required_header_unstripped][0],
             'build/include_what_you_use', 4,
             'Add #include ' + required_header_unstripped + ' for ' + template)
 
 
+_RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<')
+
+
+def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
+  """Check that make_pair's template arguments are deduced.
+
+  G++ 4.6 in C++0x mode fails badly if make_pair's template arguments are
+  specified explicitly, and such use isn't intended in any case.
+
+  Args:
+    filename: The name of the current file.
+    clean_lines: A CleansedLines instance containing the file.
+    linenum: The number of the line to check.
+    error: The function to call with any errors found.
+  """
+  raw = clean_lines.raw_lines
+  line = raw[linenum]
+  match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
+  if match:
+    error(filename, linenum, 'build/explicit_make_pair',
+          4,  # 4 = high confidence
+          'Omit template arguments from make_pair OR use pair directly OR'
+          ' if appropriate, construct a pair directly')
+
+
 def ProcessLine(filename, file_extension,
                 clean_lines, line, include_state, function_state,
-                class_state, error):
+                class_state, error, extra_check_functions=[]):
   """Processes a single line in the file.
 
   Args:
@@ -2913,30 +3133,39 @@
                  the current stack of nested class declarations being parsed.
     error: A callable to which errors are reported, which takes 4 arguments:
            filename, line number, error level, and message
-
+    extra_check_functions: An array of additional check functions that will be
+                           run on each source line. Each function takes 4
+                           arguments: filename, clean_lines, line, error
   """
   raw_lines = clean_lines.raw_lines
   ParseNolintSuppressions(filename, raw_lines[line], line, error)
   CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
   CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
-  CheckStyle(filename, clean_lines, line, file_extension, error)
+  CheckStyle(filename, clean_lines, line, file_extension, class_state, error)
   CheckLanguage(filename, clean_lines, line, file_extension, include_state,
                 error)
   CheckForNonStandardConstructs(filename, clean_lines, line,
                                 class_state, error)
   CheckPosixThreading(filename, clean_lines, line, error)
   CheckInvalidIncrement(filename, clean_lines, line, error)
+  CheckMakePairUsesDeduction(filename, clean_lines, line, error)
+  for check_fn in extra_check_functions:
+    check_fn(filename, clean_lines, line, error)
 
-
-def ProcessFileData(filename, file_extension, lines, error):
+def ProcessFileData(filename, file_extension, lines, error,
+                    extra_check_functions=[]):
   """Performs lint checks and reports any errors to the given error function.
 
   Args:
     filename: Filename of the file that is being processed.
     file_extension: The extension (dot not included) of the file.
     lines: An array of strings, each representing a line of the file, with the
-           last element being empty if the file is termined with a newline.
+           last element being empty if the file is terminated with a newline.
     error: A callable to which errors are reported, which takes 4 arguments:
+           filename, line number, error level, and message
+    extra_check_functions: An array of additional check functions that will be
+                           run on each source line. Each function takes 4
+                           arguments: filename, clean_lines, line, error
   """
   lines = (['// marker so line numbers and indices both start at 1'] + lines +
            ['// marker so line numbers end in a known way'])
@@ -2956,7 +3185,8 @@
   clean_lines = CleansedLines(lines)
   for line in xrange(clean_lines.NumLines()):
     ProcessLine(filename, file_extension, clean_lines, line,
-                include_state, function_state, class_state, error)
+                include_state, function_state, class_state, error,
+                extra_check_functions)
   class_state.CheckFinished(filename, error)
 
   CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
@@ -2967,7 +3197,7 @@
 
   CheckForNewlineAtEOF(filename, lines, error)
 
-def ProcessFile(filename, vlevel):
+def ProcessFile(filename, vlevel, extra_check_functions=[]):
   """Does google-lint on a single file.
 
   Args:
@@ -2975,6 +3205,10 @@
 
     vlevel: The level of errors to report.  Every error of confidence
     >= verbose_level will be reported.  0 is a good default.
+
+    extra_check_functions: An array of additional check functions that will be
+                           run on each source line. Each function takes 4
+                           arguments: filename, clean_lines, line, error
   """
 
   _SetVerboseLevel(vlevel)
@@ -3019,9 +3253,10 @@
       and file_extension != 'cpp'):
     sys.stderr.write('Ignoring %s; not a .cc or .h file\n' % filename)
   else:
-    ProcessFileData(filename, file_extension, lines, Error)
+    ProcessFileData(filename, file_extension, lines, Error,
+                    extra_check_functions)
     if carriage_return_found and os.linesep != '\r\n':
-      # Use 0 for linenum since outputing only one error for potentially
+      # Use 0 for linenum since outputting only one error for potentially
       # several lines.
       Error(filename, 0, 'whitespace/newline', 1,
             'One or more unexpected \\r (^M) found;'