blob: 799e14bdac310950ee87bc153066d7d04a2b4580 [file] [log] [blame]
Peter Collingbournee5d5b0c2013-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 Collingbourne28a10af2013-08-27 22:09:06 +000051#include "llvm/ADT/StringExtras.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000052#include "llvm/Analysis/ValueTracking.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000053#include "llvm/IR/IRBuilder.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000054#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000055#include "llvm/IR/InstVisitor.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000056#include "llvm/IR/LLVMContext.h"
57#include "llvm/IR/MDBuilder.h"
58#include "llvm/IR/Type.h"
59#include "llvm/IR/Value.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000060#include "llvm/Pass.h"
61#include "llvm/Support/CommandLine.h"
Alexey Samsonovb7dd3292014-07-09 19:40:08 +000062#include "llvm/Support/SpecialCaseList.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000063#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Peter Collingbourneae66d572013-08-09 21:42:53 +000064#include "llvm/Transforms/Utils/Local.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000065#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 Collingbourne68162e72013-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 Collingbournee5d5b0c2013-08-07 22:47:18 +000090 cl::Hidden);
91
Peter Collingbourne68162e72013-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 Collingbournee5d5b0c2013-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 Collingbourne0be79e12013-11-21 23:20:54 +000099// Controls whether the pass includes or ignores the labels of pointers in load
100// instructions.
101static cl::opt<bool> ClCombinePointerLabelsOnLoad(
102 "dfsan-combine-pointer-labels-on-load",
103 cl::desc("Combine the label of the pointer with the label of the data when "
104 "loading from memory."),
105 cl::Hidden, cl::init(true));
106
107// Controls whether the pass includes or ignores the labels of pointers in
108// stores instructions.
109static cl::opt<bool> ClCombinePointerLabelsOnStore(
110 "dfsan-combine-pointer-labels-on-store",
111 cl::desc("Combine the label of the pointer with the label of the data when "
112 "storing in memory."),
113 cl::Hidden, cl::init(false));
114
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000115static cl::opt<bool> ClDebugNonzeroLabels(
116 "dfsan-debug-nonzero-labels",
117 cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
118 "load or return with a nonzero label"),
119 cl::Hidden);
120
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000121namespace {
122
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000123StringRef GetGlobalTypeString(const GlobalValue &G) {
124 // Types of GlobalVariables are always pointer types.
125 Type *GType = G.getType()->getElementType();
126 // For now we support blacklisting struct types only.
127 if (StructType *SGType = dyn_cast<StructType>(GType)) {
128 if (!SGType->isLiteral())
129 return SGType->getName();
130 }
131 return "<unknown type>";
132}
133
134class DFSanABIList {
135 std::unique_ptr<SpecialCaseList> SCL;
136
137 public:
138 DFSanABIList(SpecialCaseList *SCL) : SCL(SCL) {}
139
140 /// Returns whether either this function or its source file are listed in the
141 /// given category.
142 bool isIn(const Function &F, const StringRef Category) const {
143 return isIn(*F.getParent(), Category) ||
144 SCL->inSection("fun", F.getName(), Category);
145 }
146
147 /// Returns whether this global alias is listed in the given category.
148 ///
149 /// If GA aliases a function, the alias's name is matched as a function name
150 /// would be. Similarly, aliases of globals are matched like globals.
151 bool isIn(const GlobalAlias &GA, const StringRef Category) const {
152 if (isIn(*GA.getParent(), Category))
153 return true;
154
155 if (isa<FunctionType>(GA.getType()->getElementType()))
156 return SCL->inSection("fun", GA.getName(), Category);
157
158 return SCL->inSection("global", GA.getName(), Category) ||
159 SCL->inSection("type", GetGlobalTypeString(GA), Category);
160 }
161
162 /// Returns whether this module is listed in the given category.
163 bool isIn(const Module &M, const StringRef Category) const {
164 return SCL->inSection("src", M.getModuleIdentifier(), Category);
165 }
166};
167
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000168class DataFlowSanitizer : public ModulePass {
169 friend struct DFSanFunction;
170 friend class DFSanVisitor;
171
172 enum {
173 ShadowWidth = 16
174 };
175
Peter Collingbourne68162e72013-08-14 18:54:12 +0000176 /// Which ABI should be used for instrumented functions?
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000177 enum InstrumentedABI {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000178 /// Argument and return value labels are passed through additional
179 /// arguments and by modifying the return type.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000180 IA_Args,
Peter Collingbourne68162e72013-08-14 18:54:12 +0000181
182 /// Argument and return value labels are passed through TLS variables
183 /// __dfsan_arg_tls and __dfsan_retval_tls.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000184 IA_TLS
185 };
186
Peter Collingbourne68162e72013-08-14 18:54:12 +0000187 /// How should calls to uninstrumented functions be handled?
188 enum WrapperKind {
189 /// This function is present in an uninstrumented form but we don't know
190 /// how it should be handled. Print a warning and call the function anyway.
191 /// Don't label the return value.
192 WK_Warning,
193
194 /// This function does not write to (user-accessible) memory, and its return
195 /// value is unlabelled.
196 WK_Discard,
197
198 /// This function does not write to (user-accessible) memory, and the label
199 /// of its return value is the union of the label of its arguments.
200 WK_Functional,
201
202 /// Instead of calling the function, a custom wrapper __dfsw_F is called,
203 /// where F is the name of the function. This function may wrap the
204 /// original function or provide its own implementation. This is similar to
205 /// the IA_Args ABI, except that IA_Args uses a struct return type to
206 /// pass the return value shadow in a register, while WK_Custom uses an
207 /// extra pointer argument to return the shadow. This allows the wrapped
208 /// form of the function type to be expressed in C.
209 WK_Custom
210 };
211
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000212 const DataLayout *DL;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000213 Module *Mod;
214 LLVMContext *Ctx;
215 IntegerType *ShadowTy;
216 PointerType *ShadowPtrTy;
217 IntegerType *IntptrTy;
218 ConstantInt *ZeroShadow;
219 ConstantInt *ShadowPtrMask;
220 ConstantInt *ShadowPtrMul;
221 Constant *ArgTLS;
222 Constant *RetvalTLS;
223 void *(*GetArgTLSPtr)();
224 void *(*GetRetvalTLSPtr)();
225 Constant *GetArgTLS;
226 Constant *GetRetvalTLS;
227 FunctionType *DFSanUnionFnTy;
228 FunctionType *DFSanUnionLoadFnTy;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000229 FunctionType *DFSanUnimplementedFnTy;
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000230 FunctionType *DFSanSetLabelFnTy;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000231 FunctionType *DFSanNonzeroLabelFnTy;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000232 Constant *DFSanUnionFn;
233 Constant *DFSanUnionLoadFn;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000234 Constant *DFSanUnimplementedFn;
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000235 Constant *DFSanSetLabelFn;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000236 Constant *DFSanNonzeroLabelFn;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000237 MDNode *ColdCallWeights;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000238 DFSanABIList ABIList;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000239 DenseMap<Value *, Function *> UnwrappedFnMap;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000240 AttributeSet ReadOnlyNoneAttrs;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000241
242 Value *getShadowAddress(Value *Addr, Instruction *Pos);
243 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000244 bool isInstrumented(const Function *F);
245 bool isInstrumented(const GlobalAlias *GA);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000246 FunctionType *getArgsFunctionType(FunctionType *T);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000247 FunctionType *getTrampolineFunctionType(FunctionType *T);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000248 FunctionType *getCustomFunctionType(FunctionType *T);
249 InstrumentedABI getInstrumentedABI();
250 WrapperKind getWrapperKind(Function *F);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000251 void addGlobalNamePrefix(GlobalValue *GV);
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000252 Function *buildWrapperFunction(Function *F, StringRef NewFName,
253 GlobalValue::LinkageTypes NewFLink,
254 FunctionType *NewFT);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000255 Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000256
Dmitry Vyukov96a70842013-08-13 16:52:41 +0000257 public:
Peter Collingbourne68162e72013-08-14 18:54:12 +0000258 DataFlowSanitizer(StringRef ABIListFile = StringRef(),
Craig Topperf40110f2014-04-25 05:29:35 +0000259 void *(*getArgTLS)() = nullptr,
260 void *(*getRetValTLS)() = nullptr);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000261 static char ID;
Craig Topper3e4c6972014-03-05 09:10:37 +0000262 bool doInitialization(Module &M) override;
263 bool runOnModule(Module &M) override;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000264};
265
266struct DFSanFunction {
267 DataFlowSanitizer &DFS;
268 Function *F;
269 DataFlowSanitizer::InstrumentedABI IA;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000270 bool IsNativeABI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000271 Value *ArgTLSPtr;
272 Value *RetvalTLSPtr;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000273 AllocaInst *LabelReturnAlloca;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000274 DenseMap<Value *, Value *> ValShadowMap;
275 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
276 std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
277 DenseSet<Instruction *> SkipInsts;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000278 DenseSet<Value *> NonZeroChecks;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000279
Peter Collingbourne68162e72013-08-14 18:54:12 +0000280 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
281 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()),
Craig Topperf40110f2014-04-25 05:29:35 +0000282 IsNativeABI(IsNativeABI), ArgTLSPtr(nullptr), RetvalTLSPtr(nullptr),
283 LabelReturnAlloca(nullptr) {}
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000284 Value *getArgTLSPtr();
285 Value *getArgTLS(unsigned Index, Instruction *Pos);
286 Value *getRetvalTLS();
287 Value *getShadow(Value *V);
288 void setShadow(Instruction *I, Value *Shadow);
289 Value *combineOperandShadows(Instruction *Inst);
290 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
291 Instruction *Pos);
292 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
293 Instruction *Pos);
294};
295
296class DFSanVisitor : public InstVisitor<DFSanVisitor> {
Dmitry Vyukov96a70842013-08-13 16:52:41 +0000297 public:
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000298 DFSanFunction &DFSF;
299 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
300
301 void visitOperandShadowInst(Instruction &I);
302
303 void visitBinaryOperator(BinaryOperator &BO);
304 void visitCastInst(CastInst &CI);
305 void visitCmpInst(CmpInst &CI);
306 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
307 void visitLoadInst(LoadInst &LI);
308 void visitStoreInst(StoreInst &SI);
309 void visitReturnInst(ReturnInst &RI);
310 void visitCallSite(CallSite CS);
311 void visitPHINode(PHINode &PN);
312 void visitExtractElementInst(ExtractElementInst &I);
313 void visitInsertElementInst(InsertElementInst &I);
314 void visitShuffleVectorInst(ShuffleVectorInst &I);
315 void visitExtractValueInst(ExtractValueInst &I);
316 void visitInsertValueInst(InsertValueInst &I);
317 void visitAllocaInst(AllocaInst &I);
318 void visitSelectInst(SelectInst &I);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000319 void visitMemSetInst(MemSetInst &I);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000320 void visitMemTransferInst(MemTransferInst &I);
321};
322
323}
324
325char DataFlowSanitizer::ID;
326INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
327 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
328
Peter Collingbourne68162e72013-08-14 18:54:12 +0000329ModulePass *llvm::createDataFlowSanitizerPass(StringRef ABIListFile,
330 void *(*getArgTLS)(),
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000331 void *(*getRetValTLS)()) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000332 return new DataFlowSanitizer(ABIListFile, getArgTLS, getRetValTLS);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000333}
334
Peter Collingbourne68162e72013-08-14 18:54:12 +0000335DataFlowSanitizer::DataFlowSanitizer(StringRef ABIListFile,
336 void *(*getArgTLS)(),
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000337 void *(*getRetValTLS)())
338 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS),
Peter Collingbourne68162e72013-08-14 18:54:12 +0000339 ABIList(SpecialCaseList::createOrDie(ABIListFile.empty() ? ClABIListFile
340 : ABIListFile)) {
341}
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000342
Peter Collingbourne68162e72013-08-14 18:54:12 +0000343FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000344 llvm::SmallVector<Type *, 4> ArgTypes;
345 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
346 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
347 ArgTypes.push_back(ShadowTy);
348 if (T->isVarArg())
349 ArgTypes.push_back(ShadowPtrTy);
350 Type *RetType = T->getReturnType();
351 if (!RetType->isVoidTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000352 RetType = StructType::get(RetType, ShadowTy, (Type *)nullptr);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000353 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
354}
355
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000356FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
357 assert(!T->isVarArg());
358 llvm::SmallVector<Type *, 4> ArgTypes;
359 ArgTypes.push_back(T->getPointerTo());
360 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
361 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
362 ArgTypes.push_back(ShadowTy);
363 Type *RetType = T->getReturnType();
364 if (!RetType->isVoidTy())
365 ArgTypes.push_back(ShadowPtrTy);
366 return FunctionType::get(T->getReturnType(), ArgTypes, false);
367}
368
Peter Collingbourne68162e72013-08-14 18:54:12 +0000369FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
370 assert(!T->isVarArg());
371 llvm::SmallVector<Type *, 4> ArgTypes;
Alexey Samsonov9b7e2b52013-08-28 11:25:12 +0000372 for (FunctionType::param_iterator i = T->param_begin(), e = T->param_end();
373 i != e; ++i) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000374 FunctionType *FT;
Alexey Samsonov9b7e2b52013-08-28 11:25:12 +0000375 if (isa<PointerType>(*i) && (FT = dyn_cast<FunctionType>(cast<PointerType>(
376 *i)->getElementType()))) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000377 ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
378 ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
379 } else {
380 ArgTypes.push_back(*i);
381 }
382 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000383 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
384 ArgTypes.push_back(ShadowTy);
385 Type *RetType = T->getReturnType();
386 if (!RetType->isVoidTy())
387 ArgTypes.push_back(ShadowPtrTy);
388 return FunctionType::get(T->getReturnType(), ArgTypes, false);
389}
390
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000391bool DataFlowSanitizer::doInitialization(Module &M) {
Rafael Espindola93512512014-02-25 17:30:31 +0000392 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
393 if (!DLP)
Evgeniy Stepanov119cb2e2014-04-23 12:51:32 +0000394 report_fatal_error("data layout missing");
Rafael Espindola93512512014-02-25 17:30:31 +0000395 DL = &DLP->getDataLayout();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000396
397 Mod = &M;
398 Ctx = &M.getContext();
399 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
400 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
401 IntptrTy = DL->getIntPtrType(*Ctx);
402 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
Peter Collingbournea5689e62013-08-08 00:15:27 +0000403 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000404 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
405
406 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
407 DFSanUnionFnTy =
408 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
409 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
410 DFSanUnionLoadFnTy =
411 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000412 DFSanUnimplementedFnTy = FunctionType::get(
413 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000414 Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
415 DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
416 DFSanSetLabelArgs, /*isVarArg=*/false);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000417 DFSanNonzeroLabelFnTy = FunctionType::get(
418 Type::getVoidTy(*Ctx), ArrayRef<Type *>(), /*isVarArg=*/false);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000419
420 if (GetArgTLSPtr) {
421 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
Craig Topperf40110f2014-04-25 05:29:35 +0000422 ArgTLS = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000423 GetArgTLS = ConstantExpr::getIntToPtr(
424 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
425 PointerType::getUnqual(
Craig Topperf40110f2014-04-25 05:29:35 +0000426 FunctionType::get(PointerType::getUnqual(ArgTLSTy),
427 (Type *)nullptr)));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000428 }
429 if (GetRetvalTLSPtr) {
Craig Topperf40110f2014-04-25 05:29:35 +0000430 RetvalTLS = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000431 GetRetvalTLS = ConstantExpr::getIntToPtr(
432 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
433 PointerType::getUnqual(
Craig Topperf40110f2014-04-25 05:29:35 +0000434 FunctionType::get(PointerType::getUnqual(ShadowTy),
435 (Type *)nullptr)));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000436 }
437
438 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
439 return true;
440}
441
Peter Collingbourne59b12622013-08-22 20:08:08 +0000442bool DataFlowSanitizer::isInstrumented(const Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000443 return !ABIList.isIn(*F, "uninstrumented");
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000444}
445
Peter Collingbourne59b12622013-08-22 20:08:08 +0000446bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000447 return !ABIList.isIn(*GA, "uninstrumented");
Peter Collingbourne59b12622013-08-22 20:08:08 +0000448}
449
Peter Collingbourne68162e72013-08-14 18:54:12 +0000450DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000451 return ClArgsABI ? IA_Args : IA_TLS;
452}
453
Peter Collingbourne68162e72013-08-14 18:54:12 +0000454DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000455 if (ABIList.isIn(*F, "functional"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000456 return WK_Functional;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000457 if (ABIList.isIn(*F, "discard"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000458 return WK_Discard;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000459 if (ABIList.isIn(*F, "custom"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000460 return WK_Custom;
461
462 return WK_Warning;
463}
464
Peter Collingbourne59b12622013-08-22 20:08:08 +0000465void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
466 std::string GVName = GV->getName(), Prefix = "dfs$";
467 GV->setName(Prefix + GVName);
468
469 // Try to change the name of the function in module inline asm. We only do
470 // this for specific asm directives, currently only ".symver", to try to avoid
471 // corrupting asm which happens to contain the symbol name as a substring.
472 // Note that the substitution for .symver assumes that the versioned symbol
473 // also has an instrumented name.
474 std::string Asm = GV->getParent()->getModuleInlineAsm();
475 std::string SearchStr = ".symver " + GVName + ",";
476 size_t Pos = Asm.find(SearchStr);
477 if (Pos != std::string::npos) {
478 Asm.replace(Pos, SearchStr.size(),
479 ".symver " + Prefix + GVName + "," + Prefix);
480 GV->getParent()->setModuleInlineAsm(Asm);
481 }
482}
483
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000484Function *
485DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
486 GlobalValue::LinkageTypes NewFLink,
487 FunctionType *NewFT) {
488 FunctionType *FT = F->getFunctionType();
489 Function *NewF = Function::Create(NewFT, NewFLink, NewFName,
490 F->getParent());
491 NewF->copyAttributesFrom(F);
492 NewF->removeAttributes(
493 AttributeSet::ReturnIndex,
494 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
495 AttributeSet::ReturnIndex));
496
497 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
498 std::vector<Value *> Args;
499 unsigned n = FT->getNumParams();
500 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
501 Args.push_back(&*ai);
502 CallInst *CI = CallInst::Create(F, Args, "", BB);
503 if (FT->getReturnType()->isVoidTy())
504 ReturnInst::Create(*Ctx, BB);
505 else
506 ReturnInst::Create(*Ctx, CI, BB);
507
508 return NewF;
509}
510
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000511Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
512 StringRef FName) {
513 FunctionType *FTT = getTrampolineFunctionType(FT);
514 Constant *C = Mod->getOrInsertFunction(FName, FTT);
515 Function *F = dyn_cast<Function>(C);
516 if (F && F->isDeclaration()) {
517 F->setLinkage(GlobalValue::LinkOnceODRLinkage);
518 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
519 std::vector<Value *> Args;
520 Function::arg_iterator AI = F->arg_begin(); ++AI;
521 for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
522 Args.push_back(&*AI);
523 CallInst *CI =
524 CallInst::Create(&F->getArgumentList().front(), Args, "", BB);
525 ReturnInst *RI;
526 if (FT->getReturnType()->isVoidTy())
527 RI = ReturnInst::Create(*Ctx, BB);
528 else
529 RI = ReturnInst::Create(*Ctx, CI, BB);
530
531 DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
532 Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
533 for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
534 DFSF.ValShadowMap[ValAI] = ShadowAI;
535 DFSanVisitor(DFSF).visitCallInst(*CI);
536 if (!FT->getReturnType()->isVoidTy())
537 new StoreInst(DFSF.getShadow(RI->getReturnValue()),
538 &F->getArgumentList().back(), RI);
539 }
540
541 return C;
542}
543
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000544bool DataFlowSanitizer::runOnModule(Module &M) {
545 if (!DL)
546 return false;
547
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000548 if (ABIList.isIn(M, "skip"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000549 return false;
550
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000551 if (!GetArgTLSPtr) {
552 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
553 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
554 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
555 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
556 }
557 if (!GetRetvalTLSPtr) {
558 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
559 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
560 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
561 }
562
563 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
564 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
565 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
566 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
567 F->addAttribute(1, Attribute::ZExt);
568 F->addAttribute(2, Attribute::ZExt);
569 }
570 DFSanUnionLoadFn =
571 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
572 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
Peter Collingbourne0be79e12013-11-21 23:20:54 +0000573 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000574 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
575 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000576 DFSanUnimplementedFn =
577 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000578 DFSanSetLabelFn =
579 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
580 if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
581 F->addAttribute(1, Attribute::ZExt);
582 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000583 DFSanNonzeroLabelFn =
584 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000585
586 std::vector<Function *> FnsToInstrument;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000587 llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000588 for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000589 if (!i->isIntrinsic() &&
590 i != DFSanUnionFn &&
591 i != DFSanUnionLoadFn &&
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000592 i != DFSanUnimplementedFn &&
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000593 i != DFSanSetLabelFn &&
594 i != DFSanNonzeroLabelFn)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000595 FnsToInstrument.push_back(&*i);
596 }
597
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000598 // Give function aliases prefixes when necessary, and build wrappers where the
599 // instrumentedness is inconsistent.
Peter Collingbourne59b12622013-08-22 20:08:08 +0000600 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
601 GlobalAlias *GA = &*i;
602 ++i;
603 // Don't stop on weak. We assume people aren't playing games with the
604 // instrumentedness of overridden weak aliases.
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000605 if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000606 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
607 if (GAInst && FInst) {
608 addGlobalNamePrefix(GA);
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000609 } else if (GAInst != FInst) {
610 // Non-instrumented alias of an instrumented function, or vice versa.
611 // Replace the alias with a native-ABI wrapper of the aliasee. The pass
612 // below will take care of instrumenting it.
613 Function *NewF =
614 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000615 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000616 NewF->takeName(GA);
617 GA->eraseFromParent();
618 FnsToInstrument.push_back(NewF);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000619 }
620 }
621 }
622
Peter Collingbourne68162e72013-08-14 18:54:12 +0000623 AttrBuilder B;
624 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
625 ReadOnlyNoneAttrs = AttributeSet::get(*Ctx, AttributeSet::FunctionIndex, B);
626
627 // First, change the ABI of every function in the module. ABI-listed
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000628 // functions keep their original ABI and get a wrapper function.
629 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
630 e = FnsToInstrument.end();
631 i != e; ++i) {
632 Function &F = **i;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000633 FunctionType *FT = F.getFunctionType();
Peter Collingbourne68162e72013-08-14 18:54:12 +0000634
Peter Collingbourne59b12622013-08-22 20:08:08 +0000635 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
636 FT->getReturnType()->isVoidTy());
Peter Collingbourne68162e72013-08-14 18:54:12 +0000637
638 if (isInstrumented(&F)) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000639 // Instrumented functions get a 'dfs$' prefix. This allows us to more
640 // easily identify cases of mismatching ABIs.
641 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000642 FunctionType *NewFT = getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000643 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000644 NewF->copyAttributesFrom(&F);
645 NewF->removeAttributes(
646 AttributeSet::ReturnIndex,
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000647 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
Peter Collingbourne68162e72013-08-14 18:54:12 +0000648 AttributeSet::ReturnIndex));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000649 for (Function::arg_iterator FArg = F.arg_begin(),
650 NewFArg = NewF->arg_begin(),
651 FArgEnd = F.arg_end();
652 FArg != FArgEnd; ++FArg, ++NewFArg) {
653 FArg->replaceAllUsesWith(NewFArg);
654 }
655 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
656
Chandler Carruthcdf47882014-03-09 03:16:01 +0000657 for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
658 UI != UE;) {
659 BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
660 ++UI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000661 if (BA) {
662 BA->replaceAllUsesWith(
663 BlockAddress::get(NewF, BA->getBasicBlock()));
664 delete BA;
665 }
666 }
667 F.replaceAllUsesWith(
668 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
669 NewF->takeName(&F);
670 F.eraseFromParent();
671 *i = NewF;
Peter Collingbourne59b12622013-08-22 20:08:08 +0000672 addGlobalNamePrefix(NewF);
673 } else {
674 addGlobalNamePrefix(&F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000675 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000676 // Hopefully, nobody will try to indirectly call a vararg
677 // function... yet.
678 } else if (FT->isVarArg()) {
679 UnwrappedFnMap[&F] = &F;
Craig Topperf40110f2014-04-25 05:29:35 +0000680 *i = nullptr;
Peter Collingbourne59b12622013-08-22 20:08:08 +0000681 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000682 // Build a wrapper function for F. The wrapper simply calls F, and is
683 // added to FnsToInstrument so that any instrumentation according to its
684 // WrapperKind is done in the second pass below.
685 FunctionType *NewFT = getInstrumentedABI() == IA_Args
686 ? getArgsFunctionType(FT)
687 : FT;
Alexey Samsonov6dae24d2013-08-23 07:42:51 +0000688 Function *NewF = buildWrapperFunction(
689 &F, std::string("dfsw$") + std::string(F.getName()),
690 GlobalValue::LinkOnceODRLinkage, NewFT);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000691 if (getInstrumentedABI() == IA_TLS)
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000692 NewF->removeAttributes(AttributeSet::FunctionIndex, ReadOnlyNoneAttrs);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000693
Peter Collingbourne68162e72013-08-14 18:54:12 +0000694 Value *WrappedFnCst =
695 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
696 F.replaceAllUsesWith(WrappedFnCst);
697 UnwrappedFnMap[WrappedFnCst] = &F;
698 *i = NewF;
699
700 if (!F.isDeclaration()) {
701 // This function is probably defining an interposition of an
702 // uninstrumented function and hence needs to keep the original ABI.
703 // But any functions it may call need to use the instrumented ABI, so
704 // we instrument it in a mode which preserves the original ABI.
705 FnsWithNativeABI.insert(&F);
706
707 // This code needs to rebuild the iterators, as they may be invalidated
708 // by the push_back, taking care that the new range does not include
709 // any functions added by this code.
710 size_t N = i - FnsToInstrument.begin(),
711 Count = e - FnsToInstrument.begin();
712 FnsToInstrument.push_back(&F);
713 i = FnsToInstrument.begin() + N;
714 e = FnsToInstrument.begin() + Count;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000715 }
716 }
717 }
718
719 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
720 e = FnsToInstrument.end();
721 i != e; ++i) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000722 if (!*i || (*i)->isDeclaration())
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000723 continue;
724
Peter Collingbourneae66d572013-08-09 21:42:53 +0000725 removeUnreachableBlocks(**i);
726
Peter Collingbourne68162e72013-08-14 18:54:12 +0000727 DFSanFunction DFSF(*this, *i, FnsWithNativeABI.count(*i));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000728
729 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
730 // Build a copy of the list before iterating over it.
David Blaikieceec2bd2014-04-11 01:50:01 +0000731 llvm::SmallVector<BasicBlock *, 4> BBList(
732 depth_first(&(*i)->getEntryBlock()));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000733
734 for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
735 e = BBList.end();
736 i != e; ++i) {
737 Instruction *Inst = &(*i)->front();
738 while (1) {
739 // DFSanVisitor may split the current basic block, changing the current
740 // instruction's next pointer and moving the next instruction to the
741 // tail block from which we should continue.
742 Instruction *Next = Inst->getNextNode();
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000743 // DFSanVisitor may delete Inst, so keep track of whether it was a
744 // terminator.
745 bool IsTerminator = isa<TerminatorInst>(Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000746 if (!DFSF.SkipInsts.count(Inst))
747 DFSanVisitor(DFSF).visit(Inst);
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000748 if (IsTerminator)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000749 break;
750 Inst = Next;
751 }
752 }
753
Peter Collingbourne68162e72013-08-14 18:54:12 +0000754 // We will not necessarily be able to compute the shadow for every phi node
755 // until we have visited every block. Therefore, the code that handles phi
756 // nodes adds them to the PHIFixups list so that they can be properly
757 // handled here.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000758 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
759 i = DFSF.PHIFixups.begin(),
760 e = DFSF.PHIFixups.end();
761 i != e; ++i) {
762 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
763 ++val) {
764 i->second->setIncomingValue(
765 val, DFSF.getShadow(i->first->getIncomingValue(val)));
766 }
767 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000768
769 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
770 // places (i.e. instructions in basic blocks we haven't even begun visiting
771 // yet). To make our life easier, do this work in a pass after the main
772 // instrumentation.
773 if (ClDebugNonzeroLabels) {
774 for (DenseSet<Value *>::iterator i = DFSF.NonZeroChecks.begin(),
775 e = DFSF.NonZeroChecks.end();
776 i != e; ++i) {
777 Instruction *Pos;
778 if (Instruction *I = dyn_cast<Instruction>(*i))
779 Pos = I->getNextNode();
780 else
781 Pos = DFSF.F->getEntryBlock().begin();
782 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
783 Pos = Pos->getNextNode();
784 IRBuilder<> IRB(Pos);
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000785 Value *Ne = IRB.CreateICmpNE(*i, DFSF.DFS.ZeroShadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000786 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000787 Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000788 IRBuilder<> ThenIRB(BI);
789 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn);
790 }
791 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000792 }
793
794 return false;
795}
796
797Value *DFSanFunction::getArgTLSPtr() {
798 if (ArgTLSPtr)
799 return ArgTLSPtr;
800 if (DFS.ArgTLS)
801 return ArgTLSPtr = DFS.ArgTLS;
802
803 IRBuilder<> IRB(F->getEntryBlock().begin());
804 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
805}
806
807Value *DFSanFunction::getRetvalTLS() {
808 if (RetvalTLSPtr)
809 return RetvalTLSPtr;
810 if (DFS.RetvalTLS)
811 return RetvalTLSPtr = DFS.RetvalTLS;
812
813 IRBuilder<> IRB(F->getEntryBlock().begin());
814 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
815}
816
817Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
818 IRBuilder<> IRB(Pos);
819 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
820}
821
822Value *DFSanFunction::getShadow(Value *V) {
823 if (!isa<Argument>(V) && !isa<Instruction>(V))
824 return DFS.ZeroShadow;
825 Value *&Shadow = ValShadowMap[V];
826 if (!Shadow) {
827 if (Argument *A = dyn_cast<Argument>(V)) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000828 if (IsNativeABI)
829 return DFS.ZeroShadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000830 switch (IA) {
831 case DataFlowSanitizer::IA_TLS: {
832 Value *ArgTLSPtr = getArgTLSPtr();
833 Instruction *ArgTLSPos =
834 DFS.ArgTLS ? &*F->getEntryBlock().begin()
835 : cast<Instruction>(ArgTLSPtr)->getNextNode();
836 IRBuilder<> IRB(ArgTLSPos);
837 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
838 break;
839 }
840 case DataFlowSanitizer::IA_Args: {
841 unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
842 Function::arg_iterator i = F->arg_begin();
843 while (ArgIdx--)
844 ++i;
845 Shadow = i;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000846 assert(Shadow->getType() == DFS.ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000847 break;
848 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000849 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000850 NonZeroChecks.insert(Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000851 } else {
852 Shadow = DFS.ZeroShadow;
853 }
854 }
855 return Shadow;
856}
857
858void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
859 assert(!ValShadowMap.count(I));
860 assert(Shadow->getType() == DFS.ShadowTy);
861 ValShadowMap[I] = Shadow;
862}
863
864Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
865 assert(Addr != RetvalTLS && "Reinstrumenting?");
866 IRBuilder<> IRB(Pos);
867 return IRB.CreateIntToPtr(
868 IRB.CreateMul(
869 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
870 ShadowPtrMul),
871 ShadowPtrTy);
872}
873
874// Generates IR to compute the union of the two given shadows, inserting it
875// before Pos. Returns the computed union Value.
876Value *DataFlowSanitizer::combineShadows(Value *V1, Value *V2,
877 Instruction *Pos) {
878 if (V1 == ZeroShadow)
879 return V2;
880 if (V2 == ZeroShadow)
881 return V1;
882 if (V1 == V2)
883 return V1;
884 IRBuilder<> IRB(Pos);
885 BasicBlock *Head = Pos->getParent();
886 Value *Ne = IRB.CreateICmpNE(V1, V2);
Evgeniy Stepanova284e552013-12-19 14:37:03 +0000887 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
888 Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
889 IRBuilder<> ThenIRB(BI);
890 CallInst *Call = ThenIRB.CreateCall2(DFSanUnionFn, V1, V2);
891 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
892 Call->addAttribute(1, Attribute::ZExt);
893 Call->addAttribute(2, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000894
Evgeniy Stepanova284e552013-12-19 14:37:03 +0000895 BasicBlock *Tail = BI->getSuccessor(0);
896 PHINode *Phi = PHINode::Create(ShadowTy, 2, "", Tail->begin());
897 Phi->addIncoming(Call, Call->getParent());
898 Phi->addIncoming(V1, Head);
Evgeniy Stepanova284e552013-12-19 14:37:03 +0000899 return Phi;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000900}
901
902// A convenience function which folds the shadows of each of the operands
903// of the provided instruction Inst, inserting the IR before Inst. Returns
904// the computed union Value.
905Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
906 if (Inst->getNumOperands() == 0)
907 return DFS.ZeroShadow;
908
909 Value *Shadow = getShadow(Inst->getOperand(0));
910 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
911 Shadow = DFS.combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
912 }
913 return Shadow;
914}
915
916void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
917 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
918 DFSF.setShadow(&I, CombinedShadow);
919}
920
921// Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
922// Addr has alignment Align, and take the union of each of those shadows.
923Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
924 Instruction *Pos) {
925 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
926 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
927 AllocaShadowMap.find(AI);
928 if (i != AllocaShadowMap.end()) {
929 IRBuilder<> IRB(Pos);
930 return IRB.CreateLoad(i->second);
931 }
932 }
933
934 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
935 SmallVector<Value *, 2> Objs;
936 GetUnderlyingObjects(Addr, Objs, DFS.DL);
937 bool AllConstants = true;
938 for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
939 i != e; ++i) {
940 if (isa<Function>(*i) || isa<BlockAddress>(*i))
941 continue;
942 if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
943 continue;
944
945 AllConstants = false;
946 break;
947 }
948 if (AllConstants)
949 return DFS.ZeroShadow;
950
951 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
952 switch (Size) {
953 case 0:
954 return DFS.ZeroShadow;
955 case 1: {
956 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
957 LI->setAlignment(ShadowAlign);
958 return LI;
959 }
960 case 2: {
961 IRBuilder<> IRB(Pos);
962 Value *ShadowAddr1 =
963 IRB.CreateGEP(ShadowAddr, ConstantInt::get(DFS.IntptrTy, 1));
964 return DFS.combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
965 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign),
966 Pos);
967 }
968 }
969 if (Size % (64 / DFS.ShadowWidth) == 0) {
970 // Fast path for the common case where each byte has identical shadow: load
971 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
972 // shadow is non-equal.
973 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
974 IRBuilder<> FallbackIRB(FallbackBB);
975 CallInst *FallbackCall = FallbackIRB.CreateCall2(
976 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
977 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
978
979 // Compare each of the shadows stored in the loaded 64 bits to each other,
980 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
981 IRBuilder<> IRB(Pos);
982 Value *WideAddr =
983 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
984 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
985 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
986 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
987 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
988 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
989 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
990
991 BasicBlock *Head = Pos->getParent();
992 BasicBlock *Tail = Head->splitBasicBlock(Pos);
993 // In the following code LastBr will refer to the previous basic block's
994 // conditional branch instruction, whose true successor is fixed up to point
995 // to the next block during the loop below or to the tail after the final
996 // iteration.
997 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
998 ReplaceInstWithInst(Head->getTerminator(), LastBr);
999
1000 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
1001 Ofs += 64 / DFS.ShadowWidth) {
1002 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
1003 IRBuilder<> NextIRB(NextBB);
1004 WideAddr = NextIRB.CreateGEP(WideAddr, ConstantInt::get(DFS.IntptrTy, 1));
1005 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1006 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1007 LastBr->setSuccessor(0, NextBB);
1008 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1009 }
1010
1011 LastBr->setSuccessor(0, Tail);
1012 FallbackIRB.CreateBr(Tail);
1013 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1014 Shadow->addIncoming(FallbackCall, FallbackBB);
1015 Shadow->addIncoming(TruncShadow, LastBr->getParent());
1016 return Shadow;
1017 }
1018
1019 IRBuilder<> IRB(Pos);
1020 CallInst *FallbackCall = IRB.CreateCall2(
1021 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
1022 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1023 return FallbackCall;
1024}
1025
1026void DFSanVisitor::visitLoadInst(LoadInst &LI) {
1027 uint64_t Size = DFSF.DFS.DL->getTypeStoreSize(LI.getType());
1028 uint64_t Align;
1029 if (ClPreserveAlignment) {
1030 Align = LI.getAlignment();
1031 if (Align == 0)
1032 Align = DFSF.DFS.DL->getABITypeAlignment(LI.getType());
1033 } else {
1034 Align = 1;
1035 }
1036 IRBuilder<> IRB(&LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001037 Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
1038 if (ClCombinePointerLabelsOnLoad) {
1039 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
1040 Shadow = DFSF.DFS.combineShadows(Shadow, PtrShadow, &LI);
1041 }
1042 if (Shadow != DFSF.DFS.ZeroShadow)
1043 DFSF.NonZeroChecks.insert(Shadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +00001044
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001045 DFSF.setShadow(&LI, Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001046}
1047
1048void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
1049 Value *Shadow, Instruction *Pos) {
1050 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1051 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1052 AllocaShadowMap.find(AI);
1053 if (i != AllocaShadowMap.end()) {
1054 IRBuilder<> IRB(Pos);
1055 IRB.CreateStore(Shadow, i->second);
1056 return;
1057 }
1058 }
1059
1060 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1061 IRBuilder<> IRB(Pos);
1062 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1063 if (Shadow == DFS.ZeroShadow) {
1064 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1065 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1066 Value *ExtShadowAddr =
1067 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1068 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1069 return;
1070 }
1071
1072 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1073 uint64_t Offset = 0;
1074 if (Size >= ShadowVecSize) {
1075 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1076 Value *ShadowVec = UndefValue::get(ShadowVecTy);
1077 for (unsigned i = 0; i != ShadowVecSize; ++i) {
1078 ShadowVec = IRB.CreateInsertElement(
1079 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1080 }
1081 Value *ShadowVecAddr =
1082 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1083 do {
1084 Value *CurShadowVecAddr = IRB.CreateConstGEP1_32(ShadowVecAddr, Offset);
1085 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1086 Size -= ShadowVecSize;
1087 ++Offset;
1088 } while (Size >= ShadowVecSize);
1089 Offset *= ShadowVecSize;
1090 }
1091 while (Size > 0) {
1092 Value *CurShadowAddr = IRB.CreateConstGEP1_32(ShadowAddr, Offset);
1093 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1094 --Size;
1095 ++Offset;
1096 }
1097}
1098
1099void DFSanVisitor::visitStoreInst(StoreInst &SI) {
1100 uint64_t Size =
1101 DFSF.DFS.DL->getTypeStoreSize(SI.getValueOperand()->getType());
1102 uint64_t Align;
1103 if (ClPreserveAlignment) {
1104 Align = SI.getAlignment();
1105 if (Align == 0)
1106 Align = DFSF.DFS.DL->getABITypeAlignment(SI.getValueOperand()->getType());
1107 } else {
1108 Align = 1;
1109 }
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001110
1111 Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1112 if (ClCombinePointerLabelsOnStore) {
1113 Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
1114 Shadow = DFSF.DFS.combineShadows(Shadow, PtrShadow, &SI);
1115 }
1116 DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001117}
1118
1119void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1120 visitOperandShadowInst(BO);
1121}
1122
1123void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1124
1125void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1126
1127void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1128 visitOperandShadowInst(GEPI);
1129}
1130
1131void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1132 visitOperandShadowInst(I);
1133}
1134
1135void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1136 visitOperandShadowInst(I);
1137}
1138
1139void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1140 visitOperandShadowInst(I);
1141}
1142
1143void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1144 visitOperandShadowInst(I);
1145}
1146
1147void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1148 visitOperandShadowInst(I);
1149}
1150
1151void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1152 bool AllLoadsStores = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001153 for (User *U : I.users()) {
1154 if (isa<LoadInst>(U))
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001155 continue;
1156
Chandler Carruthcdf47882014-03-09 03:16:01 +00001157 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001158 if (SI->getPointerOperand() == &I)
1159 continue;
1160 }
1161
1162 AllLoadsStores = false;
1163 break;
1164 }
1165 if (AllLoadsStores) {
1166 IRBuilder<> IRB(&I);
1167 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1168 }
1169 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1170}
1171
1172void DFSanVisitor::visitSelectInst(SelectInst &I) {
1173 Value *CondShadow = DFSF.getShadow(I.getCondition());
1174 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1175 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1176
1177 if (isa<VectorType>(I.getCondition()->getType())) {
1178 DFSF.setShadow(
1179 &I, DFSF.DFS.combineShadows(
1180 CondShadow,
1181 DFSF.DFS.combineShadows(TrueShadow, FalseShadow, &I), &I));
1182 } else {
1183 Value *ShadowSel;
1184 if (TrueShadow == FalseShadow) {
1185 ShadowSel = TrueShadow;
1186 } else {
1187 ShadowSel =
1188 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1189 }
1190 DFSF.setShadow(&I, DFSF.DFS.combineShadows(CondShadow, ShadowSel, &I));
1191 }
1192}
1193
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +00001194void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1195 IRBuilder<> IRB(&I);
1196 Value *ValShadow = DFSF.getShadow(I.getValue());
1197 IRB.CreateCall3(
1198 DFSF.DFS.DFSanSetLabelFn, ValShadow,
1199 IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
1200 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy));
1201}
1202
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001203void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1204 IRBuilder<> IRB(&I);
1205 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1206 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1207 Value *LenShadow = IRB.CreateMul(
1208 I.getLength(),
1209 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
1210 Value *AlignShadow;
1211 if (ClPreserveAlignment) {
1212 AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1213 ConstantInt::get(I.getAlignmentCst()->getType(),
1214 DFSF.DFS.ShadowWidth / 8));
1215 } else {
1216 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1217 DFSF.DFS.ShadowWidth / 8);
1218 }
1219 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1220 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1221 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
1222 IRB.CreateCall5(I.getCalledValue(), DestShadow, SrcShadow, LenShadow,
1223 AlignShadow, I.getVolatileCst());
1224}
1225
1226void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001227 if (!DFSF.IsNativeABI && RI.getReturnValue()) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001228 switch (DFSF.IA) {
1229 case DataFlowSanitizer::IA_TLS: {
1230 Value *S = DFSF.getShadow(RI.getReturnValue());
1231 IRBuilder<> IRB(&RI);
1232 IRB.CreateStore(S, DFSF.getRetvalTLS());
1233 break;
1234 }
1235 case DataFlowSanitizer::IA_Args: {
1236 IRBuilder<> IRB(&RI);
1237 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1238 Value *InsVal =
1239 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1240 Value *InsShadow =
1241 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1242 RI.setOperand(0, InsShadow);
1243 break;
1244 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001245 }
1246 }
1247}
1248
1249void DFSanVisitor::visitCallSite(CallSite CS) {
1250 Function *F = CS.getCalledFunction();
1251 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1252 visitOperandShadowInst(*CS.getInstruction());
1253 return;
1254 }
1255
Peter Collingbourne68162e72013-08-14 18:54:12 +00001256 IRBuilder<> IRB(CS.getInstruction());
1257
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001258 DenseMap<Value *, Function *>::iterator i =
1259 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1260 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001261 Function *F = i->second;
1262 switch (DFSF.DFS.getWrapperKind(F)) {
1263 case DataFlowSanitizer::WK_Warning: {
1264 CS.setCalledFunction(F);
1265 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1266 IRB.CreateGlobalStringPtr(F->getName()));
1267 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1268 return;
1269 }
1270 case DataFlowSanitizer::WK_Discard: {
1271 CS.setCalledFunction(F);
1272 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1273 return;
1274 }
1275 case DataFlowSanitizer::WK_Functional: {
1276 CS.setCalledFunction(F);
1277 visitOperandShadowInst(*CS.getInstruction());
1278 return;
1279 }
1280 case DataFlowSanitizer::WK_Custom: {
1281 // Don't try to handle invokes of custom functions, it's too complicated.
1282 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1283 // wrapper.
1284 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1285 FunctionType *FT = F->getFunctionType();
1286 FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1287 std::string CustomFName = "__dfsw_";
1288 CustomFName += F->getName();
1289 Constant *CustomF =
1290 DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1291 if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1292 CustomFn->copyAttributesFrom(F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001293
Peter Collingbourne68162e72013-08-14 18:54:12 +00001294 // Custom functions returning non-void will write to the return label.
1295 if (!FT->getReturnType()->isVoidTy()) {
1296 CustomFn->removeAttributes(AttributeSet::FunctionIndex,
1297 DFSF.DFS.ReadOnlyNoneAttrs);
1298 }
1299 }
1300
1301 std::vector<Value *> Args;
1302
1303 CallSite::arg_iterator i = CS.arg_begin();
Peter Collingbourne28a10af2013-08-27 22:09:06 +00001304 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
1305 Type *T = (*i)->getType();
1306 FunctionType *ParamFT;
1307 if (isa<PointerType>(T) &&
1308 (ParamFT = dyn_cast<FunctionType>(
1309 cast<PointerType>(T)->getElementType()))) {
1310 std::string TName = "dfst";
1311 TName += utostr(FT->getNumParams() - n);
1312 TName += "$";
1313 TName += F->getName();
1314 Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1315 Args.push_back(T);
1316 Args.push_back(
1317 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1318 } else {
1319 Args.push_back(*i);
1320 }
1321 }
Peter Collingbourne68162e72013-08-14 18:54:12 +00001322
1323 i = CS.arg_begin();
1324 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1325 Args.push_back(DFSF.getShadow(*i));
1326
1327 if (!FT->getReturnType()->isVoidTy()) {
1328 if (!DFSF.LabelReturnAlloca) {
1329 DFSF.LabelReturnAlloca =
1330 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
1331 DFSF.F->getEntryBlock().begin());
1332 }
1333 Args.push_back(DFSF.LabelReturnAlloca);
1334 }
1335
1336 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1337 CustomCI->setCallingConv(CI->getCallingConv());
1338 CustomCI->setAttributes(CI->getAttributes());
1339
1340 if (!FT->getReturnType()->isVoidTy()) {
1341 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1342 DFSF.setShadow(CustomCI, LabelLoad);
1343 }
1344
1345 CI->replaceAllUsesWith(CustomCI);
1346 CI->eraseFromParent();
1347 return;
1348 }
1349 break;
1350 }
1351 }
1352 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001353
1354 FunctionType *FT = cast<FunctionType>(
1355 CS.getCalledValue()->getType()->getPointerElementType());
Peter Collingbourne68162e72013-08-14 18:54:12 +00001356 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001357 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1358 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1359 DFSF.getArgTLS(i, CS.getInstruction()));
1360 }
1361 }
1362
Craig Topperf40110f2014-04-25 05:29:35 +00001363 Instruction *Next = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001364 if (!CS.getType()->isVoidTy()) {
1365 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1366 if (II->getNormalDest()->getSinglePredecessor()) {
1367 Next = II->getNormalDest()->begin();
1368 } else {
1369 BasicBlock *NewBB =
1370 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DFS);
1371 Next = NewBB->begin();
1372 }
1373 } else {
1374 Next = CS->getNextNode();
1375 }
1376
Peter Collingbourne68162e72013-08-14 18:54:12 +00001377 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001378 IRBuilder<> NextIRB(Next);
1379 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1380 DFSF.SkipInsts.insert(LI);
1381 DFSF.setShadow(CS.getInstruction(), LI);
Peter Collingbourne444c59e2013-08-15 18:51:12 +00001382 DFSF.NonZeroChecks.insert(LI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001383 }
1384 }
1385
1386 // Do all instrumentation for IA_Args down here to defer tampering with the
1387 // CFG in a way that SplitEdge may be able to detect.
Peter Collingbourne68162e72013-08-14 18:54:12 +00001388 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1389 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001390 Value *Func =
1391 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1392 std::vector<Value *> Args;
1393
1394 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1395 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1396 Args.push_back(*i);
1397
1398 i = CS.arg_begin();
1399 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1400 Args.push_back(DFSF.getShadow(*i));
1401
1402 if (FT->isVarArg()) {
1403 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1404 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1405 AllocaInst *VarArgShadow =
1406 new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
1407 Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
1408 for (unsigned n = 0; i != e; ++i, ++n) {
1409 IRB.CreateStore(DFSF.getShadow(*i),
1410 IRB.CreateConstGEP2_32(VarArgShadow, 0, n));
1411 Args.push_back(*i);
1412 }
1413 }
1414
1415 CallSite NewCS;
1416 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1417 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1418 Args);
1419 } else {
1420 NewCS = IRB.CreateCall(Func, Args);
1421 }
1422 NewCS.setCallingConv(CS.getCallingConv());
1423 NewCS.setAttributes(CS.getAttributes().removeAttributes(
1424 *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
1425 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType(),
1426 AttributeSet::ReturnIndex)));
1427
1428 if (Next) {
1429 ExtractValueInst *ExVal =
1430 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1431 DFSF.SkipInsts.insert(ExVal);
1432 ExtractValueInst *ExShadow =
1433 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1434 DFSF.SkipInsts.insert(ExShadow);
1435 DFSF.setShadow(ExVal, ExShadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +00001436 DFSF.NonZeroChecks.insert(ExShadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001437
1438 CS.getInstruction()->replaceAllUsesWith(ExVal);
1439 }
1440
1441 CS.getInstruction()->eraseFromParent();
1442 }
1443}
1444
1445void DFSanVisitor::visitPHINode(PHINode &PN) {
1446 PHINode *ShadowPN =
1447 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1448
1449 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1450 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1451 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1452 ++i) {
1453 ShadowPN->addIncoming(UndefShadow, *i);
1454 }
1455
1456 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1457 DFSF.setShadow(&PN, ShadowPN);
1458}