blob: 7f468f79e22d61d0db715e8d75bd211360b5036c [file] [log] [blame]
Peter Collingbourne6fa33f52013-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 Collingbourneffba4c72013-08-27 22:09:06 +000051#include "llvm/ADT/StringExtras.h"
Peter Collingbourne6fa33f52013-08-07 22:47:18 +000052#include "llvm/Analysis/ValueTracking.h"
Peter Collingbourne6fa33f52013-08-07 22:47:18 +000053#include "llvm/IR/IRBuilder.h"
Stephen Hines36b56882014-04-23 16:57:46 -070054#include "llvm/IR/InlineAsm.h"
55#include "llvm/IR/InstVisitor.h"
Peter Collingbourne6fa33f52013-08-07 22:47:18 +000056#include "llvm/IR/LLVMContext.h"
57#include "llvm/IR/MDBuilder.h"
58#include "llvm/IR/Type.h"
59#include "llvm/IR/Value.h"
Peter Collingbourne6fa33f52013-08-07 22:47:18 +000060#include "llvm/Pass.h"
61#include "llvm/Support/CommandLine.h"
62#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Peter Collingbourneaaae6e92013-08-09 21:42:53 +000063#include "llvm/Transforms/Utils/Local.h"
Peter Collingbourne6fa33f52013-08-07 22:47:18 +000064#include "llvm/Transforms/Utils/SpecialCaseList.h"
65#include <iterator>
66
67using namespace llvm;
68
69// The -dfsan-preserve-alignment flag controls whether this pass assumes that
70// alignment requirements provided by the input IR are correct. For example,
71// if the input IR contains a load with alignment 8, this flag will cause
72// the shadow load to have alignment 16. This flag is disabled by default as
73// we have unfortunately encountered too much code (including Clang itself;
74// see PR14291) which performs misaligned access.
75static cl::opt<bool> ClPreserveAlignment(
76 "dfsan-preserve-alignment",
77 cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
78 cl::init(false));
79
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +000080// The ABI list file controls how shadow parameters are passed. The pass treats
81// every function labelled "uninstrumented" in the ABI list file as conforming
82// to the "native" (i.e. unsanitized) ABI. Unless the ABI list contains
83// additional annotations for those functions, a call to one of those functions
84// will produce a warning message, as the labelling behaviour of the function is
85// unknown. The other supported annotations are "functional" and "discard",
86// which are described below under DataFlowSanitizer::WrapperKind.
87static cl::opt<std::string> ClABIListFile(
88 "dfsan-abilist",
89 cl::desc("File listing native ABI functions and how the pass treats them"),
Peter Collingbourne6fa33f52013-08-07 22:47:18 +000090 cl::Hidden);
91
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +000092// Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
93// functions (see DataFlowSanitizer::InstrumentedABI below).
Peter Collingbourne6fa33f52013-08-07 22:47:18 +000094static cl::opt<bool> ClArgsABI(
95 "dfsan-args-abi",
96 cl::desc("Use the argument ABI rather than the TLS ABI"),
97 cl::Hidden);
98
Stephen Hines36b56882014-04-23 16:57:46 -070099// Controls whether the pass includes or ignores the labels of pointers in load
100// instructions.
101static cl::opt<bool> ClCombinePointerLabelsOnLoad(
102 "dfsan-combine-pointer-labels-on-load",
103 cl::desc("Combine the label of the pointer with the label of the data when "
104 "loading from memory."),
105 cl::Hidden, cl::init(true));
106
107// Controls whether the pass includes or ignores the labels of pointers in
108// stores instructions.
109static cl::opt<bool> ClCombinePointerLabelsOnStore(
110 "dfsan-combine-pointer-labels-on-store",
111 cl::desc("Combine the label of the pointer with the label of the data when "
112 "storing in memory."),
113 cl::Hidden, cl::init(false));
114
Peter Collingbournea77d9f72013-08-15 18:51:12 +0000115static cl::opt<bool> ClDebugNonzeroLabels(
116 "dfsan-debug-nonzero-labels",
117 cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
118 "load or return with a nonzero label"),
119 cl::Hidden);
120
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000121namespace {
122
123class DataFlowSanitizer : public ModulePass {
124 friend struct DFSanFunction;
125 friend class DFSanVisitor;
126
127 enum {
128 ShadowWidth = 16
129 };
130
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000131 /// Which ABI should be used for instrumented functions?
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000132 enum InstrumentedABI {
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000133 /// Argument and return value labels are passed through additional
134 /// arguments and by modifying the return type.
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000135 IA_Args,
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000136
137 /// Argument and return value labels are passed through TLS variables
138 /// __dfsan_arg_tls and __dfsan_retval_tls.
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000139 IA_TLS
140 };
141
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000142 /// How should calls to uninstrumented functions be handled?
143 enum WrapperKind {
144 /// This function is present in an uninstrumented form but we don't know
145 /// how it should be handled. Print a warning and call the function anyway.
146 /// Don't label the return value.
147 WK_Warning,
148
149 /// This function does not write to (user-accessible) memory, and its return
150 /// value is unlabelled.
151 WK_Discard,
152
153 /// This function does not write to (user-accessible) memory, and the label
154 /// of its return value is the union of the label of its arguments.
155 WK_Functional,
156
157 /// Instead of calling the function, a custom wrapper __dfsw_F is called,
158 /// where F is the name of the function. This function may wrap the
159 /// original function or provide its own implementation. This is similar to
160 /// the IA_Args ABI, except that IA_Args uses a struct return type to
161 /// pass the return value shadow in a register, while WK_Custom uses an
162 /// extra pointer argument to return the shadow. This allows the wrapped
163 /// form of the function type to be expressed in C.
164 WK_Custom
165 };
166
Stephen Hines36b56882014-04-23 16:57:46 -0700167 const DataLayout *DL;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000168 Module *Mod;
169 LLVMContext *Ctx;
170 IntegerType *ShadowTy;
171 PointerType *ShadowPtrTy;
172 IntegerType *IntptrTy;
173 ConstantInt *ZeroShadow;
174 ConstantInt *ShadowPtrMask;
175 ConstantInt *ShadowPtrMul;
176 Constant *ArgTLS;
177 Constant *RetvalTLS;
178 void *(*GetArgTLSPtr)();
179 void *(*GetRetvalTLSPtr)();
180 Constant *GetArgTLS;
181 Constant *GetRetvalTLS;
182 FunctionType *DFSanUnionFnTy;
183 FunctionType *DFSanUnionLoadFnTy;
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000184 FunctionType *DFSanUnimplementedFnTy;
Peter Collingbourneef8136d2013-08-14 20:51:38 +0000185 FunctionType *DFSanSetLabelFnTy;
Peter Collingbournea77d9f72013-08-15 18:51:12 +0000186 FunctionType *DFSanNonzeroLabelFnTy;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000187 Constant *DFSanUnionFn;
188 Constant *DFSanUnionLoadFn;
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000189 Constant *DFSanUnimplementedFn;
Peter Collingbourneef8136d2013-08-14 20:51:38 +0000190 Constant *DFSanSetLabelFn;
Peter Collingbournea77d9f72013-08-15 18:51:12 +0000191 Constant *DFSanNonzeroLabelFn;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000192 MDNode *ColdCallWeights;
Stephen Hines36b56882014-04-23 16:57:46 -0700193 std::unique_ptr<SpecialCaseList> ABIList;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000194 DenseMap<Value *, Function *> UnwrappedFnMap;
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000195 AttributeSet ReadOnlyNoneAttrs;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000196
197 Value *getShadowAddress(Value *Addr, Instruction *Pos);
198 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
Peter Collingbournef1366c52013-08-22 20:08:08 +0000199 bool isInstrumented(const Function *F);
200 bool isInstrumented(const GlobalAlias *GA);
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000201 FunctionType *getArgsFunctionType(FunctionType *T);
Peter Collingbourneffba4c72013-08-27 22:09:06 +0000202 FunctionType *getTrampolineFunctionType(FunctionType *T);
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000203 FunctionType *getCustomFunctionType(FunctionType *T);
204 InstrumentedABI getInstrumentedABI();
205 WrapperKind getWrapperKind(Function *F);
Peter Collingbournef1366c52013-08-22 20:08:08 +0000206 void addGlobalNamePrefix(GlobalValue *GV);
Peter Collingbourne4f68e9e2013-08-22 20:08:11 +0000207 Function *buildWrapperFunction(Function *F, StringRef NewFName,
208 GlobalValue::LinkageTypes NewFLink,
209 FunctionType *NewFT);
Peter Collingbourneffba4c72013-08-27 22:09:06 +0000210 Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000211
Dmitry Vyukova036a312013-08-13 16:52:41 +0000212 public:
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000213 DataFlowSanitizer(StringRef ABIListFile = StringRef(),
Stephen Hinesdce4a402014-05-29 02:49:00 -0700214 void *(*getArgTLS)() = nullptr,
215 void *(*getRetValTLS)() = nullptr);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000216 static char ID;
Stephen Hines36b56882014-04-23 16:57:46 -0700217 bool doInitialization(Module &M) override;
218 bool runOnModule(Module &M) override;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000219};
220
221struct DFSanFunction {
222 DataFlowSanitizer &DFS;
223 Function *F;
224 DataFlowSanitizer::InstrumentedABI IA;
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000225 bool IsNativeABI;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000226 Value *ArgTLSPtr;
227 Value *RetvalTLSPtr;
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000228 AllocaInst *LabelReturnAlloca;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000229 DenseMap<Value *, Value *> ValShadowMap;
230 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
231 std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
232 DenseSet<Instruction *> SkipInsts;
Peter Collingbournea77d9f72013-08-15 18:51:12 +0000233 DenseSet<Value *> NonZeroChecks;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000234
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000235 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
236 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()),
Stephen Hinesdce4a402014-05-29 02:49:00 -0700237 IsNativeABI(IsNativeABI), ArgTLSPtr(nullptr), RetvalTLSPtr(nullptr),
238 LabelReturnAlloca(nullptr) {}
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000239 Value *getArgTLSPtr();
240 Value *getArgTLS(unsigned Index, Instruction *Pos);
241 Value *getRetvalTLS();
242 Value *getShadow(Value *V);
243 void setShadow(Instruction *I, Value *Shadow);
244 Value *combineOperandShadows(Instruction *Inst);
245 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
246 Instruction *Pos);
247 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
248 Instruction *Pos);
249};
250
251class DFSanVisitor : public InstVisitor<DFSanVisitor> {
Dmitry Vyukova036a312013-08-13 16:52:41 +0000252 public:
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000253 DFSanFunction &DFSF;
254 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
255
256 void visitOperandShadowInst(Instruction &I);
257
258 void visitBinaryOperator(BinaryOperator &BO);
259 void visitCastInst(CastInst &CI);
260 void visitCmpInst(CmpInst &CI);
261 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
262 void visitLoadInst(LoadInst &LI);
263 void visitStoreInst(StoreInst &SI);
264 void visitReturnInst(ReturnInst &RI);
265 void visitCallSite(CallSite CS);
266 void visitPHINode(PHINode &PN);
267 void visitExtractElementInst(ExtractElementInst &I);
268 void visitInsertElementInst(InsertElementInst &I);
269 void visitShuffleVectorInst(ShuffleVectorInst &I);
270 void visitExtractValueInst(ExtractValueInst &I);
271 void visitInsertValueInst(InsertValueInst &I);
272 void visitAllocaInst(AllocaInst &I);
273 void visitSelectInst(SelectInst &I);
Peter Collingbourneef8136d2013-08-14 20:51:38 +0000274 void visitMemSetInst(MemSetInst &I);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000275 void visitMemTransferInst(MemTransferInst &I);
276};
277
278}
279
280char DataFlowSanitizer::ID;
281INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
282 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
283
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000284ModulePass *llvm::createDataFlowSanitizerPass(StringRef ABIListFile,
285 void *(*getArgTLS)(),
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000286 void *(*getRetValTLS)()) {
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000287 return new DataFlowSanitizer(ABIListFile, getArgTLS, getRetValTLS);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000288}
289
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000290DataFlowSanitizer::DataFlowSanitizer(StringRef ABIListFile,
291 void *(*getArgTLS)(),
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000292 void *(*getRetValTLS)())
293 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS),
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000294 ABIList(SpecialCaseList::createOrDie(ABIListFile.empty() ? ClABIListFile
295 : ABIListFile)) {
296}
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000297
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000298FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000299 llvm::SmallVector<Type *, 4> ArgTypes;
300 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
301 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
302 ArgTypes.push_back(ShadowTy);
303 if (T->isVarArg())
304 ArgTypes.push_back(ShadowPtrTy);
305 Type *RetType = T->getReturnType();
306 if (!RetType->isVoidTy())
Stephen Hinesdce4a402014-05-29 02:49:00 -0700307 RetType = StructType::get(RetType, ShadowTy, (Type *)nullptr);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000308 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
309}
310
Peter Collingbourneffba4c72013-08-27 22:09:06 +0000311FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
312 assert(!T->isVarArg());
313 llvm::SmallVector<Type *, 4> ArgTypes;
314 ArgTypes.push_back(T->getPointerTo());
315 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
316 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
317 ArgTypes.push_back(ShadowTy);
318 Type *RetType = T->getReturnType();
319 if (!RetType->isVoidTy())
320 ArgTypes.push_back(ShadowPtrTy);
321 return FunctionType::get(T->getReturnType(), ArgTypes, false);
322}
323
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000324FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
325 assert(!T->isVarArg());
326 llvm::SmallVector<Type *, 4> ArgTypes;
Alexey Samsonovf1db2a62013-08-28 11:25:12 +0000327 for (FunctionType::param_iterator i = T->param_begin(), e = T->param_end();
328 i != e; ++i) {
Peter Collingbourneffba4c72013-08-27 22:09:06 +0000329 FunctionType *FT;
Alexey Samsonovf1db2a62013-08-28 11:25:12 +0000330 if (isa<PointerType>(*i) && (FT = dyn_cast<FunctionType>(cast<PointerType>(
331 *i)->getElementType()))) {
Peter Collingbourneffba4c72013-08-27 22:09:06 +0000332 ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
333 ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
334 } else {
335 ArgTypes.push_back(*i);
336 }
337 }
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000338 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
339 ArgTypes.push_back(ShadowTy);
340 Type *RetType = T->getReturnType();
341 if (!RetType->isVoidTy())
342 ArgTypes.push_back(ShadowPtrTy);
343 return FunctionType::get(T->getReturnType(), ArgTypes, false);
344}
345
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000346bool DataFlowSanitizer::doInitialization(Module &M) {
Stephen Hines36b56882014-04-23 16:57:46 -0700347 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
348 if (!DLP)
Stephen Hinesdce4a402014-05-29 02:49:00 -0700349 report_fatal_error("data layout missing");
Stephen Hines36b56882014-04-23 16:57:46 -0700350 DL = &DLP->getDataLayout();
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000351
352 Mod = &M;
353 Ctx = &M.getContext();
354 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
355 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
356 IntptrTy = DL->getIntPtrType(*Ctx);
357 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
Peter Collingbourne46c72c72013-08-08 00:15:27 +0000358 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000359 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
360
361 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
362 DFSanUnionFnTy =
363 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
364 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
365 DFSanUnionLoadFnTy =
366 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000367 DFSanUnimplementedFnTy = FunctionType::get(
368 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
Peter Collingbourneef8136d2013-08-14 20:51:38 +0000369 Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
370 DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
371 DFSanSetLabelArgs, /*isVarArg=*/false);
Peter Collingbournea77d9f72013-08-15 18:51:12 +0000372 DFSanNonzeroLabelFnTy = FunctionType::get(
373 Type::getVoidTy(*Ctx), ArrayRef<Type *>(), /*isVarArg=*/false);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000374
375 if (GetArgTLSPtr) {
376 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700377 ArgTLS = nullptr;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000378 GetArgTLS = ConstantExpr::getIntToPtr(
379 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
380 PointerType::getUnqual(
Stephen Hinesdce4a402014-05-29 02:49:00 -0700381 FunctionType::get(PointerType::getUnqual(ArgTLSTy),
382 (Type *)nullptr)));
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000383 }
384 if (GetRetvalTLSPtr) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700385 RetvalTLS = nullptr;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000386 GetRetvalTLS = ConstantExpr::getIntToPtr(
387 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
388 PointerType::getUnqual(
Stephen Hinesdce4a402014-05-29 02:49:00 -0700389 FunctionType::get(PointerType::getUnqual(ShadowTy),
390 (Type *)nullptr)));
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000391 }
392
393 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
394 return true;
395}
396
Peter Collingbournef1366c52013-08-22 20:08:08 +0000397bool DataFlowSanitizer::isInstrumented(const Function *F) {
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000398 return !ABIList->isIn(*F, "uninstrumented");
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000399}
400
Peter Collingbournef1366c52013-08-22 20:08:08 +0000401bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
402 return !ABIList->isIn(*GA, "uninstrumented");
403}
404
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000405DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000406 return ClArgsABI ? IA_Args : IA_TLS;
407}
408
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000409DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
410 if (ABIList->isIn(*F, "functional"))
411 return WK_Functional;
412 if (ABIList->isIn(*F, "discard"))
413 return WK_Discard;
414 if (ABIList->isIn(*F, "custom"))
415 return WK_Custom;
416
417 return WK_Warning;
418}
419
Peter Collingbournef1366c52013-08-22 20:08:08 +0000420void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
421 std::string GVName = GV->getName(), Prefix = "dfs$";
422 GV->setName(Prefix + GVName);
423
424 // Try to change the name of the function in module inline asm. We only do
425 // this for specific asm directives, currently only ".symver", to try to avoid
426 // corrupting asm which happens to contain the symbol name as a substring.
427 // Note that the substitution for .symver assumes that the versioned symbol
428 // also has an instrumented name.
429 std::string Asm = GV->getParent()->getModuleInlineAsm();
430 std::string SearchStr = ".symver " + GVName + ",";
431 size_t Pos = Asm.find(SearchStr);
432 if (Pos != std::string::npos) {
433 Asm.replace(Pos, SearchStr.size(),
434 ".symver " + Prefix + GVName + "," + Prefix);
435 GV->getParent()->setModuleInlineAsm(Asm);
436 }
437}
438
Peter Collingbourne4f68e9e2013-08-22 20:08:11 +0000439Function *
440DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
441 GlobalValue::LinkageTypes NewFLink,
442 FunctionType *NewFT) {
443 FunctionType *FT = F->getFunctionType();
444 Function *NewF = Function::Create(NewFT, NewFLink, NewFName,
445 F->getParent());
446 NewF->copyAttributesFrom(F);
447 NewF->removeAttributes(
448 AttributeSet::ReturnIndex,
449 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
450 AttributeSet::ReturnIndex));
451
452 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
453 std::vector<Value *> Args;
454 unsigned n = FT->getNumParams();
455 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
456 Args.push_back(&*ai);
457 CallInst *CI = CallInst::Create(F, Args, "", BB);
458 if (FT->getReturnType()->isVoidTy())
459 ReturnInst::Create(*Ctx, BB);
460 else
461 ReturnInst::Create(*Ctx, CI, BB);
462
463 return NewF;
464}
465
Peter Collingbourneffba4c72013-08-27 22:09:06 +0000466Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
467 StringRef FName) {
468 FunctionType *FTT = getTrampolineFunctionType(FT);
469 Constant *C = Mod->getOrInsertFunction(FName, FTT);
470 Function *F = dyn_cast<Function>(C);
471 if (F && F->isDeclaration()) {
472 F->setLinkage(GlobalValue::LinkOnceODRLinkage);
473 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
474 std::vector<Value *> Args;
475 Function::arg_iterator AI = F->arg_begin(); ++AI;
476 for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
477 Args.push_back(&*AI);
478 CallInst *CI =
479 CallInst::Create(&F->getArgumentList().front(), Args, "", BB);
480 ReturnInst *RI;
481 if (FT->getReturnType()->isVoidTy())
482 RI = ReturnInst::Create(*Ctx, BB);
483 else
484 RI = ReturnInst::Create(*Ctx, CI, BB);
485
486 DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
487 Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
488 for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
489 DFSF.ValShadowMap[ValAI] = ShadowAI;
490 DFSanVisitor(DFSF).visitCallInst(*CI);
491 if (!FT->getReturnType()->isVoidTy())
492 new StoreInst(DFSF.getShadow(RI->getReturnValue()),
493 &F->getArgumentList().back(), RI);
494 }
495
496 return C;
497}
498
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000499bool DataFlowSanitizer::runOnModule(Module &M) {
500 if (!DL)
501 return false;
502
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000503 if (ABIList->isIn(M, "skip"))
504 return false;
505
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000506 if (!GetArgTLSPtr) {
507 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
508 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
509 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
510 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
511 }
512 if (!GetRetvalTLSPtr) {
513 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
514 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
515 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
516 }
517
518 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
519 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
520 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
521 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
522 F->addAttribute(1, Attribute::ZExt);
523 F->addAttribute(2, Attribute::ZExt);
524 }
525 DFSanUnionLoadFn =
526 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
527 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
Stephen Hines36b56882014-04-23 16:57:46 -0700528 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000529 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
530 }
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000531 DFSanUnimplementedFn =
532 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
Peter Collingbourneef8136d2013-08-14 20:51:38 +0000533 DFSanSetLabelFn =
534 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
535 if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
536 F->addAttribute(1, Attribute::ZExt);
537 }
Peter Collingbournea77d9f72013-08-15 18:51:12 +0000538 DFSanNonzeroLabelFn =
539 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000540
541 std::vector<Function *> FnsToInstrument;
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000542 llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000543 for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000544 if (!i->isIntrinsic() &&
545 i != DFSanUnionFn &&
546 i != DFSanUnionLoadFn &&
Peter Collingbourneef8136d2013-08-14 20:51:38 +0000547 i != DFSanUnimplementedFn &&
Peter Collingbournea77d9f72013-08-15 18:51:12 +0000548 i != DFSanSetLabelFn &&
549 i != DFSanNonzeroLabelFn)
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000550 FnsToInstrument.push_back(&*i);
551 }
552
Peter Collingbourne054cec02013-08-22 20:08:15 +0000553 // Give function aliases prefixes when necessary, and build wrappers where the
554 // instrumentedness is inconsistent.
Peter Collingbournef1366c52013-08-22 20:08:08 +0000555 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
556 GlobalAlias *GA = &*i;
557 ++i;
558 // Don't stop on weak. We assume people aren't playing games with the
559 // instrumentedness of overridden weak aliases.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700560 if (Function *F = dyn_cast<Function>(GA->getAliasee())) {
Peter Collingbournef1366c52013-08-22 20:08:08 +0000561 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
562 if (GAInst && FInst) {
563 addGlobalNamePrefix(GA);
Peter Collingbourne054cec02013-08-22 20:08:15 +0000564 } else if (GAInst != FInst) {
565 // Non-instrumented alias of an instrumented function, or vice versa.
566 // Replace the alias with a native-ABI wrapper of the aliasee. The pass
567 // below will take care of instrumenting it.
568 Function *NewF =
569 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
570 GA->replaceAllUsesWith(NewF);
571 NewF->takeName(GA);
572 GA->eraseFromParent();
573 FnsToInstrument.push_back(NewF);
Peter Collingbournef1366c52013-08-22 20:08:08 +0000574 }
575 }
576 }
577
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000578 AttrBuilder B;
579 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
580 ReadOnlyNoneAttrs = AttributeSet::get(*Ctx, AttributeSet::FunctionIndex, B);
581
582 // First, change the ABI of every function in the module. ABI-listed
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000583 // functions keep their original ABI and get a wrapper function.
584 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
585 e = FnsToInstrument.end();
586 i != e; ++i) {
587 Function &F = **i;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000588 FunctionType *FT = F.getFunctionType();
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000589
Peter Collingbournef1366c52013-08-22 20:08:08 +0000590 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
591 FT->getReturnType()->isVoidTy());
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000592
593 if (isInstrumented(&F)) {
Peter Collingbournef1366c52013-08-22 20:08:08 +0000594 // Instrumented functions get a 'dfs$' prefix. This allows us to more
595 // easily identify cases of mismatching ABIs.
596 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000597 FunctionType *NewFT = getArgsFunctionType(FT);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000598 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000599 NewF->copyAttributesFrom(&F);
600 NewF->removeAttributes(
601 AttributeSet::ReturnIndex,
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000602 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000603 AttributeSet::ReturnIndex));
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000604 for (Function::arg_iterator FArg = F.arg_begin(),
605 NewFArg = NewF->arg_begin(),
606 FArgEnd = F.arg_end();
607 FArg != FArgEnd; ++FArg, ++NewFArg) {
608 FArg->replaceAllUsesWith(NewFArg);
609 }
610 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
611
Stephen Hines36b56882014-04-23 16:57:46 -0700612 for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
613 UI != UE;) {
614 BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
615 ++UI;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000616 if (BA) {
617 BA->replaceAllUsesWith(
618 BlockAddress::get(NewF, BA->getBasicBlock()));
619 delete BA;
620 }
621 }
622 F.replaceAllUsesWith(
623 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
624 NewF->takeName(&F);
625 F.eraseFromParent();
626 *i = NewF;
Peter Collingbournef1366c52013-08-22 20:08:08 +0000627 addGlobalNamePrefix(NewF);
628 } else {
629 addGlobalNamePrefix(&F);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000630 }
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000631 // Hopefully, nobody will try to indirectly call a vararg
632 // function... yet.
633 } else if (FT->isVarArg()) {
634 UnwrappedFnMap[&F] = &F;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700635 *i = nullptr;
Peter Collingbournef1366c52013-08-22 20:08:08 +0000636 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000637 // Build a wrapper function for F. The wrapper simply calls F, and is
638 // added to FnsToInstrument so that any instrumentation according to its
639 // WrapperKind is done in the second pass below.
640 FunctionType *NewFT = getInstrumentedABI() == IA_Args
641 ? getArgsFunctionType(FT)
642 : FT;
Alexey Samsonovbbe88b72013-08-23 07:42:51 +0000643 Function *NewF = buildWrapperFunction(
644 &F, std::string("dfsw$") + std::string(F.getName()),
645 GlobalValue::LinkOnceODRLinkage, NewFT);
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000646 if (getInstrumentedABI() == IA_TLS)
Peter Collingbourne4f68e9e2013-08-22 20:08:11 +0000647 NewF->removeAttributes(AttributeSet::FunctionIndex, ReadOnlyNoneAttrs);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000648
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000649 Value *WrappedFnCst =
650 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
651 F.replaceAllUsesWith(WrappedFnCst);
652 UnwrappedFnMap[WrappedFnCst] = &F;
653 *i = NewF;
654
655 if (!F.isDeclaration()) {
656 // This function is probably defining an interposition of an
657 // uninstrumented function and hence needs to keep the original ABI.
658 // But any functions it may call need to use the instrumented ABI, so
659 // we instrument it in a mode which preserves the original ABI.
660 FnsWithNativeABI.insert(&F);
661
662 // This code needs to rebuild the iterators, as they may be invalidated
663 // by the push_back, taking care that the new range does not include
664 // any functions added by this code.
665 size_t N = i - FnsToInstrument.begin(),
666 Count = e - FnsToInstrument.begin();
667 FnsToInstrument.push_back(&F);
668 i = FnsToInstrument.begin() + N;
669 e = FnsToInstrument.begin() + Count;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000670 }
671 }
672 }
673
674 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
675 e = FnsToInstrument.end();
676 i != e; ++i) {
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000677 if (!*i || (*i)->isDeclaration())
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000678 continue;
679
Peter Collingbourneaaae6e92013-08-09 21:42:53 +0000680 removeUnreachableBlocks(**i);
681
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000682 DFSanFunction DFSF(*this, *i, FnsWithNativeABI.count(*i));
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000683
684 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
685 // Build a copy of the list before iterating over it.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700686 llvm::SmallVector<BasicBlock *, 4> BBList(
687 depth_first(&(*i)->getEntryBlock()));
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000688
689 for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
690 e = BBList.end();
691 i != e; ++i) {
692 Instruction *Inst = &(*i)->front();
693 while (1) {
694 // DFSanVisitor may split the current basic block, changing the current
695 // instruction's next pointer and moving the next instruction to the
696 // tail block from which we should continue.
697 Instruction *Next = Inst->getNextNode();
Peter Collingbournea90d91f2013-08-12 22:38:39 +0000698 // DFSanVisitor may delete Inst, so keep track of whether it was a
699 // terminator.
700 bool IsTerminator = isa<TerminatorInst>(Inst);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000701 if (!DFSF.SkipInsts.count(Inst))
702 DFSanVisitor(DFSF).visit(Inst);
Peter Collingbournea90d91f2013-08-12 22:38:39 +0000703 if (IsTerminator)
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000704 break;
705 Inst = Next;
706 }
707 }
708
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000709 // We will not necessarily be able to compute the shadow for every phi node
710 // until we have visited every block. Therefore, the code that handles phi
711 // nodes adds them to the PHIFixups list so that they can be properly
712 // handled here.
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000713 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
714 i = DFSF.PHIFixups.begin(),
715 e = DFSF.PHIFixups.end();
716 i != e; ++i) {
717 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
718 ++val) {
719 i->second->setIncomingValue(
720 val, DFSF.getShadow(i->first->getIncomingValue(val)));
721 }
722 }
Peter Collingbournea77d9f72013-08-15 18:51:12 +0000723
724 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
725 // places (i.e. instructions in basic blocks we haven't even begun visiting
726 // yet). To make our life easier, do this work in a pass after the main
727 // instrumentation.
728 if (ClDebugNonzeroLabels) {
729 for (DenseSet<Value *>::iterator i = DFSF.NonZeroChecks.begin(),
730 e = DFSF.NonZeroChecks.end();
731 i != e; ++i) {
732 Instruction *Pos;
733 if (Instruction *I = dyn_cast<Instruction>(*i))
734 Pos = I->getNextNode();
735 else
736 Pos = DFSF.F->getEntryBlock().begin();
737 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
738 Pos = Pos->getNextNode();
739 IRBuilder<> IRB(Pos);
Stephen Hines36b56882014-04-23 16:57:46 -0700740 Value *Ne = IRB.CreateICmpNE(*i, DFSF.DFS.ZeroShadow);
Peter Collingbournea77d9f72013-08-15 18:51:12 +0000741 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
Stephen Hines36b56882014-04-23 16:57:46 -0700742 Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
Peter Collingbournea77d9f72013-08-15 18:51:12 +0000743 IRBuilder<> ThenIRB(BI);
744 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn);
745 }
746 }
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000747 }
748
749 return false;
750}
751
752Value *DFSanFunction::getArgTLSPtr() {
753 if (ArgTLSPtr)
754 return ArgTLSPtr;
755 if (DFS.ArgTLS)
756 return ArgTLSPtr = DFS.ArgTLS;
757
758 IRBuilder<> IRB(F->getEntryBlock().begin());
759 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
760}
761
762Value *DFSanFunction::getRetvalTLS() {
763 if (RetvalTLSPtr)
764 return RetvalTLSPtr;
765 if (DFS.RetvalTLS)
766 return RetvalTLSPtr = DFS.RetvalTLS;
767
768 IRBuilder<> IRB(F->getEntryBlock().begin());
769 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
770}
771
772Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
773 IRBuilder<> IRB(Pos);
774 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
775}
776
777Value *DFSanFunction::getShadow(Value *V) {
778 if (!isa<Argument>(V) && !isa<Instruction>(V))
779 return DFS.ZeroShadow;
780 Value *&Shadow = ValShadowMap[V];
781 if (!Shadow) {
782 if (Argument *A = dyn_cast<Argument>(V)) {
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000783 if (IsNativeABI)
784 return DFS.ZeroShadow;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000785 switch (IA) {
786 case DataFlowSanitizer::IA_TLS: {
787 Value *ArgTLSPtr = getArgTLSPtr();
788 Instruction *ArgTLSPos =
789 DFS.ArgTLS ? &*F->getEntryBlock().begin()
790 : cast<Instruction>(ArgTLSPtr)->getNextNode();
791 IRBuilder<> IRB(ArgTLSPos);
792 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
793 break;
794 }
795 case DataFlowSanitizer::IA_Args: {
796 unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
797 Function::arg_iterator i = F->arg_begin();
798 while (ArgIdx--)
799 ++i;
800 Shadow = i;
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +0000801 assert(Shadow->getType() == DFS.ShadowTy);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000802 break;
803 }
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000804 }
Peter Collingbournea77d9f72013-08-15 18:51:12 +0000805 NonZeroChecks.insert(Shadow);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000806 } else {
807 Shadow = DFS.ZeroShadow;
808 }
809 }
810 return Shadow;
811}
812
813void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
814 assert(!ValShadowMap.count(I));
815 assert(Shadow->getType() == DFS.ShadowTy);
816 ValShadowMap[I] = Shadow;
817}
818
819Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
820 assert(Addr != RetvalTLS && "Reinstrumenting?");
821 IRBuilder<> IRB(Pos);
822 return IRB.CreateIntToPtr(
823 IRB.CreateMul(
824 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
825 ShadowPtrMul),
826 ShadowPtrTy);
827}
828
829// Generates IR to compute the union of the two given shadows, inserting it
830// before Pos. Returns the computed union Value.
831Value *DataFlowSanitizer::combineShadows(Value *V1, Value *V2,
832 Instruction *Pos) {
833 if (V1 == ZeroShadow)
834 return V2;
835 if (V2 == ZeroShadow)
836 return V1;
837 if (V1 == V2)
838 return V1;
839 IRBuilder<> IRB(Pos);
840 BasicBlock *Head = Pos->getParent();
841 Value *Ne = IRB.CreateICmpNE(V1, V2);
Stephen Hines36b56882014-04-23 16:57:46 -0700842 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
843 Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
844 IRBuilder<> ThenIRB(BI);
845 CallInst *Call = ThenIRB.CreateCall2(DFSanUnionFn, V1, V2);
846 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
847 Call->addAttribute(1, Attribute::ZExt);
848 Call->addAttribute(2, Attribute::ZExt);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000849
Stephen Hines36b56882014-04-23 16:57:46 -0700850 BasicBlock *Tail = BI->getSuccessor(0);
851 PHINode *Phi = PHINode::Create(ShadowTy, 2, "", Tail->begin());
852 Phi->addIncoming(Call, Call->getParent());
853 Phi->addIncoming(V1, Head);
854 return Phi;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +0000855}
856
857// A convenience function which folds the shadows of each of the operands
858// of the provided instruction Inst, inserting the IR before Inst. Returns
859// the computed union Value.
860Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
861 if (Inst->getNumOperands() == 0)
862 return DFS.ZeroShadow;
863
864 Value *Shadow = getShadow(Inst->getOperand(0));
865 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
866 Shadow = DFS.combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
867 }
868 return Shadow;
869}
870
871void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
872 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
873 DFSF.setShadow(&I, CombinedShadow);
874}
875
876// Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
877// Addr has alignment Align, and take the union of each of those shadows.
878Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
879 Instruction *Pos) {
880 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
881 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
882 AllocaShadowMap.find(AI);
883 if (i != AllocaShadowMap.end()) {
884 IRBuilder<> IRB(Pos);
885 return IRB.CreateLoad(i->second);
886 }
887 }
888
889 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
890 SmallVector<Value *, 2> Objs;
891 GetUnderlyingObjects(Addr, Objs, DFS.DL);
892 bool AllConstants = true;
893 for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
894 i != e; ++i) {
895 if (isa<Function>(*i) || isa<BlockAddress>(*i))
896 continue;
897 if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
898 continue;
899
900 AllConstants = false;
901 break;
902 }
903 if (AllConstants)
904 return DFS.ZeroShadow;
905
906 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
907 switch (Size) {
908 case 0:
909 return DFS.ZeroShadow;
910 case 1: {
911 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
912 LI->setAlignment(ShadowAlign);
913 return LI;
914 }
915 case 2: {
916 IRBuilder<> IRB(Pos);
917 Value *ShadowAddr1 =
918 IRB.CreateGEP(ShadowAddr, ConstantInt::get(DFS.IntptrTy, 1));
919 return DFS.combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
920 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign),
921 Pos);
922 }
923 }
924 if (Size % (64 / DFS.ShadowWidth) == 0) {
925 // Fast path for the common case where each byte has identical shadow: load
926 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
927 // shadow is non-equal.
928 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
929 IRBuilder<> FallbackIRB(FallbackBB);
930 CallInst *FallbackCall = FallbackIRB.CreateCall2(
931 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
932 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
933
934 // Compare each of the shadows stored in the loaded 64 bits to each other,
935 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
936 IRBuilder<> IRB(Pos);
937 Value *WideAddr =
938 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
939 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
940 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
941 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
942 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
943 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
944 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
945
946 BasicBlock *Head = Pos->getParent();
947 BasicBlock *Tail = Head->splitBasicBlock(Pos);
948 // In the following code LastBr will refer to the previous basic block's
949 // conditional branch instruction, whose true successor is fixed up to point
950 // to the next block during the loop below or to the tail after the final
951 // iteration.
952 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
953 ReplaceInstWithInst(Head->getTerminator(), LastBr);
954
955 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
956 Ofs += 64 / DFS.ShadowWidth) {
957 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
958 IRBuilder<> NextIRB(NextBB);
959 WideAddr = NextIRB.CreateGEP(WideAddr, ConstantInt::get(DFS.IntptrTy, 1));
960 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
961 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
962 LastBr->setSuccessor(0, NextBB);
963 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
964 }
965
966 LastBr->setSuccessor(0, Tail);
967 FallbackIRB.CreateBr(Tail);
968 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
969 Shadow->addIncoming(FallbackCall, FallbackBB);
970 Shadow->addIncoming(TruncShadow, LastBr->getParent());
971 return Shadow;
972 }
973
974 IRBuilder<> IRB(Pos);
975 CallInst *FallbackCall = IRB.CreateCall2(
976 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
977 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
978 return FallbackCall;
979}
980
981void DFSanVisitor::visitLoadInst(LoadInst &LI) {
982 uint64_t Size = DFSF.DFS.DL->getTypeStoreSize(LI.getType());
983 uint64_t Align;
984 if (ClPreserveAlignment) {
985 Align = LI.getAlignment();
986 if (Align == 0)
987 Align = DFSF.DFS.DL->getABITypeAlignment(LI.getType());
988 } else {
989 Align = 1;
990 }
991 IRBuilder<> IRB(&LI);
Stephen Hines36b56882014-04-23 16:57:46 -0700992 Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
993 if (ClCombinePointerLabelsOnLoad) {
994 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
995 Shadow = DFSF.DFS.combineShadows(Shadow, PtrShadow, &LI);
996 }
997 if (Shadow != DFSF.DFS.ZeroShadow)
998 DFSF.NonZeroChecks.insert(Shadow);
Peter Collingbournea77d9f72013-08-15 18:51:12 +0000999
Stephen Hines36b56882014-04-23 16:57:46 -07001000 DFSF.setShadow(&LI, Shadow);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001001}
1002
1003void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
1004 Value *Shadow, Instruction *Pos) {
1005 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1006 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1007 AllocaShadowMap.find(AI);
1008 if (i != AllocaShadowMap.end()) {
1009 IRBuilder<> IRB(Pos);
1010 IRB.CreateStore(Shadow, i->second);
1011 return;
1012 }
1013 }
1014
1015 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1016 IRBuilder<> IRB(Pos);
1017 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1018 if (Shadow == DFS.ZeroShadow) {
1019 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1020 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1021 Value *ExtShadowAddr =
1022 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1023 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1024 return;
1025 }
1026
1027 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1028 uint64_t Offset = 0;
1029 if (Size >= ShadowVecSize) {
1030 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1031 Value *ShadowVec = UndefValue::get(ShadowVecTy);
1032 for (unsigned i = 0; i != ShadowVecSize; ++i) {
1033 ShadowVec = IRB.CreateInsertElement(
1034 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1035 }
1036 Value *ShadowVecAddr =
1037 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1038 do {
1039 Value *CurShadowVecAddr = IRB.CreateConstGEP1_32(ShadowVecAddr, Offset);
1040 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1041 Size -= ShadowVecSize;
1042 ++Offset;
1043 } while (Size >= ShadowVecSize);
1044 Offset *= ShadowVecSize;
1045 }
1046 while (Size > 0) {
1047 Value *CurShadowAddr = IRB.CreateConstGEP1_32(ShadowAddr, Offset);
1048 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1049 --Size;
1050 ++Offset;
1051 }
1052}
1053
1054void DFSanVisitor::visitStoreInst(StoreInst &SI) {
1055 uint64_t Size =
1056 DFSF.DFS.DL->getTypeStoreSize(SI.getValueOperand()->getType());
1057 uint64_t Align;
1058 if (ClPreserveAlignment) {
1059 Align = SI.getAlignment();
1060 if (Align == 0)
1061 Align = DFSF.DFS.DL->getABITypeAlignment(SI.getValueOperand()->getType());
1062 } else {
1063 Align = 1;
1064 }
Stephen Hines36b56882014-04-23 16:57:46 -07001065
1066 Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1067 if (ClCombinePointerLabelsOnStore) {
1068 Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
1069 Shadow = DFSF.DFS.combineShadows(Shadow, PtrShadow, &SI);
1070 }
1071 DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001072}
1073
1074void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1075 visitOperandShadowInst(BO);
1076}
1077
1078void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1079
1080void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1081
1082void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1083 visitOperandShadowInst(GEPI);
1084}
1085
1086void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1087 visitOperandShadowInst(I);
1088}
1089
1090void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1091 visitOperandShadowInst(I);
1092}
1093
1094void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1095 visitOperandShadowInst(I);
1096}
1097
1098void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1099 visitOperandShadowInst(I);
1100}
1101
1102void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1103 visitOperandShadowInst(I);
1104}
1105
1106void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1107 bool AllLoadsStores = true;
Stephen Hines36b56882014-04-23 16:57:46 -07001108 for (User *U : I.users()) {
1109 if (isa<LoadInst>(U))
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001110 continue;
1111
Stephen Hines36b56882014-04-23 16:57:46 -07001112 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001113 if (SI->getPointerOperand() == &I)
1114 continue;
1115 }
1116
1117 AllLoadsStores = false;
1118 break;
1119 }
1120 if (AllLoadsStores) {
1121 IRBuilder<> IRB(&I);
1122 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1123 }
1124 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1125}
1126
1127void DFSanVisitor::visitSelectInst(SelectInst &I) {
1128 Value *CondShadow = DFSF.getShadow(I.getCondition());
1129 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1130 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1131
1132 if (isa<VectorType>(I.getCondition()->getType())) {
1133 DFSF.setShadow(
1134 &I, DFSF.DFS.combineShadows(
1135 CondShadow,
1136 DFSF.DFS.combineShadows(TrueShadow, FalseShadow, &I), &I));
1137 } else {
1138 Value *ShadowSel;
1139 if (TrueShadow == FalseShadow) {
1140 ShadowSel = TrueShadow;
1141 } else {
1142 ShadowSel =
1143 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1144 }
1145 DFSF.setShadow(&I, DFSF.DFS.combineShadows(CondShadow, ShadowSel, &I));
1146 }
1147}
1148
Peter Collingbourneef8136d2013-08-14 20:51:38 +00001149void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1150 IRBuilder<> IRB(&I);
1151 Value *ValShadow = DFSF.getShadow(I.getValue());
1152 IRB.CreateCall3(
1153 DFSF.DFS.DFSanSetLabelFn, ValShadow,
1154 IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
1155 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy));
1156}
1157
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001158void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1159 IRBuilder<> IRB(&I);
1160 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1161 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1162 Value *LenShadow = IRB.CreateMul(
1163 I.getLength(),
1164 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
1165 Value *AlignShadow;
1166 if (ClPreserveAlignment) {
1167 AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1168 ConstantInt::get(I.getAlignmentCst()->getType(),
1169 DFSF.DFS.ShadowWidth / 8));
1170 } else {
1171 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1172 DFSF.DFS.ShadowWidth / 8);
1173 }
1174 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1175 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1176 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
1177 IRB.CreateCall5(I.getCalledValue(), DestShadow, SrcShadow, LenShadow,
1178 AlignShadow, I.getVolatileCst());
1179}
1180
1181void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +00001182 if (!DFSF.IsNativeABI && RI.getReturnValue()) {
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001183 switch (DFSF.IA) {
1184 case DataFlowSanitizer::IA_TLS: {
1185 Value *S = DFSF.getShadow(RI.getReturnValue());
1186 IRBuilder<> IRB(&RI);
1187 IRB.CreateStore(S, DFSF.getRetvalTLS());
1188 break;
1189 }
1190 case DataFlowSanitizer::IA_Args: {
1191 IRBuilder<> IRB(&RI);
1192 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1193 Value *InsVal =
1194 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1195 Value *InsShadow =
1196 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1197 RI.setOperand(0, InsShadow);
1198 break;
1199 }
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001200 }
1201 }
1202}
1203
1204void DFSanVisitor::visitCallSite(CallSite CS) {
1205 Function *F = CS.getCalledFunction();
1206 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1207 visitOperandShadowInst(*CS.getInstruction());
1208 return;
1209 }
1210
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +00001211 IRBuilder<> IRB(CS.getInstruction());
1212
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001213 DenseMap<Value *, Function *>::iterator i =
1214 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1215 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +00001216 Function *F = i->second;
1217 switch (DFSF.DFS.getWrapperKind(F)) {
1218 case DataFlowSanitizer::WK_Warning: {
1219 CS.setCalledFunction(F);
1220 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1221 IRB.CreateGlobalStringPtr(F->getName()));
1222 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1223 return;
1224 }
1225 case DataFlowSanitizer::WK_Discard: {
1226 CS.setCalledFunction(F);
1227 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1228 return;
1229 }
1230 case DataFlowSanitizer::WK_Functional: {
1231 CS.setCalledFunction(F);
1232 visitOperandShadowInst(*CS.getInstruction());
1233 return;
1234 }
1235 case DataFlowSanitizer::WK_Custom: {
1236 // Don't try to handle invokes of custom functions, it's too complicated.
1237 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1238 // wrapper.
1239 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1240 FunctionType *FT = F->getFunctionType();
1241 FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1242 std::string CustomFName = "__dfsw_";
1243 CustomFName += F->getName();
1244 Constant *CustomF =
1245 DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1246 if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1247 CustomFn->copyAttributesFrom(F);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001248
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +00001249 // Custom functions returning non-void will write to the return label.
1250 if (!FT->getReturnType()->isVoidTy()) {
1251 CustomFn->removeAttributes(AttributeSet::FunctionIndex,
1252 DFSF.DFS.ReadOnlyNoneAttrs);
1253 }
1254 }
1255
1256 std::vector<Value *> Args;
1257
1258 CallSite::arg_iterator i = CS.arg_begin();
Peter Collingbourneffba4c72013-08-27 22:09:06 +00001259 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
1260 Type *T = (*i)->getType();
1261 FunctionType *ParamFT;
1262 if (isa<PointerType>(T) &&
1263 (ParamFT = dyn_cast<FunctionType>(
1264 cast<PointerType>(T)->getElementType()))) {
1265 std::string TName = "dfst";
1266 TName += utostr(FT->getNumParams() - n);
1267 TName += "$";
1268 TName += F->getName();
1269 Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1270 Args.push_back(T);
1271 Args.push_back(
1272 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1273 } else {
1274 Args.push_back(*i);
1275 }
1276 }
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +00001277
1278 i = CS.arg_begin();
1279 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1280 Args.push_back(DFSF.getShadow(*i));
1281
1282 if (!FT->getReturnType()->isVoidTy()) {
1283 if (!DFSF.LabelReturnAlloca) {
1284 DFSF.LabelReturnAlloca =
1285 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
1286 DFSF.F->getEntryBlock().begin());
1287 }
1288 Args.push_back(DFSF.LabelReturnAlloca);
1289 }
1290
1291 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1292 CustomCI->setCallingConv(CI->getCallingConv());
1293 CustomCI->setAttributes(CI->getAttributes());
1294
1295 if (!FT->getReturnType()->isVoidTy()) {
1296 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1297 DFSF.setShadow(CustomCI, LabelLoad);
1298 }
1299
1300 CI->replaceAllUsesWith(CustomCI);
1301 CI->eraseFromParent();
1302 return;
1303 }
1304 break;
1305 }
1306 }
1307 }
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001308
1309 FunctionType *FT = cast<FunctionType>(
1310 CS.getCalledValue()->getType()->getPointerElementType());
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +00001311 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001312 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1313 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1314 DFSF.getArgTLS(i, CS.getInstruction()));
1315 }
1316 }
1317
Stephen Hinesdce4a402014-05-29 02:49:00 -07001318 Instruction *Next = nullptr;
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001319 if (!CS.getType()->isVoidTy()) {
1320 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1321 if (II->getNormalDest()->getSinglePredecessor()) {
1322 Next = II->getNormalDest()->begin();
1323 } else {
1324 BasicBlock *NewBB =
1325 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DFS);
1326 Next = NewBB->begin();
1327 }
1328 } else {
1329 Next = CS->getNextNode();
1330 }
1331
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +00001332 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001333 IRBuilder<> NextIRB(Next);
1334 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1335 DFSF.SkipInsts.insert(LI);
1336 DFSF.setShadow(CS.getInstruction(), LI);
Peter Collingbournea77d9f72013-08-15 18:51:12 +00001337 DFSF.NonZeroChecks.insert(LI);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001338 }
1339 }
1340
1341 // Do all instrumentation for IA_Args down here to defer tampering with the
1342 // CFG in a way that SplitEdge may be able to detect.
Peter Collingbournefdb1a6c2013-08-14 18:54:12 +00001343 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1344 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001345 Value *Func =
1346 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1347 std::vector<Value *> Args;
1348
1349 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1350 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1351 Args.push_back(*i);
1352
1353 i = CS.arg_begin();
1354 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1355 Args.push_back(DFSF.getShadow(*i));
1356
1357 if (FT->isVarArg()) {
1358 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1359 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1360 AllocaInst *VarArgShadow =
1361 new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
1362 Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
1363 for (unsigned n = 0; i != e; ++i, ++n) {
1364 IRB.CreateStore(DFSF.getShadow(*i),
1365 IRB.CreateConstGEP2_32(VarArgShadow, 0, n));
1366 Args.push_back(*i);
1367 }
1368 }
1369
1370 CallSite NewCS;
1371 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1372 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1373 Args);
1374 } else {
1375 NewCS = IRB.CreateCall(Func, Args);
1376 }
1377 NewCS.setCallingConv(CS.getCallingConv());
1378 NewCS.setAttributes(CS.getAttributes().removeAttributes(
1379 *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
1380 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType(),
1381 AttributeSet::ReturnIndex)));
1382
1383 if (Next) {
1384 ExtractValueInst *ExVal =
1385 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1386 DFSF.SkipInsts.insert(ExVal);
1387 ExtractValueInst *ExShadow =
1388 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1389 DFSF.SkipInsts.insert(ExShadow);
1390 DFSF.setShadow(ExVal, ExShadow);
Peter Collingbournea77d9f72013-08-15 18:51:12 +00001391 DFSF.NonZeroChecks.insert(ExShadow);
Peter Collingbourne6fa33f52013-08-07 22:47:18 +00001392
1393 CS.getInstruction()->replaceAllUsesWith(ExVal);
1394 }
1395
1396 CS.getInstruction()->eraseFromParent();
1397 }
1398}
1399
1400void DFSanVisitor::visitPHINode(PHINode &PN) {
1401 PHINode *ShadowPN =
1402 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1403
1404 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1405 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1406 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1407 ++i) {
1408 ShadowPN->addIncoming(UndefShadow, *i);
1409 }
1410
1411 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1412 DFSF.setShadow(&PN, ShadowPN);
1413}