blob: 6419adc85a2e02373b02820b2f526a4d43dcf6a5 [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 Collingbourne705a1ae2014-07-15 04:41:17 +000053#include "llvm/IR/Dominators.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000054#include "llvm/IR/IRBuilder.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000055#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000056#include "llvm/IR/InstVisitor.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000057#include "llvm/IR/LLVMContext.h"
58#include "llvm/IR/MDBuilder.h"
59#include "llvm/IR/Type.h"
60#include "llvm/IR/Value.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000061#include "llvm/Pass.h"
62#include "llvm/Support/CommandLine.h"
Alexey Samsonovb7dd3292014-07-09 19:40:08 +000063#include "llvm/Support/SpecialCaseList.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000064#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Peter Collingbourneae66d572013-08-09 21:42:53 +000065#include "llvm/Transforms/Utils/Local.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000066#include <iterator>
67
68using namespace llvm;
69
70// The -dfsan-preserve-alignment flag controls whether this pass assumes that
71// alignment requirements provided by the input IR are correct. For example,
72// if the input IR contains a load with alignment 8, this flag will cause
73// the shadow load to have alignment 16. This flag is disabled by default as
74// we have unfortunately encountered too much code (including Clang itself;
75// see PR14291) which performs misaligned access.
76static cl::opt<bool> ClPreserveAlignment(
77 "dfsan-preserve-alignment",
78 cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
79 cl::init(false));
80
Peter Collingbourne68162e72013-08-14 18:54:12 +000081// The ABI list file controls how shadow parameters are passed. The pass treats
82// every function labelled "uninstrumented" in the ABI list file as conforming
83// to the "native" (i.e. unsanitized) ABI. Unless the ABI list contains
84// additional annotations for those functions, a call to one of those functions
85// will produce a warning message, as the labelling behaviour of the function is
86// unknown. The other supported annotations are "functional" and "discard",
87// which are described below under DataFlowSanitizer::WrapperKind.
88static cl::opt<std::string> ClABIListFile(
89 "dfsan-abilist",
90 cl::desc("File listing native ABI functions and how the pass treats them"),
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000091 cl::Hidden);
92
Peter Collingbourne68162e72013-08-14 18:54:12 +000093// Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
94// functions (see DataFlowSanitizer::InstrumentedABI below).
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000095static cl::opt<bool> ClArgsABI(
96 "dfsan-args-abi",
97 cl::desc("Use the argument ABI rather than the TLS ABI"),
98 cl::Hidden);
99
Peter Collingbourne0be79e12013-11-21 23:20:54 +0000100// Controls whether the pass includes or ignores the labels of pointers in load
101// instructions.
102static cl::opt<bool> ClCombinePointerLabelsOnLoad(
103 "dfsan-combine-pointer-labels-on-load",
104 cl::desc("Combine the label of the pointer with the label of the data when "
105 "loading from memory."),
106 cl::Hidden, cl::init(true));
107
108// Controls whether the pass includes or ignores the labels of pointers in
109// stores instructions.
110static cl::opt<bool> ClCombinePointerLabelsOnStore(
111 "dfsan-combine-pointer-labels-on-store",
112 cl::desc("Combine the label of the pointer with the label of the data when "
113 "storing in memory."),
114 cl::Hidden, cl::init(false));
115
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000116static cl::opt<bool> ClDebugNonzeroLabels(
117 "dfsan-debug-nonzero-labels",
118 cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
119 "load or return with a nonzero label"),
120 cl::Hidden);
121
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000122namespace {
123
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000124StringRef GetGlobalTypeString(const GlobalValue &G) {
125 // Types of GlobalVariables are always pointer types.
126 Type *GType = G.getType()->getElementType();
127 // For now we support blacklisting struct types only.
128 if (StructType *SGType = dyn_cast<StructType>(GType)) {
129 if (!SGType->isLiteral())
130 return SGType->getName();
131 }
132 return "<unknown type>";
133}
134
135class DFSanABIList {
136 std::unique_ptr<SpecialCaseList> SCL;
137
138 public:
139 DFSanABIList(SpecialCaseList *SCL) : SCL(SCL) {}
140
141 /// Returns whether either this function or its source file are listed in the
142 /// given category.
143 bool isIn(const Function &F, const StringRef Category) const {
144 return isIn(*F.getParent(), Category) ||
145 SCL->inSection("fun", F.getName(), Category);
146 }
147
148 /// Returns whether this global alias is listed in the given category.
149 ///
150 /// If GA aliases a function, the alias's name is matched as a function name
151 /// would be. Similarly, aliases of globals are matched like globals.
152 bool isIn(const GlobalAlias &GA, const StringRef Category) const {
153 if (isIn(*GA.getParent(), Category))
154 return true;
155
156 if (isa<FunctionType>(GA.getType()->getElementType()))
157 return SCL->inSection("fun", GA.getName(), Category);
158
159 return SCL->inSection("global", GA.getName(), Category) ||
160 SCL->inSection("type", GetGlobalTypeString(GA), Category);
161 }
162
163 /// Returns whether this module is listed in the given category.
164 bool isIn(const Module &M, const StringRef Category) const {
165 return SCL->inSection("src", M.getModuleIdentifier(), Category);
166 }
167};
168
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000169class DataFlowSanitizer : public ModulePass {
170 friend struct DFSanFunction;
171 friend class DFSanVisitor;
172
173 enum {
174 ShadowWidth = 16
175 };
176
Peter Collingbourne68162e72013-08-14 18:54:12 +0000177 /// Which ABI should be used for instrumented functions?
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000178 enum InstrumentedABI {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000179 /// Argument and return value labels are passed through additional
180 /// arguments and by modifying the return type.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000181 IA_Args,
Peter Collingbourne68162e72013-08-14 18:54:12 +0000182
183 /// Argument and return value labels are passed through TLS variables
184 /// __dfsan_arg_tls and __dfsan_retval_tls.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000185 IA_TLS
186 };
187
Peter Collingbourne68162e72013-08-14 18:54:12 +0000188 /// How should calls to uninstrumented functions be handled?
189 enum WrapperKind {
190 /// This function is present in an uninstrumented form but we don't know
191 /// how it should be handled. Print a warning and call the function anyway.
192 /// Don't label the return value.
193 WK_Warning,
194
195 /// This function does not write to (user-accessible) memory, and its return
196 /// value is unlabelled.
197 WK_Discard,
198
199 /// This function does not write to (user-accessible) memory, and the label
200 /// of its return value is the union of the label of its arguments.
201 WK_Functional,
202
203 /// Instead of calling the function, a custom wrapper __dfsw_F is called,
204 /// where F is the name of the function. This function may wrap the
205 /// original function or provide its own implementation. This is similar to
206 /// the IA_Args ABI, except that IA_Args uses a struct return type to
207 /// pass the return value shadow in a register, while WK_Custom uses an
208 /// extra pointer argument to return the shadow. This allows the wrapped
209 /// form of the function type to be expressed in C.
210 WK_Custom
211 };
212
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000213 const DataLayout *DL;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000214 Module *Mod;
215 LLVMContext *Ctx;
216 IntegerType *ShadowTy;
217 PointerType *ShadowPtrTy;
218 IntegerType *IntptrTy;
219 ConstantInt *ZeroShadow;
220 ConstantInt *ShadowPtrMask;
221 ConstantInt *ShadowPtrMul;
222 Constant *ArgTLS;
223 Constant *RetvalTLS;
224 void *(*GetArgTLSPtr)();
225 void *(*GetRetvalTLSPtr)();
226 Constant *GetArgTLS;
227 Constant *GetRetvalTLS;
228 FunctionType *DFSanUnionFnTy;
229 FunctionType *DFSanUnionLoadFnTy;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000230 FunctionType *DFSanUnimplementedFnTy;
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000231 FunctionType *DFSanSetLabelFnTy;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000232 FunctionType *DFSanNonzeroLabelFnTy;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000233 Constant *DFSanUnionFn;
234 Constant *DFSanUnionLoadFn;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000235 Constant *DFSanUnimplementedFn;
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000236 Constant *DFSanSetLabelFn;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000237 Constant *DFSanNonzeroLabelFn;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000238 MDNode *ColdCallWeights;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000239 DFSanABIList ABIList;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000240 DenseMap<Value *, Function *> UnwrappedFnMap;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000241 AttributeSet ReadOnlyNoneAttrs;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000242
243 Value *getShadowAddress(Value *Addr, 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;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000269 DominatorTree DT;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000270 DataFlowSanitizer::InstrumentedABI IA;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000271 bool IsNativeABI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000272 Value *ArgTLSPtr;
273 Value *RetvalTLSPtr;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000274 AllocaInst *LabelReturnAlloca;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000275 DenseMap<Value *, Value *> ValShadowMap;
276 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
277 std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
278 DenseSet<Instruction *> SkipInsts;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000279 DenseSet<Value *> NonZeroChecks;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000280
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000281 struct CachedCombinedShadow {
282 BasicBlock *Block;
283 Value *Shadow;
284 };
285 DenseMap<std::pair<Value *, Value *>, CachedCombinedShadow>
286 CachedCombinedShadows;
287
Peter Collingbourne68162e72013-08-14 18:54:12 +0000288 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
289 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()),
Craig Topperf40110f2014-04-25 05:29:35 +0000290 IsNativeABI(IsNativeABI), ArgTLSPtr(nullptr), RetvalTLSPtr(nullptr),
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000291 LabelReturnAlloca(nullptr) {
292 DT.recalculate(*F);
293 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000294 Value *getArgTLSPtr();
295 Value *getArgTLS(unsigned Index, Instruction *Pos);
296 Value *getRetvalTLS();
297 Value *getShadow(Value *V);
298 void setShadow(Instruction *I, Value *Shadow);
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000299 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000300 Value *combineOperandShadows(Instruction *Inst);
301 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
302 Instruction *Pos);
303 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
304 Instruction *Pos);
305};
306
307class DFSanVisitor : public InstVisitor<DFSanVisitor> {
Dmitry Vyukov96a70842013-08-13 16:52:41 +0000308 public:
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000309 DFSanFunction &DFSF;
310 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
311
312 void visitOperandShadowInst(Instruction &I);
313
314 void visitBinaryOperator(BinaryOperator &BO);
315 void visitCastInst(CastInst &CI);
316 void visitCmpInst(CmpInst &CI);
317 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
318 void visitLoadInst(LoadInst &LI);
319 void visitStoreInst(StoreInst &SI);
320 void visitReturnInst(ReturnInst &RI);
321 void visitCallSite(CallSite CS);
322 void visitPHINode(PHINode &PN);
323 void visitExtractElementInst(ExtractElementInst &I);
324 void visitInsertElementInst(InsertElementInst &I);
325 void visitShuffleVectorInst(ShuffleVectorInst &I);
326 void visitExtractValueInst(ExtractValueInst &I);
327 void visitInsertValueInst(InsertValueInst &I);
328 void visitAllocaInst(AllocaInst &I);
329 void visitSelectInst(SelectInst &I);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000330 void visitMemSetInst(MemSetInst &I);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000331 void visitMemTransferInst(MemTransferInst &I);
332};
333
334}
335
336char DataFlowSanitizer::ID;
337INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
338 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
339
Peter Collingbourne68162e72013-08-14 18:54:12 +0000340ModulePass *llvm::createDataFlowSanitizerPass(StringRef ABIListFile,
341 void *(*getArgTLS)(),
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000342 void *(*getRetValTLS)()) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000343 return new DataFlowSanitizer(ABIListFile, getArgTLS, getRetValTLS);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000344}
345
Peter Collingbourne68162e72013-08-14 18:54:12 +0000346DataFlowSanitizer::DataFlowSanitizer(StringRef ABIListFile,
347 void *(*getArgTLS)(),
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000348 void *(*getRetValTLS)())
349 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS),
Peter Collingbourne68162e72013-08-14 18:54:12 +0000350 ABIList(SpecialCaseList::createOrDie(ABIListFile.empty() ? ClABIListFile
351 : ABIListFile)) {
352}
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000353
Peter Collingbourne68162e72013-08-14 18:54:12 +0000354FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000355 llvm::SmallVector<Type *, 4> ArgTypes;
356 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
357 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
358 ArgTypes.push_back(ShadowTy);
359 if (T->isVarArg())
360 ArgTypes.push_back(ShadowPtrTy);
361 Type *RetType = T->getReturnType();
362 if (!RetType->isVoidTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000363 RetType = StructType::get(RetType, ShadowTy, (Type *)nullptr);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000364 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
365}
366
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000367FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
368 assert(!T->isVarArg());
369 llvm::SmallVector<Type *, 4> ArgTypes;
370 ArgTypes.push_back(T->getPointerTo());
371 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
372 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
373 ArgTypes.push_back(ShadowTy);
374 Type *RetType = T->getReturnType();
375 if (!RetType->isVoidTy())
376 ArgTypes.push_back(ShadowPtrTy);
377 return FunctionType::get(T->getReturnType(), ArgTypes, false);
378}
379
Peter Collingbourne68162e72013-08-14 18:54:12 +0000380FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
381 assert(!T->isVarArg());
382 llvm::SmallVector<Type *, 4> ArgTypes;
Alexey Samsonov9b7e2b52013-08-28 11:25:12 +0000383 for (FunctionType::param_iterator i = T->param_begin(), e = T->param_end();
384 i != e; ++i) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000385 FunctionType *FT;
Alexey Samsonov9b7e2b52013-08-28 11:25:12 +0000386 if (isa<PointerType>(*i) && (FT = dyn_cast<FunctionType>(cast<PointerType>(
387 *i)->getElementType()))) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000388 ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
389 ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
390 } else {
391 ArgTypes.push_back(*i);
392 }
393 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000394 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
395 ArgTypes.push_back(ShadowTy);
396 Type *RetType = T->getReturnType();
397 if (!RetType->isVoidTy())
398 ArgTypes.push_back(ShadowPtrTy);
399 return FunctionType::get(T->getReturnType(), ArgTypes, false);
400}
401
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000402bool DataFlowSanitizer::doInitialization(Module &M) {
Rafael Espindola93512512014-02-25 17:30:31 +0000403 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
404 if (!DLP)
Evgeniy Stepanov119cb2e2014-04-23 12:51:32 +0000405 report_fatal_error("data layout missing");
Rafael Espindola93512512014-02-25 17:30:31 +0000406 DL = &DLP->getDataLayout();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000407
408 Mod = &M;
409 Ctx = &M.getContext();
410 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
411 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
412 IntptrTy = DL->getIntPtrType(*Ctx);
413 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
Peter Collingbournea5689e62013-08-08 00:15:27 +0000414 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000415 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
416
417 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
418 DFSanUnionFnTy =
419 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
420 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
421 DFSanUnionLoadFnTy =
422 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000423 DFSanUnimplementedFnTy = FunctionType::get(
424 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000425 Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
426 DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
427 DFSanSetLabelArgs, /*isVarArg=*/false);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000428 DFSanNonzeroLabelFnTy = FunctionType::get(
429 Type::getVoidTy(*Ctx), ArrayRef<Type *>(), /*isVarArg=*/false);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000430
431 if (GetArgTLSPtr) {
432 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
Craig Topperf40110f2014-04-25 05:29:35 +0000433 ArgTLS = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000434 GetArgTLS = ConstantExpr::getIntToPtr(
435 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
436 PointerType::getUnqual(
Craig Topperf40110f2014-04-25 05:29:35 +0000437 FunctionType::get(PointerType::getUnqual(ArgTLSTy),
438 (Type *)nullptr)));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000439 }
440 if (GetRetvalTLSPtr) {
Craig Topperf40110f2014-04-25 05:29:35 +0000441 RetvalTLS = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000442 GetRetvalTLS = ConstantExpr::getIntToPtr(
443 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
444 PointerType::getUnqual(
Craig Topperf40110f2014-04-25 05:29:35 +0000445 FunctionType::get(PointerType::getUnqual(ShadowTy),
446 (Type *)nullptr)));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000447 }
448
449 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
450 return true;
451}
452
Peter Collingbourne59b12622013-08-22 20:08:08 +0000453bool DataFlowSanitizer::isInstrumented(const Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000454 return !ABIList.isIn(*F, "uninstrumented");
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000455}
456
Peter Collingbourne59b12622013-08-22 20:08:08 +0000457bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000458 return !ABIList.isIn(*GA, "uninstrumented");
Peter Collingbourne59b12622013-08-22 20:08:08 +0000459}
460
Peter Collingbourne68162e72013-08-14 18:54:12 +0000461DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000462 return ClArgsABI ? IA_Args : IA_TLS;
463}
464
Peter Collingbourne68162e72013-08-14 18:54:12 +0000465DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000466 if (ABIList.isIn(*F, "functional"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000467 return WK_Functional;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000468 if (ABIList.isIn(*F, "discard"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000469 return WK_Discard;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000470 if (ABIList.isIn(*F, "custom"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000471 return WK_Custom;
472
473 return WK_Warning;
474}
475
Peter Collingbourne59b12622013-08-22 20:08:08 +0000476void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
477 std::string GVName = GV->getName(), Prefix = "dfs$";
478 GV->setName(Prefix + GVName);
479
480 // Try to change the name of the function in module inline asm. We only do
481 // this for specific asm directives, currently only ".symver", to try to avoid
482 // corrupting asm which happens to contain the symbol name as a substring.
483 // Note that the substitution for .symver assumes that the versioned symbol
484 // also has an instrumented name.
485 std::string Asm = GV->getParent()->getModuleInlineAsm();
486 std::string SearchStr = ".symver " + GVName + ",";
487 size_t Pos = Asm.find(SearchStr);
488 if (Pos != std::string::npos) {
489 Asm.replace(Pos, SearchStr.size(),
490 ".symver " + Prefix + GVName + "," + Prefix);
491 GV->getParent()->setModuleInlineAsm(Asm);
492 }
493}
494
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000495Function *
496DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
497 GlobalValue::LinkageTypes NewFLink,
498 FunctionType *NewFT) {
499 FunctionType *FT = F->getFunctionType();
500 Function *NewF = Function::Create(NewFT, NewFLink, NewFName,
501 F->getParent());
502 NewF->copyAttributesFrom(F);
503 NewF->removeAttributes(
504 AttributeSet::ReturnIndex,
505 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
506 AttributeSet::ReturnIndex));
507
508 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
509 std::vector<Value *> Args;
510 unsigned n = FT->getNumParams();
511 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
512 Args.push_back(&*ai);
513 CallInst *CI = CallInst::Create(F, Args, "", BB);
514 if (FT->getReturnType()->isVoidTy())
515 ReturnInst::Create(*Ctx, BB);
516 else
517 ReturnInst::Create(*Ctx, CI, BB);
518
519 return NewF;
520}
521
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000522Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
523 StringRef FName) {
524 FunctionType *FTT = getTrampolineFunctionType(FT);
525 Constant *C = Mod->getOrInsertFunction(FName, FTT);
526 Function *F = dyn_cast<Function>(C);
527 if (F && F->isDeclaration()) {
528 F->setLinkage(GlobalValue::LinkOnceODRLinkage);
529 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
530 std::vector<Value *> Args;
531 Function::arg_iterator AI = F->arg_begin(); ++AI;
532 for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
533 Args.push_back(&*AI);
534 CallInst *CI =
535 CallInst::Create(&F->getArgumentList().front(), Args, "", BB);
536 ReturnInst *RI;
537 if (FT->getReturnType()->isVoidTy())
538 RI = ReturnInst::Create(*Ctx, BB);
539 else
540 RI = ReturnInst::Create(*Ctx, CI, BB);
541
542 DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
543 Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
544 for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
545 DFSF.ValShadowMap[ValAI] = ShadowAI;
546 DFSanVisitor(DFSF).visitCallInst(*CI);
547 if (!FT->getReturnType()->isVoidTy())
548 new StoreInst(DFSF.getShadow(RI->getReturnValue()),
549 &F->getArgumentList().back(), RI);
550 }
551
552 return C;
553}
554
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000555bool DataFlowSanitizer::runOnModule(Module &M) {
556 if (!DL)
557 return false;
558
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000559 if (ABIList.isIn(M, "skip"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000560 return false;
561
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000562 if (!GetArgTLSPtr) {
563 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
564 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
565 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
566 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
567 }
568 if (!GetRetvalTLSPtr) {
569 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
570 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
571 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
572 }
573
574 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
575 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
576 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
577 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
578 F->addAttribute(1, Attribute::ZExt);
579 F->addAttribute(2, Attribute::ZExt);
580 }
581 DFSanUnionLoadFn =
582 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
583 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
Peter Collingbourne0be79e12013-11-21 23:20:54 +0000584 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000585 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
586 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000587 DFSanUnimplementedFn =
588 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000589 DFSanSetLabelFn =
590 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
591 if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
592 F->addAttribute(1, Attribute::ZExt);
593 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000594 DFSanNonzeroLabelFn =
595 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000596
597 std::vector<Function *> FnsToInstrument;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000598 llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000599 for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000600 if (!i->isIntrinsic() &&
601 i != DFSanUnionFn &&
602 i != DFSanUnionLoadFn &&
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000603 i != DFSanUnimplementedFn &&
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000604 i != DFSanSetLabelFn &&
605 i != DFSanNonzeroLabelFn)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000606 FnsToInstrument.push_back(&*i);
607 }
608
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000609 // Give function aliases prefixes when necessary, and build wrappers where the
610 // instrumentedness is inconsistent.
Peter Collingbourne59b12622013-08-22 20:08:08 +0000611 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
612 GlobalAlias *GA = &*i;
613 ++i;
614 // Don't stop on weak. We assume people aren't playing games with the
615 // instrumentedness of overridden weak aliases.
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000616 if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000617 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
618 if (GAInst && FInst) {
619 addGlobalNamePrefix(GA);
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000620 } else if (GAInst != FInst) {
621 // Non-instrumented alias of an instrumented function, or vice versa.
622 // Replace the alias with a native-ABI wrapper of the aliasee. The pass
623 // below will take care of instrumenting it.
624 Function *NewF =
625 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000626 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000627 NewF->takeName(GA);
628 GA->eraseFromParent();
629 FnsToInstrument.push_back(NewF);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000630 }
631 }
632 }
633
Peter Collingbourne68162e72013-08-14 18:54:12 +0000634 AttrBuilder B;
635 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
636 ReadOnlyNoneAttrs = AttributeSet::get(*Ctx, AttributeSet::FunctionIndex, B);
637
638 // First, change the ABI of every function in the module. ABI-listed
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000639 // functions keep their original ABI and get a wrapper function.
640 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
641 e = FnsToInstrument.end();
642 i != e; ++i) {
643 Function &F = **i;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000644 FunctionType *FT = F.getFunctionType();
Peter Collingbourne68162e72013-08-14 18:54:12 +0000645
Peter Collingbourne59b12622013-08-22 20:08:08 +0000646 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
647 FT->getReturnType()->isVoidTy());
Peter Collingbourne68162e72013-08-14 18:54:12 +0000648
649 if (isInstrumented(&F)) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000650 // Instrumented functions get a 'dfs$' prefix. This allows us to more
651 // easily identify cases of mismatching ABIs.
652 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000653 FunctionType *NewFT = getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000654 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000655 NewF->copyAttributesFrom(&F);
656 NewF->removeAttributes(
657 AttributeSet::ReturnIndex,
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000658 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
Peter Collingbourne68162e72013-08-14 18:54:12 +0000659 AttributeSet::ReturnIndex));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000660 for (Function::arg_iterator FArg = F.arg_begin(),
661 NewFArg = NewF->arg_begin(),
662 FArgEnd = F.arg_end();
663 FArg != FArgEnd; ++FArg, ++NewFArg) {
664 FArg->replaceAllUsesWith(NewFArg);
665 }
666 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
667
Chandler Carruthcdf47882014-03-09 03:16:01 +0000668 for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
669 UI != UE;) {
670 BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
671 ++UI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000672 if (BA) {
673 BA->replaceAllUsesWith(
674 BlockAddress::get(NewF, BA->getBasicBlock()));
675 delete BA;
676 }
677 }
678 F.replaceAllUsesWith(
679 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
680 NewF->takeName(&F);
681 F.eraseFromParent();
682 *i = NewF;
Peter Collingbourne59b12622013-08-22 20:08:08 +0000683 addGlobalNamePrefix(NewF);
684 } else {
685 addGlobalNamePrefix(&F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000686 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000687 // Hopefully, nobody will try to indirectly call a vararg
688 // function... yet.
689 } else if (FT->isVarArg()) {
690 UnwrappedFnMap[&F] = &F;
Craig Topperf40110f2014-04-25 05:29:35 +0000691 *i = nullptr;
Peter Collingbourne59b12622013-08-22 20:08:08 +0000692 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000693 // Build a wrapper function for F. The wrapper simply calls F, and is
694 // added to FnsToInstrument so that any instrumentation according to its
695 // WrapperKind is done in the second pass below.
696 FunctionType *NewFT = getInstrumentedABI() == IA_Args
697 ? getArgsFunctionType(FT)
698 : FT;
Alexey Samsonov6dae24d2013-08-23 07:42:51 +0000699 Function *NewF = buildWrapperFunction(
700 &F, std::string("dfsw$") + std::string(F.getName()),
701 GlobalValue::LinkOnceODRLinkage, NewFT);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000702 if (getInstrumentedABI() == IA_TLS)
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000703 NewF->removeAttributes(AttributeSet::FunctionIndex, ReadOnlyNoneAttrs);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000704
Peter Collingbourne68162e72013-08-14 18:54:12 +0000705 Value *WrappedFnCst =
706 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
707 F.replaceAllUsesWith(WrappedFnCst);
708 UnwrappedFnMap[WrappedFnCst] = &F;
709 *i = NewF;
710
711 if (!F.isDeclaration()) {
712 // This function is probably defining an interposition of an
713 // uninstrumented function and hence needs to keep the original ABI.
714 // But any functions it may call need to use the instrumented ABI, so
715 // we instrument it in a mode which preserves the original ABI.
716 FnsWithNativeABI.insert(&F);
717
718 // This code needs to rebuild the iterators, as they may be invalidated
719 // by the push_back, taking care that the new range does not include
720 // any functions added by this code.
721 size_t N = i - FnsToInstrument.begin(),
722 Count = e - FnsToInstrument.begin();
723 FnsToInstrument.push_back(&F);
724 i = FnsToInstrument.begin() + N;
725 e = FnsToInstrument.begin() + Count;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000726 }
727 }
728 }
729
730 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
731 e = FnsToInstrument.end();
732 i != e; ++i) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000733 if (!*i || (*i)->isDeclaration())
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000734 continue;
735
Peter Collingbourneae66d572013-08-09 21:42:53 +0000736 removeUnreachableBlocks(**i);
737
Peter Collingbourne68162e72013-08-14 18:54:12 +0000738 DFSanFunction DFSF(*this, *i, FnsWithNativeABI.count(*i));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000739
740 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
741 // Build a copy of the list before iterating over it.
David Blaikieceec2bd2014-04-11 01:50:01 +0000742 llvm::SmallVector<BasicBlock *, 4> BBList(
743 depth_first(&(*i)->getEntryBlock()));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000744
745 for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
746 e = BBList.end();
747 i != e; ++i) {
748 Instruction *Inst = &(*i)->front();
749 while (1) {
750 // DFSanVisitor may split the current basic block, changing the current
751 // instruction's next pointer and moving the next instruction to the
752 // tail block from which we should continue.
753 Instruction *Next = Inst->getNextNode();
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000754 // DFSanVisitor may delete Inst, so keep track of whether it was a
755 // terminator.
756 bool IsTerminator = isa<TerminatorInst>(Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000757 if (!DFSF.SkipInsts.count(Inst))
758 DFSanVisitor(DFSF).visit(Inst);
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000759 if (IsTerminator)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000760 break;
761 Inst = Next;
762 }
763 }
764
Peter Collingbourne68162e72013-08-14 18:54:12 +0000765 // We will not necessarily be able to compute the shadow for every phi node
766 // until we have visited every block. Therefore, the code that handles phi
767 // nodes adds them to the PHIFixups list so that they can be properly
768 // handled here.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000769 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
770 i = DFSF.PHIFixups.begin(),
771 e = DFSF.PHIFixups.end();
772 i != e; ++i) {
773 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
774 ++val) {
775 i->second->setIncomingValue(
776 val, DFSF.getShadow(i->first->getIncomingValue(val)));
777 }
778 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000779
780 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
781 // places (i.e. instructions in basic blocks we haven't even begun visiting
782 // yet). To make our life easier, do this work in a pass after the main
783 // instrumentation.
784 if (ClDebugNonzeroLabels) {
785 for (DenseSet<Value *>::iterator i = DFSF.NonZeroChecks.begin(),
786 e = DFSF.NonZeroChecks.end();
787 i != e; ++i) {
788 Instruction *Pos;
789 if (Instruction *I = dyn_cast<Instruction>(*i))
790 Pos = I->getNextNode();
791 else
792 Pos = DFSF.F->getEntryBlock().begin();
793 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
794 Pos = Pos->getNextNode();
795 IRBuilder<> IRB(Pos);
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000796 Value *Ne = IRB.CreateICmpNE(*i, DFSF.DFS.ZeroShadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000797 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000798 Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000799 IRBuilder<> ThenIRB(BI);
800 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn);
801 }
802 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000803 }
804
805 return false;
806}
807
808Value *DFSanFunction::getArgTLSPtr() {
809 if (ArgTLSPtr)
810 return ArgTLSPtr;
811 if (DFS.ArgTLS)
812 return ArgTLSPtr = DFS.ArgTLS;
813
814 IRBuilder<> IRB(F->getEntryBlock().begin());
815 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
816}
817
818Value *DFSanFunction::getRetvalTLS() {
819 if (RetvalTLSPtr)
820 return RetvalTLSPtr;
821 if (DFS.RetvalTLS)
822 return RetvalTLSPtr = DFS.RetvalTLS;
823
824 IRBuilder<> IRB(F->getEntryBlock().begin());
825 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
826}
827
828Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
829 IRBuilder<> IRB(Pos);
830 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
831}
832
833Value *DFSanFunction::getShadow(Value *V) {
834 if (!isa<Argument>(V) && !isa<Instruction>(V))
835 return DFS.ZeroShadow;
836 Value *&Shadow = ValShadowMap[V];
837 if (!Shadow) {
838 if (Argument *A = dyn_cast<Argument>(V)) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000839 if (IsNativeABI)
840 return DFS.ZeroShadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000841 switch (IA) {
842 case DataFlowSanitizer::IA_TLS: {
843 Value *ArgTLSPtr = getArgTLSPtr();
844 Instruction *ArgTLSPos =
845 DFS.ArgTLS ? &*F->getEntryBlock().begin()
846 : cast<Instruction>(ArgTLSPtr)->getNextNode();
847 IRBuilder<> IRB(ArgTLSPos);
848 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
849 break;
850 }
851 case DataFlowSanitizer::IA_Args: {
852 unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
853 Function::arg_iterator i = F->arg_begin();
854 while (ArgIdx--)
855 ++i;
856 Shadow = i;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000857 assert(Shadow->getType() == DFS.ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000858 break;
859 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000860 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000861 NonZeroChecks.insert(Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000862 } else {
863 Shadow = DFS.ZeroShadow;
864 }
865 }
866 return Shadow;
867}
868
869void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
870 assert(!ValShadowMap.count(I));
871 assert(Shadow->getType() == DFS.ShadowTy);
872 ValShadowMap[I] = Shadow;
873}
874
875Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
876 assert(Addr != RetvalTLS && "Reinstrumenting?");
877 IRBuilder<> IRB(Pos);
878 return IRB.CreateIntToPtr(
879 IRB.CreateMul(
880 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
881 ShadowPtrMul),
882 ShadowPtrTy);
883}
884
885// Generates IR to compute the union of the two given shadows, inserting it
886// before Pos. Returns the computed union Value.
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000887Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
888 if (V1 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000889 return V2;
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000890 if (V2 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000891 return V1;
892 if (V1 == V2)
893 return V1;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000894
895 auto Key = std::make_pair(V1, V2);
896 if (V1 > V2)
897 std::swap(Key.first, Key.second);
898 CachedCombinedShadow &CCS = CachedCombinedShadows[Key];
899 if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
900 return CCS.Shadow;
901
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000902 IRBuilder<> IRB(Pos);
903 BasicBlock *Head = Pos->getParent();
904 Value *Ne = IRB.CreateICmpNE(V1, V2);
Evgeniy Stepanova284e552013-12-19 14:37:03 +0000905 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000906 Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
Evgeniy Stepanova284e552013-12-19 14:37:03 +0000907 IRBuilder<> ThenIRB(BI);
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000908 CallInst *Call = ThenIRB.CreateCall2(DFS.DFSanUnionFn, V1, V2);
Evgeniy Stepanova284e552013-12-19 14:37:03 +0000909 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
910 Call->addAttribute(1, Attribute::ZExt);
911 Call->addAttribute(2, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000912
Evgeniy Stepanova284e552013-12-19 14:37:03 +0000913 BasicBlock *Tail = BI->getSuccessor(0);
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000914 PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", Tail->begin());
Evgeniy Stepanova284e552013-12-19 14:37:03 +0000915 Phi->addIncoming(Call, Call->getParent());
916 Phi->addIncoming(V1, Head);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000917
918 CCS.Block = Tail;
919 CCS.Shadow = Phi;
Evgeniy Stepanova284e552013-12-19 14:37:03 +0000920 return Phi;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000921}
922
923// A convenience function which folds the shadows of each of the operands
924// of the provided instruction Inst, inserting the IR before Inst. Returns
925// the computed union Value.
926Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
927 if (Inst->getNumOperands() == 0)
928 return DFS.ZeroShadow;
929
930 Value *Shadow = getShadow(Inst->getOperand(0));
931 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000932 Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000933 }
934 return Shadow;
935}
936
937void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
938 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
939 DFSF.setShadow(&I, CombinedShadow);
940}
941
942// Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
943// Addr has alignment Align, and take the union of each of those shadows.
944Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
945 Instruction *Pos) {
946 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
947 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
948 AllocaShadowMap.find(AI);
949 if (i != AllocaShadowMap.end()) {
950 IRBuilder<> IRB(Pos);
951 return IRB.CreateLoad(i->second);
952 }
953 }
954
955 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
956 SmallVector<Value *, 2> Objs;
957 GetUnderlyingObjects(Addr, Objs, DFS.DL);
958 bool AllConstants = true;
959 for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
960 i != e; ++i) {
961 if (isa<Function>(*i) || isa<BlockAddress>(*i))
962 continue;
963 if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
964 continue;
965
966 AllConstants = false;
967 break;
968 }
969 if (AllConstants)
970 return DFS.ZeroShadow;
971
972 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
973 switch (Size) {
974 case 0:
975 return DFS.ZeroShadow;
976 case 1: {
977 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
978 LI->setAlignment(ShadowAlign);
979 return LI;
980 }
981 case 2: {
982 IRBuilder<> IRB(Pos);
983 Value *ShadowAddr1 =
984 IRB.CreateGEP(ShadowAddr, ConstantInt::get(DFS.IntptrTy, 1));
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000985 return combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
986 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign), Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000987 }
988 }
989 if (Size % (64 / DFS.ShadowWidth) == 0) {
990 // Fast path for the common case where each byte has identical shadow: load
991 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
992 // shadow is non-equal.
993 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
994 IRBuilder<> FallbackIRB(FallbackBB);
995 CallInst *FallbackCall = FallbackIRB.CreateCall2(
996 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
997 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
998
999 // Compare each of the shadows stored in the loaded 64 bits to each other,
1000 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
1001 IRBuilder<> IRB(Pos);
1002 Value *WideAddr =
1003 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1004 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1005 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
1006 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
1007 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
1008 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1009 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1010
1011 BasicBlock *Head = Pos->getParent();
1012 BasicBlock *Tail = Head->splitBasicBlock(Pos);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001013
1014 if (DomTreeNode *OldNode = DT.getNode(Head)) {
1015 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1016
1017 DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1018 for (auto Child : Children)
1019 DT.changeImmediateDominator(Child, NewNode);
1020 }
1021
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001022 // In the following code LastBr will refer to the previous basic block's
1023 // conditional branch instruction, whose true successor is fixed up to point
1024 // to the next block during the loop below or to the tail after the final
1025 // iteration.
1026 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1027 ReplaceInstWithInst(Head->getTerminator(), LastBr);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001028 DT.addNewBlock(FallbackBB, Head);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001029
1030 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
1031 Ofs += 64 / DFS.ShadowWidth) {
1032 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001033 DT.addNewBlock(NextBB, LastBr->getParent());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001034 IRBuilder<> NextIRB(NextBB);
1035 WideAddr = NextIRB.CreateGEP(WideAddr, ConstantInt::get(DFS.IntptrTy, 1));
1036 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1037 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1038 LastBr->setSuccessor(0, NextBB);
1039 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1040 }
1041
1042 LastBr->setSuccessor(0, Tail);
1043 FallbackIRB.CreateBr(Tail);
1044 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1045 Shadow->addIncoming(FallbackCall, FallbackBB);
1046 Shadow->addIncoming(TruncShadow, LastBr->getParent());
1047 return Shadow;
1048 }
1049
1050 IRBuilder<> IRB(Pos);
1051 CallInst *FallbackCall = IRB.CreateCall2(
1052 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
1053 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1054 return FallbackCall;
1055}
1056
1057void DFSanVisitor::visitLoadInst(LoadInst &LI) {
1058 uint64_t Size = DFSF.DFS.DL->getTypeStoreSize(LI.getType());
1059 uint64_t Align;
1060 if (ClPreserveAlignment) {
1061 Align = LI.getAlignment();
1062 if (Align == 0)
1063 Align = DFSF.DFS.DL->getABITypeAlignment(LI.getType());
1064 } else {
1065 Align = 1;
1066 }
1067 IRBuilder<> IRB(&LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001068 Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
1069 if (ClCombinePointerLabelsOnLoad) {
1070 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001071 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001072 }
1073 if (Shadow != DFSF.DFS.ZeroShadow)
1074 DFSF.NonZeroChecks.insert(Shadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +00001075
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001076 DFSF.setShadow(&LI, Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001077}
1078
1079void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
1080 Value *Shadow, Instruction *Pos) {
1081 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1082 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1083 AllocaShadowMap.find(AI);
1084 if (i != AllocaShadowMap.end()) {
1085 IRBuilder<> IRB(Pos);
1086 IRB.CreateStore(Shadow, i->second);
1087 return;
1088 }
1089 }
1090
1091 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1092 IRBuilder<> IRB(Pos);
1093 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1094 if (Shadow == DFS.ZeroShadow) {
1095 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1096 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1097 Value *ExtShadowAddr =
1098 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1099 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1100 return;
1101 }
1102
1103 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1104 uint64_t Offset = 0;
1105 if (Size >= ShadowVecSize) {
1106 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1107 Value *ShadowVec = UndefValue::get(ShadowVecTy);
1108 for (unsigned i = 0; i != ShadowVecSize; ++i) {
1109 ShadowVec = IRB.CreateInsertElement(
1110 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1111 }
1112 Value *ShadowVecAddr =
1113 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1114 do {
1115 Value *CurShadowVecAddr = IRB.CreateConstGEP1_32(ShadowVecAddr, Offset);
1116 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1117 Size -= ShadowVecSize;
1118 ++Offset;
1119 } while (Size >= ShadowVecSize);
1120 Offset *= ShadowVecSize;
1121 }
1122 while (Size > 0) {
1123 Value *CurShadowAddr = IRB.CreateConstGEP1_32(ShadowAddr, Offset);
1124 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1125 --Size;
1126 ++Offset;
1127 }
1128}
1129
1130void DFSanVisitor::visitStoreInst(StoreInst &SI) {
1131 uint64_t Size =
1132 DFSF.DFS.DL->getTypeStoreSize(SI.getValueOperand()->getType());
1133 uint64_t Align;
1134 if (ClPreserveAlignment) {
1135 Align = SI.getAlignment();
1136 if (Align == 0)
1137 Align = DFSF.DFS.DL->getABITypeAlignment(SI.getValueOperand()->getType());
1138 } else {
1139 Align = 1;
1140 }
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001141
1142 Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1143 if (ClCombinePointerLabelsOnStore) {
1144 Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001145 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001146 }
1147 DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001148}
1149
1150void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1151 visitOperandShadowInst(BO);
1152}
1153
1154void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1155
1156void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1157
1158void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1159 visitOperandShadowInst(GEPI);
1160}
1161
1162void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1163 visitOperandShadowInst(I);
1164}
1165
1166void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1167 visitOperandShadowInst(I);
1168}
1169
1170void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1171 visitOperandShadowInst(I);
1172}
1173
1174void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1175 visitOperandShadowInst(I);
1176}
1177
1178void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1179 visitOperandShadowInst(I);
1180}
1181
1182void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1183 bool AllLoadsStores = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001184 for (User *U : I.users()) {
1185 if (isa<LoadInst>(U))
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001186 continue;
1187
Chandler Carruthcdf47882014-03-09 03:16:01 +00001188 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001189 if (SI->getPointerOperand() == &I)
1190 continue;
1191 }
1192
1193 AllLoadsStores = false;
1194 break;
1195 }
1196 if (AllLoadsStores) {
1197 IRBuilder<> IRB(&I);
1198 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1199 }
1200 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1201}
1202
1203void DFSanVisitor::visitSelectInst(SelectInst &I) {
1204 Value *CondShadow = DFSF.getShadow(I.getCondition());
1205 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1206 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1207
1208 if (isa<VectorType>(I.getCondition()->getType())) {
1209 DFSF.setShadow(
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001210 &I,
1211 DFSF.combineShadows(
1212 CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001213 } else {
1214 Value *ShadowSel;
1215 if (TrueShadow == FalseShadow) {
1216 ShadowSel = TrueShadow;
1217 } else {
1218 ShadowSel =
1219 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1220 }
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001221 DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001222 }
1223}
1224
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +00001225void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1226 IRBuilder<> IRB(&I);
1227 Value *ValShadow = DFSF.getShadow(I.getValue());
1228 IRB.CreateCall3(
1229 DFSF.DFS.DFSanSetLabelFn, ValShadow,
1230 IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
1231 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy));
1232}
1233
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001234void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1235 IRBuilder<> IRB(&I);
1236 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1237 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1238 Value *LenShadow = IRB.CreateMul(
1239 I.getLength(),
1240 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
1241 Value *AlignShadow;
1242 if (ClPreserveAlignment) {
1243 AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1244 ConstantInt::get(I.getAlignmentCst()->getType(),
1245 DFSF.DFS.ShadowWidth / 8));
1246 } else {
1247 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1248 DFSF.DFS.ShadowWidth / 8);
1249 }
1250 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1251 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1252 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
1253 IRB.CreateCall5(I.getCalledValue(), DestShadow, SrcShadow, LenShadow,
1254 AlignShadow, I.getVolatileCst());
1255}
1256
1257void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001258 if (!DFSF.IsNativeABI && RI.getReturnValue()) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001259 switch (DFSF.IA) {
1260 case DataFlowSanitizer::IA_TLS: {
1261 Value *S = DFSF.getShadow(RI.getReturnValue());
1262 IRBuilder<> IRB(&RI);
1263 IRB.CreateStore(S, DFSF.getRetvalTLS());
1264 break;
1265 }
1266 case DataFlowSanitizer::IA_Args: {
1267 IRBuilder<> IRB(&RI);
1268 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1269 Value *InsVal =
1270 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1271 Value *InsShadow =
1272 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1273 RI.setOperand(0, InsShadow);
1274 break;
1275 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001276 }
1277 }
1278}
1279
1280void DFSanVisitor::visitCallSite(CallSite CS) {
1281 Function *F = CS.getCalledFunction();
1282 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1283 visitOperandShadowInst(*CS.getInstruction());
1284 return;
1285 }
1286
Peter Collingbourne68162e72013-08-14 18:54:12 +00001287 IRBuilder<> IRB(CS.getInstruction());
1288
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001289 DenseMap<Value *, Function *>::iterator i =
1290 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1291 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001292 Function *F = i->second;
1293 switch (DFSF.DFS.getWrapperKind(F)) {
1294 case DataFlowSanitizer::WK_Warning: {
1295 CS.setCalledFunction(F);
1296 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1297 IRB.CreateGlobalStringPtr(F->getName()));
1298 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1299 return;
1300 }
1301 case DataFlowSanitizer::WK_Discard: {
1302 CS.setCalledFunction(F);
1303 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1304 return;
1305 }
1306 case DataFlowSanitizer::WK_Functional: {
1307 CS.setCalledFunction(F);
1308 visitOperandShadowInst(*CS.getInstruction());
1309 return;
1310 }
1311 case DataFlowSanitizer::WK_Custom: {
1312 // Don't try to handle invokes of custom functions, it's too complicated.
1313 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1314 // wrapper.
1315 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1316 FunctionType *FT = F->getFunctionType();
1317 FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1318 std::string CustomFName = "__dfsw_";
1319 CustomFName += F->getName();
1320 Constant *CustomF =
1321 DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1322 if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1323 CustomFn->copyAttributesFrom(F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001324
Peter Collingbourne68162e72013-08-14 18:54:12 +00001325 // Custom functions returning non-void will write to the return label.
1326 if (!FT->getReturnType()->isVoidTy()) {
1327 CustomFn->removeAttributes(AttributeSet::FunctionIndex,
1328 DFSF.DFS.ReadOnlyNoneAttrs);
1329 }
1330 }
1331
1332 std::vector<Value *> Args;
1333
1334 CallSite::arg_iterator i = CS.arg_begin();
Peter Collingbourne28a10af2013-08-27 22:09:06 +00001335 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
1336 Type *T = (*i)->getType();
1337 FunctionType *ParamFT;
1338 if (isa<PointerType>(T) &&
1339 (ParamFT = dyn_cast<FunctionType>(
1340 cast<PointerType>(T)->getElementType()))) {
1341 std::string TName = "dfst";
1342 TName += utostr(FT->getNumParams() - n);
1343 TName += "$";
1344 TName += F->getName();
1345 Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1346 Args.push_back(T);
1347 Args.push_back(
1348 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1349 } else {
1350 Args.push_back(*i);
1351 }
1352 }
Peter Collingbourne68162e72013-08-14 18:54:12 +00001353
1354 i = CS.arg_begin();
1355 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1356 Args.push_back(DFSF.getShadow(*i));
1357
1358 if (!FT->getReturnType()->isVoidTy()) {
1359 if (!DFSF.LabelReturnAlloca) {
1360 DFSF.LabelReturnAlloca =
1361 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
1362 DFSF.F->getEntryBlock().begin());
1363 }
1364 Args.push_back(DFSF.LabelReturnAlloca);
1365 }
1366
1367 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1368 CustomCI->setCallingConv(CI->getCallingConv());
1369 CustomCI->setAttributes(CI->getAttributes());
1370
1371 if (!FT->getReturnType()->isVoidTy()) {
1372 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1373 DFSF.setShadow(CustomCI, LabelLoad);
1374 }
1375
1376 CI->replaceAllUsesWith(CustomCI);
1377 CI->eraseFromParent();
1378 return;
1379 }
1380 break;
1381 }
1382 }
1383 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001384
1385 FunctionType *FT = cast<FunctionType>(
1386 CS.getCalledValue()->getType()->getPointerElementType());
Peter Collingbourne68162e72013-08-14 18:54:12 +00001387 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001388 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1389 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1390 DFSF.getArgTLS(i, CS.getInstruction()));
1391 }
1392 }
1393
Craig Topperf40110f2014-04-25 05:29:35 +00001394 Instruction *Next = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001395 if (!CS.getType()->isVoidTy()) {
1396 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1397 if (II->getNormalDest()->getSinglePredecessor()) {
1398 Next = II->getNormalDest()->begin();
1399 } else {
1400 BasicBlock *NewBB =
1401 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DFS);
1402 Next = NewBB->begin();
1403 }
1404 } else {
1405 Next = CS->getNextNode();
1406 }
1407
Peter Collingbourne68162e72013-08-14 18:54:12 +00001408 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001409 IRBuilder<> NextIRB(Next);
1410 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1411 DFSF.SkipInsts.insert(LI);
1412 DFSF.setShadow(CS.getInstruction(), LI);
Peter Collingbourne444c59e2013-08-15 18:51:12 +00001413 DFSF.NonZeroChecks.insert(LI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001414 }
1415 }
1416
1417 // Do all instrumentation for IA_Args down here to defer tampering with the
1418 // CFG in a way that SplitEdge may be able to detect.
Peter Collingbourne68162e72013-08-14 18:54:12 +00001419 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1420 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001421 Value *Func =
1422 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1423 std::vector<Value *> Args;
1424
1425 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1426 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1427 Args.push_back(*i);
1428
1429 i = CS.arg_begin();
1430 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1431 Args.push_back(DFSF.getShadow(*i));
1432
1433 if (FT->isVarArg()) {
1434 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1435 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1436 AllocaInst *VarArgShadow =
1437 new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
1438 Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
1439 for (unsigned n = 0; i != e; ++i, ++n) {
1440 IRB.CreateStore(DFSF.getShadow(*i),
1441 IRB.CreateConstGEP2_32(VarArgShadow, 0, n));
1442 Args.push_back(*i);
1443 }
1444 }
1445
1446 CallSite NewCS;
1447 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1448 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1449 Args);
1450 } else {
1451 NewCS = IRB.CreateCall(Func, Args);
1452 }
1453 NewCS.setCallingConv(CS.getCallingConv());
1454 NewCS.setAttributes(CS.getAttributes().removeAttributes(
1455 *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
1456 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType(),
1457 AttributeSet::ReturnIndex)));
1458
1459 if (Next) {
1460 ExtractValueInst *ExVal =
1461 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1462 DFSF.SkipInsts.insert(ExVal);
1463 ExtractValueInst *ExShadow =
1464 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1465 DFSF.SkipInsts.insert(ExShadow);
1466 DFSF.setShadow(ExVal, ExShadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +00001467 DFSF.NonZeroChecks.insert(ExShadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001468
1469 CS.getInstruction()->replaceAllUsesWith(ExVal);
1470 }
1471
1472 CS.getInstruction()->eraseFromParent();
1473 }
1474}
1475
1476void DFSanVisitor::visitPHINode(PHINode &PN) {
1477 PHINode *ShadowPN =
1478 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1479
1480 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1481 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1482 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1483 ++i) {
1484 ShadowPN->addIncoming(UndefShadow, *i);
1485 }
1486
1487 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1488 DFSF.setShadow(&PN, ShadowPN);
1489}