blob: 21ef3207e899dbad8f740946165c16e6d8e68c8a [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;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000261
262 Value *getShadowAddress(Value *Addr, Instruction *Pos);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000263 bool isInstrumented(const Function *F);
264 bool isInstrumented(const GlobalAlias *GA);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000265 FunctionType *getArgsFunctionType(FunctionType *T);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000266 FunctionType *getTrampolineFunctionType(FunctionType *T);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000267 FunctionType *getCustomFunctionType(FunctionType *T);
268 InstrumentedABI getInstrumentedABI();
269 WrapperKind getWrapperKind(Function *F);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000270 void addGlobalNamePrefix(GlobalValue *GV);
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000271 Function *buildWrapperFunction(Function *F, StringRef NewFName,
272 GlobalValue::LinkageTypes NewFLink,
273 FunctionType *NewFT);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000274 Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000275
Dmitry Vyukov96a70842013-08-13 16:52:41 +0000276 public:
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000277 DataFlowSanitizer(
278 const std::vector<std::string> &ABIListFiles = std::vector<std::string>(),
279 void *(*getArgTLS)() = nullptr, void *(*getRetValTLS)() = nullptr);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000280 static char ID;
Craig Topper3e4c6972014-03-05 09:10:37 +0000281 bool doInitialization(Module &M) override;
282 bool runOnModule(Module &M) override;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000283};
284
285struct DFSanFunction {
286 DataFlowSanitizer &DFS;
287 Function *F;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000288 DominatorTree DT;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000289 DataFlowSanitizer::InstrumentedABI IA;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000290 bool IsNativeABI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000291 Value *ArgTLSPtr;
292 Value *RetvalTLSPtr;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000293 AllocaInst *LabelReturnAlloca;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000294 DenseMap<Value *, Value *> ValShadowMap;
295 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
296 std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
297 DenseSet<Instruction *> SkipInsts;
Peter Collingbournefab565a2014-08-22 01:18:18 +0000298 std::vector<Value *> NonZeroChecks;
Peter Collingbournedf240b22014-08-06 00:33:40 +0000299 bool AvoidNewBlocks;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000300
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000301 struct CachedCombinedShadow {
302 BasicBlock *Block;
303 Value *Shadow;
304 };
305 DenseMap<std::pair<Value *, Value *>, CachedCombinedShadow>
306 CachedCombinedShadows;
Peter Collingbourne9947c492014-07-15 22:13:19 +0000307 DenseMap<Value *, std::set<Value *>> ShadowElements;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000308
Peter Collingbourne68162e72013-08-14 18:54:12 +0000309 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
310 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()),
Craig Topperf40110f2014-04-25 05:29:35 +0000311 IsNativeABI(IsNativeABI), ArgTLSPtr(nullptr), RetvalTLSPtr(nullptr),
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000312 LabelReturnAlloca(nullptr) {
313 DT.recalculate(*F);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000314 // FIXME: Need to track down the register allocator issue which causes poor
315 // performance in pathological cases with large numbers of basic blocks.
316 AvoidNewBlocks = F->size() > 1000;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000317 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000318 Value *getArgTLSPtr();
319 Value *getArgTLS(unsigned Index, Instruction *Pos);
320 Value *getRetvalTLS();
321 Value *getShadow(Value *V);
322 void setShadow(Instruction *I, Value *Shadow);
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000323 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000324 Value *combineOperandShadows(Instruction *Inst);
325 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
326 Instruction *Pos);
327 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
328 Instruction *Pos);
329};
330
331class DFSanVisitor : public InstVisitor<DFSanVisitor> {
Dmitry Vyukov96a70842013-08-13 16:52:41 +0000332 public:
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000333 DFSanFunction &DFSF;
334 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
335
336 void visitOperandShadowInst(Instruction &I);
337
338 void visitBinaryOperator(BinaryOperator &BO);
339 void visitCastInst(CastInst &CI);
340 void visitCmpInst(CmpInst &CI);
341 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
342 void visitLoadInst(LoadInst &LI);
343 void visitStoreInst(StoreInst &SI);
344 void visitReturnInst(ReturnInst &RI);
345 void visitCallSite(CallSite CS);
346 void visitPHINode(PHINode &PN);
347 void visitExtractElementInst(ExtractElementInst &I);
348 void visitInsertElementInst(InsertElementInst &I);
349 void visitShuffleVectorInst(ShuffleVectorInst &I);
350 void visitExtractValueInst(ExtractValueInst &I);
351 void visitInsertValueInst(InsertValueInst &I);
352 void visitAllocaInst(AllocaInst &I);
353 void visitSelectInst(SelectInst &I);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000354 void visitMemSetInst(MemSetInst &I);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000355 void visitMemTransferInst(MemTransferInst &I);
356};
357
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000358}
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000359
360char DataFlowSanitizer::ID;
361INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
362 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
363
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000364ModulePass *
365llvm::createDataFlowSanitizerPass(const std::vector<std::string> &ABIListFiles,
366 void *(*getArgTLS)(),
367 void *(*getRetValTLS)()) {
368 return new DataFlowSanitizer(ABIListFiles, getArgTLS, getRetValTLS);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000369}
370
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000371DataFlowSanitizer::DataFlowSanitizer(
372 const std::vector<std::string> &ABIListFiles, void *(*getArgTLS)(),
373 void *(*getRetValTLS)())
374 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS) {
375 std::vector<std::string> AllABIListFiles(std::move(ABIListFiles));
376 AllABIListFiles.insert(AllABIListFiles.end(), ClABIListFiles.begin(),
377 ClABIListFiles.end());
378 ABIList.set(SpecialCaseList::createOrDie(AllABIListFiles));
Peter Collingbourne68162e72013-08-14 18:54:12 +0000379}
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000380
Peter Collingbourne68162e72013-08-14 18:54:12 +0000381FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000382 llvm::SmallVector<Type *, 4> ArgTypes(T->param_begin(), T->param_end());
383 ArgTypes.append(T->getNumParams(), ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000384 if (T->isVarArg())
385 ArgTypes.push_back(ShadowPtrTy);
386 Type *RetType = T->getReturnType();
387 if (!RetType->isVoidTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000388 RetType = StructType::get(RetType, ShadowTy, (Type *)nullptr);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000389 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
390}
391
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000392FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
393 assert(!T->isVarArg());
394 llvm::SmallVector<Type *, 4> ArgTypes;
395 ArgTypes.push_back(T->getPointerTo());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000396 ArgTypes.append(T->param_begin(), T->param_end());
397 ArgTypes.append(T->getNumParams(), ShadowTy);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000398 Type *RetType = T->getReturnType();
399 if (!RetType->isVoidTy())
400 ArgTypes.push_back(ShadowPtrTy);
401 return FunctionType::get(T->getReturnType(), ArgTypes, false);
402}
403
Peter Collingbourne68162e72013-08-14 18:54:12 +0000404FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000405 llvm::SmallVector<Type *, 4> ArgTypes;
Alexey Samsonov9b7e2b52013-08-28 11:25:12 +0000406 for (FunctionType::param_iterator i = T->param_begin(), e = T->param_end();
407 i != e; ++i) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000408 FunctionType *FT;
Alexey Samsonov9b7e2b52013-08-28 11:25:12 +0000409 if (isa<PointerType>(*i) && (FT = dyn_cast<FunctionType>(cast<PointerType>(
410 *i)->getElementType()))) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000411 ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
412 ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
413 } else {
414 ArgTypes.push_back(*i);
415 }
416 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000417 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
418 ArgTypes.push_back(ShadowTy);
Peter Collingbournedd3486e2014-10-30 13:22:57 +0000419 if (T->isVarArg())
420 ArgTypes.push_back(ShadowPtrTy);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000421 Type *RetType = T->getReturnType();
422 if (!RetType->isVoidTy())
423 ArgTypes.push_back(ShadowPtrTy);
Peter Collingbournedd3486e2014-10-30 13:22:57 +0000424 return FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg());
Peter Collingbourne68162e72013-08-14 18:54:12 +0000425}
426
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000427bool DataFlowSanitizer::doInitialization(Module &M) {
Peter Collingbourne0826e602014-12-05 21:22:32 +0000428 llvm::Triple TargetTriple(M.getTargetTriple());
429 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
430 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
431 TargetTriple.getArch() == llvm::Triple::mips64el;
Adhemerval Zanellabfe1eaf2015-07-30 20:49:35 +0000432 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64 ||
433 TargetTriple.getArch() == llvm::Triple::aarch64_be;
Peter Collingbourne0826e602014-12-05 21:22:32 +0000434
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000435 const DataLayout &DL = M.getDataLayout();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000436
437 Mod = &M;
438 Ctx = &M.getContext();
439 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
440 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000441 IntptrTy = DL.getIntPtrType(*Ctx);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000442 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000443 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
Peter Collingbourne0826e602014-12-05 21:22:32 +0000444 if (IsX86_64)
445 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
446 else if (IsMIPS64)
447 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0xF000000000LL);
Adhemerval Zanellabfe1eaf2015-07-30 20:49:35 +0000448 else if (IsAArch64)
Adhemerval Zanella4754e2d2015-08-24 13:48:10 +0000449#if SANITIZER_AARCH64_VMA == 39
Adhemerval Zanellabfe1eaf2015-07-30 20:49:35 +0000450 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x7800000000LL);
Adhemerval Zanella4754e2d2015-08-24 13:48:10 +0000451#else
452 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x3c000000000LL);
453#endif
Peter Collingbourne0826e602014-12-05 21:22:32 +0000454 else
455 report_fatal_error("unsupported triple");
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000456
457 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
458 DFSanUnionFnTy =
459 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
460 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
461 DFSanUnionLoadFnTy =
462 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000463 DFSanUnimplementedFnTy = FunctionType::get(
464 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000465 Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
466 DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
467 DFSanSetLabelArgs, /*isVarArg=*/false);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000468 DFSanNonzeroLabelFnTy = FunctionType::get(
Craig Toppere1d12942014-08-27 05:25:25 +0000469 Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
Peter Collingbournea1099842014-11-05 17:21:00 +0000470 DFSanVarargWrapperFnTy = FunctionType::get(
471 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000472
473 if (GetArgTLSPtr) {
474 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
Craig Topperf40110f2014-04-25 05:29:35 +0000475 ArgTLS = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000476 GetArgTLS = ConstantExpr::getIntToPtr(
477 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
478 PointerType::getUnqual(
Craig Topperf40110f2014-04-25 05:29:35 +0000479 FunctionType::get(PointerType::getUnqual(ArgTLSTy),
480 (Type *)nullptr)));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000481 }
482 if (GetRetvalTLSPtr) {
Craig Topperf40110f2014-04-25 05:29:35 +0000483 RetvalTLS = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000484 GetRetvalTLS = ConstantExpr::getIntToPtr(
485 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
486 PointerType::getUnqual(
Craig Topperf40110f2014-04-25 05:29:35 +0000487 FunctionType::get(PointerType::getUnqual(ShadowTy),
488 (Type *)nullptr)));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000489 }
490
491 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
492 return true;
493}
494
Peter Collingbourne59b12622013-08-22 20:08:08 +0000495bool DataFlowSanitizer::isInstrumented(const Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000496 return !ABIList.isIn(*F, "uninstrumented");
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000497}
498
Peter Collingbourne59b12622013-08-22 20:08:08 +0000499bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000500 return !ABIList.isIn(*GA, "uninstrumented");
Peter Collingbourne59b12622013-08-22 20:08:08 +0000501}
502
Peter Collingbourne68162e72013-08-14 18:54:12 +0000503DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000504 return ClArgsABI ? IA_Args : IA_TLS;
505}
506
Peter Collingbourne68162e72013-08-14 18:54:12 +0000507DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000508 if (ABIList.isIn(*F, "functional"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000509 return WK_Functional;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000510 if (ABIList.isIn(*F, "discard"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000511 return WK_Discard;
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +0000512 if (ABIList.isIn(*F, "custom"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000513 return WK_Custom;
514
515 return WK_Warning;
516}
517
Peter Collingbourne59b12622013-08-22 20:08:08 +0000518void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
519 std::string GVName = GV->getName(), Prefix = "dfs$";
520 GV->setName(Prefix + GVName);
521
522 // Try to change the name of the function in module inline asm. We only do
523 // this for specific asm directives, currently only ".symver", to try to avoid
524 // corrupting asm which happens to contain the symbol name as a substring.
525 // Note that the substitution for .symver assumes that the versioned symbol
526 // also has an instrumented name.
527 std::string Asm = GV->getParent()->getModuleInlineAsm();
528 std::string SearchStr = ".symver " + GVName + ",";
529 size_t Pos = Asm.find(SearchStr);
530 if (Pos != std::string::npos) {
531 Asm.replace(Pos, SearchStr.size(),
532 ".symver " + Prefix + GVName + "," + Prefix);
533 GV->getParent()->setModuleInlineAsm(Asm);
534 }
535}
536
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000537Function *
538DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
539 GlobalValue::LinkageTypes NewFLink,
540 FunctionType *NewFT) {
541 FunctionType *FT = F->getFunctionType();
542 Function *NewF = Function::Create(NewFT, NewFLink, NewFName,
543 F->getParent());
544 NewF->copyAttributesFrom(F);
545 NewF->removeAttributes(
Pete Cooper2777d8872015-05-06 23:19:56 +0000546 AttributeSet::ReturnIndex,
547 AttributeSet::get(F->getContext(), AttributeSet::ReturnIndex,
548 AttributeFuncs::typeIncompatible(NewFT->getReturnType())));
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000549
550 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
Peter Collingbournea1099842014-11-05 17:21:00 +0000551 if (F->isVarArg()) {
552 NewF->removeAttributes(
553 AttributeSet::FunctionIndex,
554 AttributeSet().addAttribute(*Ctx, AttributeSet::FunctionIndex,
555 "split-stack"));
556 CallInst::Create(DFSanVarargWrapperFn,
557 IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "",
558 BB);
559 new UnreachableInst(*Ctx, BB);
560 } else {
561 std::vector<Value *> Args;
562 unsigned n = FT->getNumParams();
563 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
564 Args.push_back(&*ai);
565 CallInst *CI = CallInst::Create(F, Args, "", BB);
566 if (FT->getReturnType()->isVoidTy())
567 ReturnInst::Create(*Ctx, BB);
568 else
569 ReturnInst::Create(*Ctx, CI, BB);
570 }
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000571
572 return NewF;
573}
574
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000575Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
576 StringRef FName) {
577 FunctionType *FTT = getTrampolineFunctionType(FT);
578 Constant *C = Mod->getOrInsertFunction(FName, FTT);
579 Function *F = dyn_cast<Function>(C);
580 if (F && F->isDeclaration()) {
581 F->setLinkage(GlobalValue::LinkOnceODRLinkage);
582 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
583 std::vector<Value *> Args;
584 Function::arg_iterator AI = F->arg_begin(); ++AI;
585 for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
586 Args.push_back(&*AI);
587 CallInst *CI =
588 CallInst::Create(&F->getArgumentList().front(), Args, "", BB);
589 ReturnInst *RI;
590 if (FT->getReturnType()->isVoidTy())
591 RI = ReturnInst::Create(*Ctx, BB);
592 else
593 RI = ReturnInst::Create(*Ctx, CI, BB);
594
595 DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
596 Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
597 for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000598 DFSF.ValShadowMap[&*ValAI] = &*ShadowAI;
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000599 DFSanVisitor(DFSF).visitCallInst(*CI);
600 if (!FT->getReturnType()->isVoidTy())
601 new StoreInst(DFSF.getShadow(RI->getReturnValue()),
602 &F->getArgumentList().back(), RI);
603 }
604
605 return C;
606}
607
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000608bool DataFlowSanitizer::runOnModule(Module &M) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000609 if (ABIList.isIn(M, "skip"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000610 return false;
611
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000612 if (!GetArgTLSPtr) {
613 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
614 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
615 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
616 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
617 }
618 if (!GetRetvalTLSPtr) {
619 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
620 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
621 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
622 }
623
624 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
625 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
Peter Collingbournedf240b22014-08-06 00:33:40 +0000626 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
627 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
628 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
629 F->addAttribute(1, Attribute::ZExt);
630 F->addAttribute(2, Attribute::ZExt);
631 }
632 DFSanCheckedUnionFn = Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy);
633 if (Function *F = dyn_cast<Function>(DFSanCheckedUnionFn)) {
634 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000635 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
636 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
637 F->addAttribute(1, Attribute::ZExt);
638 F->addAttribute(2, Attribute::ZExt);
639 }
640 DFSanUnionLoadFn =
641 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
642 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
Peter Collingbournedf240b22014-08-06 00:33:40 +0000643 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
Peter Collingbourne0be79e12013-11-21 23:20:54 +0000644 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000645 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
646 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000647 DFSanUnimplementedFn =
648 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000649 DFSanSetLabelFn =
650 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
651 if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
652 F->addAttribute(1, Attribute::ZExt);
653 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000654 DFSanNonzeroLabelFn =
655 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
Peter Collingbournea1099842014-11-05 17:21:00 +0000656 DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper",
657 DFSanVarargWrapperFnTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000658
659 std::vector<Function *> FnsToInstrument;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000660 llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000661 for (Function &i : M) {
662 if (!i.isIntrinsic() &&
663 &i != DFSanUnionFn &&
664 &i != DFSanCheckedUnionFn &&
665 &i != DFSanUnionLoadFn &&
666 &i != DFSanUnimplementedFn &&
667 &i != DFSanSetLabelFn &&
668 &i != DFSanNonzeroLabelFn &&
669 &i != DFSanVarargWrapperFn)
670 FnsToInstrument.push_back(&i);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000671 }
672
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000673 // Give function aliases prefixes when necessary, and build wrappers where the
674 // instrumentedness is inconsistent.
Peter Collingbourne59b12622013-08-22 20:08:08 +0000675 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
676 GlobalAlias *GA = &*i;
677 ++i;
678 // Don't stop on weak. We assume people aren't playing games with the
679 // instrumentedness of overridden weak aliases.
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000680 if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000681 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
682 if (GAInst && FInst) {
683 addGlobalNamePrefix(GA);
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000684 } else if (GAInst != FInst) {
685 // Non-instrumented alias of an instrumented function, or vice versa.
686 // Replace the alias with a native-ABI wrapper of the aliasee. The pass
687 // below will take care of instrumenting it.
688 Function *NewF =
689 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000690 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000691 NewF->takeName(GA);
692 GA->eraseFromParent();
693 FnsToInstrument.push_back(NewF);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000694 }
695 }
696 }
697
Peter Collingbourne68162e72013-08-14 18:54:12 +0000698 AttrBuilder B;
699 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
700 ReadOnlyNoneAttrs = AttributeSet::get(*Ctx, AttributeSet::FunctionIndex, B);
701
702 // First, change the ABI of every function in the module. ABI-listed
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000703 // functions keep their original ABI and get a wrapper function.
704 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
705 e = FnsToInstrument.end();
706 i != e; ++i) {
707 Function &F = **i;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000708 FunctionType *FT = F.getFunctionType();
Peter Collingbourne68162e72013-08-14 18:54:12 +0000709
Peter Collingbourne59b12622013-08-22 20:08:08 +0000710 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
711 FT->getReturnType()->isVoidTy());
Peter Collingbourne68162e72013-08-14 18:54:12 +0000712
713 if (isInstrumented(&F)) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000714 // Instrumented functions get a 'dfs$' prefix. This allows us to more
715 // easily identify cases of mismatching ABIs.
716 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000717 FunctionType *NewFT = getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000718 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000719 NewF->copyAttributesFrom(&F);
720 NewF->removeAttributes(
Pete Cooper2777d8872015-05-06 23:19:56 +0000721 AttributeSet::ReturnIndex,
722 AttributeSet::get(NewF->getContext(), AttributeSet::ReturnIndex,
723 AttributeFuncs::typeIncompatible(NewFT->getReturnType())));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000724 for (Function::arg_iterator FArg = F.arg_begin(),
725 NewFArg = NewF->arg_begin(),
726 FArgEnd = F.arg_end();
727 FArg != FArgEnd; ++FArg, ++NewFArg) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000728 FArg->replaceAllUsesWith(&*NewFArg);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000729 }
730 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
731
Chandler Carruthcdf47882014-03-09 03:16:01 +0000732 for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
733 UI != UE;) {
734 BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
735 ++UI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000736 if (BA) {
737 BA->replaceAllUsesWith(
738 BlockAddress::get(NewF, BA->getBasicBlock()));
739 delete BA;
740 }
741 }
742 F.replaceAllUsesWith(
743 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
744 NewF->takeName(&F);
745 F.eraseFromParent();
746 *i = NewF;
Peter Collingbourne59b12622013-08-22 20:08:08 +0000747 addGlobalNamePrefix(NewF);
748 } else {
749 addGlobalNamePrefix(&F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000750 }
Peter Collingbourne59b12622013-08-22 20:08:08 +0000751 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000752 // Build a wrapper function for F. The wrapper simply calls F, and is
753 // added to FnsToInstrument so that any instrumentation according to its
754 // WrapperKind is done in the second pass below.
755 FunctionType *NewFT = getInstrumentedABI() == IA_Args
756 ? getArgsFunctionType(FT)
757 : FT;
Alexey Samsonov6dae24d2013-08-23 07:42:51 +0000758 Function *NewF = buildWrapperFunction(
759 &F, std::string("dfsw$") + std::string(F.getName()),
760 GlobalValue::LinkOnceODRLinkage, NewFT);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000761 if (getInstrumentedABI() == IA_TLS)
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000762 NewF->removeAttributes(AttributeSet::FunctionIndex, ReadOnlyNoneAttrs);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000763
Peter Collingbourne68162e72013-08-14 18:54:12 +0000764 Value *WrappedFnCst =
765 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
766 F.replaceAllUsesWith(WrappedFnCst);
David Blaikiec6c6c7b2014-10-07 22:59:46 +0000767
Peter Collingbourne68162e72013-08-14 18:54:12 +0000768 UnwrappedFnMap[WrappedFnCst] = &F;
769 *i = NewF;
770
771 if (!F.isDeclaration()) {
772 // This function is probably defining an interposition of an
773 // uninstrumented function and hence needs to keep the original ABI.
774 // But any functions it may call need to use the instrumented ABI, so
775 // we instrument it in a mode which preserves the original ABI.
776 FnsWithNativeABI.insert(&F);
777
778 // This code needs to rebuild the iterators, as they may be invalidated
779 // by the push_back, taking care that the new range does not include
780 // any functions added by this code.
781 size_t N = i - FnsToInstrument.begin(),
782 Count = e - FnsToInstrument.begin();
783 FnsToInstrument.push_back(&F);
784 i = FnsToInstrument.begin() + N;
785 e = FnsToInstrument.begin() + Count;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000786 }
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +0000787 // Hopefully, nobody will try to indirectly call a vararg
788 // function... yet.
789 } else if (FT->isVarArg()) {
790 UnwrappedFnMap[&F] = &F;
791 *i = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000792 }
793 }
794
795 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
796 e = FnsToInstrument.end();
797 i != e; ++i) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000798 if (!*i || (*i)->isDeclaration())
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000799 continue;
800
Peter Collingbourneae66d572013-08-09 21:42:53 +0000801 removeUnreachableBlocks(**i);
802
Peter Collingbourne68162e72013-08-14 18:54:12 +0000803 DFSanFunction DFSF(*this, *i, FnsWithNativeABI.count(*i));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000804
805 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
806 // Build a copy of the list before iterating over it.
David Blaikieceec2bd2014-04-11 01:50:01 +0000807 llvm::SmallVector<BasicBlock *, 4> BBList(
808 depth_first(&(*i)->getEntryBlock()));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000809
810 for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
811 e = BBList.end();
812 i != e; ++i) {
813 Instruction *Inst = &(*i)->front();
814 while (1) {
815 // DFSanVisitor may split the current basic block, changing the current
816 // instruction's next pointer and moving the next instruction to the
817 // tail block from which we should continue.
818 Instruction *Next = Inst->getNextNode();
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000819 // DFSanVisitor may delete Inst, so keep track of whether it was a
820 // terminator.
821 bool IsTerminator = isa<TerminatorInst>(Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000822 if (!DFSF.SkipInsts.count(Inst))
823 DFSanVisitor(DFSF).visit(Inst);
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000824 if (IsTerminator)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000825 break;
826 Inst = Next;
827 }
828 }
829
Peter Collingbourne68162e72013-08-14 18:54:12 +0000830 // We will not necessarily be able to compute the shadow for every phi node
831 // until we have visited every block. Therefore, the code that handles phi
832 // nodes adds them to the PHIFixups list so that they can be properly
833 // handled here.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000834 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
835 i = DFSF.PHIFixups.begin(),
836 e = DFSF.PHIFixups.end();
837 i != e; ++i) {
838 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
839 ++val) {
840 i->second->setIncomingValue(
841 val, DFSF.getShadow(i->first->getIncomingValue(val)));
842 }
843 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000844
845 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
846 // places (i.e. instructions in basic blocks we haven't even begun visiting
847 // yet). To make our life easier, do this work in a pass after the main
848 // instrumentation.
849 if (ClDebugNonzeroLabels) {
Peter Collingbournefab565a2014-08-22 01:18:18 +0000850 for (Value *V : DFSF.NonZeroChecks) {
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000851 Instruction *Pos;
Peter Collingbournefab565a2014-08-22 01:18:18 +0000852 if (Instruction *I = dyn_cast<Instruction>(V))
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000853 Pos = I->getNextNode();
854 else
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000855 Pos = &DFSF.F->getEntryBlock().front();
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000856 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
857 Pos = Pos->getNextNode();
858 IRBuilder<> IRB(Pos);
Peter Collingbournefab565a2014-08-22 01:18:18 +0000859 Value *Ne = IRB.CreateICmpNE(V, DFSF.DFS.ZeroShadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000860 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000861 Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000862 IRBuilder<> ThenIRB(BI);
David Blaikieff6409d2015-05-18 22:13:54 +0000863 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn, {});
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000864 }
865 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000866 }
867
868 return false;
869}
870
871Value *DFSanFunction::getArgTLSPtr() {
872 if (ArgTLSPtr)
873 return ArgTLSPtr;
874 if (DFS.ArgTLS)
875 return ArgTLSPtr = DFS.ArgTLS;
876
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000877 IRBuilder<> IRB(&F->getEntryBlock().front());
David Blaikieff6409d2015-05-18 22:13:54 +0000878 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS, {});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000879}
880
881Value *DFSanFunction::getRetvalTLS() {
882 if (RetvalTLSPtr)
883 return RetvalTLSPtr;
884 if (DFS.RetvalTLS)
885 return RetvalTLSPtr = DFS.RetvalTLS;
886
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000887 IRBuilder<> IRB(&F->getEntryBlock().front());
David Blaikieff6409d2015-05-18 22:13:54 +0000888 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS, {});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000889}
890
891Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
892 IRBuilder<> IRB(Pos);
893 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
894}
895
896Value *DFSanFunction::getShadow(Value *V) {
897 if (!isa<Argument>(V) && !isa<Instruction>(V))
898 return DFS.ZeroShadow;
899 Value *&Shadow = ValShadowMap[V];
900 if (!Shadow) {
901 if (Argument *A = dyn_cast<Argument>(V)) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000902 if (IsNativeABI)
903 return DFS.ZeroShadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000904 switch (IA) {
905 case DataFlowSanitizer::IA_TLS: {
906 Value *ArgTLSPtr = getArgTLSPtr();
907 Instruction *ArgTLSPos =
908 DFS.ArgTLS ? &*F->getEntryBlock().begin()
909 : cast<Instruction>(ArgTLSPtr)->getNextNode();
910 IRBuilder<> IRB(ArgTLSPos);
911 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
912 break;
913 }
914 case DataFlowSanitizer::IA_Args: {
915 unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
916 Function::arg_iterator i = F->arg_begin();
917 while (ArgIdx--)
918 ++i;
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000919 Shadow = &*i;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000920 assert(Shadow->getType() == DFS.ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000921 break;
922 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000923 }
Peter Collingbournefab565a2014-08-22 01:18:18 +0000924 NonZeroChecks.push_back(Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000925 } else {
926 Shadow = DFS.ZeroShadow;
927 }
928 }
929 return Shadow;
930}
931
932void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
933 assert(!ValShadowMap.count(I));
934 assert(Shadow->getType() == DFS.ShadowTy);
935 ValShadowMap[I] = Shadow;
936}
937
938Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
939 assert(Addr != RetvalTLS && "Reinstrumenting?");
940 IRBuilder<> IRB(Pos);
941 return IRB.CreateIntToPtr(
942 IRB.CreateMul(
943 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
944 ShadowPtrMul),
945 ShadowPtrTy);
946}
947
948// Generates IR to compute the union of the two given shadows, inserting it
949// before Pos. Returns the computed union Value.
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000950Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
951 if (V1 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000952 return V2;
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000953 if (V2 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000954 return V1;
955 if (V1 == V2)
956 return V1;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000957
Peter Collingbourne9947c492014-07-15 22:13:19 +0000958 auto V1Elems = ShadowElements.find(V1);
959 auto V2Elems = ShadowElements.find(V2);
960 if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
961 if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
962 V2Elems->second.begin(), V2Elems->second.end())) {
963 return V1;
964 } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
965 V1Elems->second.begin(), V1Elems->second.end())) {
966 return V2;
967 }
968 } else if (V1Elems != ShadowElements.end()) {
969 if (V1Elems->second.count(V2))
970 return V1;
971 } else if (V2Elems != ShadowElements.end()) {
972 if (V2Elems->second.count(V1))
973 return V2;
974 }
975
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000976 auto Key = std::make_pair(V1, V2);
977 if (V1 > V2)
978 std::swap(Key.first, Key.second);
979 CachedCombinedShadow &CCS = CachedCombinedShadows[Key];
980 if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
981 return CCS.Shadow;
982
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000983 IRBuilder<> IRB(Pos);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000984 if (AvoidNewBlocks) {
David Blaikieff6409d2015-05-18 22:13:54 +0000985 CallInst *Call = IRB.CreateCall(DFS.DFSanCheckedUnionFn, {V1, V2});
Peter Collingbournedf240b22014-08-06 00:33:40 +0000986 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
987 Call->addAttribute(1, Attribute::ZExt);
988 Call->addAttribute(2, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000989
Peter Collingbournedf240b22014-08-06 00:33:40 +0000990 CCS.Block = Pos->getParent();
991 CCS.Shadow = Call;
992 } else {
993 BasicBlock *Head = Pos->getParent();
994 Value *Ne = IRB.CreateICmpNE(V1, V2);
995 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
996 Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
997 IRBuilder<> ThenIRB(BI);
David Blaikieff6409d2015-05-18 22:13:54 +0000998 CallInst *Call = ThenIRB.CreateCall(DFS.DFSanUnionFn, {V1, V2});
Peter Collingbournedf240b22014-08-06 00:33:40 +0000999 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1000 Call->addAttribute(1, Attribute::ZExt);
1001 Call->addAttribute(2, Attribute::ZExt);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001002
Peter Collingbournedf240b22014-08-06 00:33:40 +00001003 BasicBlock *Tail = BI->getSuccessor(0);
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001004 PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
Peter Collingbournedf240b22014-08-06 00:33:40 +00001005 Phi->addIncoming(Call, Call->getParent());
1006 Phi->addIncoming(V1, Head);
1007
1008 CCS.Block = Tail;
1009 CCS.Shadow = Phi;
1010 }
Peter Collingbourne9947c492014-07-15 22:13:19 +00001011
1012 std::set<Value *> UnionElems;
1013 if (V1Elems != ShadowElements.end()) {
1014 UnionElems = V1Elems->second;
1015 } else {
1016 UnionElems.insert(V1);
1017 }
1018 if (V2Elems != ShadowElements.end()) {
1019 UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
1020 } else {
1021 UnionElems.insert(V2);
1022 }
Peter Collingbournedf240b22014-08-06 00:33:40 +00001023 ShadowElements[CCS.Shadow] = std::move(UnionElems);
Peter Collingbourne9947c492014-07-15 22:13:19 +00001024
Peter Collingbournedf240b22014-08-06 00:33:40 +00001025 return CCS.Shadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001026}
1027
1028// A convenience function which folds the shadows of each of the operands
1029// of the provided instruction Inst, inserting the IR before Inst. Returns
1030// the computed union Value.
1031Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
1032 if (Inst->getNumOperands() == 0)
1033 return DFS.ZeroShadow;
1034
1035 Value *Shadow = getShadow(Inst->getOperand(0));
1036 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001037 Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001038 }
1039 return Shadow;
1040}
1041
1042void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
1043 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1044 DFSF.setShadow(&I, CombinedShadow);
1045}
1046
1047// Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
1048// Addr has alignment Align, and take the union of each of those shadows.
1049Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
1050 Instruction *Pos) {
1051 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1052 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1053 AllocaShadowMap.find(AI);
1054 if (i != AllocaShadowMap.end()) {
1055 IRBuilder<> IRB(Pos);
1056 return IRB.CreateLoad(i->second);
1057 }
1058 }
1059
1060 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1061 SmallVector<Value *, 2> Objs;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001062 GetUnderlyingObjects(Addr, Objs, Pos->getModule()->getDataLayout());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001063 bool AllConstants = true;
1064 for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
1065 i != e; ++i) {
1066 if (isa<Function>(*i) || isa<BlockAddress>(*i))
1067 continue;
1068 if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
1069 continue;
1070
1071 AllConstants = false;
1072 break;
1073 }
1074 if (AllConstants)
1075 return DFS.ZeroShadow;
1076
1077 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1078 switch (Size) {
1079 case 0:
1080 return DFS.ZeroShadow;
1081 case 1: {
1082 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
1083 LI->setAlignment(ShadowAlign);
1084 return LI;
1085 }
1086 case 2: {
1087 IRBuilder<> IRB(Pos);
David Blaikie93c54442015-04-03 19:41:44 +00001088 Value *ShadowAddr1 = IRB.CreateGEP(DFS.ShadowTy, ShadowAddr,
1089 ConstantInt::get(DFS.IntptrTy, 1));
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001090 return combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
1091 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign), Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001092 }
1093 }
Peter Collingbournedf240b22014-08-06 00:33:40 +00001094 if (!AvoidNewBlocks && Size % (64 / DFS.ShadowWidth) == 0) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001095 // Fast path for the common case where each byte has identical shadow: load
1096 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
1097 // shadow is non-equal.
1098 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
1099 IRBuilder<> FallbackIRB(FallbackBB);
David Blaikieff6409d2015-05-18 22:13:54 +00001100 CallInst *FallbackCall = FallbackIRB.CreateCall(
1101 DFS.DFSanUnionLoadFn,
1102 {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001103 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1104
1105 // Compare each of the shadows stored in the loaded 64 bits to each other,
1106 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
1107 IRBuilder<> IRB(Pos);
1108 Value *WideAddr =
1109 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1110 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1111 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
1112 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
1113 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
1114 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1115 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1116
1117 BasicBlock *Head = Pos->getParent();
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001118 BasicBlock *Tail = Head->splitBasicBlock(Pos->getIterator());
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001119
1120 if (DomTreeNode *OldNode = DT.getNode(Head)) {
1121 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1122
1123 DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1124 for (auto Child : Children)
1125 DT.changeImmediateDominator(Child, NewNode);
1126 }
1127
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001128 // In the following code LastBr will refer to the previous basic block's
1129 // conditional branch instruction, whose true successor is fixed up to point
1130 // to the next block during the loop below or to the tail after the final
1131 // iteration.
1132 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1133 ReplaceInstWithInst(Head->getTerminator(), LastBr);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001134 DT.addNewBlock(FallbackBB, Head);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001135
1136 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
1137 Ofs += 64 / DFS.ShadowWidth) {
1138 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001139 DT.addNewBlock(NextBB, LastBr->getParent());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001140 IRBuilder<> NextIRB(NextBB);
David Blaikie93c54442015-04-03 19:41:44 +00001141 WideAddr = NextIRB.CreateGEP(Type::getInt64Ty(*DFS.Ctx), WideAddr,
1142 ConstantInt::get(DFS.IntptrTy, 1));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001143 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1144 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1145 LastBr->setSuccessor(0, NextBB);
1146 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1147 }
1148
1149 LastBr->setSuccessor(0, Tail);
1150 FallbackIRB.CreateBr(Tail);
1151 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1152 Shadow->addIncoming(FallbackCall, FallbackBB);
1153 Shadow->addIncoming(TruncShadow, LastBr->getParent());
1154 return Shadow;
1155 }
1156
1157 IRBuilder<> IRB(Pos);
David Blaikieff6409d2015-05-18 22:13:54 +00001158 CallInst *FallbackCall = IRB.CreateCall(
1159 DFS.DFSanUnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001160 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1161 return FallbackCall;
1162}
1163
1164void DFSanVisitor::visitLoadInst(LoadInst &LI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001165 auto &DL = LI.getModule()->getDataLayout();
1166 uint64_t Size = DL.getTypeStoreSize(LI.getType());
Peter Collingbourne142fdff2014-08-01 21:18:18 +00001167 if (Size == 0) {
1168 DFSF.setShadow(&LI, DFSF.DFS.ZeroShadow);
1169 return;
1170 }
1171
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001172 uint64_t Align;
1173 if (ClPreserveAlignment) {
1174 Align = LI.getAlignment();
1175 if (Align == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001176 Align = DL.getABITypeAlignment(LI.getType());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001177 } else {
1178 Align = 1;
1179 }
1180 IRBuilder<> IRB(&LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001181 Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
1182 if (ClCombinePointerLabelsOnLoad) {
1183 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001184 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001185 }
1186 if (Shadow != DFSF.DFS.ZeroShadow)
Peter Collingbournefab565a2014-08-22 01:18:18 +00001187 DFSF.NonZeroChecks.push_back(Shadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +00001188
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001189 DFSF.setShadow(&LI, Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001190}
1191
1192void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
1193 Value *Shadow, Instruction *Pos) {
1194 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1195 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1196 AllocaShadowMap.find(AI);
1197 if (i != AllocaShadowMap.end()) {
1198 IRBuilder<> IRB(Pos);
1199 IRB.CreateStore(Shadow, i->second);
1200 return;
1201 }
1202 }
1203
1204 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1205 IRBuilder<> IRB(Pos);
1206 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1207 if (Shadow == DFS.ZeroShadow) {
1208 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1209 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1210 Value *ExtShadowAddr =
1211 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1212 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1213 return;
1214 }
1215
1216 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1217 uint64_t Offset = 0;
1218 if (Size >= ShadowVecSize) {
1219 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1220 Value *ShadowVec = UndefValue::get(ShadowVecTy);
1221 for (unsigned i = 0; i != ShadowVecSize; ++i) {
1222 ShadowVec = IRB.CreateInsertElement(
1223 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1224 }
1225 Value *ShadowVecAddr =
1226 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1227 do {
David Blaikie95d3e532015-04-03 23:03:54 +00001228 Value *CurShadowVecAddr =
1229 IRB.CreateConstGEP1_32(ShadowVecTy, ShadowVecAddr, Offset);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001230 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1231 Size -= ShadowVecSize;
1232 ++Offset;
1233 } while (Size >= ShadowVecSize);
1234 Offset *= ShadowVecSize;
1235 }
1236 while (Size > 0) {
David Blaikie95d3e532015-04-03 23:03:54 +00001237 Value *CurShadowAddr =
1238 IRB.CreateConstGEP1_32(DFS.ShadowTy, ShadowAddr, Offset);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001239 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1240 --Size;
1241 ++Offset;
1242 }
1243}
1244
1245void DFSanVisitor::visitStoreInst(StoreInst &SI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001246 auto &DL = SI.getModule()->getDataLayout();
1247 uint64_t Size = DL.getTypeStoreSize(SI.getValueOperand()->getType());
Peter Collingbourne142fdff2014-08-01 21:18:18 +00001248 if (Size == 0)
1249 return;
1250
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001251 uint64_t Align;
1252 if (ClPreserveAlignment) {
1253 Align = SI.getAlignment();
1254 if (Align == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001255 Align = DL.getABITypeAlignment(SI.getValueOperand()->getType());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001256 } else {
1257 Align = 1;
1258 }
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001259
1260 Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1261 if (ClCombinePointerLabelsOnStore) {
1262 Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001263 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001264 }
1265 DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001266}
1267
1268void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1269 visitOperandShadowInst(BO);
1270}
1271
1272void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1273
1274void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1275
1276void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1277 visitOperandShadowInst(GEPI);
1278}
1279
1280void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1281 visitOperandShadowInst(I);
1282}
1283
1284void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1285 visitOperandShadowInst(I);
1286}
1287
1288void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1289 visitOperandShadowInst(I);
1290}
1291
1292void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1293 visitOperandShadowInst(I);
1294}
1295
1296void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1297 visitOperandShadowInst(I);
1298}
1299
1300void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1301 bool AllLoadsStores = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001302 for (User *U : I.users()) {
1303 if (isa<LoadInst>(U))
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001304 continue;
1305
Chandler Carruthcdf47882014-03-09 03:16:01 +00001306 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001307 if (SI->getPointerOperand() == &I)
1308 continue;
1309 }
1310
1311 AllLoadsStores = false;
1312 break;
1313 }
1314 if (AllLoadsStores) {
1315 IRBuilder<> IRB(&I);
1316 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1317 }
1318 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1319}
1320
1321void DFSanVisitor::visitSelectInst(SelectInst &I) {
1322 Value *CondShadow = DFSF.getShadow(I.getCondition());
1323 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1324 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1325
1326 if (isa<VectorType>(I.getCondition()->getType())) {
1327 DFSF.setShadow(
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001328 &I,
1329 DFSF.combineShadows(
1330 CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001331 } else {
1332 Value *ShadowSel;
1333 if (TrueShadow == FalseShadow) {
1334 ShadowSel = TrueShadow;
1335 } else {
1336 ShadowSel =
1337 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1338 }
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001339 DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001340 }
1341}
1342
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +00001343void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1344 IRBuilder<> IRB(&I);
1345 Value *ValShadow = DFSF.getShadow(I.getValue());
David Blaikieff6409d2015-05-18 22:13:54 +00001346 IRB.CreateCall(DFSF.DFS.DFSanSetLabelFn,
1347 {ValShadow, IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(
1348 *DFSF.DFS.Ctx)),
1349 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +00001350}
1351
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001352void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1353 IRBuilder<> IRB(&I);
1354 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1355 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1356 Value *LenShadow = IRB.CreateMul(
1357 I.getLength(),
1358 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
Pete Cooper67cf9a72015-11-19 05:56:52 +00001359 Value *AlignShadow;
1360 if (ClPreserveAlignment) {
1361 AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1362 ConstantInt::get(I.getAlignmentCst()->getType(),
1363 DFSF.DFS.ShadowWidth / 8));
1364 } else {
1365 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1366 DFSF.DFS.ShadowWidth / 8);
1367 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001368 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1369 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1370 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
Pete Cooper67cf9a72015-11-19 05:56:52 +00001371 IRB.CreateCall(I.getCalledValue(), {DestShadow, SrcShadow, LenShadow,
1372 AlignShadow, I.getVolatileCst()});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001373}
1374
1375void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001376 if (!DFSF.IsNativeABI && RI.getReturnValue()) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001377 switch (DFSF.IA) {
1378 case DataFlowSanitizer::IA_TLS: {
1379 Value *S = DFSF.getShadow(RI.getReturnValue());
1380 IRBuilder<> IRB(&RI);
1381 IRB.CreateStore(S, DFSF.getRetvalTLS());
1382 break;
1383 }
1384 case DataFlowSanitizer::IA_Args: {
1385 IRBuilder<> IRB(&RI);
1386 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1387 Value *InsVal =
1388 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1389 Value *InsShadow =
1390 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1391 RI.setOperand(0, InsShadow);
1392 break;
1393 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001394 }
1395 }
1396}
1397
1398void DFSanVisitor::visitCallSite(CallSite CS) {
1399 Function *F = CS.getCalledFunction();
1400 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1401 visitOperandShadowInst(*CS.getInstruction());
1402 return;
1403 }
1404
Peter Collingbournea1099842014-11-05 17:21:00 +00001405 // Calls to this function are synthesized in wrappers, and we shouldn't
1406 // instrument them.
1407 if (F == DFSF.DFS.DFSanVarargWrapperFn)
1408 return;
1409
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +00001410 assert(!(cast<FunctionType>(
1411 CS.getCalledValue()->getType()->getPointerElementType())->isVarArg() &&
1412 dyn_cast<InvokeInst>(CS.getInstruction())));
1413
Peter Collingbourne68162e72013-08-14 18:54:12 +00001414 IRBuilder<> IRB(CS.getInstruction());
1415
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001416 DenseMap<Value *, Function *>::iterator i =
1417 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1418 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001419 Function *F = i->second;
1420 switch (DFSF.DFS.getWrapperKind(F)) {
1421 case DataFlowSanitizer::WK_Warning: {
1422 CS.setCalledFunction(F);
1423 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1424 IRB.CreateGlobalStringPtr(F->getName()));
1425 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1426 return;
1427 }
1428 case DataFlowSanitizer::WK_Discard: {
1429 CS.setCalledFunction(F);
1430 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1431 return;
1432 }
1433 case DataFlowSanitizer::WK_Functional: {
1434 CS.setCalledFunction(F);
1435 visitOperandShadowInst(*CS.getInstruction());
1436 return;
1437 }
1438 case DataFlowSanitizer::WK_Custom: {
1439 // Don't try to handle invokes of custom functions, it's too complicated.
1440 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1441 // wrapper.
1442 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1443 FunctionType *FT = F->getFunctionType();
1444 FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1445 std::string CustomFName = "__dfsw_";
1446 CustomFName += F->getName();
1447 Constant *CustomF =
1448 DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1449 if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1450 CustomFn->copyAttributesFrom(F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001451
Peter Collingbourne68162e72013-08-14 18:54:12 +00001452 // Custom functions returning non-void will write to the return label.
1453 if (!FT->getReturnType()->isVoidTy()) {
1454 CustomFn->removeAttributes(AttributeSet::FunctionIndex,
1455 DFSF.DFS.ReadOnlyNoneAttrs);
1456 }
1457 }
1458
1459 std::vector<Value *> Args;
1460
1461 CallSite::arg_iterator i = CS.arg_begin();
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001462 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +00001463 Type *T = (*i)->getType();
1464 FunctionType *ParamFT;
1465 if (isa<PointerType>(T) &&
1466 (ParamFT = dyn_cast<FunctionType>(
1467 cast<PointerType>(T)->getElementType()))) {
1468 std::string TName = "dfst";
1469 TName += utostr(FT->getNumParams() - n);
1470 TName += "$";
1471 TName += F->getName();
1472 Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1473 Args.push_back(T);
1474 Args.push_back(
1475 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1476 } else {
1477 Args.push_back(*i);
1478 }
1479 }
Peter Collingbourne68162e72013-08-14 18:54:12 +00001480
1481 i = CS.arg_begin();
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001482 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
Peter Collingbourne68162e72013-08-14 18:54:12 +00001483 Args.push_back(DFSF.getShadow(*i));
1484
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001485 if (FT->isVarArg()) {
David Blaikie1b01e7e2015-04-05 22:44:57 +00001486 auto *LabelVATy = ArrayType::get(DFSF.DFS.ShadowTy,
1487 CS.arg_size() - FT->getNumParams());
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001488 auto *LabelVAAlloca = new AllocaInst(
1489 LabelVATy, "labelva", &DFSF.F->getEntryBlock().front());
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001490
1491 for (unsigned n = 0; i != CS.arg_end(); ++i, ++n) {
David Blaikie64646022015-04-05 22:41:44 +00001492 auto LabelVAPtr = IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, n);
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001493 IRB.CreateStore(DFSF.getShadow(*i), LabelVAPtr);
1494 }
1495
David Blaikie64646022015-04-05 22:41:44 +00001496 Args.push_back(IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, 0));
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001497 }
1498
Peter Collingbourne68162e72013-08-14 18:54:12 +00001499 if (!FT->getReturnType()->isVoidTy()) {
1500 if (!DFSF.LabelReturnAlloca) {
1501 DFSF.LabelReturnAlloca =
1502 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001503 &DFSF.F->getEntryBlock().front());
Peter Collingbourne68162e72013-08-14 18:54:12 +00001504 }
1505 Args.push_back(DFSF.LabelReturnAlloca);
1506 }
1507
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001508 for (i = CS.arg_begin() + FT->getNumParams(); i != CS.arg_end(); ++i)
1509 Args.push_back(*i);
1510
Peter Collingbourne68162e72013-08-14 18:54:12 +00001511 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1512 CustomCI->setCallingConv(CI->getCallingConv());
1513 CustomCI->setAttributes(CI->getAttributes());
1514
1515 if (!FT->getReturnType()->isVoidTy()) {
1516 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1517 DFSF.setShadow(CustomCI, LabelLoad);
1518 }
1519
1520 CI->replaceAllUsesWith(CustomCI);
1521 CI->eraseFromParent();
1522 return;
1523 }
1524 break;
1525 }
1526 }
1527 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001528
1529 FunctionType *FT = cast<FunctionType>(
1530 CS.getCalledValue()->getType()->getPointerElementType());
Peter Collingbourne68162e72013-08-14 18:54:12 +00001531 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001532 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1533 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1534 DFSF.getArgTLS(i, CS.getInstruction()));
1535 }
1536 }
1537
Craig Topperf40110f2014-04-25 05:29:35 +00001538 Instruction *Next = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001539 if (!CS.getType()->isVoidTy()) {
1540 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1541 if (II->getNormalDest()->getSinglePredecessor()) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001542 Next = &II->getNormalDest()->front();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001543 } else {
1544 BasicBlock *NewBB =
Chandler Carruthd4500562015-01-19 12:36:53 +00001545 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001546 Next = &NewBB->front();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001547 }
1548 } else {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001549 assert(CS->getIterator() != CS->getParent()->end());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001550 Next = CS->getNextNode();
1551 }
1552
Peter Collingbourne68162e72013-08-14 18:54:12 +00001553 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001554 IRBuilder<> NextIRB(Next);
1555 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1556 DFSF.SkipInsts.insert(LI);
1557 DFSF.setShadow(CS.getInstruction(), LI);
Peter Collingbournefab565a2014-08-22 01:18:18 +00001558 DFSF.NonZeroChecks.push_back(LI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001559 }
1560 }
1561
1562 // Do all instrumentation for IA_Args down here to defer tampering with the
1563 // CFG in a way that SplitEdge may be able to detect.
Peter Collingbourne68162e72013-08-14 18:54:12 +00001564 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1565 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001566 Value *Func =
1567 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1568 std::vector<Value *> Args;
1569
1570 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1571 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1572 Args.push_back(*i);
1573
1574 i = CS.arg_begin();
1575 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1576 Args.push_back(DFSF.getShadow(*i));
1577
1578 if (FT->isVarArg()) {
1579 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1580 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1581 AllocaInst *VarArgShadow =
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001582 new AllocaInst(VarArgArrayTy, "", &DFSF.F->getEntryBlock().front());
David Blaikie4e5d47f42015-04-04 21:07:10 +00001583 Args.push_back(IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, 0));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001584 for (unsigned n = 0; i != e; ++i, ++n) {
David Blaikie4e5d47f42015-04-04 21:07:10 +00001585 IRB.CreateStore(
1586 DFSF.getShadow(*i),
1587 IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, n));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001588 Args.push_back(*i);
1589 }
1590 }
1591
1592 CallSite NewCS;
1593 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1594 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1595 Args);
1596 } else {
1597 NewCS = IRB.CreateCall(Func, Args);
1598 }
1599 NewCS.setCallingConv(CS.getCallingConv());
1600 NewCS.setAttributes(CS.getAttributes().removeAttributes(
1601 *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
Pete Cooper2777d8872015-05-06 23:19:56 +00001602 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType())));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001603
1604 if (Next) {
1605 ExtractValueInst *ExVal =
1606 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1607 DFSF.SkipInsts.insert(ExVal);
1608 ExtractValueInst *ExShadow =
1609 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1610 DFSF.SkipInsts.insert(ExShadow);
1611 DFSF.setShadow(ExVal, ExShadow);
Peter Collingbournefab565a2014-08-22 01:18:18 +00001612 DFSF.NonZeroChecks.push_back(ExShadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001613
1614 CS.getInstruction()->replaceAllUsesWith(ExVal);
1615 }
1616
1617 CS.getInstruction()->eraseFromParent();
1618 }
1619}
1620
1621void DFSanVisitor::visitPHINode(PHINode &PN) {
1622 PHINode *ShadowPN =
1623 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1624
1625 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1626 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1627 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1628 ++i) {
1629 ShadowPN->addIncoming(UndefShadow, *i);
1630 }
1631
1632 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1633 DFSF.setShadow(&PN, ShadowPN);
1634}