blob: 8ee5482ceaf7725cc9686236b91e223abfb8475d [file] [log] [blame]
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001//===-- 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/Transforms/Instrumentation.h"
48#include "llvm/ADT/DenseMap.h"
49#include "llvm/ADT/DenseSet.h"
50#include "llvm/ADT/DepthFirstIterator.h"
Peter Collingbourneffba4c72013-08-27 22:09:06 +000051#include "llvm/ADT/StringExtras.h"
Peter Collingbourne6fa33f52013-08-07 22:47:18 +000052#include "llvm/Analysis/ValueTracking.h"
53#include "llvm/IR/InlineAsm.h"
54#include "llvm/IR/IRBuilder.h"
55#include "llvm/IR/LLVMContext.h"
56#include "llvm/IR/MDBuilder.h"
57#include "llvm/IR/Type.h"
58#include "llvm/IR/Value.h"
59#include "llvm/InstVisitor.h"
60#include "llvm/Pass.h"
61#include "llvm/Support/CommandLine.h"
62#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Peter Collingbourneaaae6e92013-08-09 21:42:53 +000063#include "llvm/Transforms/Utils/Local.h"
Peter Collingbourne6fa33f52013-08-07 22:47:18 +000064#include "llvm/Transforms/Utils/SpecialCaseList.h"
65#include <iterator>
66
67using namespace llvm;
68
69// The -dfsan-preserve-alignment flag controls whether this pass assumes that
70// alignment requirements provided by the input IR are correct. For example,
71// if the input IR contains a load with alignment 8, this flag will cause
72// the shadow load to have alignment 16. This flag is disabled by default as
73// we have unfortunately encountered too much code (including Clang itself;
74// see PR14291) which performs misaligned access.
75static cl::opt<bool> ClPreserveAlignment(
76 "dfsan-preserve-alignment",
77 cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
78 cl::init(false));
79
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +000080// The ABI list file controls how shadow parameters are passed. The pass treats
81// every function labelled "uninstrumented" in the ABI list file as conforming
82// to the "native" (i.e. unsanitized) ABI. Unless the ABI list contains
83// additional annotations for those functions, a call to one of those functions
84// will produce a warning message, as the labelling behaviour of the function is
85// unknown. The other supported annotations are "functional" and "discard",
86// which are described below under DataFlowSanitizer::WrapperKind.
87static cl::opt<std::string> ClABIListFile(
88 "dfsan-abilist",
89 cl::desc("File listing native ABI functions and how the pass treats them"),
Peter Collingbourne6fa33f52013-08-07 22:47:18 +000090 cl::Hidden);
91
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +000092// Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
93// functions (see DataFlowSanitizer::InstrumentedABI below).
Peter Collingbourne6fa33f52013-08-07 22:47:18 +000094static cl::opt<bool> ClArgsABI(
95 "dfsan-args-abi",
96 cl::desc("Use the argument ABI rather than the TLS ABI"),
97 cl::Hidden);
98
Peter Collingbournea77d9f72013-08-15 18:51:12 +000099static cl::opt<bool> ClDebugNonzeroLabels(
100 "dfsan-debug-nonzero-labels",
101 cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
102 "load or return with a nonzero label"),
103 cl::Hidden);
104
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000105namespace {
106
107class DataFlowSanitizer : public ModulePass {
108 friend struct DFSanFunction;
109 friend class DFSanVisitor;
110
111 enum {
112 ShadowWidth = 16
113 };
114
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000115 /// Which ABI should be used for instrumented functions?
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000116 enum InstrumentedABI {
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000117 /// Argument and return value labels are passed through additional
118 /// arguments and by modifying the return type.
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000119 IA_Args,
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000120
121 /// Argument and return value labels are passed through TLS variables
122 /// __dfsan_arg_tls and __dfsan_retval_tls.
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000123 IA_TLS
124 };
125
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000126 /// How should calls to uninstrumented functions be handled?
127 enum WrapperKind {
128 /// This function is present in an uninstrumented form but we don't know
129 /// how it should be handled. Print a warning and call the function anyway.
130 /// Don't label the return value.
131 WK_Warning,
132
133 /// This function does not write to (user-accessible) memory, and its return
134 /// value is unlabelled.
135 WK_Discard,
136
137 /// This function does not write to (user-accessible) memory, and the label
138 /// of its return value is the union of the label of its arguments.
139 WK_Functional,
140
141 /// Instead of calling the function, a custom wrapper __dfsw_F is called,
142 /// where F is the name of the function. This function may wrap the
143 /// original function or provide its own implementation. This is similar to
144 /// the IA_Args ABI, except that IA_Args uses a struct return type to
145 /// pass the return value shadow in a register, while WK_Custom uses an
146 /// extra pointer argument to return the shadow. This allows the wrapped
147 /// form of the function type to be expressed in C.
148 WK_Custom
149 };
150
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000151 DataLayout *DL;
152 Module *Mod;
153 LLVMContext *Ctx;
154 IntegerType *ShadowTy;
155 PointerType *ShadowPtrTy;
156 IntegerType *IntptrTy;
157 ConstantInt *ZeroShadow;
158 ConstantInt *ShadowPtrMask;
159 ConstantInt *ShadowPtrMul;
160 Constant *ArgTLS;
161 Constant *RetvalTLS;
162 void *(*GetArgTLSPtr)();
163 void *(*GetRetvalTLSPtr)();
164 Constant *GetArgTLS;
165 Constant *GetRetvalTLS;
166 FunctionType *DFSanUnionFnTy;
167 FunctionType *DFSanUnionLoadFnTy;
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000168 FunctionType *DFSanUnimplementedFnTy;
Peter Collingbourneef8136d2013-08-14 20:51:38 +0000169 FunctionType *DFSanSetLabelFnTy;
Peter Collingbournea77d9f72013-08-15 18:51:12 +0000170 FunctionType *DFSanNonzeroLabelFnTy;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000171 Constant *DFSanUnionFn;
172 Constant *DFSanUnionLoadFn;
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000173 Constant *DFSanUnimplementedFn;
Peter Collingbourneef8136d2013-08-14 20:51:38 +0000174 Constant *DFSanSetLabelFn;
Peter Collingbournea77d9f72013-08-15 18:51:12 +0000175 Constant *DFSanNonzeroLabelFn;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000176 MDNode *ColdCallWeights;
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000177 OwningPtr<SpecialCaseList> ABIList;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000178 DenseMap<Value *, Function *> UnwrappedFnMap;
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000179 AttributeSet ReadOnlyNoneAttrs;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000180
181 Value *getShadowAddress(Value *Addr, Instruction *Pos);
182 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
Peter Collingbournef1366c52013-08-22 20:08:08 +0000183 bool isInstrumented(const Function *F);
184 bool isInstrumented(const GlobalAlias *GA);
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000185 FunctionType *getArgsFunctionType(FunctionType *T);
Peter Collingbourneffba4c72013-08-27 22:09:06 +0000186 FunctionType *getTrampolineFunctionType(FunctionType *T);
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000187 FunctionType *getCustomFunctionType(FunctionType *T);
188 InstrumentedABI getInstrumentedABI();
189 WrapperKind getWrapperKind(Function *F);
Peter Collingbournef1366c52013-08-22 20:08:08 +0000190 void addGlobalNamePrefix(GlobalValue *GV);
Peter Collingbourne4f68e9e2013-08-22 20:08:11 +0000191 Function *buildWrapperFunction(Function *F, StringRef NewFName,
192 GlobalValue::LinkageTypes NewFLink,
193 FunctionType *NewFT);
Peter Collingbourneffba4c72013-08-27 22:09:06 +0000194 Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000195
Dmitry Vyukova036a312013-08-13 16:52:41 +0000196 public:
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000197 DataFlowSanitizer(StringRef ABIListFile = StringRef(),
198 void *(*getArgTLS)() = 0, void *(*getRetValTLS)() = 0);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000199 static char ID;
200 bool doInitialization(Module &M);
201 bool runOnModule(Module &M);
202};
203
204struct DFSanFunction {
205 DataFlowSanitizer &DFS;
206 Function *F;
207 DataFlowSanitizer::InstrumentedABI IA;
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000208 bool IsNativeABI;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000209 Value *ArgTLSPtr;
210 Value *RetvalTLSPtr;
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000211 AllocaInst *LabelReturnAlloca;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000212 DenseMap<Value *, Value *> ValShadowMap;
213 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
214 std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
215 DenseSet<Instruction *> SkipInsts;
Peter Collingbournea77d9f72013-08-15 18:51:12 +0000216 DenseSet<Value *> NonZeroChecks;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000217
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000218 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
219 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()),
220 IsNativeABI(IsNativeABI), ArgTLSPtr(0), RetvalTLSPtr(0),
221 LabelReturnAlloca(0) {}
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000222 Value *getArgTLSPtr();
223 Value *getArgTLS(unsigned Index, Instruction *Pos);
224 Value *getRetvalTLS();
225 Value *getShadow(Value *V);
226 void setShadow(Instruction *I, Value *Shadow);
227 Value *combineOperandShadows(Instruction *Inst);
228 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
229 Instruction *Pos);
230 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
231 Instruction *Pos);
232};
233
234class DFSanVisitor : public InstVisitor<DFSanVisitor> {
Dmitry Vyukova036a312013-08-13 16:52:41 +0000235 public:
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000236 DFSanFunction &DFSF;
237 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
238
239 void visitOperandShadowInst(Instruction &I);
240
241 void visitBinaryOperator(BinaryOperator &BO);
242 void visitCastInst(CastInst &CI);
243 void visitCmpInst(CmpInst &CI);
244 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
245 void visitLoadInst(LoadInst &LI);
246 void visitStoreInst(StoreInst &SI);
247 void visitReturnInst(ReturnInst &RI);
248 void visitCallSite(CallSite CS);
249 void visitPHINode(PHINode &PN);
250 void visitExtractElementInst(ExtractElementInst &I);
251 void visitInsertElementInst(InsertElementInst &I);
252 void visitShuffleVectorInst(ShuffleVectorInst &I);
253 void visitExtractValueInst(ExtractValueInst &I);
254 void visitInsertValueInst(InsertValueInst &I);
255 void visitAllocaInst(AllocaInst &I);
256 void visitSelectInst(SelectInst &I);
Peter Collingbourneef8136d2013-08-14 20:51:38 +0000257 void visitMemSetInst(MemSetInst &I);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000258 void visitMemTransferInst(MemTransferInst &I);
259};
260
261}
262
263char DataFlowSanitizer::ID;
264INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
265 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
266
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000267ModulePass *llvm::createDataFlowSanitizerPass(StringRef ABIListFile,
268 void *(*getArgTLS)(),
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000269 void *(*getRetValTLS)()) {
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000270 return new DataFlowSanitizer(ABIListFile, getArgTLS, getRetValTLS);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000271}
272
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000273DataFlowSanitizer::DataFlowSanitizer(StringRef ABIListFile,
274 void *(*getArgTLS)(),
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000275 void *(*getRetValTLS)())
276 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS),
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000277 ABIList(SpecialCaseList::createOrDie(ABIListFile.empty() ? ClABIListFile
278 : ABIListFile)) {
279}
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000280
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000281FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000282 llvm::SmallVector<Type *, 4> ArgTypes;
283 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
284 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
285 ArgTypes.push_back(ShadowTy);
286 if (T->isVarArg())
287 ArgTypes.push_back(ShadowPtrTy);
288 Type *RetType = T->getReturnType();
289 if (!RetType->isVoidTy())
290 RetType = StructType::get(RetType, ShadowTy, (Type *)0);
291 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
292}
293
Peter Collingbourneffba4c72013-08-27 22:09:06 +0000294FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
295 assert(!T->isVarArg());
296 llvm::SmallVector<Type *, 4> ArgTypes;
297 ArgTypes.push_back(T->getPointerTo());
298 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
299 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
300 ArgTypes.push_back(ShadowTy);
301 Type *RetType = T->getReturnType();
302 if (!RetType->isVoidTy())
303 ArgTypes.push_back(ShadowPtrTy);
304 return FunctionType::get(T->getReturnType(), ArgTypes, false);
305}
306
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000307FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
308 assert(!T->isVarArg());
309 llvm::SmallVector<Type *, 4> ArgTypes;
Peter Collingbourneffba4c72013-08-27 22:09:06 +0000310 for (FunctionType::param_iterator i = T->param_begin(), e = T->param_end(); i != e; ++i) {
311 FunctionType *FT;
312 if (isa<PointerType>(*i) &&
313 (FT = dyn_cast<FunctionType>(cast<PointerType>(*i)->getElementType()))) {
314 ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
315 ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
316 } else {
317 ArgTypes.push_back(*i);
318 }
319 }
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000320 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
321 ArgTypes.push_back(ShadowTy);
322 Type *RetType = T->getReturnType();
323 if (!RetType->isVoidTy())
324 ArgTypes.push_back(ShadowPtrTy);
325 return FunctionType::get(T->getReturnType(), ArgTypes, false);
326}
327
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000328bool DataFlowSanitizer::doInitialization(Module &M) {
329 DL = getAnalysisIfAvailable<DataLayout>();
330 if (!DL)
331 return false;
332
333 Mod = &M;
334 Ctx = &M.getContext();
335 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
336 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
337 IntptrTy = DL->getIntPtrType(*Ctx);
338 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
Peter Collingbourne46c72c72013-08-08 00:15:27 +0000339 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000340 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
341
342 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
343 DFSanUnionFnTy =
344 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
345 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
346 DFSanUnionLoadFnTy =
347 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000348 DFSanUnimplementedFnTy = FunctionType::get(
349 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
Peter Collingbourneef8136d2013-08-14 20:51:38 +0000350 Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
351 DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
352 DFSanSetLabelArgs, /*isVarArg=*/false);
Peter Collingbournea77d9f72013-08-15 18:51:12 +0000353 DFSanNonzeroLabelFnTy = FunctionType::get(
354 Type::getVoidTy(*Ctx), ArrayRef<Type *>(), /*isVarArg=*/false);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000355
356 if (GetArgTLSPtr) {
357 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
358 ArgTLS = 0;
359 GetArgTLS = ConstantExpr::getIntToPtr(
360 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
361 PointerType::getUnqual(
362 FunctionType::get(PointerType::getUnqual(ArgTLSTy), (Type *)0)));
363 }
364 if (GetRetvalTLSPtr) {
365 RetvalTLS = 0;
366 GetRetvalTLS = ConstantExpr::getIntToPtr(
367 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
368 PointerType::getUnqual(
369 FunctionType::get(PointerType::getUnqual(ShadowTy), (Type *)0)));
370 }
371
372 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
373 return true;
374}
375
Peter Collingbournef1366c52013-08-22 20:08:08 +0000376bool DataFlowSanitizer::isInstrumented(const Function *F) {
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000377 return !ABIList->isIn(*F, "uninstrumented");
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000378}
379
Peter Collingbournef1366c52013-08-22 20:08:08 +0000380bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
381 return !ABIList->isIn(*GA, "uninstrumented");
382}
383
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000384DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000385 return ClArgsABI ? IA_Args : IA_TLS;
386}
387
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000388DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
389 if (ABIList->isIn(*F, "functional"))
390 return WK_Functional;
391 if (ABIList->isIn(*F, "discard"))
392 return WK_Discard;
393 if (ABIList->isIn(*F, "custom"))
394 return WK_Custom;
395
396 return WK_Warning;
397}
398
Peter Collingbournef1366c52013-08-22 20:08:08 +0000399void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
400 std::string GVName = GV->getName(), Prefix = "dfs$";
401 GV->setName(Prefix + GVName);
402
403 // Try to change the name of the function in module inline asm. We only do
404 // this for specific asm directives, currently only ".symver", to try to avoid
405 // corrupting asm which happens to contain the symbol name as a substring.
406 // Note that the substitution for .symver assumes that the versioned symbol
407 // also has an instrumented name.
408 std::string Asm = GV->getParent()->getModuleInlineAsm();
409 std::string SearchStr = ".symver " + GVName + ",";
410 size_t Pos = Asm.find(SearchStr);
411 if (Pos != std::string::npos) {
412 Asm.replace(Pos, SearchStr.size(),
413 ".symver " + Prefix + GVName + "," + Prefix);
414 GV->getParent()->setModuleInlineAsm(Asm);
415 }
416}
417
Peter Collingbourne4f68e9e2013-08-22 20:08:11 +0000418Function *
419DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
420 GlobalValue::LinkageTypes NewFLink,
421 FunctionType *NewFT) {
422 FunctionType *FT = F->getFunctionType();
423 Function *NewF = Function::Create(NewFT, NewFLink, NewFName,
424 F->getParent());
425 NewF->copyAttributesFrom(F);
426 NewF->removeAttributes(
427 AttributeSet::ReturnIndex,
428 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
429 AttributeSet::ReturnIndex));
430
431 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
432 std::vector<Value *> Args;
433 unsigned n = FT->getNumParams();
434 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
435 Args.push_back(&*ai);
436 CallInst *CI = CallInst::Create(F, Args, "", BB);
437 if (FT->getReturnType()->isVoidTy())
438 ReturnInst::Create(*Ctx, BB);
439 else
440 ReturnInst::Create(*Ctx, CI, BB);
441
442 return NewF;
443}
444
Peter Collingbourneffba4c72013-08-27 22:09:06 +0000445Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
446 StringRef FName) {
447 FunctionType *FTT = getTrampolineFunctionType(FT);
448 Constant *C = Mod->getOrInsertFunction(FName, FTT);
449 Function *F = dyn_cast<Function>(C);
450 if (F && F->isDeclaration()) {
451 F->setLinkage(GlobalValue::LinkOnceODRLinkage);
452 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
453 std::vector<Value *> Args;
454 Function::arg_iterator AI = F->arg_begin(); ++AI;
455 for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
456 Args.push_back(&*AI);
457 CallInst *CI =
458 CallInst::Create(&F->getArgumentList().front(), Args, "", BB);
459 ReturnInst *RI;
460 if (FT->getReturnType()->isVoidTy())
461 RI = ReturnInst::Create(*Ctx, BB);
462 else
463 RI = ReturnInst::Create(*Ctx, CI, BB);
464
465 DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
466 Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
467 for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
468 DFSF.ValShadowMap[ValAI] = ShadowAI;
469 DFSanVisitor(DFSF).visitCallInst(*CI);
470 if (!FT->getReturnType()->isVoidTy())
471 new StoreInst(DFSF.getShadow(RI->getReturnValue()),
472 &F->getArgumentList().back(), RI);
473 }
474
475 return C;
476}
477
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000478bool DataFlowSanitizer::runOnModule(Module &M) {
479 if (!DL)
480 return false;
481
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000482 if (ABIList->isIn(M, "skip"))
483 return false;
484
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000485 if (!GetArgTLSPtr) {
486 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
487 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
488 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
489 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
490 }
491 if (!GetRetvalTLSPtr) {
492 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
493 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
494 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
495 }
496
497 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
498 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
499 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
500 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
501 F->addAttribute(1, Attribute::ZExt);
502 F->addAttribute(2, Attribute::ZExt);
503 }
504 DFSanUnionLoadFn =
505 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
506 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
507 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
508 }
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000509 DFSanUnimplementedFn =
510 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
Peter Collingbourneef8136d2013-08-14 20:51:38 +0000511 DFSanSetLabelFn =
512 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
513 if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
514 F->addAttribute(1, Attribute::ZExt);
515 }
Peter Collingbournea77d9f72013-08-15 18:51:12 +0000516 DFSanNonzeroLabelFn =
517 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000518
519 std::vector<Function *> FnsToInstrument;
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000520 llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000521 for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000522 if (!i->isIntrinsic() &&
523 i != DFSanUnionFn &&
524 i != DFSanUnionLoadFn &&
Peter Collingbourneef8136d2013-08-14 20:51:38 +0000525 i != DFSanUnimplementedFn &&
Peter Collingbournea77d9f72013-08-15 18:51:12 +0000526 i != DFSanSetLabelFn &&
527 i != DFSanNonzeroLabelFn)
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000528 FnsToInstrument.push_back(&*i);
529 }
530
Peter Collingbourne054cec02013-08-22 20:08:15 +0000531 // Give function aliases prefixes when necessary, and build wrappers where the
532 // instrumentedness is inconsistent.
Peter Collingbournef1366c52013-08-22 20:08:08 +0000533 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
534 GlobalAlias *GA = &*i;
535 ++i;
536 // Don't stop on weak. We assume people aren't playing games with the
537 // instrumentedness of overridden weak aliases.
538 if (Function *F = dyn_cast<Function>(
539 GA->resolveAliasedGlobal(/*stopOnWeak=*/false))) {
540 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
541 if (GAInst && FInst) {
542 addGlobalNamePrefix(GA);
Peter Collingbourne054cec02013-08-22 20:08:15 +0000543 } else if (GAInst != FInst) {
544 // Non-instrumented alias of an instrumented function, or vice versa.
545 // Replace the alias with a native-ABI wrapper of the aliasee. The pass
546 // below will take care of instrumenting it.
547 Function *NewF =
548 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
549 GA->replaceAllUsesWith(NewF);
550 NewF->takeName(GA);
551 GA->eraseFromParent();
552 FnsToInstrument.push_back(NewF);
Peter Collingbournef1366c52013-08-22 20:08:08 +0000553 }
554 }
555 }
556
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000557 AttrBuilder B;
558 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
559 ReadOnlyNoneAttrs = AttributeSet::get(*Ctx, AttributeSet::FunctionIndex, B);
560
561 // First, change the ABI of every function in the module. ABI-listed
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000562 // functions keep their original ABI and get a wrapper function.
563 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
564 e = FnsToInstrument.end();
565 i != e; ++i) {
566 Function &F = **i;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000567 FunctionType *FT = F.getFunctionType();
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000568
Peter Collingbournef1366c52013-08-22 20:08:08 +0000569 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
570 FT->getReturnType()->isVoidTy());
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000571
572 if (isInstrumented(&F)) {
Peter Collingbournef1366c52013-08-22 20:08:08 +0000573 // Instrumented functions get a 'dfs$' prefix. This allows us to more
574 // easily identify cases of mismatching ABIs.
575 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000576 FunctionType *NewFT = getArgsFunctionType(FT);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000577 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000578 NewF->copyAttributesFrom(&F);
579 NewF->removeAttributes(
580 AttributeSet::ReturnIndex,
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000581 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000582 AttributeSet::ReturnIndex));
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000583 for (Function::arg_iterator FArg = F.arg_begin(),
584 NewFArg = NewF->arg_begin(),
585 FArgEnd = F.arg_end();
586 FArg != FArgEnd; ++FArg, ++NewFArg) {
587 FArg->replaceAllUsesWith(NewFArg);
588 }
589 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
590
591 for (Function::use_iterator ui = F.use_begin(), ue = F.use_end();
592 ui != ue;) {
593 BlockAddress *BA = dyn_cast<BlockAddress>(ui.getUse().getUser());
594 ++ui;
595 if (BA) {
596 BA->replaceAllUsesWith(
597 BlockAddress::get(NewF, BA->getBasicBlock()));
598 delete BA;
599 }
600 }
601 F.replaceAllUsesWith(
602 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
603 NewF->takeName(&F);
604 F.eraseFromParent();
605 *i = NewF;
Peter Collingbournef1366c52013-08-22 20:08:08 +0000606 addGlobalNamePrefix(NewF);
607 } else {
608 addGlobalNamePrefix(&F);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000609 }
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000610 // Hopefully, nobody will try to indirectly call a vararg
611 // function... yet.
612 } else if (FT->isVarArg()) {
613 UnwrappedFnMap[&F] = &F;
614 *i = 0;
Peter Collingbournef1366c52013-08-22 20:08:08 +0000615 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000616 // Build a wrapper function for F. The wrapper simply calls F, and is
617 // added to FnsToInstrument so that any instrumentation according to its
618 // WrapperKind is done in the second pass below.
619 FunctionType *NewFT = getInstrumentedABI() == IA_Args
620 ? getArgsFunctionType(FT)
621 : FT;
Alexey Samsonovbbe88b72013-08-23 07:42:51 +0000622 Function *NewF = buildWrapperFunction(
623 &F, std::string("dfsw$") + std::string(F.getName()),
624 GlobalValue::LinkOnceODRLinkage, NewFT);
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000625 if (getInstrumentedABI() == IA_TLS)
Peter Collingbourne4f68e9e2013-08-22 20:08:11 +0000626 NewF->removeAttributes(AttributeSet::FunctionIndex, ReadOnlyNoneAttrs);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000627
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000628 Value *WrappedFnCst =
629 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
630 F.replaceAllUsesWith(WrappedFnCst);
631 UnwrappedFnMap[WrappedFnCst] = &F;
632 *i = NewF;
633
634 if (!F.isDeclaration()) {
635 // This function is probably defining an interposition of an
636 // uninstrumented function and hence needs to keep the original ABI.
637 // But any functions it may call need to use the instrumented ABI, so
638 // we instrument it in a mode which preserves the original ABI.
639 FnsWithNativeABI.insert(&F);
640
641 // This code needs to rebuild the iterators, as they may be invalidated
642 // by the push_back, taking care that the new range does not include
643 // any functions added by this code.
644 size_t N = i - FnsToInstrument.begin(),
645 Count = e - FnsToInstrument.begin();
646 FnsToInstrument.push_back(&F);
647 i = FnsToInstrument.begin() + N;
648 e = FnsToInstrument.begin() + Count;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000649 }
650 }
651 }
652
653 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
654 e = FnsToInstrument.end();
655 i != e; ++i) {
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000656 if (!*i || (*i)->isDeclaration())
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000657 continue;
658
Peter Collingbourneaaae6e92013-08-09 21:42:53 +0000659 removeUnreachableBlocks(**i);
660
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000661 DFSanFunction DFSF(*this, *i, FnsWithNativeABI.count(*i));
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000662
663 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
664 // Build a copy of the list before iterating over it.
665 llvm::SmallVector<BasicBlock *, 4> BBList;
666 std::copy(df_begin(&(*i)->getEntryBlock()), df_end(&(*i)->getEntryBlock()),
667 std::back_inserter(BBList));
668
669 for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
670 e = BBList.end();
671 i != e; ++i) {
672 Instruction *Inst = &(*i)->front();
673 while (1) {
674 // DFSanVisitor may split the current basic block, changing the current
675 // instruction's next pointer and moving the next instruction to the
676 // tail block from which we should continue.
677 Instruction *Next = Inst->getNextNode();
Peter Collingbournea90d91f2013-08-12 22:38:39 +0000678 // DFSanVisitor may delete Inst, so keep track of whether it was a
679 // terminator.
680 bool IsTerminator = isa<TerminatorInst>(Inst);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000681 if (!DFSF.SkipInsts.count(Inst))
682 DFSanVisitor(DFSF).visit(Inst);
Peter Collingbournea90d91f2013-08-12 22:38:39 +0000683 if (IsTerminator)
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000684 break;
685 Inst = Next;
686 }
687 }
688
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000689 // We will not necessarily be able to compute the shadow for every phi node
690 // until we have visited every block. Therefore, the code that handles phi
691 // nodes adds them to the PHIFixups list so that they can be properly
692 // handled here.
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000693 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
694 i = DFSF.PHIFixups.begin(),
695 e = DFSF.PHIFixups.end();
696 i != e; ++i) {
697 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
698 ++val) {
699 i->second->setIncomingValue(
700 val, DFSF.getShadow(i->first->getIncomingValue(val)));
701 }
702 }
Peter Collingbournea77d9f72013-08-15 18:51:12 +0000703
704 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
705 // places (i.e. instructions in basic blocks we haven't even begun visiting
706 // yet). To make our life easier, do this work in a pass after the main
707 // instrumentation.
708 if (ClDebugNonzeroLabels) {
709 for (DenseSet<Value *>::iterator i = DFSF.NonZeroChecks.begin(),
710 e = DFSF.NonZeroChecks.end();
711 i != e; ++i) {
712 Instruction *Pos;
713 if (Instruction *I = dyn_cast<Instruction>(*i))
714 Pos = I->getNextNode();
715 else
716 Pos = DFSF.F->getEntryBlock().begin();
717 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
718 Pos = Pos->getNextNode();
719 IRBuilder<> IRB(Pos);
720 Instruction *NeInst = cast<Instruction>(
721 IRB.CreateICmpNE(*i, DFSF.DFS.ZeroShadow));
722 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
723 NeInst, /*Unreachable=*/ false, ColdCallWeights));
724 IRBuilder<> ThenIRB(BI);
725 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn);
726 }
727 }
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000728 }
729
730 return false;
731}
732
733Value *DFSanFunction::getArgTLSPtr() {
734 if (ArgTLSPtr)
735 return ArgTLSPtr;
736 if (DFS.ArgTLS)
737 return ArgTLSPtr = DFS.ArgTLS;
738
739 IRBuilder<> IRB(F->getEntryBlock().begin());
740 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
741}
742
743Value *DFSanFunction::getRetvalTLS() {
744 if (RetvalTLSPtr)
745 return RetvalTLSPtr;
746 if (DFS.RetvalTLS)
747 return RetvalTLSPtr = DFS.RetvalTLS;
748
749 IRBuilder<> IRB(F->getEntryBlock().begin());
750 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
751}
752
753Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
754 IRBuilder<> IRB(Pos);
755 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
756}
757
758Value *DFSanFunction::getShadow(Value *V) {
759 if (!isa<Argument>(V) && !isa<Instruction>(V))
760 return DFS.ZeroShadow;
761 Value *&Shadow = ValShadowMap[V];
762 if (!Shadow) {
763 if (Argument *A = dyn_cast<Argument>(V)) {
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000764 if (IsNativeABI)
765 return DFS.ZeroShadow;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000766 switch (IA) {
767 case DataFlowSanitizer::IA_TLS: {
768 Value *ArgTLSPtr = getArgTLSPtr();
769 Instruction *ArgTLSPos =
770 DFS.ArgTLS ? &*F->getEntryBlock().begin()
771 : cast<Instruction>(ArgTLSPtr)->getNextNode();
772 IRBuilder<> IRB(ArgTLSPos);
773 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
774 break;
775 }
776 case DataFlowSanitizer::IA_Args: {
777 unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
778 Function::arg_iterator i = F->arg_begin();
779 while (ArgIdx--)
780 ++i;
781 Shadow = i;
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000782 assert(Shadow->getType() == DFS.ShadowTy);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000783 break;
784 }
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000785 }
Peter Collingbournea77d9f72013-08-15 18:51:12 +0000786 NonZeroChecks.insert(Shadow);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000787 } else {
788 Shadow = DFS.ZeroShadow;
789 }
790 }
791 return Shadow;
792}
793
794void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
795 assert(!ValShadowMap.count(I));
796 assert(Shadow->getType() == DFS.ShadowTy);
797 ValShadowMap[I] = Shadow;
798}
799
800Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
801 assert(Addr != RetvalTLS && "Reinstrumenting?");
802 IRBuilder<> IRB(Pos);
803 return IRB.CreateIntToPtr(
804 IRB.CreateMul(
805 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
806 ShadowPtrMul),
807 ShadowPtrTy);
808}
809
810// Generates IR to compute the union of the two given shadows, inserting it
811// before Pos. Returns the computed union Value.
812Value *DataFlowSanitizer::combineShadows(Value *V1, Value *V2,
813 Instruction *Pos) {
814 if (V1 == ZeroShadow)
815 return V2;
816 if (V2 == ZeroShadow)
817 return V1;
818 if (V1 == V2)
819 return V1;
820 IRBuilder<> IRB(Pos);
821 BasicBlock *Head = Pos->getParent();
822 Value *Ne = IRB.CreateICmpNE(V1, V2);
823 Instruction *NeInst = dyn_cast<Instruction>(Ne);
824 if (NeInst) {
825 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
826 NeInst, /*Unreachable=*/ false, ColdCallWeights));
827 IRBuilder<> ThenIRB(BI);
828 CallInst *Call = ThenIRB.CreateCall2(DFSanUnionFn, V1, V2);
829 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
830 Call->addAttribute(1, Attribute::ZExt);
831 Call->addAttribute(2, Attribute::ZExt);
832
833 BasicBlock *Tail = BI->getSuccessor(0);
834 PHINode *Phi = PHINode::Create(ShadowTy, 2, "", Tail->begin());
835 Phi->addIncoming(Call, Call->getParent());
Peter Collingbournef3c03142013-08-23 18:45:06 +0000836 Phi->addIncoming(V1, Head);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000837 Pos = Phi;
838 return Phi;
839 } else {
840 assert(0 && "todo");
841 return 0;
842 }
843}
844
845// A convenience function which folds the shadows of each of the operands
846// of the provided instruction Inst, inserting the IR before Inst. Returns
847// the computed union Value.
848Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
849 if (Inst->getNumOperands() == 0)
850 return DFS.ZeroShadow;
851
852 Value *Shadow = getShadow(Inst->getOperand(0));
853 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
854 Shadow = DFS.combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
855 }
856 return Shadow;
857}
858
859void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
860 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
861 DFSF.setShadow(&I, CombinedShadow);
862}
863
864// Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
865// Addr has alignment Align, and take the union of each of those shadows.
866Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
867 Instruction *Pos) {
868 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
869 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
870 AllocaShadowMap.find(AI);
871 if (i != AllocaShadowMap.end()) {
872 IRBuilder<> IRB(Pos);
873 return IRB.CreateLoad(i->second);
874 }
875 }
876
877 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
878 SmallVector<Value *, 2> Objs;
879 GetUnderlyingObjects(Addr, Objs, DFS.DL);
880 bool AllConstants = true;
881 for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
882 i != e; ++i) {
883 if (isa<Function>(*i) || isa<BlockAddress>(*i))
884 continue;
885 if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
886 continue;
887
888 AllConstants = false;
889 break;
890 }
891 if (AllConstants)
892 return DFS.ZeroShadow;
893
894 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
895 switch (Size) {
896 case 0:
897 return DFS.ZeroShadow;
898 case 1: {
899 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
900 LI->setAlignment(ShadowAlign);
901 return LI;
902 }
903 case 2: {
904 IRBuilder<> IRB(Pos);
905 Value *ShadowAddr1 =
906 IRB.CreateGEP(ShadowAddr, ConstantInt::get(DFS.IntptrTy, 1));
907 return DFS.combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
908 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign),
909 Pos);
910 }
911 }
912 if (Size % (64 / DFS.ShadowWidth) == 0) {
913 // Fast path for the common case where each byte has identical shadow: load
914 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
915 // shadow is non-equal.
916 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
917 IRBuilder<> FallbackIRB(FallbackBB);
918 CallInst *FallbackCall = FallbackIRB.CreateCall2(
919 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
920 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
921
922 // Compare each of the shadows stored in the loaded 64 bits to each other,
923 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
924 IRBuilder<> IRB(Pos);
925 Value *WideAddr =
926 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
927 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
928 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
929 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
930 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
931 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
932 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
933
934 BasicBlock *Head = Pos->getParent();
935 BasicBlock *Tail = Head->splitBasicBlock(Pos);
936 // In the following code LastBr will refer to the previous basic block's
937 // conditional branch instruction, whose true successor is fixed up to point
938 // to the next block during the loop below or to the tail after the final
939 // iteration.
940 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
941 ReplaceInstWithInst(Head->getTerminator(), LastBr);
942
943 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
944 Ofs += 64 / DFS.ShadowWidth) {
945 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
946 IRBuilder<> NextIRB(NextBB);
947 WideAddr = NextIRB.CreateGEP(WideAddr, ConstantInt::get(DFS.IntptrTy, 1));
948 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
949 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
950 LastBr->setSuccessor(0, NextBB);
951 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
952 }
953
954 LastBr->setSuccessor(0, Tail);
955 FallbackIRB.CreateBr(Tail);
956 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
957 Shadow->addIncoming(FallbackCall, FallbackBB);
958 Shadow->addIncoming(TruncShadow, LastBr->getParent());
959 return Shadow;
960 }
961
962 IRBuilder<> IRB(Pos);
963 CallInst *FallbackCall = IRB.CreateCall2(
964 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
965 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
966 return FallbackCall;
967}
968
969void DFSanVisitor::visitLoadInst(LoadInst &LI) {
970 uint64_t Size = DFSF.DFS.DL->getTypeStoreSize(LI.getType());
971 uint64_t Align;
972 if (ClPreserveAlignment) {
973 Align = LI.getAlignment();
974 if (Align == 0)
975 Align = DFSF.DFS.DL->getABITypeAlignment(LI.getType());
976 } else {
977 Align = 1;
978 }
979 IRBuilder<> IRB(&LI);
980 Value *LoadedShadow =
981 DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
982 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
Peter Collingbournea77d9f72013-08-15 18:51:12 +0000983 Value *CombinedShadow = DFSF.DFS.combineShadows(LoadedShadow, PtrShadow, &LI);
984 if (CombinedShadow != DFSF.DFS.ZeroShadow)
985 DFSF.NonZeroChecks.insert(CombinedShadow);
986
987 DFSF.setShadow(&LI, CombinedShadow);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000988}
989
990void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
991 Value *Shadow, Instruction *Pos) {
992 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
993 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
994 AllocaShadowMap.find(AI);
995 if (i != AllocaShadowMap.end()) {
996 IRBuilder<> IRB(Pos);
997 IRB.CreateStore(Shadow, i->second);
998 return;
999 }
1000 }
1001
1002 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1003 IRBuilder<> IRB(Pos);
1004 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1005 if (Shadow == DFS.ZeroShadow) {
1006 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1007 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1008 Value *ExtShadowAddr =
1009 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1010 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1011 return;
1012 }
1013
1014 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1015 uint64_t Offset = 0;
1016 if (Size >= ShadowVecSize) {
1017 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1018 Value *ShadowVec = UndefValue::get(ShadowVecTy);
1019 for (unsigned i = 0; i != ShadowVecSize; ++i) {
1020 ShadowVec = IRB.CreateInsertElement(
1021 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1022 }
1023 Value *ShadowVecAddr =
1024 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1025 do {
1026 Value *CurShadowVecAddr = IRB.CreateConstGEP1_32(ShadowVecAddr, Offset);
1027 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1028 Size -= ShadowVecSize;
1029 ++Offset;
1030 } while (Size >= ShadowVecSize);
1031 Offset *= ShadowVecSize;
1032 }
1033 while (Size > 0) {
1034 Value *CurShadowAddr = IRB.CreateConstGEP1_32(ShadowAddr, Offset);
1035 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1036 --Size;
1037 ++Offset;
1038 }
1039}
1040
1041void DFSanVisitor::visitStoreInst(StoreInst &SI) {
1042 uint64_t Size =
1043 DFSF.DFS.DL->getTypeStoreSize(SI.getValueOperand()->getType());
1044 uint64_t Align;
1045 if (ClPreserveAlignment) {
1046 Align = SI.getAlignment();
1047 if (Align == 0)
1048 Align = DFSF.DFS.DL->getABITypeAlignment(SI.getValueOperand()->getType());
1049 } else {
1050 Align = 1;
1051 }
1052 DFSF.storeShadow(SI.getPointerOperand(), Size, Align,
1053 DFSF.getShadow(SI.getValueOperand()), &SI);
1054}
1055
1056void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1057 visitOperandShadowInst(BO);
1058}
1059
1060void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1061
1062void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1063
1064void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1065 visitOperandShadowInst(GEPI);
1066}
1067
1068void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1069 visitOperandShadowInst(I);
1070}
1071
1072void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1073 visitOperandShadowInst(I);
1074}
1075
1076void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1077 visitOperandShadowInst(I);
1078}
1079
1080void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1081 visitOperandShadowInst(I);
1082}
1083
1084void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1085 visitOperandShadowInst(I);
1086}
1087
1088void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1089 bool AllLoadsStores = true;
1090 for (Instruction::use_iterator i = I.use_begin(), e = I.use_end(); i != e;
1091 ++i) {
1092 if (isa<LoadInst>(*i))
1093 continue;
1094
1095 if (StoreInst *SI = dyn_cast<StoreInst>(*i)) {
1096 if (SI->getPointerOperand() == &I)
1097 continue;
1098 }
1099
1100 AllLoadsStores = false;
1101 break;
1102 }
1103 if (AllLoadsStores) {
1104 IRBuilder<> IRB(&I);
1105 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1106 }
1107 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1108}
1109
1110void DFSanVisitor::visitSelectInst(SelectInst &I) {
1111 Value *CondShadow = DFSF.getShadow(I.getCondition());
1112 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1113 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1114
1115 if (isa<VectorType>(I.getCondition()->getType())) {
1116 DFSF.setShadow(
1117 &I, DFSF.DFS.combineShadows(
1118 CondShadow,
1119 DFSF.DFS.combineShadows(TrueShadow, FalseShadow, &I), &I));
1120 } else {
1121 Value *ShadowSel;
1122 if (TrueShadow == FalseShadow) {
1123 ShadowSel = TrueShadow;
1124 } else {
1125 ShadowSel =
1126 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1127 }
1128 DFSF.setShadow(&I, DFSF.DFS.combineShadows(CondShadow, ShadowSel, &I));
1129 }
1130}
1131
Peter Collingbourneef8136d2013-08-14 20:51:38 +00001132void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1133 IRBuilder<> IRB(&I);
1134 Value *ValShadow = DFSF.getShadow(I.getValue());
1135 IRB.CreateCall3(
1136 DFSF.DFS.DFSanSetLabelFn, ValShadow,
1137 IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
1138 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy));
1139}
1140
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001141void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1142 IRBuilder<> IRB(&I);
1143 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1144 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1145 Value *LenShadow = IRB.CreateMul(
1146 I.getLength(),
1147 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
1148 Value *AlignShadow;
1149 if (ClPreserveAlignment) {
1150 AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1151 ConstantInt::get(I.getAlignmentCst()->getType(),
1152 DFSF.DFS.ShadowWidth / 8));
1153 } else {
1154 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1155 DFSF.DFS.ShadowWidth / 8);
1156 }
1157 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1158 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1159 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
1160 IRB.CreateCall5(I.getCalledValue(), DestShadow, SrcShadow, LenShadow,
1161 AlignShadow, I.getVolatileCst());
1162}
1163
1164void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +00001165 if (!DFSF.IsNativeABI && RI.getReturnValue()) {
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001166 switch (DFSF.IA) {
1167 case DataFlowSanitizer::IA_TLS: {
1168 Value *S = DFSF.getShadow(RI.getReturnValue());
1169 IRBuilder<> IRB(&RI);
1170 IRB.CreateStore(S, DFSF.getRetvalTLS());
1171 break;
1172 }
1173 case DataFlowSanitizer::IA_Args: {
1174 IRBuilder<> IRB(&RI);
1175 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1176 Value *InsVal =
1177 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1178 Value *InsShadow =
1179 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1180 RI.setOperand(0, InsShadow);
1181 break;
1182 }
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001183 }
1184 }
1185}
1186
1187void DFSanVisitor::visitCallSite(CallSite CS) {
1188 Function *F = CS.getCalledFunction();
1189 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1190 visitOperandShadowInst(*CS.getInstruction());
1191 return;
1192 }
1193
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +00001194 IRBuilder<> IRB(CS.getInstruction());
1195
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001196 DenseMap<Value *, Function *>::iterator i =
1197 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1198 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +00001199 Function *F = i->second;
1200 switch (DFSF.DFS.getWrapperKind(F)) {
1201 case DataFlowSanitizer::WK_Warning: {
1202 CS.setCalledFunction(F);
1203 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1204 IRB.CreateGlobalStringPtr(F->getName()));
1205 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1206 return;
1207 }
1208 case DataFlowSanitizer::WK_Discard: {
1209 CS.setCalledFunction(F);
1210 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1211 return;
1212 }
1213 case DataFlowSanitizer::WK_Functional: {
1214 CS.setCalledFunction(F);
1215 visitOperandShadowInst(*CS.getInstruction());
1216 return;
1217 }
1218 case DataFlowSanitizer::WK_Custom: {
1219 // Don't try to handle invokes of custom functions, it's too complicated.
1220 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1221 // wrapper.
1222 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1223 FunctionType *FT = F->getFunctionType();
1224 FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1225 std::string CustomFName = "__dfsw_";
1226 CustomFName += F->getName();
1227 Constant *CustomF =
1228 DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1229 if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1230 CustomFn->copyAttributesFrom(F);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001231
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +00001232 // Custom functions returning non-void will write to the return label.
1233 if (!FT->getReturnType()->isVoidTy()) {
1234 CustomFn->removeAttributes(AttributeSet::FunctionIndex,
1235 DFSF.DFS.ReadOnlyNoneAttrs);
1236 }
1237 }
1238
1239 std::vector<Value *> Args;
1240
1241 CallSite::arg_iterator i = CS.arg_begin();
Peter Collingbourneffba4c72013-08-27 22:09:06 +00001242 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
1243 Type *T = (*i)->getType();
1244 FunctionType *ParamFT;
1245 if (isa<PointerType>(T) &&
1246 (ParamFT = dyn_cast<FunctionType>(
1247 cast<PointerType>(T)->getElementType()))) {
1248 std::string TName = "dfst";
1249 TName += utostr(FT->getNumParams() - n);
1250 TName += "$";
1251 TName += F->getName();
1252 Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1253 Args.push_back(T);
1254 Args.push_back(
1255 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1256 } else {
1257 Args.push_back(*i);
1258 }
1259 }
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +00001260
1261 i = CS.arg_begin();
1262 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1263 Args.push_back(DFSF.getShadow(*i));
1264
1265 if (!FT->getReturnType()->isVoidTy()) {
1266 if (!DFSF.LabelReturnAlloca) {
1267 DFSF.LabelReturnAlloca =
1268 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
1269 DFSF.F->getEntryBlock().begin());
1270 }
1271 Args.push_back(DFSF.LabelReturnAlloca);
1272 }
1273
1274 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1275 CustomCI->setCallingConv(CI->getCallingConv());
1276 CustomCI->setAttributes(CI->getAttributes());
1277
1278 if (!FT->getReturnType()->isVoidTy()) {
1279 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1280 DFSF.setShadow(CustomCI, LabelLoad);
1281 }
1282
1283 CI->replaceAllUsesWith(CustomCI);
1284 CI->eraseFromParent();
1285 return;
1286 }
1287 break;
1288 }
1289 }
1290 }
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001291
1292 FunctionType *FT = cast<FunctionType>(
1293 CS.getCalledValue()->getType()->getPointerElementType());
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +00001294 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001295 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1296 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1297 DFSF.getArgTLS(i, CS.getInstruction()));
1298 }
1299 }
1300
1301 Instruction *Next = 0;
1302 if (!CS.getType()->isVoidTy()) {
1303 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1304 if (II->getNormalDest()->getSinglePredecessor()) {
1305 Next = II->getNormalDest()->begin();
1306 } else {
1307 BasicBlock *NewBB =
1308 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DFS);
1309 Next = NewBB->begin();
1310 }
1311 } else {
1312 Next = CS->getNextNode();
1313 }
1314
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +00001315 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001316 IRBuilder<> NextIRB(Next);
1317 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1318 DFSF.SkipInsts.insert(LI);
1319 DFSF.setShadow(CS.getInstruction(), LI);
Peter Collingbournea77d9f72013-08-15 18:51:12 +00001320 DFSF.NonZeroChecks.insert(LI);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001321 }
1322 }
1323
1324 // Do all instrumentation for IA_Args down here to defer tampering with the
1325 // CFG in a way that SplitEdge may be able to detect.
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +00001326 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1327 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001328 Value *Func =
1329 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1330 std::vector<Value *> Args;
1331
1332 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1333 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1334 Args.push_back(*i);
1335
1336 i = CS.arg_begin();
1337 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1338 Args.push_back(DFSF.getShadow(*i));
1339
1340 if (FT->isVarArg()) {
1341 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1342 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1343 AllocaInst *VarArgShadow =
1344 new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
1345 Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
1346 for (unsigned n = 0; i != e; ++i, ++n) {
1347 IRB.CreateStore(DFSF.getShadow(*i),
1348 IRB.CreateConstGEP2_32(VarArgShadow, 0, n));
1349 Args.push_back(*i);
1350 }
1351 }
1352
1353 CallSite NewCS;
1354 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1355 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1356 Args);
1357 } else {
1358 NewCS = IRB.CreateCall(Func, Args);
1359 }
1360 NewCS.setCallingConv(CS.getCallingConv());
1361 NewCS.setAttributes(CS.getAttributes().removeAttributes(
1362 *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
1363 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType(),
1364 AttributeSet::ReturnIndex)));
1365
1366 if (Next) {
1367 ExtractValueInst *ExVal =
1368 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1369 DFSF.SkipInsts.insert(ExVal);
1370 ExtractValueInst *ExShadow =
1371 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1372 DFSF.SkipInsts.insert(ExShadow);
1373 DFSF.setShadow(ExVal, ExShadow);
Peter Collingbournea77d9f72013-08-15 18:51:12 +00001374 DFSF.NonZeroChecks.insert(ExShadow);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001375
1376 CS.getInstruction()->replaceAllUsesWith(ExVal);
1377 }
1378
1379 CS.getInstruction()->eraseFromParent();
1380 }
1381}
1382
1383void DFSanVisitor::visitPHINode(PHINode &PN) {
1384 PHINode *ShadowPN =
1385 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1386
1387 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1388 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1389 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1390 ++i) {
1391 ShadowPN->addIncoming(UndefShadow, *i);
1392 }
1393
1394 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1395 DFSF.setShadow(&PN, ShadowPN);
1396}