blob: 35057cdd47e9783c70f482ad95e5c49cc9025b28 [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 Collingbourne9947c492014-07-15 22:13:19 +000066#include <algorithm>
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000067#include <iterator>
Peter Collingbourne9947c492014-07-15 22:13:19 +000068#include <set>
69#include <utility>
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000070
71using namespace llvm;
72
73// The -dfsan-preserve-alignment flag controls whether this pass assumes that
74// alignment requirements provided by the input IR are correct. For example,
75// if the input IR contains a load with alignment 8, this flag will cause
76// the shadow load to have alignment 16. This flag is disabled by default as
77// we have unfortunately encountered too much code (including Clang itself;
78// see PR14291) which performs misaligned access.
79static cl::opt<bool> ClPreserveAlignment(
80 "dfsan-preserve-alignment",
81 cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
82 cl::init(false));
83
Peter Collingbourne68162e72013-08-14 18:54:12 +000084// The ABI list file controls how shadow parameters are passed. The pass treats
85// every function labelled "uninstrumented" in the ABI list file as conforming
86// to the "native" (i.e. unsanitized) ABI. Unless the ABI list contains
87// additional annotations for those functions, a call to one of those functions
88// will produce a warning message, as the labelling behaviour of the function is
89// unknown. The other supported annotations are "functional" and "discard",
90// which are described below under DataFlowSanitizer::WrapperKind.
91static cl::opt<std::string> ClABIListFile(
92 "dfsan-abilist",
93 cl::desc("File listing native ABI functions and how the pass treats them"),
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000094 cl::Hidden);
95
Peter Collingbourne68162e72013-08-14 18:54:12 +000096// Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
97// functions (see DataFlowSanitizer::InstrumentedABI below).
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000098static cl::opt<bool> ClArgsABI(
99 "dfsan-args-abi",
100 cl::desc("Use the argument ABI rather than the TLS ABI"),
101 cl::Hidden);
102
Peter Collingbourne0be79e12013-11-21 23:20:54 +0000103// Controls whether the pass includes or ignores the labels of pointers in load
104// instructions.
105static cl::opt<bool> ClCombinePointerLabelsOnLoad(
106 "dfsan-combine-pointer-labels-on-load",
107 cl::desc("Combine the label of the pointer with the label of the data when "
108 "loading from memory."),
109 cl::Hidden, cl::init(true));
110
111// Controls whether the pass includes or ignores the labels of pointers in
112// stores instructions.
113static cl::opt<bool> ClCombinePointerLabelsOnStore(
114 "dfsan-combine-pointer-labels-on-store",
115 cl::desc("Combine the label of the pointer with the label of the data when "
116 "storing in memory."),
117 cl::Hidden, cl::init(false));
118
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000119static cl::opt<bool> ClDebugNonzeroLabels(
120 "dfsan-debug-nonzero-labels",
121 cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
122 "load or return with a nonzero label"),
123 cl::Hidden);
124
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000125namespace {
126
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000127StringRef GetGlobalTypeString(const GlobalValue &G) {
128 // Types of GlobalVariables are always pointer types.
129 Type *GType = G.getType()->getElementType();
130 // For now we support blacklisting struct types only.
131 if (StructType *SGType = dyn_cast<StructType>(GType)) {
132 if (!SGType->isLiteral())
133 return SGType->getName();
134 }
135 return "<unknown type>";
136}
137
138class DFSanABIList {
139 std::unique_ptr<SpecialCaseList> SCL;
140
141 public:
142 DFSanABIList(SpecialCaseList *SCL) : SCL(SCL) {}
143
144 /// Returns whether either this function or its source file are listed in the
145 /// given category.
146 bool isIn(const Function &F, const StringRef Category) const {
147 return isIn(*F.getParent(), Category) ||
148 SCL->inSection("fun", F.getName(), Category);
149 }
150
151 /// Returns whether this global alias is listed in the given category.
152 ///
153 /// If GA aliases a function, the alias's name is matched as a function name
154 /// would be. Similarly, aliases of globals are matched like globals.
155 bool isIn(const GlobalAlias &GA, const StringRef Category) const {
156 if (isIn(*GA.getParent(), Category))
157 return true;
158
159 if (isa<FunctionType>(GA.getType()->getElementType()))
160 return SCL->inSection("fun", GA.getName(), Category);
161
162 return SCL->inSection("global", GA.getName(), Category) ||
163 SCL->inSection("type", GetGlobalTypeString(GA), Category);
164 }
165
166 /// Returns whether this module is listed in the given category.
167 bool isIn(const Module &M, const StringRef Category) const {
168 return SCL->inSection("src", M.getModuleIdentifier(), Category);
169 }
170};
171
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000172class DataFlowSanitizer : public ModulePass {
173 friend struct DFSanFunction;
174 friend class DFSanVisitor;
175
176 enum {
177 ShadowWidth = 16
178 };
179
Peter Collingbourne68162e72013-08-14 18:54:12 +0000180 /// Which ABI should be used for instrumented functions?
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000181 enum InstrumentedABI {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000182 /// Argument and return value labels are passed through additional
183 /// arguments and by modifying the return type.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000184 IA_Args,
Peter Collingbourne68162e72013-08-14 18:54:12 +0000185
186 /// Argument and return value labels are passed through TLS variables
187 /// __dfsan_arg_tls and __dfsan_retval_tls.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000188 IA_TLS
189 };
190
Peter Collingbourne68162e72013-08-14 18:54:12 +0000191 /// How should calls to uninstrumented functions be handled?
192 enum WrapperKind {
193 /// This function is present in an uninstrumented form but we don't know
194 /// how it should be handled. Print a warning and call the function anyway.
195 /// Don't label the return value.
196 WK_Warning,
197
198 /// This function does not write to (user-accessible) memory, and its return
199 /// value is unlabelled.
200 WK_Discard,
201
202 /// This function does not write to (user-accessible) memory, and the label
203 /// of its return value is the union of the label of its arguments.
204 WK_Functional,
205
206 /// Instead of calling the function, a custom wrapper __dfsw_F is called,
207 /// where F is the name of the function. This function may wrap the
208 /// original function or provide its own implementation. This is similar to
209 /// the IA_Args ABI, except that IA_Args uses a struct return type to
210 /// pass the return value shadow in a register, while WK_Custom uses an
211 /// extra pointer argument to return the shadow. This allows the wrapped
212 /// form of the function type to be expressed in C.
213 WK_Custom
214 };
215
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000216 const DataLayout *DL;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000217 Module *Mod;
218 LLVMContext *Ctx;
219 IntegerType *ShadowTy;
220 PointerType *ShadowPtrTy;
221 IntegerType *IntptrTy;
222 ConstantInt *ZeroShadow;
223 ConstantInt *ShadowPtrMask;
224 ConstantInt *ShadowPtrMul;
225 Constant *ArgTLS;
226 Constant *RetvalTLS;
227 void *(*GetArgTLSPtr)();
228 void *(*GetRetvalTLSPtr)();
229 Constant *GetArgTLS;
230 Constant *GetRetvalTLS;
231 FunctionType *DFSanUnionFnTy;
232 FunctionType *DFSanUnionLoadFnTy;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000233 FunctionType *DFSanUnimplementedFnTy;
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000234 FunctionType *DFSanSetLabelFnTy;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000235 FunctionType *DFSanNonzeroLabelFnTy;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000236 Constant *DFSanUnionFn;
237 Constant *DFSanUnionLoadFn;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000238 Constant *DFSanUnimplementedFn;
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000239 Constant *DFSanSetLabelFn;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000240 Constant *DFSanNonzeroLabelFn;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000241 MDNode *ColdCallWeights;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000242 DFSanABIList ABIList;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000243 DenseMap<Value *, Function *> UnwrappedFnMap;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000244 AttributeSet ReadOnlyNoneAttrs;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000245
246 Value *getShadowAddress(Value *Addr, Instruction *Pos);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000247 bool isInstrumented(const Function *F);
248 bool isInstrumented(const GlobalAlias *GA);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000249 FunctionType *getArgsFunctionType(FunctionType *T);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000250 FunctionType *getTrampolineFunctionType(FunctionType *T);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000251 FunctionType *getCustomFunctionType(FunctionType *T);
252 InstrumentedABI getInstrumentedABI();
253 WrapperKind getWrapperKind(Function *F);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000254 void addGlobalNamePrefix(GlobalValue *GV);
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000255 Function *buildWrapperFunction(Function *F, StringRef NewFName,
256 GlobalValue::LinkageTypes NewFLink,
257 FunctionType *NewFT);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000258 Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000259
Dmitry Vyukov96a70842013-08-13 16:52:41 +0000260 public:
Peter Collingbourne68162e72013-08-14 18:54:12 +0000261 DataFlowSanitizer(StringRef ABIListFile = StringRef(),
Craig Topperf40110f2014-04-25 05:29:35 +0000262 void *(*getArgTLS)() = nullptr,
263 void *(*getRetValTLS)() = nullptr);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000264 static char ID;
Craig Topper3e4c6972014-03-05 09:10:37 +0000265 bool doInitialization(Module &M) override;
266 bool runOnModule(Module &M) override;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000267};
268
269struct DFSanFunction {
270 DataFlowSanitizer &DFS;
271 Function *F;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000272 DominatorTree DT;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000273 DataFlowSanitizer::InstrumentedABI IA;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000274 bool IsNativeABI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000275 Value *ArgTLSPtr;
276 Value *RetvalTLSPtr;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000277 AllocaInst *LabelReturnAlloca;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000278 DenseMap<Value *, Value *> ValShadowMap;
279 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
280 std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
281 DenseSet<Instruction *> SkipInsts;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000282 DenseSet<Value *> NonZeroChecks;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000283
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000284 struct CachedCombinedShadow {
285 BasicBlock *Block;
286 Value *Shadow;
287 };
288 DenseMap<std::pair<Value *, Value *>, CachedCombinedShadow>
289 CachedCombinedShadows;
Peter Collingbourne9947c492014-07-15 22:13:19 +0000290 DenseMap<Value *, std::set<Value *>> ShadowElements;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000291
Peter Collingbourne68162e72013-08-14 18:54:12 +0000292 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
293 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()),
Craig Topperf40110f2014-04-25 05:29:35 +0000294 IsNativeABI(IsNativeABI), ArgTLSPtr(nullptr), RetvalTLSPtr(nullptr),
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000295 LabelReturnAlloca(nullptr) {
296 DT.recalculate(*F);
297 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000298 Value *getArgTLSPtr();
299 Value *getArgTLS(unsigned Index, Instruction *Pos);
300 Value *getRetvalTLS();
301 Value *getShadow(Value *V);
302 void setShadow(Instruction *I, Value *Shadow);
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000303 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000304 Value *combineOperandShadows(Instruction *Inst);
305 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
306 Instruction *Pos);
307 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
308 Instruction *Pos);
309};
310
311class DFSanVisitor : public InstVisitor<DFSanVisitor> {
Dmitry Vyukov96a70842013-08-13 16:52:41 +0000312 public:
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000313 DFSanFunction &DFSF;
314 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
315
316 void visitOperandShadowInst(Instruction &I);
317
318 void visitBinaryOperator(BinaryOperator &BO);
319 void visitCastInst(CastInst &CI);
320 void visitCmpInst(CmpInst &CI);
321 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
322 void visitLoadInst(LoadInst &LI);
323 void visitStoreInst(StoreInst &SI);
324 void visitReturnInst(ReturnInst &RI);
325 void visitCallSite(CallSite CS);
326 void visitPHINode(PHINode &PN);
327 void visitExtractElementInst(ExtractElementInst &I);
328 void visitInsertElementInst(InsertElementInst &I);
329 void visitShuffleVectorInst(ShuffleVectorInst &I);
330 void visitExtractValueInst(ExtractValueInst &I);
331 void visitInsertValueInst(InsertValueInst &I);
332 void visitAllocaInst(AllocaInst &I);
333 void visitSelectInst(SelectInst &I);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000334 void visitMemSetInst(MemSetInst &I);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000335 void visitMemTransferInst(MemTransferInst &I);
336};
337
338}
339
340char DataFlowSanitizer::ID;
341INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
342 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
343
Peter Collingbourne68162e72013-08-14 18:54:12 +0000344ModulePass *llvm::createDataFlowSanitizerPass(StringRef ABIListFile,
345 void *(*getArgTLS)(),
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000346 void *(*getRetValTLS)()) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000347 return new DataFlowSanitizer(ABIListFile, getArgTLS, getRetValTLS);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000348}
349
Peter Collingbourne68162e72013-08-14 18:54:12 +0000350DataFlowSanitizer::DataFlowSanitizer(StringRef ABIListFile,
351 void *(*getArgTLS)(),
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000352 void *(*getRetValTLS)())
353 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS),
Peter Collingbourne68162e72013-08-14 18:54:12 +0000354 ABIList(SpecialCaseList::createOrDie(ABIListFile.empty() ? ClABIListFile
355 : ABIListFile)) {
356}
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000357
Peter Collingbourne68162e72013-08-14 18:54:12 +0000358FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000359 llvm::SmallVector<Type *, 4> ArgTypes;
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 if (T->isVarArg())
364 ArgTypes.push_back(ShadowPtrTy);
365 Type *RetType = T->getReturnType();
366 if (!RetType->isVoidTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000367 RetType = StructType::get(RetType, ShadowTy, (Type *)nullptr);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000368 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
369}
370
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000371FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
372 assert(!T->isVarArg());
373 llvm::SmallVector<Type *, 4> ArgTypes;
374 ArgTypes.push_back(T->getPointerTo());
375 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
376 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
377 ArgTypes.push_back(ShadowTy);
378 Type *RetType = T->getReturnType();
379 if (!RetType->isVoidTy())
380 ArgTypes.push_back(ShadowPtrTy);
381 return FunctionType::get(T->getReturnType(), ArgTypes, false);
382}
383
Peter Collingbourne68162e72013-08-14 18:54:12 +0000384FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
385 assert(!T->isVarArg());
386 llvm::SmallVector<Type *, 4> ArgTypes;
Alexey Samsonov9b7e2b52013-08-28 11:25:12 +0000387 for (FunctionType::param_iterator i = T->param_begin(), e = T->param_end();
388 i != e; ++i) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000389 FunctionType *FT;
Alexey Samsonov9b7e2b52013-08-28 11:25:12 +0000390 if (isa<PointerType>(*i) && (FT = dyn_cast<FunctionType>(cast<PointerType>(
391 *i)->getElementType()))) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000392 ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
393 ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
394 } else {
395 ArgTypes.push_back(*i);
396 }
397 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000398 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
399 ArgTypes.push_back(ShadowTy);
400 Type *RetType = T->getReturnType();
401 if (!RetType->isVoidTy())
402 ArgTypes.push_back(ShadowPtrTy);
403 return FunctionType::get(T->getReturnType(), ArgTypes, false);
404}
405
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000406bool DataFlowSanitizer::doInitialization(Module &M) {
Rafael Espindola93512512014-02-25 17:30:31 +0000407 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
408 if (!DLP)
Evgeniy Stepanov119cb2e2014-04-23 12:51:32 +0000409 report_fatal_error("data layout missing");
Rafael Espindola93512512014-02-25 17:30:31 +0000410 DL = &DLP->getDataLayout();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000411
412 Mod = &M;
413 Ctx = &M.getContext();
414 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
415 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
416 IntptrTy = DL->getIntPtrType(*Ctx);
417 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
Peter Collingbournea5689e62013-08-08 00:15:27 +0000418 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000419 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
420
421 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
422 DFSanUnionFnTy =
423 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
424 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
425 DFSanUnionLoadFnTy =
426 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000427 DFSanUnimplementedFnTy = FunctionType::get(
428 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000429 Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
430 DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
431 DFSanSetLabelArgs, /*isVarArg=*/false);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000432 DFSanNonzeroLabelFnTy = FunctionType::get(
433 Type::getVoidTy(*Ctx), ArrayRef<Type *>(), /*isVarArg=*/false);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000434
435 if (GetArgTLSPtr) {
436 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
Craig Topperf40110f2014-04-25 05:29:35 +0000437 ArgTLS = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000438 GetArgTLS = ConstantExpr::getIntToPtr(
439 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
440 PointerType::getUnqual(
Craig Topperf40110f2014-04-25 05:29:35 +0000441 FunctionType::get(PointerType::getUnqual(ArgTLSTy),
442 (Type *)nullptr)));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000443 }
444 if (GetRetvalTLSPtr) {
Craig Topperf40110f2014-04-25 05:29:35 +0000445 RetvalTLS = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000446 GetRetvalTLS = ConstantExpr::getIntToPtr(
447 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
448 PointerType::getUnqual(
Craig Topperf40110f2014-04-25 05:29:35 +0000449 FunctionType::get(PointerType::getUnqual(ShadowTy),
450 (Type *)nullptr)));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000451 }
452
453 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
454 return true;
455}
456
Peter Collingbourne59b12622013-08-22 20:08:08 +0000457bool DataFlowSanitizer::isInstrumented(const Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000458 return !ABIList.isIn(*F, "uninstrumented");
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000459}
460
Peter Collingbourne59b12622013-08-22 20:08:08 +0000461bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000462 return !ABIList.isIn(*GA, "uninstrumented");
Peter Collingbourne59b12622013-08-22 20:08:08 +0000463}
464
Peter Collingbourne68162e72013-08-14 18:54:12 +0000465DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000466 return ClArgsABI ? IA_Args : IA_TLS;
467}
468
Peter Collingbourne68162e72013-08-14 18:54:12 +0000469DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000470 if (ABIList.isIn(*F, "functional"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000471 return WK_Functional;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000472 if (ABIList.isIn(*F, "discard"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000473 return WK_Discard;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000474 if (ABIList.isIn(*F, "custom"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000475 return WK_Custom;
476
477 return WK_Warning;
478}
479
Peter Collingbourne59b12622013-08-22 20:08:08 +0000480void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
481 std::string GVName = GV->getName(), Prefix = "dfs$";
482 GV->setName(Prefix + GVName);
483
484 // Try to change the name of the function in module inline asm. We only do
485 // this for specific asm directives, currently only ".symver", to try to avoid
486 // corrupting asm which happens to contain the symbol name as a substring.
487 // Note that the substitution for .symver assumes that the versioned symbol
488 // also has an instrumented name.
489 std::string Asm = GV->getParent()->getModuleInlineAsm();
490 std::string SearchStr = ".symver " + GVName + ",";
491 size_t Pos = Asm.find(SearchStr);
492 if (Pos != std::string::npos) {
493 Asm.replace(Pos, SearchStr.size(),
494 ".symver " + Prefix + GVName + "," + Prefix);
495 GV->getParent()->setModuleInlineAsm(Asm);
496 }
497}
498
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000499Function *
500DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
501 GlobalValue::LinkageTypes NewFLink,
502 FunctionType *NewFT) {
503 FunctionType *FT = F->getFunctionType();
504 Function *NewF = Function::Create(NewFT, NewFLink, NewFName,
505 F->getParent());
506 NewF->copyAttributesFrom(F);
507 NewF->removeAttributes(
508 AttributeSet::ReturnIndex,
509 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
510 AttributeSet::ReturnIndex));
511
512 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
513 std::vector<Value *> Args;
514 unsigned n = FT->getNumParams();
515 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
516 Args.push_back(&*ai);
517 CallInst *CI = CallInst::Create(F, Args, "", BB);
518 if (FT->getReturnType()->isVoidTy())
519 ReturnInst::Create(*Ctx, BB);
520 else
521 ReturnInst::Create(*Ctx, CI, BB);
522
523 return NewF;
524}
525
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000526Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
527 StringRef FName) {
528 FunctionType *FTT = getTrampolineFunctionType(FT);
529 Constant *C = Mod->getOrInsertFunction(FName, FTT);
530 Function *F = dyn_cast<Function>(C);
531 if (F && F->isDeclaration()) {
532 F->setLinkage(GlobalValue::LinkOnceODRLinkage);
533 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
534 std::vector<Value *> Args;
535 Function::arg_iterator AI = F->arg_begin(); ++AI;
536 for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
537 Args.push_back(&*AI);
538 CallInst *CI =
539 CallInst::Create(&F->getArgumentList().front(), Args, "", BB);
540 ReturnInst *RI;
541 if (FT->getReturnType()->isVoidTy())
542 RI = ReturnInst::Create(*Ctx, BB);
543 else
544 RI = ReturnInst::Create(*Ctx, CI, BB);
545
546 DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
547 Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
548 for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
549 DFSF.ValShadowMap[ValAI] = ShadowAI;
550 DFSanVisitor(DFSF).visitCallInst(*CI);
551 if (!FT->getReturnType()->isVoidTy())
552 new StoreInst(DFSF.getShadow(RI->getReturnValue()),
553 &F->getArgumentList().back(), RI);
554 }
555
556 return C;
557}
558
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000559bool DataFlowSanitizer::runOnModule(Module &M) {
560 if (!DL)
561 return false;
562
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000563 if (ABIList.isIn(M, "skip"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000564 return false;
565
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000566 if (!GetArgTLSPtr) {
567 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
568 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
569 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
570 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
571 }
572 if (!GetRetvalTLSPtr) {
573 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
574 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
575 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
576 }
577
578 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
579 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
580 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
581 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
582 F->addAttribute(1, Attribute::ZExt);
583 F->addAttribute(2, Attribute::ZExt);
584 }
585 DFSanUnionLoadFn =
586 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
587 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
Peter Collingbourne0be79e12013-11-21 23:20:54 +0000588 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000589 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
590 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000591 DFSanUnimplementedFn =
592 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000593 DFSanSetLabelFn =
594 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
595 if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
596 F->addAttribute(1, Attribute::ZExt);
597 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000598 DFSanNonzeroLabelFn =
599 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000600
601 std::vector<Function *> FnsToInstrument;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000602 llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000603 for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000604 if (!i->isIntrinsic() &&
605 i != DFSanUnionFn &&
606 i != DFSanUnionLoadFn &&
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000607 i != DFSanUnimplementedFn &&
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000608 i != DFSanSetLabelFn &&
609 i != DFSanNonzeroLabelFn)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000610 FnsToInstrument.push_back(&*i);
611 }
612
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000613 // Give function aliases prefixes when necessary, and build wrappers where the
614 // instrumentedness is inconsistent.
Peter Collingbourne59b12622013-08-22 20:08:08 +0000615 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
616 GlobalAlias *GA = &*i;
617 ++i;
618 // Don't stop on weak. We assume people aren't playing games with the
619 // instrumentedness of overridden weak aliases.
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000620 if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000621 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
622 if (GAInst && FInst) {
623 addGlobalNamePrefix(GA);
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000624 } else if (GAInst != FInst) {
625 // Non-instrumented alias of an instrumented function, or vice versa.
626 // Replace the alias with a native-ABI wrapper of the aliasee. The pass
627 // below will take care of instrumenting it.
628 Function *NewF =
629 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000630 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000631 NewF->takeName(GA);
632 GA->eraseFromParent();
633 FnsToInstrument.push_back(NewF);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000634 }
635 }
636 }
637
Peter Collingbourne68162e72013-08-14 18:54:12 +0000638 AttrBuilder B;
639 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
640 ReadOnlyNoneAttrs = AttributeSet::get(*Ctx, AttributeSet::FunctionIndex, B);
641
642 // First, change the ABI of every function in the module. ABI-listed
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000643 // functions keep their original ABI and get a wrapper function.
644 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
645 e = FnsToInstrument.end();
646 i != e; ++i) {
647 Function &F = **i;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000648 FunctionType *FT = F.getFunctionType();
Peter Collingbourne68162e72013-08-14 18:54:12 +0000649
Peter Collingbourne59b12622013-08-22 20:08:08 +0000650 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
651 FT->getReturnType()->isVoidTy());
Peter Collingbourne68162e72013-08-14 18:54:12 +0000652
653 if (isInstrumented(&F)) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000654 // Instrumented functions get a 'dfs$' prefix. This allows us to more
655 // easily identify cases of mismatching ABIs.
656 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000657 FunctionType *NewFT = getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000658 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000659 NewF->copyAttributesFrom(&F);
660 NewF->removeAttributes(
661 AttributeSet::ReturnIndex,
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000662 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
Peter Collingbourne68162e72013-08-14 18:54:12 +0000663 AttributeSet::ReturnIndex));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000664 for (Function::arg_iterator FArg = F.arg_begin(),
665 NewFArg = NewF->arg_begin(),
666 FArgEnd = F.arg_end();
667 FArg != FArgEnd; ++FArg, ++NewFArg) {
668 FArg->replaceAllUsesWith(NewFArg);
669 }
670 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
671
Chandler Carruthcdf47882014-03-09 03:16:01 +0000672 for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
673 UI != UE;) {
674 BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
675 ++UI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000676 if (BA) {
677 BA->replaceAllUsesWith(
678 BlockAddress::get(NewF, BA->getBasicBlock()));
679 delete BA;
680 }
681 }
682 F.replaceAllUsesWith(
683 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
684 NewF->takeName(&F);
685 F.eraseFromParent();
686 *i = NewF;
Peter Collingbourne59b12622013-08-22 20:08:08 +0000687 addGlobalNamePrefix(NewF);
688 } else {
689 addGlobalNamePrefix(&F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000690 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000691 // Hopefully, nobody will try to indirectly call a vararg
692 // function... yet.
693 } else if (FT->isVarArg()) {
694 UnwrappedFnMap[&F] = &F;
Craig Topperf40110f2014-04-25 05:29:35 +0000695 *i = nullptr;
Peter Collingbourne59b12622013-08-22 20:08:08 +0000696 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000697 // Build a wrapper function for F. The wrapper simply calls F, and is
698 // added to FnsToInstrument so that any instrumentation according to its
699 // WrapperKind is done in the second pass below.
700 FunctionType *NewFT = getInstrumentedABI() == IA_Args
701 ? getArgsFunctionType(FT)
702 : FT;
Alexey Samsonov6dae24d2013-08-23 07:42:51 +0000703 Function *NewF = buildWrapperFunction(
704 &F, std::string("dfsw$") + std::string(F.getName()),
705 GlobalValue::LinkOnceODRLinkage, NewFT);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000706 if (getInstrumentedABI() == IA_TLS)
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000707 NewF->removeAttributes(AttributeSet::FunctionIndex, ReadOnlyNoneAttrs);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000708
Peter Collingbourne68162e72013-08-14 18:54:12 +0000709 Value *WrappedFnCst =
710 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
711 F.replaceAllUsesWith(WrappedFnCst);
712 UnwrappedFnMap[WrappedFnCst] = &F;
713 *i = NewF;
714
715 if (!F.isDeclaration()) {
716 // This function is probably defining an interposition of an
717 // uninstrumented function and hence needs to keep the original ABI.
718 // But any functions it may call need to use the instrumented ABI, so
719 // we instrument it in a mode which preserves the original ABI.
720 FnsWithNativeABI.insert(&F);
721
722 // This code needs to rebuild the iterators, as they may be invalidated
723 // by the push_back, taking care that the new range does not include
724 // any functions added by this code.
725 size_t N = i - FnsToInstrument.begin(),
726 Count = e - FnsToInstrument.begin();
727 FnsToInstrument.push_back(&F);
728 i = FnsToInstrument.begin() + N;
729 e = FnsToInstrument.begin() + Count;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000730 }
731 }
732 }
733
734 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
735 e = FnsToInstrument.end();
736 i != e; ++i) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000737 if (!*i || (*i)->isDeclaration())
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000738 continue;
739
Peter Collingbourneae66d572013-08-09 21:42:53 +0000740 removeUnreachableBlocks(**i);
741
Peter Collingbourne68162e72013-08-14 18:54:12 +0000742 DFSanFunction DFSF(*this, *i, FnsWithNativeABI.count(*i));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000743
744 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
745 // Build a copy of the list before iterating over it.
David Blaikieceec2bd2014-04-11 01:50:01 +0000746 llvm::SmallVector<BasicBlock *, 4> BBList(
747 depth_first(&(*i)->getEntryBlock()));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000748
749 for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
750 e = BBList.end();
751 i != e; ++i) {
752 Instruction *Inst = &(*i)->front();
753 while (1) {
754 // DFSanVisitor may split the current basic block, changing the current
755 // instruction's next pointer and moving the next instruction to the
756 // tail block from which we should continue.
757 Instruction *Next = Inst->getNextNode();
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000758 // DFSanVisitor may delete Inst, so keep track of whether it was a
759 // terminator.
760 bool IsTerminator = isa<TerminatorInst>(Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000761 if (!DFSF.SkipInsts.count(Inst))
762 DFSanVisitor(DFSF).visit(Inst);
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000763 if (IsTerminator)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000764 break;
765 Inst = Next;
766 }
767 }
768
Peter Collingbourne68162e72013-08-14 18:54:12 +0000769 // We will not necessarily be able to compute the shadow for every phi node
770 // until we have visited every block. Therefore, the code that handles phi
771 // nodes adds them to the PHIFixups list so that they can be properly
772 // handled here.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000773 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
774 i = DFSF.PHIFixups.begin(),
775 e = DFSF.PHIFixups.end();
776 i != e; ++i) {
777 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
778 ++val) {
779 i->second->setIncomingValue(
780 val, DFSF.getShadow(i->first->getIncomingValue(val)));
781 }
782 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000783
784 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
785 // places (i.e. instructions in basic blocks we haven't even begun visiting
786 // yet). To make our life easier, do this work in a pass after the main
787 // instrumentation.
788 if (ClDebugNonzeroLabels) {
789 for (DenseSet<Value *>::iterator i = DFSF.NonZeroChecks.begin(),
790 e = DFSF.NonZeroChecks.end();
791 i != e; ++i) {
792 Instruction *Pos;
793 if (Instruction *I = dyn_cast<Instruction>(*i))
794 Pos = I->getNextNode();
795 else
796 Pos = DFSF.F->getEntryBlock().begin();
797 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
798 Pos = Pos->getNextNode();
799 IRBuilder<> IRB(Pos);
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000800 Value *Ne = IRB.CreateICmpNE(*i, DFSF.DFS.ZeroShadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000801 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000802 Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000803 IRBuilder<> ThenIRB(BI);
804 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn);
805 }
806 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000807 }
808
809 return false;
810}
811
812Value *DFSanFunction::getArgTLSPtr() {
813 if (ArgTLSPtr)
814 return ArgTLSPtr;
815 if (DFS.ArgTLS)
816 return ArgTLSPtr = DFS.ArgTLS;
817
818 IRBuilder<> IRB(F->getEntryBlock().begin());
819 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
820}
821
822Value *DFSanFunction::getRetvalTLS() {
823 if (RetvalTLSPtr)
824 return RetvalTLSPtr;
825 if (DFS.RetvalTLS)
826 return RetvalTLSPtr = DFS.RetvalTLS;
827
828 IRBuilder<> IRB(F->getEntryBlock().begin());
829 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
830}
831
832Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
833 IRBuilder<> IRB(Pos);
834 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
835}
836
837Value *DFSanFunction::getShadow(Value *V) {
838 if (!isa<Argument>(V) && !isa<Instruction>(V))
839 return DFS.ZeroShadow;
840 Value *&Shadow = ValShadowMap[V];
841 if (!Shadow) {
842 if (Argument *A = dyn_cast<Argument>(V)) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000843 if (IsNativeABI)
844 return DFS.ZeroShadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000845 switch (IA) {
846 case DataFlowSanitizer::IA_TLS: {
847 Value *ArgTLSPtr = getArgTLSPtr();
848 Instruction *ArgTLSPos =
849 DFS.ArgTLS ? &*F->getEntryBlock().begin()
850 : cast<Instruction>(ArgTLSPtr)->getNextNode();
851 IRBuilder<> IRB(ArgTLSPos);
852 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
853 break;
854 }
855 case DataFlowSanitizer::IA_Args: {
856 unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
857 Function::arg_iterator i = F->arg_begin();
858 while (ArgIdx--)
859 ++i;
860 Shadow = i;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000861 assert(Shadow->getType() == DFS.ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000862 break;
863 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000864 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000865 NonZeroChecks.insert(Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000866 } else {
867 Shadow = DFS.ZeroShadow;
868 }
869 }
870 return Shadow;
871}
872
873void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
874 assert(!ValShadowMap.count(I));
875 assert(Shadow->getType() == DFS.ShadowTy);
876 ValShadowMap[I] = Shadow;
877}
878
879Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
880 assert(Addr != RetvalTLS && "Reinstrumenting?");
881 IRBuilder<> IRB(Pos);
882 return IRB.CreateIntToPtr(
883 IRB.CreateMul(
884 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
885 ShadowPtrMul),
886 ShadowPtrTy);
887}
888
889// Generates IR to compute the union of the two given shadows, inserting it
890// before Pos. Returns the computed union Value.
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000891Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
892 if (V1 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000893 return V2;
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000894 if (V2 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000895 return V1;
896 if (V1 == V2)
897 return V1;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000898
Peter Collingbourne9947c492014-07-15 22:13:19 +0000899 auto V1Elems = ShadowElements.find(V1);
900 auto V2Elems = ShadowElements.find(V2);
901 if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
902 if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
903 V2Elems->second.begin(), V2Elems->second.end())) {
904 return V1;
905 } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
906 V1Elems->second.begin(), V1Elems->second.end())) {
907 return V2;
908 }
909 } else if (V1Elems != ShadowElements.end()) {
910 if (V1Elems->second.count(V2))
911 return V1;
912 } else if (V2Elems != ShadowElements.end()) {
913 if (V2Elems->second.count(V1))
914 return V2;
915 }
916
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000917 auto Key = std::make_pair(V1, V2);
918 if (V1 > V2)
919 std::swap(Key.first, Key.second);
920 CachedCombinedShadow &CCS = CachedCombinedShadows[Key];
921 if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
922 return CCS.Shadow;
923
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000924 IRBuilder<> IRB(Pos);
925 BasicBlock *Head = Pos->getParent();
926 Value *Ne = IRB.CreateICmpNE(V1, V2);
Evgeniy Stepanova284e552013-12-19 14:37:03 +0000927 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000928 Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
Evgeniy Stepanova284e552013-12-19 14:37:03 +0000929 IRBuilder<> ThenIRB(BI);
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000930 CallInst *Call = ThenIRB.CreateCall2(DFS.DFSanUnionFn, V1, V2);
Evgeniy Stepanova284e552013-12-19 14:37:03 +0000931 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
932 Call->addAttribute(1, Attribute::ZExt);
933 Call->addAttribute(2, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000934
Evgeniy Stepanova284e552013-12-19 14:37:03 +0000935 BasicBlock *Tail = BI->getSuccessor(0);
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000936 PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", Tail->begin());
Evgeniy Stepanova284e552013-12-19 14:37:03 +0000937 Phi->addIncoming(Call, Call->getParent());
938 Phi->addIncoming(V1, Head);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000939
940 CCS.Block = Tail;
941 CCS.Shadow = Phi;
Peter Collingbourne9947c492014-07-15 22:13:19 +0000942
943 std::set<Value *> UnionElems;
944 if (V1Elems != ShadowElements.end()) {
945 UnionElems = V1Elems->second;
946 } else {
947 UnionElems.insert(V1);
948 }
949 if (V2Elems != ShadowElements.end()) {
950 UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
951 } else {
952 UnionElems.insert(V2);
953 }
954 ShadowElements[Phi] = std::move(UnionElems);
955
Evgeniy Stepanova284e552013-12-19 14:37:03 +0000956 return Phi;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000957}
958
959// A convenience function which folds the shadows of each of the operands
960// of the provided instruction Inst, inserting the IR before Inst. Returns
961// the computed union Value.
962Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
963 if (Inst->getNumOperands() == 0)
964 return DFS.ZeroShadow;
965
966 Value *Shadow = getShadow(Inst->getOperand(0));
967 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000968 Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000969 }
970 return Shadow;
971}
972
973void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
974 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
975 DFSF.setShadow(&I, CombinedShadow);
976}
977
978// Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
979// Addr has alignment Align, and take the union of each of those shadows.
980Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
981 Instruction *Pos) {
982 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
983 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
984 AllocaShadowMap.find(AI);
985 if (i != AllocaShadowMap.end()) {
986 IRBuilder<> IRB(Pos);
987 return IRB.CreateLoad(i->second);
988 }
989 }
990
991 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
992 SmallVector<Value *, 2> Objs;
993 GetUnderlyingObjects(Addr, Objs, DFS.DL);
994 bool AllConstants = true;
995 for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
996 i != e; ++i) {
997 if (isa<Function>(*i) || isa<BlockAddress>(*i))
998 continue;
999 if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
1000 continue;
1001
1002 AllConstants = false;
1003 break;
1004 }
1005 if (AllConstants)
1006 return DFS.ZeroShadow;
1007
1008 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1009 switch (Size) {
1010 case 0:
1011 return DFS.ZeroShadow;
1012 case 1: {
1013 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
1014 LI->setAlignment(ShadowAlign);
1015 return LI;
1016 }
1017 case 2: {
1018 IRBuilder<> IRB(Pos);
1019 Value *ShadowAddr1 =
1020 IRB.CreateGEP(ShadowAddr, ConstantInt::get(DFS.IntptrTy, 1));
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001021 return combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
1022 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign), Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001023 }
1024 }
1025 if (Size % (64 / DFS.ShadowWidth) == 0) {
1026 // Fast path for the common case where each byte has identical shadow: load
1027 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
1028 // shadow is non-equal.
1029 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
1030 IRBuilder<> FallbackIRB(FallbackBB);
1031 CallInst *FallbackCall = FallbackIRB.CreateCall2(
1032 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
1033 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1034
1035 // Compare each of the shadows stored in the loaded 64 bits to each other,
1036 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
1037 IRBuilder<> IRB(Pos);
1038 Value *WideAddr =
1039 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1040 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1041 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
1042 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
1043 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
1044 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1045 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1046
1047 BasicBlock *Head = Pos->getParent();
1048 BasicBlock *Tail = Head->splitBasicBlock(Pos);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001049
1050 if (DomTreeNode *OldNode = DT.getNode(Head)) {
1051 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1052
1053 DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1054 for (auto Child : Children)
1055 DT.changeImmediateDominator(Child, NewNode);
1056 }
1057
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001058 // In the following code LastBr will refer to the previous basic block's
1059 // conditional branch instruction, whose true successor is fixed up to point
1060 // to the next block during the loop below or to the tail after the final
1061 // iteration.
1062 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1063 ReplaceInstWithInst(Head->getTerminator(), LastBr);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001064 DT.addNewBlock(FallbackBB, Head);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001065
1066 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
1067 Ofs += 64 / DFS.ShadowWidth) {
1068 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001069 DT.addNewBlock(NextBB, LastBr->getParent());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001070 IRBuilder<> NextIRB(NextBB);
1071 WideAddr = NextIRB.CreateGEP(WideAddr, ConstantInt::get(DFS.IntptrTy, 1));
1072 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1073 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1074 LastBr->setSuccessor(0, NextBB);
1075 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1076 }
1077
1078 LastBr->setSuccessor(0, Tail);
1079 FallbackIRB.CreateBr(Tail);
1080 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1081 Shadow->addIncoming(FallbackCall, FallbackBB);
1082 Shadow->addIncoming(TruncShadow, LastBr->getParent());
1083 return Shadow;
1084 }
1085
1086 IRBuilder<> IRB(Pos);
1087 CallInst *FallbackCall = IRB.CreateCall2(
1088 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
1089 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1090 return FallbackCall;
1091}
1092
1093void DFSanVisitor::visitLoadInst(LoadInst &LI) {
1094 uint64_t Size = DFSF.DFS.DL->getTypeStoreSize(LI.getType());
1095 uint64_t Align;
1096 if (ClPreserveAlignment) {
1097 Align = LI.getAlignment();
1098 if (Align == 0)
1099 Align = DFSF.DFS.DL->getABITypeAlignment(LI.getType());
1100 } else {
1101 Align = 1;
1102 }
1103 IRBuilder<> IRB(&LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001104 Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
1105 if (ClCombinePointerLabelsOnLoad) {
1106 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001107 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001108 }
1109 if (Shadow != DFSF.DFS.ZeroShadow)
1110 DFSF.NonZeroChecks.insert(Shadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +00001111
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001112 DFSF.setShadow(&LI, Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001113}
1114
1115void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
1116 Value *Shadow, Instruction *Pos) {
1117 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1118 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1119 AllocaShadowMap.find(AI);
1120 if (i != AllocaShadowMap.end()) {
1121 IRBuilder<> IRB(Pos);
1122 IRB.CreateStore(Shadow, i->second);
1123 return;
1124 }
1125 }
1126
1127 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1128 IRBuilder<> IRB(Pos);
1129 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1130 if (Shadow == DFS.ZeroShadow) {
1131 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1132 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1133 Value *ExtShadowAddr =
1134 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1135 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1136 return;
1137 }
1138
1139 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1140 uint64_t Offset = 0;
1141 if (Size >= ShadowVecSize) {
1142 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1143 Value *ShadowVec = UndefValue::get(ShadowVecTy);
1144 for (unsigned i = 0; i != ShadowVecSize; ++i) {
1145 ShadowVec = IRB.CreateInsertElement(
1146 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1147 }
1148 Value *ShadowVecAddr =
1149 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1150 do {
1151 Value *CurShadowVecAddr = IRB.CreateConstGEP1_32(ShadowVecAddr, Offset);
1152 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1153 Size -= ShadowVecSize;
1154 ++Offset;
1155 } while (Size >= ShadowVecSize);
1156 Offset *= ShadowVecSize;
1157 }
1158 while (Size > 0) {
1159 Value *CurShadowAddr = IRB.CreateConstGEP1_32(ShadowAddr, Offset);
1160 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1161 --Size;
1162 ++Offset;
1163 }
1164}
1165
1166void DFSanVisitor::visitStoreInst(StoreInst &SI) {
1167 uint64_t Size =
1168 DFSF.DFS.DL->getTypeStoreSize(SI.getValueOperand()->getType());
1169 uint64_t Align;
1170 if (ClPreserveAlignment) {
1171 Align = SI.getAlignment();
1172 if (Align == 0)
1173 Align = DFSF.DFS.DL->getABITypeAlignment(SI.getValueOperand()->getType());
1174 } else {
1175 Align = 1;
1176 }
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001177
1178 Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1179 if (ClCombinePointerLabelsOnStore) {
1180 Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001181 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001182 }
1183 DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001184}
1185
1186void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1187 visitOperandShadowInst(BO);
1188}
1189
1190void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1191
1192void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1193
1194void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1195 visitOperandShadowInst(GEPI);
1196}
1197
1198void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1199 visitOperandShadowInst(I);
1200}
1201
1202void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1203 visitOperandShadowInst(I);
1204}
1205
1206void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1207 visitOperandShadowInst(I);
1208}
1209
1210void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1211 visitOperandShadowInst(I);
1212}
1213
1214void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1215 visitOperandShadowInst(I);
1216}
1217
1218void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1219 bool AllLoadsStores = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001220 for (User *U : I.users()) {
1221 if (isa<LoadInst>(U))
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001222 continue;
1223
Chandler Carruthcdf47882014-03-09 03:16:01 +00001224 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001225 if (SI->getPointerOperand() == &I)
1226 continue;
1227 }
1228
1229 AllLoadsStores = false;
1230 break;
1231 }
1232 if (AllLoadsStores) {
1233 IRBuilder<> IRB(&I);
1234 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1235 }
1236 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1237}
1238
1239void DFSanVisitor::visitSelectInst(SelectInst &I) {
1240 Value *CondShadow = DFSF.getShadow(I.getCondition());
1241 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1242 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1243
1244 if (isa<VectorType>(I.getCondition()->getType())) {
1245 DFSF.setShadow(
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001246 &I,
1247 DFSF.combineShadows(
1248 CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001249 } else {
1250 Value *ShadowSel;
1251 if (TrueShadow == FalseShadow) {
1252 ShadowSel = TrueShadow;
1253 } else {
1254 ShadowSel =
1255 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1256 }
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001257 DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001258 }
1259}
1260
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +00001261void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1262 IRBuilder<> IRB(&I);
1263 Value *ValShadow = DFSF.getShadow(I.getValue());
1264 IRB.CreateCall3(
1265 DFSF.DFS.DFSanSetLabelFn, ValShadow,
1266 IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
1267 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy));
1268}
1269
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001270void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1271 IRBuilder<> IRB(&I);
1272 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1273 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1274 Value *LenShadow = IRB.CreateMul(
1275 I.getLength(),
1276 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
1277 Value *AlignShadow;
1278 if (ClPreserveAlignment) {
1279 AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1280 ConstantInt::get(I.getAlignmentCst()->getType(),
1281 DFSF.DFS.ShadowWidth / 8));
1282 } else {
1283 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1284 DFSF.DFS.ShadowWidth / 8);
1285 }
1286 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1287 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1288 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
1289 IRB.CreateCall5(I.getCalledValue(), DestShadow, SrcShadow, LenShadow,
1290 AlignShadow, I.getVolatileCst());
1291}
1292
1293void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001294 if (!DFSF.IsNativeABI && RI.getReturnValue()) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001295 switch (DFSF.IA) {
1296 case DataFlowSanitizer::IA_TLS: {
1297 Value *S = DFSF.getShadow(RI.getReturnValue());
1298 IRBuilder<> IRB(&RI);
1299 IRB.CreateStore(S, DFSF.getRetvalTLS());
1300 break;
1301 }
1302 case DataFlowSanitizer::IA_Args: {
1303 IRBuilder<> IRB(&RI);
1304 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1305 Value *InsVal =
1306 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1307 Value *InsShadow =
1308 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1309 RI.setOperand(0, InsShadow);
1310 break;
1311 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001312 }
1313 }
1314}
1315
1316void DFSanVisitor::visitCallSite(CallSite CS) {
1317 Function *F = CS.getCalledFunction();
1318 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1319 visitOperandShadowInst(*CS.getInstruction());
1320 return;
1321 }
1322
Peter Collingbourne68162e72013-08-14 18:54:12 +00001323 IRBuilder<> IRB(CS.getInstruction());
1324
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001325 DenseMap<Value *, Function *>::iterator i =
1326 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1327 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001328 Function *F = i->second;
1329 switch (DFSF.DFS.getWrapperKind(F)) {
1330 case DataFlowSanitizer::WK_Warning: {
1331 CS.setCalledFunction(F);
1332 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1333 IRB.CreateGlobalStringPtr(F->getName()));
1334 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1335 return;
1336 }
1337 case DataFlowSanitizer::WK_Discard: {
1338 CS.setCalledFunction(F);
1339 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1340 return;
1341 }
1342 case DataFlowSanitizer::WK_Functional: {
1343 CS.setCalledFunction(F);
1344 visitOperandShadowInst(*CS.getInstruction());
1345 return;
1346 }
1347 case DataFlowSanitizer::WK_Custom: {
1348 // Don't try to handle invokes of custom functions, it's too complicated.
1349 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1350 // wrapper.
1351 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1352 FunctionType *FT = F->getFunctionType();
1353 FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1354 std::string CustomFName = "__dfsw_";
1355 CustomFName += F->getName();
1356 Constant *CustomF =
1357 DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1358 if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1359 CustomFn->copyAttributesFrom(F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001360
Peter Collingbourne68162e72013-08-14 18:54:12 +00001361 // Custom functions returning non-void will write to the return label.
1362 if (!FT->getReturnType()->isVoidTy()) {
1363 CustomFn->removeAttributes(AttributeSet::FunctionIndex,
1364 DFSF.DFS.ReadOnlyNoneAttrs);
1365 }
1366 }
1367
1368 std::vector<Value *> Args;
1369
1370 CallSite::arg_iterator i = CS.arg_begin();
Peter Collingbourne28a10af2013-08-27 22:09:06 +00001371 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
1372 Type *T = (*i)->getType();
1373 FunctionType *ParamFT;
1374 if (isa<PointerType>(T) &&
1375 (ParamFT = dyn_cast<FunctionType>(
1376 cast<PointerType>(T)->getElementType()))) {
1377 std::string TName = "dfst";
1378 TName += utostr(FT->getNumParams() - n);
1379 TName += "$";
1380 TName += F->getName();
1381 Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1382 Args.push_back(T);
1383 Args.push_back(
1384 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1385 } else {
1386 Args.push_back(*i);
1387 }
1388 }
Peter Collingbourne68162e72013-08-14 18:54:12 +00001389
1390 i = CS.arg_begin();
1391 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1392 Args.push_back(DFSF.getShadow(*i));
1393
1394 if (!FT->getReturnType()->isVoidTy()) {
1395 if (!DFSF.LabelReturnAlloca) {
1396 DFSF.LabelReturnAlloca =
1397 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
1398 DFSF.F->getEntryBlock().begin());
1399 }
1400 Args.push_back(DFSF.LabelReturnAlloca);
1401 }
1402
1403 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1404 CustomCI->setCallingConv(CI->getCallingConv());
1405 CustomCI->setAttributes(CI->getAttributes());
1406
1407 if (!FT->getReturnType()->isVoidTy()) {
1408 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1409 DFSF.setShadow(CustomCI, LabelLoad);
1410 }
1411
1412 CI->replaceAllUsesWith(CustomCI);
1413 CI->eraseFromParent();
1414 return;
1415 }
1416 break;
1417 }
1418 }
1419 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001420
1421 FunctionType *FT = cast<FunctionType>(
1422 CS.getCalledValue()->getType()->getPointerElementType());
Peter Collingbourne68162e72013-08-14 18:54:12 +00001423 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001424 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1425 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1426 DFSF.getArgTLS(i, CS.getInstruction()));
1427 }
1428 }
1429
Craig Topperf40110f2014-04-25 05:29:35 +00001430 Instruction *Next = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001431 if (!CS.getType()->isVoidTy()) {
1432 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1433 if (II->getNormalDest()->getSinglePredecessor()) {
1434 Next = II->getNormalDest()->begin();
1435 } else {
1436 BasicBlock *NewBB =
1437 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DFS);
1438 Next = NewBB->begin();
1439 }
1440 } else {
1441 Next = CS->getNextNode();
1442 }
1443
Peter Collingbourne68162e72013-08-14 18:54:12 +00001444 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001445 IRBuilder<> NextIRB(Next);
1446 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1447 DFSF.SkipInsts.insert(LI);
1448 DFSF.setShadow(CS.getInstruction(), LI);
Peter Collingbourne444c59e2013-08-15 18:51:12 +00001449 DFSF.NonZeroChecks.insert(LI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001450 }
1451 }
1452
1453 // Do all instrumentation for IA_Args down here to defer tampering with the
1454 // CFG in a way that SplitEdge may be able to detect.
Peter Collingbourne68162e72013-08-14 18:54:12 +00001455 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1456 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001457 Value *Func =
1458 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1459 std::vector<Value *> Args;
1460
1461 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1462 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1463 Args.push_back(*i);
1464
1465 i = CS.arg_begin();
1466 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1467 Args.push_back(DFSF.getShadow(*i));
1468
1469 if (FT->isVarArg()) {
1470 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1471 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1472 AllocaInst *VarArgShadow =
1473 new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
1474 Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
1475 for (unsigned n = 0; i != e; ++i, ++n) {
1476 IRB.CreateStore(DFSF.getShadow(*i),
1477 IRB.CreateConstGEP2_32(VarArgShadow, 0, n));
1478 Args.push_back(*i);
1479 }
1480 }
1481
1482 CallSite NewCS;
1483 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1484 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1485 Args);
1486 } else {
1487 NewCS = IRB.CreateCall(Func, Args);
1488 }
1489 NewCS.setCallingConv(CS.getCallingConv());
1490 NewCS.setAttributes(CS.getAttributes().removeAttributes(
1491 *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
1492 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType(),
1493 AttributeSet::ReturnIndex)));
1494
1495 if (Next) {
1496 ExtractValueInst *ExVal =
1497 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1498 DFSF.SkipInsts.insert(ExVal);
1499 ExtractValueInst *ExShadow =
1500 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1501 DFSF.SkipInsts.insert(ExShadow);
1502 DFSF.setShadow(ExVal, ExShadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +00001503 DFSF.NonZeroChecks.insert(ExShadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001504
1505 CS.getInstruction()->replaceAllUsesWith(ExVal);
1506 }
1507
1508 CS.getInstruction()->eraseFromParent();
1509 }
1510}
1511
1512void DFSanVisitor::visitPHINode(PHINode &PN) {
1513 PHINode *ShadowPN =
1514 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1515
1516 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1517 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1518 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1519 ++i) {
1520 ShadowPN->addIncoming(UndefShadow, *i);
1521 }
1522
1523 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1524 DFSF.setShadow(&PN, ShadowPN);
1525}