blob: e3a4b383be2ade30a69854e502b7d948c847eb0b [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;
Peter Collingbournedf240b22014-08-06 00:33:40 +0000237 Constant *DFSanCheckedUnionFn;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000238 Constant *DFSanUnionLoadFn;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000239 Constant *DFSanUnimplementedFn;
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000240 Constant *DFSanSetLabelFn;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000241 Constant *DFSanNonzeroLabelFn;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000242 MDNode *ColdCallWeights;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000243 DFSanABIList ABIList;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000244 DenseMap<Value *, Function *> UnwrappedFnMap;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000245 AttributeSet ReadOnlyNoneAttrs;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000246
247 Value *getShadowAddress(Value *Addr, Instruction *Pos);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000248 bool isInstrumented(const Function *F);
249 bool isInstrumented(const GlobalAlias *GA);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000250 FunctionType *getArgsFunctionType(FunctionType *T);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000251 FunctionType *getTrampolineFunctionType(FunctionType *T);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000252 FunctionType *getCustomFunctionType(FunctionType *T);
253 InstrumentedABI getInstrumentedABI();
254 WrapperKind getWrapperKind(Function *F);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000255 void addGlobalNamePrefix(GlobalValue *GV);
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000256 Function *buildWrapperFunction(Function *F, StringRef NewFName,
257 GlobalValue::LinkageTypes NewFLink,
258 FunctionType *NewFT);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000259 Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000260
Dmitry Vyukov96a70842013-08-13 16:52:41 +0000261 public:
Peter Collingbourne68162e72013-08-14 18:54:12 +0000262 DataFlowSanitizer(StringRef ABIListFile = StringRef(),
Craig Topperf40110f2014-04-25 05:29:35 +0000263 void *(*getArgTLS)() = nullptr,
264 void *(*getRetValTLS)() = nullptr);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000265 static char ID;
Craig Topper3e4c6972014-03-05 09:10:37 +0000266 bool doInitialization(Module &M) override;
267 bool runOnModule(Module &M) override;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000268};
269
270struct DFSanFunction {
271 DataFlowSanitizer &DFS;
272 Function *F;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000273 DominatorTree DT;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000274 DataFlowSanitizer::InstrumentedABI IA;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000275 bool IsNativeABI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000276 Value *ArgTLSPtr;
277 Value *RetvalTLSPtr;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000278 AllocaInst *LabelReturnAlloca;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000279 DenseMap<Value *, Value *> ValShadowMap;
280 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
281 std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
282 DenseSet<Instruction *> SkipInsts;
Peter Collingbournefab565a2014-08-22 01:18:18 +0000283 std::vector<Value *> NonZeroChecks;
Peter Collingbournedf240b22014-08-06 00:33:40 +0000284 bool AvoidNewBlocks;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000285
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000286 struct CachedCombinedShadow {
287 BasicBlock *Block;
288 Value *Shadow;
289 };
290 DenseMap<std::pair<Value *, Value *>, CachedCombinedShadow>
291 CachedCombinedShadows;
Peter Collingbourne9947c492014-07-15 22:13:19 +0000292 DenseMap<Value *, std::set<Value *>> ShadowElements;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000293
Peter Collingbourne68162e72013-08-14 18:54:12 +0000294 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
295 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()),
Craig Topperf40110f2014-04-25 05:29:35 +0000296 IsNativeABI(IsNativeABI), ArgTLSPtr(nullptr), RetvalTLSPtr(nullptr),
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000297 LabelReturnAlloca(nullptr) {
298 DT.recalculate(*F);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000299 // FIXME: Need to track down the register allocator issue which causes poor
300 // performance in pathological cases with large numbers of basic blocks.
301 AvoidNewBlocks = F->size() > 1000;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000302 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000303 Value *getArgTLSPtr();
304 Value *getArgTLS(unsigned Index, Instruction *Pos);
305 Value *getRetvalTLS();
306 Value *getShadow(Value *V);
307 void setShadow(Instruction *I, Value *Shadow);
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000308 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000309 Value *combineOperandShadows(Instruction *Inst);
310 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
311 Instruction *Pos);
312 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
313 Instruction *Pos);
314};
315
316class DFSanVisitor : public InstVisitor<DFSanVisitor> {
Dmitry Vyukov96a70842013-08-13 16:52:41 +0000317 public:
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000318 DFSanFunction &DFSF;
319 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
320
321 void visitOperandShadowInst(Instruction &I);
322
323 void visitBinaryOperator(BinaryOperator &BO);
324 void visitCastInst(CastInst &CI);
325 void visitCmpInst(CmpInst &CI);
326 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
327 void visitLoadInst(LoadInst &LI);
328 void visitStoreInst(StoreInst &SI);
329 void visitReturnInst(ReturnInst &RI);
330 void visitCallSite(CallSite CS);
331 void visitPHINode(PHINode &PN);
332 void visitExtractElementInst(ExtractElementInst &I);
333 void visitInsertElementInst(InsertElementInst &I);
334 void visitShuffleVectorInst(ShuffleVectorInst &I);
335 void visitExtractValueInst(ExtractValueInst &I);
336 void visitInsertValueInst(InsertValueInst &I);
337 void visitAllocaInst(AllocaInst &I);
338 void visitSelectInst(SelectInst &I);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000339 void visitMemSetInst(MemSetInst &I);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000340 void visitMemTransferInst(MemTransferInst &I);
341};
342
343}
344
345char DataFlowSanitizer::ID;
346INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
347 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
348
Peter Collingbourne68162e72013-08-14 18:54:12 +0000349ModulePass *llvm::createDataFlowSanitizerPass(StringRef ABIListFile,
350 void *(*getArgTLS)(),
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000351 void *(*getRetValTLS)()) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000352 return new DataFlowSanitizer(ABIListFile, getArgTLS, getRetValTLS);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000353}
354
Peter Collingbourne68162e72013-08-14 18:54:12 +0000355DataFlowSanitizer::DataFlowSanitizer(StringRef ABIListFile,
356 void *(*getArgTLS)(),
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000357 void *(*getRetValTLS)())
358 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS),
Peter Collingbourne68162e72013-08-14 18:54:12 +0000359 ABIList(SpecialCaseList::createOrDie(ABIListFile.empty() ? ClABIListFile
360 : ABIListFile)) {
361}
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000362
Peter Collingbourne68162e72013-08-14 18:54:12 +0000363FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000364 llvm::SmallVector<Type *, 4> ArgTypes;
365 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
366 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
367 ArgTypes.push_back(ShadowTy);
368 if (T->isVarArg())
369 ArgTypes.push_back(ShadowPtrTy);
370 Type *RetType = T->getReturnType();
371 if (!RetType->isVoidTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000372 RetType = StructType::get(RetType, ShadowTy, (Type *)nullptr);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000373 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
374}
375
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000376FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
377 assert(!T->isVarArg());
378 llvm::SmallVector<Type *, 4> ArgTypes;
379 ArgTypes.push_back(T->getPointerTo());
380 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
381 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
382 ArgTypes.push_back(ShadowTy);
383 Type *RetType = T->getReturnType();
384 if (!RetType->isVoidTy())
385 ArgTypes.push_back(ShadowPtrTy);
386 return FunctionType::get(T->getReturnType(), ArgTypes, false);
387}
388
Peter Collingbourne68162e72013-08-14 18:54:12 +0000389FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
390 assert(!T->isVarArg());
391 llvm::SmallVector<Type *, 4> ArgTypes;
Alexey Samsonov9b7e2b52013-08-28 11:25:12 +0000392 for (FunctionType::param_iterator i = T->param_begin(), e = T->param_end();
393 i != e; ++i) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000394 FunctionType *FT;
Alexey Samsonov9b7e2b52013-08-28 11:25:12 +0000395 if (isa<PointerType>(*i) && (FT = dyn_cast<FunctionType>(cast<PointerType>(
396 *i)->getElementType()))) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000397 ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
398 ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
399 } else {
400 ArgTypes.push_back(*i);
401 }
402 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000403 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
404 ArgTypes.push_back(ShadowTy);
405 Type *RetType = T->getReturnType();
406 if (!RetType->isVoidTy())
407 ArgTypes.push_back(ShadowPtrTy);
408 return FunctionType::get(T->getReturnType(), ArgTypes, false);
409}
410
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000411bool DataFlowSanitizer::doInitialization(Module &M) {
Rafael Espindola93512512014-02-25 17:30:31 +0000412 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
413 if (!DLP)
Evgeniy Stepanov119cb2e2014-04-23 12:51:32 +0000414 report_fatal_error("data layout missing");
Rafael Espindola93512512014-02-25 17:30:31 +0000415 DL = &DLP->getDataLayout();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000416
417 Mod = &M;
418 Ctx = &M.getContext();
419 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
420 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
421 IntptrTy = DL->getIntPtrType(*Ctx);
422 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
Peter Collingbournea5689e62013-08-08 00:15:27 +0000423 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000424 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
425
426 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
427 DFSanUnionFnTy =
428 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
429 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
430 DFSanUnionLoadFnTy =
431 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000432 DFSanUnimplementedFnTy = FunctionType::get(
433 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000434 Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
435 DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
436 DFSanSetLabelArgs, /*isVarArg=*/false);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000437 DFSanNonzeroLabelFnTy = FunctionType::get(
Craig Toppere1d12942014-08-27 05:25:25 +0000438 Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000439
440 if (GetArgTLSPtr) {
441 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
Craig Topperf40110f2014-04-25 05:29:35 +0000442 ArgTLS = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000443 GetArgTLS = ConstantExpr::getIntToPtr(
444 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
445 PointerType::getUnqual(
Craig Topperf40110f2014-04-25 05:29:35 +0000446 FunctionType::get(PointerType::getUnqual(ArgTLSTy),
447 (Type *)nullptr)));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000448 }
449 if (GetRetvalTLSPtr) {
Craig Topperf40110f2014-04-25 05:29:35 +0000450 RetvalTLS = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000451 GetRetvalTLS = ConstantExpr::getIntToPtr(
452 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
453 PointerType::getUnqual(
Craig Topperf40110f2014-04-25 05:29:35 +0000454 FunctionType::get(PointerType::getUnqual(ShadowTy),
455 (Type *)nullptr)));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000456 }
457
458 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
459 return true;
460}
461
Peter Collingbourne59b12622013-08-22 20:08:08 +0000462bool DataFlowSanitizer::isInstrumented(const Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000463 return !ABIList.isIn(*F, "uninstrumented");
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000464}
465
Peter Collingbourne59b12622013-08-22 20:08:08 +0000466bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000467 return !ABIList.isIn(*GA, "uninstrumented");
Peter Collingbourne59b12622013-08-22 20:08:08 +0000468}
469
Peter Collingbourne68162e72013-08-14 18:54:12 +0000470DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000471 return ClArgsABI ? IA_Args : IA_TLS;
472}
473
Peter Collingbourne68162e72013-08-14 18:54:12 +0000474DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000475 if (ABIList.isIn(*F, "functional"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000476 return WK_Functional;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000477 if (ABIList.isIn(*F, "discard"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000478 return WK_Discard;
Peter Collingbournef39430b2014-08-20 01:40:23 +0000479 if (ABIList.isIn(*F, "custom") && !F->isVarArg())
Peter Collingbourne68162e72013-08-14 18:54:12 +0000480 return WK_Custom;
481
482 return WK_Warning;
483}
484
Peter Collingbourne59b12622013-08-22 20:08:08 +0000485void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
486 std::string GVName = GV->getName(), Prefix = "dfs$";
487 GV->setName(Prefix + GVName);
488
489 // Try to change the name of the function in module inline asm. We only do
490 // this for specific asm directives, currently only ".symver", to try to avoid
491 // corrupting asm which happens to contain the symbol name as a substring.
492 // Note that the substitution for .symver assumes that the versioned symbol
493 // also has an instrumented name.
494 std::string Asm = GV->getParent()->getModuleInlineAsm();
495 std::string SearchStr = ".symver " + GVName + ",";
496 size_t Pos = Asm.find(SearchStr);
497 if (Pos != std::string::npos) {
498 Asm.replace(Pos, SearchStr.size(),
499 ".symver " + Prefix + GVName + "," + Prefix);
500 GV->getParent()->setModuleInlineAsm(Asm);
501 }
502}
503
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000504Function *
505DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
506 GlobalValue::LinkageTypes NewFLink,
507 FunctionType *NewFT) {
508 FunctionType *FT = F->getFunctionType();
509 Function *NewF = Function::Create(NewFT, NewFLink, NewFName,
510 F->getParent());
511 NewF->copyAttributesFrom(F);
512 NewF->removeAttributes(
513 AttributeSet::ReturnIndex,
514 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
515 AttributeSet::ReturnIndex));
516
517 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
518 std::vector<Value *> Args;
519 unsigned n = FT->getNumParams();
520 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
521 Args.push_back(&*ai);
522 CallInst *CI = CallInst::Create(F, Args, "", BB);
523 if (FT->getReturnType()->isVoidTy())
524 ReturnInst::Create(*Ctx, BB);
525 else
526 ReturnInst::Create(*Ctx, CI, BB);
527
528 return NewF;
529}
530
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000531Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
532 StringRef FName) {
533 FunctionType *FTT = getTrampolineFunctionType(FT);
534 Constant *C = Mod->getOrInsertFunction(FName, FTT);
535 Function *F = dyn_cast<Function>(C);
536 if (F && F->isDeclaration()) {
537 F->setLinkage(GlobalValue::LinkOnceODRLinkage);
538 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
539 std::vector<Value *> Args;
540 Function::arg_iterator AI = F->arg_begin(); ++AI;
541 for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
542 Args.push_back(&*AI);
543 CallInst *CI =
544 CallInst::Create(&F->getArgumentList().front(), Args, "", BB);
545 ReturnInst *RI;
546 if (FT->getReturnType()->isVoidTy())
547 RI = ReturnInst::Create(*Ctx, BB);
548 else
549 RI = ReturnInst::Create(*Ctx, CI, BB);
550
551 DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
552 Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
553 for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
554 DFSF.ValShadowMap[ValAI] = ShadowAI;
555 DFSanVisitor(DFSF).visitCallInst(*CI);
556 if (!FT->getReturnType()->isVoidTy())
557 new StoreInst(DFSF.getShadow(RI->getReturnValue()),
558 &F->getArgumentList().back(), RI);
559 }
560
561 return C;
562}
563
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000564bool DataFlowSanitizer::runOnModule(Module &M) {
565 if (!DL)
566 return false;
567
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000568 if (ABIList.isIn(M, "skip"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000569 return false;
570
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000571 if (!GetArgTLSPtr) {
572 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
573 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
574 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
575 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
576 }
577 if (!GetRetvalTLSPtr) {
578 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
579 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
580 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
581 }
582
583 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
584 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
Peter Collingbournedf240b22014-08-06 00:33:40 +0000585 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
586 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
587 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
588 F->addAttribute(1, Attribute::ZExt);
589 F->addAttribute(2, Attribute::ZExt);
590 }
591 DFSanCheckedUnionFn = Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy);
592 if (Function *F = dyn_cast<Function>(DFSanCheckedUnionFn)) {
593 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000594 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
595 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
596 F->addAttribute(1, Attribute::ZExt);
597 F->addAttribute(2, Attribute::ZExt);
598 }
599 DFSanUnionLoadFn =
600 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
601 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
Peter Collingbournedf240b22014-08-06 00:33:40 +0000602 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
Peter Collingbourne0be79e12013-11-21 23:20:54 +0000603 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000604 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
605 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000606 DFSanUnimplementedFn =
607 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000608 DFSanSetLabelFn =
609 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
610 if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
611 F->addAttribute(1, Attribute::ZExt);
612 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000613 DFSanNonzeroLabelFn =
614 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000615
616 std::vector<Function *> FnsToInstrument;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000617 llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000618 for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000619 if (!i->isIntrinsic() &&
620 i != DFSanUnionFn &&
Peter Collingbournedf240b22014-08-06 00:33:40 +0000621 i != DFSanCheckedUnionFn &&
Peter Collingbourne68162e72013-08-14 18:54:12 +0000622 i != DFSanUnionLoadFn &&
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000623 i != DFSanUnimplementedFn &&
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000624 i != DFSanSetLabelFn &&
625 i != DFSanNonzeroLabelFn)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000626 FnsToInstrument.push_back(&*i);
627 }
628
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000629 // Give function aliases prefixes when necessary, and build wrappers where the
630 // instrumentedness is inconsistent.
Peter Collingbourne59b12622013-08-22 20:08:08 +0000631 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
632 GlobalAlias *GA = &*i;
633 ++i;
634 // Don't stop on weak. We assume people aren't playing games with the
635 // instrumentedness of overridden weak aliases.
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000636 if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000637 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
638 if (GAInst && FInst) {
639 addGlobalNamePrefix(GA);
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000640 } else if (GAInst != FInst) {
641 // Non-instrumented alias of an instrumented function, or vice versa.
642 // Replace the alias with a native-ABI wrapper of the aliasee. The pass
643 // below will take care of instrumenting it.
644 Function *NewF =
645 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000646 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000647 NewF->takeName(GA);
648 GA->eraseFromParent();
649 FnsToInstrument.push_back(NewF);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000650 }
651 }
652 }
653
Peter Collingbourne68162e72013-08-14 18:54:12 +0000654 AttrBuilder B;
655 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
656 ReadOnlyNoneAttrs = AttributeSet::get(*Ctx, AttributeSet::FunctionIndex, B);
657
658 // First, change the ABI of every function in the module. ABI-listed
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000659 // functions keep their original ABI and get a wrapper function.
660 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
661 e = FnsToInstrument.end();
662 i != e; ++i) {
663 Function &F = **i;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000664 FunctionType *FT = F.getFunctionType();
Peter Collingbourne68162e72013-08-14 18:54:12 +0000665
Peter Collingbourne59b12622013-08-22 20:08:08 +0000666 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
667 FT->getReturnType()->isVoidTy());
Peter Collingbourne68162e72013-08-14 18:54:12 +0000668
669 if (isInstrumented(&F)) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000670 // Instrumented functions get a 'dfs$' prefix. This allows us to more
671 // easily identify cases of mismatching ABIs.
672 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000673 FunctionType *NewFT = getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000674 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000675 NewF->copyAttributesFrom(&F);
676 NewF->removeAttributes(
677 AttributeSet::ReturnIndex,
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000678 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
Peter Collingbourne68162e72013-08-14 18:54:12 +0000679 AttributeSet::ReturnIndex));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000680 for (Function::arg_iterator FArg = F.arg_begin(),
681 NewFArg = NewF->arg_begin(),
682 FArgEnd = F.arg_end();
683 FArg != FArgEnd; ++FArg, ++NewFArg) {
684 FArg->replaceAllUsesWith(NewFArg);
685 }
686 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
687
Chandler Carruthcdf47882014-03-09 03:16:01 +0000688 for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
689 UI != UE;) {
690 BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
691 ++UI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000692 if (BA) {
693 BA->replaceAllUsesWith(
694 BlockAddress::get(NewF, BA->getBasicBlock()));
695 delete BA;
696 }
697 }
698 F.replaceAllUsesWith(
699 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
700 NewF->takeName(&F);
701 F.eraseFromParent();
702 *i = NewF;
Peter Collingbourne59b12622013-08-22 20:08:08 +0000703 addGlobalNamePrefix(NewF);
704 } else {
705 addGlobalNamePrefix(&F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000706 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000707 // Hopefully, nobody will try to indirectly call a vararg
708 // function... yet.
709 } else if (FT->isVarArg()) {
710 UnwrappedFnMap[&F] = &F;
Craig Topperf40110f2014-04-25 05:29:35 +0000711 *i = nullptr;
Peter Collingbourne59b12622013-08-22 20:08:08 +0000712 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000713 // Build a wrapper function for F. The wrapper simply calls F, and is
714 // added to FnsToInstrument so that any instrumentation according to its
715 // WrapperKind is done in the second pass below.
716 FunctionType *NewFT = getInstrumentedABI() == IA_Args
717 ? getArgsFunctionType(FT)
718 : FT;
Alexey Samsonov6dae24d2013-08-23 07:42:51 +0000719 Function *NewF = buildWrapperFunction(
720 &F, std::string("dfsw$") + std::string(F.getName()),
721 GlobalValue::LinkOnceODRLinkage, NewFT);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000722 if (getInstrumentedABI() == IA_TLS)
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000723 NewF->removeAttributes(AttributeSet::FunctionIndex, ReadOnlyNoneAttrs);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000724
Peter Collingbourne68162e72013-08-14 18:54:12 +0000725 Value *WrappedFnCst =
726 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
727 F.replaceAllUsesWith(WrappedFnCst);
728 UnwrappedFnMap[WrappedFnCst] = &F;
729 *i = NewF;
730
731 if (!F.isDeclaration()) {
732 // This function is probably defining an interposition of an
733 // uninstrumented function and hence needs to keep the original ABI.
734 // But any functions it may call need to use the instrumented ABI, so
735 // we instrument it in a mode which preserves the original ABI.
736 FnsWithNativeABI.insert(&F);
737
738 // This code needs to rebuild the iterators, as they may be invalidated
739 // by the push_back, taking care that the new range does not include
740 // any functions added by this code.
741 size_t N = i - FnsToInstrument.begin(),
742 Count = e - FnsToInstrument.begin();
743 FnsToInstrument.push_back(&F);
744 i = FnsToInstrument.begin() + N;
745 e = FnsToInstrument.begin() + Count;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000746 }
747 }
748 }
749
750 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
751 e = FnsToInstrument.end();
752 i != e; ++i) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000753 if (!*i || (*i)->isDeclaration())
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000754 continue;
755
Peter Collingbourneae66d572013-08-09 21:42:53 +0000756 removeUnreachableBlocks(**i);
757
Peter Collingbourne68162e72013-08-14 18:54:12 +0000758 DFSanFunction DFSF(*this, *i, FnsWithNativeABI.count(*i));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000759
760 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
761 // Build a copy of the list before iterating over it.
David Blaikieceec2bd2014-04-11 01:50:01 +0000762 llvm::SmallVector<BasicBlock *, 4> BBList(
763 depth_first(&(*i)->getEntryBlock()));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000764
765 for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
766 e = BBList.end();
767 i != e; ++i) {
768 Instruction *Inst = &(*i)->front();
769 while (1) {
770 // DFSanVisitor may split the current basic block, changing the current
771 // instruction's next pointer and moving the next instruction to the
772 // tail block from which we should continue.
773 Instruction *Next = Inst->getNextNode();
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000774 // DFSanVisitor may delete Inst, so keep track of whether it was a
775 // terminator.
776 bool IsTerminator = isa<TerminatorInst>(Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000777 if (!DFSF.SkipInsts.count(Inst))
778 DFSanVisitor(DFSF).visit(Inst);
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000779 if (IsTerminator)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000780 break;
781 Inst = Next;
782 }
783 }
784
Peter Collingbourne68162e72013-08-14 18:54:12 +0000785 // We will not necessarily be able to compute the shadow for every phi node
786 // until we have visited every block. Therefore, the code that handles phi
787 // nodes adds them to the PHIFixups list so that they can be properly
788 // handled here.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000789 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
790 i = DFSF.PHIFixups.begin(),
791 e = DFSF.PHIFixups.end();
792 i != e; ++i) {
793 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
794 ++val) {
795 i->second->setIncomingValue(
796 val, DFSF.getShadow(i->first->getIncomingValue(val)));
797 }
798 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000799
800 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
801 // places (i.e. instructions in basic blocks we haven't even begun visiting
802 // yet). To make our life easier, do this work in a pass after the main
803 // instrumentation.
804 if (ClDebugNonzeroLabels) {
Peter Collingbournefab565a2014-08-22 01:18:18 +0000805 for (Value *V : DFSF.NonZeroChecks) {
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000806 Instruction *Pos;
Peter Collingbournefab565a2014-08-22 01:18:18 +0000807 if (Instruction *I = dyn_cast<Instruction>(V))
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000808 Pos = I->getNextNode();
809 else
810 Pos = DFSF.F->getEntryBlock().begin();
811 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
812 Pos = Pos->getNextNode();
813 IRBuilder<> IRB(Pos);
Peter Collingbournefab565a2014-08-22 01:18:18 +0000814 Value *Ne = IRB.CreateICmpNE(V, DFSF.DFS.ZeroShadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000815 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000816 Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000817 IRBuilder<> ThenIRB(BI);
818 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn);
819 }
820 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000821 }
822
823 return false;
824}
825
826Value *DFSanFunction::getArgTLSPtr() {
827 if (ArgTLSPtr)
828 return ArgTLSPtr;
829 if (DFS.ArgTLS)
830 return ArgTLSPtr = DFS.ArgTLS;
831
832 IRBuilder<> IRB(F->getEntryBlock().begin());
833 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
834}
835
836Value *DFSanFunction::getRetvalTLS() {
837 if (RetvalTLSPtr)
838 return RetvalTLSPtr;
839 if (DFS.RetvalTLS)
840 return RetvalTLSPtr = DFS.RetvalTLS;
841
842 IRBuilder<> IRB(F->getEntryBlock().begin());
843 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
844}
845
846Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
847 IRBuilder<> IRB(Pos);
848 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
849}
850
851Value *DFSanFunction::getShadow(Value *V) {
852 if (!isa<Argument>(V) && !isa<Instruction>(V))
853 return DFS.ZeroShadow;
854 Value *&Shadow = ValShadowMap[V];
855 if (!Shadow) {
856 if (Argument *A = dyn_cast<Argument>(V)) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000857 if (IsNativeABI)
858 return DFS.ZeroShadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000859 switch (IA) {
860 case DataFlowSanitizer::IA_TLS: {
861 Value *ArgTLSPtr = getArgTLSPtr();
862 Instruction *ArgTLSPos =
863 DFS.ArgTLS ? &*F->getEntryBlock().begin()
864 : cast<Instruction>(ArgTLSPtr)->getNextNode();
865 IRBuilder<> IRB(ArgTLSPos);
866 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
867 break;
868 }
869 case DataFlowSanitizer::IA_Args: {
870 unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
871 Function::arg_iterator i = F->arg_begin();
872 while (ArgIdx--)
873 ++i;
874 Shadow = i;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000875 assert(Shadow->getType() == DFS.ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000876 break;
877 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000878 }
Peter Collingbournefab565a2014-08-22 01:18:18 +0000879 NonZeroChecks.push_back(Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000880 } else {
881 Shadow = DFS.ZeroShadow;
882 }
883 }
884 return Shadow;
885}
886
887void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
888 assert(!ValShadowMap.count(I));
889 assert(Shadow->getType() == DFS.ShadowTy);
890 ValShadowMap[I] = Shadow;
891}
892
893Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
894 assert(Addr != RetvalTLS && "Reinstrumenting?");
895 IRBuilder<> IRB(Pos);
896 return IRB.CreateIntToPtr(
897 IRB.CreateMul(
898 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
899 ShadowPtrMul),
900 ShadowPtrTy);
901}
902
903// Generates IR to compute the union of the two given shadows, inserting it
904// before Pos. Returns the computed union Value.
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000905Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
906 if (V1 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000907 return V2;
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000908 if (V2 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000909 return V1;
910 if (V1 == V2)
911 return V1;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000912
Peter Collingbourne9947c492014-07-15 22:13:19 +0000913 auto V1Elems = ShadowElements.find(V1);
914 auto V2Elems = ShadowElements.find(V2);
915 if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
916 if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
917 V2Elems->second.begin(), V2Elems->second.end())) {
918 return V1;
919 } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
920 V1Elems->second.begin(), V1Elems->second.end())) {
921 return V2;
922 }
923 } else if (V1Elems != ShadowElements.end()) {
924 if (V1Elems->second.count(V2))
925 return V1;
926 } else if (V2Elems != ShadowElements.end()) {
927 if (V2Elems->second.count(V1))
928 return V2;
929 }
930
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000931 auto Key = std::make_pair(V1, V2);
932 if (V1 > V2)
933 std::swap(Key.first, Key.second);
934 CachedCombinedShadow &CCS = CachedCombinedShadows[Key];
935 if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
936 return CCS.Shadow;
937
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000938 IRBuilder<> IRB(Pos);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000939 if (AvoidNewBlocks) {
940 CallInst *Call = IRB.CreateCall2(DFS.DFSanCheckedUnionFn, V1, V2);
941 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
942 Call->addAttribute(1, Attribute::ZExt);
943 Call->addAttribute(2, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000944
Peter Collingbournedf240b22014-08-06 00:33:40 +0000945 CCS.Block = Pos->getParent();
946 CCS.Shadow = Call;
947 } else {
948 BasicBlock *Head = Pos->getParent();
949 Value *Ne = IRB.CreateICmpNE(V1, V2);
950 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
951 Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
952 IRBuilder<> ThenIRB(BI);
953 CallInst *Call = ThenIRB.CreateCall2(DFS.DFSanUnionFn, V1, V2);
954 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
955 Call->addAttribute(1, Attribute::ZExt);
956 Call->addAttribute(2, Attribute::ZExt);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000957
Peter Collingbournedf240b22014-08-06 00:33:40 +0000958 BasicBlock *Tail = BI->getSuccessor(0);
959 PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", Tail->begin());
960 Phi->addIncoming(Call, Call->getParent());
961 Phi->addIncoming(V1, Head);
962
963 CCS.Block = Tail;
964 CCS.Shadow = Phi;
965 }
Peter Collingbourne9947c492014-07-15 22:13:19 +0000966
967 std::set<Value *> UnionElems;
968 if (V1Elems != ShadowElements.end()) {
969 UnionElems = V1Elems->second;
970 } else {
971 UnionElems.insert(V1);
972 }
973 if (V2Elems != ShadowElements.end()) {
974 UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
975 } else {
976 UnionElems.insert(V2);
977 }
Peter Collingbournedf240b22014-08-06 00:33:40 +0000978 ShadowElements[CCS.Shadow] = std::move(UnionElems);
Peter Collingbourne9947c492014-07-15 22:13:19 +0000979
Peter Collingbournedf240b22014-08-06 00:33:40 +0000980 return CCS.Shadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000981}
982
983// A convenience function which folds the shadows of each of the operands
984// of the provided instruction Inst, inserting the IR before Inst. Returns
985// the computed union Value.
986Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
987 if (Inst->getNumOperands() == 0)
988 return DFS.ZeroShadow;
989
990 Value *Shadow = getShadow(Inst->getOperand(0));
991 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000992 Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000993 }
994 return Shadow;
995}
996
997void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
998 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
999 DFSF.setShadow(&I, CombinedShadow);
1000}
1001
1002// Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
1003// Addr has alignment Align, and take the union of each of those shadows.
1004Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
1005 Instruction *Pos) {
1006 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1007 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1008 AllocaShadowMap.find(AI);
1009 if (i != AllocaShadowMap.end()) {
1010 IRBuilder<> IRB(Pos);
1011 return IRB.CreateLoad(i->second);
1012 }
1013 }
1014
1015 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1016 SmallVector<Value *, 2> Objs;
1017 GetUnderlyingObjects(Addr, Objs, DFS.DL);
1018 bool AllConstants = true;
1019 for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
1020 i != e; ++i) {
1021 if (isa<Function>(*i) || isa<BlockAddress>(*i))
1022 continue;
1023 if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
1024 continue;
1025
1026 AllConstants = false;
1027 break;
1028 }
1029 if (AllConstants)
1030 return DFS.ZeroShadow;
1031
1032 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1033 switch (Size) {
1034 case 0:
1035 return DFS.ZeroShadow;
1036 case 1: {
1037 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
1038 LI->setAlignment(ShadowAlign);
1039 return LI;
1040 }
1041 case 2: {
1042 IRBuilder<> IRB(Pos);
1043 Value *ShadowAddr1 =
1044 IRB.CreateGEP(ShadowAddr, ConstantInt::get(DFS.IntptrTy, 1));
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001045 return combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
1046 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign), Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001047 }
1048 }
Peter Collingbournedf240b22014-08-06 00:33:40 +00001049 if (!AvoidNewBlocks && Size % (64 / DFS.ShadowWidth) == 0) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001050 // Fast path for the common case where each byte has identical shadow: load
1051 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
1052 // shadow is non-equal.
1053 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
1054 IRBuilder<> FallbackIRB(FallbackBB);
1055 CallInst *FallbackCall = FallbackIRB.CreateCall2(
1056 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
1057 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1058
1059 // Compare each of the shadows stored in the loaded 64 bits to each other,
1060 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
1061 IRBuilder<> IRB(Pos);
1062 Value *WideAddr =
1063 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1064 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1065 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
1066 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
1067 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
1068 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1069 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1070
1071 BasicBlock *Head = Pos->getParent();
1072 BasicBlock *Tail = Head->splitBasicBlock(Pos);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001073
1074 if (DomTreeNode *OldNode = DT.getNode(Head)) {
1075 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1076
1077 DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1078 for (auto Child : Children)
1079 DT.changeImmediateDominator(Child, NewNode);
1080 }
1081
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001082 // In the following code LastBr will refer to the previous basic block's
1083 // conditional branch instruction, whose true successor is fixed up to point
1084 // to the next block during the loop below or to the tail after the final
1085 // iteration.
1086 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1087 ReplaceInstWithInst(Head->getTerminator(), LastBr);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001088 DT.addNewBlock(FallbackBB, Head);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001089
1090 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
1091 Ofs += 64 / DFS.ShadowWidth) {
1092 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001093 DT.addNewBlock(NextBB, LastBr->getParent());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001094 IRBuilder<> NextIRB(NextBB);
1095 WideAddr = NextIRB.CreateGEP(WideAddr, ConstantInt::get(DFS.IntptrTy, 1));
1096 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1097 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1098 LastBr->setSuccessor(0, NextBB);
1099 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1100 }
1101
1102 LastBr->setSuccessor(0, Tail);
1103 FallbackIRB.CreateBr(Tail);
1104 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1105 Shadow->addIncoming(FallbackCall, FallbackBB);
1106 Shadow->addIncoming(TruncShadow, LastBr->getParent());
1107 return Shadow;
1108 }
1109
1110 IRBuilder<> IRB(Pos);
1111 CallInst *FallbackCall = IRB.CreateCall2(
1112 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
1113 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1114 return FallbackCall;
1115}
1116
1117void DFSanVisitor::visitLoadInst(LoadInst &LI) {
1118 uint64_t Size = DFSF.DFS.DL->getTypeStoreSize(LI.getType());
Peter Collingbourne142fdff2014-08-01 21:18:18 +00001119 if (Size == 0) {
1120 DFSF.setShadow(&LI, DFSF.DFS.ZeroShadow);
1121 return;
1122 }
1123
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001124 uint64_t Align;
1125 if (ClPreserveAlignment) {
1126 Align = LI.getAlignment();
1127 if (Align == 0)
1128 Align = DFSF.DFS.DL->getABITypeAlignment(LI.getType());
1129 } else {
1130 Align = 1;
1131 }
1132 IRBuilder<> IRB(&LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001133 Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
1134 if (ClCombinePointerLabelsOnLoad) {
1135 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001136 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001137 }
1138 if (Shadow != DFSF.DFS.ZeroShadow)
Peter Collingbournefab565a2014-08-22 01:18:18 +00001139 DFSF.NonZeroChecks.push_back(Shadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +00001140
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001141 DFSF.setShadow(&LI, Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001142}
1143
1144void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
1145 Value *Shadow, Instruction *Pos) {
1146 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1147 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1148 AllocaShadowMap.find(AI);
1149 if (i != AllocaShadowMap.end()) {
1150 IRBuilder<> IRB(Pos);
1151 IRB.CreateStore(Shadow, i->second);
1152 return;
1153 }
1154 }
1155
1156 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1157 IRBuilder<> IRB(Pos);
1158 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1159 if (Shadow == DFS.ZeroShadow) {
1160 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1161 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1162 Value *ExtShadowAddr =
1163 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1164 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1165 return;
1166 }
1167
1168 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1169 uint64_t Offset = 0;
1170 if (Size >= ShadowVecSize) {
1171 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1172 Value *ShadowVec = UndefValue::get(ShadowVecTy);
1173 for (unsigned i = 0; i != ShadowVecSize; ++i) {
1174 ShadowVec = IRB.CreateInsertElement(
1175 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1176 }
1177 Value *ShadowVecAddr =
1178 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1179 do {
1180 Value *CurShadowVecAddr = IRB.CreateConstGEP1_32(ShadowVecAddr, Offset);
1181 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1182 Size -= ShadowVecSize;
1183 ++Offset;
1184 } while (Size >= ShadowVecSize);
1185 Offset *= ShadowVecSize;
1186 }
1187 while (Size > 0) {
1188 Value *CurShadowAddr = IRB.CreateConstGEP1_32(ShadowAddr, Offset);
1189 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1190 --Size;
1191 ++Offset;
1192 }
1193}
1194
1195void DFSanVisitor::visitStoreInst(StoreInst &SI) {
1196 uint64_t Size =
1197 DFSF.DFS.DL->getTypeStoreSize(SI.getValueOperand()->getType());
Peter Collingbourne142fdff2014-08-01 21:18:18 +00001198 if (Size == 0)
1199 return;
1200
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001201 uint64_t Align;
1202 if (ClPreserveAlignment) {
1203 Align = SI.getAlignment();
1204 if (Align == 0)
1205 Align = DFSF.DFS.DL->getABITypeAlignment(SI.getValueOperand()->getType());
1206 } else {
1207 Align = 1;
1208 }
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001209
1210 Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1211 if (ClCombinePointerLabelsOnStore) {
1212 Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001213 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001214 }
1215 DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001216}
1217
1218void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1219 visitOperandShadowInst(BO);
1220}
1221
1222void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1223
1224void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1225
1226void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1227 visitOperandShadowInst(GEPI);
1228}
1229
1230void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1231 visitOperandShadowInst(I);
1232}
1233
1234void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1235 visitOperandShadowInst(I);
1236}
1237
1238void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1239 visitOperandShadowInst(I);
1240}
1241
1242void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1243 visitOperandShadowInst(I);
1244}
1245
1246void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1247 visitOperandShadowInst(I);
1248}
1249
1250void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1251 bool AllLoadsStores = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001252 for (User *U : I.users()) {
1253 if (isa<LoadInst>(U))
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001254 continue;
1255
Chandler Carruthcdf47882014-03-09 03:16:01 +00001256 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001257 if (SI->getPointerOperand() == &I)
1258 continue;
1259 }
1260
1261 AllLoadsStores = false;
1262 break;
1263 }
1264 if (AllLoadsStores) {
1265 IRBuilder<> IRB(&I);
1266 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1267 }
1268 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1269}
1270
1271void DFSanVisitor::visitSelectInst(SelectInst &I) {
1272 Value *CondShadow = DFSF.getShadow(I.getCondition());
1273 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1274 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1275
1276 if (isa<VectorType>(I.getCondition()->getType())) {
1277 DFSF.setShadow(
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001278 &I,
1279 DFSF.combineShadows(
1280 CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001281 } else {
1282 Value *ShadowSel;
1283 if (TrueShadow == FalseShadow) {
1284 ShadowSel = TrueShadow;
1285 } else {
1286 ShadowSel =
1287 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1288 }
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001289 DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001290 }
1291}
1292
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +00001293void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1294 IRBuilder<> IRB(&I);
1295 Value *ValShadow = DFSF.getShadow(I.getValue());
1296 IRB.CreateCall3(
1297 DFSF.DFS.DFSanSetLabelFn, ValShadow,
1298 IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
1299 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy));
1300}
1301
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001302void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1303 IRBuilder<> IRB(&I);
1304 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1305 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1306 Value *LenShadow = IRB.CreateMul(
1307 I.getLength(),
1308 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
1309 Value *AlignShadow;
1310 if (ClPreserveAlignment) {
1311 AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1312 ConstantInt::get(I.getAlignmentCst()->getType(),
1313 DFSF.DFS.ShadowWidth / 8));
1314 } else {
1315 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1316 DFSF.DFS.ShadowWidth / 8);
1317 }
1318 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1319 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1320 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
1321 IRB.CreateCall5(I.getCalledValue(), DestShadow, SrcShadow, LenShadow,
1322 AlignShadow, I.getVolatileCst());
1323}
1324
1325void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001326 if (!DFSF.IsNativeABI && RI.getReturnValue()) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001327 switch (DFSF.IA) {
1328 case DataFlowSanitizer::IA_TLS: {
1329 Value *S = DFSF.getShadow(RI.getReturnValue());
1330 IRBuilder<> IRB(&RI);
1331 IRB.CreateStore(S, DFSF.getRetvalTLS());
1332 break;
1333 }
1334 case DataFlowSanitizer::IA_Args: {
1335 IRBuilder<> IRB(&RI);
1336 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1337 Value *InsVal =
1338 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1339 Value *InsShadow =
1340 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1341 RI.setOperand(0, InsShadow);
1342 break;
1343 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001344 }
1345 }
1346}
1347
1348void DFSanVisitor::visitCallSite(CallSite CS) {
1349 Function *F = CS.getCalledFunction();
1350 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1351 visitOperandShadowInst(*CS.getInstruction());
1352 return;
1353 }
1354
Peter Collingbourne68162e72013-08-14 18:54:12 +00001355 IRBuilder<> IRB(CS.getInstruction());
1356
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001357 DenseMap<Value *, Function *>::iterator i =
1358 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1359 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001360 Function *F = i->second;
1361 switch (DFSF.DFS.getWrapperKind(F)) {
1362 case DataFlowSanitizer::WK_Warning: {
1363 CS.setCalledFunction(F);
1364 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1365 IRB.CreateGlobalStringPtr(F->getName()));
1366 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1367 return;
1368 }
1369 case DataFlowSanitizer::WK_Discard: {
1370 CS.setCalledFunction(F);
1371 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1372 return;
1373 }
1374 case DataFlowSanitizer::WK_Functional: {
1375 CS.setCalledFunction(F);
1376 visitOperandShadowInst(*CS.getInstruction());
1377 return;
1378 }
1379 case DataFlowSanitizer::WK_Custom: {
1380 // Don't try to handle invokes of custom functions, it's too complicated.
1381 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1382 // wrapper.
1383 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1384 FunctionType *FT = F->getFunctionType();
1385 FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1386 std::string CustomFName = "__dfsw_";
1387 CustomFName += F->getName();
1388 Constant *CustomF =
1389 DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1390 if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1391 CustomFn->copyAttributesFrom(F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001392
Peter Collingbourne68162e72013-08-14 18:54:12 +00001393 // Custom functions returning non-void will write to the return label.
1394 if (!FT->getReturnType()->isVoidTy()) {
1395 CustomFn->removeAttributes(AttributeSet::FunctionIndex,
1396 DFSF.DFS.ReadOnlyNoneAttrs);
1397 }
1398 }
1399
1400 std::vector<Value *> Args;
1401
1402 CallSite::arg_iterator i = CS.arg_begin();
Peter Collingbourne28a10af2013-08-27 22:09:06 +00001403 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
1404 Type *T = (*i)->getType();
1405 FunctionType *ParamFT;
1406 if (isa<PointerType>(T) &&
1407 (ParamFT = dyn_cast<FunctionType>(
1408 cast<PointerType>(T)->getElementType()))) {
1409 std::string TName = "dfst";
1410 TName += utostr(FT->getNumParams() - n);
1411 TName += "$";
1412 TName += F->getName();
1413 Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1414 Args.push_back(T);
1415 Args.push_back(
1416 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1417 } else {
1418 Args.push_back(*i);
1419 }
1420 }
Peter Collingbourne68162e72013-08-14 18:54:12 +00001421
1422 i = CS.arg_begin();
1423 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1424 Args.push_back(DFSF.getShadow(*i));
1425
1426 if (!FT->getReturnType()->isVoidTy()) {
1427 if (!DFSF.LabelReturnAlloca) {
1428 DFSF.LabelReturnAlloca =
1429 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
1430 DFSF.F->getEntryBlock().begin());
1431 }
1432 Args.push_back(DFSF.LabelReturnAlloca);
1433 }
1434
1435 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1436 CustomCI->setCallingConv(CI->getCallingConv());
1437 CustomCI->setAttributes(CI->getAttributes());
1438
1439 if (!FT->getReturnType()->isVoidTy()) {
1440 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1441 DFSF.setShadow(CustomCI, LabelLoad);
1442 }
1443
1444 CI->replaceAllUsesWith(CustomCI);
1445 CI->eraseFromParent();
1446 return;
1447 }
1448 break;
1449 }
1450 }
1451 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001452
1453 FunctionType *FT = cast<FunctionType>(
1454 CS.getCalledValue()->getType()->getPointerElementType());
Peter Collingbourne68162e72013-08-14 18:54:12 +00001455 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001456 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1457 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1458 DFSF.getArgTLS(i, CS.getInstruction()));
1459 }
1460 }
1461
Craig Topperf40110f2014-04-25 05:29:35 +00001462 Instruction *Next = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001463 if (!CS.getType()->isVoidTy()) {
1464 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1465 if (II->getNormalDest()->getSinglePredecessor()) {
1466 Next = II->getNormalDest()->begin();
1467 } else {
1468 BasicBlock *NewBB =
1469 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DFS);
1470 Next = NewBB->begin();
1471 }
1472 } else {
1473 Next = CS->getNextNode();
1474 }
1475
Peter Collingbourne68162e72013-08-14 18:54:12 +00001476 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001477 IRBuilder<> NextIRB(Next);
1478 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1479 DFSF.SkipInsts.insert(LI);
1480 DFSF.setShadow(CS.getInstruction(), LI);
Peter Collingbournefab565a2014-08-22 01:18:18 +00001481 DFSF.NonZeroChecks.push_back(LI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001482 }
1483 }
1484
1485 // Do all instrumentation for IA_Args down here to defer tampering with the
1486 // CFG in a way that SplitEdge may be able to detect.
Peter Collingbourne68162e72013-08-14 18:54:12 +00001487 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1488 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001489 Value *Func =
1490 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1491 std::vector<Value *> Args;
1492
1493 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1494 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1495 Args.push_back(*i);
1496
1497 i = CS.arg_begin();
1498 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1499 Args.push_back(DFSF.getShadow(*i));
1500
1501 if (FT->isVarArg()) {
1502 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1503 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1504 AllocaInst *VarArgShadow =
1505 new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
1506 Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
1507 for (unsigned n = 0; i != e; ++i, ++n) {
1508 IRB.CreateStore(DFSF.getShadow(*i),
1509 IRB.CreateConstGEP2_32(VarArgShadow, 0, n));
1510 Args.push_back(*i);
1511 }
1512 }
1513
1514 CallSite NewCS;
1515 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1516 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1517 Args);
1518 } else {
1519 NewCS = IRB.CreateCall(Func, Args);
1520 }
1521 NewCS.setCallingConv(CS.getCallingConv());
1522 NewCS.setAttributes(CS.getAttributes().removeAttributes(
1523 *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
1524 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType(),
1525 AttributeSet::ReturnIndex)));
1526
1527 if (Next) {
1528 ExtractValueInst *ExVal =
1529 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1530 DFSF.SkipInsts.insert(ExVal);
1531 ExtractValueInst *ExShadow =
1532 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1533 DFSF.SkipInsts.insert(ExShadow);
1534 DFSF.setShadow(ExVal, ExShadow);
Peter Collingbournefab565a2014-08-22 01:18:18 +00001535 DFSF.NonZeroChecks.push_back(ExShadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001536
1537 CS.getInstruction()->replaceAllUsesWith(ExVal);
1538 }
1539
1540 CS.getInstruction()->eraseFromParent();
1541 }
1542}
1543
1544void DFSanVisitor::visitPHINode(PHINode &PN) {
1545 PHINode *ShadowPN =
1546 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1547
1548 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1549 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1550 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1551 ++i) {
1552 ShadowPN->addIncoming(UndefShadow, *i);
1553 }
1554
1555 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1556 DFSF.setShadow(&PN, ShadowPN);
1557}