blob: 3b204b77f0e3dff5bdad89d1352b13ba6640f1b2 [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
Adhemerval Zanella4754e2d2015-08-24 13:48:10 +000075// VMA size definition for architecture that support multiple sizes.
76// AArch64 has 3 VMA sizes: 39, 42 and 48.
77#ifndef SANITIZER_AARCH64_VMA
78# define SANITIZER_AARCH64_VMA 39
79#else
80# if SANITIZER_AARCH64_VMA != 39 && SANITIZER_AARCH64_VMA != 42
81# error "invalid SANITIZER_AARCH64_VMA size"
82# endif
83#endif
84
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000085// The -dfsan-preserve-alignment flag controls whether this pass assumes that
86// alignment requirements provided by the input IR are correct. For example,
87// if the input IR contains a load with alignment 8, this flag will cause
88// the shadow load to have alignment 16. This flag is disabled by default as
89// we have unfortunately encountered too much code (including Clang itself;
90// see PR14291) which performs misaligned access.
91static cl::opt<bool> ClPreserveAlignment(
92 "dfsan-preserve-alignment",
93 cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
94 cl::init(false));
95
Alexey Samsonovb9b80272015-02-04 17:39:48 +000096// The ABI list files control how shadow parameters are passed. The pass treats
Peter Collingbourne68162e72013-08-14 18:54:12 +000097// every function labelled "uninstrumented" in the ABI list file as conforming
98// to the "native" (i.e. unsanitized) ABI. Unless the ABI list contains
99// additional annotations for those functions, a call to one of those functions
100// will produce a warning message, as the labelling behaviour of the function is
101// unknown. The other supported annotations are "functional" and "discard",
102// which are described below under DataFlowSanitizer::WrapperKind.
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000103static cl::list<std::string> ClABIListFiles(
Peter Collingbourne68162e72013-08-14 18:54:12 +0000104 "dfsan-abilist",
105 cl::desc("File listing native ABI functions and how the pass treats them"),
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000106 cl::Hidden);
107
Peter Collingbourne68162e72013-08-14 18:54:12 +0000108// Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
109// functions (see DataFlowSanitizer::InstrumentedABI below).
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000110static cl::opt<bool> ClArgsABI(
111 "dfsan-args-abi",
112 cl::desc("Use the argument ABI rather than the TLS ABI"),
113 cl::Hidden);
114
Peter Collingbourne0be79e12013-11-21 23:20:54 +0000115// Controls whether the pass includes or ignores the labels of pointers in load
116// instructions.
117static cl::opt<bool> ClCombinePointerLabelsOnLoad(
118 "dfsan-combine-pointer-labels-on-load",
119 cl::desc("Combine the label of the pointer with the label of the data when "
120 "loading from memory."),
121 cl::Hidden, cl::init(true));
122
123// Controls whether the pass includes or ignores the labels of pointers in
124// stores instructions.
125static cl::opt<bool> ClCombinePointerLabelsOnStore(
126 "dfsan-combine-pointer-labels-on-store",
127 cl::desc("Combine the label of the pointer with the label of the data when "
128 "storing in memory."),
129 cl::Hidden, cl::init(false));
130
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000131static cl::opt<bool> ClDebugNonzeroLabels(
132 "dfsan-debug-nonzero-labels",
133 cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
134 "load or return with a nonzero label"),
135 cl::Hidden);
136
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000137namespace {
138
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000139StringRef GetGlobalTypeString(const GlobalValue &G) {
140 // Types of GlobalVariables are always pointer types.
141 Type *GType = G.getType()->getElementType();
142 // For now we support blacklisting struct types only.
143 if (StructType *SGType = dyn_cast<StructType>(GType)) {
144 if (!SGType->isLiteral())
145 return SGType->getName();
146 }
147 return "<unknown type>";
148}
149
150class DFSanABIList {
151 std::unique_ptr<SpecialCaseList> SCL;
152
153 public:
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000154 DFSanABIList() {}
155
156 void set(std::unique_ptr<SpecialCaseList> List) { SCL = std::move(List); }
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000157
158 /// Returns whether either this function or its source file are listed in the
159 /// given category.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000160 bool isIn(const Function &F, StringRef Category) const {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000161 return isIn(*F.getParent(), Category) ||
162 SCL->inSection("fun", F.getName(), Category);
163 }
164
165 /// Returns whether this global alias is listed in the given category.
166 ///
167 /// If GA aliases a function, the alias's name is matched as a function name
168 /// would be. Similarly, aliases of globals are matched like globals.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000169 bool isIn(const GlobalAlias &GA, StringRef Category) const {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000170 if (isIn(*GA.getParent(), Category))
171 return true;
172
173 if (isa<FunctionType>(GA.getType()->getElementType()))
174 return SCL->inSection("fun", GA.getName(), Category);
175
176 return SCL->inSection("global", GA.getName(), Category) ||
177 SCL->inSection("type", GetGlobalTypeString(GA), Category);
178 }
179
180 /// Returns whether this module is listed in the given category.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000181 bool isIn(const Module &M, StringRef Category) const {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000182 return SCL->inSection("src", M.getModuleIdentifier(), Category);
183 }
184};
185
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000186class DataFlowSanitizer : public ModulePass {
187 friend struct DFSanFunction;
188 friend class DFSanVisitor;
189
190 enum {
191 ShadowWidth = 16
192 };
193
Peter Collingbourne68162e72013-08-14 18:54:12 +0000194 /// Which ABI should be used for instrumented functions?
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000195 enum InstrumentedABI {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000196 /// Argument and return value labels are passed through additional
197 /// arguments and by modifying the return type.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000198 IA_Args,
Peter Collingbourne68162e72013-08-14 18:54:12 +0000199
200 /// Argument and return value labels are passed through TLS variables
201 /// __dfsan_arg_tls and __dfsan_retval_tls.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000202 IA_TLS
203 };
204
Peter Collingbourne68162e72013-08-14 18:54:12 +0000205 /// How should calls to uninstrumented functions be handled?
206 enum WrapperKind {
207 /// This function is present in an uninstrumented form but we don't know
208 /// how it should be handled. Print a warning and call the function anyway.
209 /// Don't label the return value.
210 WK_Warning,
211
212 /// This function does not write to (user-accessible) memory, and its return
213 /// value is unlabelled.
214 WK_Discard,
215
216 /// This function does not write to (user-accessible) memory, and the label
217 /// of its return value is the union of the label of its arguments.
218 WK_Functional,
219
220 /// Instead of calling the function, a custom wrapper __dfsw_F is called,
221 /// where F is the name of the function. This function may wrap the
222 /// original function or provide its own implementation. This is similar to
223 /// the IA_Args ABI, except that IA_Args uses a struct return type to
224 /// pass the return value shadow in a register, while WK_Custom uses an
225 /// extra pointer argument to return the shadow. This allows the wrapped
226 /// form of the function type to be expressed in C.
227 WK_Custom
228 };
229
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000230 Module *Mod;
231 LLVMContext *Ctx;
232 IntegerType *ShadowTy;
233 PointerType *ShadowPtrTy;
234 IntegerType *IntptrTy;
235 ConstantInt *ZeroShadow;
236 ConstantInt *ShadowPtrMask;
237 ConstantInt *ShadowPtrMul;
238 Constant *ArgTLS;
239 Constant *RetvalTLS;
240 void *(*GetArgTLSPtr)();
241 void *(*GetRetvalTLSPtr)();
242 Constant *GetArgTLS;
243 Constant *GetRetvalTLS;
244 FunctionType *DFSanUnionFnTy;
245 FunctionType *DFSanUnionLoadFnTy;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000246 FunctionType *DFSanUnimplementedFnTy;
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000247 FunctionType *DFSanSetLabelFnTy;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000248 FunctionType *DFSanNonzeroLabelFnTy;
Peter Collingbournea1099842014-11-05 17:21:00 +0000249 FunctionType *DFSanVarargWrapperFnTy;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000250 Constant *DFSanUnionFn;
Peter Collingbournedf240b22014-08-06 00:33:40 +0000251 Constant *DFSanCheckedUnionFn;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000252 Constant *DFSanUnionLoadFn;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000253 Constant *DFSanUnimplementedFn;
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000254 Constant *DFSanSetLabelFn;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000255 Constant *DFSanNonzeroLabelFn;
Peter Collingbournea1099842014-11-05 17:21:00 +0000256 Constant *DFSanVarargWrapperFn;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000257 MDNode *ColdCallWeights;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000258 DFSanABIList ABIList;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000259 DenseMap<Value *, Function *> UnwrappedFnMap;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000260 AttributeSet ReadOnlyNoneAttrs;
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000261 DenseMap<const Function *, DISubprogram *> FunctionDIs;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000262
263 Value *getShadowAddress(Value *Addr, Instruction *Pos);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000264 bool isInstrumented(const Function *F);
265 bool isInstrumented(const GlobalAlias *GA);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000266 FunctionType *getArgsFunctionType(FunctionType *T);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000267 FunctionType *getTrampolineFunctionType(FunctionType *T);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000268 FunctionType *getCustomFunctionType(FunctionType *T);
269 InstrumentedABI getInstrumentedABI();
270 WrapperKind getWrapperKind(Function *F);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000271 void addGlobalNamePrefix(GlobalValue *GV);
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000272 Function *buildWrapperFunction(Function *F, StringRef NewFName,
273 GlobalValue::LinkageTypes NewFLink,
274 FunctionType *NewFT);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000275 Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000276
Dmitry Vyukov96a70842013-08-13 16:52:41 +0000277 public:
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000278 DataFlowSanitizer(
279 const std::vector<std::string> &ABIListFiles = std::vector<std::string>(),
280 void *(*getArgTLS)() = nullptr, void *(*getRetValTLS)() = nullptr);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000281 static char ID;
Craig Topper3e4c6972014-03-05 09:10:37 +0000282 bool doInitialization(Module &M) override;
283 bool runOnModule(Module &M) override;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000284};
285
286struct DFSanFunction {
287 DataFlowSanitizer &DFS;
288 Function *F;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000289 DominatorTree DT;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000290 DataFlowSanitizer::InstrumentedABI IA;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000291 bool IsNativeABI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000292 Value *ArgTLSPtr;
293 Value *RetvalTLSPtr;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000294 AllocaInst *LabelReturnAlloca;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000295 DenseMap<Value *, Value *> ValShadowMap;
296 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
297 std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
298 DenseSet<Instruction *> SkipInsts;
Peter Collingbournefab565a2014-08-22 01:18:18 +0000299 std::vector<Value *> NonZeroChecks;
Peter Collingbournedf240b22014-08-06 00:33:40 +0000300 bool AvoidNewBlocks;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000301
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000302 struct CachedCombinedShadow {
303 BasicBlock *Block;
304 Value *Shadow;
305 };
306 DenseMap<std::pair<Value *, Value *>, CachedCombinedShadow>
307 CachedCombinedShadows;
Peter Collingbourne9947c492014-07-15 22:13:19 +0000308 DenseMap<Value *, std::set<Value *>> ShadowElements;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000309
Peter Collingbourne68162e72013-08-14 18:54:12 +0000310 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
311 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()),
Craig Topperf40110f2014-04-25 05:29:35 +0000312 IsNativeABI(IsNativeABI), ArgTLSPtr(nullptr), RetvalTLSPtr(nullptr),
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000313 LabelReturnAlloca(nullptr) {
314 DT.recalculate(*F);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000315 // FIXME: Need to track down the register allocator issue which causes poor
316 // performance in pathological cases with large numbers of basic blocks.
317 AvoidNewBlocks = F->size() > 1000;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000318 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000319 Value *getArgTLSPtr();
320 Value *getArgTLS(unsigned Index, Instruction *Pos);
321 Value *getRetvalTLS();
322 Value *getShadow(Value *V);
323 void setShadow(Instruction *I, Value *Shadow);
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000324 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000325 Value *combineOperandShadows(Instruction *Inst);
326 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
327 Instruction *Pos);
328 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
329 Instruction *Pos);
330};
331
332class DFSanVisitor : public InstVisitor<DFSanVisitor> {
Dmitry Vyukov96a70842013-08-13 16:52:41 +0000333 public:
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000334 DFSanFunction &DFSF;
335 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
336
337 void visitOperandShadowInst(Instruction &I);
338
339 void visitBinaryOperator(BinaryOperator &BO);
340 void visitCastInst(CastInst &CI);
341 void visitCmpInst(CmpInst &CI);
342 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
343 void visitLoadInst(LoadInst &LI);
344 void visitStoreInst(StoreInst &SI);
345 void visitReturnInst(ReturnInst &RI);
346 void visitCallSite(CallSite CS);
347 void visitPHINode(PHINode &PN);
348 void visitExtractElementInst(ExtractElementInst &I);
349 void visitInsertElementInst(InsertElementInst &I);
350 void visitShuffleVectorInst(ShuffleVectorInst &I);
351 void visitExtractValueInst(ExtractValueInst &I);
352 void visitInsertValueInst(InsertValueInst &I);
353 void visitAllocaInst(AllocaInst &I);
354 void visitSelectInst(SelectInst &I);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000355 void visitMemSetInst(MemSetInst &I);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000356 void visitMemTransferInst(MemTransferInst &I);
357};
358
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000359}
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000360
361char DataFlowSanitizer::ID;
362INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
363 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
364
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000365ModulePass *
366llvm::createDataFlowSanitizerPass(const std::vector<std::string> &ABIListFiles,
367 void *(*getArgTLS)(),
368 void *(*getRetValTLS)()) {
369 return new DataFlowSanitizer(ABIListFiles, getArgTLS, getRetValTLS);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000370}
371
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000372DataFlowSanitizer::DataFlowSanitizer(
373 const std::vector<std::string> &ABIListFiles, void *(*getArgTLS)(),
374 void *(*getRetValTLS)())
375 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS) {
376 std::vector<std::string> AllABIListFiles(std::move(ABIListFiles));
377 AllABIListFiles.insert(AllABIListFiles.end(), ClABIListFiles.begin(),
378 ClABIListFiles.end());
379 ABIList.set(SpecialCaseList::createOrDie(AllABIListFiles));
Peter Collingbourne68162e72013-08-14 18:54:12 +0000380}
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000381
Peter Collingbourne68162e72013-08-14 18:54:12 +0000382FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000383 llvm::SmallVector<Type *, 4> ArgTypes(T->param_begin(), T->param_end());
384 ArgTypes.append(T->getNumParams(), ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000385 if (T->isVarArg())
386 ArgTypes.push_back(ShadowPtrTy);
387 Type *RetType = T->getReturnType();
388 if (!RetType->isVoidTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000389 RetType = StructType::get(RetType, ShadowTy, (Type *)nullptr);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000390 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
391}
392
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000393FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
394 assert(!T->isVarArg());
395 llvm::SmallVector<Type *, 4> ArgTypes;
396 ArgTypes.push_back(T->getPointerTo());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000397 ArgTypes.append(T->param_begin(), T->param_end());
398 ArgTypes.append(T->getNumParams(), ShadowTy);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000399 Type *RetType = T->getReturnType();
400 if (!RetType->isVoidTy())
401 ArgTypes.push_back(ShadowPtrTy);
402 return FunctionType::get(T->getReturnType(), ArgTypes, false);
403}
404
Peter Collingbourne68162e72013-08-14 18:54:12 +0000405FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000406 llvm::SmallVector<Type *, 4> ArgTypes;
Alexey Samsonov9b7e2b52013-08-28 11:25:12 +0000407 for (FunctionType::param_iterator i = T->param_begin(), e = T->param_end();
408 i != e; ++i) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000409 FunctionType *FT;
Alexey Samsonov9b7e2b52013-08-28 11:25:12 +0000410 if (isa<PointerType>(*i) && (FT = dyn_cast<FunctionType>(cast<PointerType>(
411 *i)->getElementType()))) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000412 ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
413 ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
414 } else {
415 ArgTypes.push_back(*i);
416 }
417 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000418 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
419 ArgTypes.push_back(ShadowTy);
Peter Collingbournedd3486e2014-10-30 13:22:57 +0000420 if (T->isVarArg())
421 ArgTypes.push_back(ShadowPtrTy);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000422 Type *RetType = T->getReturnType();
423 if (!RetType->isVoidTy())
424 ArgTypes.push_back(ShadowPtrTy);
Peter Collingbournedd3486e2014-10-30 13:22:57 +0000425 return FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg());
Peter Collingbourne68162e72013-08-14 18:54:12 +0000426}
427
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000428bool DataFlowSanitizer::doInitialization(Module &M) {
Peter Collingbourne0826e602014-12-05 21:22:32 +0000429 llvm::Triple TargetTriple(M.getTargetTriple());
430 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
431 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
432 TargetTriple.getArch() == llvm::Triple::mips64el;
Adhemerval Zanellabfe1eaf2015-07-30 20:49:35 +0000433 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64 ||
434 TargetTriple.getArch() == llvm::Triple::aarch64_be;
Peter Collingbourne0826e602014-12-05 21:22:32 +0000435
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000436 const DataLayout &DL = M.getDataLayout();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000437
438 Mod = &M;
439 Ctx = &M.getContext();
440 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
441 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000442 IntptrTy = DL.getIntPtrType(*Ctx);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000443 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000444 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
Peter Collingbourne0826e602014-12-05 21:22:32 +0000445 if (IsX86_64)
446 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
447 else if (IsMIPS64)
448 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0xF000000000LL);
Adhemerval Zanellabfe1eaf2015-07-30 20:49:35 +0000449 else if (IsAArch64)
Adhemerval Zanella4754e2d2015-08-24 13:48:10 +0000450#if SANITIZER_AARCH64_VMA == 39
Adhemerval Zanellabfe1eaf2015-07-30 20:49:35 +0000451 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x7800000000LL);
Adhemerval Zanella4754e2d2015-08-24 13:48:10 +0000452#else
453 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x3c000000000LL);
454#endif
Peter Collingbourne0826e602014-12-05 21:22:32 +0000455 else
456 report_fatal_error("unsupported triple");
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000457
458 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
459 DFSanUnionFnTy =
460 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
461 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
462 DFSanUnionLoadFnTy =
463 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000464 DFSanUnimplementedFnTy = FunctionType::get(
465 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000466 Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
467 DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
468 DFSanSetLabelArgs, /*isVarArg=*/false);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000469 DFSanNonzeroLabelFnTy = FunctionType::get(
Craig Toppere1d12942014-08-27 05:25:25 +0000470 Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
Peter Collingbournea1099842014-11-05 17:21:00 +0000471 DFSanVarargWrapperFnTy = FunctionType::get(
472 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000473
474 if (GetArgTLSPtr) {
475 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
Craig Topperf40110f2014-04-25 05:29:35 +0000476 ArgTLS = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000477 GetArgTLS = ConstantExpr::getIntToPtr(
478 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
479 PointerType::getUnqual(
Craig Topperf40110f2014-04-25 05:29:35 +0000480 FunctionType::get(PointerType::getUnqual(ArgTLSTy),
481 (Type *)nullptr)));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000482 }
483 if (GetRetvalTLSPtr) {
Craig Topperf40110f2014-04-25 05:29:35 +0000484 RetvalTLS = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000485 GetRetvalTLS = ConstantExpr::getIntToPtr(
486 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
487 PointerType::getUnqual(
Craig Topperf40110f2014-04-25 05:29:35 +0000488 FunctionType::get(PointerType::getUnqual(ShadowTy),
489 (Type *)nullptr)));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000490 }
491
492 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
493 return true;
494}
495
Peter Collingbourne59b12622013-08-22 20:08:08 +0000496bool DataFlowSanitizer::isInstrumented(const Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000497 return !ABIList.isIn(*F, "uninstrumented");
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000498}
499
Peter Collingbourne59b12622013-08-22 20:08:08 +0000500bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000501 return !ABIList.isIn(*GA, "uninstrumented");
Peter Collingbourne59b12622013-08-22 20:08:08 +0000502}
503
Peter Collingbourne68162e72013-08-14 18:54:12 +0000504DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000505 return ClArgsABI ? IA_Args : IA_TLS;
506}
507
Peter Collingbourne68162e72013-08-14 18:54:12 +0000508DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000509 if (ABIList.isIn(*F, "functional"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000510 return WK_Functional;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000511 if (ABIList.isIn(*F, "discard"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000512 return WK_Discard;
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +0000513 if (ABIList.isIn(*F, "custom"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000514 return WK_Custom;
515
516 return WK_Warning;
517}
518
Peter Collingbourne59b12622013-08-22 20:08:08 +0000519void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
520 std::string GVName = GV->getName(), Prefix = "dfs$";
521 GV->setName(Prefix + GVName);
522
523 // Try to change the name of the function in module inline asm. We only do
524 // this for specific asm directives, currently only ".symver", to try to avoid
525 // corrupting asm which happens to contain the symbol name as a substring.
526 // Note that the substitution for .symver assumes that the versioned symbol
527 // also has an instrumented name.
528 std::string Asm = GV->getParent()->getModuleInlineAsm();
529 std::string SearchStr = ".symver " + GVName + ",";
530 size_t Pos = Asm.find(SearchStr);
531 if (Pos != std::string::npos) {
532 Asm.replace(Pos, SearchStr.size(),
533 ".symver " + Prefix + GVName + "," + Prefix);
534 GV->getParent()->setModuleInlineAsm(Asm);
535 }
536}
537
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000538Function *
539DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
540 GlobalValue::LinkageTypes NewFLink,
541 FunctionType *NewFT) {
542 FunctionType *FT = F->getFunctionType();
543 Function *NewF = Function::Create(NewFT, NewFLink, NewFName,
544 F->getParent());
545 NewF->copyAttributesFrom(F);
546 NewF->removeAttributes(
Pete Cooper2777d8872015-05-06 23:19:56 +0000547 AttributeSet::ReturnIndex,
548 AttributeSet::get(F->getContext(), AttributeSet::ReturnIndex,
549 AttributeFuncs::typeIncompatible(NewFT->getReturnType())));
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000550
551 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
Peter Collingbournea1099842014-11-05 17:21:00 +0000552 if (F->isVarArg()) {
553 NewF->removeAttributes(
554 AttributeSet::FunctionIndex,
555 AttributeSet().addAttribute(*Ctx, AttributeSet::FunctionIndex,
556 "split-stack"));
557 CallInst::Create(DFSanVarargWrapperFn,
558 IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "",
559 BB);
560 new UnreachableInst(*Ctx, BB);
561 } else {
562 std::vector<Value *> Args;
563 unsigned n = FT->getNumParams();
564 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
565 Args.push_back(&*ai);
566 CallInst *CI = CallInst::Create(F, Args, "", BB);
567 if (FT->getReturnType()->isVoidTy())
568 ReturnInst::Create(*Ctx, BB);
569 else
570 ReturnInst::Create(*Ctx, CI, BB);
571 }
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000572
573 return NewF;
574}
575
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000576Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
577 StringRef FName) {
578 FunctionType *FTT = getTrampolineFunctionType(FT);
579 Constant *C = Mod->getOrInsertFunction(FName, FTT);
580 Function *F = dyn_cast<Function>(C);
581 if (F && F->isDeclaration()) {
582 F->setLinkage(GlobalValue::LinkOnceODRLinkage);
583 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
584 std::vector<Value *> Args;
585 Function::arg_iterator AI = F->arg_begin(); ++AI;
586 for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
587 Args.push_back(&*AI);
588 CallInst *CI =
589 CallInst::Create(&F->getArgumentList().front(), Args, "", BB);
590 ReturnInst *RI;
591 if (FT->getReturnType()->isVoidTy())
592 RI = ReturnInst::Create(*Ctx, BB);
593 else
594 RI = ReturnInst::Create(*Ctx, CI, BB);
595
596 DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
597 Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
598 for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000599 DFSF.ValShadowMap[&*ValAI] = &*ShadowAI;
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000600 DFSanVisitor(DFSF).visitCallInst(*CI);
601 if (!FT->getReturnType()->isVoidTy())
602 new StoreInst(DFSF.getShadow(RI->getReturnValue()),
603 &F->getArgumentList().back(), RI);
604 }
605
606 return C;
607}
608
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000609bool DataFlowSanitizer::runOnModule(Module &M) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000610 if (ABIList.isIn(M, "skip"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000611 return false;
612
David Blaikiec6c6c7b2014-10-07 22:59:46 +0000613 FunctionDIs = makeSubprogramMap(M);
614
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000615 if (!GetArgTLSPtr) {
616 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
617 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
618 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
619 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
620 }
621 if (!GetRetvalTLSPtr) {
622 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
623 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
624 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
625 }
626
627 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
628 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
Peter Collingbournedf240b22014-08-06 00:33:40 +0000629 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
630 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
631 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
632 F->addAttribute(1, Attribute::ZExt);
633 F->addAttribute(2, Attribute::ZExt);
634 }
635 DFSanCheckedUnionFn = Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy);
636 if (Function *F = dyn_cast<Function>(DFSanCheckedUnionFn)) {
637 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000638 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
639 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
640 F->addAttribute(1, Attribute::ZExt);
641 F->addAttribute(2, Attribute::ZExt);
642 }
643 DFSanUnionLoadFn =
644 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
645 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
Peter Collingbournedf240b22014-08-06 00:33:40 +0000646 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
Peter Collingbourne0be79e12013-11-21 23:20:54 +0000647 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000648 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
649 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000650 DFSanUnimplementedFn =
651 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000652 DFSanSetLabelFn =
653 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
654 if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
655 F->addAttribute(1, Attribute::ZExt);
656 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000657 DFSanNonzeroLabelFn =
658 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
Peter Collingbournea1099842014-11-05 17:21:00 +0000659 DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper",
660 DFSanVarargWrapperFnTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000661
662 std::vector<Function *> FnsToInstrument;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000663 llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000664 for (Function &i : M) {
665 if (!i.isIntrinsic() &&
666 &i != DFSanUnionFn &&
667 &i != DFSanCheckedUnionFn &&
668 &i != DFSanUnionLoadFn &&
669 &i != DFSanUnimplementedFn &&
670 &i != DFSanSetLabelFn &&
671 &i != DFSanNonzeroLabelFn &&
672 &i != DFSanVarargWrapperFn)
673 FnsToInstrument.push_back(&i);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000674 }
675
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000676 // Give function aliases prefixes when necessary, and build wrappers where the
677 // instrumentedness is inconsistent.
Peter Collingbourne59b12622013-08-22 20:08:08 +0000678 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
679 GlobalAlias *GA = &*i;
680 ++i;
681 // Don't stop on weak. We assume people aren't playing games with the
682 // instrumentedness of overridden weak aliases.
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000683 if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000684 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
685 if (GAInst && FInst) {
686 addGlobalNamePrefix(GA);
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000687 } else if (GAInst != FInst) {
688 // Non-instrumented alias of an instrumented function, or vice versa.
689 // Replace the alias with a native-ABI wrapper of the aliasee. The pass
690 // below will take care of instrumenting it.
691 Function *NewF =
692 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000693 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000694 NewF->takeName(GA);
695 GA->eraseFromParent();
696 FnsToInstrument.push_back(NewF);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000697 }
698 }
699 }
700
Peter Collingbourne68162e72013-08-14 18:54:12 +0000701 AttrBuilder B;
702 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
703 ReadOnlyNoneAttrs = AttributeSet::get(*Ctx, AttributeSet::FunctionIndex, B);
704
705 // First, change the ABI of every function in the module. ABI-listed
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000706 // functions keep their original ABI and get a wrapper function.
707 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
708 e = FnsToInstrument.end();
709 i != e; ++i) {
710 Function &F = **i;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000711 FunctionType *FT = F.getFunctionType();
Peter Collingbourne68162e72013-08-14 18:54:12 +0000712
Peter Collingbourne59b12622013-08-22 20:08:08 +0000713 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
714 FT->getReturnType()->isVoidTy());
Peter Collingbourne68162e72013-08-14 18:54:12 +0000715
716 if (isInstrumented(&F)) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000717 // Instrumented functions get a 'dfs$' prefix. This allows us to more
718 // easily identify cases of mismatching ABIs.
719 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000720 FunctionType *NewFT = getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000721 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000722 NewF->copyAttributesFrom(&F);
723 NewF->removeAttributes(
Pete Cooper2777d8872015-05-06 23:19:56 +0000724 AttributeSet::ReturnIndex,
725 AttributeSet::get(NewF->getContext(), AttributeSet::ReturnIndex,
726 AttributeFuncs::typeIncompatible(NewFT->getReturnType())));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000727 for (Function::arg_iterator FArg = F.arg_begin(),
728 NewFArg = NewF->arg_begin(),
729 FArgEnd = F.arg_end();
730 FArg != FArgEnd; ++FArg, ++NewFArg) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000731 FArg->replaceAllUsesWith(&*NewFArg);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000732 }
733 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
734
Chandler Carruthcdf47882014-03-09 03:16:01 +0000735 for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
736 UI != UE;) {
737 BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
738 ++UI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000739 if (BA) {
740 BA->replaceAllUsesWith(
741 BlockAddress::get(NewF, BA->getBasicBlock()));
742 delete BA;
743 }
744 }
745 F.replaceAllUsesWith(
746 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
747 NewF->takeName(&F);
748 F.eraseFromParent();
749 *i = NewF;
Peter Collingbourne59b12622013-08-22 20:08:08 +0000750 addGlobalNamePrefix(NewF);
751 } else {
752 addGlobalNamePrefix(&F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000753 }
Peter Collingbourne59b12622013-08-22 20:08:08 +0000754 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000755 // Build a wrapper function for F. The wrapper simply calls F, and is
756 // added to FnsToInstrument so that any instrumentation according to its
757 // WrapperKind is done in the second pass below.
758 FunctionType *NewFT = getInstrumentedABI() == IA_Args
759 ? getArgsFunctionType(FT)
760 : FT;
Alexey Samsonov6dae24d2013-08-23 07:42:51 +0000761 Function *NewF = buildWrapperFunction(
762 &F, std::string("dfsw$") + std::string(F.getName()),
763 GlobalValue::LinkOnceODRLinkage, NewFT);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000764 if (getInstrumentedABI() == IA_TLS)
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000765 NewF->removeAttributes(AttributeSet::FunctionIndex, ReadOnlyNoneAttrs);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000766
Peter Collingbourne68162e72013-08-14 18:54:12 +0000767 Value *WrappedFnCst =
768 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
769 F.replaceAllUsesWith(WrappedFnCst);
David Blaikiec6c6c7b2014-10-07 22:59:46 +0000770
771 // Patch the pointer to LLVM function in debug info descriptor.
772 auto DI = FunctionDIs.find(&F);
773 if (DI != FunctionDIs.end())
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000774 DI->second->replaceFunction(&F);
David Blaikiec6c6c7b2014-10-07 22:59:46 +0000775
Peter Collingbourne68162e72013-08-14 18:54:12 +0000776 UnwrappedFnMap[WrappedFnCst] = &F;
777 *i = NewF;
778
779 if (!F.isDeclaration()) {
780 // This function is probably defining an interposition of an
781 // uninstrumented function and hence needs to keep the original ABI.
782 // But any functions it may call need to use the instrumented ABI, so
783 // we instrument it in a mode which preserves the original ABI.
784 FnsWithNativeABI.insert(&F);
785
786 // This code needs to rebuild the iterators, as they may be invalidated
787 // by the push_back, taking care that the new range does not include
788 // any functions added by this code.
789 size_t N = i - FnsToInstrument.begin(),
790 Count = e - FnsToInstrument.begin();
791 FnsToInstrument.push_back(&F);
792 i = FnsToInstrument.begin() + N;
793 e = FnsToInstrument.begin() + Count;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000794 }
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +0000795 // Hopefully, nobody will try to indirectly call a vararg
796 // function... yet.
797 } else if (FT->isVarArg()) {
798 UnwrappedFnMap[&F] = &F;
799 *i = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000800 }
801 }
802
803 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
804 e = FnsToInstrument.end();
805 i != e; ++i) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000806 if (!*i || (*i)->isDeclaration())
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000807 continue;
808
Peter Collingbourneae66d572013-08-09 21:42:53 +0000809 removeUnreachableBlocks(**i);
810
Peter Collingbourne68162e72013-08-14 18:54:12 +0000811 DFSanFunction DFSF(*this, *i, FnsWithNativeABI.count(*i));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000812
813 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
814 // Build a copy of the list before iterating over it.
David Blaikieceec2bd2014-04-11 01:50:01 +0000815 llvm::SmallVector<BasicBlock *, 4> BBList(
816 depth_first(&(*i)->getEntryBlock()));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000817
818 for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
819 e = BBList.end();
820 i != e; ++i) {
821 Instruction *Inst = &(*i)->front();
822 while (1) {
823 // DFSanVisitor may split the current basic block, changing the current
824 // instruction's next pointer and moving the next instruction to the
825 // tail block from which we should continue.
826 Instruction *Next = Inst->getNextNode();
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000827 // DFSanVisitor may delete Inst, so keep track of whether it was a
828 // terminator.
829 bool IsTerminator = isa<TerminatorInst>(Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000830 if (!DFSF.SkipInsts.count(Inst))
831 DFSanVisitor(DFSF).visit(Inst);
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000832 if (IsTerminator)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000833 break;
834 Inst = Next;
835 }
836 }
837
Peter Collingbourne68162e72013-08-14 18:54:12 +0000838 // We will not necessarily be able to compute the shadow for every phi node
839 // until we have visited every block. Therefore, the code that handles phi
840 // nodes adds them to the PHIFixups list so that they can be properly
841 // handled here.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000842 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
843 i = DFSF.PHIFixups.begin(),
844 e = DFSF.PHIFixups.end();
845 i != e; ++i) {
846 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
847 ++val) {
848 i->second->setIncomingValue(
849 val, DFSF.getShadow(i->first->getIncomingValue(val)));
850 }
851 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000852
853 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
854 // places (i.e. instructions in basic blocks we haven't even begun visiting
855 // yet). To make our life easier, do this work in a pass after the main
856 // instrumentation.
857 if (ClDebugNonzeroLabels) {
Peter Collingbournefab565a2014-08-22 01:18:18 +0000858 for (Value *V : DFSF.NonZeroChecks) {
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000859 Instruction *Pos;
Peter Collingbournefab565a2014-08-22 01:18:18 +0000860 if (Instruction *I = dyn_cast<Instruction>(V))
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000861 Pos = I->getNextNode();
862 else
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000863 Pos = &DFSF.F->getEntryBlock().front();
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000864 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
865 Pos = Pos->getNextNode();
866 IRBuilder<> IRB(Pos);
Peter Collingbournefab565a2014-08-22 01:18:18 +0000867 Value *Ne = IRB.CreateICmpNE(V, DFSF.DFS.ZeroShadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000868 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000869 Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000870 IRBuilder<> ThenIRB(BI);
David Blaikieff6409d2015-05-18 22:13:54 +0000871 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn, {});
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000872 }
873 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000874 }
875
876 return false;
877}
878
879Value *DFSanFunction::getArgTLSPtr() {
880 if (ArgTLSPtr)
881 return ArgTLSPtr;
882 if (DFS.ArgTLS)
883 return ArgTLSPtr = DFS.ArgTLS;
884
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000885 IRBuilder<> IRB(&F->getEntryBlock().front());
David Blaikieff6409d2015-05-18 22:13:54 +0000886 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS, {});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000887}
888
889Value *DFSanFunction::getRetvalTLS() {
890 if (RetvalTLSPtr)
891 return RetvalTLSPtr;
892 if (DFS.RetvalTLS)
893 return RetvalTLSPtr = DFS.RetvalTLS;
894
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000895 IRBuilder<> IRB(&F->getEntryBlock().front());
David Blaikieff6409d2015-05-18 22:13:54 +0000896 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS, {});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000897}
898
899Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
900 IRBuilder<> IRB(Pos);
901 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
902}
903
904Value *DFSanFunction::getShadow(Value *V) {
905 if (!isa<Argument>(V) && !isa<Instruction>(V))
906 return DFS.ZeroShadow;
907 Value *&Shadow = ValShadowMap[V];
908 if (!Shadow) {
909 if (Argument *A = dyn_cast<Argument>(V)) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000910 if (IsNativeABI)
911 return DFS.ZeroShadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000912 switch (IA) {
913 case DataFlowSanitizer::IA_TLS: {
914 Value *ArgTLSPtr = getArgTLSPtr();
915 Instruction *ArgTLSPos =
916 DFS.ArgTLS ? &*F->getEntryBlock().begin()
917 : cast<Instruction>(ArgTLSPtr)->getNextNode();
918 IRBuilder<> IRB(ArgTLSPos);
919 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
920 break;
921 }
922 case DataFlowSanitizer::IA_Args: {
923 unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
924 Function::arg_iterator i = F->arg_begin();
925 while (ArgIdx--)
926 ++i;
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000927 Shadow = &*i;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000928 assert(Shadow->getType() == DFS.ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000929 break;
930 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000931 }
Peter Collingbournefab565a2014-08-22 01:18:18 +0000932 NonZeroChecks.push_back(Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000933 } else {
934 Shadow = DFS.ZeroShadow;
935 }
936 }
937 return Shadow;
938}
939
940void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
941 assert(!ValShadowMap.count(I));
942 assert(Shadow->getType() == DFS.ShadowTy);
943 ValShadowMap[I] = Shadow;
944}
945
946Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
947 assert(Addr != RetvalTLS && "Reinstrumenting?");
948 IRBuilder<> IRB(Pos);
949 return IRB.CreateIntToPtr(
950 IRB.CreateMul(
951 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
952 ShadowPtrMul),
953 ShadowPtrTy);
954}
955
956// Generates IR to compute the union of the two given shadows, inserting it
957// before Pos. Returns the computed union Value.
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000958Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
959 if (V1 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000960 return V2;
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000961 if (V2 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000962 return V1;
963 if (V1 == V2)
964 return V1;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000965
Peter Collingbourne9947c492014-07-15 22:13:19 +0000966 auto V1Elems = ShadowElements.find(V1);
967 auto V2Elems = ShadowElements.find(V2);
968 if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
969 if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
970 V2Elems->second.begin(), V2Elems->second.end())) {
971 return V1;
972 } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
973 V1Elems->second.begin(), V1Elems->second.end())) {
974 return V2;
975 }
976 } else if (V1Elems != ShadowElements.end()) {
977 if (V1Elems->second.count(V2))
978 return V1;
979 } else if (V2Elems != ShadowElements.end()) {
980 if (V2Elems->second.count(V1))
981 return V2;
982 }
983
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000984 auto Key = std::make_pair(V1, V2);
985 if (V1 > V2)
986 std::swap(Key.first, Key.second);
987 CachedCombinedShadow &CCS = CachedCombinedShadows[Key];
988 if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
989 return CCS.Shadow;
990
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000991 IRBuilder<> IRB(Pos);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000992 if (AvoidNewBlocks) {
David Blaikieff6409d2015-05-18 22:13:54 +0000993 CallInst *Call = IRB.CreateCall(DFS.DFSanCheckedUnionFn, {V1, V2});
Peter Collingbournedf240b22014-08-06 00:33:40 +0000994 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
995 Call->addAttribute(1, Attribute::ZExt);
996 Call->addAttribute(2, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000997
Peter Collingbournedf240b22014-08-06 00:33:40 +0000998 CCS.Block = Pos->getParent();
999 CCS.Shadow = Call;
1000 } else {
1001 BasicBlock *Head = Pos->getParent();
1002 Value *Ne = IRB.CreateICmpNE(V1, V2);
1003 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
1004 Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
1005 IRBuilder<> ThenIRB(BI);
David Blaikieff6409d2015-05-18 22:13:54 +00001006 CallInst *Call = ThenIRB.CreateCall(DFS.DFSanUnionFn, {V1, V2});
Peter Collingbournedf240b22014-08-06 00:33:40 +00001007 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1008 Call->addAttribute(1, Attribute::ZExt);
1009 Call->addAttribute(2, Attribute::ZExt);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001010
Peter Collingbournedf240b22014-08-06 00:33:40 +00001011 BasicBlock *Tail = BI->getSuccessor(0);
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001012 PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
Peter Collingbournedf240b22014-08-06 00:33:40 +00001013 Phi->addIncoming(Call, Call->getParent());
1014 Phi->addIncoming(V1, Head);
1015
1016 CCS.Block = Tail;
1017 CCS.Shadow = Phi;
1018 }
Peter Collingbourne9947c492014-07-15 22:13:19 +00001019
1020 std::set<Value *> UnionElems;
1021 if (V1Elems != ShadowElements.end()) {
1022 UnionElems = V1Elems->second;
1023 } else {
1024 UnionElems.insert(V1);
1025 }
1026 if (V2Elems != ShadowElements.end()) {
1027 UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
1028 } else {
1029 UnionElems.insert(V2);
1030 }
Peter Collingbournedf240b22014-08-06 00:33:40 +00001031 ShadowElements[CCS.Shadow] = std::move(UnionElems);
Peter Collingbourne9947c492014-07-15 22:13:19 +00001032
Peter Collingbournedf240b22014-08-06 00:33:40 +00001033 return CCS.Shadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001034}
1035
1036// A convenience function which folds the shadows of each of the operands
1037// of the provided instruction Inst, inserting the IR before Inst. Returns
1038// the computed union Value.
1039Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
1040 if (Inst->getNumOperands() == 0)
1041 return DFS.ZeroShadow;
1042
1043 Value *Shadow = getShadow(Inst->getOperand(0));
1044 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001045 Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001046 }
1047 return Shadow;
1048}
1049
1050void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
1051 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1052 DFSF.setShadow(&I, CombinedShadow);
1053}
1054
1055// Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
1056// Addr has alignment Align, and take the union of each of those shadows.
1057Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
1058 Instruction *Pos) {
1059 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1060 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1061 AllocaShadowMap.find(AI);
1062 if (i != AllocaShadowMap.end()) {
1063 IRBuilder<> IRB(Pos);
1064 return IRB.CreateLoad(i->second);
1065 }
1066 }
1067
1068 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1069 SmallVector<Value *, 2> Objs;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001070 GetUnderlyingObjects(Addr, Objs, Pos->getModule()->getDataLayout());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001071 bool AllConstants = true;
1072 for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
1073 i != e; ++i) {
1074 if (isa<Function>(*i) || isa<BlockAddress>(*i))
1075 continue;
1076 if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
1077 continue;
1078
1079 AllConstants = false;
1080 break;
1081 }
1082 if (AllConstants)
1083 return DFS.ZeroShadow;
1084
1085 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1086 switch (Size) {
1087 case 0:
1088 return DFS.ZeroShadow;
1089 case 1: {
1090 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
1091 LI->setAlignment(ShadowAlign);
1092 return LI;
1093 }
1094 case 2: {
1095 IRBuilder<> IRB(Pos);
David Blaikie93c54442015-04-03 19:41:44 +00001096 Value *ShadowAddr1 = IRB.CreateGEP(DFS.ShadowTy, ShadowAddr,
1097 ConstantInt::get(DFS.IntptrTy, 1));
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001098 return combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
1099 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign), Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001100 }
1101 }
Peter Collingbournedf240b22014-08-06 00:33:40 +00001102 if (!AvoidNewBlocks && Size % (64 / DFS.ShadowWidth) == 0) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001103 // Fast path for the common case where each byte has identical shadow: load
1104 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
1105 // shadow is non-equal.
1106 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
1107 IRBuilder<> FallbackIRB(FallbackBB);
David Blaikieff6409d2015-05-18 22:13:54 +00001108 CallInst *FallbackCall = FallbackIRB.CreateCall(
1109 DFS.DFSanUnionLoadFn,
1110 {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001111 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1112
1113 // Compare each of the shadows stored in the loaded 64 bits to each other,
1114 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
1115 IRBuilder<> IRB(Pos);
1116 Value *WideAddr =
1117 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1118 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1119 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
1120 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
1121 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
1122 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1123 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1124
1125 BasicBlock *Head = Pos->getParent();
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001126 BasicBlock *Tail = Head->splitBasicBlock(Pos->getIterator());
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001127
1128 if (DomTreeNode *OldNode = DT.getNode(Head)) {
1129 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1130
1131 DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1132 for (auto Child : Children)
1133 DT.changeImmediateDominator(Child, NewNode);
1134 }
1135
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001136 // In the following code LastBr will refer to the previous basic block's
1137 // conditional branch instruction, whose true successor is fixed up to point
1138 // to the next block during the loop below or to the tail after the final
1139 // iteration.
1140 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1141 ReplaceInstWithInst(Head->getTerminator(), LastBr);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001142 DT.addNewBlock(FallbackBB, Head);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001143
1144 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
1145 Ofs += 64 / DFS.ShadowWidth) {
1146 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001147 DT.addNewBlock(NextBB, LastBr->getParent());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001148 IRBuilder<> NextIRB(NextBB);
David Blaikie93c54442015-04-03 19:41:44 +00001149 WideAddr = NextIRB.CreateGEP(Type::getInt64Ty(*DFS.Ctx), WideAddr,
1150 ConstantInt::get(DFS.IntptrTy, 1));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001151 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1152 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1153 LastBr->setSuccessor(0, NextBB);
1154 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1155 }
1156
1157 LastBr->setSuccessor(0, Tail);
1158 FallbackIRB.CreateBr(Tail);
1159 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1160 Shadow->addIncoming(FallbackCall, FallbackBB);
1161 Shadow->addIncoming(TruncShadow, LastBr->getParent());
1162 return Shadow;
1163 }
1164
1165 IRBuilder<> IRB(Pos);
David Blaikieff6409d2015-05-18 22:13:54 +00001166 CallInst *FallbackCall = IRB.CreateCall(
1167 DFS.DFSanUnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001168 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1169 return FallbackCall;
1170}
1171
1172void DFSanVisitor::visitLoadInst(LoadInst &LI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001173 auto &DL = LI.getModule()->getDataLayout();
1174 uint64_t Size = DL.getTypeStoreSize(LI.getType());
Peter Collingbourne142fdff2014-08-01 21:18:18 +00001175 if (Size == 0) {
1176 DFSF.setShadow(&LI, DFSF.DFS.ZeroShadow);
1177 return;
1178 }
1179
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001180 uint64_t Align;
1181 if (ClPreserveAlignment) {
1182 Align = LI.getAlignment();
1183 if (Align == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001184 Align = DL.getABITypeAlignment(LI.getType());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001185 } else {
1186 Align = 1;
1187 }
1188 IRBuilder<> IRB(&LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001189 Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
1190 if (ClCombinePointerLabelsOnLoad) {
1191 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001192 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001193 }
1194 if (Shadow != DFSF.DFS.ZeroShadow)
Peter Collingbournefab565a2014-08-22 01:18:18 +00001195 DFSF.NonZeroChecks.push_back(Shadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +00001196
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001197 DFSF.setShadow(&LI, Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001198}
1199
1200void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
1201 Value *Shadow, Instruction *Pos) {
1202 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1203 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1204 AllocaShadowMap.find(AI);
1205 if (i != AllocaShadowMap.end()) {
1206 IRBuilder<> IRB(Pos);
1207 IRB.CreateStore(Shadow, i->second);
1208 return;
1209 }
1210 }
1211
1212 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1213 IRBuilder<> IRB(Pos);
1214 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1215 if (Shadow == DFS.ZeroShadow) {
1216 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1217 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1218 Value *ExtShadowAddr =
1219 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1220 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1221 return;
1222 }
1223
1224 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1225 uint64_t Offset = 0;
1226 if (Size >= ShadowVecSize) {
1227 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1228 Value *ShadowVec = UndefValue::get(ShadowVecTy);
1229 for (unsigned i = 0; i != ShadowVecSize; ++i) {
1230 ShadowVec = IRB.CreateInsertElement(
1231 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1232 }
1233 Value *ShadowVecAddr =
1234 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1235 do {
David Blaikie95d3e532015-04-03 23:03:54 +00001236 Value *CurShadowVecAddr =
1237 IRB.CreateConstGEP1_32(ShadowVecTy, ShadowVecAddr, Offset);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001238 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1239 Size -= ShadowVecSize;
1240 ++Offset;
1241 } while (Size >= ShadowVecSize);
1242 Offset *= ShadowVecSize;
1243 }
1244 while (Size > 0) {
David Blaikie95d3e532015-04-03 23:03:54 +00001245 Value *CurShadowAddr =
1246 IRB.CreateConstGEP1_32(DFS.ShadowTy, ShadowAddr, Offset);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001247 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1248 --Size;
1249 ++Offset;
1250 }
1251}
1252
1253void DFSanVisitor::visitStoreInst(StoreInst &SI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001254 auto &DL = SI.getModule()->getDataLayout();
1255 uint64_t Size = DL.getTypeStoreSize(SI.getValueOperand()->getType());
Peter Collingbourne142fdff2014-08-01 21:18:18 +00001256 if (Size == 0)
1257 return;
1258
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001259 uint64_t Align;
1260 if (ClPreserveAlignment) {
1261 Align = SI.getAlignment();
1262 if (Align == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001263 Align = DL.getABITypeAlignment(SI.getValueOperand()->getType());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001264 } else {
1265 Align = 1;
1266 }
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001267
1268 Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1269 if (ClCombinePointerLabelsOnStore) {
1270 Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001271 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001272 }
1273 DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001274}
1275
1276void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1277 visitOperandShadowInst(BO);
1278}
1279
1280void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1281
1282void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1283
1284void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1285 visitOperandShadowInst(GEPI);
1286}
1287
1288void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1289 visitOperandShadowInst(I);
1290}
1291
1292void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1293 visitOperandShadowInst(I);
1294}
1295
1296void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1297 visitOperandShadowInst(I);
1298}
1299
1300void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1301 visitOperandShadowInst(I);
1302}
1303
1304void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1305 visitOperandShadowInst(I);
1306}
1307
1308void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1309 bool AllLoadsStores = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001310 for (User *U : I.users()) {
1311 if (isa<LoadInst>(U))
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001312 continue;
1313
Chandler Carruthcdf47882014-03-09 03:16:01 +00001314 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001315 if (SI->getPointerOperand() == &I)
1316 continue;
1317 }
1318
1319 AllLoadsStores = false;
1320 break;
1321 }
1322 if (AllLoadsStores) {
1323 IRBuilder<> IRB(&I);
1324 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1325 }
1326 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1327}
1328
1329void DFSanVisitor::visitSelectInst(SelectInst &I) {
1330 Value *CondShadow = DFSF.getShadow(I.getCondition());
1331 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1332 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1333
1334 if (isa<VectorType>(I.getCondition()->getType())) {
1335 DFSF.setShadow(
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001336 &I,
1337 DFSF.combineShadows(
1338 CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001339 } else {
1340 Value *ShadowSel;
1341 if (TrueShadow == FalseShadow) {
1342 ShadowSel = TrueShadow;
1343 } else {
1344 ShadowSel =
1345 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1346 }
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001347 DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001348 }
1349}
1350
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +00001351void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1352 IRBuilder<> IRB(&I);
1353 Value *ValShadow = DFSF.getShadow(I.getValue());
David Blaikieff6409d2015-05-18 22:13:54 +00001354 IRB.CreateCall(DFSF.DFS.DFSanSetLabelFn,
1355 {ValShadow, IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(
1356 *DFSF.DFS.Ctx)),
1357 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +00001358}
1359
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001360void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1361 IRBuilder<> IRB(&I);
1362 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1363 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1364 Value *LenShadow = IRB.CreateMul(
1365 I.getLength(),
1366 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
1367 Value *AlignShadow;
1368 if (ClPreserveAlignment) {
1369 AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1370 ConstantInt::get(I.getAlignmentCst()->getType(),
1371 DFSF.DFS.ShadowWidth / 8));
1372 } else {
1373 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1374 DFSF.DFS.ShadowWidth / 8);
1375 }
1376 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1377 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1378 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
David Blaikieff6409d2015-05-18 22:13:54 +00001379 IRB.CreateCall(I.getCalledValue(), {DestShadow, SrcShadow, LenShadow,
1380 AlignShadow, I.getVolatileCst()});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001381}
1382
1383void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001384 if (!DFSF.IsNativeABI && RI.getReturnValue()) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001385 switch (DFSF.IA) {
1386 case DataFlowSanitizer::IA_TLS: {
1387 Value *S = DFSF.getShadow(RI.getReturnValue());
1388 IRBuilder<> IRB(&RI);
1389 IRB.CreateStore(S, DFSF.getRetvalTLS());
1390 break;
1391 }
1392 case DataFlowSanitizer::IA_Args: {
1393 IRBuilder<> IRB(&RI);
1394 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1395 Value *InsVal =
1396 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1397 Value *InsShadow =
1398 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1399 RI.setOperand(0, InsShadow);
1400 break;
1401 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001402 }
1403 }
1404}
1405
1406void DFSanVisitor::visitCallSite(CallSite CS) {
1407 Function *F = CS.getCalledFunction();
1408 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1409 visitOperandShadowInst(*CS.getInstruction());
1410 return;
1411 }
1412
Peter Collingbournea1099842014-11-05 17:21:00 +00001413 // Calls to this function are synthesized in wrappers, and we shouldn't
1414 // instrument them.
1415 if (F == DFSF.DFS.DFSanVarargWrapperFn)
1416 return;
1417
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +00001418 assert(!(cast<FunctionType>(
1419 CS.getCalledValue()->getType()->getPointerElementType())->isVarArg() &&
1420 dyn_cast<InvokeInst>(CS.getInstruction())));
1421
Peter Collingbourne68162e72013-08-14 18:54:12 +00001422 IRBuilder<> IRB(CS.getInstruction());
1423
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001424 DenseMap<Value *, Function *>::iterator i =
1425 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1426 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001427 Function *F = i->second;
1428 switch (DFSF.DFS.getWrapperKind(F)) {
1429 case DataFlowSanitizer::WK_Warning: {
1430 CS.setCalledFunction(F);
1431 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1432 IRB.CreateGlobalStringPtr(F->getName()));
1433 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1434 return;
1435 }
1436 case DataFlowSanitizer::WK_Discard: {
1437 CS.setCalledFunction(F);
1438 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1439 return;
1440 }
1441 case DataFlowSanitizer::WK_Functional: {
1442 CS.setCalledFunction(F);
1443 visitOperandShadowInst(*CS.getInstruction());
1444 return;
1445 }
1446 case DataFlowSanitizer::WK_Custom: {
1447 // Don't try to handle invokes of custom functions, it's too complicated.
1448 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1449 // wrapper.
1450 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1451 FunctionType *FT = F->getFunctionType();
1452 FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1453 std::string CustomFName = "__dfsw_";
1454 CustomFName += F->getName();
1455 Constant *CustomF =
1456 DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1457 if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1458 CustomFn->copyAttributesFrom(F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001459
Peter Collingbourne68162e72013-08-14 18:54:12 +00001460 // Custom functions returning non-void will write to the return label.
1461 if (!FT->getReturnType()->isVoidTy()) {
1462 CustomFn->removeAttributes(AttributeSet::FunctionIndex,
1463 DFSF.DFS.ReadOnlyNoneAttrs);
1464 }
1465 }
1466
1467 std::vector<Value *> Args;
1468
1469 CallSite::arg_iterator i = CS.arg_begin();
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001470 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +00001471 Type *T = (*i)->getType();
1472 FunctionType *ParamFT;
1473 if (isa<PointerType>(T) &&
1474 (ParamFT = dyn_cast<FunctionType>(
1475 cast<PointerType>(T)->getElementType()))) {
1476 std::string TName = "dfst";
1477 TName += utostr(FT->getNumParams() - n);
1478 TName += "$";
1479 TName += F->getName();
1480 Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1481 Args.push_back(T);
1482 Args.push_back(
1483 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1484 } else {
1485 Args.push_back(*i);
1486 }
1487 }
Peter Collingbourne68162e72013-08-14 18:54:12 +00001488
1489 i = CS.arg_begin();
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001490 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
Peter Collingbourne68162e72013-08-14 18:54:12 +00001491 Args.push_back(DFSF.getShadow(*i));
1492
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001493 if (FT->isVarArg()) {
David Blaikie1b01e7e2015-04-05 22:44:57 +00001494 auto *LabelVATy = ArrayType::get(DFSF.DFS.ShadowTy,
1495 CS.arg_size() - FT->getNumParams());
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001496 auto *LabelVAAlloca = new AllocaInst(
1497 LabelVATy, "labelva", &DFSF.F->getEntryBlock().front());
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001498
1499 for (unsigned n = 0; i != CS.arg_end(); ++i, ++n) {
David Blaikie64646022015-04-05 22:41:44 +00001500 auto LabelVAPtr = IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, n);
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001501 IRB.CreateStore(DFSF.getShadow(*i), LabelVAPtr);
1502 }
1503
David Blaikie64646022015-04-05 22:41:44 +00001504 Args.push_back(IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, 0));
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001505 }
1506
Peter Collingbourne68162e72013-08-14 18:54:12 +00001507 if (!FT->getReturnType()->isVoidTy()) {
1508 if (!DFSF.LabelReturnAlloca) {
1509 DFSF.LabelReturnAlloca =
1510 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001511 &DFSF.F->getEntryBlock().front());
Peter Collingbourne68162e72013-08-14 18:54:12 +00001512 }
1513 Args.push_back(DFSF.LabelReturnAlloca);
1514 }
1515
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001516 for (i = CS.arg_begin() + FT->getNumParams(); i != CS.arg_end(); ++i)
1517 Args.push_back(*i);
1518
Peter Collingbourne68162e72013-08-14 18:54:12 +00001519 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1520 CustomCI->setCallingConv(CI->getCallingConv());
1521 CustomCI->setAttributes(CI->getAttributes());
1522
1523 if (!FT->getReturnType()->isVoidTy()) {
1524 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1525 DFSF.setShadow(CustomCI, LabelLoad);
1526 }
1527
1528 CI->replaceAllUsesWith(CustomCI);
1529 CI->eraseFromParent();
1530 return;
1531 }
1532 break;
1533 }
1534 }
1535 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001536
1537 FunctionType *FT = cast<FunctionType>(
1538 CS.getCalledValue()->getType()->getPointerElementType());
Peter Collingbourne68162e72013-08-14 18:54:12 +00001539 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001540 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1541 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1542 DFSF.getArgTLS(i, CS.getInstruction()));
1543 }
1544 }
1545
Craig Topperf40110f2014-04-25 05:29:35 +00001546 Instruction *Next = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001547 if (!CS.getType()->isVoidTy()) {
1548 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1549 if (II->getNormalDest()->getSinglePredecessor()) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001550 Next = &II->getNormalDest()->front();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001551 } else {
1552 BasicBlock *NewBB =
Chandler Carruthd4500562015-01-19 12:36:53 +00001553 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001554 Next = &NewBB->front();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001555 }
1556 } else {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001557 assert(CS->getIterator() != CS->getParent()->end());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001558 Next = CS->getNextNode();
1559 }
1560
Peter Collingbourne68162e72013-08-14 18:54:12 +00001561 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001562 IRBuilder<> NextIRB(Next);
1563 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1564 DFSF.SkipInsts.insert(LI);
1565 DFSF.setShadow(CS.getInstruction(), LI);
Peter Collingbournefab565a2014-08-22 01:18:18 +00001566 DFSF.NonZeroChecks.push_back(LI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001567 }
1568 }
1569
1570 // Do all instrumentation for IA_Args down here to defer tampering with the
1571 // CFG in a way that SplitEdge may be able to detect.
Peter Collingbourne68162e72013-08-14 18:54:12 +00001572 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1573 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001574 Value *Func =
1575 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1576 std::vector<Value *> Args;
1577
1578 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1579 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1580 Args.push_back(*i);
1581
1582 i = CS.arg_begin();
1583 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1584 Args.push_back(DFSF.getShadow(*i));
1585
1586 if (FT->isVarArg()) {
1587 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1588 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1589 AllocaInst *VarArgShadow =
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001590 new AllocaInst(VarArgArrayTy, "", &DFSF.F->getEntryBlock().front());
David Blaikie4e5d47f42015-04-04 21:07:10 +00001591 Args.push_back(IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, 0));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001592 for (unsigned n = 0; i != e; ++i, ++n) {
David Blaikie4e5d47f42015-04-04 21:07:10 +00001593 IRB.CreateStore(
1594 DFSF.getShadow(*i),
1595 IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, n));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001596 Args.push_back(*i);
1597 }
1598 }
1599
1600 CallSite NewCS;
1601 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1602 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1603 Args);
1604 } else {
1605 NewCS = IRB.CreateCall(Func, Args);
1606 }
1607 NewCS.setCallingConv(CS.getCallingConv());
1608 NewCS.setAttributes(CS.getAttributes().removeAttributes(
1609 *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
Pete Cooper2777d8872015-05-06 23:19:56 +00001610 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType())));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001611
1612 if (Next) {
1613 ExtractValueInst *ExVal =
1614 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1615 DFSF.SkipInsts.insert(ExVal);
1616 ExtractValueInst *ExShadow =
1617 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1618 DFSF.SkipInsts.insert(ExShadow);
1619 DFSF.setShadow(ExVal, ExShadow);
Peter Collingbournefab565a2014-08-22 01:18:18 +00001620 DFSF.NonZeroChecks.push_back(ExShadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001621
1622 CS.getInstruction()->replaceAllUsesWith(ExVal);
1623 }
1624
1625 CS.getInstruction()->eraseFromParent();
1626 }
1627}
1628
1629void DFSanVisitor::visitPHINode(PHINode &PN) {
1630 PHINode *ShadowPN =
1631 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1632
1633 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1634 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1635 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1636 ++i) {
1637 ShadowPN->addIncoming(UndefShadow, *i);
1638 }
1639
1640 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1641 DFSF.setShadow(&PN, ShadowPN);
1642}