LLVM  5.0.0
DataFlowSanitizer.cpp
Go to the documentation of this file.
1 //===-- DataFlowSanitizer.cpp - dynamic data flow analysis ----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// This file is a part of DataFlowSanitizer, a generalised dynamic data flow
11 /// analysis.
12 ///
13 /// Unlike other Sanitizer tools, this tool is not designed to detect a specific
14 /// class of bugs on its own. Instead, it provides a generic dynamic data flow
15 /// analysis framework to be used by clients to help detect application-specific
16 /// issues within their own code.
17 ///
18 /// The analysis is based on automatic propagation of data flow labels (also
19 /// known as taint labels) through a program as it performs computation. Each
20 /// byte of application memory is backed by two bytes of shadow memory which
21 /// hold the label. On Linux/x86_64, memory is laid out as follows:
22 ///
23 /// +--------------------+ 0x800000000000 (top of memory)
24 /// | application memory |
25 /// +--------------------+ 0x700000008000 (kAppAddr)
26 /// | |
27 /// | unused |
28 /// | |
29 /// +--------------------+ 0x200200000000 (kUnusedAddr)
30 /// | union table |
31 /// +--------------------+ 0x200000000000 (kUnionTableAddr)
32 /// | shadow memory |
33 /// +--------------------+ 0x000000010000 (kShadowAddr)
34 /// | reserved by kernel |
35 /// +--------------------+ 0x000000000000
36 ///
37 /// To derive a shadow memory address from an application memory address,
38 /// bits 44-46 are cleared to bring the address into the range
39 /// [0x000000008000,0x100000000000). Then the address is shifted left by 1 to
40 /// account for the double byte representation of shadow labels and move the
41 /// address into the shadow memory range. See the function
42 /// DataFlowSanitizer::getShadowAddress below.
43 ///
44 /// For more information, please refer to the design document:
45 /// http://clang.llvm.org/docs/DataFlowSanitizerDesign.html
46 
47 #include "llvm/ADT/DenseMap.h"
48 #include "llvm/ADT/DenseSet.h"
50 #include "llvm/ADT/StringExtras.h"
51 #include "llvm/ADT/Triple.h"
53 #include "llvm/IR/DebugInfo.h"
54 #include "llvm/IR/Dominators.h"
55 #include "llvm/IR/IRBuilder.h"
56 #include "llvm/IR/InlineAsm.h"
57 #include "llvm/IR/InstVisitor.h"
58 #include "llvm/IR/LLVMContext.h"
59 #include "llvm/IR/MDBuilder.h"
60 #include "llvm/IR/Type.h"
61 #include "llvm/IR/Value.h"
62 #include "llvm/Pass.h"
68 #include <algorithm>
69 #include <iterator>
70 #include <set>
71 #include <utility>
72 
73 using namespace llvm;
74 
75 // External symbol to be used when generating the shadow address for
76 // architectures with multiple VMAs. Instead of using a constant integer
77 // the runtime will set the external mask based on the VMA range.
78 static const char *const kDFSanExternShadowPtrMask = "__dfsan_shadow_ptr_mask";
79 
80 // The -dfsan-preserve-alignment flag controls whether this pass assumes that
81 // alignment requirements provided by the input IR are correct. For example,
82 // if the input IR contains a load with alignment 8, this flag will cause
83 // the shadow load to have alignment 16. This flag is disabled by default as
84 // we have unfortunately encountered too much code (including Clang itself;
85 // see PR14291) which performs misaligned access.
87  "dfsan-preserve-alignment",
88  cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
89  cl::init(false));
90 
91 // The ABI list files control how shadow parameters are passed. The pass treats
92 // every function labelled "uninstrumented" in the ABI list file as conforming
93 // to the "native" (i.e. unsanitized) ABI. Unless the ABI list contains
94 // additional annotations for those functions, a call to one of those functions
95 // will produce a warning message, as the labelling behaviour of the function is
96 // unknown. The other supported annotations are "functional" and "discard",
97 // which are described below under DataFlowSanitizer::WrapperKind.
99  "dfsan-abilist",
100  cl::desc("File listing native ABI functions and how the pass treats them"),
101  cl::Hidden);
102 
103 // Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
104 // functions (see DataFlowSanitizer::InstrumentedABI below).
105 static cl::opt<bool> ClArgsABI(
106  "dfsan-args-abi",
107  cl::desc("Use the argument ABI rather than the TLS ABI"),
108  cl::Hidden);
109 
110 // Controls whether the pass includes or ignores the labels of pointers in load
111 // instructions.
113  "dfsan-combine-pointer-labels-on-load",
114  cl::desc("Combine the label of the pointer with the label of the data when "
115  "loading from memory."),
116  cl::Hidden, cl::init(true));
117 
118 // Controls whether the pass includes or ignores the labels of pointers in
119 // stores instructions.
121  "dfsan-combine-pointer-labels-on-store",
122  cl::desc("Combine the label of the pointer with the label of the data when "
123  "storing in memory."),
124  cl::Hidden, cl::init(false));
125 
127  "dfsan-debug-nonzero-labels",
128  cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
129  "load or return with a nonzero label"),
130  cl::Hidden);
131 
132 
133 namespace {
134 
135 StringRef GetGlobalTypeString(const GlobalValue &G) {
136  // Types of GlobalVariables are always pointer types.
137  Type *GType = G.getValueType();
138  // For now we support blacklisting struct types only.
139  if (StructType *SGType = dyn_cast<StructType>(GType)) {
140  if (!SGType->isLiteral())
141  return SGType->getName();
142  }
143  return "<unknown type>";
144 }
145 
146 class DFSanABIList {
147  std::unique_ptr<SpecialCaseList> SCL;
148 
149  public:
150  DFSanABIList() {}
151 
152  void set(std::unique_ptr<SpecialCaseList> List) { SCL = std::move(List); }
153 
154  /// Returns whether either this function or its source file are listed in the
155  /// given category.
156  bool isIn(const Function &F, StringRef Category) const {
157  return isIn(*F.getParent(), Category) ||
158  SCL->inSection("fun", F.getName(), Category);
159  }
160 
161  /// Returns whether this global alias is listed in the given category.
162  ///
163  /// If GA aliases a function, the alias's name is matched as a function name
164  /// would be. Similarly, aliases of globals are matched like globals.
165  bool isIn(const GlobalAlias &GA, StringRef Category) const {
166  if (isIn(*GA.getParent(), Category))
167  return true;
168 
169  if (isa<FunctionType>(GA.getValueType()))
170  return SCL->inSection("fun", GA.getName(), Category);
171 
172  return SCL->inSection("global", GA.getName(), Category) ||
173  SCL->inSection("type", GetGlobalTypeString(GA), Category);
174  }
175 
176  /// Returns whether this module is listed in the given category.
177  bool isIn(const Module &M, StringRef Category) const {
178  return SCL->inSection("src", M.getModuleIdentifier(), Category);
179  }
180 };
181 
182 class DataFlowSanitizer : public ModulePass {
183  friend struct DFSanFunction;
184  friend class DFSanVisitor;
185 
186  enum {
187  ShadowWidth = 16
188  };
189 
190  /// Which ABI should be used for instrumented functions?
191  enum InstrumentedABI {
192  /// Argument and return value labels are passed through additional
193  /// arguments and by modifying the return type.
194  IA_Args,
195 
196  /// Argument and return value labels are passed through TLS variables
197  /// __dfsan_arg_tls and __dfsan_retval_tls.
198  IA_TLS
199  };
200 
201  /// How should calls to uninstrumented functions be handled?
202  enum WrapperKind {
203  /// This function is present in an uninstrumented form but we don't know
204  /// how it should be handled. Print a warning and call the function anyway.
205  /// Don't label the return value.
206  WK_Warning,
207 
208  /// This function does not write to (user-accessible) memory, and its return
209  /// value is unlabelled.
210  WK_Discard,
211 
212  /// This function does not write to (user-accessible) memory, and the label
213  /// of its return value is the union of the label of its arguments.
214  WK_Functional,
215 
216  /// Instead of calling the function, a custom wrapper __dfsw_F is called,
217  /// where F is the name of the function. This function may wrap the
218  /// original function or provide its own implementation. This is similar to
219  /// the IA_Args ABI, except that IA_Args uses a struct return type to
220  /// pass the return value shadow in a register, while WK_Custom uses an
221  /// extra pointer argument to return the shadow. This allows the wrapped
222  /// form of the function type to be expressed in C.
223  WK_Custom
224  };
225 
226  Module *Mod;
227  LLVMContext *Ctx;
228  IntegerType *ShadowTy;
229  PointerType *ShadowPtrTy;
230  IntegerType *IntptrTy;
231  ConstantInt *ZeroShadow;
232  ConstantInt *ShadowPtrMask;
233  ConstantInt *ShadowPtrMul;
234  Constant *ArgTLS;
235  Constant *RetvalTLS;
236  void *(*GetArgTLSPtr)();
237  void *(*GetRetvalTLSPtr)();
238  Constant *GetArgTLS;
239  Constant *GetRetvalTLS;
240  Constant *ExternalShadowMask;
241  FunctionType *DFSanUnionFnTy;
242  FunctionType *DFSanUnionLoadFnTy;
243  FunctionType *DFSanUnimplementedFnTy;
244  FunctionType *DFSanSetLabelFnTy;
245  FunctionType *DFSanNonzeroLabelFnTy;
246  FunctionType *DFSanVarargWrapperFnTy;
247  Constant *DFSanUnionFn;
248  Constant *DFSanCheckedUnionFn;
249  Constant *DFSanUnionLoadFn;
250  Constant *DFSanUnimplementedFn;
251  Constant *DFSanSetLabelFn;
252  Constant *DFSanNonzeroLabelFn;
253  Constant *DFSanVarargWrapperFn;
254  MDNode *ColdCallWeights;
255  DFSanABIList ABIList;
256  DenseMap<Value *, Function *> UnwrappedFnMap;
257  AttrBuilder ReadOnlyNoneAttrs;
258  bool DFSanRuntimeShadowMask;
259 
260  Value *getShadowAddress(Value *Addr, Instruction *Pos);
261  bool isInstrumented(const Function *F);
262  bool isInstrumented(const GlobalAlias *GA);
263  FunctionType *getArgsFunctionType(FunctionType *T);
264  FunctionType *getTrampolineFunctionType(FunctionType *T);
265  FunctionType *getCustomFunctionType(FunctionType *T);
266  InstrumentedABI getInstrumentedABI();
267  WrapperKind getWrapperKind(Function *F);
268  void addGlobalNamePrefix(GlobalValue *GV);
269  Function *buildWrapperFunction(Function *F, StringRef NewFName,
270  GlobalValue::LinkageTypes NewFLink,
271  FunctionType *NewFT);
272  Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
273 
274  public:
275  DataFlowSanitizer(
276  const std::vector<std::string> &ABIListFiles = std::vector<std::string>(),
277  void *(*getArgTLS)() = nullptr, void *(*getRetValTLS)() = nullptr);
278  static char ID;
279  bool doInitialization(Module &M) override;
280  bool runOnModule(Module &M) override;
281 };
282 
283 struct DFSanFunction {
284  DataFlowSanitizer &DFS;
285  Function *F;
286  DominatorTree DT;
287  DataFlowSanitizer::InstrumentedABI IA;
288  bool IsNativeABI;
289  Value *ArgTLSPtr;
290  Value *RetvalTLSPtr;
291  AllocaInst *LabelReturnAlloca;
292  DenseMap<Value *, Value *> ValShadowMap;
293  DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
294  std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
295  DenseSet<Instruction *> SkipInsts;
296  std::vector<Value *> NonZeroChecks;
297  bool AvoidNewBlocks;
298 
299  struct CachedCombinedShadow {
300  BasicBlock *Block;
301  Value *Shadow;
302  };
303  DenseMap<std::pair<Value *, Value *>, CachedCombinedShadow>
304  CachedCombinedShadows;
305  DenseMap<Value *, std::set<Value *>> ShadowElements;
306 
307  DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
308  : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()),
309  IsNativeABI(IsNativeABI), ArgTLSPtr(nullptr), RetvalTLSPtr(nullptr),
310  LabelReturnAlloca(nullptr) {
311  DT.recalculate(*F);
312  // FIXME: Need to track down the register allocator issue which causes poor
313  // performance in pathological cases with large numbers of basic blocks.
314  AvoidNewBlocks = F->size() > 1000;
315  }
316  Value *getArgTLSPtr();
317  Value *getArgTLS(unsigned Index, Instruction *Pos);
318  Value *getRetvalTLS();
319  Value *getShadow(Value *V);
320  void setShadow(Instruction *I, Value *Shadow);
321  Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
322  Value *combineOperandShadows(Instruction *Inst);
323  Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
324  Instruction *Pos);
325  void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
326  Instruction *Pos);
327 };
328 
329 class DFSanVisitor : public InstVisitor<DFSanVisitor> {
330  public:
331  DFSanFunction &DFSF;
332  DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
333 
334  const DataLayout &getDataLayout() const {
335  return DFSF.F->getParent()->getDataLayout();
336  }
337 
338  void visitOperandShadowInst(Instruction &I);
339 
340  void visitBinaryOperator(BinaryOperator &BO);
341  void visitCastInst(CastInst &CI);
342  void visitCmpInst(CmpInst &CI);
343  void visitGetElementPtrInst(GetElementPtrInst &GEPI);
344  void visitLoadInst(LoadInst &LI);
345  void visitStoreInst(StoreInst &SI);
346  void visitReturnInst(ReturnInst &RI);
347  void visitCallSite(CallSite CS);
348  void visitPHINode(PHINode &PN);
349  void visitExtractElementInst(ExtractElementInst &I);
350  void visitInsertElementInst(InsertElementInst &I);
351  void visitShuffleVectorInst(ShuffleVectorInst &I);
352  void visitExtractValueInst(ExtractValueInst &I);
353  void visitInsertValueInst(InsertValueInst &I);
354  void visitAllocaInst(AllocaInst &I);
355  void visitSelectInst(SelectInst &I);
356  void visitMemSetInst(MemSetInst &I);
357  void visitMemTransferInst(MemTransferInst &I);
358 };
359 
360 }
361 
363 INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
364  "DataFlowSanitizer: dynamic data flow analysis.", false, false)
365 
366 ModulePass *
367 llvm::createDataFlowSanitizerPass(const std::vector<std::string> &ABIListFiles,
368  void *(*getArgTLS)(),
369  void *(*getRetValTLS)()) {
370  return new DataFlowSanitizer(ABIListFiles, getArgTLS, getRetValTLS);
371 }
372 
373 DataFlowSanitizer::DataFlowSanitizer(
374  const std::vector<std::string> &ABIListFiles, void *(*getArgTLS)(),
375  void *(*getRetValTLS)())
376  : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS),
377  DFSanRuntimeShadowMask(false) {
378  std::vector<std::string> AllABIListFiles(std::move(ABIListFiles));
379  AllABIListFiles.insert(AllABIListFiles.end(), ClABIListFiles.begin(),
380  ClABIListFiles.end());
381  ABIList.set(SpecialCaseList::createOrDie(AllABIListFiles));
382 }
383 
384 FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
386  ArgTypes.append(T->getNumParams(), ShadowTy);
387  if (T->isVarArg())
388  ArgTypes.push_back(ShadowPtrTy);
389  Type *RetType = T->getReturnType();
390  if (!RetType->isVoidTy())
391  RetType = StructType::get(RetType, ShadowTy);
392  return FunctionType::get(RetType, ArgTypes, T->isVarArg());
393 }
394 
395 FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
396  assert(!T->isVarArg());
398  ArgTypes.push_back(T->getPointerTo());
399  ArgTypes.append(T->param_begin(), T->param_end());
400  ArgTypes.append(T->getNumParams(), ShadowTy);
401  Type *RetType = T->getReturnType();
402  if (!RetType->isVoidTy())
403  ArgTypes.push_back(ShadowPtrTy);
404  return FunctionType::get(T->getReturnType(), ArgTypes, false);
405 }
406 
407 FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
409  for (FunctionType::param_iterator i = T->param_begin(), e = T->param_end();
410  i != e; ++i) {
411  FunctionType *FT;
412  if (isa<PointerType>(*i) && (FT = dyn_cast<FunctionType>(cast<PointerType>(
413  *i)->getElementType()))) {
414  ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
415  ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
416  } else {
417  ArgTypes.push_back(*i);
418  }
419  }
420  for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
421  ArgTypes.push_back(ShadowTy);
422  if (T->isVarArg())
423  ArgTypes.push_back(ShadowPtrTy);
424  Type *RetType = T->getReturnType();
425  if (!RetType->isVoidTy())
426  ArgTypes.push_back(ShadowPtrTy);
427  return FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg());
428 }
429 
430 bool DataFlowSanitizer::doInitialization(Module &M) {
431  llvm::Triple TargetTriple(M.getTargetTriple());
432  bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
433  bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
434  TargetTriple.getArch() == llvm::Triple::mips64el;
435  bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64 ||
436  TargetTriple.getArch() == llvm::Triple::aarch64_be;
437 
438  const DataLayout &DL = M.getDataLayout();
439 
440  Mod = &M;
441  Ctx = &M.getContext();
442  ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
443  ShadowPtrTy = PointerType::getUnqual(ShadowTy);
444  IntptrTy = DL.getIntPtrType(*Ctx);
445  ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
446  ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
447  if (IsX86_64)
448  ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
449  else if (IsMIPS64)
450  ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0xF000000000LL);
451  // AArch64 supports multiple VMAs and the shadow mask is set at runtime.
452  else if (IsAArch64)
453  DFSanRuntimeShadowMask = true;
454  else
455  report_fatal_error("unsupported triple");
456 
457  Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
458  DFSanUnionFnTy =
459  FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
460  Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
461  DFSanUnionLoadFnTy =
462  FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
463  DFSanUnimplementedFnTy = FunctionType::get(
464  Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
465  Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
466  DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
467  DFSanSetLabelArgs, /*isVarArg=*/false);
468  DFSanNonzeroLabelFnTy = FunctionType::get(
469  Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
470  DFSanVarargWrapperFnTy = FunctionType::get(
471  Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
472 
473  if (GetArgTLSPtr) {
474  Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
475  ArgTLS = nullptr;
476  GetArgTLS = ConstantExpr::getIntToPtr(
477  ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
478  PointerType::getUnqual(
479  FunctionType::get(PointerType::getUnqual(ArgTLSTy), false)));
480  }
481  if (GetRetvalTLSPtr) {
482  RetvalTLS = nullptr;
483  GetRetvalTLS = ConstantExpr::getIntToPtr(
484  ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
485  PointerType::getUnqual(
486  FunctionType::get(PointerType::getUnqual(ShadowTy), false)));
487  }
488 
489  ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
490  return true;
491 }
492 
493 bool DataFlowSanitizer::isInstrumented(const Function *F) {
494  return !ABIList.isIn(*F, "uninstrumented");
495 }
496 
497 bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
498  return !ABIList.isIn(*GA, "uninstrumented");
499 }
500 
501 DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
502  return ClArgsABI ? IA_Args : IA_TLS;
503 }
504 
505 DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
506  if (ABIList.isIn(*F, "functional"))
507  return WK_Functional;
508  if (ABIList.isIn(*F, "discard"))
509  return WK_Discard;
510  if (ABIList.isIn(*F, "custom"))
511  return WK_Custom;
512 
513  return WK_Warning;
514 }
515 
516 void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
517  std::string GVName = GV->getName(), Prefix = "dfs$";
518  GV->setName(Prefix + GVName);
519 
520  // Try to change the name of the function in module inline asm. We only do
521  // this for specific asm directives, currently only ".symver", to try to avoid
522  // corrupting asm which happens to contain the symbol name as a substring.
523  // Note that the substitution for .symver assumes that the versioned symbol
524  // also has an instrumented name.
525  std::string Asm = GV->getParent()->getModuleInlineAsm();
526  std::string SearchStr = ".symver " + GVName + ",";
527  size_t Pos = Asm.find(SearchStr);
528  if (Pos != std::string::npos) {
529  Asm.replace(Pos, SearchStr.size(),
530  ".symver " + Prefix + GVName + "," + Prefix);
531  GV->getParent()->setModuleInlineAsm(Asm);
532  }
533 }
534 
535 Function *
536 DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
537  GlobalValue::LinkageTypes NewFLink,
538  FunctionType *NewFT) {
539  FunctionType *FT = F->getFunctionType();
540  Function *NewF = Function::Create(NewFT, NewFLink, NewFName,
541  F->getParent());
542  NewF->copyAttributesFrom(F);
543  NewF->removeAttributes(
544  AttributeList::ReturnIndex,
546 
547  BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
548  if (F->isVarArg()) {
549  NewF->removeAttributes(AttributeList::FunctionIndex,
550  AttrBuilder().addAttribute("split-stack"));
551  CallInst::Create(DFSanVarargWrapperFn,
552  IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "",
553  BB);
554  new UnreachableInst(*Ctx, BB);
555  } else {
556  std::vector<Value *> Args;
557  unsigned n = FT->getNumParams();
558  for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
559  Args.push_back(&*ai);
560  CallInst *CI = CallInst::Create(F, Args, "", BB);
561  if (FT->getReturnType()->isVoidTy())
562  ReturnInst::Create(*Ctx, BB);
563  else
564  ReturnInst::Create(*Ctx, CI, BB);
565  }
566 
567  return NewF;
568 }
569 
570 Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
571  StringRef FName) {
572  FunctionType *FTT = getTrampolineFunctionType(FT);
573  Constant *C = Mod->getOrInsertFunction(FName, FTT);
574  Function *F = dyn_cast<Function>(C);
575  if (F && F->isDeclaration()) {
576  F->setLinkage(GlobalValue::LinkOnceODRLinkage);
577  BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
578  std::vector<Value *> Args;
579  Function::arg_iterator AI = F->arg_begin(); ++AI;
580  for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
581  Args.push_back(&*AI);
582  CallInst *CI = CallInst::Create(&*F->arg_begin(), Args, "", BB);
583  ReturnInst *RI;
584  if (FT->getReturnType()->isVoidTy())
585  RI = ReturnInst::Create(*Ctx, BB);
586  else
587  RI = ReturnInst::Create(*Ctx, CI, BB);
588 
589  DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
590  Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
591  for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
592  DFSF.ValShadowMap[&*ValAI] = &*ShadowAI;
593  DFSanVisitor(DFSF).visitCallInst(*CI);
594  if (!FT->getReturnType()->isVoidTy())
595  new StoreInst(DFSF.getShadow(RI->getReturnValue()),
596  &*std::prev(F->arg_end()), RI);
597  }
598 
599  return C;
600 }
601 
602 bool DataFlowSanitizer::runOnModule(Module &M) {
603  if (ABIList.isIn(M, "skip"))
604  return false;
605 
606  if (!GetArgTLSPtr) {
607  Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
608  ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
609  if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
610  G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
611  }
612  if (!GetRetvalTLSPtr) {
613  RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
614  if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
615  G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
616  }
617 
618  ExternalShadowMask =
619  Mod->getOrInsertGlobal(kDFSanExternShadowPtrMask, IntptrTy);
620 
621  DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
622  if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
623  F->addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
624  F->addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
625  F->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
626  F->addParamAttr(0, Attribute::ZExt);
627  F->addParamAttr(1, Attribute::ZExt);
628  }
629  DFSanCheckedUnionFn = Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy);
630  if (Function *F = dyn_cast<Function>(DFSanCheckedUnionFn)) {
631  F->addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
632  F->addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
633  F->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
634  F->addParamAttr(0, Attribute::ZExt);
635  F->addParamAttr(1, Attribute::ZExt);
636  }
637  DFSanUnionLoadFn =
638  Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
639  if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
640  F->addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
641  F->addAttribute(AttributeList::FunctionIndex, Attribute::ReadOnly);
642  F->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
643  }
644  DFSanUnimplementedFn =
645  Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
646  DFSanSetLabelFn =
647  Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
648  if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
649  F->addParamAttr(0, Attribute::ZExt);
650  }
651  DFSanNonzeroLabelFn =
652  Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
653  DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper",
654  DFSanVarargWrapperFnTy);
655 
656  std::vector<Function *> FnsToInstrument;
657  llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
658  for (Function &i : M) {
659  if (!i.isIntrinsic() &&
660  &i != DFSanUnionFn &&
661  &i != DFSanCheckedUnionFn &&
662  &i != DFSanUnionLoadFn &&
663  &i != DFSanUnimplementedFn &&
664  &i != DFSanSetLabelFn &&
665  &i != DFSanNonzeroLabelFn &&
666  &i != DFSanVarargWrapperFn)
667  FnsToInstrument.push_back(&i);
668  }
669 
670  // Give function aliases prefixes when necessary, and build wrappers where the
671  // instrumentedness is inconsistent.
672  for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
673  GlobalAlias *GA = &*i;
674  ++i;
675  // Don't stop on weak. We assume people aren't playing games with the
676  // instrumentedness of overridden weak aliases.
677  if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
678  bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
679  if (GAInst && FInst) {
680  addGlobalNamePrefix(GA);
681  } else if (GAInst != FInst) {
682  // Non-instrumented alias of an instrumented function, or vice versa.
683  // Replace the alias with a native-ABI wrapper of the aliasee. The pass
684  // below will take care of instrumenting it.
685  Function *NewF =
686  buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
687  GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
688  NewF->takeName(GA);
689  GA->eraseFromParent();
690  FnsToInstrument.push_back(NewF);
691  }
692  }
693  }
694 
695  ReadOnlyNoneAttrs.addAttribute(Attribute::ReadOnly)
696  .addAttribute(Attribute::ReadNone);
697 
698  // First, change the ABI of every function in the module. ABI-listed
699  // functions keep their original ABI and get a wrapper function.
700  for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
701  e = FnsToInstrument.end();
702  i != e; ++i) {
703  Function &F = **i;
704  FunctionType *FT = F.getFunctionType();
705 
706  bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
707  FT->getReturnType()->isVoidTy());
708 
709  if (isInstrumented(&F)) {
710  // Instrumented functions get a 'dfs$' prefix. This allows us to more
711  // easily identify cases of mismatching ABIs.
712  if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
713  FunctionType *NewFT = getArgsFunctionType(FT);
714  Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
715  NewF->copyAttributesFrom(&F);
716  NewF->removeAttributes(
717  AttributeList::ReturnIndex,
719  for (Function::arg_iterator FArg = F.arg_begin(),
720  NewFArg = NewF->arg_begin(),
721  FArgEnd = F.arg_end();
722  FArg != FArgEnd; ++FArg, ++NewFArg) {
723  FArg->replaceAllUsesWith(&*NewFArg);
724  }
725  NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
726 
727  for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
728  UI != UE;) {
729  BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
730  ++UI;
731  if (BA) {
732  BA->replaceAllUsesWith(
733  BlockAddress::get(NewF, BA->getBasicBlock()));
734  delete BA;
735  }
736  }
738  ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
739  NewF->takeName(&F);
740  F.eraseFromParent();
741  *i = NewF;
742  addGlobalNamePrefix(NewF);
743  } else {
744  addGlobalNamePrefix(&F);
745  }
746  } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
747  // Build a wrapper function for F. The wrapper simply calls F, and is
748  // added to FnsToInstrument so that any instrumentation according to its
749  // WrapperKind is done in the second pass below.
750  FunctionType *NewFT = getInstrumentedABI() == IA_Args
751  ? getArgsFunctionType(FT)
752  : FT;
753  Function *NewF = buildWrapperFunction(
754  &F, std::string("dfsw$") + std::string(F.getName()),
755  GlobalValue::LinkOnceODRLinkage, NewFT);
756  if (getInstrumentedABI() == IA_TLS)
757  NewF->removeAttributes(AttributeList::FunctionIndex, ReadOnlyNoneAttrs);
758 
759  Value *WrappedFnCst =
760  ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
761  F.replaceAllUsesWith(WrappedFnCst);
762 
763  UnwrappedFnMap[WrappedFnCst] = &F;
764  *i = NewF;
765 
766  if (!F.isDeclaration()) {
767  // This function is probably defining an interposition of an
768  // uninstrumented function and hence needs to keep the original ABI.
769  // But any functions it may call need to use the instrumented ABI, so
770  // we instrument it in a mode which preserves the original ABI.
771  FnsWithNativeABI.insert(&F);
772 
773  // This code needs to rebuild the iterators, as they may be invalidated
774  // by the push_back, taking care that the new range does not include
775  // any functions added by this code.
776  size_t N = i - FnsToInstrument.begin(),
777  Count = e - FnsToInstrument.begin();
778  FnsToInstrument.push_back(&F);
779  i = FnsToInstrument.begin() + N;
780  e = FnsToInstrument.begin() + Count;
781  }
782  // Hopefully, nobody will try to indirectly call a vararg
783  // function... yet.
784  } else if (FT->isVarArg()) {
785  UnwrappedFnMap[&F] = &F;
786  *i = nullptr;
787  }
788  }
789 
790  for (Function *i : FnsToInstrument) {
791  if (!i || i->isDeclaration())
792  continue;
793 
795 
796  DFSanFunction DFSF(*this, i, FnsWithNativeABI.count(i));
797 
798  // DFSanVisitor may create new basic blocks, which confuses df_iterator.
799  // Build a copy of the list before iterating over it.
800  llvm::SmallVector<BasicBlock *, 4> BBList(depth_first(&i->getEntryBlock()));
801 
802  for (BasicBlock *i : BBList) {
803  Instruction *Inst = &i->front();
804  while (1) {
805  // DFSanVisitor may split the current basic block, changing the current
806  // instruction's next pointer and moving the next instruction to the
807  // tail block from which we should continue.
808  Instruction *Next = Inst->getNextNode();
809  // DFSanVisitor may delete Inst, so keep track of whether it was a
810  // terminator.
811  bool IsTerminator = isa<TerminatorInst>(Inst);
812  if (!DFSF.SkipInsts.count(Inst))
813  DFSanVisitor(DFSF).visit(Inst);
814  if (IsTerminator)
815  break;
816  Inst = Next;
817  }
818  }
819 
820  // We will not necessarily be able to compute the shadow for every phi node
821  // until we have visited every block. Therefore, the code that handles phi
822  // nodes adds them to the PHIFixups list so that they can be properly
823  // handled here.
824  for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
825  i = DFSF.PHIFixups.begin(),
826  e = DFSF.PHIFixups.end();
827  i != e; ++i) {
828  for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
829  ++val) {
830  i->second->setIncomingValue(
831  val, DFSF.getShadow(i->first->getIncomingValue(val)));
832  }
833  }
834 
835  // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
836  // places (i.e. instructions in basic blocks we haven't even begun visiting
837  // yet). To make our life easier, do this work in a pass after the main
838  // instrumentation.
839  if (ClDebugNonzeroLabels) {
840  for (Value *V : DFSF.NonZeroChecks) {
841  Instruction *Pos;
842  if (Instruction *I = dyn_cast<Instruction>(V))
843  Pos = I->getNextNode();
844  else
845  Pos = &DFSF.F->getEntryBlock().front();
846  while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
847  Pos = Pos->getNextNode();
848  IRBuilder<> IRB(Pos);
849  Value *Ne = IRB.CreateICmpNE(V, DFSF.DFS.ZeroShadow);
850  BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
851  Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
852  IRBuilder<> ThenIRB(BI);
853  ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn, {});
854  }
855  }
856  }
857 
858  return false;
859 }
860 
861 Value *DFSanFunction::getArgTLSPtr() {
862  if (ArgTLSPtr)
863  return ArgTLSPtr;
864  if (DFS.ArgTLS)
865  return ArgTLSPtr = DFS.ArgTLS;
866 
867  IRBuilder<> IRB(&F->getEntryBlock().front());
868  return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS, {});
869 }
870 
871 Value *DFSanFunction::getRetvalTLS() {
872  if (RetvalTLSPtr)
873  return RetvalTLSPtr;
874  if (DFS.RetvalTLS)
875  return RetvalTLSPtr = DFS.RetvalTLS;
876 
877  IRBuilder<> IRB(&F->getEntryBlock().front());
878  return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS, {});
879 }
880 
881 Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
882  IRBuilder<> IRB(Pos);
883  return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
884 }
885 
886 Value *DFSanFunction::getShadow(Value *V) {
887  if (!isa<Argument>(V) && !isa<Instruction>(V))
888  return DFS.ZeroShadow;
889  Value *&Shadow = ValShadowMap[V];
890  if (!Shadow) {
891  if (Argument *A = dyn_cast<Argument>(V)) {
892  if (IsNativeABI)
893  return DFS.ZeroShadow;
894  switch (IA) {
895  case DataFlowSanitizer::IA_TLS: {
896  Value *ArgTLSPtr = getArgTLSPtr();
897  Instruction *ArgTLSPos =
898  DFS.ArgTLS ? &*F->getEntryBlock().begin()
899  : cast<Instruction>(ArgTLSPtr)->getNextNode();
900  IRBuilder<> IRB(ArgTLSPos);
901  Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
902  break;
903  }
904  case DataFlowSanitizer::IA_Args: {
905  unsigned ArgIdx = A->getArgNo() + F->arg_size() / 2;
907  while (ArgIdx--)
908  ++i;
909  Shadow = &*i;
910  assert(Shadow->getType() == DFS.ShadowTy);
911  break;
912  }
913  }
914  NonZeroChecks.push_back(Shadow);
915  } else {
916  Shadow = DFS.ZeroShadow;
917  }
918  }
919  return Shadow;
920 }
921 
922 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
923  assert(!ValShadowMap.count(I));
924  assert(Shadow->getType() == DFS.ShadowTy);
925  ValShadowMap[I] = Shadow;
926 }
927 
928 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
929  assert(Addr != RetvalTLS && "Reinstrumenting?");
930  IRBuilder<> IRB(Pos);
931  Value *ShadowPtrMaskValue;
932  if (DFSanRuntimeShadowMask)
933  ShadowPtrMaskValue = IRB.CreateLoad(IntptrTy, ExternalShadowMask);
934  else
935  ShadowPtrMaskValue = ShadowPtrMask;
936  return IRB.CreateIntToPtr(
937  IRB.CreateMul(
938  IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy),
939  IRB.CreatePtrToInt(ShadowPtrMaskValue, IntptrTy)),
940  ShadowPtrMul),
941  ShadowPtrTy);
942 }
943 
944 // Generates IR to compute the union of the two given shadows, inserting it
945 // before Pos. Returns the computed union Value.
946 Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
947  if (V1 == DFS.ZeroShadow)
948  return V2;
949  if (V2 == DFS.ZeroShadow)
950  return V1;
951  if (V1 == V2)
952  return V1;
953 
954  auto V1Elems = ShadowElements.find(V1);
955  auto V2Elems = ShadowElements.find(V2);
956  if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
957  if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
958  V2Elems->second.begin(), V2Elems->second.end())) {
959  return V1;
960  } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
961  V1Elems->second.begin(), V1Elems->second.end())) {
962  return V2;
963  }
964  } else if (V1Elems != ShadowElements.end()) {
965  if (V1Elems->second.count(V2))
966  return V1;
967  } else if (V2Elems != ShadowElements.end()) {
968  if (V2Elems->second.count(V1))
969  return V2;
970  }
971 
972  auto Key = std::make_pair(V1, V2);
973  if (V1 > V2)
974  std::swap(Key.first, Key.second);
975  CachedCombinedShadow &CCS = CachedCombinedShadows[Key];
976  if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
977  return CCS.Shadow;
978 
979  IRBuilder<> IRB(Pos);
980  if (AvoidNewBlocks) {
981  CallInst *Call = IRB.CreateCall(DFS.DFSanCheckedUnionFn, {V1, V2});
982  Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
983  Call->addParamAttr(0, Attribute::ZExt);
984  Call->addParamAttr(1, Attribute::ZExt);
985 
986  CCS.Block = Pos->getParent();
987  CCS.Shadow = Call;
988  } else {
989  BasicBlock *Head = Pos->getParent();
990  Value *Ne = IRB.CreateICmpNE(V1, V2);
991  BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
992  Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
993  IRBuilder<> ThenIRB(BI);
994  CallInst *Call = ThenIRB.CreateCall(DFS.DFSanUnionFn, {V1, V2});
995  Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
996  Call->addParamAttr(0, Attribute::ZExt);
997  Call->addParamAttr(1, Attribute::ZExt);
998 
999  BasicBlock *Tail = BI->getSuccessor(0);
1000  PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1001  Phi->addIncoming(Call, Call->getParent());
1002  Phi->addIncoming(V1, Head);
1003 
1004  CCS.Block = Tail;
1005  CCS.Shadow = Phi;
1006  }
1007 
1008  std::set<Value *> UnionElems;
1009  if (V1Elems != ShadowElements.end()) {
1010  UnionElems = V1Elems->second;
1011  } else {
1012  UnionElems.insert(V1);
1013  }
1014  if (V2Elems != ShadowElements.end()) {
1015  UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
1016  } else {
1017  UnionElems.insert(V2);
1018  }
1019  ShadowElements[CCS.Shadow] = std::move(UnionElems);
1020 
1021  return CCS.Shadow;
1022 }
1023 
1024 // A convenience function which folds the shadows of each of the operands
1025 // of the provided instruction Inst, inserting the IR before Inst. Returns
1026 // the computed union Value.
1027 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
1028  if (Inst->getNumOperands() == 0)
1029  return DFS.ZeroShadow;
1030 
1031  Value *Shadow = getShadow(Inst->getOperand(0));
1032  for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
1033  Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
1034  }
1035  return Shadow;
1036 }
1037 
1038 void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
1039  Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1040  DFSF.setShadow(&I, CombinedShadow);
1041 }
1042 
1043 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
1044 // Addr has alignment Align, and take the union of each of those shadows.
1045 Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
1046  Instruction *Pos) {
1047  if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1049  AllocaShadowMap.find(AI);
1050  if (i != AllocaShadowMap.end()) {
1051  IRBuilder<> IRB(Pos);
1052  return IRB.CreateLoad(i->second);
1053  }
1054  }
1055 
1056  uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1058  GetUnderlyingObjects(Addr, Objs, Pos->getModule()->getDataLayout());
1059  bool AllConstants = true;
1060  for (Value *Obj : Objs) {
1061  if (isa<Function>(Obj) || isa<BlockAddress>(Obj))
1062  continue;
1063  if (isa<GlobalVariable>(Obj) && cast<GlobalVariable>(Obj)->isConstant())
1064  continue;
1065 
1066  AllConstants = false;
1067  break;
1068  }
1069  if (AllConstants)
1070  return DFS.ZeroShadow;
1071 
1072  Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1073  switch (Size) {
1074  case 0:
1075  return DFS.ZeroShadow;
1076  case 1: {
1077  LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
1078  LI->setAlignment(ShadowAlign);
1079  return LI;
1080  }
1081  case 2: {
1082  IRBuilder<> IRB(Pos);
1083  Value *ShadowAddr1 = IRB.CreateGEP(DFS.ShadowTy, ShadowAddr,
1084  ConstantInt::get(DFS.IntptrTy, 1));
1085  return combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
1086  IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign), Pos);
1087  }
1088  }
1089  if (!AvoidNewBlocks && Size % (64 / DFS.ShadowWidth) == 0) {
1090  // Fast path for the common case where each byte has identical shadow: load
1091  // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
1092  // shadow is non-equal.
1093  BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
1094  IRBuilder<> FallbackIRB(FallbackBB);
1095  CallInst *FallbackCall = FallbackIRB.CreateCall(
1096  DFS.DFSanUnionLoadFn,
1097  {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
1098  FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1099 
1100  // Compare each of the shadows stored in the loaded 64 bits to each other,
1101  // by computing (WideShadow rotl ShadowWidth) == WideShadow.
1102  IRBuilder<> IRB(Pos);
1103  Value *WideAddr =
1104  IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1105  Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1106  Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
1107  Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
1108  Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
1109  Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1110  Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1111 
1112  BasicBlock *Head = Pos->getParent();
1113  BasicBlock *Tail = Head->splitBasicBlock(Pos->getIterator());
1114 
1115  if (DomTreeNode *OldNode = DT.getNode(Head)) {
1116  std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1117 
1118  DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1119  for (auto Child : Children)
1120  DT.changeImmediateDominator(Child, NewNode);
1121  }
1122 
1123  // In the following code LastBr will refer to the previous basic block's
1124  // conditional branch instruction, whose true successor is fixed up to point
1125  // to the next block during the loop below or to the tail after the final
1126  // iteration.
1127  BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1128  ReplaceInstWithInst(Head->getTerminator(), LastBr);
1129  DT.addNewBlock(FallbackBB, Head);
1130 
1131  for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
1132  Ofs += 64 / DFS.ShadowWidth) {
1133  BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
1134  DT.addNewBlock(NextBB, LastBr->getParent());
1135  IRBuilder<> NextIRB(NextBB);
1136  WideAddr = NextIRB.CreateGEP(Type::getInt64Ty(*DFS.Ctx), WideAddr,
1137  ConstantInt::get(DFS.IntptrTy, 1));
1138  Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1139  ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1140  LastBr->setSuccessor(0, NextBB);
1141  LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1142  }
1143 
1144  LastBr->setSuccessor(0, Tail);
1145  FallbackIRB.CreateBr(Tail);
1146  PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1147  Shadow->addIncoming(FallbackCall, FallbackBB);
1148  Shadow->addIncoming(TruncShadow, LastBr->getParent());
1149  return Shadow;
1150  }
1151 
1152  IRBuilder<> IRB(Pos);
1153  CallInst *FallbackCall = IRB.CreateCall(
1154  DFS.DFSanUnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
1155  FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1156  return FallbackCall;
1157 }
1158 
1159 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
1160  auto &DL = LI.getModule()->getDataLayout();
1161  uint64_t Size = DL.getTypeStoreSize(LI.getType());
1162  if (Size == 0) {
1163  DFSF.setShadow(&LI, DFSF.DFS.ZeroShadow);
1164  return;
1165  }
1166 
1167  uint64_t Align;
1168  if (ClPreserveAlignment) {
1169  Align = LI.getAlignment();
1170  if (Align == 0)
1171  Align = DL.getABITypeAlignment(LI.getType());
1172  } else {
1173  Align = 1;
1174  }
1175  IRBuilder<> IRB(&LI);
1176  Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
1178  Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
1179  Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI);
1180  }
1181  if (Shadow != DFSF.DFS.ZeroShadow)
1182  DFSF.NonZeroChecks.push_back(Shadow);
1183 
1184  DFSF.setShadow(&LI, Shadow);
1185 }
1186 
1187 void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
1188  Value *Shadow, Instruction *Pos) {
1189  if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1191  AllocaShadowMap.find(AI);
1192  if (i != AllocaShadowMap.end()) {
1193  IRBuilder<> IRB(Pos);
1194  IRB.CreateStore(Shadow, i->second);
1195  return;
1196  }
1197  }
1198 
1199  uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1200  IRBuilder<> IRB(Pos);
1201  Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1202  if (Shadow == DFS.ZeroShadow) {
1203  IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1204  Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1205  Value *ExtShadowAddr =
1206  IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1207  IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1208  return;
1209  }
1210 
1211  const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1212  uint64_t Offset = 0;
1213  if (Size >= ShadowVecSize) {
1214  VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1215  Value *ShadowVec = UndefValue::get(ShadowVecTy);
1216  for (unsigned i = 0; i != ShadowVecSize; ++i) {
1217  ShadowVec = IRB.CreateInsertElement(
1218  ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1219  }
1220  Value *ShadowVecAddr =
1221  IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1222  do {
1223  Value *CurShadowVecAddr =
1224  IRB.CreateConstGEP1_32(ShadowVecTy, ShadowVecAddr, Offset);
1225  IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1226  Size -= ShadowVecSize;
1227  ++Offset;
1228  } while (Size >= ShadowVecSize);
1229  Offset *= ShadowVecSize;
1230  }
1231  while (Size > 0) {
1232  Value *CurShadowAddr =
1233  IRB.CreateConstGEP1_32(DFS.ShadowTy, ShadowAddr, Offset);
1234  IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1235  --Size;
1236  ++Offset;
1237  }
1238 }
1239 
1240 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
1241  auto &DL = SI.getModule()->getDataLayout();
1242  uint64_t Size = DL.getTypeStoreSize(SI.getValueOperand()->getType());
1243  if (Size == 0)
1244  return;
1245 
1246  uint64_t Align;
1247  if (ClPreserveAlignment) {
1248  Align = SI.getAlignment();
1249  if (Align == 0)
1250  Align = DL.getABITypeAlignment(SI.getValueOperand()->getType());
1251  } else {
1252  Align = 1;
1253  }
1254 
1255  Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1257  Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
1258  Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
1259  }
1260  DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
1261 }
1262 
1263 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1264  visitOperandShadowInst(BO);
1265 }
1266 
1267 void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1268 
1269 void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1270 
1271 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1272  visitOperandShadowInst(GEPI);
1273 }
1274 
1275 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1276  visitOperandShadowInst(I);
1277 }
1278 
1279 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1280  visitOperandShadowInst(I);
1281 }
1282 
1283 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1284  visitOperandShadowInst(I);
1285 }
1286 
1287 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1288  visitOperandShadowInst(I);
1289 }
1290 
1291 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1292  visitOperandShadowInst(I);
1293 }
1294 
1295 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1296  bool AllLoadsStores = true;
1297  for (User *U : I.users()) {
1298  if (isa<LoadInst>(U))
1299  continue;
1300 
1301  if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1302  if (SI->getPointerOperand() == &I)
1303  continue;
1304  }
1305 
1306  AllLoadsStores = false;
1307  break;
1308  }
1309  if (AllLoadsStores) {
1310  IRBuilder<> IRB(&I);
1311  DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1312  }
1313  DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1314 }
1315 
1316 void DFSanVisitor::visitSelectInst(SelectInst &I) {
1317  Value *CondShadow = DFSF.getShadow(I.getCondition());
1318  Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1319  Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1320 
1321  if (isa<VectorType>(I.getCondition()->getType())) {
1322  DFSF.setShadow(
1323  &I,
1324  DFSF.combineShadows(
1325  CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &I));
1326  } else {
1327  Value *ShadowSel;
1328  if (TrueShadow == FalseShadow) {
1329  ShadowSel = TrueShadow;
1330  } else {
1331  ShadowSel =
1332  SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1333  }
1334  DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I));
1335  }
1336 }
1337 
1338 void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1339  IRBuilder<> IRB(&I);
1340  Value *ValShadow = DFSF.getShadow(I.getValue());
1341  IRB.CreateCall(DFSF.DFS.DFSanSetLabelFn,
1342  {ValShadow, IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(
1343  *DFSF.DFS.Ctx)),
1344  IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
1345 }
1346 
1347 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1348  IRBuilder<> IRB(&I);
1349  Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1350  Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1351  Value *LenShadow = IRB.CreateMul(
1352  I.getLength(),
1353  ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
1354  Value *AlignShadow;
1355  if (ClPreserveAlignment) {
1356  AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1357  ConstantInt::get(I.getAlignmentCst()->getType(),
1358  DFSF.DFS.ShadowWidth / 8));
1359  } else {
1360  AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1361  DFSF.DFS.ShadowWidth / 8);
1362  }
1363  Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1364  DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1365  SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
1366  IRB.CreateCall(I.getCalledValue(), {DestShadow, SrcShadow, LenShadow,
1367  AlignShadow, I.getVolatileCst()});
1368 }
1369 
1370 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
1371  if (!DFSF.IsNativeABI && RI.getReturnValue()) {
1372  switch (DFSF.IA) {
1373  case DataFlowSanitizer::IA_TLS: {
1374  Value *S = DFSF.getShadow(RI.getReturnValue());
1375  IRBuilder<> IRB(&RI);
1376  IRB.CreateStore(S, DFSF.getRetvalTLS());
1377  break;
1378  }
1379  case DataFlowSanitizer::IA_Args: {
1380  IRBuilder<> IRB(&RI);
1381  Type *RT = DFSF.F->getFunctionType()->getReturnType();
1382  Value *InsVal =
1383  IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1384  Value *InsShadow =
1385  IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1386  RI.setOperand(0, InsShadow);
1387  break;
1388  }
1389  }
1390  }
1391 }
1392 
1393 void DFSanVisitor::visitCallSite(CallSite CS) {
1394  Function *F = CS.getCalledFunction();
1395  if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1396  visitOperandShadowInst(*CS.getInstruction());
1397  return;
1398  }
1399 
1400  // Calls to this function are synthesized in wrappers, and we shouldn't
1401  // instrument them.
1402  if (F == DFSF.DFS.DFSanVarargWrapperFn)
1403  return;
1404 
1405  IRBuilder<> IRB(CS.getInstruction());
1406 
1408  DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1409  if (i != DFSF.DFS.UnwrappedFnMap.end()) {
1410  Function *F = i->second;
1411  switch (DFSF.DFS.getWrapperKind(F)) {
1412  case DataFlowSanitizer::WK_Warning: {
1413  CS.setCalledFunction(F);
1414  IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1415  IRB.CreateGlobalStringPtr(F->getName()));
1416  DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1417  return;
1418  }
1419  case DataFlowSanitizer::WK_Discard: {
1420  CS.setCalledFunction(F);
1421  DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1422  return;
1423  }
1424  case DataFlowSanitizer::WK_Functional: {
1425  CS.setCalledFunction(F);
1426  visitOperandShadowInst(*CS.getInstruction());
1427  return;
1428  }
1429  case DataFlowSanitizer::WK_Custom: {
1430  // Don't try to handle invokes of custom functions, it's too complicated.
1431  // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1432  // wrapper.
1433  if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1434  FunctionType *FT = F->getFunctionType();
1435  FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1436  std::string CustomFName = "__dfsw_";
1437  CustomFName += F->getName();
1438  Constant *CustomF =
1439  DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1440  if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1441  CustomFn->copyAttributesFrom(F);
1442 
1443  // Custom functions returning non-void will write to the return label.
1444  if (!FT->getReturnType()->isVoidTy()) {
1445  CustomFn->removeAttributes(AttributeList::FunctionIndex,
1446  DFSF.DFS.ReadOnlyNoneAttrs);
1447  }
1448  }
1449 
1450  std::vector<Value *> Args;
1451 
1452  CallSite::arg_iterator i = CS.arg_begin();
1453  for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
1454  Type *T = (*i)->getType();
1455  FunctionType *ParamFT;
1456  if (isa<PointerType>(T) &&
1457  (ParamFT = dyn_cast<FunctionType>(
1458  cast<PointerType>(T)->getElementType()))) {
1459  std::string TName = "dfst";
1460  TName += utostr(FT->getNumParams() - n);
1461  TName += "$";
1462  TName += F->getName();
1463  Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1464  Args.push_back(T);
1465  Args.push_back(
1466  IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1467  } else {
1468  Args.push_back(*i);
1469  }
1470  }
1471 
1472  i = CS.arg_begin();
1473  const unsigned ShadowArgStart = Args.size();
1474  for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1475  Args.push_back(DFSF.getShadow(*i));
1476 
1477  if (FT->isVarArg()) {
1478  auto *LabelVATy = ArrayType::get(DFSF.DFS.ShadowTy,
1479  CS.arg_size() - FT->getNumParams());
1480  auto *LabelVAAlloca = new AllocaInst(
1481  LabelVATy, getDataLayout().getAllocaAddrSpace(),
1482  "labelva", &DFSF.F->getEntryBlock().front());
1483 
1484  for (unsigned n = 0; i != CS.arg_end(); ++i, ++n) {
1485  auto LabelVAPtr = IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, n);
1486  IRB.CreateStore(DFSF.getShadow(*i), LabelVAPtr);
1487  }
1488 
1489  Args.push_back(IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, 0));
1490  }
1491 
1492  if (!FT->getReturnType()->isVoidTy()) {
1493  if (!DFSF.LabelReturnAlloca) {
1494  DFSF.LabelReturnAlloca =
1495  new AllocaInst(DFSF.DFS.ShadowTy,
1496  getDataLayout().getAllocaAddrSpace(),
1497  "labelreturn", &DFSF.F->getEntryBlock().front());
1498  }
1499  Args.push_back(DFSF.LabelReturnAlloca);
1500  }
1501 
1502  for (i = CS.arg_begin() + FT->getNumParams(); i != CS.arg_end(); ++i)
1503  Args.push_back(*i);
1504 
1505  CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1506  CustomCI->setCallingConv(CI->getCallingConv());
1507  CustomCI->setAttributes(CI->getAttributes());
1508 
1509  // Update the parameter attributes of the custom call instruction to
1510  // zero extend the shadow parameters. This is required for targets
1511  // which consider ShadowTy an illegal type.
1512  for (unsigned n = 0; n < FT->getNumParams(); n++) {
1513  const unsigned ArgNo = ShadowArgStart + n;
1514  if (CustomCI->getArgOperand(ArgNo)->getType() == DFSF.DFS.ShadowTy)
1515  CustomCI->addParamAttr(ArgNo, Attribute::ZExt);
1516  }
1517 
1518  if (!FT->getReturnType()->isVoidTy()) {
1519  LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1520  DFSF.setShadow(CustomCI, LabelLoad);
1521  }
1522 
1523  CI->replaceAllUsesWith(CustomCI);
1524  CI->eraseFromParent();
1525  return;
1526  }
1527  break;
1528  }
1529  }
1530  }
1531 
1532  FunctionType *FT = cast<FunctionType>(
1534  if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1535  for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1536  IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1537  DFSF.getArgTLS(i, CS.getInstruction()));
1538  }
1539  }
1540 
1541  Instruction *Next = nullptr;
1542  if (!CS.getType()->isVoidTy()) {
1543  if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1544  if (II->getNormalDest()->getSinglePredecessor()) {
1545  Next = &II->getNormalDest()->front();
1546  } else {
1547  BasicBlock *NewBB =
1548  SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
1549  Next = &NewBB->front();
1550  }
1551  } else {
1552  assert(CS->getIterator() != CS->getParent()->end());
1553  Next = CS->getNextNode();
1554  }
1555 
1556  if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1557  IRBuilder<> NextIRB(Next);
1558  LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1559  DFSF.SkipInsts.insert(LI);
1560  DFSF.setShadow(CS.getInstruction(), LI);
1561  DFSF.NonZeroChecks.push_back(LI);
1562  }
1563  }
1564 
1565  // Do all instrumentation for IA_Args down here to defer tampering with the
1566  // CFG in a way that SplitEdge may be able to detect.
1567  if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1568  FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
1569  Value *Func =
1570  IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1571  std::vector<Value *> Args;
1572 
1573  CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1574  for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1575  Args.push_back(*i);
1576 
1577  i = CS.arg_begin();
1578  for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1579  Args.push_back(DFSF.getShadow(*i));
1580 
1581  if (FT->isVarArg()) {
1582  unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1583  ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1584  AllocaInst *VarArgShadow =
1585  new AllocaInst(VarArgArrayTy, getDataLayout().getAllocaAddrSpace(),
1586  "", &DFSF.F->getEntryBlock().front());
1587  Args.push_back(IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, 0));
1588  for (unsigned n = 0; i != e; ++i, ++n) {
1589  IRB.CreateStore(
1590  DFSF.getShadow(*i),
1591  IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, n));
1592  Args.push_back(*i);
1593  }
1594  }
1595 
1596  CallSite NewCS;
1597  if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1598  NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1599  Args);
1600  } else {
1601  NewCS = IRB.CreateCall(Func, Args);
1602  }
1603  NewCS.setCallingConv(CS.getCallingConv());
1605  *DFSF.DFS.Ctx, AttributeList::ReturnIndex,
1607 
1608  if (Next) {
1609  ExtractValueInst *ExVal =
1610  ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1611  DFSF.SkipInsts.insert(ExVal);
1612  ExtractValueInst *ExShadow =
1613  ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1614  DFSF.SkipInsts.insert(ExShadow);
1615  DFSF.setShadow(ExVal, ExShadow);
1616  DFSF.NonZeroChecks.push_back(ExShadow);
1617 
1618  CS.getInstruction()->replaceAllUsesWith(ExVal);
1619  }
1620 
1622  }
1623 }
1624 
1625 void DFSanVisitor::visitPHINode(PHINode &PN) {
1626  PHINode *ShadowPN =
1627  PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1628 
1629  // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1630  Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1631  for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1632  ++i) {
1633  ShadowPN->addIncoming(UndefShadow, *i);
1634  }
1635 
1636  DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1637  DFSF.setShadow(&PN, ShadowPN);
1638 }
IterTy arg_end() const
Definition: CallSite.h:549
const NoneType None
Definition: None.h:24
Return a value (possibly void), from a function.
Value * getValueOperand()
Definition: Instructions.h:395
const Value * getCalledValue() const
Get a pointer to the function that is invoked by this instruction.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:69
static cl::list< std::string > ClABIListFiles("dfsan-abilist", cl::desc("File listing native ABI functions and how the pass treats them"), cl::Hidden)
void push_back(const T &Elt)
Definition: SmallVector.h:211
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:109
LinkageTypes getLinkage() const
Definition: GlobalValue.h:430
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
Definition: Constants.h:172
void ReplaceInstWithInst(BasicBlock::InstListType &BIL, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
This class is the base class for the comparison instructions.
Definition: InstrTypes.h:850
static bool isConstant(const MachineInstr &MI)
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
This instruction extracts a struct member or array element value from an aggregate value...
size_t arg_size() const
Definition: Function.h:622
This class represents an incoming formal argument to a Function.
Definition: Argument.h:30
Base class for instruction visitors.
Definition: InstVisitor.h:81
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:289
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:103
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
adds the attribute to the list of attributes for the given arg.
Definition: Function.cpp:365
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Definition: DerivedTypes.h:139
ConstantInt * getAlignmentCst() const
Value * getValue() const
Return the arguments to the instruction.
Implements a dense probed hash-table based set.
Definition: DenseSet.h:221
unsigned getNumOperands() const
Definition: User.h:176
DataLayout DL
BBTy * getParent() const
Get the basic block containing the call site.
Definition: CallSite.h:94
Type * getValueType() const
Definition: GlobalValue.h:262
This class represents a function call, abstracting a target machine's calling convention.
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
Definition: Function.h:172
This instruction constructs a fixed permutation of two input vectors.
This class wraps the llvm.memset intrinsic.
arg_iterator arg_end()
Definition: Function.h:604
const Instruction & front() const
Definition: BasicBlock.h:264
Metadata node.
Definition: Metadata.h:862
An instruction for reading from memory.
Definition: Instructions.h:164
void GetUnderlyingObjects(Value *V, SmallVectorImpl< Value * > &Objects, const DataLayout &DL, LoopInfo *LI=nullptr, unsigned MaxLookup=6)
This method is similar to GetUnderlyingObject except that it can look through phi and select instruct...
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:233
Type * getPointerElementType() const
Definition: Type.h:373
unsigned arg_size() const
Definition: CallSite.h:216
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
Definition: Globals.cpp:432
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:218
block_iterator block_end()
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:252
void setCallingConv(CallingConv::ID CC)
static cl::opt< bool > ClArgsABI("dfsan-args-abi", cl::desc("Use the argument ABI rather than the TLS ABI"), cl::Hidden)
The address of a basic block.
Definition: Constants.h:813
This class represents the LLVM 'select' instruction.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
This is the base class for all instructions that perform data casts.
Definition: InstrTypes.h:560
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Definition: Function.h:150
Class to represent struct types.
Definition: DerivedTypes.h:201
param_iterator param_end() const
Definition: DerivedTypes.h:129
ValTy * getCalledValue() const
Return the pointer to function that is being called.
Definition: CallSite.h:97
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:664
void setThreadLocalMode(ThreadLocalMode Val)
Definition: GlobalValue.h:237
void setModuleInlineAsm(StringRef Asm)
Set the module-scope inline assembly blocks.
Definition: Module.h:273
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:284
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition: Module.h:208
static cl::opt< bool > ClCombinePointerLabelsOnStore("dfsan-combine-pointer-labels-on-store", cl::desc("Combine the label of the pointer with the label of the data when ""storing in memory."), cl::Hidden, cl::init(false))
block_iterator block_begin()
Class to represent function types.
Definition: DerivedTypes.h:103
#define F(x, y, z)
Definition: MD5.cpp:55
CallingConv::ID getCallingConv() const
Get the calling convention of the call.
Definition: CallSite.h:309
Class to represent array types.
Definition: DerivedTypes.h:369
BasicBlock * getSuccessor(unsigned i) const
Base class for the actual dominator tree node.
static std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:160
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
Definition: Triple.h:281
An instruction for storing to memory.
Definition: Instructions.h:306
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:428
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:290
iterator begin()
Definition: Function.h:580
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:134
Class to represent pointers.
Definition: DerivedTypes.h:467
unsigned getNumIncomingValues() const
Return the number of incoming edges.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
Definition: Instructions.h:837
Function Alias Analysis false
void setAttributes(AttributeList PAL)
Set the parameter attributes of the call.
Definition: CallSite.h:330
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:401
This instruction inserts a single (scalar) element into a VectorType value.
unsigned getAlignment() const
Return the alignment of the access that is being performed.
Definition: Instructions.h:351
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:137
Conditional or Unconditional Branch instruction.
This function has undefined behavior.
This is an important base class in LLVM.
Definition: Constant.h:42
const Value * getCondition() const
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition: Function.cpp:463
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
param_iterator param_begin() const
Definition: DerivedTypes.h:128
static const char *const kDFSanExternShadowPtrMask
#define A
Definition: LargeTest.cpp:12
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:372
void addAttribute(unsigned i, Attribute::AttrKind Kind)
adds the attribute to the list of attributes.
Definition: Function.cpp:347
void splice(iterator where, iplist_impl &L2)
Definition: ilist.h:342
const GlobalObject * getBaseObject() const
ConstantInt * getVolatileCst() const
void setCallingConv(CallingConv::ID CC)
Set the calling convention of the call.
Definition: CallSite.h:313
size_t size() const
Definition: Function.h:585
Value * getOperand(unsigned i) const
Definition: User.h:154
Value * getPointerOperand()
Definition: Instructions.h:270
AttributeList getAttributes() const
Get the parameter attributes of the call.
Definition: CallSite.h:326
arg_iterator arg_begin()
Definition: Function.h:595
self_iterator getIterator()
Definition: ilist_node.h:82
Class to represent integer types.
Definition: DerivedTypes.h:40
void setAlignment(unsigned Align)
Type * getType() const
Return the type of the instruction that generated this call site.
Definition: CallSite.h:261
MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight)
Return metadata containing two branch weights.
Definition: MDBuilder.cpp:37
const Value * getTrueValue() const
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
static void DFS(BasicBlock *Root, SetVector< BasicBlock * > &Set)
const std::string & getModuleInlineAsm() const
Get any module-scope inline assembly blocks.
Definition: Module.h:241
IterTy arg_begin() const
Definition: CallSite.h:545
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
Definition: DataLayout.cpp:700
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
Definition: DataLayout.cpp:680
Iterator for intrusive lists based on ilist_node.
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
Definition: Function.h:557
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:423
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
InstrTy * getInstruction() const
Definition: CallSite.h:89
Value * getDest() const
This is just like getRawDest, but it strips off any cast instructions that feed it, giving the original input.
iterator end()
Definition: BasicBlock.h:254
bool removeUnreachableBlocks(Function &F, LazyValueInfo *LVI=nullptr)
Remove all blocks that can not be reached from the function's entry.
Definition: Local.cpp:1669
ValTy * getArgument(unsigned ArgNo) const
Definition: CallSite.h:183
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:57
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
Type::subtype_iterator param_iterator
Definition: DerivedTypes.h:126
static ManagedStatic< CodeViewErrorCategory > Category
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:383
const DataFlowGraph & G
Definition: RDFGraph.cpp:206
TerminatorInst * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
static cl::opt< bool > ClDebugNonzeroLabels("dfsan-debug-nonzero-labels", cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, ""load or return with a nonzero label"), cl::Hidden)
const size_t N
Value * getLength() const
BasicBlock * getBasicBlock() const
Definition: Constants.h:840
const BasicBlock & getEntryBlock() const
Definition: Function.h:564
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:425
void setOperand(unsigned i, Value *Val)
Definition: User.h:159
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:923
static cl::opt< bool > ClPreserveAlignment("dfsan-preserve-alignment", cl::desc("respect alignment requirements provided by input IR"), cl::Hidden, cl::init(false))
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
Class to represent vector types.
Definition: DerivedTypes.h:393
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:48
INITIALIZE_PASS(DataFlowSanitizer,"dfsan","DataFlowSanitizer: dynamic data flow analysis.", false, false) ModulePass *llvm
iterator_range< user_iterator > users()
Definition: Value.h:395
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:395
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
AttributeList removeAttributes(LLVMContext &C, unsigned Index, const AttrBuilder &AttrsToRemove) const
Remove the specified attributes at the specified index from this attribute list.
Value * getSource() const
This is just like getRawSource, but it strips off any cast instructions that feed it...
void removeAttributes(unsigned i, const AttrBuilder &Attrs)
removes the attributes from the list of attributes.
Definition: Function.cpp:395
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:260
This class wraps the llvm.memcpy/memmove intrinsics.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.cpp:361
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:200
#define C
Definition: LargeTest.cpp:25
unsigned getAlignment() const
Return the alignment of the access that is being performed.
Definition: Instructions.h:226
AttributeList getAttributes() const
Return the parameter attributes for this call.
const NodeList & List
Definition: RDFGraph.cpp:205
#define I(x, y, z)
Definition: MD5.cpp:58
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:235
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
CallInst * CreateCall(Value *Callee, ArrayRef< Value * > Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1659
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
This instruction extracts a single (scalar) element from a VectorType value.
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
Definition: Function.cpp:202
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
Definition: BasicBlock.cpp:382
uint64_t getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
Definition: DataLayout.h:388
bool isVarArg() const
Definition: DerivedTypes.h:123
iterator_range< df_iterator< T > > depth_first(const T &G)
Type * getReturnType() const
Definition: DerivedTypes.h:124
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
Definition: Value.h:371
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it's an indirect...
Definition: CallSite.h:104
aarch64 promote const
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:545
LLVM Value Representation.
Definition: Value.h:73
AttrBuilder typeIncompatible(Type *Ty)
Which attributes cannot be applied to a type.
ModulePass * createDataFlowSanitizerPass(const std::vector< std::string > &ABIListFiles=std::vector< std::string >(), void *(*getArgTLS)()=nullptr, void *(*getRetValTLS)()=nullptr)
Invoke instruction.
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the edge connecting specified block.
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
Definition: Type.cpp:639
const Value * getFalseValue() const
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
CallingConv::ID getCallingConv() const
getCallingConv/setCallingConv - Get or set the calling convention of this function call...
void addAttribute(unsigned i, Attribute::AttrKind Kind)
adds the attribute to the list of attributes.
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:120
static cl::opt< bool > ClCombinePointerLabelsOnLoad("dfsan-combine-pointer-labels-on-load", cl::desc("Combine the label of the pointer with the label of the data when ""loading from memory."), cl::Hidden, cl::init(true))
Value * getPointerOperand()
Definition: Instructions.h:398
void setCalledFunction(Value *V)
Set the callee to the specified value.
Definition: CallSite.h:123
const BasicBlock * getParent() const
Definition: Instruction.h:66
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:237
bool isVoidTy() const
Return true if this is 'void'.
Definition: Type.h:141
an instruction to allocate memory on the stack
Definition: Instructions.h:60
This instruction inserts a struct field of array element value into an aggregate value.
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
user_iterator user_end()
Definition: Value.h:379