[llvm-commits] [poolalloc] r133643 - in /poolalloc/trunk: include/assistDS/TypeChecks.h lib/AssistDS/TypeChecks.cpp lib/AssistDS/TypeChecksOpt.cpp runtime/DynamicTypeChecks/Makefile runtime/DynamicTypeChecks/TypeRuntime.c runtime/DynamicTypeChecks/TypeRuntime.cpp

Arushi Aggarwal aggarwa4 at illinois.edu
Wed Jun 22 13:57:15 PDT 2011


Author: aggarwa4
Date: Wed Jun 22 15:57:15 2011
New Revision: 133643

URL: http://llvm.org/viewvc/llvm-project?rev=133643&view=rev
Log:
Modify handling of va lists. Store the metadata(total
arguments, metadata for each, and number read) in 
a map in memory, instead of in SSA values. This makes
the handling much easier.

Also clean up a lot of dead code, caused by this and the
previous changes.


Added:
    poolalloc/trunk/runtime/DynamicTypeChecks/TypeRuntime.cpp
Removed:
    poolalloc/trunk/runtime/DynamicTypeChecks/TypeRuntime.c
Modified:
    poolalloc/trunk/include/assistDS/TypeChecks.h
    poolalloc/trunk/lib/AssistDS/TypeChecks.cpp
    poolalloc/trunk/lib/AssistDS/TypeChecksOpt.cpp
    poolalloc/trunk/runtime/DynamicTypeChecks/Makefile

Modified: poolalloc/trunk/include/assistDS/TypeChecks.h
URL: http://llvm.org/viewvc/llvm-project/poolalloc/trunk/include/assistDS/TypeChecks.h?rev=133643&r1=133642&r2=133643&view=diff
==============================================================================
--- poolalloc/trunk/include/assistDS/TypeChecks.h (original)
+++ poolalloc/trunk/include/assistDS/TypeChecks.h Wed Jun 22 15:57:15 2011
@@ -34,15 +34,11 @@
 class TypeChecks : public ModulePass {
 private:
   std::map<const Type *, unsigned int> UsedTypes;
-  std::map<Function *, Function *> VAListFunctionsMap;
   std::map<Function *, Function *> IndFunctionsMap;
   std::list<Function *> VAArgFunctions;
-  std::list<Function *> VAListFunctions;
   std::list<Function *> ByValFunctions;
   std::list<Function *> AddressTakenFunctions;
   std::set<Instruction*> IndCalls;
-  // Map of VAList to current count
-  std::map<Value*, Value*> CounterMap;
 
   // Analysis from other passes.
   TargetData *TD;
@@ -68,6 +64,7 @@
   bool visitLoadInst(Module &M, LoadInst &LI);
   bool visitStoreInst(Module &M, StoreInst &SI);
   bool visitAllocaInst(Module &M, AllocaInst &AI);
+  bool visitVAArgInst(Module &M, VAArgInst &VI);
 
   bool visitGlobal(Module &M, GlobalVariable &GV, 
                    Constant *C, Instruction &I, SmallVector<Value*,8>);
@@ -80,8 +77,6 @@
 
 
   bool visitVarArgFunction(Module &M, Function &F); 
-  bool visitVAListFunction(Module &M, Function &F); 
-  void visitVAListCall(Function *F);
   bool visitInternalVarArgFunction(Module &M, Function &F); 
 
   bool visitInputFunctionValue(Module &M, Value *V, Instruction *CI);

Modified: poolalloc/trunk/lib/AssistDS/TypeChecks.cpp
URL: http://llvm.org/viewvc/llvm-project/poolalloc/trunk/lib/AssistDS/TypeChecks.cpp?rev=133643&r1=133642&r2=133643&view=diff
==============================================================================
--- poolalloc/trunk/lib/AssistDS/TypeChecks.cpp (original)
+++ poolalloc/trunk/lib/AssistDS/TypeChecks.cpp Wed Jun 22 15:57:15 2011
@@ -60,19 +60,28 @@
 static const Type *Int32Ty = 0;
 static const Type *Int64Ty = 0;
 static const PointerType *VoidPtrTy = 0;
+static Constant *One = 0;
+static Constant *Zero = 0;
+static Constant *RegisterArgv;
+static Constant *RegisterEnvp;
+
 static Constant *trackGlobal;
+static Constant *trackStoreInst;
 static Constant *trackStringInput;
 static Constant *trackArray;
+
 static Constant *trackInitInst;
 static Constant *trackUnInitInst;
-static Constant *trackStoreInst;
+
+static Constant *getTypeTag;
 static Constant *checkTypeInst;
+
 static Constant *copyTypeInfo;
 static Constant *setTypeInfo;
-static Constant *RegisterArgv;
-static Constant *RegisterEnvp;
-static Constant *compareTypeAndNumber;
-static Constant *getTypeTag;
+
+static Constant *setVAInfo;
+static Constant *copyVAInfo;
+static Constant *checkVAArg;
 
 unsigned int TypeChecks::getTypeMarker(const Type * Ty) {
   if(DisablePointerTypeChecks) {
@@ -122,6 +131,8 @@
   Int32Ty = IntegerType::getInt32Ty(M.getContext());
   Int64Ty = IntegerType::getInt64Ty(M.getContext());
   VoidPtrTy = PointerType::getUnqual(Int8Ty);
+  One = ConstantInt::get(Int64Ty, 1);
+  Zero = ConstantInt::get(Int64Ty, 0);
 
   RegisterArgv = M.getOrInsertFunction("trackArgvType",
                                        VoidTy,
@@ -193,22 +204,33 @@
                                        Int64Ty,/*size*/
                                        Int32Ty,/*tag*/
                                        NULL);
-  compareTypeAndNumber = M.getOrInsertFunction("compareTypeAndNumber",
-                                               VoidTy,
-                                               Int64Ty,/*Total Args*/
-                                               Int64Ty,/*Arg accessed*/
-                                               Int8Ty,/*type*/
-                                               VoidPtrTy,/*metadata ptr*/
-                                               Int32Ty,/*tag*/
-                                               NULL);
   trackStringInput = M.getOrInsertFunction("trackStringInput",
                                            VoidTy,
                                            VoidPtrTy,
                                            Int32Ty,
                                            NULL);
+  setVAInfo = M.getOrInsertFunction("setVAInfo",
+                                    VoidTy,
+                                    VoidPtrTy,/*va_list ptr*/
+                                    Int64Ty,/*total num of elements in va_list */
+                                    VoidPtrTy,/*ptr to metadta*/
+                                    Int32Ty,/*tag*/
+                                    NULL);
+  copyVAInfo = M.getOrInsertFunction("copyVAInfo",
+                                     VoidTy,
+                                     VoidPtrTy,/*dst va_list*/
+                                     VoidPtrTy,/*src va_list */
+                                     Int32Ty,/*tag*/
+                                     NULL);
+  checkVAArg = M.getOrInsertFunction("checkVAArgType",
+                                     VoidTy,
+                                     VoidPtrTy,/*va_list ptr*/
+                                     Int8Ty,/*type*/
+                                     Int32Ty,/*tag*/
+                                     NULL);
+
 
   UsedTypes.clear(); // Reset if run multiple times.
-  VAListFunctions.clear();
   VAArgFunctions.clear();
   ByValFunctions.clear();
   AddressTakenFunctions.clear();
@@ -258,23 +280,6 @@
       VAArgFunctions.push_back(&F);
       continue;
     }
-    // Iterate and find all VAList functions
-    bool isVAListFunc = false;
-    const Type *ListType  = M.getTypeByName("struct.__va_list_tag");
-    if(!ListType)
-      continue;
-
-    const Type *ListPtrType = ListType->getPointerTo();
-    for (Function::arg_iterator I = F.arg_begin(); I != F.arg_end(); ++I) {
-      if(I->getType() == ListPtrType) {
-        isVAListFunc = true;
-        break;
-      }
-    }
-    if(isVAListFunc) {
-      VAListFunctions.push_back(&F);
-      continue;
-    }
   }
 
   // Modify all byval functions
@@ -285,21 +290,6 @@
   }
 
 
