Properly handle asserts for libbcc.

BUG=3430681

Change-Id: I906bbdefa6724cefa0e11f04ff1c5a9bc85ab88b
diff --git a/Android.mk b/Android.mk
index 90edc7d..b9a19c0 100644
--- a/Android.mk
+++ b/Android.mk
@@ -17,6 +17,9 @@
 ifneq ($(TARGET_SIMULATOR),true)
 
 local_cflags_for_libbcc := -Wall -Wno-unused-parameter -Werror
+ifneq ($(TARGET_BUILD_VARIANT),eng)
+local_cflags_for_libbcc += -D__DISABLE_ASSERTS
+endif
 
 LOCAL_PATH := $(call my-dir)
 
diff --git a/include/bcc/bcc_assert.h b/include/bcc/bcc_assert.h
new file mode 100644
index 0000000..bd4a1e9
--- /dev/null
+++ b/include/bcc/bcc_assert.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2011, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _FRAMEWORKS_COMPILE_LIBBCC_INCLUDE_BCC_BCC_ASSERT_H_  // NOLINT
+#define _FRAMEWORKS_COMPILE_LIBBCC_INCLUDE_BCC_BCC_ASSERT_H_
+
+#ifdef __cplusplus
+#include <cstdlib>
+#include <cstdio>
+#else
+#include <stdlib.h>
+#include <stdio.h>
+#endif  // __cplusplus
+
+#ifdef __DISABLE_ASSERTS
+#define bccAssert(v) do {} while (0)
+#else
+#define __ABORT_ON_FAILURES 1
+#define bccAssert(v)                                          \
+  do {                                                        \
+    if (!(v)) {                                               \
+      fprintf(stderr, "bccAssert failed at %s:%d - '%s'\n",   \
+          __FILE__, __LINE__, #v);                            \
+      if (__ABORT_ON_FAILURES) {                              \
+        abort();                                              \
+      }                                                       \
+    }                                                         \
+  } while (0)
+#endif  // __DISABLE_ASSERTS
+
+
+#endif  // _FRAMEWORKS_COMPILE_LIBBCC_INCLUDE_BCC_BCC_ASSERT_H_  NOLINT
diff --git a/lib/CodeGen/CodeEmitter.cpp b/lib/CodeGen/CodeEmitter.cpp
index 0029909..2b7f9ea 100644
--- a/lib/CodeGen/CodeEmitter.cpp
+++ b/lib/CodeGen/CodeEmitter.cpp
@@ -357,7 +357,7 @@
         GetConstantValue(Op0, Result);
         if (PtrWidth != Result.IntVal.getBitWidth())
           Result.IntVal = Result.IntVal.zextOrTrunc(PtrWidth);
-        assert(Result.IntVal.getBitWidth() <= 64 && "Bad pointer width");
+        bccAssert(Result.IntVal.getBitWidth() <= 64 && "Bad pointer width");
 
         Result.PointerVal =
             llvm::PointerTy(
@@ -371,7 +371,7 @@
 
         switch (Op0->getType()->getTypeID()) {
           case llvm::Type::IntegerTyID: {
-            assert(DestTy->isFloatingPointTy() && "invalid bitcast");
+            bccAssert(DestTy->isFloatingPointTy() && "invalid bitcast");
             if (DestTy->isFloatTy())
               Result.FloatVal = Result.IntVal.bitsToFloat();
             else if (DestTy->isDoubleTy())
@@ -379,17 +379,17 @@
             break;
           }
           case llvm::Type::FloatTyID: {
-            assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
+            bccAssert(DestTy->isIntegerTy(32) && "Invalid bitcast");
             Result.IntVal.floatToBits(Result.FloatVal);
             break;
           }
           case llvm::Type::DoubleTyID: {
-            assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
+            bccAssert(DestTy->isIntegerTy(64) && "Invalid bitcast");
             Result.IntVal.doubleToBits(Result.DoubleVal);
             break;
           }
           case llvm::Type::PointerTyID: {
-            assert(DestTy->isPointerTy() && "Invalid bitcast");
+            bccAssert(DestTy->isPointerTy() && "Invalid bitcast");
             break;  // getConstantValue(Op0) above already converted it
           }
           default: {
@@ -617,7 +617,7 @@
           break;
         }
         case llvm::Value::BlockAddressVal: {
-          assert(false && "JIT does not support address-of-label yet!");
+          bccAssert(false && "JIT does not support address-of-label yet!");
         }
         default: {
           llvm_unreachable("Unknown constant pointer type!");
@@ -646,7 +646,7 @@
   switch (Ty->getTypeID()) {
     case llvm::Type::IntegerTyID: {
       const llvm::APInt &IntVal = Val.IntVal;
-      assert(((IntVal.getBitWidth() + 7) / 8 >= StoreBytes) &&
+      bccAssert(((IntVal.getBitWidth() + 7) / 8 >= StoreBytes) &&
           "Integer too small!");
 
       const uint8_t *Src =
@@ -851,9 +851,9 @@
   if (JT.empty() || mpJumpTableBase == 0)
     return;
 
-  assert(llvm::TargetMachine::getRelocationModel() == llvm::Reloc::Static &&
-         (MJTI->getEntrySize(*mpTD) == sizeof(mpTD /* a pointer type */)) &&
-         "Cross JIT'ing?");
+  bccAssert(llvm::TargetMachine::getRelocationModel() == llvm::Reloc::Static &&
+            (MJTI->getEntrySize(*mpTD) == sizeof(mpTD /* a pointer type */)) &&
+            "Cross JIT'ing?");
 
   // For each jump table, map each target in the jump table to the
   // address of an emitted MachineBasicBlock.
@@ -946,7 +946,7 @@
           break;
         }
         case llvm::Value::GlobalAliasVal: {
-          assert(false && "Alias should be resolved ultimately!");
+          bccAssert(false && "Alias should be resolved ultimately!");
         }
       }
       break;
@@ -1015,8 +1015,8 @@
   if (Addr)
     return Addr;
 
-  assert((F->isDeclaration() || F->hasAvailableExternallyLinkage()) &&
-         "Internal error: only external defined function routes here!");
+  bccAssert((F->isDeclaration() || F->hasAvailableExternallyLinkage()) &&
+            "Internal error: only external defined function routes here!");
 
   // Handle the failure resolution by ourselves.
   Addr = GetPointerToNamedSymbol(F->getName().str().c_str(),
@@ -1245,7 +1245,7 @@
   // set TargetData
   mpTD = TM.getTargetData();
 
-  assert(!mpTJI->needsGOT() && "We don't support GOT needed target!");
+  bccAssert(!mpTJI->needsGOT() && "We don't support GOT needed target!");
 
   return;
 }
@@ -1355,7 +1355,7 @@
           ResultPtr =
              (void*) getConstantPoolEntryAddress(MR.getConstantPoolIndex());
         } else {
-          assert(MR.isJumpTableIndex() && "Unknown type of relocation");
+          bccAssert(MR.isJumpTableIndex() && "Unknown type of relocation");
           ResultPtr =
               (void*) getJumpTableEntryAddress(MR.getJumpTableIndex());
         }
@@ -1441,7 +1441,7 @@
 
 
 void CodeEmitter::finishGVStub() {
-  assert(CurBufferPtr != BufferEnd && "Stub overflowed allocated space.");
+  bccAssert(CurBufferPtr != BufferEnd && "Stub overflowed allocated space.");
 
   // restore
   BufferBegin = mpSavedBufferBegin;
@@ -1487,7 +1487,7 @@
   const std::vector<llvm::MachineJumpTableEntry> &JT =
       mpJumpTable->getJumpTables();
 
-  assert((Index < JT.size()) && "Invalid jump table index!");
+  bccAssert((Index < JT.size()) && "Invalid jump table index!");
 
   unsigned int Offset = 0;
   unsigned int EntrySize = mpJumpTable->getEntrySize(*mpTD);
@@ -1504,9 +1504,9 @@
 // the label for the MBB has been emitted.
 uintptr_t CodeEmitter::getMachineBasicBlockAddress(
                                         llvm::MachineBasicBlock *MBB) const {
-  assert(mMBBLocations.size() > (unsigned) MBB->getNumber() &&
-         mMBBLocations[MBB->getNumber()] &&
-         "MBB not emitted!");
+  bccAssert(mMBBLocations.size() > (unsigned) MBB->getNumber() &&
+            mMBBLocations[MBB->getNumber()] &&
+            "MBB not emitted!");
   return mMBBLocations[MBB->getNumber()];
 }
 
@@ -1522,8 +1522,8 @@
 
   void *Addr = GetPointerToGlobalIfAvailable(F);
 
-  assert(Addr != Stub &&
-         "Function must have non-stub address to be updated.");
+  bccAssert(Addr != Stub &&
+            "Function must have non-stub address to be updated.");
 
   // Tell the target jit info to rewrite the stub at the specified address,
   // rather than creating a new one.
diff --git a/lib/CodeGen/CodeEmitter.h b/lib/CodeGen/CodeEmitter.h
index c4e0d78..5210901 100644
--- a/lib/CodeGen/CodeEmitter.h
+++ b/lib/CodeGen/CodeEmitter.h
@@ -15,6 +15,7 @@
 #define BCC_CODEEMITTER_H
 
 #include <bcc/bcc.h>
+#include <bcc/bcc_assert.h>
 #include <bcc/bcc_cache.h>
 #include "bcc_internal.h"
 
@@ -23,6 +24,7 @@
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
+#include "llvm/CodeGen/MachineConstantPool.h"
 #include "llvm/CodeGen/MachineRelocation.h"
 #include "llvm/CodeGen/JITCodeEmitter.h"
 #include "llvm/Support/ValueHandle.h"
@@ -31,7 +33,6 @@
 #include <vector>
 #include <set>
 
-#include <assert.h>
 #include <stdint.h>
 
 namespace llvm {
@@ -41,7 +42,6 @@
   class GlobalValue;
   class Function;
   class MachineBasicBlock;
-  class MachineConstantPool;
   class MachineFunction;
   class MachineJumpTableInfo;
   class MachineModuleInfo;
@@ -221,8 +221,8 @@
     // Return the address of the @Index entry in the constant pool that was
     // last emitted with the emitConstantPool method.
     virtual uintptr_t getConstantPoolEntryAddress(unsigned Index) const {
-      assert(Index < mpConstantPool->getConstants().size() &&
-             "Invalid constant pool index!");
+      bccAssert(Index < mpConstantPool->getConstants().size() &&
+                "Invalid constant pool index!");
       return mConstPoolAddresses[Index];
     }
 
@@ -238,7 +238,7 @@
     // Return the address of the specified LabelID, only usable after the
     // LabelID has been emitted.
     virtual uintptr_t getLabelAddress(llvm::MCSymbol *Label) const {
-      assert(mLabelLocations.count(Label) && "Label not emitted!");
+      bccAssert(mLabelLocations.count(Label) && "Label not emitted!");
       return mLabelLocations.find(Label)->second;
     }
 
diff --git a/lib/CodeGen/CodeMemoryManager.cpp b/lib/CodeGen/CodeMemoryManager.cpp
index bf90b66..c48f7a7 100644
--- a/lib/CodeGen/CodeMemoryManager.cpp
+++ b/lib/CodeGen/CodeMemoryManager.cpp
@@ -12,6 +12,8 @@
 //===----------------------------------------------------------------------===//
 
 #define LOG_TAG "bcc"
+#include <bcc/bcc_assert.h>
+
 #include <cutils/log.h>
 
 #include "CodeMemoryManager.h"
@@ -21,7 +23,6 @@
 
 #include <sys/mman.h>
 
-#include <assert.h>
 #include <stddef.h>
 
 #include <map>
@@ -111,7 +112,7 @@
 // If the current table requires a Global Offset Table, this method is
 // invoked to allocate it.  This method is required to set HasGOT to true.
 void CodeMemoryManager::AllocateGOT() {
-  assert(mpGOTBase != NULL && "Cannot allocate the GOT multiple times");
+  bccAssert(mpGOTBase != NULL && "Cannot allocate the GOT multiple times");
   mpGOTBase = allocateSGMemory(MaxGOTSize);
   HasGOT = true;
 }
@@ -149,19 +150,19 @@
 void CodeMemoryManager::endFunctionBody(const llvm::Function *F,
                                         uint8_t *FunctionStart,
                                         uint8_t *FunctionEnd) {
-  assert(FunctionEnd > FunctionStart);
-  assert(FunctionStart == (getCodeMemBase() + mCurFuncMemIdx) &&
-         "Mismatched function start/end!");
+  bccAssert(FunctionEnd > FunctionStart);
+  bccAssert(FunctionStart == (getCodeMemBase() + mCurFuncMemIdx) &&
+            "Mismatched function start/end!");
 
   // Advance the pointer
   intptr_t FunctionCodeSize = FunctionEnd - FunctionStart;
-  assert(FunctionCodeSize <= getFreeCodeMemSize() &&
-         "Code size excess the limitation!");
+  bccAssert(FunctionCodeSize <= getFreeCodeMemSize() &&
+            "Code size excess the limitation!");
   mCurFuncMemIdx += FunctionCodeSize;
 
   // Record there's a function in our memory start from @FunctionStart
-  assert(mFunctionMap.find(F) == mFunctionMap.end() &&
-         "Function already emitted!");
+  bccAssert(mFunctionMap.find(F) == mFunctionMap.end() &&
+            "Function already emitted!");
   mFunctionMap.insert(
       std::make_pair<const llvm::Function*, std::pair<void*, void*> >(
           F, std::make_pair(FunctionStart, FunctionEnd)));
@@ -224,14 +225,14 @@
     }
   }
 
-  assert((FunctionStart == NULL) && "Memory is never allocated!");
+  bccAssert((FunctionStart == NULL) && "Memory is never allocated!");
 
   // free the memory
   intptr_t SizeNeedMove = (getCodeMemBase() + mCurFuncMemIdx) - FunctionEnd;
 
-  assert(SizeNeedMove >= 0 &&
-         "Internal error: CodeMemoryManager::mCurFuncMemIdx may not"
-         " be correctly calculated!");
+  bccAssert(SizeNeedMove >= 0 &&
+            "Internal error: CodeMemoryManager::mCurFuncMemIdx may not"
+            " be correctly calculated!");
 
   if (SizeNeedMove > 0) {
     // there's data behind deallocating function
diff --git a/lib/CodeGen/CodeMemoryManager.h b/lib/CodeGen/CodeMemoryManager.h
index 1ca0a06..833a351 100644
--- a/lib/CodeGen/CodeMemoryManager.h
+++ b/lib/CodeGen/CodeMemoryManager.h
@@ -18,10 +18,11 @@
 
 #include "llvm/ExecutionEngine/JITMemoryManager.h"
 
+#include <bcc/bcc_assert.h>
+
 #include <map>
 #include <utility>
 
-#include <assert.h>
 #include <stddef.h>
 #include <stdint.h>
 
@@ -197,14 +198,16 @@
     // emit the exception table.
     virtual uint8_t *startExceptionTable(const llvm::Function *F,
                                          uintptr_t &ActualSize) {
-      assert(false && "Exception is not allowed in our language specification");
+      bccAssert(false &&
+                "Exception is not allowed in our language specification");
       return NULL;
     }
 
     // This method is called when the JIT is done emitting the exception table.
     virtual void endExceptionTable(const llvm::Function *F, uint8_t *TableStart,
                                    uint8_t *TableEnd, uint8_t *FrameRegister) {
-      assert(false && "Exception is not allowed in our language specification");
+      bccAssert(false &&
+                "Exception is not allowed in our language specification");
     }
 
     // Free the specified exception table's memory. The argument must be the
@@ -212,7 +215,8 @@
     // deallocated yet. This is never called when the JIT is currently emitting
     // an exception table.
     virtual void deallocateExceptionTable(void *ET) {
-      assert(false && "Exception is not allowed in our language specification");
+      bccAssert(false &&
+                "Exception is not allowed in our language specification");
     }
 
     // Below are the methods we create
diff --git a/lib/ExecutionEngine/Compiler.cpp b/lib/ExecutionEngine/Compiler.cpp
index b1bd093..4eaf87d 100644
--- a/lib/ExecutionEngine/Compiler.cpp
+++ b/lib/ExecutionEngine/Compiler.cpp
@@ -521,8 +521,8 @@
       varList.push_back(NULL);
     }
 
-    assert((varList.size() == ExportVarMetadata->getNumOperands()) &&
-           "Number of slots doesn't match the number of export variables!");
+    bccAssert((varList.size() == ExportVarMetadata->getNumOperands()) &&
+              "Number of slots doesn't match the number of export variables!");
   }
 
   if (ExportFuncMetadata) {
diff --git a/lib/ExecutionEngine/Runtime.c b/lib/ExecutionEngine/Runtime.c
index e814361..f940c35 100644
--- a/lib/ExecutionEngine/Runtime.c
+++ b/lib/ExecutionEngine/Runtime.c
@@ -16,9 +16,11 @@
 
 #include "RuntimeStub.h"
 
+#include <bcc/bcc_assert.h>
+
+#include <stdbool.h>
 #include <string.h>
 #include <stdlib.h>
-#include <assert.h>
 
 typedef struct {
   const char *mName;
@@ -79,7 +81,7 @@
     int *Ptr = FindRuntimeFunction(Name);
 
     if (Ptr != (int*) gRuntimes[i].mPtr)
-      assert(false && "Table is corrupted (runtime name should be sorted in "
-                      "Runtime.def).");
+      bccAssert(false && "Table is corrupted (runtime name should be sorted "
+                         "in Runtime.def).");
   }
 }
diff --git a/runtime/BlocksRuntime/runtime.c b/runtime/BlocksRuntime/runtime.c
index 175357b..4527655 100644
--- a/runtime/BlocksRuntime/runtime.c
+++ b/runtime/BlocksRuntime/runtime.c
@@ -490,7 +490,7 @@
     if (!arg) return;
     aBlock = (struct Block_layout *)arg;
     if (aBlock->flags & BLOCK_IS_GC) {
-        // assert(aBlock->Block_flags & BLOCK_HAS_CTOR);
+        // bccAssert(aBlock->Block_flags & BLOCK_HAS_CTOR);
         return; // ignore, we are being called because of a DTOR
     }
     _Block_release(aBlock);