blob: 8344e087a9593ad4ee922d190981b935d08b6616 [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 Collingbourne0826e602014-12-05 21:22:32 +000052#include "llvm/ADT/Triple.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000053#include "llvm/Analysis/ValueTracking.h"
Peter Collingbourne705a1ae2014-07-15 04:41:17 +000054#include "llvm/IR/Dominators.h"
David Blaikiec6c6c7b2014-10-07 22:59:46 +000055#include "llvm/IR/DebugInfo.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000056#include "llvm/IR/IRBuilder.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000057#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000058#include "llvm/IR/InstVisitor.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000059#include "llvm/IR/LLVMContext.h"
60#include "llvm/IR/MDBuilder.h"
61#include "llvm/IR/Type.h"
62#include "llvm/IR/Value.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000063#include "llvm/Pass.h"
64#include "llvm/Support/CommandLine.h"
Alexey Samsonovb7dd3292014-07-09 19:40:08 +000065#include "llvm/Support/SpecialCaseList.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000066#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Peter Collingbourneae66d572013-08-09 21:42:53 +000067#include "llvm/Transforms/Utils/Local.h"
Peter Collingbourne9947c492014-07-15 22:13:19 +000068#include <algorithm>
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000069#include <iterator>
Peter Collingbourne9947c492014-07-15 22:13:19 +000070#include <set>
71#include <utility>
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000072
73using namespace llvm;
74
75// The -dfsan-preserve-alignment flag controls whether this pass assumes that
76// alignment requirements provided by the input IR are correct. For example,
77// if the input IR contains a load with alignment 8, this flag will cause
78// the shadow load to have alignment 16. This flag is disabled by default as
79// we have unfortunately encountered too much code (including Clang itself;
80// see PR14291) which performs misaligned access.
81static cl::opt<bool> ClPreserveAlignment(
82 "dfsan-preserve-alignment",
83 cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
84 cl::init(false));
85
Alexey Samsonovb9b80272015-02-04 17:39:48 +000086// The ABI list files control how shadow parameters are passed. The pass treats
Peter Collingbourne68162e72013-08-14 18:54:12 +000087// every function labelled "uninstrumented" in the ABI list file as conforming
88// to the "native" (i.e. unsanitized) ABI. Unless the ABI list contains
89// additional annotations for those functions, a call to one of those functions
90// will produce a warning message, as the labelling behaviour of the function is
91// unknown. The other supported annotations are "functional" and "discard",
92// which are described below under DataFlowSanitizer::WrapperKind.
Alexey Samsonovb9b80272015-02-04 17:39:48 +000093static cl::list<std::string> ClABIListFiles(
Peter Collingbourne68162e72013-08-14 18:54:12 +000094 "dfsan-abilist",
95 cl::desc("File listing native ABI functions and how the pass treats them"),
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000096 cl::Hidden);
97
Peter Collingbourne68162e72013-08-14 18:54:12 +000098// Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
99// functions (see DataFlowSanitizer::InstrumentedABI below).
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000100static cl::opt<bool> ClArgsABI(
101 "dfsan-args-abi",
102 cl::desc("Use the argument ABI rather than the TLS ABI"),
103 cl::Hidden);
104
Peter Collingbourne0be79e12013-11-21 23:20:54 +0000105// Controls whether the pass includes or ignores the labels of pointers in load
106// instructions.
107static cl::opt<bool> ClCombinePointerLabelsOnLoad(
108 "dfsan-combine-pointer-labels-on-load",
109 cl::desc("Combine the label of the pointer with the label of the data when "
110 "loading from memory."),
111 cl::Hidden, cl::init(true));
112
113// Controls whether the pass includes or ignores the labels of pointers in
114// stores instructions.
115static cl::opt<bool> ClCombinePointerLabelsOnStore(
116 "dfsan-combine-pointer-labels-on-store",
117 cl::desc("Combine the label of the pointer with the label of the data when "
118 "storing in memory."),
119 cl::Hidden, cl::init(false));
120
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000121static cl::opt<bool> ClDebugNonzeroLabels(
122 "dfsan-debug-nonzero-labels",
123 cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
124 "load or return with a nonzero label"),
125 cl::Hidden);
126
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000127namespace {
128
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000129StringRef GetGlobalTypeString(const GlobalValue &G) {
130 // Types of GlobalVariables are always pointer types.
131 Type *GType = G.getType()->getElementType();
132 // For now we support blacklisting struct types only.
133 if (StructType *SGType = dyn_cast<StructType>(GType)) {
134 if (!SGType->isLiteral())
135 return SGType->getName();
136 }
137 return "<unknown type>";
138}
139
140class DFSanABIList {
141 std::unique_ptr<SpecialCaseList> SCL;
142
143 public:
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000144 DFSanABIList() {}
145
146 void set(std::unique_ptr<SpecialCaseList> List) { SCL = std::move(List); }
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000147
148 /// Returns whether either this function or its source file are listed in the
149 /// given category.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000150 bool isIn(const Function &F, StringRef Category) const {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000151 return isIn(*F.getParent(), Category) ||
152 SCL->inSection("fun", F.getName(), Category);
153 }
154
155 /// Returns whether this global alias is listed in the given category.
156 ///
157 /// If GA aliases a function, the alias's name is matched as a function name
158 /// would be. Similarly, aliases of globals are matched like globals.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000159 bool isIn(const GlobalAlias &GA, StringRef Category) const {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000160 if (isIn(*GA.getParent(), Category))
161 return true;
162
163 if (isa<FunctionType>(GA.getType()->getElementType()))
164 return SCL->inSection("fun", GA.getName(), Category);
165
166 return SCL->inSection("global", GA.getName(), Category) ||
167 SCL->inSection("type", GetGlobalTypeString(GA), Category);
168 }
169
170 /// Returns whether this module is listed in the given category.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000171 bool isIn(const Module &M, StringRef Category) const {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000172 return SCL->inSection("src", M.getModuleIdentifier(), Category);
173 }
174};
175
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000176class DataFlowSanitizer : public ModulePass {
177 friend struct DFSanFunction;
178 friend class DFSanVisitor;
179
180 enum {
181 ShadowWidth = 16
182 };
183
Peter Collingbourne68162e72013-08-14 18:54:12 +0000184 /// Which ABI should be used for instrumented functions?
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000185 enum InstrumentedABI {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000186 /// Argument and return value labels are passed through additional
187 /// arguments and by modifying the return type.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000188 IA_Args,
Peter Collingbourne68162e72013-08-14 18:54:12 +0000189
190 /// Argument and return value labels are passed through TLS variables
191 /// __dfsan_arg_tls and __dfsan_retval_tls.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000192 IA_TLS
193 };
194
Peter Collingbourne68162e72013-08-14 18:54:12 +0000195 /// How should calls to uninstrumented functions be handled?
196 enum WrapperKind {
197 /// This function is present in an uninstrumented form but we don't know
198 /// how it should be handled. Print a warning and call the function anyway.
199 /// Don't label the return value.
200 WK_Warning,
201
202 /// This function does not write to (user-accessible) memory, and its return
203 /// value is unlabelled.
204 WK_Discard,
205
206 /// This function does not write to (user-accessible) memory, and the label
207 /// of its return value is the union of the label of its arguments.
208 WK_Functional,
209
210 /// Instead of calling the function, a custom wrapper __dfsw_F is called,
211 /// where F is the name of the function. This function may wrap the
212 /// original function or provide its own implementation. This is similar to
213 /// the IA_Args ABI, except that IA_Args uses a struct return type to
214 /// pass the return value shadow in a register, while WK_Custom uses an
215 /// extra pointer argument to return the shadow. This allows the wrapped
216 /// form of the function type to be expressed in C.
217 WK_Custom
218 };
219
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000220 Module *Mod;
221 LLVMContext *Ctx;
222 IntegerType *ShadowTy;
223 PointerType *ShadowPtrTy;
224 IntegerType *IntptrTy;
225 ConstantInt *ZeroShadow;
226 ConstantInt *ShadowPtrMask;
227 ConstantInt *ShadowPtrMul;
228 Constant *ArgTLS;
229 Constant *RetvalTLS;
230 void *(*GetArgTLSPtr)();
231 void *(*GetRetvalTLSPtr)();
232 Constant *GetArgTLS;
233 Constant *GetRetvalTLS;
234 FunctionType *DFSanUnionFnTy;
235 FunctionType *DFSanUnionLoadFnTy;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000236 FunctionType *DFSanUnimplementedFnTy;
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000237 FunctionType *DFSanSetLabelFnTy;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000238 FunctionType *DFSanNonzeroLabelFnTy;
Peter Collingbournea1099842014-11-05 17:21:00 +0000239 FunctionType *DFSanVarargWrapperFnTy;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000240 Constant *DFSanUnionFn;
Peter Collingbournedf240b22014-08-06 00:33:40 +0000241 Constant *DFSanCheckedUnionFn;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000242 Constant *DFSanUnionLoadFn;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000243 Constant *DFSanUnimplementedFn;
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000244 Constant *DFSanSetLabelFn;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000245 Constant *DFSanNonzeroLabelFn;
Peter Collingbournea1099842014-11-05 17:21:00 +0000246 Constant *DFSanVarargWrapperFn;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000247 MDNode *ColdCallWeights;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000248 DFSanABIList ABIList;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000249 DenseMap<Value *, Function *> UnwrappedFnMap;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000250 AttributeSet ReadOnlyNoneAttrs;
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000251 DenseMap<const Function *, DISubprogram *> FunctionDIs;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000252
253 Value *getShadowAddress(Value *Addr, Instruction *Pos);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000254 bool isInstrumented(const Function *F);
255 bool isInstrumented(const GlobalAlias *GA);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000256 FunctionType *getArgsFunctionType(FunctionType *T);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000257 FunctionType *getTrampolineFunctionType(FunctionType *T);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000258 FunctionType *getCustomFunctionType(FunctionType *T);
259 InstrumentedABI getInstrumentedABI();
260 WrapperKind getWrapperKind(Function *F);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000261 void addGlobalNamePrefix(GlobalValue *GV);
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000262 Function *buildWrapperFunction(Function *F, StringRef NewFName,
263 GlobalValue::LinkageTypes NewFLink,
264 FunctionType *NewFT);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000265 Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000266
Dmitry Vyukov96a70842013-08-13 16:52:41 +0000267 public:
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000268 DataFlowSanitizer(
269 const std::vector<std::string> &ABIListFiles = std::vector<std::string>(),
270 void *(*getArgTLS)() = nullptr, void *(*getRetValTLS)() = nullptr);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000271 static char ID;
Craig Topper3e4c6972014-03-05 09:10:37 +0000272 bool doInitialization(Module &M) override;
273 bool runOnModule(Module &M) override;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000274};
275
276struct DFSanFunction {
277 DataFlowSanitizer &DFS;
278 Function *F;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000279 DominatorTree DT;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000280 DataFlowSanitizer::InstrumentedABI IA;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000281 bool IsNativeABI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000282 Value *ArgTLSPtr;
283 Value *RetvalTLSPtr;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000284 AllocaInst *LabelReturnAlloca;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000285 DenseMap<Value *, Value *> ValShadowMap;
286 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
287 std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
288 DenseSet<Instruction *> SkipInsts;
Peter Collingbournefab565a2014-08-22 01:18:18 +0000289 std::vector<Value *> NonZeroChecks;
Peter Collingbournedf240b22014-08-06 00:33:40 +0000290 bool AvoidNewBlocks;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000291
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000292 struct CachedCombinedShadow {
293 BasicBlock *Block;
294 Value *Shadow;
295 };
296 DenseMap<std::pair<Value *, Value *>, CachedCombinedShadow>
297 CachedCombinedShadows;
Peter Collingbourne9947c492014-07-15 22:13:19 +0000298 DenseMap<Value *, std::set<Value *>> ShadowElements;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000299
Peter Collingbourne68162e72013-08-14 18:54:12 +0000300 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
301 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()),
Craig Topperf40110f2014-04-25 05:29:35 +0000302 IsNativeABI(IsNativeABI), ArgTLSPtr(nullptr), RetvalTLSPtr(nullptr),
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000303 LabelReturnAlloca(nullptr) {
304 DT.recalculate(*F);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000305 // FIXME: Need to track down the register allocator issue which causes poor
306 // performance in pathological cases with large numbers of basic blocks.
307 AvoidNewBlocks = F->size() > 1000;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000308 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000309 Value *getArgTLSPtr();
310 Value *getArgTLS(unsigned Index, Instruction *Pos);
311 Value *getRetvalTLS();
312 Value *getShadow(Value *V);
313 void setShadow(Instruction *I, Value *Shadow);
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000314 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000315 Value *combineOperandShadows(Instruction *Inst);
316 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
317 Instruction *Pos);
318 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
319 Instruction *Pos);
320};
321
322class DFSanVisitor : public InstVisitor<DFSanVisitor> {
Dmitry Vyukov96a70842013-08-13 16:52:41 +0000323 public:
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000324 DFSanFunction &DFSF;
325 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
326
327 void visitOperandShadowInst(Instruction &I);
328
329 void visitBinaryOperator(BinaryOperator &BO);
330 void visitCastInst(CastInst &CI);
331 void visitCmpInst(CmpInst &CI);
332 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
333 void visitLoadInst(LoadInst &LI);
334 void visitStoreInst(StoreInst &SI);
335 void visitReturnInst(ReturnInst &RI);
336 void visitCallSite(CallSite CS);
337 void visitPHINode(PHINode &PN);
338 void visitExtractElementInst(ExtractElementInst &I);
339 void visitInsertElementInst(InsertElementInst &I);
340 void visitShuffleVectorInst(ShuffleVectorInst &I);
341 void visitExtractValueInst(ExtractValueInst &I);
342 void visitInsertValueInst(InsertValueInst &I);
343 void visitAllocaInst(AllocaInst &I);
344 void visitSelectInst(SelectInst &I);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000345 void visitMemSetInst(MemSetInst &I);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000346 void visitMemTransferInst(MemTransferInst &I);
347};
348
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000349}
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000350
351char DataFlowSanitizer::ID;
352INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
353 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
354
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000355ModulePass *
356llvm::createDataFlowSanitizerPass(const std::vector<std::string> &ABIListFiles,
357 void *(*getArgTLS)(),
358 void *(*getRetValTLS)()) {
359 return new DataFlowSanitizer(ABIListFiles, getArgTLS, getRetValTLS);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000360}
361
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000362DataFlowSanitizer::DataFlowSanitizer(
363 const std::vector<std::string> &ABIListFiles, void *(*getArgTLS)(),
364 void *(*getRetValTLS)())
365 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS) {
366 std::vector<std::string> AllABIListFiles(std::move(ABIListFiles));
367 AllABIListFiles.insert(AllABIListFiles.end(), ClABIListFiles.begin(),
368 ClABIListFiles.end());
369 ABIList.set(SpecialCaseList::createOrDie(AllABIListFiles));
Peter Collingbourne68162e72013-08-14 18:54:12 +0000370}
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000371
Peter Collingbourne68162e72013-08-14 18:54:12 +0000372FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000373 llvm::SmallVector<Type *, 4> ArgTypes(T->param_begin(), T->param_end());
374 ArgTypes.append(T->getNumParams(), ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000375 if (T->isVarArg())
376 ArgTypes.push_back(ShadowPtrTy);
377 Type *RetType = T->getReturnType();
378 if (!RetType->isVoidTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000379 RetType = StructType::get(RetType, ShadowTy, (Type *)nullptr);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000380 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
381}
382
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000383FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
384 assert(!T->isVarArg());
385 llvm::SmallVector<Type *, 4> ArgTypes;
386 ArgTypes.push_back(T->getPointerTo());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000387 ArgTypes.append(T->param_begin(), T->param_end());
388 ArgTypes.append(T->getNumParams(), ShadowTy);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000389 Type *RetType = T->getReturnType();
390 if (!RetType->isVoidTy())
391 ArgTypes.push_back(ShadowPtrTy);
392 return FunctionType::get(T->getReturnType(), ArgTypes, false);
393}
394
Peter Collingbourne68162e72013-08-14 18:54:12 +0000395FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
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);
Peter Collingbournedd3486e2014-10-30 13:22:57 +0000410 if (T->isVarArg())
411 ArgTypes.push_back(ShadowPtrTy);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000412 Type *RetType = T->getReturnType();
413 if (!RetType->isVoidTy())
414 ArgTypes.push_back(ShadowPtrTy);
Peter Collingbournedd3486e2014-10-30 13:22:57 +0000415 return FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg());
Peter Collingbourne68162e72013-08-14 18:54:12 +0000416}
417
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000418bool DataFlowSanitizer::doInitialization(Module &M) {
Peter Collingbourne0826e602014-12-05 21:22:32 +0000419 llvm::Triple TargetTriple(M.getTargetTriple());
420 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
421 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
422 TargetTriple.getArch() == llvm::Triple::mips64el;
Adhemerval Zanellabfe1eaf2015-07-30 20:49:35 +0000423 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64 ||
424 TargetTriple.getArch() == llvm::Triple::aarch64_be;
Peter Collingbourne0826e602014-12-05 21:22:32 +0000425
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000426 const DataLayout &DL = M.getDataLayout();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000427
428 Mod = &M;
429 Ctx = &M.getContext();
430 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
431 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000432 IntptrTy = DL.getIntPtrType(*Ctx);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000433 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000434 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
Peter Collingbourne0826e602014-12-05 21:22:32 +0000435 if (IsX86_64)
436 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
437 else if (IsMIPS64)
438 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0xF000000000LL);
Adhemerval Zanellabfe1eaf2015-07-30 20:49:35 +0000439 else if (IsAArch64)
440 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x7800000000LL);
Peter Collingbourne0826e602014-12-05 21:22:32 +0000441 else
442 report_fatal_error("unsupported triple");
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000443
444 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
445 DFSanUnionFnTy =
446 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
447 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
448 DFSanUnionLoadFnTy =
449 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000450 DFSanUnimplementedFnTy = FunctionType::get(
451 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000452 Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
453 DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
454 DFSanSetLabelArgs, /*isVarArg=*/false);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000455 DFSanNonzeroLabelFnTy = FunctionType::get(
Craig Toppere1d12942014-08-27 05:25:25 +0000456 Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
Peter Collingbournea1099842014-11-05 17:21:00 +0000457 DFSanVarargWrapperFnTy = FunctionType::get(
458 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000459
460 if (GetArgTLSPtr) {
461 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
Craig Topperf40110f2014-04-25 05:29:35 +0000462 ArgTLS = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000463 GetArgTLS = ConstantExpr::getIntToPtr(
464 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
465 PointerType::getUnqual(
Craig Topperf40110f2014-04-25 05:29:35 +0000466 FunctionType::get(PointerType::getUnqual(ArgTLSTy),
467 (Type *)nullptr)));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000468 }
469 if (GetRetvalTLSPtr) {
Craig Topperf40110f2014-04-25 05:29:35 +0000470 RetvalTLS = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000471 GetRetvalTLS = ConstantExpr::getIntToPtr(
472 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
473 PointerType::getUnqual(
Craig Topperf40110f2014-04-25 05:29:35 +0000474 FunctionType::get(PointerType::getUnqual(ShadowTy),
475 (Type *)nullptr)));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000476 }
477
478 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
479 return true;
480}
481
Peter Collingbourne59b12622013-08-22 20:08:08 +0000482bool DataFlowSanitizer::isInstrumented(const Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000483 return !ABIList.isIn(*F, "uninstrumented");
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000484}
485
Peter Collingbourne59b12622013-08-22 20:08:08 +0000486bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000487 return !ABIList.isIn(*GA, "uninstrumented");
Peter Collingbourne59b12622013-08-22 20:08:08 +0000488}
489
Peter Collingbourne68162e72013-08-14 18:54:12 +0000490DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000491 return ClArgsABI ? IA_Args : IA_TLS;
492}
493
Peter Collingbourne68162e72013-08-14 18:54:12 +0000494DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000495 if (ABIList.isIn(*F, "functional"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000496 return WK_Functional;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000497 if (ABIList.isIn(*F, "discard"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000498 return WK_Discard;
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +0000499 if (ABIList.isIn(*F, "custom"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000500 return WK_Custom;
501
502 return WK_Warning;
503}
504
Peter Collingbourne59b12622013-08-22 20:08:08 +0000505void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
506 std::string GVName = GV->getName(), Prefix = "dfs$";
507 GV->setName(Prefix + GVName);
508
509 // Try to change the name of the function in module inline asm. We only do
510 // this for specific asm directives, currently only ".symver", to try to avoid
511 // corrupting asm which happens to contain the symbol name as a substring.
512 // Note that the substitution for .symver assumes that the versioned symbol
513 // also has an instrumented name.
514 std::string Asm = GV->getParent()->getModuleInlineAsm();
515 std::string SearchStr = ".symver " + GVName + ",";
516 size_t Pos = Asm.find(SearchStr);
517 if (Pos != std::string::npos) {
518 Asm.replace(Pos, SearchStr.size(),
519 ".symver " + Prefix + GVName + "," + Prefix);
520 GV->getParent()->setModuleInlineAsm(Asm);
521 }
522}
523
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000524Function *
525DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
526 GlobalValue::LinkageTypes NewFLink,
527 FunctionType *NewFT) {
528 FunctionType *FT = F->getFunctionType();
529 Function *NewF = Function::Create(NewFT, NewFLink, NewFName,
530 F->getParent());
531 NewF->copyAttributesFrom(F);
532 NewF->removeAttributes(
Pete Cooper2777d8872015-05-06 23:19:56 +0000533 AttributeSet::ReturnIndex,
534 AttributeSet::get(F->getContext(), AttributeSet::ReturnIndex,
535 AttributeFuncs::typeIncompatible(NewFT->getReturnType())));
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000536
537 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
Peter Collingbournea1099842014-11-05 17:21:00 +0000538 if (F->isVarArg()) {
539 NewF->removeAttributes(
540 AttributeSet::FunctionIndex,
541 AttributeSet().addAttribute(*Ctx, AttributeSet::FunctionIndex,
542 "split-stack"));
543 CallInst::Create(DFSanVarargWrapperFn,
544 IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "",
545 BB);
546 new UnreachableInst(*Ctx, BB);
547 } else {
548 std::vector<Value *> Args;
549 unsigned n = FT->getNumParams();
550 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
551 Args.push_back(&*ai);
552 CallInst *CI = CallInst::Create(F, Args, "", BB);
553 if (FT->getReturnType()->isVoidTy())
554 ReturnInst::Create(*Ctx, BB);
555 else
556 ReturnInst::Create(*Ctx, CI, BB);
557 }
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000558
559 return NewF;
560}
561
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000562Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
563 StringRef FName) {
564 FunctionType *FTT = getTrampolineFunctionType(FT);
565 Constant *C = Mod->getOrInsertFunction(FName, FTT);
566 Function *F = dyn_cast<Function>(C);
567 if (F && F->isDeclaration()) {
568 F->setLinkage(GlobalValue::LinkOnceODRLinkage);
569 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
570 std::vector<Value *> Args;
571 Function::arg_iterator AI = F->arg_begin(); ++AI;
572 for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
573 Args.push_back(&*AI);
574 CallInst *CI =
575 CallInst::Create(&F->getArgumentList().front(), Args, "", BB);
576 ReturnInst *RI;
577 if (FT->getReturnType()->isVoidTy())
578 RI = ReturnInst::Create(*Ctx, BB);
579 else
580 RI = ReturnInst::Create(*Ctx, CI, BB);
581
582 DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
583 Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
584 for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
585 DFSF.ValShadowMap[ValAI] = ShadowAI;
586 DFSanVisitor(DFSF).visitCallInst(*CI);
587 if (!FT->getReturnType()->isVoidTy())
588 new StoreInst(DFSF.getShadow(RI->getReturnValue()),
589 &F->getArgumentList().back(), RI);
590 }
591
592 return C;
593}
594
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000595bool DataFlowSanitizer::runOnModule(Module &M) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000596 if (ABIList.isIn(M, "skip"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000597 return false;
598
David Blaikiec6c6c7b2014-10-07 22:59:46 +0000599 FunctionDIs = makeSubprogramMap(M);
600
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000601 if (!GetArgTLSPtr) {
602 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
603 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
604 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
605 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
606 }
607 if (!GetRetvalTLSPtr) {
608 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
609 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
610 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
611 }
612
613 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
614 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
Peter Collingbournedf240b22014-08-06 00:33:40 +0000615 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
616 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
617 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
618 F->addAttribute(1, Attribute::ZExt);
619 F->addAttribute(2, Attribute::ZExt);
620 }
621 DFSanCheckedUnionFn = Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy);
622 if (Function *F = dyn_cast<Function>(DFSanCheckedUnionFn)) {
623 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000624 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
625 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
626 F->addAttribute(1, Attribute::ZExt);
627 F->addAttribute(2, Attribute::ZExt);
628 }
629 DFSanUnionLoadFn =
630 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
631 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
Peter Collingbournedf240b22014-08-06 00:33:40 +0000632 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
Peter Collingbourne0be79e12013-11-21 23:20:54 +0000633 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000634 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
635 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000636 DFSanUnimplementedFn =
637 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000638 DFSanSetLabelFn =
639 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
640 if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
641 F->addAttribute(1, Attribute::ZExt);
642 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000643 DFSanNonzeroLabelFn =
644 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
Peter Collingbournea1099842014-11-05 17:21:00 +0000645 DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper",
646 DFSanVarargWrapperFnTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000647
648 std::vector<Function *> FnsToInstrument;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000649 llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000650 for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000651 if (!i->isIntrinsic() &&
652 i != DFSanUnionFn &&
Peter Collingbournedf240b22014-08-06 00:33:40 +0000653 i != DFSanCheckedUnionFn &&
Peter Collingbourne68162e72013-08-14 18:54:12 +0000654 i != DFSanUnionLoadFn &&
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000655 i != DFSanUnimplementedFn &&
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000656 i != DFSanSetLabelFn &&
Peter Collingbournea1099842014-11-05 17:21:00 +0000657 i != DFSanNonzeroLabelFn &&
658 i != DFSanVarargWrapperFn)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000659 FnsToInstrument.push_back(&*i);
660 }
661
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000662 // Give function aliases prefixes when necessary, and build wrappers where the
663 // instrumentedness is inconsistent.
Peter Collingbourne59b12622013-08-22 20:08:08 +0000664 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
665 GlobalAlias *GA = &*i;
666 ++i;
667 // Don't stop on weak. We assume people aren't playing games with the
668 // instrumentedness of overridden weak aliases.
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000669 if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000670 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
671 if (GAInst && FInst) {
672 addGlobalNamePrefix(GA);
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000673 } else if (GAInst != FInst) {
674 // Non-instrumented alias of an instrumented function, or vice versa.
675 // Replace the alias with a native-ABI wrapper of the aliasee. The pass
676 // below will take care of instrumenting it.
677 Function *NewF =
678 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000679 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000680 NewF->takeName(GA);
681 GA->eraseFromParent();
682 FnsToInstrument.push_back(NewF);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000683 }
684 }
685 }
686
Peter Collingbourne68162e72013-08-14 18:54:12 +0000687 AttrBuilder B;
688 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
689 ReadOnlyNoneAttrs = AttributeSet::get(*Ctx, AttributeSet::FunctionIndex, B);
690
691 // First, change the ABI of every function in the module. ABI-listed
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000692 // functions keep their original ABI and get a wrapper function.
693 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
694 e = FnsToInstrument.end();
695 i != e; ++i) {
696 Function &F = **i;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000697 FunctionType *FT = F.getFunctionType();
Peter Collingbourne68162e72013-08-14 18:54:12 +0000698
Peter Collingbourne59b12622013-08-22 20:08:08 +0000699 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
700 FT->getReturnType()->isVoidTy());
Peter Collingbourne68162e72013-08-14 18:54:12 +0000701
702 if (isInstrumented(&F)) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000703 // Instrumented functions get a 'dfs$' prefix. This allows us to more
704 // easily identify cases of mismatching ABIs.
705 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000706 FunctionType *NewFT = getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000707 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000708 NewF->copyAttributesFrom(&F);
709 NewF->removeAttributes(
Pete Cooper2777d8872015-05-06 23:19:56 +0000710 AttributeSet::ReturnIndex,
711 AttributeSet::get(NewF->getContext(), AttributeSet::ReturnIndex,
712 AttributeFuncs::typeIncompatible(NewFT->getReturnType())));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000713 for (Function::arg_iterator FArg = F.arg_begin(),
714 NewFArg = NewF->arg_begin(),
715 FArgEnd = F.arg_end();
716 FArg != FArgEnd; ++FArg, ++NewFArg) {
717 FArg->replaceAllUsesWith(NewFArg);
718 }
719 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
720
Chandler Carruthcdf47882014-03-09 03:16:01 +0000721 for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
722 UI != UE;) {
723 BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
724 ++UI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000725 if (BA) {
726 BA->replaceAllUsesWith(
727 BlockAddress::get(NewF, BA->getBasicBlock()));
728 delete BA;
729 }
730 }
731 F.replaceAllUsesWith(
732 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
733 NewF->takeName(&F);
734 F.eraseFromParent();
735 *i = NewF;
Peter Collingbourne59b12622013-08-22 20:08:08 +0000736 addGlobalNamePrefix(NewF);
737 } else {
738 addGlobalNamePrefix(&F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000739 }
Peter Collingbourne59b12622013-08-22 20:08:08 +0000740 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000741 // Build a wrapper function for F. The wrapper simply calls F, and is
742 // added to FnsToInstrument so that any instrumentation according to its
743 // WrapperKind is done in the second pass below.
744 FunctionType *NewFT = getInstrumentedABI() == IA_Args
745 ? getArgsFunctionType(FT)
746 : FT;
Alexey Samsonov6dae24d2013-08-23 07:42:51 +0000747 Function *NewF = buildWrapperFunction(
748 &F, std::string("dfsw$") + std::string(F.getName()),
749 GlobalValue::LinkOnceODRLinkage, NewFT);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000750 if (getInstrumentedABI() == IA_TLS)
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000751 NewF->removeAttributes(AttributeSet::FunctionIndex, ReadOnlyNoneAttrs);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000752
Peter Collingbourne68162e72013-08-14 18:54:12 +0000753 Value *WrappedFnCst =
754 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
755 F.replaceAllUsesWith(WrappedFnCst);
David Blaikiec6c6c7b2014-10-07 22:59:46 +0000756
757 // Patch the pointer to LLVM function in debug info descriptor.
758 auto DI = FunctionDIs.find(&F);
759 if (DI != FunctionDIs.end())
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000760 DI->second->replaceFunction(&F);
David Blaikiec6c6c7b2014-10-07 22:59:46 +0000761
Peter Collingbourne68162e72013-08-14 18:54:12 +0000762 UnwrappedFnMap[WrappedFnCst] = &F;
763 *i = NewF;
764
765 if (!F.isDeclaration()) {
766 // This function is probably defining an interposition of an
767 // uninstrumented function and hence needs to keep the original ABI.
768 // But any functions it may call need to use the instrumented ABI, so
769 // we instrument it in a mode which preserves the original ABI.
770 FnsWithNativeABI.insert(&F);
771
772 // This code needs to rebuild the iterators, as they may be invalidated
773 // by the push_back, taking care that the new range does not include
774 // any functions added by this code.
775 size_t N = i - FnsToInstrument.begin(),
776 Count = e - FnsToInstrument.begin();
777 FnsToInstrument.push_back(&F);
778 i = FnsToInstrument.begin() + N;
779 e = FnsToInstrument.begin() + Count;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000780 }
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +0000781 // Hopefully, nobody will try to indirectly call a vararg
782 // function... yet.
783 } else if (FT->isVarArg()) {
784 UnwrappedFnMap[&F] = &F;
785 *i = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000786 }
787 }
788
789 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
790 e = FnsToInstrument.end();
791 i != e; ++i) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000792 if (!*i || (*i)->isDeclaration())
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000793 continue;
794
Peter Collingbourneae66d572013-08-09 21:42:53 +0000795 removeUnreachableBlocks(**i);
796
Peter Collingbourne68162e72013-08-14 18:54:12 +0000797 DFSanFunction DFSF(*this, *i, FnsWithNativeABI.count(*i));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000798
799 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
800 // Build a copy of the list before iterating over it.
David Blaikieceec2bd2014-04-11 01:50:01 +0000801 llvm::SmallVector<BasicBlock *, 4> BBList(
802 depth_first(&(*i)->getEntryBlock()));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000803
804 for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
805 e = BBList.end();
806 i != e; ++i) {
807 Instruction *Inst = &(*i)->front();
808 while (1) {
809 // DFSanVisitor may split the current basic block, changing the current
810 // instruction's next pointer and moving the next instruction to the
811 // tail block from which we should continue.
812 Instruction *Next = Inst->getNextNode();
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000813 // DFSanVisitor may delete Inst, so keep track of whether it was a
814 // terminator.
815 bool IsTerminator = isa<TerminatorInst>(Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000816 if (!DFSF.SkipInsts.count(Inst))
817 DFSanVisitor(DFSF).visit(Inst);
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000818 if (IsTerminator)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000819 break;
820 Inst = Next;
821 }
822 }
823
Peter Collingbourne68162e72013-08-14 18:54:12 +0000824 // We will not necessarily be able to compute the shadow for every phi node
825 // until we have visited every block. Therefore, the code that handles phi
826 // nodes adds them to the PHIFixups list so that they can be properly
827 // handled here.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000828 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
829 i = DFSF.PHIFixups.begin(),
830 e = DFSF.PHIFixups.end();
831 i != e; ++i) {
832 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
833 ++val) {
834 i->second->setIncomingValue(
835 val, DFSF.getShadow(i->first->getIncomingValue(val)));
836 }
837 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000838
839 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
840 // places (i.e. instructions in basic blocks we haven't even begun visiting
841 // yet). To make our life easier, do this work in a pass after the main
842 // instrumentation.
843 if (ClDebugNonzeroLabels) {
Peter Collingbournefab565a2014-08-22 01:18:18 +0000844 for (Value *V : DFSF.NonZeroChecks) {
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000845 Instruction *Pos;
Peter Collingbournefab565a2014-08-22 01:18:18 +0000846 if (Instruction *I = dyn_cast<Instruction>(V))
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000847 Pos = I->getNextNode();
848 else
849 Pos = DFSF.F->getEntryBlock().begin();
850 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
851 Pos = Pos->getNextNode();
852 IRBuilder<> IRB(Pos);
Peter Collingbournefab565a2014-08-22 01:18:18 +0000853 Value *Ne = IRB.CreateICmpNE(V, DFSF.DFS.ZeroShadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000854 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000855 Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000856 IRBuilder<> ThenIRB(BI);
David Blaikieff6409d2015-05-18 22:13:54 +0000857 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn, {});
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000858 }
859 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000860 }
861
862 return false;
863}
864
865Value *DFSanFunction::getArgTLSPtr() {
866 if (ArgTLSPtr)
867 return ArgTLSPtr;
868 if (DFS.ArgTLS)
869 return ArgTLSPtr = DFS.ArgTLS;
870
871 IRBuilder<> IRB(F->getEntryBlock().begin());
David Blaikieff6409d2015-05-18 22:13:54 +0000872 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS, {});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000873}
874
875Value *DFSanFunction::getRetvalTLS() {
876 if (RetvalTLSPtr)
877 return RetvalTLSPtr;
878 if (DFS.RetvalTLS)
879 return RetvalTLSPtr = DFS.RetvalTLS;
880
881 IRBuilder<> IRB(F->getEntryBlock().begin());
David Blaikieff6409d2015-05-18 22:13:54 +0000882 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS, {});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000883}
884
885Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
886 IRBuilder<> IRB(Pos);
887 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
888}
889
890Value *DFSanFunction::getShadow(Value *V) {
891 if (!isa<Argument>(V) && !isa<Instruction>(V))
892 return DFS.ZeroShadow;
893 Value *&Shadow = ValShadowMap[V];
894 if (!Shadow) {
895 if (Argument *A = dyn_cast<Argument>(V)) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000896 if (IsNativeABI)
897 return DFS.ZeroShadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000898 switch (IA) {
899 case DataFlowSanitizer::IA_TLS: {
900 Value *ArgTLSPtr = getArgTLSPtr();
901 Instruction *ArgTLSPos =
902 DFS.ArgTLS ? &*F->getEntryBlock().begin()
903 : cast<Instruction>(ArgTLSPtr)->getNextNode();
904 IRBuilder<> IRB(ArgTLSPos);
905 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
906 break;
907 }
908 case DataFlowSanitizer::IA_Args: {
909 unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
910 Function::arg_iterator i = F->arg_begin();
911 while (ArgIdx--)
912 ++i;
913 Shadow = i;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000914 assert(Shadow->getType() == DFS.ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000915 break;
916 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000917 }
Peter Collingbournefab565a2014-08-22 01:18:18 +0000918 NonZeroChecks.push_back(Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000919 } else {
920 Shadow = DFS.ZeroShadow;
921 }
922 }
923 return Shadow;
924}
925
926void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
927 assert(!ValShadowMap.count(I));
928 assert(Shadow->getType() == DFS.ShadowTy);
929 ValShadowMap[I] = Shadow;
930}
931
932Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
933 assert(Addr != RetvalTLS && "Reinstrumenting?");
934 IRBuilder<> IRB(Pos);
935 return IRB.CreateIntToPtr(
936 IRB.CreateMul(
937 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
938 ShadowPtrMul),
939 ShadowPtrTy);
940}
941
942// Generates IR to compute the union of the two given shadows, inserting it
943// before Pos. Returns the computed union Value.
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000944Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
945 if (V1 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000946 return V2;
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000947 if (V2 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000948 return V1;
949 if (V1 == V2)
950 return V1;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000951
Peter Collingbourne9947c492014-07-15 22:13:19 +0000952 auto V1Elems = ShadowElements.find(V1);
953 auto V2Elems = ShadowElements.find(V2);
954 if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
955 if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
956 V2Elems->second.begin(), V2Elems->second.end())) {
957 return V1;
958 } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
959 V1Elems->second.begin(), V1Elems->second.end())) {
960 return V2;
961 }
962 } else if (V1Elems != ShadowElements.end()) {
963 if (V1Elems->second.count(V2))
964 return V1;
965 } else if (V2Elems != ShadowElements.end()) {
966 if (V2Elems->second.count(V1))
967 return V2;
968 }
969
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000970 auto Key = std::make_pair(V1, V2);
971 if (V1 > V2)
972 std::swap(Key.first, Key.second);
973 CachedCombinedShadow &CCS = CachedCombinedShadows[Key];
974 if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
975 return CCS.Shadow;
976
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000977 IRBuilder<> IRB(Pos);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000978 if (AvoidNewBlocks) {
David Blaikieff6409d2015-05-18 22:13:54 +0000979 CallInst *Call = IRB.CreateCall(DFS.DFSanCheckedUnionFn, {V1, V2});
Peter Collingbournedf240b22014-08-06 00:33:40 +0000980 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
981 Call->addAttribute(1, Attribute::ZExt);
982 Call->addAttribute(2, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000983
Peter Collingbournedf240b22014-08-06 00:33:40 +0000984 CCS.Block = Pos->getParent();
985 CCS.Shadow = Call;
986 } else {
987 BasicBlock *Head = Pos->getParent();
988 Value *Ne = IRB.CreateICmpNE(V1, V2);
989 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
990 Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
991 IRBuilder<> ThenIRB(BI);
David Blaikieff6409d2015-05-18 22:13:54 +0000992 CallInst *Call = ThenIRB.CreateCall(DFS.DFSanUnionFn, {V1, V2});
Peter Collingbournedf240b22014-08-06 00:33:40 +0000993 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
994 Call->addAttribute(1, Attribute::ZExt);
995 Call->addAttribute(2, Attribute::ZExt);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000996
Peter Collingbournedf240b22014-08-06 00:33:40 +0000997 BasicBlock *Tail = BI->getSuccessor(0);
998 PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", Tail->begin());
999 Phi->addIncoming(Call, Call->getParent());
1000 Phi->addIncoming(V1, Head);
1001
1002 CCS.Block = Tail;
1003 CCS.Shadow = Phi;
1004 }
Peter Collingbourne9947c492014-07-15 22:13:19 +00001005
1006 std::set<Value *> UnionElems;
1007 if (V1Elems != ShadowElements.end()) {
1008 UnionElems = V1Elems->second;
1009 } else {
1010 UnionElems.insert(V1);
1011 }
1012 if (V2Elems != ShadowElements.end()) {
1013 UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
1014 } else {
1015 UnionElems.insert(V2);
1016 }
Peter Collingbournedf240b22014-08-06 00:33:40 +00001017 ShadowElements[CCS.Shadow] = std::move(UnionElems);
Peter Collingbourne9947c492014-07-15 22:13:19 +00001018
Peter Collingbournedf240b22014-08-06 00:33:40 +00001019 return CCS.Shadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001020}
1021
1022// A convenience function which folds the shadows of each of the operands
1023// of the provided instruction Inst, inserting the IR before Inst. Returns
1024// the computed union Value.
1025Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
1026 if (Inst->getNumOperands() == 0)
1027 return DFS.ZeroShadow;
1028
1029 Value *Shadow = getShadow(Inst->getOperand(0));
1030 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001031 Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001032 }
1033 return Shadow;
1034}
1035
1036void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
1037 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1038 DFSF.setShadow(&I, CombinedShadow);
1039}
1040
1041// Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
1042// Addr has alignment Align, and take the union of each of those shadows.
1043Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
1044 Instruction *Pos) {
1045 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1046 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1047 AllocaShadowMap.find(AI);
1048 if (i != AllocaShadowMap.end()) {
1049 IRBuilder<> IRB(Pos);
1050 return IRB.CreateLoad(i->second);
1051 }
1052 }
1053
1054 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1055 SmallVector<Value *, 2> Objs;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001056 GetUnderlyingObjects(Addr, Objs, Pos->getModule()->getDataLayout());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001057 bool AllConstants = true;
1058 for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
1059 i != e; ++i) {
1060 if (isa<Function>(*i) || isa<BlockAddress>(*i))
1061 continue;
1062 if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
1063 continue;
1064
1065 AllConstants = false;
1066 break;
1067 }
1068 if (AllConstants)
1069 return DFS.ZeroShadow;
1070
1071 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1072 switch (Size) {
1073 case 0:
1074 return DFS.ZeroShadow;
1075 case 1: {
1076 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
1077 LI->setAlignment(ShadowAlign);
1078 return LI;
1079 }
1080 case 2: {
1081 IRBuilder<> IRB(Pos);
David Blaikie93c54442015-04-03 19:41:44 +00001082 Value *ShadowAddr1 = IRB.CreateGEP(DFS.ShadowTy, ShadowAddr,
1083 ConstantInt::get(DFS.IntptrTy, 1));
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001084 return combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
1085 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign), Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001086 }
1087 }
Peter Collingbournedf240b22014-08-06 00:33:40 +00001088 if (!AvoidNewBlocks && Size % (64 / DFS.ShadowWidth) == 0) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001089 // Fast path for the common case where each byte has identical shadow: load
1090 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
1091 // shadow is non-equal.
1092 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
1093 IRBuilder<> FallbackIRB(FallbackBB);
David Blaikieff6409d2015-05-18 22:13:54 +00001094 CallInst *FallbackCall = FallbackIRB.CreateCall(
1095 DFS.DFSanUnionLoadFn,
1096 {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001097 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1098
1099 // Compare each of the shadows stored in the loaded 64 bits to each other,
1100 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
1101 IRBuilder<> IRB(Pos);
1102 Value *WideAddr =
1103 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1104 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1105 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
1106 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
1107 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
1108 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1109 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1110
1111 BasicBlock *Head = Pos->getParent();
1112 BasicBlock *Tail = Head->splitBasicBlock(Pos);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001113
1114 if (DomTreeNode *OldNode = DT.getNode(Head)) {
1115 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1116
1117 DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1118 for (auto Child : Children)
1119 DT.changeImmediateDominator(Child, NewNode);
1120 }
1121
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001122 // In the following code LastBr will refer to the previous basic block's
1123 // conditional branch instruction, whose true successor is fixed up to point
1124 // to the next block during the loop below or to the tail after the final
1125 // iteration.
1126 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1127 ReplaceInstWithInst(Head->getTerminator(), LastBr);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001128 DT.addNewBlock(FallbackBB, Head);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001129
1130 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
1131 Ofs += 64 / DFS.ShadowWidth) {
1132 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001133 DT.addNewBlock(NextBB, LastBr->getParent());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001134 IRBuilder<> NextIRB(NextBB);
David Blaikie93c54442015-04-03 19:41:44 +00001135 WideAddr = NextIRB.CreateGEP(Type::getInt64Ty(*DFS.Ctx), WideAddr,
1136 ConstantInt::get(DFS.IntptrTy, 1));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001137 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1138 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1139 LastBr->setSuccessor(0, NextBB);
1140 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1141 }
1142
1143 LastBr->setSuccessor(0, Tail);
1144 FallbackIRB.CreateBr(Tail);
1145 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1146 Shadow->addIncoming(FallbackCall, FallbackBB);
1147 Shadow->addIncoming(TruncShadow, LastBr->getParent());
1148 return Shadow;
1149 }
1150
1151 IRBuilder<> IRB(Pos);
David Blaikieff6409d2015-05-18 22:13:54 +00001152 CallInst *FallbackCall = IRB.CreateCall(
1153 DFS.DFSanUnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001154 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1155 return FallbackCall;
1156}
1157
1158void DFSanVisitor::visitLoadInst(LoadInst &LI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001159 auto &DL = LI.getModule()->getDataLayout();
1160 uint64_t Size = DL.getTypeStoreSize(LI.getType());
Peter Collingbourne142fdff2014-08-01 21:18:18 +00001161 if (Size == 0) {
1162 DFSF.setShadow(&LI, DFSF.DFS.ZeroShadow);
1163 return;
1164 }
1165
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001166 uint64_t Align;
1167 if (ClPreserveAlignment) {
1168 Align = LI.getAlignment();
1169 if (Align == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001170 Align = DL.getABITypeAlignment(LI.getType());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001171 } else {
1172 Align = 1;
1173 }
1174 IRBuilder<> IRB(&LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001175 Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
1176 if (ClCombinePointerLabelsOnLoad) {
1177 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001178 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001179 }
1180 if (Shadow != DFSF.DFS.ZeroShadow)
Peter Collingbournefab565a2014-08-22 01:18:18 +00001181 DFSF.NonZeroChecks.push_back(Shadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +00001182
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001183 DFSF.setShadow(&LI, Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001184}
1185
1186void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
1187 Value *Shadow, Instruction *Pos) {
1188 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1189 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1190 AllocaShadowMap.find(AI);
1191 if (i != AllocaShadowMap.end()) {
1192 IRBuilder<> IRB(Pos);
1193 IRB.CreateStore(Shadow, i->second);
1194 return;
1195 }
1196 }
1197
1198 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1199 IRBuilder<> IRB(Pos);
1200 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1201 if (Shadow == DFS.ZeroShadow) {
1202 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1203 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1204 Value *ExtShadowAddr =
1205 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1206 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1207 return;
1208 }
1209
1210 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1211 uint64_t Offset = 0;
1212 if (Size >= ShadowVecSize) {
1213 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1214 Value *ShadowVec = UndefValue::get(ShadowVecTy);
1215 for (unsigned i = 0; i != ShadowVecSize; ++i) {
1216 ShadowVec = IRB.CreateInsertElement(
1217 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1218 }
1219 Value *ShadowVecAddr =
1220 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1221 do {
David Blaikie95d3e532015-04-03 23:03:54 +00001222 Value *CurShadowVecAddr =
1223 IRB.CreateConstGEP1_32(ShadowVecTy, ShadowVecAddr, Offset);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001224 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1225 Size -= ShadowVecSize;
1226 ++Offset;
1227 } while (Size >= ShadowVecSize);
1228 Offset *= ShadowVecSize;
1229 }
1230 while (Size > 0) {
David Blaikie95d3e532015-04-03 23:03:54 +00001231 Value *CurShadowAddr =
1232 IRB.CreateConstGEP1_32(DFS.ShadowTy, ShadowAddr, Offset);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001233 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1234 --Size;
1235 ++Offset;
1236 }
1237}
1238
1239void DFSanVisitor::visitStoreInst(StoreInst &SI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001240 auto &DL = SI.getModule()->getDataLayout();
1241 uint64_t Size = DL.getTypeStoreSize(SI.getValueOperand()->getType());
Peter Collingbourne142fdff2014-08-01 21:18:18 +00001242 if (Size == 0)
1243 return;
1244
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001245 uint64_t Align;
1246 if (ClPreserveAlignment) {
1247 Align = SI.getAlignment();
1248 if (Align == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001249 Align = DL.getABITypeAlignment(SI.getValueOperand()->getType());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001250 } else {
1251 Align = 1;
1252 }
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001253
1254 Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1255 if (ClCombinePointerLabelsOnStore) {
1256 Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001257 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001258 }
1259 DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001260}
1261
1262void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1263 visitOperandShadowInst(BO);
1264}
1265
1266void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1267
1268void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1269
1270void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1271 visitOperandShadowInst(GEPI);
1272}
1273
1274void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1275 visitOperandShadowInst(I);
1276}
1277
1278void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1279 visitOperandShadowInst(I);
1280}
1281
1282void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1283 visitOperandShadowInst(I);
1284}
1285
1286void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1287 visitOperandShadowInst(I);
1288}
1289
1290void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1291 visitOperandShadowInst(I);
1292}
1293
1294void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1295 bool AllLoadsStores = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001296 for (User *U : I.users()) {
1297 if (isa<LoadInst>(U))
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001298 continue;
1299
Chandler Carruthcdf47882014-03-09 03:16:01 +00001300 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001301 if (SI->getPointerOperand() == &I)
1302 continue;
1303 }
1304
1305 AllLoadsStores = false;
1306 break;
1307 }
1308 if (AllLoadsStores) {
1309 IRBuilder<> IRB(&I);
1310 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1311 }
1312 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1313}
1314
1315void DFSanVisitor::visitSelectInst(SelectInst &I) {
1316 Value *CondShadow = DFSF.getShadow(I.getCondition());
1317 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1318 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1319
1320 if (isa<VectorType>(I.getCondition()->getType())) {
1321 DFSF.setShadow(
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001322 &I,
1323 DFSF.combineShadows(
1324 CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001325 } else {
1326 Value *ShadowSel;
1327 if (TrueShadow == FalseShadow) {
1328 ShadowSel = TrueShadow;
1329 } else {
1330 ShadowSel =
1331 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1332 }
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001333 DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001334 }
1335}
1336
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +00001337void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1338 IRBuilder<> IRB(&I);
1339 Value *ValShadow = DFSF.getShadow(I.getValue());
David Blaikieff6409d2015-05-18 22:13:54 +00001340 IRB.CreateCall(DFSF.DFS.DFSanSetLabelFn,
1341 {ValShadow, IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(
1342 *DFSF.DFS.Ctx)),
1343 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +00001344}
1345
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001346void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1347 IRBuilder<> IRB(&I);
1348 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1349 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1350 Value *LenShadow = IRB.CreateMul(
1351 I.getLength(),
1352 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
1353 Value *AlignShadow;
1354 if (ClPreserveAlignment) {
1355 AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1356 ConstantInt::get(I.getAlignmentCst()->getType(),
1357 DFSF.DFS.ShadowWidth / 8));
1358 } else {
1359 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1360 DFSF.DFS.ShadowWidth / 8);
1361 }
1362 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1363 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1364 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
David Blaikieff6409d2015-05-18 22:13:54 +00001365 IRB.CreateCall(I.getCalledValue(), {DestShadow, SrcShadow, LenShadow,
1366 AlignShadow, I.getVolatileCst()});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001367}
1368
1369void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001370 if (!DFSF.IsNativeABI && RI.getReturnValue()) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001371 switch (DFSF.IA) {
1372 case DataFlowSanitizer::IA_TLS: {
1373 Value *S = DFSF.getShadow(RI.getReturnValue());
1374 IRBuilder<> IRB(&RI);
1375 IRB.CreateStore(S, DFSF.getRetvalTLS());
1376 break;
1377 }
1378 case DataFlowSanitizer::IA_Args: {
1379 IRBuilder<> IRB(&RI);
1380 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1381 Value *InsVal =
1382 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1383 Value *InsShadow =
1384 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1385 RI.setOperand(0, InsShadow);
1386 break;
1387 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001388 }
1389 }
1390}
1391
1392void DFSanVisitor::visitCallSite(CallSite CS) {
1393 Function *F = CS.getCalledFunction();
1394 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1395 visitOperandShadowInst(*CS.getInstruction());
1396 return;
1397 }
1398
Peter Collingbournea1099842014-11-05 17:21:00 +00001399 // Calls to this function are synthesized in wrappers, and we shouldn't
1400 // instrument them.
1401 if (F == DFSF.DFS.DFSanVarargWrapperFn)
1402 return;
1403
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +00001404 assert(!(cast<FunctionType>(
1405 CS.getCalledValue()->getType()->getPointerElementType())->isVarArg() &&
1406 dyn_cast<InvokeInst>(CS.getInstruction())));
1407
Peter Collingbourne68162e72013-08-14 18:54:12 +00001408 IRBuilder<> IRB(CS.getInstruction());
1409
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001410 DenseMap<Value *, Function *>::iterator i =
1411 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1412 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001413 Function *F = i->second;
1414 switch (DFSF.DFS.getWrapperKind(F)) {
1415 case DataFlowSanitizer::WK_Warning: {
1416 CS.setCalledFunction(F);
1417 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1418 IRB.CreateGlobalStringPtr(F->getName()));
1419 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1420 return;
1421 }
1422 case DataFlowSanitizer::WK_Discard: {
1423 CS.setCalledFunction(F);
1424 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1425 return;
1426 }
1427 case DataFlowSanitizer::WK_Functional: {
1428 CS.setCalledFunction(F);
1429 visitOperandShadowInst(*CS.getInstruction());
1430 return;
1431 }
1432 case DataFlowSanitizer::WK_Custom: {
1433 // Don't try to handle invokes of custom functions, it's too complicated.
1434 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1435 // wrapper.
1436 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1437 FunctionType *FT = F->getFunctionType();
1438 FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1439 std::string CustomFName = "__dfsw_";
1440 CustomFName += F->getName();
1441 Constant *CustomF =
1442 DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1443 if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1444 CustomFn->copyAttributesFrom(F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001445
Peter Collingbourne68162e72013-08-14 18:54:12 +00001446 // Custom functions returning non-void will write to the return label.
1447 if (!FT->getReturnType()->isVoidTy()) {
1448 CustomFn->removeAttributes(AttributeSet::FunctionIndex,
1449 DFSF.DFS.ReadOnlyNoneAttrs);
1450 }
1451 }
1452
1453 std::vector<Value *> Args;
1454
1455 CallSite::arg_iterator i = CS.arg_begin();
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001456 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +00001457 Type *T = (*i)->getType();
1458 FunctionType *ParamFT;
1459 if (isa<PointerType>(T) &&
1460 (ParamFT = dyn_cast<FunctionType>(
1461 cast<PointerType>(T)->getElementType()))) {
1462 std::string TName = "dfst";
1463 TName += utostr(FT->getNumParams() - n);
1464 TName += "$";
1465 TName += F->getName();
1466 Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1467 Args.push_back(T);
1468 Args.push_back(
1469 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1470 } else {
1471 Args.push_back(*i);
1472 }
1473 }
Peter Collingbourne68162e72013-08-14 18:54:12 +00001474
1475 i = CS.arg_begin();
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001476 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
Peter Collingbourne68162e72013-08-14 18:54:12 +00001477 Args.push_back(DFSF.getShadow(*i));
1478
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001479 if (FT->isVarArg()) {
David Blaikie1b01e7e2015-04-05 22:44:57 +00001480 auto *LabelVATy = ArrayType::get(DFSF.DFS.ShadowTy,
1481 CS.arg_size() - FT->getNumParams());
David Blaikie64646022015-04-05 22:41:44 +00001482 auto *LabelVAAlloca = new AllocaInst(LabelVATy, "labelva",
1483 DFSF.F->getEntryBlock().begin());
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001484
1485 for (unsigned n = 0; i != CS.arg_end(); ++i, ++n) {
David Blaikie64646022015-04-05 22:41:44 +00001486 auto LabelVAPtr = IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, n);
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001487 IRB.CreateStore(DFSF.getShadow(*i), LabelVAPtr);
1488 }
1489
David Blaikie64646022015-04-05 22:41:44 +00001490 Args.push_back(IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, 0));
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001491 }
1492
Peter Collingbourne68162e72013-08-14 18:54:12 +00001493 if (!FT->getReturnType()->isVoidTy()) {
1494 if (!DFSF.LabelReturnAlloca) {
1495 DFSF.LabelReturnAlloca =
1496 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
1497 DFSF.F->getEntryBlock().begin());
1498 }
1499 Args.push_back(DFSF.LabelReturnAlloca);
1500 }
1501
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001502 for (i = CS.arg_begin() + FT->getNumParams(); i != CS.arg_end(); ++i)
1503 Args.push_back(*i);
1504
Peter Collingbourne68162e72013-08-14 18:54:12 +00001505 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1506 CustomCI->setCallingConv(CI->getCallingConv());
1507 CustomCI->setAttributes(CI->getAttributes());
1508
1509 if (!FT->getReturnType()->isVoidTy()) {
1510 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1511 DFSF.setShadow(CustomCI, LabelLoad);
1512 }
1513
1514 CI->replaceAllUsesWith(CustomCI);
1515 CI->eraseFromParent();
1516 return;
1517 }
1518 break;
1519 }
1520 }
1521 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001522
1523 FunctionType *FT = cast<FunctionType>(
1524 CS.getCalledValue()->getType()->getPointerElementType());
Peter Collingbourne68162e72013-08-14 18:54:12 +00001525 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001526 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1527 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1528 DFSF.getArgTLS(i, CS.getInstruction()));
1529 }
1530 }
1531
Craig Topperf40110f2014-04-25 05:29:35 +00001532 Instruction *Next = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001533 if (!CS.getType()->isVoidTy()) {
1534 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1535 if (II->getNormalDest()->getSinglePredecessor()) {
1536 Next = II->getNormalDest()->begin();
1537 } else {
1538 BasicBlock *NewBB =
Chandler Carruthd4500562015-01-19 12:36:53 +00001539 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001540 Next = NewBB->begin();
1541 }
1542 } else {
1543 Next = CS->getNextNode();
1544 }
1545
Peter Collingbourne68162e72013-08-14 18:54:12 +00001546 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001547 IRBuilder<> NextIRB(Next);
1548 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1549 DFSF.SkipInsts.insert(LI);
1550 DFSF.setShadow(CS.getInstruction(), LI);
Peter Collingbournefab565a2014-08-22 01:18:18 +00001551 DFSF.NonZeroChecks.push_back(LI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001552 }
1553 }
1554
1555 // Do all instrumentation for IA_Args down here to defer tampering with the
1556 // CFG in a way that SplitEdge may be able to detect.
Peter Collingbourne68162e72013-08-14 18:54:12 +00001557 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1558 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001559 Value *Func =
1560 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1561 std::vector<Value *> Args;
1562
1563 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1564 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1565 Args.push_back(*i);
1566
1567 i = CS.arg_begin();
1568 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1569 Args.push_back(DFSF.getShadow(*i));
1570
1571 if (FT->isVarArg()) {
1572 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1573 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1574 AllocaInst *VarArgShadow =
1575 new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
David Blaikie4e5d47f42015-04-04 21:07:10 +00001576 Args.push_back(IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, 0));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001577 for (unsigned n = 0; i != e; ++i, ++n) {
David Blaikie4e5d47f42015-04-04 21:07:10 +00001578 IRB.CreateStore(
1579 DFSF.getShadow(*i),
1580 IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, n));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001581 Args.push_back(*i);
1582 }
1583 }
1584
1585 CallSite NewCS;
1586 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1587 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1588 Args);
1589 } else {
1590 NewCS = IRB.CreateCall(Func, Args);
1591 }
1592 NewCS.setCallingConv(CS.getCallingConv());
1593 NewCS.setAttributes(CS.getAttributes().removeAttributes(
1594 *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
Pete Cooper2777d8872015-05-06 23:19:56 +00001595 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType())));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001596
1597 if (Next) {
1598 ExtractValueInst *ExVal =
1599 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1600 DFSF.SkipInsts.insert(ExVal);
1601 ExtractValueInst *ExShadow =
1602 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1603 DFSF.SkipInsts.insert(ExShadow);
1604 DFSF.setShadow(ExVal, ExShadow);
Peter Collingbournefab565a2014-08-22 01:18:18 +00001605 DFSF.NonZeroChecks.push_back(ExShadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001606
1607 CS.getInstruction()->replaceAllUsesWith(ExVal);
1608 }
1609
1610 CS.getInstruction()->eraseFromParent();
1611 }
1612}
1613
1614void DFSanVisitor::visitPHINode(PHINode &PN) {
1615 PHINode *ShadowPN =
1616 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1617
1618 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1619 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1620 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1621 ++i) {
1622 ShadowPN->addIncoming(UndefShadow, *i);
1623 }
1624
1625 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1626 DFSF.setShadow(&PN, ShadowPN);
1627}