-  // NOTE:must visit before VAArgFunctions, to populate the map with the
-  // correct cloned functions.
-  while(!VAListFunctions.empty()) {
-    Function *F = VAListFunctions.back();
-    VAListFunctions.pop_back();
-    modified |= visitVAListFunction(M, *F);
-  }
-
-  // iterate through all the VAList funtions and modify call sites
-  // to call the new function 
-  std::map<Function *, Function *>::iterator FI = VAListFunctionsMap.begin(), 
-    FE = VAListFunctionsMap.end();
-  for(; FI != FE; FI++) {
-    visitVAListCall(FI->second);
-  }
   while(!VAArgFunctions.empty()) {
     Function *F = VAArgFunctions.back();
     VAArgFunctions.pop_back();
@@ -335,6 +325,8 @@
         modified |= visitInvokeInst(M, *II);
       } else if (AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
         modified |= visitAllocaInst(M, *AI);
+      } else if (VAArgInst *VI = dyn_cast<VAArgInst>(&I)) {
+        modified |= visitVAArgInst(M, *VI);
       }
     }
   }
@@ -347,7 +339,7 @@
     modified |= visitIndirectCallSite(M,I);
   }
 
-  FI = IndFunctionsMap.begin(), FE = IndFunctionsMap.end();
+  std::map<Function *, Function * >::iterator FI = IndFunctionsMap.begin(), FE = IndFunctionsMap.end();
   for(;FI!=FE;++FI) {
     Function *F = FI->first;
 
@@ -475,211 +467,6 @@
                     );
 }
 
-void TypeChecks::visitVAListCall(Function *F) {
-  for (Function::iterator B = F->begin(), FE = F->end(); B != FE; ++B) {
-    for (BasicBlock::iterator I = B->begin(), BE = B->end(); I != BE;) {
-      CallInst *CI = dyn_cast<CallInst>(I++);
-      if(!CI)
-        continue;
-      Function *CalledF = dyn_cast<Function>(CI->getCalledFunction());
-      if(VAListFunctionsMap.find(CalledF) == VAListFunctionsMap.end())
-        continue;
-      const Type *ListType  = F->getParent()->getTypeByName("struct.__va_list_tag");
-      const Type *ListPtrType = ListType->getPointerTo();
-      unsigned VAListArgNum = 0;
-      for (Function::arg_iterator I = CalledF->arg_begin(); 
-           I != CalledF->arg_end(); ++I) {
-        VAListArgNum ++;
-        if(I->getType() == ListPtrType) {
-          break;
-        }
-      }
-
-      if(CounterMap.find(CI->getOperand(VAListArgNum)->stripPointerCasts()) == CounterMap.end()) {
-        // If this is a va_list we do not know about,
-        // do not insert checks.
-
-        // FIXME: Handle cases where va_list is stored in memory
-         continue;
-      }
-      Function::arg_iterator NII = F->arg_begin();
-      std::vector<Value *>Args;
-      Args.push_back(NII++); // total count
-      Value *CounterSrc = CounterMap[CI->getOperand(VAListArgNum)->stripPointerCasts()];
-      LoadInst *CountValue = new LoadInst(CounterSrc, "count", CI);
-      Args.push_back(CountValue); // current count
-      NII++;
-      Args.push_back(NII); // MD
-      for(unsigned i = 1 ;i < CI->getNumOperands(); i++) {
-        // Add the original argument
-        Args.push_back(CI->getOperand(i));
-      }
-      CallInst *CINew = CallInst::Create(VAListFunctionsMap[CalledF], 
-                                         Args.begin(), 
-                                         Args.end(),
-                                         "", CI);
-      CI->replaceAllUsesWith(CINew);
-      CI->eraseFromParent();
-    }
-  }
-}
-
-bool TypeChecks::visitVAListFunction(Module &M, Function &F_orig) {
-  if(!F_orig.hasInternalLinkage())
-    return false;
-
-  int VAListArgNum = 0;
-  // Check if one of the arguments is a va_list
-  const Type *ListType  = M.getTypeByName("struct.__va_list_tag");
-  if(!ListType)
-    return false;
-  const Type *ListPtrType = ListType->getPointerTo();
-  Argument *VAListArg = NULL; 
-  for (Function::arg_iterator I = F_orig.arg_begin(); 
-       I != F_orig.arg_end(); ++I) {
-    VAListArgNum ++;
-    if(I->getType() == ListPtrType) {
-      VAListArg = I;
-      break;
-    }
-  }
-
-  // Clone the function to add arguments for count, MD
-
-  // 1. Create the new argument types vector
-  std::vector<const Type*>TP;
-  TP.push_back(Int64Ty); // for count
-  TP.push_back(Int64Ty); // for count
-  TP.push_back(VoidPtrTy); // for MD
-  for (Function::arg_iterator I = F_orig.arg_begin();
-       I != F_orig.arg_end(); ++I) {
-    TP.push_back(I->getType());
-  }
-  // 2. Create the new function prototype
-  const FunctionType *NewFTy = FunctionType::get(F_orig.getReturnType(),
-                                                 TP,/*argument types*/
-                                                 false);/*vararg*/
-  Function *F = Function::Create(NewFTy,
-                                 GlobalValue::InternalLinkage,
-                                 F_orig.getNameStr() + ".INT",
-                                 &M);
-
-  // 3. Set the mapping for args
-  Function::arg_iterator NI = F->arg_begin();
-  DenseMap<const Value*, Value*> ValueMap;
-  NI->setName("TotalCount");
-  NI++;
-  NI->setName("CurrentCount");
-  NI++;
-  NI->setName("MD");
-  NI++;
-  for (Function::arg_iterator II = F_orig.arg_begin(); 
-       NI != F->arg_end(); ++II, ++NI) {
-    // Each new argument maps to the argument in the old function
-    // For these arguments, also copy over the attributes
-    ValueMap[II] = NI;
-    NI->setName(II->getName());
-    NI->addAttr(F_orig.getAttributes()
-                .getParamAttributes(II->getArgNo() + 1));
-  }
-
-  // 4. Copy over the attributes for the function.
-  F->setAttributes(F->getAttributes()
-                   .addAttr(0, F_orig.getAttributes().getRetAttributes()));
-  F->setAttributes(F->getAttributes()
-                   .addAttr(~0, F_orig.getAttributes().getFnAttributes()));
-
-  // 5. Perform the cloning.
-  SmallVector<ReturnInst*,100> Returns;
-  CloneFunctionInto(F, &F_orig, ValueMap, Returns);
-
-  VAListFunctionsMap[&F_orig] =  F;
-  inst_iterator InsPt = inst_begin(F);
-
-
-  // Store the information
-  Function::arg_iterator NII = F->arg_begin();
-  AllocaInst *VASizeLoc = new AllocaInst(Int64Ty, "", &*InsPt);
-  new StoreInst(NII, VASizeLoc, &*InsPt);
-  NII++;
-  AllocaInst *Counter = new AllocaInst(Int64Ty, "",&*InsPt);
-  new StoreInst(NII, Counter, &*InsPt); 
-  errs() << F->getNameStr() <<"\n";
-  NII++;
-  AllocaInst *VAMDLoc = new AllocaInst(VoidPtrTy, "", &*InsPt);
-  new StoreInst(NII, VAMDLoc, &*InsPt);
-
-  CounterMap[ValueMap[VAListArg]] = Counter;
-  // Find all va_copy calls
-  for (Function::iterator B = F->begin(), FE = F->end(); B != FE; ++B) {
-    for (BasicBlock::iterator I = B->begin(), BE = B->end(); I != BE;I++) {
-      CallInst *CI = dyn_cast<CallInst>(I);
-      if(!CI)
-        continue;
-      Function *CalledF = dyn_cast<Function>(CI->getCalledFunction());
-      if(!CalledF)
-        continue;
-      if(!CalledF->isIntrinsic())
-        continue;
-      if(CalledF->getIntrinsicID() != Intrinsic::vacopy) 
-        continue;
-      if(CounterMap.find(CI->getOperand(2)->stripPointerCasts()) == CounterMap.end()) {
-        // If this is a va_list we do not know about,
-        // do not insert checks.
-
-        // FIXME: Handle cases where va_list is stored in memory
-         continue;
-      }
-      // Reinitialize the counter
-      AllocaInst *CounterDest = new AllocaInst(Int64Ty, "",&*InsPt);
-      Value *CounterSource = CounterMap[CI->getOperand(2)->stripPointerCasts()];
-      LoadInst *CurrentValue = new LoadInst(CounterSource, "count", CI);
-      new StoreInst(CurrentValue, CounterDest, CI);
-      CounterMap[CI->getOperand(1)->stripPointerCasts()] = CounterDest;
-    }
-  }
-
-
-  // instrument va_arg to increment the counter
-  for (Function::iterator B = F->begin(), FE = F->end(); B != FE; ++B) {
-    for (BasicBlock::iterator I = B->begin(), BE = B->end(); I != BE;) {
-      VAArgInst *VI = dyn_cast<VAArgInst>(I++);
-      if(!VI)
-        continue;
-      if(CounterMap.find(VI->getOperand(0)->stripPointerCasts()) == CounterMap.end()) {
-        // If this is a va_list we do not know about,
-        // do not insert checks.
-
-        // FIXME: Handle cases where va_list is stored in memory
-         continue;
-      }
-      Constant *One = ConstantInt::get(Int64Ty, 1);
-      Value *CounterSrc = CounterMap[VI->getOperand(0)->stripPointerCasts()];
-      LoadInst *OldValue = new LoadInst(CounterSrc, "count", VI);
-      Instruction *NewValue = BinaryOperator::Create(BinaryOperator::Add,
-                                                     OldValue,
-                                                     One,
-                                                     "count",
-                                                     VI);
-      new StoreInst(NewValue, CounterSrc, VI);
-      std::vector<Value *> Args;
-      Instruction *VASize = new LoadInst(VASizeLoc, "", VI);
-      Instruction *VAMetaData = new LoadInst(VAMDLoc, "", VI);
-      Args.push_back(VASize);
-      Args.push_back(OldValue);
-      Args.push_back(getTypeMarkerConstant(VI));
-      Args.push_back(VAMetaData);
-      Args.push_back(getTagCounter());
-      CallInst::Create(compareTypeAndNumber,
-                       Args.begin(),
-                       Args.end(),
-                       "", VI);
-    }
-  }
-
-  return true;
-}
-
 bool TypeChecks::visitAddressTakenFunction(Module &M, Function &F) {
   // Clone function
   // 1. Create the new argument types vector
@@ -823,13 +610,13 @@
                                                  true);
   Function *NewF = Function::Create(NewFTy,
                                     GlobalValue::InternalLinkage,
-                                    F.getNameStr() + ".mod",
+                                    F.getNameStr() + ".vararg",
                                     &M);
 
   // 3. Set the mapping for the args
   Function::arg_iterator NI = NewF->arg_begin();
   DenseMap<const Value *, Value*> ValueMap;
