blob: d74ccdfccb8261a597f2a36beb0f81a3911e8682 [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
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000047#include "llvm/ADT/DenseMap.h"
48#include "llvm/ADT/DenseSet.h"
49#include "llvm/ADT/DepthFirstIterator.h"
Peter Collingbourne28a10af2013-08-27 22:09:06 +000050#include "llvm/ADT/StringExtras.h"
Peter Collingbourne0826e602014-12-05 21:22:32 +000051#include "llvm/ADT/Triple.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000052#include "llvm/Analysis/ValueTracking.h"
David Blaikiec6c6c7b2014-10-07 22:59:46 +000053#include "llvm/IR/DebugInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000054#include "llvm/IR/Dominators.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000055#include "llvm/IR/IRBuilder.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000056#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000057#include "llvm/IR/InstVisitor.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000058#include "llvm/IR/LLVMContext.h"
59#include "llvm/IR/MDBuilder.h"
60#include "llvm/IR/Type.h"
61#include "llvm/IR/Value.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000062#include "llvm/Pass.h"
63#include "llvm/Support/CommandLine.h"
Alexey Samsonovb7dd3292014-07-09 19:40:08 +000064#include "llvm/Support/SpecialCaseList.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000065#include "llvm/Transforms/Instrumentation.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 Zanellad93c0c42015-11-27 12:42:39 +000075// External symbol to be used when generating the shadow address for
76// architectures with multiple VMAs. Instead of using a constant integer
77// the runtime will set the external mask based on the VMA range.
78static const char *const kDFSanExternShadowPtrMask = "__dfsan_shadow_ptr_mask";
Adhemerval Zanella4754e2d2015-08-24 13:48:10 +000079
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000080// The -dfsan-preserve-alignment flag controls whether this pass assumes that
81// alignment requirements provided by the input IR are correct. For example,
82// if the input IR contains a load with alignment 8, this flag will cause
83// the shadow load to have alignment 16. This flag is disabled by default as
84// we have unfortunately encountered too much code (including Clang itself;
85// see PR14291) which performs misaligned access.
86static cl::opt<bool> ClPreserveAlignment(
87 "dfsan-preserve-alignment",
88 cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
89 cl::init(false));
90
Alexey Samsonovb9b80272015-02-04 17:39:48 +000091// The ABI list files control how shadow parameters are passed. The pass treats
Peter Collingbourne68162e72013-08-14 18:54:12 +000092// every function labelled "uninstrumented" in the ABI list file as conforming
93// to the "native" (i.e. unsanitized) ABI. Unless the ABI list contains
94// additional annotations for those functions, a call to one of those functions
95// will produce a warning message, as the labelling behaviour of the function is
96// unknown. The other supported annotations are "functional" and "discard",
97// which are described below under DataFlowSanitizer::WrapperKind.
Alexey Samsonovb9b80272015-02-04 17:39:48 +000098static cl::list<std::string> ClABIListFiles(
Peter Collingbourne68162e72013-08-14 18:54:12 +000099 "dfsan-abilist",
100 cl::desc("File listing native ABI functions and how the pass treats them"),
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000101 cl::Hidden);
102
Peter Collingbourne68162e72013-08-14 18:54:12 +0000103// Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
104// functions (see DataFlowSanitizer::InstrumentedABI below).
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000105static cl::opt<bool> ClArgsABI(
106 "dfsan-args-abi",
107 cl::desc("Use the argument ABI rather than the TLS ABI"),
108 cl::Hidden);
109
Peter Collingbourne0be79e12013-11-21 23:20:54 +0000110// Controls whether the pass includes or ignores the labels of pointers in load
111// instructions.
112static cl::opt<bool> ClCombinePointerLabelsOnLoad(
113 "dfsan-combine-pointer-labels-on-load",
114 cl::desc("Combine the label of the pointer with the label of the data when "
115 "loading from memory."),
116 cl::Hidden, cl::init(true));
117
118// Controls whether the pass includes or ignores the labels of pointers in
119// stores instructions.
120static cl::opt<bool> ClCombinePointerLabelsOnStore(
121 "dfsan-combine-pointer-labels-on-store",
122 cl::desc("Combine the label of the pointer with the label of the data when "
123 "storing in memory."),
124 cl::Hidden, cl::init(false));
125
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000126static cl::opt<bool> ClDebugNonzeroLabels(
127 "dfsan-debug-nonzero-labels",
128 cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
129 "load or return with a nonzero label"),
130 cl::Hidden);
131
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000132
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000133namespace {
134
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000135StringRef GetGlobalTypeString(const GlobalValue &G) {
136 // Types of GlobalVariables are always pointer types.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000137 Type *GType = G.getValueType();
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000138 // For now we support blacklisting struct types only.
139 if (StructType *SGType = dyn_cast<StructType>(GType)) {
140 if (!SGType->isLiteral())
141 return SGType->getName();
142 }
143 return "<unknown type>";
144}
145
146class DFSanABIList {
147 std::unique_ptr<SpecialCaseList> SCL;
148
149 public:
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000150 DFSanABIList() {}
151
152 void set(std::unique_ptr<SpecialCaseList> List) { SCL = std::move(List); }
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000153
154 /// Returns whether either this function or its source file are listed in the
155 /// given category.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000156 bool isIn(const Function &F, StringRef Category) const {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000157 return isIn(*F.getParent(), Category) ||
Vlad Tsyrklevich998b2202017-09-25 22:11:11 +0000158 SCL->inSection("dataflow", "fun", F.getName(), Category);
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000159 }
160
161 /// Returns whether this global alias is listed in the given category.
162 ///
163 /// If GA aliases a function, the alias's name is matched as a function name
164 /// would be. Similarly, aliases of globals are matched like globals.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000165 bool isIn(const GlobalAlias &GA, StringRef Category) const {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000166 if (isIn(*GA.getParent(), Category))
167 return true;
168
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000169 if (isa<FunctionType>(GA.getValueType()))
Vlad Tsyrklevich998b2202017-09-25 22:11:11 +0000170 return SCL->inSection("dataflow", "fun", GA.getName(), Category);
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000171
Vlad Tsyrklevich998b2202017-09-25 22:11:11 +0000172 return SCL->inSection("dataflow", "global", GA.getName(), Category) ||
173 SCL->inSection("dataflow", "type", GetGlobalTypeString(GA),
174 Category);
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000175 }
176
177 /// Returns whether this module is listed in the given category.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000178 bool isIn(const Module &M, StringRef Category) const {
Vlad Tsyrklevich998b2202017-09-25 22:11:11 +0000179 return SCL->inSection("dataflow", "src", M.getModuleIdentifier(), Category);
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000180 }
181};
182
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000183class DataFlowSanitizer : public ModulePass {
184 friend struct DFSanFunction;
185 friend class DFSanVisitor;
186
187 enum {
188 ShadowWidth = 16
189 };
190
Peter Collingbourne68162e72013-08-14 18:54:12 +0000191 /// Which ABI should be used for instrumented functions?
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000192 enum InstrumentedABI {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000193 /// Argument and return value labels are passed through additional
194 /// arguments and by modifying the return type.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000195 IA_Args,
Peter Collingbourne68162e72013-08-14 18:54:12 +0000196
197 /// Argument and return value labels are passed through TLS variables
198 /// __dfsan_arg_tls and __dfsan_retval_tls.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000199 IA_TLS
200 };
201
Peter Collingbourne68162e72013-08-14 18:54:12 +0000202 /// How should calls to uninstrumented functions be handled?
203 enum WrapperKind {
204 /// This function is present in an uninstrumented form but we don't know
205 /// how it should be handled. Print a warning and call the function anyway.
206 /// Don't label the return value.
207 WK_Warning,
208
209 /// This function does not write to (user-accessible) memory, and its return
210 /// value is unlabelled.
211 WK_Discard,
212
213 /// This function does not write to (user-accessible) memory, and the label
214 /// of its return value is the union of the label of its arguments.
215 WK_Functional,
216
217 /// Instead of calling the function, a custom wrapper __dfsw_F is called,
218 /// where F is the name of the function. This function may wrap the
219 /// original function or provide its own implementation. This is similar to
220 /// the IA_Args ABI, except that IA_Args uses a struct return type to
221 /// pass the return value shadow in a register, while WK_Custom uses an
222 /// extra pointer argument to return the shadow. This allows the wrapped
223 /// form of the function type to be expressed in C.
224 WK_Custom
225 };
226
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000227 Module *Mod;
228 LLVMContext *Ctx;
229 IntegerType *ShadowTy;
230 PointerType *ShadowPtrTy;
231 IntegerType *IntptrTy;
232 ConstantInt *ZeroShadow;
233 ConstantInt *ShadowPtrMask;
234 ConstantInt *ShadowPtrMul;
235 Constant *ArgTLS;
236 Constant *RetvalTLS;
237 void *(*GetArgTLSPtr)();
238 void *(*GetRetvalTLSPtr)();
239 Constant *GetArgTLS;
240 Constant *GetRetvalTLS;
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000241 Constant *ExternalShadowMask;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000242 FunctionType *DFSanUnionFnTy;
243 FunctionType *DFSanUnionLoadFnTy;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000244 FunctionType *DFSanUnimplementedFnTy;
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000245 FunctionType *DFSanSetLabelFnTy;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000246 FunctionType *DFSanNonzeroLabelFnTy;
Peter Collingbournea1099842014-11-05 17:21:00 +0000247 FunctionType *DFSanVarargWrapperFnTy;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000248 Constant *DFSanUnionFn;
Peter Collingbournedf240b22014-08-06 00:33:40 +0000249 Constant *DFSanCheckedUnionFn;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000250 Constant *DFSanUnionLoadFn;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000251 Constant *DFSanUnimplementedFn;
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000252 Constant *DFSanSetLabelFn;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000253 Constant *DFSanNonzeroLabelFn;
Peter Collingbournea1099842014-11-05 17:21:00 +0000254 Constant *DFSanVarargWrapperFn;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000255 MDNode *ColdCallWeights;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000256 DFSanABIList ABIList;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000257 DenseMap<Value *, Function *> UnwrappedFnMap;
Reid Kleckneree4930b2017-05-02 22:07:37 +0000258 AttrBuilder ReadOnlyNoneAttrs;
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000259 bool DFSanRuntimeShadowMask;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000260
261 Value *getShadowAddress(Value *Addr, Instruction *Pos);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000262 bool isInstrumented(const Function *F);
263 bool isInstrumented(const GlobalAlias *GA);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000264 FunctionType *getArgsFunctionType(FunctionType *T);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000265 FunctionType *getTrampolineFunctionType(FunctionType *T);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000266 FunctionType *getCustomFunctionType(FunctionType *T);
267 InstrumentedABI getInstrumentedABI();
268 WrapperKind getWrapperKind(Function *F);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000269 void addGlobalNamePrefix(GlobalValue *GV);
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000270 Function *buildWrapperFunction(Function *F, StringRef NewFName,
271 GlobalValue::LinkageTypes NewFLink,
272 FunctionType *NewFT);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000273 Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000274
Dmitry Vyukov96a70842013-08-13 16:52:41 +0000275 public:
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000276 DataFlowSanitizer(
277 const std::vector<std::string> &ABIListFiles = std::vector<std::string>(),
278 void *(*getArgTLS)() = nullptr, void *(*getRetValTLS)() = nullptr);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000279 static char ID;
Craig Topper3e4c6972014-03-05 09:10:37 +0000280 bool doInitialization(Module &M) override;
281 bool runOnModule(Module &M) override;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000282};
283
284struct DFSanFunction {
285 DataFlowSanitizer &DFS;
286 Function *F;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000287 DominatorTree DT;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000288 DataFlowSanitizer::InstrumentedABI IA;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000289 bool IsNativeABI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000290 Value *ArgTLSPtr;
291 Value *RetvalTLSPtr;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000292 AllocaInst *LabelReturnAlloca;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000293 DenseMap<Value *, Value *> ValShadowMap;
294 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
295 std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
296 DenseSet<Instruction *> SkipInsts;
Peter Collingbournefab565a2014-08-22 01:18:18 +0000297 std::vector<Value *> NonZeroChecks;
Peter Collingbournedf240b22014-08-06 00:33:40 +0000298 bool AvoidNewBlocks;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000299
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000300 struct CachedCombinedShadow {
301 BasicBlock *Block;
302 Value *Shadow;
303 };
304 DenseMap<std::pair<Value *, Value *>, CachedCombinedShadow>
305 CachedCombinedShadows;
Peter Collingbourne9947c492014-07-15 22:13:19 +0000306 DenseMap<Value *, std::set<Value *>> ShadowElements;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000307
Peter Collingbourne68162e72013-08-14 18:54:12 +0000308 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
309 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()),
Craig Topperf40110f2014-04-25 05:29:35 +0000310 IsNativeABI(IsNativeABI), ArgTLSPtr(nullptr), RetvalTLSPtr(nullptr),
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000311 LabelReturnAlloca(nullptr) {
312 DT.recalculate(*F);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000313 // FIXME: Need to track down the register allocator issue which causes poor
314 // performance in pathological cases with large numbers of basic blocks.
315 AvoidNewBlocks = F->size() > 1000;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000316 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000317 Value *getArgTLSPtr();
318 Value *getArgTLS(unsigned Index, Instruction *Pos);
319 Value *getRetvalTLS();
320 Value *getShadow(Value *V);
321 void setShadow(Instruction *I, Value *Shadow);
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000322 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000323 Value *combineOperandShadows(Instruction *Inst);
324 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
325 Instruction *Pos);
326 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
327 Instruction *Pos);
328};
329
330class DFSanVisitor : public InstVisitor<DFSanVisitor> {
Dmitry Vyukov96a70842013-08-13 16:52:41 +0000331 public:
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000332 DFSanFunction &DFSF;
333 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
334
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000335 const DataLayout &getDataLayout() const {
336 return DFSF.F->getParent()->getDataLayout();
337 }
338
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000339 void visitOperandShadowInst(Instruction &I);
340
341 void visitBinaryOperator(BinaryOperator &BO);
342 void visitCastInst(CastInst &CI);
343 void visitCmpInst(CmpInst &CI);
344 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
345 void visitLoadInst(LoadInst &LI);
346 void visitStoreInst(StoreInst &SI);
347 void visitReturnInst(ReturnInst &RI);
348 void visitCallSite(CallSite CS);
349 void visitPHINode(PHINode &PN);
350 void visitExtractElementInst(ExtractElementInst &I);
351 void visitInsertElementInst(InsertElementInst &I);
352 void visitShuffleVectorInst(ShuffleVectorInst &I);
353 void visitExtractValueInst(ExtractValueInst &I);
354 void visitInsertValueInst(InsertValueInst &I);
355 void visitAllocaInst(AllocaInst &I);
356 void visitSelectInst(SelectInst &I);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000357 void visitMemSetInst(MemSetInst &I);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000358 void visitMemTransferInst(MemTransferInst &I);
359};
360
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000361}
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000362
363char DataFlowSanitizer::ID;
364INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
365 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
366
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000367ModulePass *
368llvm::createDataFlowSanitizerPass(const std::vector<std::string> &ABIListFiles,
369 void *(*getArgTLS)(),
370 void *(*getRetValTLS)()) {
371 return new DataFlowSanitizer(ABIListFiles, getArgTLS, getRetValTLS);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000372}
373
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000374DataFlowSanitizer::DataFlowSanitizer(
375 const std::vector<std::string> &ABIListFiles, void *(*getArgTLS)(),
376 void *(*getRetValTLS)())
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000377 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS),
378 DFSanRuntimeShadowMask(false) {
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000379 std::vector<std::string> AllABIListFiles(std::move(ABIListFiles));
380 AllABIListFiles.insert(AllABIListFiles.end(), ClABIListFiles.begin(),
381 ClABIListFiles.end());
382 ABIList.set(SpecialCaseList::createOrDie(AllABIListFiles));
Peter Collingbourne68162e72013-08-14 18:54:12 +0000383}
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000384
Peter Collingbourne68162e72013-08-14 18:54:12 +0000385FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000386 llvm::SmallVector<Type *, 4> ArgTypes(T->param_begin(), T->param_end());
387 ArgTypes.append(T->getNumParams(), ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000388 if (T->isVarArg())
389 ArgTypes.push_back(ShadowPtrTy);
390 Type *RetType = T->getReturnType();
391 if (!RetType->isVoidTy())
Serge Gueltone38003f2017-05-09 19:31:13 +0000392 RetType = StructType::get(RetType, ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000393 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
394}
395
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000396FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
397 assert(!T->isVarArg());
398 llvm::SmallVector<Type *, 4> ArgTypes;
399 ArgTypes.push_back(T->getPointerTo());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000400 ArgTypes.append(T->param_begin(), T->param_end());
401 ArgTypes.append(T->getNumParams(), ShadowTy);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000402 Type *RetType = T->getReturnType();
403 if (!RetType->isVoidTy())
404 ArgTypes.push_back(ShadowPtrTy);
405 return FunctionType::get(T->getReturnType(), ArgTypes, false);
406}
407
Peter Collingbourne68162e72013-08-14 18:54:12 +0000408FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000409 llvm::SmallVector<Type *, 4> ArgTypes;
Alexey Samsonov9b7e2b52013-08-28 11:25:12 +0000410 for (FunctionType::param_iterator i = T->param_begin(), e = T->param_end();
411 i != e; ++i) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000412 FunctionType *FT;
Alexey Samsonov9b7e2b52013-08-28 11:25:12 +0000413 if (isa<PointerType>(*i) && (FT = dyn_cast<FunctionType>(cast<PointerType>(
414 *i)->getElementType()))) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000415 ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
416 ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
417 } else {
418 ArgTypes.push_back(*i);
419 }
420 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000421 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
422 ArgTypes.push_back(ShadowTy);
Peter Collingbournedd3486e2014-10-30 13:22:57 +0000423 if (T->isVarArg())
424 ArgTypes.push_back(ShadowPtrTy);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000425 Type *RetType = T->getReturnType();
426 if (!RetType->isVoidTy())
427 ArgTypes.push_back(ShadowPtrTy);
Peter Collingbournedd3486e2014-10-30 13:22:57 +0000428 return FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg());
Peter Collingbourne68162e72013-08-14 18:54:12 +0000429}
430
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000431bool DataFlowSanitizer::doInitialization(Module &M) {
Peter Collingbourne0826e602014-12-05 21:22:32 +0000432 llvm::Triple TargetTriple(M.getTargetTriple());
433 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
434 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
435 TargetTriple.getArch() == llvm::Triple::mips64el;
Adhemerval Zanellabfe1eaf2015-07-30 20:49:35 +0000436 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64 ||
437 TargetTriple.getArch() == llvm::Triple::aarch64_be;
Peter Collingbourne0826e602014-12-05 21:22:32 +0000438
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000439 const DataLayout &DL = M.getDataLayout();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000440
441 Mod = &M;
442 Ctx = &M.getContext();
443 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
444 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000445 IntptrTy = DL.getIntPtrType(*Ctx);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000446 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000447 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
Peter Collingbourne0826e602014-12-05 21:22:32 +0000448 if (IsX86_64)
449 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
450 else if (IsMIPS64)
451 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0xF000000000LL);
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000452 // AArch64 supports multiple VMAs and the shadow mask is set at runtime.
Adhemerval Zanellabfe1eaf2015-07-30 20:49:35 +0000453 else if (IsAArch64)
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000454 DFSanRuntimeShadowMask = true;
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(
Serge Guelton778ece82017-05-10 13:24:17 +0000480 FunctionType::get(PointerType::getUnqual(ArgTLSTy), false)));
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(
Serge Guelton778ece82017-05-10 13:24:17 +0000487 FunctionType::get(PointerType::getUnqual(ShadowTy), false)));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000488 }
489
490 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
491 return true;
492}
493
Peter Collingbourne59b12622013-08-22 20:08:08 +0000494bool DataFlowSanitizer::isInstrumented(const Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000495 return !ABIList.isIn(*F, "uninstrumented");
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000496}
497
Peter Collingbourne59b12622013-08-22 20:08:08 +0000498bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000499 return !ABIList.isIn(*GA, "uninstrumented");
Peter Collingbourne59b12622013-08-22 20:08:08 +0000500}
501
Peter Collingbourne68162e72013-08-14 18:54:12 +0000502DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000503 return ClArgsABI ? IA_Args : IA_TLS;
504}
505
Peter Collingbourne68162e72013-08-14 18:54:12 +0000506DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000507 if (ABIList.isIn(*F, "functional"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000508 return WK_Functional;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000509 if (ABIList.isIn(*F, "discard"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000510 return WK_Discard;
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +0000511 if (ABIList.isIn(*F, "custom"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000512 return WK_Custom;
513
514 return WK_Warning;
515}
516
Peter Collingbourne59b12622013-08-22 20:08:08 +0000517void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
518 std::string GVName = GV->getName(), Prefix = "dfs$";
519 GV->setName(Prefix + GVName);
520
521 // Try to change the name of the function in module inline asm. We only do
522 // this for specific asm directives, currently only ".symver", to try to avoid
523 // corrupting asm which happens to contain the symbol name as a substring.
524 // Note that the substitution for .symver assumes that the versioned symbol
525 // also has an instrumented name.
526 std::string Asm = GV->getParent()->getModuleInlineAsm();
527 std::string SearchStr = ".symver " + GVName + ",";
528 size_t Pos = Asm.find(SearchStr);
529 if (Pos != std::string::npos) {
530 Asm.replace(Pos, SearchStr.size(),
531 ".symver " + Prefix + GVName + "," + Prefix);
532 GV->getParent()->setModuleInlineAsm(Asm);
533 }
534}
535
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000536Function *
537DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
538 GlobalValue::LinkageTypes NewFLink,
539 FunctionType *NewFT) {
540 FunctionType *FT = F->getFunctionType();
541 Function *NewF = Function::Create(NewFT, NewFLink, NewFName,
542 F->getParent());
543 NewF->copyAttributesFrom(F);
544 NewF->removeAttributes(
Reid Klecknerb5180542017-03-21 16:57:19 +0000545 AttributeList::ReturnIndex,
Reid Kleckneree4930b2017-05-02 22:07:37 +0000546 AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000547
548 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
Peter Collingbournea1099842014-11-05 17:21:00 +0000549 if (F->isVarArg()) {
Reid Kleckneree4930b2017-05-02 22:07:37 +0000550 NewF->removeAttributes(AttributeList::FunctionIndex,
551 AttrBuilder().addAttribute("split-stack"));
Peter Collingbournea1099842014-11-05 17:21:00 +0000552 CallInst::Create(DFSanVarargWrapperFn,
553 IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "",
554 BB);
555 new UnreachableInst(*Ctx, BB);
556 } else {
557 std::vector<Value *> Args;
558 unsigned n = FT->getNumParams();
559 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
560 Args.push_back(&*ai);
561 CallInst *CI = CallInst::Create(F, Args, "", BB);
562 if (FT->getReturnType()->isVoidTy())
563 ReturnInst::Create(*Ctx, BB);
564 else
565 ReturnInst::Create(*Ctx, CI, BB);
566 }
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000567
568 return NewF;
569}
570
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000571Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
572 StringRef FName) {
573 FunctionType *FTT = getTrampolineFunctionType(FT);
574 Constant *C = Mod->getOrInsertFunction(FName, FTT);
575 Function *F = dyn_cast<Function>(C);
576 if (F && F->isDeclaration()) {
577 F->setLinkage(GlobalValue::LinkOnceODRLinkage);
578 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
579 std::vector<Value *> Args;
580 Function::arg_iterator AI = F->arg_begin(); ++AI;
581 for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
582 Args.push_back(&*AI);
Reid Kleckner45707d42017-03-16 22:59:15 +0000583 CallInst *CI = CallInst::Create(&*F->arg_begin(), Args, "", BB);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000584 ReturnInst *RI;
585 if (FT->getReturnType()->isVoidTy())
586 RI = ReturnInst::Create(*Ctx, BB);
587 else
588 RI = ReturnInst::Create(*Ctx, CI, BB);
589
590 DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
591 Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
592 for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000593 DFSF.ValShadowMap[&*ValAI] = &*ShadowAI;
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000594 DFSanVisitor(DFSF).visitCallInst(*CI);
595 if (!FT->getReturnType()->isVoidTy())
596 new StoreInst(DFSF.getShadow(RI->getReturnValue()),
Reid Kleckner45707d42017-03-16 22:59:15 +0000597 &*std::prev(F->arg_end()), RI);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000598 }
599
600 return C;
601}
602
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000603bool DataFlowSanitizer::runOnModule(Module &M) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000604 if (ABIList.isIn(M, "skip"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000605 return false;
606
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000607 if (!GetArgTLSPtr) {
608 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
609 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
610 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
611 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
612 }
613 if (!GetRetvalTLSPtr) {
614 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
615 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
616 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
617 }
618
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000619 ExternalShadowMask =
620 Mod->getOrInsertGlobal(kDFSanExternShadowPtrMask, IntptrTy);
621
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000622 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
623 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000624 F->addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
625 F->addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
626 F->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Reid Klecknera0b45f42017-05-03 18:17:31 +0000627 F->addParamAttr(0, Attribute::ZExt);
628 F->addParamAttr(1, Attribute::ZExt);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000629 }
630 DFSanCheckedUnionFn = Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy);
631 if (Function *F = dyn_cast<Function>(DFSanCheckedUnionFn)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000632 F->addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
633 F->addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
634 F->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Reid Klecknera0b45f42017-05-03 18:17:31 +0000635 F->addParamAttr(0, Attribute::ZExt);
636 F->addParamAttr(1, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000637 }
638 DFSanUnionLoadFn =
639 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
640 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000641 F->addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
642 F->addAttribute(AttributeList::FunctionIndex, Attribute::ReadOnly);
643 F->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000644 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000645 DFSanUnimplementedFn =
646 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000647 DFSanSetLabelFn =
648 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
649 if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
Reid Klecknera0b45f42017-05-03 18:17:31 +0000650 F->addParamAttr(0, Attribute::ZExt);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000651 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000652 DFSanNonzeroLabelFn =
653 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
Peter Collingbournea1099842014-11-05 17:21:00 +0000654 DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper",
655 DFSanVarargWrapperFnTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000656
657 std::vector<Function *> FnsToInstrument;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000658 llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000659 for (Function &i : M) {
660 if (!i.isIntrinsic() &&
661 &i != DFSanUnionFn &&
662 &i != DFSanCheckedUnionFn &&
663 &i != DFSanUnionLoadFn &&
664 &i != DFSanUnimplementedFn &&
665 &i != DFSanSetLabelFn &&
666 &i != DFSanNonzeroLabelFn &&
667 &i != DFSanVarargWrapperFn)
668 FnsToInstrument.push_back(&i);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000669 }
670
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000671 // Give function aliases prefixes when necessary, and build wrappers where the
672 // instrumentedness is inconsistent.
Peter Collingbourne59b12622013-08-22 20:08:08 +0000673 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
674 GlobalAlias *GA = &*i;
675 ++i;
676 // Don't stop on weak. We assume people aren't playing games with the
677 // instrumentedness of overridden weak aliases.
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000678 if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000679 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
680 if (GAInst && FInst) {
681 addGlobalNamePrefix(GA);
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000682 } else if (GAInst != FInst) {
683 // Non-instrumented alias of an instrumented function, or vice versa.
684 // Replace the alias with a native-ABI wrapper of the aliasee. The pass
685 // below will take care of instrumenting it.
686 Function *NewF =
687 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000688 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000689 NewF->takeName(GA);
690 GA->eraseFromParent();
691 FnsToInstrument.push_back(NewF);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000692 }
693 }
694 }
695
Reid Kleckneree4930b2017-05-02 22:07:37 +0000696 ReadOnlyNoneAttrs.addAttribute(Attribute::ReadOnly)
697 .addAttribute(Attribute::ReadNone);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000698
699 // First, change the ABI of every function in the module. ABI-listed
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000700 // functions keep their original ABI and get a wrapper function.
701 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
702 e = FnsToInstrument.end();
703 i != e; ++i) {
704 Function &F = **i;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000705 FunctionType *FT = F.getFunctionType();
Peter Collingbourne68162e72013-08-14 18:54:12 +0000706
Peter Collingbourne59b12622013-08-22 20:08:08 +0000707 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
708 FT->getReturnType()->isVoidTy());
Peter Collingbourne68162e72013-08-14 18:54:12 +0000709
710 if (isInstrumented(&F)) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000711 // Instrumented functions get a 'dfs$' prefix. This allows us to more
712 // easily identify cases of mismatching ABIs.
713 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000714 FunctionType *NewFT = getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000715 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000716 NewF->copyAttributesFrom(&F);
717 NewF->removeAttributes(
Reid Klecknerb5180542017-03-21 16:57:19 +0000718 AttributeList::ReturnIndex,
Reid Kleckneree4930b2017-05-02 22:07:37 +0000719 AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000720 for (Function::arg_iterator FArg = F.arg_begin(),
721 NewFArg = NewF->arg_begin(),
722 FArgEnd = F.arg_end();
723 FArg != FArgEnd; ++FArg, ++NewFArg) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000724 FArg->replaceAllUsesWith(&*NewFArg);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000725 }
726 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
727
Chandler Carruthcdf47882014-03-09 03:16:01 +0000728 for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
729 UI != UE;) {
730 BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
731 ++UI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000732 if (BA) {
733 BA->replaceAllUsesWith(
734 BlockAddress::get(NewF, BA->getBasicBlock()));
735 delete BA;
736 }
737 }
738 F.replaceAllUsesWith(
739 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
740 NewF->takeName(&F);
741 F.eraseFromParent();
742 *i = NewF;
Peter Collingbourne59b12622013-08-22 20:08:08 +0000743 addGlobalNamePrefix(NewF);
744 } else {
745 addGlobalNamePrefix(&F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000746 }
Peter Collingbourne59b12622013-08-22 20:08:08 +0000747 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000748 // Build a wrapper function for F. The wrapper simply calls F, and is
749 // added to FnsToInstrument so that any instrumentation according to its
750 // WrapperKind is done in the second pass below.
751 FunctionType *NewFT = getInstrumentedABI() == IA_Args
752 ? getArgsFunctionType(FT)
753 : FT;
Alexey Samsonov6dae24d2013-08-23 07:42:51 +0000754 Function *NewF = buildWrapperFunction(
755 &F, std::string("dfsw$") + std::string(F.getName()),
756 GlobalValue::LinkOnceODRLinkage, NewFT);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000757 if (getInstrumentedABI() == IA_TLS)
Reid Klecknerb5180542017-03-21 16:57:19 +0000758 NewF->removeAttributes(AttributeList::FunctionIndex, ReadOnlyNoneAttrs);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000759
Peter Collingbourne68162e72013-08-14 18:54:12 +0000760 Value *WrappedFnCst =
761 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
762 F.replaceAllUsesWith(WrappedFnCst);
David Blaikiec6c6c7b2014-10-07 22:59:46 +0000763
Peter Collingbourne68162e72013-08-14 18:54:12 +0000764 UnwrappedFnMap[WrappedFnCst] = &F;
765 *i = NewF;
766
767 if (!F.isDeclaration()) {
768 // This function is probably defining an interposition of an
769 // uninstrumented function and hence needs to keep the original ABI.
770 // But any functions it may call need to use the instrumented ABI, so
771 // we instrument it in a mode which preserves the original ABI.
772 FnsWithNativeABI.insert(&F);
773
774 // This code needs to rebuild the iterators, as they may be invalidated
775 // by the push_back, taking care that the new range does not include
776 // any functions added by this code.
777 size_t N = i - FnsToInstrument.begin(),
778 Count = e - FnsToInstrument.begin();
779 FnsToInstrument.push_back(&F);
780 i = FnsToInstrument.begin() + N;
781 e = FnsToInstrument.begin() + Count;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000782 }
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +0000783 // Hopefully, nobody will try to indirectly call a vararg
784 // function... yet.
785 } else if (FT->isVarArg()) {
786 UnwrappedFnMap[&F] = &F;
787 *i = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000788 }
789 }
790
Benjamin Kramer135f7352016-06-26 12:28:59 +0000791 for (Function *i : FnsToInstrument) {
792 if (!i || i->isDeclaration())
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000793 continue;
794
Benjamin Kramer135f7352016-06-26 12:28:59 +0000795 removeUnreachableBlocks(*i);
Peter Collingbourneae66d572013-08-09 21:42:53 +0000796
Benjamin Kramer135f7352016-06-26 12:28:59 +0000797 DFSanFunction DFSF(*this, i, FnsWithNativeABI.count(i));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000798
799 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
800 // Build a copy of the list before iterating over it.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000801 llvm::SmallVector<BasicBlock *, 4> BBList(depth_first(&i->getEntryBlock()));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000802
Benjamin Kramer135f7352016-06-26 12:28:59 +0000803 for (BasicBlock *i : BBList) {
804 Instruction *Inst = &i->front();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000805 while (1) {
806 // DFSanVisitor may split the current basic block, changing the current
807 // instruction's next pointer and moving the next instruction to the
808 // tail block from which we should continue.
809 Instruction *Next = Inst->getNextNode();
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000810 // DFSanVisitor may delete Inst, so keep track of whether it was a
811 // terminator.
812 bool IsTerminator = isa<TerminatorInst>(Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000813 if (!DFSF.SkipInsts.count(Inst))
814 DFSanVisitor(DFSF).visit(Inst);
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000815 if (IsTerminator)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000816 break;
817 Inst = Next;
818 }
819 }
820
Peter Collingbourne68162e72013-08-14 18:54:12 +0000821 // We will not necessarily be able to compute the shadow for every phi node
822 // until we have visited every block. Therefore, the code that handles phi
823 // nodes adds them to the PHIFixups list so that they can be properly
824 // handled here.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000825 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
826 i = DFSF.PHIFixups.begin(),
827 e = DFSF.PHIFixups.end();
828 i != e; ++i) {
829 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
830 ++val) {
831 i->second->setIncomingValue(
832 val, DFSF.getShadow(i->first->getIncomingValue(val)));
833 }
834 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000835
836 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
837 // places (i.e. instructions in basic blocks we haven't even begun visiting
838 // yet). To make our life easier, do this work in a pass after the main
839 // instrumentation.
840 if (ClDebugNonzeroLabels) {
Peter Collingbournefab565a2014-08-22 01:18:18 +0000841 for (Value *V : DFSF.NonZeroChecks) {
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000842 Instruction *Pos;
Peter Collingbournefab565a2014-08-22 01:18:18 +0000843 if (Instruction *I = dyn_cast<Instruction>(V))
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000844 Pos = I->getNextNode();
845 else
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000846 Pos = &DFSF.F->getEntryBlock().front();
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000847 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
848 Pos = Pos->getNextNode();
849 IRBuilder<> IRB(Pos);
Peter Collingbournefab565a2014-08-22 01:18:18 +0000850 Value *Ne = IRB.CreateICmpNE(V, DFSF.DFS.ZeroShadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000851 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000852 Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000853 IRBuilder<> ThenIRB(BI);
David Blaikieff6409d2015-05-18 22:13:54 +0000854 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn, {});
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000855 }
856 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000857 }
858
859 return false;
860}
861
862Value *DFSanFunction::getArgTLSPtr() {
863 if (ArgTLSPtr)
864 return ArgTLSPtr;
865 if (DFS.ArgTLS)
866 return ArgTLSPtr = DFS.ArgTLS;
867
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000868 IRBuilder<> IRB(&F->getEntryBlock().front());
David Blaikieff6409d2015-05-18 22:13:54 +0000869 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS, {});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000870}
871
872Value *DFSanFunction::getRetvalTLS() {
873 if (RetvalTLSPtr)
874 return RetvalTLSPtr;
875 if (DFS.RetvalTLS)
876 return RetvalTLSPtr = DFS.RetvalTLS;
877
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000878 IRBuilder<> IRB(&F->getEntryBlock().front());
David Blaikieff6409d2015-05-18 22:13:54 +0000879 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS, {});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000880}
881
882Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
883 IRBuilder<> IRB(Pos);
884 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
885}
886
887Value *DFSanFunction::getShadow(Value *V) {
888 if (!isa<Argument>(V) && !isa<Instruction>(V))
889 return DFS.ZeroShadow;
890 Value *&Shadow = ValShadowMap[V];
891 if (!Shadow) {
892 if (Argument *A = dyn_cast<Argument>(V)) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000893 if (IsNativeABI)
894 return DFS.ZeroShadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000895 switch (IA) {
896 case DataFlowSanitizer::IA_TLS: {
897 Value *ArgTLSPtr = getArgTLSPtr();
898 Instruction *ArgTLSPos =
899 DFS.ArgTLS ? &*F->getEntryBlock().begin()
900 : cast<Instruction>(ArgTLSPtr)->getNextNode();
901 IRBuilder<> IRB(ArgTLSPos);
902 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
903 break;
904 }
905 case DataFlowSanitizer::IA_Args: {
Reid Kleckner45707d42017-03-16 22:59:15 +0000906 unsigned ArgIdx = A->getArgNo() + F->arg_size() / 2;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000907 Function::arg_iterator i = F->arg_begin();
908 while (ArgIdx--)
909 ++i;
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000910 Shadow = &*i;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000911 assert(Shadow->getType() == DFS.ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000912 break;
913 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000914 }
Peter Collingbournefab565a2014-08-22 01:18:18 +0000915 NonZeroChecks.push_back(Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000916 } else {
917 Shadow = DFS.ZeroShadow;
918 }
919 }
920 return Shadow;
921}
922
923void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
924 assert(!ValShadowMap.count(I));
925 assert(Shadow->getType() == DFS.ShadowTy);
926 ValShadowMap[I] = Shadow;
927}
928
929Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
930 assert(Addr != RetvalTLS && "Reinstrumenting?");
931 IRBuilder<> IRB(Pos);
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000932 Value *ShadowPtrMaskValue;
933 if (DFSanRuntimeShadowMask)
934 ShadowPtrMaskValue = IRB.CreateLoad(IntptrTy, ExternalShadowMask);
935 else
936 ShadowPtrMaskValue = ShadowPtrMask;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000937 return IRB.CreateIntToPtr(
938 IRB.CreateMul(
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000939 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy),
940 IRB.CreatePtrToInt(ShadowPtrMaskValue, IntptrTy)),
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000941 ShadowPtrMul),
942 ShadowPtrTy);
943}
944
945// Generates IR to compute the union of the two given shadows, inserting it
946// before Pos. Returns the computed union Value.
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000947Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
948 if (V1 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000949 return V2;
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000950 if (V2 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000951 return V1;
952 if (V1 == V2)
953 return V1;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000954
Peter Collingbourne9947c492014-07-15 22:13:19 +0000955 auto V1Elems = ShadowElements.find(V1);
956 auto V2Elems = ShadowElements.find(V2);
957 if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
958 if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
959 V2Elems->second.begin(), V2Elems->second.end())) {
960 return V1;
961 } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
962 V1Elems->second.begin(), V1Elems->second.end())) {
963 return V2;
964 }
965 } else if (V1Elems != ShadowElements.end()) {
966 if (V1Elems->second.count(V2))
967 return V1;
968 } else if (V2Elems != ShadowElements.end()) {
969 if (V2Elems->second.count(V1))
970 return V2;
971 }
972
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000973 auto Key = std::make_pair(V1, V2);
974 if (V1 > V2)
975 std::swap(Key.first, Key.second);
976 CachedCombinedShadow &CCS = CachedCombinedShadows[Key];
977 if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
978 return CCS.Shadow;
979
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000980 IRBuilder<> IRB(Pos);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000981 if (AvoidNewBlocks) {
David Blaikieff6409d2015-05-18 22:13:54 +0000982 CallInst *Call = IRB.CreateCall(DFS.DFSanCheckedUnionFn, {V1, V2});
Reid Klecknerb5180542017-03-21 16:57:19 +0000983 Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Reid Klecknera0b45f42017-05-03 18:17:31 +0000984 Call->addParamAttr(0, Attribute::ZExt);
985 Call->addParamAttr(1, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000986
Peter Collingbournedf240b22014-08-06 00:33:40 +0000987 CCS.Block = Pos->getParent();
988 CCS.Shadow = Call;
989 } else {
990 BasicBlock *Head = Pos->getParent();
991 Value *Ne = IRB.CreateICmpNE(V1, V2);
992 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
993 Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
994 IRBuilder<> ThenIRB(BI);
David Blaikieff6409d2015-05-18 22:13:54 +0000995 CallInst *Call = ThenIRB.CreateCall(DFS.DFSanUnionFn, {V1, V2});
Reid Klecknerb5180542017-03-21 16:57:19 +0000996 Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Reid Klecknera0b45f42017-05-03 18:17:31 +0000997 Call->addParamAttr(0, Attribute::ZExt);
998 Call->addParamAttr(1, Attribute::ZExt);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000999
Peter Collingbournedf240b22014-08-06 00:33:40 +00001000 BasicBlock *Tail = BI->getSuccessor(0);
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001001 PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
Peter Collingbournedf240b22014-08-06 00:33:40 +00001002 Phi->addIncoming(Call, Call->getParent());
1003 Phi->addIncoming(V1, Head);
1004
1005 CCS.Block = Tail;
1006 CCS.Shadow = Phi;
1007 }
Peter Collingbourne9947c492014-07-15 22:13:19 +00001008
1009 std::set<Value *> UnionElems;
1010 if (V1Elems != ShadowElements.end()) {
1011 UnionElems = V1Elems->second;
1012 } else {
1013 UnionElems.insert(V1);
1014 }
1015 if (V2Elems != ShadowElements.end()) {
1016 UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
1017 } else {
1018 UnionElems.insert(V2);
1019 }
Peter Collingbournedf240b22014-08-06 00:33:40 +00001020 ShadowElements[CCS.Shadow] = std::move(UnionElems);
Peter Collingbourne9947c492014-07-15 22:13:19 +00001021
Peter Collingbournedf240b22014-08-06 00:33:40 +00001022 return CCS.Shadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001023}
1024
1025// A convenience function which folds the shadows of each of the operands
1026// of the provided instruction Inst, inserting the IR before Inst. Returns
1027// the computed union Value.
1028Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
1029 if (Inst->getNumOperands() == 0)
1030 return DFS.ZeroShadow;
1031
1032 Value *Shadow = getShadow(Inst->getOperand(0));
1033 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001034 Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001035 }
1036 return Shadow;
1037}
1038
1039void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
1040 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1041 DFSF.setShadow(&I, CombinedShadow);
1042}
1043
1044// Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
1045// Addr has alignment Align, and take the union of each of those shadows.
1046Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
1047 Instruction *Pos) {
1048 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1049 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1050 AllocaShadowMap.find(AI);
1051 if (i != AllocaShadowMap.end()) {
1052 IRBuilder<> IRB(Pos);
1053 return IRB.CreateLoad(i->second);
1054 }
1055 }
1056
1057 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1058 SmallVector<Value *, 2> Objs;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001059 GetUnderlyingObjects(Addr, Objs, Pos->getModule()->getDataLayout());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001060 bool AllConstants = true;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001061 for (Value *Obj : Objs) {
1062 if (isa<Function>(Obj) || isa<BlockAddress>(Obj))
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001063 continue;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001064 if (isa<GlobalVariable>(Obj) && cast<GlobalVariable>(Obj)->isConstant())
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001065 continue;
1066
1067 AllConstants = false;
1068 break;
1069 }
1070 if (AllConstants)
1071 return DFS.ZeroShadow;
1072
1073 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1074 switch (Size) {
1075 case 0:
1076 return DFS.ZeroShadow;
1077 case 1: {
1078 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
1079 LI->setAlignment(ShadowAlign);
1080 return LI;
1081 }
1082 case 2: {
1083 IRBuilder<> IRB(Pos);
David Blaikie93c54442015-04-03 19:41:44 +00001084 Value *ShadowAddr1 = IRB.CreateGEP(DFS.ShadowTy, ShadowAddr,
1085 ConstantInt::get(DFS.IntptrTy, 1));
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001086 return combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
1087 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign), Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001088 }
1089 }
Peter Collingbournedf240b22014-08-06 00:33:40 +00001090 if (!AvoidNewBlocks && Size % (64 / DFS.ShadowWidth) == 0) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001091 // Fast path for the common case where each byte has identical shadow: load
1092 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
1093 // shadow is non-equal.
1094 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
1095 IRBuilder<> FallbackIRB(FallbackBB);
David Blaikieff6409d2015-05-18 22:13:54 +00001096 CallInst *FallbackCall = FallbackIRB.CreateCall(
1097 DFS.DFSanUnionLoadFn,
1098 {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
Reid Klecknerb5180542017-03-21 16:57:19 +00001099 FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001100
1101 // Compare each of the shadows stored in the loaded 64 bits to each other,
1102 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
1103 IRBuilder<> IRB(Pos);
1104 Value *WideAddr =
1105 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1106 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1107 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
1108 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
1109 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
1110 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1111 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1112
1113 BasicBlock *Head = Pos->getParent();
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001114 BasicBlock *Tail = Head->splitBasicBlock(Pos->getIterator());
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001115
1116 if (DomTreeNode *OldNode = DT.getNode(Head)) {
1117 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1118
1119 DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1120 for (auto Child : Children)
1121 DT.changeImmediateDominator(Child, NewNode);
1122 }
1123
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001124 // In the following code LastBr will refer to the previous basic block's
1125 // conditional branch instruction, whose true successor is fixed up to point
1126 // to the next block during the loop below or to the tail after the final
1127 // iteration.
1128 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1129 ReplaceInstWithInst(Head->getTerminator(), LastBr);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001130 DT.addNewBlock(FallbackBB, Head);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001131
1132 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
1133 Ofs += 64 / DFS.ShadowWidth) {
1134 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001135 DT.addNewBlock(NextBB, LastBr->getParent());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001136 IRBuilder<> NextIRB(NextBB);
David Blaikie93c54442015-04-03 19:41:44 +00001137 WideAddr = NextIRB.CreateGEP(Type::getInt64Ty(*DFS.Ctx), WideAddr,
1138 ConstantInt::get(DFS.IntptrTy, 1));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001139 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1140 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1141 LastBr->setSuccessor(0, NextBB);
1142 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1143 }
1144
1145 LastBr->setSuccessor(0, Tail);
1146 FallbackIRB.CreateBr(Tail);
1147 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1148 Shadow->addIncoming(FallbackCall, FallbackBB);
1149 Shadow->addIncoming(TruncShadow, LastBr->getParent());
1150 return Shadow;
1151 }
1152
1153 IRBuilder<> IRB(Pos);
David Blaikieff6409d2015-05-18 22:13:54 +00001154 CallInst *FallbackCall = IRB.CreateCall(
1155 DFS.DFSanUnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
Reid Klecknerb5180542017-03-21 16:57:19 +00001156 FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001157 return FallbackCall;
1158}
1159
1160void DFSanVisitor::visitLoadInst(LoadInst &LI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001161 auto &DL = LI.getModule()->getDataLayout();
1162 uint64_t Size = DL.getTypeStoreSize(LI.getType());
Peter Collingbourne142fdff2014-08-01 21:18:18 +00001163 if (Size == 0) {
1164 DFSF.setShadow(&LI, DFSF.DFS.ZeroShadow);
1165 return;
1166 }
1167
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001168 uint64_t Align;
1169 if (ClPreserveAlignment) {
1170 Align = LI.getAlignment();
1171 if (Align == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001172 Align = DL.getABITypeAlignment(LI.getType());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001173 } else {
1174 Align = 1;
1175 }
1176 IRBuilder<> IRB(&LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001177 Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
1178 if (ClCombinePointerLabelsOnLoad) {
1179 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001180 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001181 }
1182 if (Shadow != DFSF.DFS.ZeroShadow)
Peter Collingbournefab565a2014-08-22 01:18:18 +00001183 DFSF.NonZeroChecks.push_back(Shadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +00001184
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001185 DFSF.setShadow(&LI, Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001186}
1187
1188void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
1189 Value *Shadow, Instruction *Pos) {
1190 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1191 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1192 AllocaShadowMap.find(AI);
1193 if (i != AllocaShadowMap.end()) {
1194 IRBuilder<> IRB(Pos);
1195 IRB.CreateStore(Shadow, i->second);
1196 return;
1197 }
1198 }
1199
1200 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1201 IRBuilder<> IRB(Pos);
1202 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1203 if (Shadow == DFS.ZeroShadow) {
1204 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1205 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1206 Value *ExtShadowAddr =
1207 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1208 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1209 return;
1210 }
1211
1212 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1213 uint64_t Offset = 0;
1214 if (Size >= ShadowVecSize) {
1215 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1216 Value *ShadowVec = UndefValue::get(ShadowVecTy);
1217 for (unsigned i = 0; i != ShadowVecSize; ++i) {
1218 ShadowVec = IRB.CreateInsertElement(
1219 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1220 }
1221 Value *ShadowVecAddr =
1222 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1223 do {
David Blaikie95d3e532015-04-03 23:03:54 +00001224 Value *CurShadowVecAddr =
1225 IRB.CreateConstGEP1_32(ShadowVecTy, ShadowVecAddr, Offset);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001226 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1227 Size -= ShadowVecSize;
1228 ++Offset;
1229 } while (Size >= ShadowVecSize);
1230 Offset *= ShadowVecSize;
1231 }
1232 while (Size > 0) {
David Blaikie95d3e532015-04-03 23:03:54 +00001233 Value *CurShadowAddr =
1234 IRB.CreateConstGEP1_32(DFS.ShadowTy, ShadowAddr, Offset);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001235 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1236 --Size;
1237 ++Offset;
1238 }
1239}
1240
1241void DFSanVisitor::visitStoreInst(StoreInst &SI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001242 auto &DL = SI.getModule()->getDataLayout();
1243 uint64_t Size = DL.getTypeStoreSize(SI.getValueOperand()->getType());
Peter Collingbourne142fdff2014-08-01 21:18:18 +00001244 if (Size == 0)
1245 return;
1246
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001247 uint64_t Align;
1248 if (ClPreserveAlignment) {
1249 Align = SI.getAlignment();
1250 if (Align == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001251 Align = DL.getABITypeAlignment(SI.getValueOperand()->getType());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001252 } else {
1253 Align = 1;
1254 }
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001255
1256 Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1257 if (ClCombinePointerLabelsOnStore) {
1258 Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001259 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001260 }
1261 DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001262}
1263
1264void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1265 visitOperandShadowInst(BO);
1266}
1267
1268void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1269
1270void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1271
1272void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1273 visitOperandShadowInst(GEPI);
1274}
1275
1276void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1277 visitOperandShadowInst(I);
1278}
1279
1280void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1281 visitOperandShadowInst(I);
1282}
1283
1284void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1285 visitOperandShadowInst(I);
1286}
1287
1288void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1289 visitOperandShadowInst(I);
1290}
1291
1292void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1293 visitOperandShadowInst(I);
1294}
1295
1296void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1297 bool AllLoadsStores = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001298 for (User *U : I.users()) {
1299 if (isa<LoadInst>(U))
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001300 continue;
1301
Chandler Carruthcdf47882014-03-09 03:16:01 +00001302 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001303 if (SI->getPointerOperand() == &I)
1304 continue;
1305 }
1306
1307 AllLoadsStores = false;
1308 break;
1309 }
1310 if (AllLoadsStores) {
1311 IRBuilder<> IRB(&I);
1312 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1313 }
1314 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1315}
1316
1317void DFSanVisitor::visitSelectInst(SelectInst &I) {
1318 Value *CondShadow = DFSF.getShadow(I.getCondition());
1319 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1320 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1321
1322 if (isa<VectorType>(I.getCondition()->getType())) {
1323 DFSF.setShadow(
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001324 &I,
1325 DFSF.combineShadows(
1326 CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001327 } else {
1328 Value *ShadowSel;
1329 if (TrueShadow == FalseShadow) {
1330 ShadowSel = TrueShadow;
1331 } else {
1332 ShadowSel =
1333 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1334 }
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001335 DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001336 }
1337}
1338
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +00001339void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1340 IRBuilder<> IRB(&I);
1341 Value *ValShadow = DFSF.getShadow(I.getValue());
David Blaikieff6409d2015-05-18 22:13:54 +00001342 IRB.CreateCall(DFSF.DFS.DFSanSetLabelFn,
1343 {ValShadow, IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(
1344 *DFSF.DFS.Ctx)),
1345 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +00001346}
1347
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001348void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1349 IRBuilder<> IRB(&I);
1350 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1351 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1352 Value *LenShadow = IRB.CreateMul(
1353 I.getLength(),
1354 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
Pete Cooper67cf9a72015-11-19 05:56:52 +00001355 Value *AlignShadow;
1356 if (ClPreserveAlignment) {
1357 AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1358 ConstantInt::get(I.getAlignmentCst()->getType(),
1359 DFSF.DFS.ShadowWidth / 8));
1360 } else {
1361 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1362 DFSF.DFS.ShadowWidth / 8);
1363 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001364 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1365 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1366 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
Pete Cooper67cf9a72015-11-19 05:56:52 +00001367 IRB.CreateCall(I.getCalledValue(), {DestShadow, SrcShadow, LenShadow,
1368 AlignShadow, I.getVolatileCst()});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001369}
1370
1371void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001372 if (!DFSF.IsNativeABI && RI.getReturnValue()) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001373 switch (DFSF.IA) {
1374 case DataFlowSanitizer::IA_TLS: {
1375 Value *S = DFSF.getShadow(RI.getReturnValue());
1376 IRBuilder<> IRB(&RI);
1377 IRB.CreateStore(S, DFSF.getRetvalTLS());
1378 break;
1379 }
1380 case DataFlowSanitizer::IA_Args: {
1381 IRBuilder<> IRB(&RI);
1382 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1383 Value *InsVal =
1384 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1385 Value *InsShadow =
1386 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1387 RI.setOperand(0, InsShadow);
1388 break;
1389 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001390 }
1391 }
1392}
1393
1394void DFSanVisitor::visitCallSite(CallSite CS) {
1395 Function *F = CS.getCalledFunction();
1396 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1397 visitOperandShadowInst(*CS.getInstruction());
1398 return;
1399 }
1400
Peter Collingbournea1099842014-11-05 17:21:00 +00001401 // Calls to this function are synthesized in wrappers, and we shouldn't
1402 // instrument them.
1403 if (F == DFSF.DFS.DFSanVarargWrapperFn)
1404 return;
1405
Peter Collingbourne68162e72013-08-14 18:54:12 +00001406 IRBuilder<> IRB(CS.getInstruction());
1407
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001408 DenseMap<Value *, Function *>::iterator i =
1409 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1410 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001411 Function *F = i->second;
1412 switch (DFSF.DFS.getWrapperKind(F)) {
1413 case DataFlowSanitizer::WK_Warning: {
1414 CS.setCalledFunction(F);
1415 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1416 IRB.CreateGlobalStringPtr(F->getName()));
1417 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1418 return;
1419 }
1420 case DataFlowSanitizer::WK_Discard: {
1421 CS.setCalledFunction(F);
1422 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1423 return;
1424 }
1425 case DataFlowSanitizer::WK_Functional: {
1426 CS.setCalledFunction(F);
1427 visitOperandShadowInst(*CS.getInstruction());
1428 return;
1429 }
1430 case DataFlowSanitizer::WK_Custom: {
1431 // Don't try to handle invokes of custom functions, it's too complicated.
1432 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1433 // wrapper.
1434 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1435 FunctionType *FT = F->getFunctionType();
1436 FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1437 std::string CustomFName = "__dfsw_";
1438 CustomFName += F->getName();
1439 Constant *CustomF =
1440 DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1441 if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1442 CustomFn->copyAttributesFrom(F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001443
Peter Collingbourne68162e72013-08-14 18:54:12 +00001444 // Custom functions returning non-void will write to the return label.
1445 if (!FT->getReturnType()->isVoidTy()) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001446 CustomFn->removeAttributes(AttributeList::FunctionIndex,
Peter Collingbourne68162e72013-08-14 18:54:12 +00001447 DFSF.DFS.ReadOnlyNoneAttrs);
1448 }
1449 }
1450
1451 std::vector<Value *> Args;
1452
1453 CallSite::arg_iterator i = CS.arg_begin();
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001454 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +00001455 Type *T = (*i)->getType();
1456 FunctionType *ParamFT;
1457 if (isa<PointerType>(T) &&
1458 (ParamFT = dyn_cast<FunctionType>(
1459 cast<PointerType>(T)->getElementType()))) {
1460 std::string TName = "dfst";
1461 TName += utostr(FT->getNumParams() - n);
1462 TName += "$";
1463 TName += F->getName();
1464 Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1465 Args.push_back(T);
1466 Args.push_back(
1467 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1468 } else {
1469 Args.push_back(*i);
1470 }
1471 }
Peter Collingbourne68162e72013-08-14 18:54:12 +00001472
1473 i = CS.arg_begin();
Simon Dardisb5205c62017-08-17 14:14:25 +00001474 const unsigned ShadowArgStart = Args.size();
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001475 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
Peter Collingbourne68162e72013-08-14 18:54:12 +00001476 Args.push_back(DFSF.getShadow(*i));
1477
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001478 if (FT->isVarArg()) {
David Blaikie1b01e7e2015-04-05 22:44:57 +00001479 auto *LabelVATy = ArrayType::get(DFSF.DFS.ShadowTy,
1480 CS.arg_size() - FT->getNumParams());
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001481 auto *LabelVAAlloca = new AllocaInst(
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001482 LabelVATy, getDataLayout().getAllocaAddrSpace(),
1483 "labelva", &DFSF.F->getEntryBlock().front());
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001484
1485 for (unsigned n = 0; i != CS.arg_end(); ++i, ++n) {
David Blaikie64646022015-04-05 22:41:44 +00001486 auto LabelVAPtr = IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, n);
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001487 IRB.CreateStore(DFSF.getShadow(*i), LabelVAPtr);
1488 }
1489
David Blaikie64646022015-04-05 22:41:44 +00001490 Args.push_back(IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, 0));
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001491 }
1492
Peter Collingbourne68162e72013-08-14 18:54:12 +00001493 if (!FT->getReturnType()->isVoidTy()) {
1494 if (!DFSF.LabelReturnAlloca) {
1495 DFSF.LabelReturnAlloca =
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001496 new AllocaInst(DFSF.DFS.ShadowTy,
1497 getDataLayout().getAllocaAddrSpace(),
1498 "labelreturn", &DFSF.F->getEntryBlock().front());
Peter Collingbourne68162e72013-08-14 18:54:12 +00001499 }
1500 Args.push_back(DFSF.LabelReturnAlloca);
1501 }
1502
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001503 for (i = CS.arg_begin() + FT->getNumParams(); i != CS.arg_end(); ++i)
1504 Args.push_back(*i);
1505
Peter Collingbourne68162e72013-08-14 18:54:12 +00001506 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1507 CustomCI->setCallingConv(CI->getCallingConv());
1508 CustomCI->setAttributes(CI->getAttributes());
1509
Simon Dardisb5205c62017-08-17 14:14:25 +00001510 // Update the parameter attributes of the custom call instruction to
1511 // zero extend the shadow parameters. This is required for targets
1512 // which consider ShadowTy an illegal type.
1513 for (unsigned n = 0; n < FT->getNumParams(); n++) {
1514 const unsigned ArgNo = ShadowArgStart + n;
1515 if (CustomCI->getArgOperand(ArgNo)->getType() == DFSF.DFS.ShadowTy)
1516 CustomCI->addParamAttr(ArgNo, Attribute::ZExt);
1517 }
1518
Peter Collingbourne68162e72013-08-14 18:54:12 +00001519 if (!FT->getReturnType()->isVoidTy()) {
1520 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1521 DFSF.setShadow(CustomCI, LabelLoad);
1522 }
1523
1524 CI->replaceAllUsesWith(CustomCI);
1525 CI->eraseFromParent();
1526 return;
1527 }
1528 break;
1529 }
1530 }
1531 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001532
1533 FunctionType *FT = cast<FunctionType>(
1534 CS.getCalledValue()->getType()->getPointerElementType());
Peter Collingbourne68162e72013-08-14 18:54:12 +00001535 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001536 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1537 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1538 DFSF.getArgTLS(i, CS.getInstruction()));
1539 }
1540 }
1541
Craig Topperf40110f2014-04-25 05:29:35 +00001542 Instruction *Next = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001543 if (!CS.getType()->isVoidTy()) {
1544 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1545 if (II->getNormalDest()->getSinglePredecessor()) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001546 Next = &II->getNormalDest()->front();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001547 } else {
1548 BasicBlock *NewBB =
Chandler Carruthd4500562015-01-19 12:36:53 +00001549 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001550 Next = &NewBB->front();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001551 }
1552 } else {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001553 assert(CS->getIterator() != CS->getParent()->end());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001554 Next = CS->getNextNode();
1555 }
1556
Peter Collingbourne68162e72013-08-14 18:54:12 +00001557 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001558 IRBuilder<> NextIRB(Next);
1559 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1560 DFSF.SkipInsts.insert(LI);
1561 DFSF.setShadow(CS.getInstruction(), LI);
Peter Collingbournefab565a2014-08-22 01:18:18 +00001562 DFSF.NonZeroChecks.push_back(LI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001563 }
1564 }
1565
1566 // Do all instrumentation for IA_Args down here to defer tampering with the
1567 // CFG in a way that SplitEdge may be able to detect.
Peter Collingbourne68162e72013-08-14 18:54:12 +00001568 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1569 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001570 Value *Func =
1571 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1572 std::vector<Value *> Args;
1573
1574 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1575 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1576 Args.push_back(*i);
1577
1578 i = CS.arg_begin();
1579 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1580 Args.push_back(DFSF.getShadow(*i));
1581
1582 if (FT->isVarArg()) {
1583 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1584 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1585 AllocaInst *VarArgShadow =
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001586 new AllocaInst(VarArgArrayTy, getDataLayout().getAllocaAddrSpace(),
1587 "", &DFSF.F->getEntryBlock().front());
David Blaikie4e5d47f42015-04-04 21:07:10 +00001588 Args.push_back(IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, 0));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001589 for (unsigned n = 0; i != e; ++i, ++n) {
David Blaikie4e5d47f42015-04-04 21:07:10 +00001590 IRB.CreateStore(
1591 DFSF.getShadow(*i),
1592 IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, n));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001593 Args.push_back(*i);
1594 }
1595 }
1596
1597 CallSite NewCS;
1598 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1599 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1600 Args);
1601 } else {
1602 NewCS = IRB.CreateCall(Func, Args);
1603 }
1604 NewCS.setCallingConv(CS.getCallingConv());
1605 NewCS.setAttributes(CS.getAttributes().removeAttributes(
Reid Klecknerb5180542017-03-21 16:57:19 +00001606 *DFSF.DFS.Ctx, AttributeList::ReturnIndex,
Pete Cooper2777d8872015-05-06 23:19:56 +00001607 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType())));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001608
1609 if (Next) {
1610 ExtractValueInst *ExVal =
1611 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1612 DFSF.SkipInsts.insert(ExVal);
1613 ExtractValueInst *ExShadow =
1614 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1615 DFSF.SkipInsts.insert(ExShadow);
1616 DFSF.setShadow(ExVal, ExShadow);
Peter Collingbournefab565a2014-08-22 01:18:18 +00001617 DFSF.NonZeroChecks.push_back(ExShadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001618
1619 CS.getInstruction()->replaceAllUsesWith(ExVal);
1620 }
1621
1622 CS.getInstruction()->eraseFromParent();
1623 }
1624}
1625
1626void DFSanVisitor::visitPHINode(PHINode &PN) {
1627 PHINode *ShadowPN =
1628 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1629
1630 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1631 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1632 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1633 ++i) {
1634 ShadowPN->addIncoming(UndefShadow, *i);
1635 }
1636
1637 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1638 DFSF.setShadow(&PN, ShadowPN);
1639}