blob: 446bcf79b5585aea7d67f142ee11fd431607f676 [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:
Kostya Serebryanyad238522014-09-02 21:46:51 +0000142 DFSanABIList(std::unique_ptr<SpecialCaseList> SCL) : SCL(std::move(SCL)) {}
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000143
144 /// Returns whether either this function or its source file are listed in the
145 /// given category.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000146 bool isIn(const Function &F, StringRef Category) const {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000147 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.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000155 bool isIn(const GlobalAlias &GA, StringRef Category) const {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000156 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.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000167 bool isIn(const Module &M, StringRef Category) const {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000168 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) {
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +0000390 if (T->isVarArg()) {
391 // The labels are passed after all the arguments so there is no need to
392 // adjust the function type.
393 return T;
394 }
395
Peter Collingbourne68162e72013-08-14 18:54:12 +0000396 llvm::SmallVector<Type *, 4> ArgTypes;
Alexey Samsonov9b7e2b52013-08-28 11:25:12 +0000397 for (FunctionType::param_iterator i = T->param_begin(), e = T->param_end();
398 i != e; ++i) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000399 FunctionType *FT;
Alexey Samsonov9b7e2b52013-08-28 11:25:12 +0000400 if (isa<PointerType>(*i) && (FT = dyn_cast<FunctionType>(cast<PointerType>(
401 *i)->getElementType()))) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000402 ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
403 ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
404 } else {
405 ArgTypes.push_back(*i);
406 }
407 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000408 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
409 ArgTypes.push_back(ShadowTy);
410 Type *RetType = T->getReturnType();
411 if (!RetType->isVoidTy())
412 ArgTypes.push_back(ShadowPtrTy);
413 return FunctionType::get(T->getReturnType(), ArgTypes, false);
414}
415
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000416bool DataFlowSanitizer::doInitialization(Module &M) {
Rafael Espindola93512512014-02-25 17:30:31 +0000417 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
418 if (!DLP)
Evgeniy Stepanov119cb2e2014-04-23 12:51:32 +0000419 report_fatal_error("data layout missing");
Rafael Espindola93512512014-02-25 17:30:31 +0000420 DL = &DLP->getDataLayout();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000421
422 Mod = &M;
423 Ctx = &M.getContext();
424 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
425 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
426 IntptrTy = DL->getIntPtrType(*Ctx);
427 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
Peter Collingbournea5689e62013-08-08 00:15:27 +0000428 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000429 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
430
431 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
432 DFSanUnionFnTy =
433 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
434 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
435 DFSanUnionLoadFnTy =
436 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000437 DFSanUnimplementedFnTy = FunctionType::get(
438 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000439 Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
440 DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
441 DFSanSetLabelArgs, /*isVarArg=*/false);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000442 DFSanNonzeroLabelFnTy = FunctionType::get(
Craig Toppere1d12942014-08-27 05:25:25 +0000443 Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000444
445 if (GetArgTLSPtr) {
446 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
Craig Topperf40110f2014-04-25 05:29:35 +0000447 ArgTLS = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000448 GetArgTLS = ConstantExpr::getIntToPtr(
449 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
450 PointerType::getUnqual(
Craig Topperf40110f2014-04-25 05:29:35 +0000451 FunctionType::get(PointerType::getUnqual(ArgTLSTy),
452 (Type *)nullptr)));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000453 }
454 if (GetRetvalTLSPtr) {
Craig Topperf40110f2014-04-25 05:29:35 +0000455 RetvalTLS = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000456 GetRetvalTLS = ConstantExpr::getIntToPtr(
457 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
458 PointerType::getUnqual(
Craig Topperf40110f2014-04-25 05:29:35 +0000459 FunctionType::get(PointerType::getUnqual(ShadowTy),
460 (Type *)nullptr)));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000461 }
462
463 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
464 return true;
465}
466
Peter Collingbourne59b12622013-08-22 20:08:08 +0000467bool DataFlowSanitizer::isInstrumented(const Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000468 return !ABIList.isIn(*F, "uninstrumented");
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000469}
470
Peter Collingbourne59b12622013-08-22 20:08:08 +0000471bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000472 return !ABIList.isIn(*GA, "uninstrumented");
Peter Collingbourne59b12622013-08-22 20:08:08 +0000473}
474
Peter Collingbourne68162e72013-08-14 18:54:12 +0000475DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000476 return ClArgsABI ? IA_Args : IA_TLS;
477}
478
Peter Collingbourne68162e72013-08-14 18:54:12 +0000479DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000480 if (ABIList.isIn(*F, "functional"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000481 return WK_Functional;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000482 if (ABIList.isIn(*F, "discard"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000483 return WK_Discard;
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +0000484 if (ABIList.isIn(*F, "custom"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000485 return WK_Custom;
486
487 return WK_Warning;
488}
489
Peter Collingbourne59b12622013-08-22 20:08:08 +0000490void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
491 std::string GVName = GV->getName(), Prefix = "dfs$";
492 GV->setName(Prefix + GVName);
493
494 // Try to change the name of the function in module inline asm. We only do
495 // this for specific asm directives, currently only ".symver", to try to avoid
496 // corrupting asm which happens to contain the symbol name as a substring.
497 // Note that the substitution for .symver assumes that the versioned symbol
498 // also has an instrumented name.
499 std::string Asm = GV->getParent()->getModuleInlineAsm();
500 std::string SearchStr = ".symver " + GVName + ",";
501 size_t Pos = Asm.find(SearchStr);
502 if (Pos != std::string::npos) {
503 Asm.replace(Pos, SearchStr.size(),
504 ".symver " + Prefix + GVName + "," + Prefix);
505 GV->getParent()->setModuleInlineAsm(Asm);
506 }
507}
508
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000509Function *
510DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
511 GlobalValue::LinkageTypes NewFLink,
512 FunctionType *NewFT) {
513 FunctionType *FT = F->getFunctionType();
514 Function *NewF = Function::Create(NewFT, NewFLink, NewFName,
515 F->getParent());
516 NewF->copyAttributesFrom(F);
517 NewF->removeAttributes(
518 AttributeSet::ReturnIndex,
519 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
520 AttributeSet::ReturnIndex));
521
522 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
523 std::vector<Value *> Args;
524 unsigned n = FT->getNumParams();
525 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
526 Args.push_back(&*ai);
527 CallInst *CI = CallInst::Create(F, Args, "", BB);
528 if (FT->getReturnType()->isVoidTy())
529 ReturnInst::Create(*Ctx, BB);
530 else
531 ReturnInst::Create(*Ctx, CI, BB);
532
533 return NewF;
534}
535
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000536Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
537 StringRef FName) {
538 FunctionType *FTT = getTrampolineFunctionType(FT);
539 Constant *C = Mod->getOrInsertFunction(FName, FTT);
540 Function *F = dyn_cast<Function>(C);
541 if (F && F->isDeclaration()) {
542 F->setLinkage(GlobalValue::LinkOnceODRLinkage);
543 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
544 std::vector<Value *> Args;
545 Function::arg_iterator AI = F->arg_begin(); ++AI;
546 for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
547 Args.push_back(&*AI);
548 CallInst *CI =
549 CallInst::Create(&F->getArgumentList().front(), Args, "", BB);
550 ReturnInst *RI;
551 if (FT->getReturnType()->isVoidTy())
552 RI = ReturnInst::Create(*Ctx, BB);
553 else
554 RI = ReturnInst::Create(*Ctx, CI, BB);
555
556 DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
557 Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
558 for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
559 DFSF.ValShadowMap[ValAI] = ShadowAI;
560 DFSanVisitor(DFSF).visitCallInst(*CI);
561 if (!FT->getReturnType()->isVoidTy())
562 new StoreInst(DFSF.getShadow(RI->getReturnValue()),
563 &F->getArgumentList().back(), RI);
564 }
565
566 return C;
567}
568
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000569bool DataFlowSanitizer::runOnModule(Module &M) {
570 if (!DL)
571 return false;
572
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000573 if (ABIList.isIn(M, "skip"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000574 return false;
575
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000576 if (!GetArgTLSPtr) {
577 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
578 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
579 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
580 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
581 }
582 if (!GetRetvalTLSPtr) {
583 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
584 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
585 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
586 }
587
588 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
589 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
Peter Collingbournedf240b22014-08-06 00:33:40 +0000590 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
591 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
592 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
593 F->addAttribute(1, Attribute::ZExt);
594 F->addAttribute(2, Attribute::ZExt);
595 }
596 DFSanCheckedUnionFn = Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy);
597 if (Function *F = dyn_cast<Function>(DFSanCheckedUnionFn)) {
598 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000599 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
600 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
601 F->addAttribute(1, Attribute::ZExt);
602 F->addAttribute(2, Attribute::ZExt);
603 }
604 DFSanUnionLoadFn =
605 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
606 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
Peter Collingbournedf240b22014-08-06 00:33:40 +0000607 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
Peter Collingbourne0be79e12013-11-21 23:20:54 +0000608 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000609 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
610 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000611 DFSanUnimplementedFn =
612 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000613 DFSanSetLabelFn =
614 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
615 if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
616 F->addAttribute(1, Attribute::ZExt);
617 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000618 DFSanNonzeroLabelFn =
619 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000620
621 std::vector<Function *> FnsToInstrument;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000622 llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000623 for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000624 if (!i->isIntrinsic() &&
625 i != DFSanUnionFn &&
Peter Collingbournedf240b22014-08-06 00:33:40 +0000626 i != DFSanCheckedUnionFn &&
Peter Collingbourne68162e72013-08-14 18:54:12 +0000627 i != DFSanUnionLoadFn &&
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000628 i != DFSanUnimplementedFn &&
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000629 i != DFSanSetLabelFn &&
630 i != DFSanNonzeroLabelFn)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000631 FnsToInstrument.push_back(&*i);
632 }
633
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000634 // Give function aliases prefixes when necessary, and build wrappers where the
635 // instrumentedness is inconsistent.
Peter Collingbourne59b12622013-08-22 20:08:08 +0000636 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
637 GlobalAlias *GA = &*i;
638 ++i;
639 // Don't stop on weak. We assume people aren't playing games with the
640 // instrumentedness of overridden weak aliases.
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000641 if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000642 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
643 if (GAInst && FInst) {
644 addGlobalNamePrefix(GA);
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000645 } else if (GAInst != FInst) {
646 // Non-instrumented alias of an instrumented function, or vice versa.
647 // Replace the alias with a native-ABI wrapper of the aliasee. The pass
648 // below will take care of instrumenting it.
649 Function *NewF =
650 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000651 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000652 NewF->takeName(GA);
653 GA->eraseFromParent();
654 FnsToInstrument.push_back(NewF);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000655 }
656 }
657 }
658
Peter Collingbourne68162e72013-08-14 18:54:12 +0000659 AttrBuilder B;
660 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
661 ReadOnlyNoneAttrs = AttributeSet::get(*Ctx, AttributeSet::FunctionIndex, B);
662
663 // First, change the ABI of every function in the module. ABI-listed
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000664 // functions keep their original ABI and get a wrapper function.
665 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
666 e = FnsToInstrument.end();
667 i != e; ++i) {
668 Function &F = **i;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000669 FunctionType *FT = F.getFunctionType();
Peter Collingbourne68162e72013-08-14 18:54:12 +0000670
Peter Collingbourne59b12622013-08-22 20:08:08 +0000671 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
672 FT->getReturnType()->isVoidTy());
Peter Collingbourne68162e72013-08-14 18:54:12 +0000673
674 if (isInstrumented(&F)) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000675 // Instrumented functions get a 'dfs$' prefix. This allows us to more
676 // easily identify cases of mismatching ABIs.
677 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000678 FunctionType *NewFT = getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000679 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000680 NewF->copyAttributesFrom(&F);
681 NewF->removeAttributes(
682 AttributeSet::ReturnIndex,
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000683 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
Peter Collingbourne68162e72013-08-14 18:54:12 +0000684 AttributeSet::ReturnIndex));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000685 for (Function::arg_iterator FArg = F.arg_begin(),
686 NewFArg = NewF->arg_begin(),
687 FArgEnd = F.arg_end();
688 FArg != FArgEnd; ++FArg, ++NewFArg) {
689 FArg->replaceAllUsesWith(NewFArg);
690 }
691 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
692
Chandler Carruthcdf47882014-03-09 03:16:01 +0000693 for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
694 UI != UE;) {
695 BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
696 ++UI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000697 if (BA) {
698 BA->replaceAllUsesWith(
699 BlockAddress::get(NewF, BA->getBasicBlock()));
700 delete BA;
701 }
702 }
703 F.replaceAllUsesWith(
704 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
705 NewF->takeName(&F);
706 F.eraseFromParent();
707 *i = NewF;
Peter Collingbourne59b12622013-08-22 20:08:08 +0000708 addGlobalNamePrefix(NewF);
709 } else {
710 addGlobalNamePrefix(&F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000711 }
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 }
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +0000747 // Hopefully, nobody will try to indirectly call a vararg
748 // function... yet.
749 } else if (FT->isVarArg()) {
750 UnwrappedFnMap[&F] = &F;
751 *i = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000752 }
753 }
754
755 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
756 e = FnsToInstrument.end();
757 i != e; ++i) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000758 if (!*i || (*i)->isDeclaration())
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000759 continue;
760
Peter Collingbourneae66d572013-08-09 21:42:53 +0000761 removeUnreachableBlocks(**i);
762
Peter Collingbourne68162e72013-08-14 18:54:12 +0000763 DFSanFunction DFSF(*this, *i, FnsWithNativeABI.count(*i));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000764
765 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
766 // Build a copy of the list before iterating over it.
David Blaikieceec2bd2014-04-11 01:50:01 +0000767 llvm::SmallVector<BasicBlock *, 4> BBList(
768 depth_first(&(*i)->getEntryBlock()));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000769
770 for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
771 e = BBList.end();
772 i != e; ++i) {
773 Instruction *Inst = &(*i)->front();
774 while (1) {
775 // DFSanVisitor may split the current basic block, changing the current
776 // instruction's next pointer and moving the next instruction to the
777 // tail block from which we should continue.
778 Instruction *Next = Inst->getNextNode();
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000779 // DFSanVisitor may delete Inst, so keep track of whether it was a
780 // terminator.
781 bool IsTerminator = isa<TerminatorInst>(Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000782 if (!DFSF.SkipInsts.count(Inst))
783 DFSanVisitor(DFSF).visit(Inst);
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000784 if (IsTerminator)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000785 break;
786 Inst = Next;
787 }
788 }
789
Peter Collingbourne68162e72013-08-14 18:54:12 +0000790 // We will not necessarily be able to compute the shadow for every phi node
791 // until we have visited every block. Therefore, the code that handles phi
792 // nodes adds them to the PHIFixups list so that they can be properly
793 // handled here.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000794 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
795 i = DFSF.PHIFixups.begin(),
796 e = DFSF.PHIFixups.end();
797 i != e; ++i) {
798 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
799 ++val) {
800 i->second->setIncomingValue(
801 val, DFSF.getShadow(i->first->getIncomingValue(val)));
802 }
803 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000804
805 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
806 // places (i.e. instructions in basic blocks we haven't even begun visiting
807 // yet). To make our life easier, do this work in a pass after the main
808 // instrumentation.
809 if (ClDebugNonzeroLabels) {
Peter Collingbournefab565a2014-08-22 01:18:18 +0000810 for (Value *V : DFSF.NonZeroChecks) {
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000811 Instruction *Pos;
Peter Collingbournefab565a2014-08-22 01:18:18 +0000812 if (Instruction *I = dyn_cast<Instruction>(V))
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000813 Pos = I->getNextNode();
814 else
815 Pos = DFSF.F->getEntryBlock().begin();
816 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
817 Pos = Pos->getNextNode();
818 IRBuilder<> IRB(Pos);
Peter Collingbournefab565a2014-08-22 01:18:18 +0000819 Value *Ne = IRB.CreateICmpNE(V, DFSF.DFS.ZeroShadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000820 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000821 Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000822 IRBuilder<> ThenIRB(BI);
823 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn);
824 }
825 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000826 }
827
828 return false;
829}
830
831Value *DFSanFunction::getArgTLSPtr() {
832 if (ArgTLSPtr)
833 return ArgTLSPtr;
834 if (DFS.ArgTLS)
835 return ArgTLSPtr = DFS.ArgTLS;
836
837 IRBuilder<> IRB(F->getEntryBlock().begin());
838 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
839}
840
841Value *DFSanFunction::getRetvalTLS() {
842 if (RetvalTLSPtr)
843 return RetvalTLSPtr;
844 if (DFS.RetvalTLS)
845 return RetvalTLSPtr = DFS.RetvalTLS;
846
847 IRBuilder<> IRB(F->getEntryBlock().begin());
848 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
849}
850
851Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
852 IRBuilder<> IRB(Pos);
853 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
854}
855
856Value *DFSanFunction::getShadow(Value *V) {
857 if (!isa<Argument>(V) && !isa<Instruction>(V))
858 return DFS.ZeroShadow;
859 Value *&Shadow = ValShadowMap[V];
860 if (!Shadow) {
861 if (Argument *A = dyn_cast<Argument>(V)) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000862 if (IsNativeABI)
863 return DFS.ZeroShadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000864 switch (IA) {
865 case DataFlowSanitizer::IA_TLS: {
866 Value *ArgTLSPtr = getArgTLSPtr();
867 Instruction *ArgTLSPos =
868 DFS.ArgTLS ? &*F->getEntryBlock().begin()
869 : cast<Instruction>(ArgTLSPtr)->getNextNode();
870 IRBuilder<> IRB(ArgTLSPos);
871 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
872 break;
873 }
874 case DataFlowSanitizer::IA_Args: {
875 unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
876 Function::arg_iterator i = F->arg_begin();
877 while (ArgIdx--)
878 ++i;
879 Shadow = i;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000880 assert(Shadow->getType() == DFS.ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000881 break;
882 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000883 }
Peter Collingbournefab565a2014-08-22 01:18:18 +0000884 NonZeroChecks.push_back(Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000885 } else {
886 Shadow = DFS.ZeroShadow;
887 }
888 }
889 return Shadow;
890}
891
892void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
893 assert(!ValShadowMap.count(I));
894 assert(Shadow->getType() == DFS.ShadowTy);
895 ValShadowMap[I] = Shadow;
896}
897
898Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
899 assert(Addr != RetvalTLS && "Reinstrumenting?");
900 IRBuilder<> IRB(Pos);
901 return IRB.CreateIntToPtr(
902 IRB.CreateMul(
903 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
904 ShadowPtrMul),
905 ShadowPtrTy);
906}
907
908// Generates IR to compute the union of the two given shadows, inserting it
909// before Pos. Returns the computed union Value.
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000910Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
911 if (V1 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000912 return V2;
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000913 if (V2 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000914 return V1;
915 if (V1 == V2)
916 return V1;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000917
Peter Collingbourne9947c492014-07-15 22:13:19 +0000918 auto V1Elems = ShadowElements.find(V1);
919 auto V2Elems = ShadowElements.find(V2);
920 if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
921 if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
922 V2Elems->second.begin(), V2Elems->second.end())) {
923 return V1;
924 } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
925 V1Elems->second.begin(), V1Elems->second.end())) {
926 return V2;
927 }
928 } else if (V1Elems != ShadowElements.end()) {
929 if (V1Elems->second.count(V2))
930 return V1;
931 } else if (V2Elems != ShadowElements.end()) {
932 if (V2Elems->second.count(V1))
933 return V2;
934 }
935
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000936 auto Key = std::make_pair(V1, V2);
937 if (V1 > V2)
938 std::swap(Key.first, Key.second);
939 CachedCombinedShadow &CCS = CachedCombinedShadows[Key];
940 if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
941 return CCS.Shadow;
942
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000943 IRBuilder<> IRB(Pos);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000944 if (AvoidNewBlocks) {
945 CallInst *Call = IRB.CreateCall2(DFS.DFSanCheckedUnionFn, V1, V2);
946 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
947 Call->addAttribute(1, Attribute::ZExt);
948 Call->addAttribute(2, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000949
Peter Collingbournedf240b22014-08-06 00:33:40 +0000950 CCS.Block = Pos->getParent();
951 CCS.Shadow = Call;
952 } else {
953 BasicBlock *Head = Pos->getParent();
954 Value *Ne = IRB.CreateICmpNE(V1, V2);
955 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
956 Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
957 IRBuilder<> ThenIRB(BI);
958 CallInst *Call = ThenIRB.CreateCall2(DFS.DFSanUnionFn, V1, V2);
959 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
960 Call->addAttribute(1, Attribute::ZExt);
961 Call->addAttribute(2, Attribute::ZExt);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000962
Peter Collingbournedf240b22014-08-06 00:33:40 +0000963 BasicBlock *Tail = BI->getSuccessor(0);
964 PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", Tail->begin());
965 Phi->addIncoming(Call, Call->getParent());
966 Phi->addIncoming(V1, Head);
967
968 CCS.Block = Tail;
969 CCS.Shadow = Phi;
970 }
Peter Collingbourne9947c492014-07-15 22:13:19 +0000971
972 std::set<Value *> UnionElems;
973 if (V1Elems != ShadowElements.end()) {
974 UnionElems = V1Elems->second;
975 } else {
976 UnionElems.insert(V1);
977 }
978 if (V2Elems != ShadowElements.end()) {
979 UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
980 } else {
981 UnionElems.insert(V2);
982 }
Peter Collingbournedf240b22014-08-06 00:33:40 +0000983 ShadowElements[CCS.Shadow] = std::move(UnionElems);
Peter Collingbourne9947c492014-07-15 22:13:19 +0000984
Peter Collingbournedf240b22014-08-06 00:33:40 +0000985 return CCS.Shadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000986}
987
988// A convenience function which folds the shadows of each of the operands
989// of the provided instruction Inst, inserting the IR before Inst. Returns
990// the computed union Value.
991Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
992 if (Inst->getNumOperands() == 0)
993 return DFS.ZeroShadow;
994
995 Value *Shadow = getShadow(Inst->getOperand(0));
996 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000997 Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000998 }
999 return Shadow;
1000}
1001
1002void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
1003 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1004 DFSF.setShadow(&I, CombinedShadow);
1005}
1006
1007// Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
1008// Addr has alignment Align, and take the union of each of those shadows.
1009Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
1010 Instruction *Pos) {
1011 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1012 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1013 AllocaShadowMap.find(AI);
1014 if (i != AllocaShadowMap.end()) {
1015 IRBuilder<> IRB(Pos);
1016 return IRB.CreateLoad(i->second);
1017 }
1018 }
1019
1020 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1021 SmallVector<Value *, 2> Objs;
1022 GetUnderlyingObjects(Addr, Objs, DFS.DL);
1023 bool AllConstants = true;
1024 for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
1025 i != e; ++i) {
1026 if (isa<Function>(*i) || isa<BlockAddress>(*i))
1027 continue;
1028 if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
1029 continue;
1030
1031 AllConstants = false;
1032 break;
1033 }
1034 if (AllConstants)
1035 return DFS.ZeroShadow;
1036
1037 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1038 switch (Size) {
1039 case 0:
1040 return DFS.ZeroShadow;
1041 case 1: {
1042 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
1043 LI->setAlignment(ShadowAlign);
1044 return LI;
1045 }
1046 case 2: {
1047 IRBuilder<> IRB(Pos);
1048 Value *ShadowAddr1 =
1049 IRB.CreateGEP(ShadowAddr, ConstantInt::get(DFS.IntptrTy, 1));
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001050 return combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
1051 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign), Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001052 }
1053 }
Peter Collingbournedf240b22014-08-06 00:33:40 +00001054 if (!AvoidNewBlocks && Size % (64 / DFS.ShadowWidth) == 0) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001055 // Fast path for the common case where each byte has identical shadow: load
1056 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
1057 // shadow is non-equal.
1058 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
1059 IRBuilder<> FallbackIRB(FallbackBB);
1060 CallInst *FallbackCall = FallbackIRB.CreateCall2(
1061 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
1062 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1063
1064 // Compare each of the shadows stored in the loaded 64 bits to each other,
1065 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
1066 IRBuilder<> IRB(Pos);
1067 Value *WideAddr =
1068 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1069 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1070 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
1071 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
1072 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
1073 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1074 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1075
1076 BasicBlock *Head = Pos->getParent();
1077 BasicBlock *Tail = Head->splitBasicBlock(Pos);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001078
1079 if (DomTreeNode *OldNode = DT.getNode(Head)) {
1080 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1081
1082 DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1083 for (auto Child : Children)
1084 DT.changeImmediateDominator(Child, NewNode);
1085 }
1086
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001087 // In the following code LastBr will refer to the previous basic block's
1088 // conditional branch instruction, whose true successor is fixed up to point
1089 // to the next block during the loop below or to the tail after the final
1090 // iteration.
1091 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1092 ReplaceInstWithInst(Head->getTerminator(), LastBr);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001093 DT.addNewBlock(FallbackBB, Head);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001094
1095 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
1096 Ofs += 64 / DFS.ShadowWidth) {
1097 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001098 DT.addNewBlock(NextBB, LastBr->getParent());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001099 IRBuilder<> NextIRB(NextBB);
1100 WideAddr = NextIRB.CreateGEP(WideAddr, ConstantInt::get(DFS.IntptrTy, 1));
1101 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1102 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1103 LastBr->setSuccessor(0, NextBB);
1104 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1105 }
1106
1107 LastBr->setSuccessor(0, Tail);
1108 FallbackIRB.CreateBr(Tail);
1109 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1110 Shadow->addIncoming(FallbackCall, FallbackBB);
1111 Shadow->addIncoming(TruncShadow, LastBr->getParent());
1112 return Shadow;
1113 }
1114
1115 IRBuilder<> IRB(Pos);
1116 CallInst *FallbackCall = IRB.CreateCall2(
1117 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
1118 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1119 return FallbackCall;
1120}
1121
1122void DFSanVisitor::visitLoadInst(LoadInst &LI) {
1123 uint64_t Size = DFSF.DFS.DL->getTypeStoreSize(LI.getType());
Peter Collingbourne142fdff2014-08-01 21:18:18 +00001124 if (Size == 0) {
1125 DFSF.setShadow(&LI, DFSF.DFS.ZeroShadow);
1126 return;
1127 }
1128
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001129 uint64_t Align;
1130 if (ClPreserveAlignment) {
1131 Align = LI.getAlignment();
1132 if (Align == 0)
1133 Align = DFSF.DFS.DL->getABITypeAlignment(LI.getType());
1134 } else {
1135 Align = 1;
1136 }
1137 IRBuilder<> IRB(&LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001138 Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
1139 if (ClCombinePointerLabelsOnLoad) {
1140 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001141 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001142 }
1143 if (Shadow != DFSF.DFS.ZeroShadow)
Peter Collingbournefab565a2014-08-22 01:18:18 +00001144 DFSF.NonZeroChecks.push_back(Shadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +00001145
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001146 DFSF.setShadow(&LI, Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001147}
1148
1149void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
1150 Value *Shadow, Instruction *Pos) {
1151 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1152 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1153 AllocaShadowMap.find(AI);
1154 if (i != AllocaShadowMap.end()) {
1155 IRBuilder<> IRB(Pos);
1156 IRB.CreateStore(Shadow, i->second);
1157 return;
1158 }
1159 }
1160
1161 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1162 IRBuilder<> IRB(Pos);
1163 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1164 if (Shadow == DFS.ZeroShadow) {
1165 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1166 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1167 Value *ExtShadowAddr =
1168 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1169 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1170 return;
1171 }
1172
1173 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1174 uint64_t Offset = 0;
1175 if (Size >= ShadowVecSize) {
1176 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1177 Value *ShadowVec = UndefValue::get(ShadowVecTy);
1178 for (unsigned i = 0; i != ShadowVecSize; ++i) {
1179 ShadowVec = IRB.CreateInsertElement(
1180 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1181 }
1182 Value *ShadowVecAddr =
1183 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1184 do {
1185 Value *CurShadowVecAddr = IRB.CreateConstGEP1_32(ShadowVecAddr, Offset);
1186 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1187 Size -= ShadowVecSize;
1188 ++Offset;
1189 } while (Size >= ShadowVecSize);
1190 Offset *= ShadowVecSize;
1191 }
1192 while (Size > 0) {
1193 Value *CurShadowAddr = IRB.CreateConstGEP1_32(ShadowAddr, Offset);
1194 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1195 --Size;
1196 ++Offset;
1197 }
1198}
1199
1200void DFSanVisitor::visitStoreInst(StoreInst &SI) {
1201 uint64_t Size =
1202 DFSF.DFS.DL->getTypeStoreSize(SI.getValueOperand()->getType());
Peter Collingbourne142fdff2014-08-01 21:18:18 +00001203 if (Size == 0)
1204 return;
1205
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001206 uint64_t Align;
1207 if (ClPreserveAlignment) {
1208 Align = SI.getAlignment();
1209 if (Align == 0)
1210 Align = DFSF.DFS.DL->getABITypeAlignment(SI.getValueOperand()->getType());
1211 } else {
1212 Align = 1;
1213 }
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001214
1215 Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1216 if (ClCombinePointerLabelsOnStore) {
1217 Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001218 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001219 }
1220 DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001221}
1222
1223void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1224 visitOperandShadowInst(BO);
1225}
1226
1227void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1228
1229void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1230
1231void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1232 visitOperandShadowInst(GEPI);
1233}
1234
1235void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1236 visitOperandShadowInst(I);
1237}
1238
1239void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1240 visitOperandShadowInst(I);
1241}
1242
1243void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1244 visitOperandShadowInst(I);
1245}
1246
1247void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1248 visitOperandShadowInst(I);
1249}
1250
1251void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1252 visitOperandShadowInst(I);
1253}
1254
1255void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1256 bool AllLoadsStores = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001257 for (User *U : I.users()) {
1258 if (isa<LoadInst>(U))
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001259 continue;
1260
Chandler Carruthcdf47882014-03-09 03:16:01 +00001261 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001262 if (SI->getPointerOperand() == &I)
1263 continue;
1264 }
1265
1266 AllLoadsStores = false;
1267 break;
1268 }
1269 if (AllLoadsStores) {
1270 IRBuilder<> IRB(&I);
1271 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1272 }
1273 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1274}
1275
1276void DFSanVisitor::visitSelectInst(SelectInst &I) {
1277 Value *CondShadow = DFSF.getShadow(I.getCondition());
1278 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1279 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1280
1281 if (isa<VectorType>(I.getCondition()->getType())) {
1282 DFSF.setShadow(
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001283 &I,
1284 DFSF.combineShadows(
1285 CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001286 } else {
1287 Value *ShadowSel;
1288 if (TrueShadow == FalseShadow) {
1289 ShadowSel = TrueShadow;
1290 } else {
1291 ShadowSel =
1292 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1293 }
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001294 DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001295 }
1296}
1297
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +00001298void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1299 IRBuilder<> IRB(&I);
1300 Value *ValShadow = DFSF.getShadow(I.getValue());
1301 IRB.CreateCall3(
1302 DFSF.DFS.DFSanSetLabelFn, ValShadow,
1303 IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
1304 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy));
1305}
1306
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001307void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1308 IRBuilder<> IRB(&I);
1309 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1310 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1311 Value *LenShadow = IRB.CreateMul(
1312 I.getLength(),
1313 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
1314 Value *AlignShadow;
1315 if (ClPreserveAlignment) {
1316 AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1317 ConstantInt::get(I.getAlignmentCst()->getType(),
1318 DFSF.DFS.ShadowWidth / 8));
1319 } else {
1320 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1321 DFSF.DFS.ShadowWidth / 8);
1322 }
1323 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1324 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1325 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
1326 IRB.CreateCall5(I.getCalledValue(), DestShadow, SrcShadow, LenShadow,
1327 AlignShadow, I.getVolatileCst());
1328}
1329
1330void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001331 if (!DFSF.IsNativeABI && RI.getReturnValue()) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001332 switch (DFSF.IA) {
1333 case DataFlowSanitizer::IA_TLS: {
1334 Value *S = DFSF.getShadow(RI.getReturnValue());
1335 IRBuilder<> IRB(&RI);
1336 IRB.CreateStore(S, DFSF.getRetvalTLS());
1337 break;
1338 }
1339 case DataFlowSanitizer::IA_Args: {
1340 IRBuilder<> IRB(&RI);
1341 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1342 Value *InsVal =
1343 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1344 Value *InsShadow =
1345 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1346 RI.setOperand(0, InsShadow);
1347 break;
1348 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001349 }
1350 }
1351}
1352
1353void DFSanVisitor::visitCallSite(CallSite CS) {
1354 Function *F = CS.getCalledFunction();
1355 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1356 visitOperandShadowInst(*CS.getInstruction());
1357 return;
1358 }
1359
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +00001360 assert(!(cast<FunctionType>(
1361 CS.getCalledValue()->getType()->getPointerElementType())->isVarArg() &&
1362 dyn_cast<InvokeInst>(CS.getInstruction())));
1363
Peter Collingbourne68162e72013-08-14 18:54:12 +00001364 IRBuilder<> IRB(CS.getInstruction());
1365
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001366 DenseMap<Value *, Function *>::iterator i =
1367 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1368 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001369 Function *F = i->second;
1370 switch (DFSF.DFS.getWrapperKind(F)) {
1371 case DataFlowSanitizer::WK_Warning: {
1372 CS.setCalledFunction(F);
1373 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1374 IRB.CreateGlobalStringPtr(F->getName()));
1375 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1376 return;
1377 }
1378 case DataFlowSanitizer::WK_Discard: {
1379 CS.setCalledFunction(F);
1380 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1381 return;
1382 }
1383 case DataFlowSanitizer::WK_Functional: {
1384 CS.setCalledFunction(F);
1385 visitOperandShadowInst(*CS.getInstruction());
1386 return;
1387 }
1388 case DataFlowSanitizer::WK_Custom: {
1389 // Don't try to handle invokes of custom functions, it's too complicated.
1390 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1391 // wrapper.
1392 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1393 FunctionType *FT = F->getFunctionType();
1394 FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1395 std::string CustomFName = "__dfsw_";
1396 CustomFName += F->getName();
1397 Constant *CustomF =
1398 DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1399 if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1400 CustomFn->copyAttributesFrom(F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001401
Peter Collingbourne68162e72013-08-14 18:54:12 +00001402 // Custom functions returning non-void will write to the return label.
1403 if (!FT->getReturnType()->isVoidTy()) {
1404 CustomFn->removeAttributes(AttributeSet::FunctionIndex,
1405 DFSF.DFS.ReadOnlyNoneAttrs);
1406 }
1407 }
1408
1409 std::vector<Value *> Args;
1410
1411 CallSite::arg_iterator i = CS.arg_begin();
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +00001412 for (unsigned n = CS.arg_size(); n != 0; ++i, --n) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +00001413 Type *T = (*i)->getType();
1414 FunctionType *ParamFT;
1415 if (isa<PointerType>(T) &&
1416 (ParamFT = dyn_cast<FunctionType>(
1417 cast<PointerType>(T)->getElementType()))) {
1418 std::string TName = "dfst";
1419 TName += utostr(FT->getNumParams() - n);
1420 TName += "$";
1421 TName += F->getName();
1422 Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1423 Args.push_back(T);
1424 Args.push_back(
1425 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1426 } else {
1427 Args.push_back(*i);
1428 }
1429 }
Peter Collingbourne68162e72013-08-14 18:54:12 +00001430
1431 i = CS.arg_begin();
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +00001432 for (unsigned n = CS.arg_size(); n != 0; ++i, --n)
Peter Collingbourne68162e72013-08-14 18:54:12 +00001433 Args.push_back(DFSF.getShadow(*i));
1434
1435 if (!FT->getReturnType()->isVoidTy()) {
1436 if (!DFSF.LabelReturnAlloca) {
1437 DFSF.LabelReturnAlloca =
1438 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
1439 DFSF.F->getEntryBlock().begin());
1440 }
1441 Args.push_back(DFSF.LabelReturnAlloca);
1442 }
1443
1444 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1445 CustomCI->setCallingConv(CI->getCallingConv());
1446 CustomCI->setAttributes(CI->getAttributes());
1447
1448 if (!FT->getReturnType()->isVoidTy()) {
1449 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1450 DFSF.setShadow(CustomCI, LabelLoad);
1451 }
1452
1453 CI->replaceAllUsesWith(CustomCI);
1454 CI->eraseFromParent();
1455 return;
1456 }
1457 break;
1458 }
1459 }
1460 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001461
1462 FunctionType *FT = cast<FunctionType>(
1463 CS.getCalledValue()->getType()->getPointerElementType());
Peter Collingbourne68162e72013-08-14 18:54:12 +00001464 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001465 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1466 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1467 DFSF.getArgTLS(i, CS.getInstruction()));
1468 }
1469 }
1470
Craig Topperf40110f2014-04-25 05:29:35 +00001471 Instruction *Next = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001472 if (!CS.getType()->isVoidTy()) {
1473 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1474 if (II->getNormalDest()->getSinglePredecessor()) {
1475 Next = II->getNormalDest()->begin();
1476 } else {
1477 BasicBlock *NewBB =
1478 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DFS);
1479 Next = NewBB->begin();
1480 }
1481 } else {
1482 Next = CS->getNextNode();
1483 }
1484
Peter Collingbourne68162e72013-08-14 18:54:12 +00001485 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001486 IRBuilder<> NextIRB(Next);
1487 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1488 DFSF.SkipInsts.insert(LI);
1489 DFSF.setShadow(CS.getInstruction(), LI);
Peter Collingbournefab565a2014-08-22 01:18:18 +00001490 DFSF.NonZeroChecks.push_back(LI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001491 }
1492 }
1493
1494 // Do all instrumentation for IA_Args down here to defer tampering with the
1495 // CFG in a way that SplitEdge may be able to detect.
Peter Collingbourne68162e72013-08-14 18:54:12 +00001496 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1497 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001498 Value *Func =
1499 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1500 std::vector<Value *> Args;
1501
1502 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1503 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1504 Args.push_back(*i);
1505
1506 i = CS.arg_begin();
1507 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1508 Args.push_back(DFSF.getShadow(*i));
1509
1510 if (FT->isVarArg()) {
1511 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1512 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1513 AllocaInst *VarArgShadow =
1514 new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
1515 Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
1516 for (unsigned n = 0; i != e; ++i, ++n) {
1517 IRB.CreateStore(DFSF.getShadow(*i),
1518 IRB.CreateConstGEP2_32(VarArgShadow, 0, n));
1519 Args.push_back(*i);
1520 }
1521 }
1522
1523 CallSite NewCS;
1524 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1525 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1526 Args);
1527 } else {
1528 NewCS = IRB.CreateCall(Func, Args);
1529 }
1530 NewCS.setCallingConv(CS.getCallingConv());
1531 NewCS.setAttributes(CS.getAttributes().removeAttributes(
1532 *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
1533 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType(),
1534 AttributeSet::ReturnIndex)));
1535
1536 if (Next) {
1537 ExtractValueInst *ExVal =
1538 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1539 DFSF.SkipInsts.insert(ExVal);
1540 ExtractValueInst *ExShadow =
1541 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1542 DFSF.SkipInsts.insert(ExShadow);
1543 DFSF.setShadow(ExVal, ExShadow);
Peter Collingbournefab565a2014-08-22 01:18:18 +00001544 DFSF.NonZeroChecks.push_back(ExShadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001545
1546 CS.getInstruction()->replaceAllUsesWith(ExVal);
1547 }
1548
1549 CS.getInstruction()->eraseFromParent();
1550 }
1551}
1552
1553void DFSanVisitor::visitPHINode(PHINode &PN) {
1554 PHINode *ShadowPN =
1555 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1556
1557 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1558 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1559 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1560 ++i) {
1561 ShadowPN->addIncoming(UndefShadow, *i);
1562 }
1563
1564 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1565 DFSF.setShadow(&PN, ShadowPN);
1566}