-  NI->setName("TotalCount");
+  NI->setName("TotalArgCount");
   NI++;
   NI->setName("MD");
   NI++;
@@ -856,7 +643,6 @@
   // Store the information
   inst_iterator InsPt = inst_begin(NewF);
   Function::arg_iterator NII = NewF->arg_begin();
-  AllocaInst *VASizeLoc = new AllocaInst(Int64Ty, "", &*InsPt);
   // Subtract the number of initial arguments
   Constant *InitialArgs = ConstantInt::get(Int64Ty, F.arg_size());
   Instruction *NewValue = BinaryOperator::Create(BinaryOperator::Sub,
@@ -864,10 +650,8 @@
                                                  InitialArgs,
                                                  "varargs",
                                                  &*InsPt);
-  new StoreInst(NewValue, VASizeLoc, &*InsPt);
   NII++;
 
-  AllocaInst *VAMDLoc = new AllocaInst(VoidPtrTy, "", &*InsPt);
   // Increment by the number of Initial Args, so as to not read the metadata
   //for those.
   Value *Idx[2];
@@ -877,12 +661,6 @@
                                                              Idx, 
                                                              Idx + 1, 
                                                              "", &*InsPt);
-  new StoreInst(GEP, VAMDLoc, &*InsPt);
-  // Add a counter variable to the function entry
-  AllocaInst *Counter = new AllocaInst(Int64Ty, "",&*InsPt);
-  new StoreInst(ConstantInt::get(Int64Ty, 0), Counter, &*InsPt); 
-
-
   // visit all VAStarts and initialize the counter
   for (Function::iterator B = NewF->begin(), FE = NewF->end(); B != FE; ++B) {
     for (BasicBlock::iterator I = B->begin(), BE = B->end(); I != BE;I++) {
@@ -897,9 +675,13 @@
       if(CalledF->getIntrinsicID() != Intrinsic::vastart) 
         continue;
       // Reinitialize the counter
-      StoreInst *SI3 = new StoreInst(ConstantInt::get(Int64Ty, 0), Counter);
-      SI3->insertAfter(CI);
-      CounterMap[CI->getOperand(1)->stripPointerCasts()] = Counter;
+      CastInst *BCI = BitCastInst::CreatePointerCast(CI->getOperand(1), VoidPtrTy, "", CI);
+      std::vector<Value *> Args;
+      Args.push_back(BCI);
+      Args.push_back(NewValue);
+      Args.push_back(GEP);
+      Args.push_back(getTagCounter());
+      CallInst::Create(setVAInfo, Args.begin(), Args.end(), "", CI);
     }
   }
 
@@ -916,93 +698,13 @@
         continue;
       if(CalledF->getIntrinsicID() != Intrinsic::vacopy) 
         continue;
-      // Reinitialize the counter
-      AllocaInst *CounterDest = new AllocaInst(Int64Ty, "",&*InsPt);
-      Value *CounterSource = CounterMap[CI->getOperand(2)->stripPointerCasts()];
-      LoadInst *CurrentValue = new LoadInst(CounterSource, "count", CI);
-      new StoreInst(CurrentValue, CounterDest, CI);
-      CounterMap[CI->getOperand(1)->stripPointerCasts()] = CounterDest;
-    }
-  }
-
-  // Modify function to add checks on every var_arg call to ensure that we
-  // are not accessing more arguments than we passed in.
-
-  // Increment the counter
-  for (Function::iterator B = NewF->begin(), FE = NewF->end(); B != FE; ++B) {
-    for (BasicBlock::iterator I = B->begin(), BE = B->end(); I != BE;) {
-      VAArgInst *VI = dyn_cast<VAArgInst>(I++);
-      if(!VI)
-        continue;
-      if(CounterMap.find(VI->getOperand(0)->stripPointerCasts()) == CounterMap.end()) {
-        // If this is a va_list we do not know about,
-        // do not insert checks.
-
-        // FIXME: Handle cases where va_list is stored in memory
-         continue;
-      }
-      Constant *One = ConstantInt::get(Int64Ty, 1);
-      Value *CounterSrc = CounterMap[VI->getOperand(0)->stripPointerCasts()];
-      LoadInst *OldValue = new LoadInst(CounterSrc, "count", VI);
-      Instruction *NewValue = BinaryOperator::Create(BinaryOperator::Add,
-                                                     OldValue,
-                                                     One,
-                                                     "count",
-                                                     VI);
-      new StoreInst(NewValue, CounterSrc, VI);
+      CastInst *BCI_Src = BitCastInst::CreatePointerCast(CI->getOperand(2), VoidPtrTy, "", CI);
+      CastInst *BCI_Dest = BitCastInst::CreatePointerCast(CI->getOperand(1), VoidPtrTy, "", CI);
       std::vector<Value *> Args;
-      Instruction *VASize = new LoadInst(VASizeLoc, "", VI);
-      Instruction *VAMetaData = new LoadInst(VAMDLoc, "", VI);
-      Args.push_back(VASize);
-      Args.push_back(OldValue);
-      Args.push_back(getTypeMarkerConstant(VI));
-      Args.push_back(VAMetaData);
+      Args.push_back(BCI_Dest);
+      Args.push_back(BCI_Src);
       Args.push_back(getTagCounter());
-      CallInst::Create(compareTypeAndNumber,
-                       Args.begin(),
-                       Args.end(),
-                       "", VI);
-    }
-  }
-
-
-  // modify calls to va list functions to pass the metadata
-  for (Function::iterator B = NewF->begin(), FE = NewF->end(); B != FE; ++B) {
-    for (BasicBlock::iterator I = B->begin(), BE = B->end(); I != BE;) {
-      CallInst *CI = dyn_cast<CallInst>(I++);
-      if(!CI)
-        continue;
-      Function *CalledF = dyn_cast<Function>(CI->getCalledFunction());
-
-      if(VAListFunctionsMap.find(CalledF) == VAListFunctionsMap.end())
-        continue;
-      const Type *ListType  = M.getTypeByName("struct.__va_list_tag");
-      const Type *ListPtrType = ListType->getPointerTo();
-      unsigned VAListArgNum = 0;
-      for (Function::arg_iterator I = CalledF->arg_begin(); 
-           I != CalledF->arg_end(); ++I) {
-        VAListArgNum ++;
-        if(I->getType() == ListPtrType) {
-          break;
-        }
-      }
-      std::vector<Value *>Args;
-
-      Value *CounterSrc = CounterMap[CI->getOperand(VAListArgNum)->stripPointerCasts()];
-      Instruction *VASize = new LoadInst(VASizeLoc, "", CI);
-      Instruction *VACounter = new LoadInst(CounterSrc, "", CI);
-      Instruction *VAMetaData = new LoadInst(VAMDLoc, "", CI);
-      Args.push_back(VASize); // toatl count
-      Args.push_back(VACounter); // current count
-      Args.push_back(VAMetaData); // MD
-      for(unsigned i = 1 ;i < CI->getNumOperands(); i++) {
-        // Add the original argument
-        Args.push_back(CI->getOperand(i));
-      }
-      CallInst *CINew = CallInst::Create(VAListFunctionsMap[CalledF], 
-                                         Args.begin(), Args.end(), "", CI);
-      CI->replaceAllUsesWith(CINew);
-      CI->eraseFromParent();
+      CallInst::Create(copyVAInfo, Args.begin(), Args.end(), "", CI);
     }
   }
 
@@ -1357,7 +1059,7 @@
     if(!I->hasInitializer())
       continue;
     SmallVector<Value*,8>index;
-    index.push_back(ConstantInt::get(Int64Ty, 0));
+    index.push_back(Zero);
     visitGlobal(M, *I, I->getInitializer(), *InsertPt, index);
   }
   //
@@ -1538,6 +1240,17 @@
   }
   return true;
 }
+bool TypeChecks::visitVAArgInst(Module &M, VAArgInst &VI) {
+  if(!VI.getParent()->getParent()->hasInternalLinkage())
+    return false;
+  CastInst *BCI = BitCastInst::CreatePointerCast(VI.getOperand(0), VoidPtrTy, "", &VI);
+  std::vector<Value *>Args;
+  Args.push_back(BCI);
+  Args.push_back(getTypeMarkerConstant(&VI));
+  Args.push_back(getTagCounter());
+  CallInst::Create(checkVAArg, Args.begin(), Args.end(), "", &VI);
+  return false;
+}
 
 // Insert code to initialize meta data to bottom
 // Insert code to set objects to 0
@@ -1880,7 +1593,6 @@
       Args.push_back(BCI);
       CastInst *Size = CastInst::CreateIntegerCast(I, Int64Ty, false);
       Size->insertAfter(I);
-      Constant *One = ConstantInt::get(Int64Ty, 1);
       Instruction *NewValue = BinaryOperator::Create(BinaryOperator::Add,
                                                      Size,
                                                      One);
@@ -2112,4 +1824,3 @@
 
   return true;
 }
-

Modified: poolalloc/trunk/lib/AssistDS/TypeChecksOpt.cpp
URL: http://llvm.org/viewvc/llvm-project/poolalloc/trunk/lib/AssistDS/TypeChecksOpt.cpp?rev=133643&r1=133642&r2=133643&view=diff
==============================================================================
--- poolalloc/trunk/lib/AssistDS/TypeChecksOpt.cpp (original)
+++ poolalloc/trunk/lib/AssistDS/TypeChecksOpt.cpp Wed Jun 22 15:57:15 2011
@@ -43,7 +43,6 @@
 static const PointerType *VoidPtrTy = 0;
 static Constant *trackGlobal;
 static Constant *trackStringInput;
-static Constant *trackArray;
 static Constant *trackInitInst;
 static Constant *trackUnInitInst;
 static Constant *trackStoreInst;
@@ -51,7 +50,6 @@
 static Constant *setTypeInfo;
 static Constant *checkTypeInst;
 static Constant *MallocFunc;
-static Constant *getTypeTag;
 
 bool TypeChecksOpt::runOnModule(Module &M) {
   TS = &getAnalysis<dsa::TypeSafety<TDDataStructures> >();
@@ -63,12 +61,6 @@
   Int64Ty = IntegerType::getInt64Ty(M.getContext());
   VoidPtrTy = PointerType::getUnqual(Int8Ty);
 
-  getTypeTag = M.getOrInsertFunction("getTypeTag",
-                                     VoidTy,
-                                     VoidPtrTy, /*ptr*/
-                                     Int64Ty, /*size*/
-                                     VoidPtrTy, /*dest for type tag*/
-                                     NULL);
   trackGlobal = M.getOrInsertFunction("trackGlobal",
                                       VoidTy,
                                       VoidPtrTy,/*ptr*/
@@ -76,13 +68,6 @@
                                       Int64Ty,/*size*/
                                       Int32Ty,/*tag*/
                                       NULL);
-  trackArray = M.getOrInsertFunction("trackArray",
-                                     VoidTy,
-                                     VoidPtrTy,/*ptr*/
-                                     Int64Ty,/*size*/
-                                     Int64Ty,/*count*/
-                                     Int32Ty,/*tag*/
-                                     NULL);
   trackInitInst = M.getOrInsertFunction("trackInitInst",
                                         VoidTy,
                                         VoidPtrTy,/*ptr*/

Modified: poolalloc/trunk/runtime/DynamicTypeChecks/Makefile
URL: http://llvm.org/viewvc/llvm-project/poolalloc/trunk/runtime/DynamicTypeChecks/Makefile?rev=133643&r1=133642&r2=133643&view=diff
==============================================================================
--- poolalloc/trunk/runtime/DynamicTypeChecks/Makefile (original)
+++ poolalloc/trunk/runtime/DynamicTypeChecks/Makefile Wed Jun 22 15:57:15 2011
@@ -8,6 +8,10 @@
 endif
 endif
 
+ifdef ENABLE_OPTIMIZED
+CXXFLAGS += -DNDEBUG=1
+endif
+
 include $(LEVEL)/Makefile.common
 
 # Always build optimized and debug versions

Removed: poolalloc/trunk/runtime/DynamicTypeChecks/TypeRuntime.c
URL: http://llvm.org/viewvc/llvm-project/poolalloc/trunk/runtime/DynamicTypeChecks/TypeRuntime.c?rev=133642&view=auto
==============================================================================
--- poolalloc/trunk/runtime/DynamicTypeChecks/TypeRuntime.c (original)
+++ poolalloc/trunk/runtime/DynamicTypeChecks/TypeRuntime.c (removed)
@@ -1,303 +0,0 @@
-#include <assert.h>
-#include <inttypes.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <netdb.h>
-#include <poll.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <sys/mman.h>
-
-#define DEBUG (0)
-
-/* Size of shadow memory.  We're hoping everything fits in 46bits. */
-#define SIZE ((size_t)(1L << 46))
-
-/* Fixed start of memory.  Needs to be page-aligned,
- * and it needs to be large enough that program itself is loaded below it
- * and so are the libraries. 
- * FIXME: This address has been picked for maute. Might not work on other
- * machines. Need a more robust way of picking base address.
- * For now, run a version of the tool without the base fixed, and 
- * choose address.
- #define BASE ((void *)(0x2aaaab2a5000))
- */
-#define BASE ((void *)(0x2aaaab88c000))
-/*
- * Do some macro magic to get mmap macros defined properly on all platforms.
- */
-#if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
-# define MAP_ANONYMOUS MAP_ANON
-#endif /* defined(MAP_ANON) && !defined(MAP_ANONYMOUS) */
-
-uint8_t * const shadow_begin = BASE;
-
-extern char* typeNames[];
-
-void trackInitInst(void *ptr, uint64_t size, uint32_t tag);
-
-inline uintptr_t maskAddress(void *ptr) {
-  uintptr_t p = (uintptr_t)ptr;
-  if (p >= (uintptr_t)BASE + SIZE) p -= SIZE;
-
-#if DEBUG
-  assert(p <= SIZE && "Pointer out of range!");
-#endif
-  return p;
-}
-
-
-void trackStringInput(void *ptr, uint32_t tag) {
-  trackInitInst(ptr, strlen(ptr) + 1, tag);
-}
-
-
-/**
- * Initialize the shadow memory which records the 1:1 mapping of addresses to types.
- */
-void shadowInit() {
-  char * res = mmap(BASE, SIZE, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
-
-  if (res == MAP_FAILED) {
-    fprintf(stderr, "Failed to map the shadow memory!\n");
-    fflush(stderr);
-    assert(0 && "MAP_FAILED");
-  }
-}
-
-/**
- * Copy arguments into a new array, and initialize
- * metadata for that location to TOP/initialized.
- */
-void trackArgvType(int argc, char **argv) {
-  int index = 0;
-  for (; index < argc; ++index) {
-    trackInitInst(argv[index], (strlen(argv[index]) + 1)*sizeof(char), 0);
-  }
-  trackInitInst(argv, (argc + 1)*sizeof(char*), 0);
-}
-
-void trackEnvpType(char **envp) {
-  int index = 0;
-  for(;envp[index] != NULL; ++index)
-    trackInitInst(envp[index], (strlen(envp[index]) + 1)*sizeof(char), 0);
-  trackInitInst(envp, (index )*sizeof(char*), 0);
-}
-
-/**
- * Record the global type and address in the shadow memory.
- */
-void trackGlobal(void *ptr, uint8_t typeNumber, uint64_t size, uint32_t tag) {
-  uintptr_t p = maskAddress(ptr);
-  shadow_begin[p] = typeNumber;
-  memset(&shadow_begin[p + 1], 0, size - 1);
-#if DEBUG
-  printf("Global(%d): %p, %p = %u | %lu bytes\n", tag, ptr, (void *)p, typeNumber, size);
-#endif
-}
-
-/**
- * Record the type stored at ptr(of size size) and replicate it
- */
-void trackArray(void *ptr, uint64_t size, uint64_t count, uint32_t tag) {
-  uintptr_t p = maskAddress(ptr);
-  uintptr_t p1 = maskAddress(ptr);
-  uint64_t i;
-
-  for (i = 1; i < count; ++i) {
-    p += size;
-    memcpy(&shadow_begin[p], &shadow_begin[p1], size);
-  }
-}
-
-/**
- * Record the stored type and address in the shadow memory.
- */
-void trackStoreInst(void *ptr, uint8_t typeNumber, uint64_t size, uint32_t tag) {
-  uintptr_t p = maskAddress(ptr);
-  shadow_begin[p] = typeNumber;
-  memset(&shadow_begin[p + 1], 0, size - 1);
-  printf("Store(%d): %p, %p = %u | %lu bytes | \n", tag, ptr, (void *)p, typeNumber, size);
-
-}
-
-/** 
- * Check that the two types match
- */
-void compareTypes(uint8_t typeNumberSrc, uint8_t typeNumberDest, uint32_t tag) {
-  if(typeNumberSrc != typeNumberDest) {
-    printf("Type mismatch(%u): expecting %s, found %s! \n", tag, typeNames[typeNumberDest], typeNames[typeNumberSrc]);
-  }
-}
-
-/**
- * Check that number of VAArg accessed is not greater than those passed
- */
-void compareNumber(uint64_t NumArgsPassed, uint64_t ArgAccessed, uint32_t tag){
-  if(ArgAccessed > NumArgsPassed) {
-    printf("Type mismatch(%u): Accessing variable %lu, passed only %lu! \n", tag, ArgAccessed, NumArgsPassed);
-  }
-}
-
-/**
- * Combined check for Va_arg. 
- * Check that no. of arguments is less than passed
- * Check that the type being accessed is correct
- * MD : pointer to array of metadata for each argument passed
- */
-void compareTypeAndNumber(uint64_t NumArgsPassed, uint64_t ArgAccessed, uint8_t TypeAccessed, void *MD, uint32_t tag) {
-  compareNumber(NumArgsPassed, ArgAccessed, tag);
-  compareTypes(TypeAccessed, ((uint8_t*)MD)[ArgAccessed], tag);
-}
-
-void getTypeTag(void *ptr, uint64_t size, uint8_t *dest) {
-  uintptr_t p = maskAddress(ptr);
-  assert(p + size < SIZE);
-
-  memcpy(dest, &shadow_begin[p], size);
-}
-
-void checkType(uint8_t typeNumber, uint64_t size, uint8_t *metadata, void *ptr, uint32_t tag) {
-  uint8_t i = 1;
-  /* Check if this an initialized but untyped memory.*/
-  if (typeNumber != metadata[0]) {
-    if (metadata[0] != 0xFF) {
-      printf("Type mismatch(%u): %p expecting %s, found %s!\n", tag, ptr, typeNames[typeNumber], typeNames[metadata[0]]);
-      return;
-    } else {
-      /* If so, set type to the type being read.
-         Check that none of the bytes are typed.*/
-      for (; i < size; ++i) {
-        if (0xFF != metadata[i]) {
-          printf("Type alignment mismatch(%u): expecting %s, found %s!\n", tag, typeNames[typeNumber], typeNames[metadata[i]]);
-          break;
-        }
-      }
-      trackStoreInst(ptr, typeNumber, size, tag);
-      return ;
-    }
-  }
-
-  for (; i < size; ++i) {
-    if (0 != metadata[i]) {
-      printf("Type alignment mismatch(%u): expecting %s, found %s!\n", tag, typeNames[typeNumber], typeNames[metadata[0]]);
-      break;
-    }
-  }
-
-}
-
-/**
- *  For memset type instructions, that set values. 
- *  0xFF type indicates that any type can be read, 
- */
-void trackInitInst(void *ptr, uint64_t size, uint32_t tag) {
-  uintptr_t p = maskAddress(ptr);
-  memset(&shadow_begin[p], 0xFF, size);
-#if DEBUG
-  printf("Initialize: %p, %p | %lu bytes | %u\n", ptr, (void *)p, size, tag);
-#endif
-}
-
-/**
- * Clear the metadata for given pointer
- */
-void trackUnInitInst(void *ptr, uint64_t size, uint32_t tag) {
-  uintptr_t p = maskAddress(ptr);
-  memset(&shadow_begin[p], 0x00, size);
-#if DEBUG
-  printf("Unitialize: %p, %p | %lu bytes | %u\n", ptr, (void *)p, size, tag);
-#endif
-}
-
-/**
- * Copy size bits of metadata from src ptr to dest ptr.
- */
-void copyTypeInfo(void *dstptr, void *srcptr, uint64_t size, uint32_t tag) {
-  uintptr_t d = maskAddress(dstptr);
-  uintptr_t s = maskAddress(srcptr);
-  memcpy(&shadow_begin[d], &shadow_begin[s], size);
-#if DEBUG
-  printf("Copy(%d): %p, %p = %u | %lu bytes \n", tag, dstptr, srcptr, shadow_begin[s], size);
-#endif
-}
-void setTypeInfo(void *dstptr, void *metadata, uint64_t size, uint32_t tag) {
-  uintptr_t d = maskAddress(dstptr);
-  memcpy(&shadow_begin[d], metadata, size);
-}
-
-/**
- * Initialize metadata for the pointer returned by __ctype_b_loc
- */
-void trackctype(void *ptr, uint32_t tag) {
-  short *p, *p1;
-  trackInitInst(ptr, sizeof(short*), tag);
-  p = *(short**)ptr;
-  p1 = p -128;
-  trackInitInst(p1, sizeof(short)*384, tag);
-}
-
-void trackctype_32(void *ptr, uint32_t tag) {
-  int *p, *p1;
-  trackInitInst(ptr, sizeof(int*), tag);
-  p = *(int**)ptr;
-  p1 = p -128 ;
-  trackInitInst(p1, sizeof(int)*384, tag);
-}
-
-/**
- * Initialize metadata for the dst pointer of strncpy
- */
-void trackStrncpyInst(void *dst, void *src, uint64_t size, uint32_t tag) {
-  if(strlen(src) < size)
-    size = strlen(src) + 1;
-  copyTypeInfo(dst, src, size, tag);
-}
-
-/**
- * Initialize metadata for the dst pointer of strcpy
- */
-void trackStrcpyInst(void *dst, void *src, uint32_t tag) {
-  copyTypeInfo(dst, src, strlen(src)+1, tag);
-}
-
-void trackStrcatInst(void *dst, void *src, uint32_t tag) {
-  uintptr_t dst_start = (uintptr_t)(dst) + strlen(dst) -1;
-  copyTypeInfo((void*)dst_start, src, strlen(src)+1, tag);
-}
-
-void trackgetcwd(void *ptr, uint32_t tag) {
-  if(!ptr)
-    return;
-  trackInitInst(ptr, strlen(ptr) + 1, tag);
-}
-
-void trackgethostname(void *ptr, uint32_t tag) {
-  trackInitInst(ptr, strlen(ptr) + 1, tag);
-}
-
-void trackgetaddrinfo(void *ptr, uint32_t tag) {
-  struct addrinfo *res;
-  struct addrinfo ** result = (struct addrinfo **)ptr;
-  for(res = *result; res != NULL; res = res->ai_next) {
-    trackInitInst(res->ai_addr, sizeof(struct sockaddr), tag);
-    trackInitInst(res, sizeof(struct addrinfo), tag);
-  }
-
-  trackInitInst(result, sizeof(struct addrinfo*), tag);
-}
-
-void trackaccept(void *ptr, uint32_t tag) {
-  trackInitInst(ptr, sizeof(struct sockaddr), tag);
-}
-
-void trackpoll(void *ptr, uint64_t nfds, uint32_t tag) {
-  struct pollfd *fds = (struct pollfd *)ptr;
-  unsigned i = 0;
-  while (i < nfds) {
-    trackInitInst(&fds[i], sizeof(struct pollfd), tag);
-    i++;
-  }
-}

Added: poolalloc/trunk/runtime/DynamicTypeChecks/TypeRuntime.cpp
URL: http://llvm.org/viewvc/llvm-project/poolalloc/trunk/runtime/DynamicTypeChecks/TypeRuntime.cpp?rev=133643&view=auto
==============================================================================
--- poolalloc/trunk/runtime/DynamicTypeChecks/TypeRuntime.cpp (added)
+++ poolalloc/trunk/runtime/DynamicTypeChecks/TypeRuntime.cpp Wed Jun 22 15:57:15 2011
@@ -0,0 +1,389 @@
+#include <assert.h>
+#include <inttypes.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <netdb.h>
+#include <poll.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/mman.h>
+
+#include <map>
+
+#define DEBUG (0)
+
+/* Size of shadow memory.  We're hoping everything fits in 46bits. */
+#define SIZE ((size_t)(1L << 46))
+
+/* Fixed start of memory.  Needs to be page-aligned,
+ * and it needs to be large enough that program itself is loaded below it
+ * and so are the libraries. 
+ * FIXME: This address has been picked for maute. Might not work on other
+ * machines. Need a more robust way of picking base address.
+ * For now, run a version of the tool without the base fixed, and 
+ * choose address.
+ */
+#define BASE ((uint8_t *)(0x2aaaab88c000))
+/*
+ * Do some macro magic to get mmap macros defined properly on all platforms.
+ */
+#if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
+# define MAP_ANONYMOUS MAP_ANON
+#endif /* defined(MAP_ANON) && !defined(MAP_ANONYMOUS) */
+
+struct va_info {
+  uint64_t numElements;
+  uint64_t counter;
+  uint8_t *metadata;
+};
+
+// Map to store info about va lists
+std::map<void *, struct va_info> VA_InfoMap;
+
+// Pointer to the shadow_memory
+uint8_t * const shadow_begin = BASE;
+
+// Map from type numbers to type names.
+extern char* typeNames[];
+
+extern "C" {
+  void trackInitInst(void *ptr, uint64_t size, uint32_t tag);
+  void shadowInit();
+  void trackArgvType(int argc, char **argv) ;
+  void trackEnvpType(char **envp) ;
+  void trackGlobal(void *ptr, uint8_t typeNumber, uint64_t size, uint32_t tag) ;
+  void trackArray(void *ptr, uint64_t size, uint64_t count, uint32_t tag) ;
+  void trackStoreInst(void *ptr, uint8_t typeNumber, uint64_t size, uint32_t tag) ;
+  void trackStringInput(void *ptr, uint32_t tag) ;
+  void compareTypes(uint8_t typeNumberSrc, uint8_t typeNumberDest, uint32_t tag) ;
+  void compareNumber(uint64_t NumArgsPassed, uint64_t ArgAccessed, uint32_t tag);
+  void compareTypeAndNumber(uint64_t NumArgsPassed, uint64_t ArgAccessed, uint8_t TypeAccessed, void *MD, uint32_t tag) ;
+  void checkVAArgType(void *va_list, uint8_t TypeAccessed, uint32_t tag) ;
+  void getTypeTag(void *ptr, uint64_t size, uint8_t *dest) ;
+  void checkType(uint8_t typeNumber, uint64_t size, uint8_t *metadata, void *ptr, uint32_t tag);
+  void trackInitInst(void *ptr, uint64_t size, uint32_t tag) ;
+  void trackUnInitInst(void *ptr, uint64_t size, uint32_t tag) ;
+  void copyTypeInfo(void *dstptr, void *srcptr, uint64_t size, uint32_t tag) ;
+  void setTypeInfo(void *dstptr, void *metadata, uint64_t size, uint32_t tag) ;
+  void setVAInfo(void *va_list, uint64_t totalCount, uint8_t *metadata_ptr) ;
+  void copyVAInfo(void *va_list_dst, uint8_t *va_list_src) ;
+  void trackctype(void *ptr, uint32_t tag) ;
+  void trackctype_32(void *ptr, uint32_t tag) ;
+  void trackStrncpyInst(void *dst, void *src, uint64_t size, uint32_t tag) ;
+  void trackStrcpyInst(void *dst, void *src, uint32_t tag) ;
+  void trackStrcatInst(void *dst, void *src, uint32_t tag) ;
+  void trackgetcwd(void *ptr, uint32_t tag) ;
+  void trackgethostname(void *ptr, uint32_t tag) ;
+  void trackgetaddrinfo(void *ptr, uint32_t tag) ;
+  void trackaccept(void *ptr, uint32_t tag) ;
+  void trackpoll(void *ptr, uint64_t nfds, uint32_t tag) ;
+}
+
+void trackInitInst(void *ptr, uint64_t size, uint32_t tag);
+
+inline uintptr_t maskAddress(void *ptr) {
+  uintptr_t p = (uintptr_t)ptr;
+  if (p >= (uintptr_t)BASE + SIZE) p -= SIZE;
+
+#if DEBUG
+  assert(p <= SIZE && "Pointer out of range!");
+#endif
+  return p;
+}
+
+/**
+ * Initialize the shadow memory which records the 1:1 mapping of addresses to types.
+ */
+void shadowInit() {
+  void * res = mmap(BASE, SIZE, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
+
+  if (res == MAP_FAILED) {
+    fprintf(stderr, "Failed to map the shadow memory!\n");
+    fflush(stderr);
+    assert(0 && "MAP_FAILED");
+  }
+  VA_InfoMap.clear();
+}
+
+/**
+ * initialize metadata to TOP/initialized.
+ */
+void trackArgvType(int argc, char **argv) {
+  int index = 0;
+  for (; index < argc; ++index) {
+    trackInitInst(argv[index], (strlen(argv[index]) + 1)*sizeof(char), 0);
+  }
+  trackInitInst(argv, (argc + 1)*sizeof(char*), 0);
+}
+
+/**
+ * initialize metadata to TOP/initialized.
+ */
+void trackEnvpType(char **envp) {
+  int index = 0;
+  for(;envp[index] != NULL; ++index)
+    trackInitInst(envp[index], (strlen(envp[index]) + 1)*sizeof(char), 0);
+  trackInitInst(envp, (index )*sizeof(char*), 0);
+}
+
+/**
+ * Record the global type and address in the shadow memory.
+ */
+void trackGlobal(void *ptr, uint8_t typeNumber, uint64_t size, uint32_t tag) {
+  uintptr_t p = maskAddress(ptr);
+  shadow_begin[p] = typeNumber;
+  memset(&shadow_begin[p + 1], 0, size - 1);
+#if DEBUG
+  printf("Global(%d): %p, %p = %u | %lu bytes\n", tag, ptr, (void *)p, typeNumber, size);
+#endif
+}
+
+/**
+ * Record the type stored at ptr(of size size) and replicate it
+ */
+void trackArray(void *ptr, uint64_t size, uint64_t count, uint32_t tag) {
+  uintptr_t p = maskAddress(ptr);
+  uintptr_t p1 = maskAddress(ptr);
+  uint64_t i;
+
+  for (i = 1; i < count; ++i) {
+    p += size;
+    memcpy(&shadow_begin[p], &shadow_begin[p1], size);
+  }
+}
+
+/**
+ * Record the stored type and address in the shadow memory.
+ */
+void trackStoreInst(void *ptr, uint8_t typeNumber, uint64_t size, uint32_t tag) {
+  uintptr_t p = maskAddress(ptr);
+  shadow_begin[p] = typeNumber;
+  memset(&shadow_begin[p + 1], 0, size - 1);
+#if DEBUG
+  printf("Store(%d): %p, %p = %u | %lu bytes | \n", tag, ptr, (void *)p, typeNumber, size);
+#endif
+
+}
+
+/**
+ * Record that a string is stored at ptr
+ */
+void trackStringInput(void *ptr, uint32_t tag) {
+  trackInitInst(ptr, strlen((const char *)ptr) + 1, tag);
+}
+
+/** 
+ * Check that the two types match
+ */
+void compareTypes(uint8_t typeNumberSrc, uint8_t typeNumberDest, uint32_t tag) {
+  if(typeNumberSrc != typeNumberDest) {
+    printf("Type mismatch(%u): expecting %s, found %s! \n", tag, typeNames[typeNumberDest], typeNames[typeNumberSrc]);
+  }
+}
+
+/**
+ * Check that number of VAArg accessed is not greater than those passed
+ */
+void compareNumber(uint64_t NumArgsPassed, uint64_t ArgAccessed, uint32_t tag){
+  if(ArgAccessed > NumArgsPassed) {
+    printf("Type mismatch(%u): Accessing variable %lu, passed only %lu! \n", tag, ArgAccessed, NumArgsPassed);
+  }
+}
+
+/**
+ * Combined check for Va_arg. 
+ * Check that no. of arguments is less than passed
+ * Check that the type being accessed is correct
+ */
+void checkVAArgType(void *va_list, uint8_t TypeAccessed, uint32_t tag) {
+  va_info v = VA_InfoMap[va_list];
+  compareNumber(v.numElements, v.counter, tag);
+  compareTypes(TypeAccessed, v.metadata[v.counter], tag);
+  v.counter++;
+  VA_InfoMap[va_list] = v;
+}
+
+/**
+ * For loads, return the metadata(for size bytes) stored at the ptr
+ * Store it in dest
+ */
+void getTypeTag(void *ptr, uint64_t size, uint8_t *dest) {
+  uintptr_t p = maskAddress(ptr);
+  assert(p + size < SIZE);
+
+  memcpy(dest, &shadow_begin[p], size);
+}
+
+/**
+ * Compare the typeNumber with the type info(for given size) stored at the metadata ptr.
+ * ptr and tag are for debugging
+ */
+void __attribute__((always_inline))
+checkType(uint8_t typeNumber, uint64_t size, uint8_t *metadata, void *ptr, uint32_t tag) {
+  /* Check if this an initialized but untyped memory.*/
+  if (typeNumber != metadata[0]) {
+    if (metadata[0] != 0xFF) {
+      printf("Type mismatch(%u): %p expecting %s, found %s!\n", tag, ptr, typeNames[typeNumber], typeNames[metadata[0]]);
+      return;
+    } else {
+      /* If so, set type to the type being read.
+         Check that none of the bytes are typed.*/
+      for (unsigned i = 1; i < size; ++i) {
+        if (0xFF != metadata[i]) {
+          printf("Type alignment mismatch(%u): expecting %s, found %s!\n", tag, typeNames[typeNumber], typeNames[metadata[i]]);
+          break;
+        }
+      }
+      trackStoreInst(ptr, typeNumber, size, tag);
+      return ;
+    }
+  }
+
+  for (unsigned i = 1 ; i < size; ++i) {
+    if (0 != metadata[i]) {
+      printf("Type alignment mismatch(%u): expecting %s, found %s!\n", tag, typeNames[typeNumber], typeNames[metadata[0]]);
+      break;
+    }
+  }
+}
+
+/**
+ *  For memset type instructions, that set values. 
+ *  0xFF type indicates that any type can be read, 
+ */
+void trackInitInst(void *ptr, uint64_t size, uint32_t tag) {
+  uintptr_t p = maskAddress(ptr);
+  memset(&shadow_begin[p], 0xFF, size);
+#if DEBUG
+  printf("Initialize: %p, %p | %lu bytes | %u\n", ptr, (void *)p, size, tag);
+#endif
+}
+
+/**
+ * Clear the metadata for given pointer
+ */
+void trackUnInitInst(void *ptr, uint64_t size, uint32_t tag) {
+  uintptr_t p = maskAddress(ptr);
+  memset(&shadow_begin[p], 0x00, size);
+#if DEBUG
+  printf("Unitialize: %p, %p | %lu bytes | %u\n", ptr, (void *)p, size, tag);
+#endif
+}
+
+/**
+ * Copy size bytes of metadata from src ptr to dest ptr.
+ */
+void copyTypeInfo(void *dstptr, void *srcptr, uint64_t size, uint32_t tag) {
+  uintptr_t d = maskAddress(dstptr);
+  uintptr_t s = maskAddress(srcptr);
+  memcpy(&shadow_begin[d], &shadow_begin[s], size);
+#if DEBUG
+  printf("Copy(%d): %p, %p = %u | %lu bytes \n", tag, dstptr, srcptr, shadow_begin[s], size);
+#endif
+}
+
+/**
+ * Copy size bytes of metadata from metadata to dest ptr
+ */
+void setTypeInfo(void *dstptr, void *metadata, uint64_t size, uint32_t tag) {
+  uintptr_t d = maskAddress(dstptr);
+  memcpy(&shadow_begin[d], metadata, size);
+}
+
+/**
+ * Initialize the metadata for a given VAList
+ */
+void setVAInfo(void *va_list, uint64_t totalCount, uint8_t *metadata_ptr, uint32_t tag) {
+  struct va_info v = {totalCount, 0, metadata_ptr};
+  VA_InfoMap[va_list] = v;
+}
+
+/**
+ * Copy va list metadata from one list to the other.
+ */
+void copyVAInfo(void *va_list_dst, uint8_t *va_list_src, uint32_t tag) {
+  VA_InfoMap[va_list_dst] = VA_InfoMap[va_list_src];
+}
+
+/**
+ * Initialize metadata for the pointer returned by __ctype_b_loc
+ */
+void trackctype(void *ptr, uint32_t tag) {
+  short *p, *p1;
+  trackInitInst(ptr, sizeof(short*), tag);
+  p = *(short**)ptr;
+  p1 = p -128;
+  trackInitInst(p1, sizeof(short)*384, tag);
+}
+
+void trackctype_32(void *ptr, uint32_t tag) {
+  int *p, *p1;
+  trackInitInst(ptr, sizeof(int*), tag);
+  p = *(int**)ptr;
+  p1 = p -128 ;
+  trackInitInst(p1, sizeof(int)*384, tag);
+}
+
+/**
+ * Initialize metadata for the dst pointer of strncpy
+ */
+void trackStrncpyInst(void *dst, void *src, uint64_t size, uint32_t tag) {
+  if(strlen((const char *)src) < size)
+    size = strlen((const char *)src) + 1;
+  copyTypeInfo(dst, src, size, tag);
+}
+
+/**
+ * Initialize metadata for the dst pointer of strcpy
+ */
+void trackStrcpyInst(void *dst, void *src, uint32_t tag) {
+  copyTypeInfo(dst, src, strlen((const char *)src)+1, tag);
+}
+
+/**
+ * Initialize the metadata fr dst pointer of strcap
+ */
+void trackStrcatInst(void *dst, void *src, uint32_t tag) {
+  uintptr_t dst_start = (uintptr_t)(dst) + strlen((const char *)dst) -1;
+  copyTypeInfo((void*)dst_start, src, strlen((const char *)src)+1, tag);
+}
+
+/**
+ * Initialize metadata for some library functions
+ */
+
+void trackgetcwd(void *ptr, uint32_t tag) {
+  if(!ptr)
+    return;
+  trackInitInst(ptr, strlen((const char *)ptr) + 1, tag);
+}
+
+void trackgethostname(void *ptr, uint32_t tag) {
+  trackInitInst(ptr, strlen((const char *)ptr) + 1, tag);
+}
+
+void trackgetaddrinfo(void *ptr, uint32_t tag) {
+  struct addrinfo *res;
+  struct addrinfo ** result = (struct addrinfo **)ptr;
+  for(res = *result; res != NULL; res = res->ai_next) {
+    trackInitInst(res->ai_addr, sizeof(struct sockaddr), tag);
+    trackInitInst(res, sizeof(struct addrinfo), tag);
+  }
+
+  trackInitInst(result, sizeof(struct addrinfo*), tag);
+}
+
+void trackaccept(void *ptr, uint32_t tag) {
+  trackInitInst(ptr, sizeof(struct sockaddr), tag);
+}
+
+void trackpoll(void *ptr, uint64_t nfds, uint32_t tag) {
+  struct pollfd *fds = (struct pollfd *)ptr;
+  unsigned i = 0;
+  while (i < nfds) {
+    trackInitInst(&fds[i], sizeof(struct pollfd), tag);
+    i++;
+  }
+}





More information about the llvm-commits mailing list