blob: 4e454f0c95b6598b69921a79b1f25ba592988216 [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 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) ||
158 SCL->inSection("fun", F.getName(), Category);
159 }
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()))
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000170 return SCL->inSection("fun", GA.getName(), Category);
171
172 return SCL->inSection("global", GA.getName(), Category) ||
173 SCL->inSection("type", GetGlobalTypeString(GA), Category);
174 }
175
176 /// Returns whether this module is listed in the given category.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000177 bool isIn(const Module &M, StringRef Category) const {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000178 return SCL->inSection("src", M.getModuleIdentifier(), Category);
179 }
180};
181
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000182class DataFlowSanitizer : public ModulePass {
183 friend struct DFSanFunction;
184 friend class DFSanVisitor;
185
186 enum {
187 ShadowWidth = 16
188 };
189
Peter Collingbourne68162e72013-08-14 18:54:12 +0000190 /// Which ABI should be used for instrumented functions?
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000191 enum InstrumentedABI {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000192 /// Argument and return value labels are passed through additional
193 /// arguments and by modifying the return type.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000194 IA_Args,
Peter Collingbourne68162e72013-08-14 18:54:12 +0000195
196 /// Argument and return value labels are passed through TLS variables
197 /// __dfsan_arg_tls and __dfsan_retval_tls.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000198 IA_TLS
199 };
200
Peter Collingbourne68162e72013-08-14 18:54:12 +0000201 /// How should calls to uninstrumented functions be handled?
202 enum WrapperKind {
203 /// This function is present in an uninstrumented form but we don't know
204 /// how it should be handled. Print a warning and call the function anyway.
205 /// Don't label the return value.
206 WK_Warning,
207
208 /// This function does not write to (user-accessible) memory, and its return
209 /// value is unlabelled.
210 WK_Discard,
211
212 /// This function does not write to (user-accessible) memory, and the label
213 /// of its return value is the union of the label of its arguments.
214 WK_Functional,
215
216 /// Instead of calling the function, a custom wrapper __dfsw_F is called,
217 /// where F is the name of the function. This function may wrap the
218 /// original function or provide its own implementation. This is similar to
219 /// the IA_Args ABI, except that IA_Args uses a struct return type to
220 /// pass the return value shadow in a register, while WK_Custom uses an
221 /// extra pointer argument to return the shadow. This allows the wrapped
222 /// form of the function type to be expressed in C.
223 WK_Custom
224 };
225
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000226 Module *Mod;
227 LLVMContext *Ctx;
228 IntegerType *ShadowTy;
229 PointerType *ShadowPtrTy;
230 IntegerType *IntptrTy;
231 ConstantInt *ZeroShadow;
232 ConstantInt *ShadowPtrMask;
233 ConstantInt *ShadowPtrMul;
234 Constant *ArgTLS;
235 Constant *RetvalTLS;
236 void *(*GetArgTLSPtr)();
237 void *(*GetRetvalTLSPtr)();
238 Constant *GetArgTLS;
239 Constant *GetRetvalTLS;
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000240 Constant *ExternalShadowMask;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000241 FunctionType *DFSanUnionFnTy;
242 FunctionType *DFSanUnionLoadFnTy;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000243 FunctionType *DFSanUnimplementedFnTy;
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000244 FunctionType *DFSanSetLabelFnTy;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000245 FunctionType *DFSanNonzeroLabelFnTy;
Peter Collingbournea1099842014-11-05 17:21:00 +0000246 FunctionType *DFSanVarargWrapperFnTy;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000247 Constant *DFSanUnionFn;
Peter Collingbournedf240b22014-08-06 00:33:40 +0000248 Constant *DFSanCheckedUnionFn;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000249 Constant *DFSanUnionLoadFn;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000250 Constant *DFSanUnimplementedFn;
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000251 Constant *DFSanSetLabelFn;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000252 Constant *DFSanNonzeroLabelFn;
Peter Collingbournea1099842014-11-05 17:21:00 +0000253 Constant *DFSanVarargWrapperFn;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000254 MDNode *ColdCallWeights;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000255 DFSanABIList ABIList;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000256 DenseMap<Value *, Function *> UnwrappedFnMap;
Reid Klecknerb5180542017-03-21 16:57:19 +0000257 AttributeList ReadOnlyNoneAttrs;
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000258 bool DFSanRuntimeShadowMask;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000259
260 Value *getShadowAddress(Value *Addr, Instruction *Pos);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000261 bool isInstrumented(const Function *F);
262 bool isInstrumented(const GlobalAlias *GA);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000263 FunctionType *getArgsFunctionType(FunctionType *T);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000264 FunctionType *getTrampolineFunctionType(FunctionType *T);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000265 FunctionType *getCustomFunctionType(FunctionType *T);
266 InstrumentedABI getInstrumentedABI();
267 WrapperKind getWrapperKind(Function *F);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000268 void addGlobalNamePrefix(GlobalValue *GV);
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000269 Function *buildWrapperFunction(Function *F, StringRef NewFName,
270 GlobalValue::LinkageTypes NewFLink,
271 FunctionType *NewFT);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000272 Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000273
Dmitry Vyukov96a70842013-08-13 16:52:41 +0000274 public:
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000275 DataFlowSanitizer(
276 const std::vector<std::string> &ABIListFiles = std::vector<std::string>(),
277 void *(*getArgTLS)() = nullptr, void *(*getRetValTLS)() = nullptr);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000278 static char ID;
Craig Topper3e4c6972014-03-05 09:10:37 +0000279 bool doInitialization(Module &M) override;
280 bool runOnModule(Module &M) override;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000281};
282
283struct DFSanFunction {
284 DataFlowSanitizer &DFS;
285 Function *F;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000286 DominatorTree DT;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000287 DataFlowSanitizer::InstrumentedABI IA;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000288 bool IsNativeABI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000289 Value *ArgTLSPtr;
290 Value *RetvalTLSPtr;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000291 AllocaInst *LabelReturnAlloca;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000292 DenseMap<Value *, Value *> ValShadowMap;
293 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
294 std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
295 DenseSet<Instruction *> SkipInsts;
Peter Collingbournefab565a2014-08-22 01:18:18 +0000296 std::vector<Value *> NonZeroChecks;
Peter Collingbournedf240b22014-08-06 00:33:40 +0000297 bool AvoidNewBlocks;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000298
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000299 struct CachedCombinedShadow {
300 BasicBlock *Block;
301 Value *Shadow;
302 };
303 DenseMap<std::pair<Value *, Value *>, CachedCombinedShadow>
304 CachedCombinedShadows;
Peter Collingbourne9947c492014-07-15 22:13:19 +0000305 DenseMap<Value *, std::set<Value *>> ShadowElements;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000306
Peter Collingbourne68162e72013-08-14 18:54:12 +0000307 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
308 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()),
Craig Topperf40110f2014-04-25 05:29:35 +0000309 IsNativeABI(IsNativeABI), ArgTLSPtr(nullptr), RetvalTLSPtr(nullptr),
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000310 LabelReturnAlloca(nullptr) {
311 DT.recalculate(*F);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000312 // FIXME: Need to track down the register allocator issue which causes poor
313 // performance in pathological cases with large numbers of basic blocks.
314 AvoidNewBlocks = F->size() > 1000;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000315 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000316 Value *getArgTLSPtr();
317 Value *getArgTLS(unsigned Index, Instruction *Pos);
318 Value *getRetvalTLS();
319 Value *getShadow(Value *V);
320 void setShadow(Instruction *I, Value *Shadow);
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000321 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000322 Value *combineOperandShadows(Instruction *Inst);
323 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
324 Instruction *Pos);
325 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
326 Instruction *Pos);
327};
328
329class DFSanVisitor : public InstVisitor<DFSanVisitor> {
Dmitry Vyukov96a70842013-08-13 16:52:41 +0000330 public:
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000331 DFSanFunction &DFSF;
332 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
333
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000334 const DataLayout &getDataLayout() const {
335 return DFSF.F->getParent()->getDataLayout();
336 }
337
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000338 void visitOperandShadowInst(Instruction &I);
339
340 void visitBinaryOperator(BinaryOperator &BO);
341 void visitCastInst(CastInst &CI);
342 void visitCmpInst(CmpInst &CI);
343 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
344 void visitLoadInst(LoadInst &LI);
345 void visitStoreInst(StoreInst &SI);
346 void visitReturnInst(ReturnInst &RI);
347 void visitCallSite(CallSite CS);
348 void visitPHINode(PHINode &PN);
349 void visitExtractElementInst(ExtractElementInst &I);
350 void visitInsertElementInst(InsertElementInst &I);
351 void visitShuffleVectorInst(ShuffleVectorInst &I);
352 void visitExtractValueInst(ExtractValueInst &I);
353 void visitInsertValueInst(InsertValueInst &I);
354 void visitAllocaInst(AllocaInst &I);
355 void visitSelectInst(SelectInst &I);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000356 void visitMemSetInst(MemSetInst &I);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000357 void visitMemTransferInst(MemTransferInst &I);
358};
359
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000360}
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000361
362char DataFlowSanitizer::ID;
363INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
364 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
365
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000366ModulePass *
367llvm::createDataFlowSanitizerPass(const std::vector<std::string> &ABIListFiles,
368 void *(*getArgTLS)(),
369 void *(*getRetValTLS)()) {
370 return new DataFlowSanitizer(ABIListFiles, getArgTLS, getRetValTLS);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000371}
372
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000373DataFlowSanitizer::DataFlowSanitizer(
374 const std::vector<std::string> &ABIListFiles, void *(*getArgTLS)(),
375 void *(*getRetValTLS)())
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000376 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS),
377 DFSanRuntimeShadowMask(false) {
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000378 std::vector<std::string> AllABIListFiles(std::move(ABIListFiles));
379 AllABIListFiles.insert(AllABIListFiles.end(), ClABIListFiles.begin(),
380 ClABIListFiles.end());
381 ABIList.set(SpecialCaseList::createOrDie(AllABIListFiles));
Peter Collingbourne68162e72013-08-14 18:54:12 +0000382}
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000383
Peter Collingbourne68162e72013-08-14 18:54:12 +0000384FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000385 llvm::SmallVector<Type *, 4> ArgTypes(T->param_begin(), T->param_end());
386 ArgTypes.append(T->getNumParams(), ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000387 if (T->isVarArg())
388 ArgTypes.push_back(ShadowPtrTy);
389 Type *RetType = T->getReturnType();
390 if (!RetType->isVoidTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000391 RetType = StructType::get(RetType, ShadowTy, (Type *)nullptr);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000392 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
393}
394
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000395FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
396 assert(!T->isVarArg());
397 llvm::SmallVector<Type *, 4> ArgTypes;
398 ArgTypes.push_back(T->getPointerTo());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000399 ArgTypes.append(T->param_begin(), T->param_end());
400 ArgTypes.append(T->getNumParams(), ShadowTy);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000401 Type *RetType = T->getReturnType();
402 if (!RetType->isVoidTy())
403 ArgTypes.push_back(ShadowPtrTy);
404 return FunctionType::get(T->getReturnType(), ArgTypes, false);
405}
406
Peter Collingbourne68162e72013-08-14 18:54:12 +0000407FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000408 llvm::SmallVector<Type *, 4> ArgTypes;
Alexey Samsonov9b7e2b52013-08-28 11:25:12 +0000409 for (FunctionType::param_iterator i = T->param_begin(), e = T->param_end();
410 i != e; ++i) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000411 FunctionType *FT;
Alexey Samsonov9b7e2b52013-08-28 11:25:12 +0000412 if (isa<PointerType>(*i) && (FT = dyn_cast<FunctionType>(cast<PointerType>(
413 *i)->getElementType()))) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000414 ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
415 ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
416 } else {
417 ArgTypes.push_back(*i);
418 }
419 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000420 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
421 ArgTypes.push_back(ShadowTy);
Peter Collingbournedd3486e2014-10-30 13:22:57 +0000422 if (T->isVarArg())
423 ArgTypes.push_back(ShadowPtrTy);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000424 Type *RetType = T->getReturnType();
425 if (!RetType->isVoidTy())
426 ArgTypes.push_back(ShadowPtrTy);
Peter Collingbournedd3486e2014-10-30 13:22:57 +0000427 return FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg());
Peter Collingbourne68162e72013-08-14 18:54:12 +0000428}
429
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000430bool DataFlowSanitizer::doInitialization(Module &M) {
Peter Collingbourne0826e602014-12-05 21:22:32 +0000431 llvm::Triple TargetTriple(M.getTargetTriple());
432 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
433 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
434 TargetTriple.getArch() == llvm::Triple::mips64el;
Adhemerval Zanellabfe1eaf2015-07-30 20:49:35 +0000435 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64 ||
436 TargetTriple.getArch() == llvm::Triple::aarch64_be;
Peter Collingbourne0826e602014-12-05 21:22:32 +0000437
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000438 const DataLayout &DL = M.getDataLayout();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000439
440 Mod = &M;
441 Ctx = &M.getContext();
442 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
443 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000444 IntptrTy = DL.getIntPtrType(*Ctx);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000445 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000446 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
Peter Collingbourne0826e602014-12-05 21:22:32 +0000447 if (IsX86_64)
448 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
449 else if (IsMIPS64)
450 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0xF000000000LL);
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000451 // AArch64 supports multiple VMAs and the shadow mask is set at runtime.
Adhemerval Zanellabfe1eaf2015-07-30 20:49:35 +0000452 else if (IsAArch64)
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000453 DFSanRuntimeShadowMask = true;
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(
Reid Klecknerb5180542017-03-21 16:57:19 +0000546 AttributeList::ReturnIndex,
547 AttributeList::get(
548 F->getContext(), AttributeList::ReturnIndex,
549 AttributeFuncs::typeIncompatible(NewFT->getReturnType())));
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000550
551 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
Peter Collingbournea1099842014-11-05 17:21:00 +0000552 if (F->isVarArg()) {
553 NewF->removeAttributes(
Reid Klecknerb5180542017-03-21 16:57:19 +0000554 AttributeList::FunctionIndex,
555 AttributeList().addAttribute(*Ctx, AttributeList::FunctionIndex,
556 "split-stack"));
Peter Collingbournea1099842014-11-05 17:21:00 +0000557 CallInst::Create(DFSanVarargWrapperFn,
558 IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "",
559 BB);
560 new UnreachableInst(*Ctx, BB);
561 } else {
562 std::vector<Value *> Args;
563 unsigned n = FT->getNumParams();
564 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
565 Args.push_back(&*ai);
566 CallInst *CI = CallInst::Create(F, Args, "", BB);
567 if (FT->getReturnType()->isVoidTy())
568 ReturnInst::Create(*Ctx, BB);
569 else
570 ReturnInst::Create(*Ctx, CI, BB);
571 }
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000572
573 return NewF;
574}
575
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000576Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
577 StringRef FName) {
578 FunctionType *FTT = getTrampolineFunctionType(FT);
579 Constant *C = Mod->getOrInsertFunction(FName, FTT);
580 Function *F = dyn_cast<Function>(C);
581 if (F && F->isDeclaration()) {
582 F->setLinkage(GlobalValue::LinkOnceODRLinkage);
583 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
584 std::vector<Value *> Args;
585 Function::arg_iterator AI = F->arg_begin(); ++AI;
586 for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
587 Args.push_back(&*AI);
Reid Kleckner45707d42017-03-16 22:59:15 +0000588 CallInst *CI = CallInst::Create(&*F->arg_begin(), Args, "", BB);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000589 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()),
Reid Kleckner45707d42017-03-16 22:59:15 +0000602 &*std::prev(F->arg_end()), RI);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000603 }
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
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000624 ExternalShadowMask =
625 Mod->getOrInsertGlobal(kDFSanExternShadowPtrMask, IntptrTy);
626
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000627 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
628 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000629 F->addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
630 F->addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
631 F->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000632 F->addAttribute(1, Attribute::ZExt);
633 F->addAttribute(2, Attribute::ZExt);
634 }
635 DFSanCheckedUnionFn = Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy);
636 if (Function *F = dyn_cast<Function>(DFSanCheckedUnionFn)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000637 F->addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
638 F->addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
639 F->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000640 F->addAttribute(1, Attribute::ZExt);
641 F->addAttribute(2, Attribute::ZExt);
642 }
643 DFSanUnionLoadFn =
644 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
645 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000646 F->addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
647 F->addAttribute(AttributeList::FunctionIndex, Attribute::ReadOnly);
648 F->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000649 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000650 DFSanUnimplementedFn =
651 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000652 DFSanSetLabelFn =
653 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
654 if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
655 F->addAttribute(1, Attribute::ZExt);
656 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000657 DFSanNonzeroLabelFn =
658 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
Peter Collingbournea1099842014-11-05 17:21:00 +0000659 DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper",
660 DFSanVarargWrapperFnTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000661
662 std::vector<Function *> FnsToInstrument;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000663 llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000664 for (Function &i : M) {
665 if (!i.isIntrinsic() &&
666 &i != DFSanUnionFn &&
667 &i != DFSanCheckedUnionFn &&
668 &i != DFSanUnionLoadFn &&
669 &i != DFSanUnimplementedFn &&
670 &i != DFSanSetLabelFn &&
671 &i != DFSanNonzeroLabelFn &&
672 &i != DFSanVarargWrapperFn)
673 FnsToInstrument.push_back(&i);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000674 }
675
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000676 // Give function aliases prefixes when necessary, and build wrappers where the
677 // instrumentedness is inconsistent.
Peter Collingbourne59b12622013-08-22 20:08:08 +0000678 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
679 GlobalAlias *GA = &*i;
680 ++i;
681 // Don't stop on weak. We assume people aren't playing games with the
682 // instrumentedness of overridden weak aliases.
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000683 if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000684 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
685 if (GAInst && FInst) {
686 addGlobalNamePrefix(GA);
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000687 } else if (GAInst != FInst) {
688 // Non-instrumented alias of an instrumented function, or vice versa.
689 // Replace the alias with a native-ABI wrapper of the aliasee. The pass
690 // below will take care of instrumenting it.
691 Function *NewF =
692 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000693 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000694 NewF->takeName(GA);
695 GA->eraseFromParent();
696 FnsToInstrument.push_back(NewF);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000697 }
698 }
699 }
700
Peter Collingbourne68162e72013-08-14 18:54:12 +0000701 AttrBuilder B;
702 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
Reid Klecknerb5180542017-03-21 16:57:19 +0000703 ReadOnlyNoneAttrs = AttributeList::get(*Ctx, AttributeList::FunctionIndex, B);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000704
705 // First, change the ABI of every function in the module. ABI-listed
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000706 // functions keep their original ABI and get a wrapper function.
707 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
708 e = FnsToInstrument.end();
709 i != e; ++i) {
710 Function &F = **i;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000711 FunctionType *FT = F.getFunctionType();
Peter Collingbourne68162e72013-08-14 18:54:12 +0000712
Peter Collingbourne59b12622013-08-22 20:08:08 +0000713 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
714 FT->getReturnType()->isVoidTy());
Peter Collingbourne68162e72013-08-14 18:54:12 +0000715
716 if (isInstrumented(&F)) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000717 // Instrumented functions get a 'dfs$' prefix. This allows us to more
718 // easily identify cases of mismatching ABIs.
719 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000720 FunctionType *NewFT = getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000721 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000722 NewF->copyAttributesFrom(&F);
723 NewF->removeAttributes(
Reid Klecknerb5180542017-03-21 16:57:19 +0000724 AttributeList::ReturnIndex,
725 AttributeList::get(
726 NewF->getContext(), AttributeList::ReturnIndex,
727 AttributeFuncs::typeIncompatible(NewFT->getReturnType())));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000728 for (Function::arg_iterator FArg = F.arg_begin(),
729 NewFArg = NewF->arg_begin(),
730 FArgEnd = F.arg_end();
731 FArg != FArgEnd; ++FArg, ++NewFArg) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000732 FArg->replaceAllUsesWith(&*NewFArg);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000733 }
734 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
735
Chandler Carruthcdf47882014-03-09 03:16:01 +0000736 for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
737 UI != UE;) {
738 BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
739 ++UI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000740 if (BA) {
741 BA->replaceAllUsesWith(
742 BlockAddress::get(NewF, BA->getBasicBlock()));
743 delete BA;
744 }
745 }
746 F.replaceAllUsesWith(
747 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
748 NewF->takeName(&F);
749 F.eraseFromParent();
750 *i = NewF;
Peter Collingbourne59b12622013-08-22 20:08:08 +0000751 addGlobalNamePrefix(NewF);
752 } else {
753 addGlobalNamePrefix(&F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000754 }
Peter Collingbourne59b12622013-08-22 20:08:08 +0000755 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000756 // Build a wrapper function for F. The wrapper simply calls F, and is
757 // added to FnsToInstrument so that any instrumentation according to its
758 // WrapperKind is done in the second pass below.
759 FunctionType *NewFT = getInstrumentedABI() == IA_Args
760 ? getArgsFunctionType(FT)
761 : FT;
Alexey Samsonov6dae24d2013-08-23 07:42:51 +0000762 Function *NewF = buildWrapperFunction(
763 &F, std::string("dfsw$") + std::string(F.getName()),
764 GlobalValue::LinkOnceODRLinkage, NewFT);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000765 if (getInstrumentedABI() == IA_TLS)
Reid Klecknerb5180542017-03-21 16:57:19 +0000766 NewF->removeAttributes(AttributeList::FunctionIndex, ReadOnlyNoneAttrs);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000767
Peter Collingbourne68162e72013-08-14 18:54:12 +0000768 Value *WrappedFnCst =
769 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
770 F.replaceAllUsesWith(WrappedFnCst);
David Blaikiec6c6c7b2014-10-07 22:59:46 +0000771
Peter Collingbourne68162e72013-08-14 18:54:12 +0000772 UnwrappedFnMap[WrappedFnCst] = &F;
773 *i = NewF;
774
775 if (!F.isDeclaration()) {
776 // This function is probably defining an interposition of an
777 // uninstrumented function and hence needs to keep the original ABI.
778 // But any functions it may call need to use the instrumented ABI, so
779 // we instrument it in a mode which preserves the original ABI.
780 FnsWithNativeABI.insert(&F);
781
782 // This code needs to rebuild the iterators, as they may be invalidated
783 // by the push_back, taking care that the new range does not include
784 // any functions added by this code.
785 size_t N = i - FnsToInstrument.begin(),
786 Count = e - FnsToInstrument.begin();
787 FnsToInstrument.push_back(&F);
788 i = FnsToInstrument.begin() + N;
789 e = FnsToInstrument.begin() + Count;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000790 }
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +0000791 // Hopefully, nobody will try to indirectly call a vararg
792 // function... yet.
793 } else if (FT->isVarArg()) {
794 UnwrappedFnMap[&F] = &F;
795 *i = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000796 }
797 }
798
Benjamin Kramer135f7352016-06-26 12:28:59 +0000799 for (Function *i : FnsToInstrument) {
800 if (!i || i->isDeclaration())
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000801 continue;
802
Benjamin Kramer135f7352016-06-26 12:28:59 +0000803 removeUnreachableBlocks(*i);
Peter Collingbourneae66d572013-08-09 21:42:53 +0000804
Benjamin Kramer135f7352016-06-26 12:28:59 +0000805 DFSanFunction DFSF(*this, i, FnsWithNativeABI.count(i));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000806
807 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
808 // Build a copy of the list before iterating over it.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000809 llvm::SmallVector<BasicBlock *, 4> BBList(depth_first(&i->getEntryBlock()));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000810
Benjamin Kramer135f7352016-06-26 12:28:59 +0000811 for (BasicBlock *i : BBList) {
812 Instruction *Inst = &i->front();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000813 while (1) {
814 // DFSanVisitor may split the current basic block, changing the current
815 // instruction's next pointer and moving the next instruction to the
816 // tail block from which we should continue.
817 Instruction *Next = Inst->getNextNode();
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000818 // DFSanVisitor may delete Inst, so keep track of whether it was a
819 // terminator.
820 bool IsTerminator = isa<TerminatorInst>(Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000821 if (!DFSF.SkipInsts.count(Inst))
822 DFSanVisitor(DFSF).visit(Inst);
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000823 if (IsTerminator)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000824 break;
825 Inst = Next;
826 }
827 }
828
Peter Collingbourne68162e72013-08-14 18:54:12 +0000829 // We will not necessarily be able to compute the shadow for every phi node
830 // until we have visited every block. Therefore, the code that handles phi
831 // nodes adds them to the PHIFixups list so that they can be properly
832 // handled here.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000833 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
834 i = DFSF.PHIFixups.begin(),
835 e = DFSF.PHIFixups.end();
836 i != e; ++i) {
837 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
838 ++val) {
839 i->second->setIncomingValue(
840 val, DFSF.getShadow(i->first->getIncomingValue(val)));
841 }
842 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000843
844 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
845 // places (i.e. instructions in basic blocks we haven't even begun visiting
846 // yet). To make our life easier, do this work in a pass after the main
847 // instrumentation.
848 if (ClDebugNonzeroLabels) {
Peter Collingbournefab565a2014-08-22 01:18:18 +0000849 for (Value *V : DFSF.NonZeroChecks) {
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000850 Instruction *Pos;
Peter Collingbournefab565a2014-08-22 01:18:18 +0000851 if (Instruction *I = dyn_cast<Instruction>(V))
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000852 Pos = I->getNextNode();
853 else
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000854 Pos = &DFSF.F->getEntryBlock().front();
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000855 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
856 Pos = Pos->getNextNode();
857 IRBuilder<> IRB(Pos);
Peter Collingbournefab565a2014-08-22 01:18:18 +0000858 Value *Ne = IRB.CreateICmpNE(V, DFSF.DFS.ZeroShadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000859 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000860 Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000861 IRBuilder<> ThenIRB(BI);
David Blaikieff6409d2015-05-18 22:13:54 +0000862 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn, {});
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000863 }
864 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000865 }
866
867 return false;
868}
869
870Value *DFSanFunction::getArgTLSPtr() {
871 if (ArgTLSPtr)
872 return ArgTLSPtr;
873 if (DFS.ArgTLS)
874 return ArgTLSPtr = DFS.ArgTLS;
875
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000876 IRBuilder<> IRB(&F->getEntryBlock().front());
David Blaikieff6409d2015-05-18 22:13:54 +0000877 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS, {});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000878}
879
880Value *DFSanFunction::getRetvalTLS() {
881 if (RetvalTLSPtr)
882 return RetvalTLSPtr;
883 if (DFS.RetvalTLS)
884 return RetvalTLSPtr = DFS.RetvalTLS;
885
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000886 IRBuilder<> IRB(&F->getEntryBlock().front());
David Blaikieff6409d2015-05-18 22:13:54 +0000887 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS, {});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000888}
889
890Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
891 IRBuilder<> IRB(Pos);
892 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
893}
894
895Value *DFSanFunction::getShadow(Value *V) {
896 if (!isa<Argument>(V) && !isa<Instruction>(V))
897 return DFS.ZeroShadow;
898 Value *&Shadow = ValShadowMap[V];
899 if (!Shadow) {
900 if (Argument *A = dyn_cast<Argument>(V)) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000901 if (IsNativeABI)
902 return DFS.ZeroShadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000903 switch (IA) {
904 case DataFlowSanitizer::IA_TLS: {
905 Value *ArgTLSPtr = getArgTLSPtr();
906 Instruction *ArgTLSPos =
907 DFS.ArgTLS ? &*F->getEntryBlock().begin()
908 : cast<Instruction>(ArgTLSPtr)->getNextNode();
909 IRBuilder<> IRB(ArgTLSPos);
910 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
911 break;
912 }
913 case DataFlowSanitizer::IA_Args: {
Reid Kleckner45707d42017-03-16 22:59:15 +0000914 unsigned ArgIdx = A->getArgNo() + F->arg_size() / 2;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000915 Function::arg_iterator i = F->arg_begin();
916 while (ArgIdx--)
917 ++i;
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000918 Shadow = &*i;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000919 assert(Shadow->getType() == DFS.ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000920 break;
921 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000922 }
Peter Collingbournefab565a2014-08-22 01:18:18 +0000923 NonZeroChecks.push_back(Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000924 } else {
925 Shadow = DFS.ZeroShadow;
926 }
927 }
928 return Shadow;
929}
930
931void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
932 assert(!ValShadowMap.count(I));
933 assert(Shadow->getType() == DFS.ShadowTy);
934 ValShadowMap[I] = Shadow;
935}
936
937Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
938 assert(Addr != RetvalTLS && "Reinstrumenting?");
939 IRBuilder<> IRB(Pos);
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000940 Value *ShadowPtrMaskValue;
941 if (DFSanRuntimeShadowMask)
942 ShadowPtrMaskValue = IRB.CreateLoad(IntptrTy, ExternalShadowMask);
943 else
944 ShadowPtrMaskValue = ShadowPtrMask;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000945 return IRB.CreateIntToPtr(
946 IRB.CreateMul(
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000947 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy),
948 IRB.CreatePtrToInt(ShadowPtrMaskValue, IntptrTy)),
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000949 ShadowPtrMul),
950 ShadowPtrTy);
951}
952
953// Generates IR to compute the union of the two given shadows, inserting it
954// before Pos. Returns the computed union Value.
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000955Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
956 if (V1 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000957 return V2;
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000958 if (V2 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000959 return V1;
960 if (V1 == V2)
961 return V1;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000962
Peter Collingbourne9947c492014-07-15 22:13:19 +0000963 auto V1Elems = ShadowElements.find(V1);
964 auto V2Elems = ShadowElements.find(V2);
965 if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
966 if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
967 V2Elems->second.begin(), V2Elems->second.end())) {
968 return V1;
969 } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
970 V1Elems->second.begin(), V1Elems->second.end())) {
971 return V2;
972 }
973 } else if (V1Elems != ShadowElements.end()) {
974 if (V1Elems->second.count(V2))
975 return V1;
976 } else if (V2Elems != ShadowElements.end()) {
977 if (V2Elems->second.count(V1))
978 return V2;
979 }
980
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000981 auto Key = std::make_pair(V1, V2);
982 if (V1 > V2)
983 std::swap(Key.first, Key.second);
984 CachedCombinedShadow &CCS = CachedCombinedShadows[Key];
985 if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
986 return CCS.Shadow;
987
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000988 IRBuilder<> IRB(Pos);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000989 if (AvoidNewBlocks) {
David Blaikieff6409d2015-05-18 22:13:54 +0000990 CallInst *Call = IRB.CreateCall(DFS.DFSanCheckedUnionFn, {V1, V2});
Reid Klecknerb5180542017-03-21 16:57:19 +0000991 Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000992 Call->addAttribute(1, Attribute::ZExt);
993 Call->addAttribute(2, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000994
Peter Collingbournedf240b22014-08-06 00:33:40 +0000995 CCS.Block = Pos->getParent();
996 CCS.Shadow = Call;
997 } else {
998 BasicBlock *Head = Pos->getParent();
999 Value *Ne = IRB.CreateICmpNE(V1, V2);
1000 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
1001 Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
1002 IRBuilder<> ThenIRB(BI);
David Blaikieff6409d2015-05-18 22:13:54 +00001003 CallInst *Call = ThenIRB.CreateCall(DFS.DFSanUnionFn, {V1, V2});
Reid Klecknerb5180542017-03-21 16:57:19 +00001004 Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Peter Collingbournedf240b22014-08-06 00:33:40 +00001005 Call->addAttribute(1, Attribute::ZExt);
1006 Call->addAttribute(2, Attribute::ZExt);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001007
Peter Collingbournedf240b22014-08-06 00:33:40 +00001008 BasicBlock *Tail = BI->getSuccessor(0);
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001009 PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
Peter Collingbournedf240b22014-08-06 00:33:40 +00001010 Phi->addIncoming(Call, Call->getParent());
1011 Phi->addIncoming(V1, Head);
1012
1013 CCS.Block = Tail;
1014 CCS.Shadow = Phi;
1015 }
Peter Collingbourne9947c492014-07-15 22:13:19 +00001016
1017 std::set<Value *> UnionElems;
1018 if (V1Elems != ShadowElements.end()) {
1019 UnionElems = V1Elems->second;
1020 } else {
1021 UnionElems.insert(V1);
1022 }
1023 if (V2Elems != ShadowElements.end()) {
1024 UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
1025 } else {
1026 UnionElems.insert(V2);
1027 }
Peter Collingbournedf240b22014-08-06 00:33:40 +00001028 ShadowElements[CCS.Shadow] = std::move(UnionElems);
Peter Collingbourne9947c492014-07-15 22:13:19 +00001029
Peter Collingbournedf240b22014-08-06 00:33:40 +00001030 return CCS.Shadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001031}
1032
1033// A convenience function which folds the shadows of each of the operands
1034// of the provided instruction Inst, inserting the IR before Inst. Returns
1035// the computed union Value.
1036Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
1037 if (Inst->getNumOperands() == 0)
1038 return DFS.ZeroShadow;
1039
1040 Value *Shadow = getShadow(Inst->getOperand(0));
1041 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001042 Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001043 }
1044 return Shadow;
1045}
1046
1047void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
1048 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1049 DFSF.setShadow(&I, CombinedShadow);
1050}
1051
1052// Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
1053// Addr has alignment Align, and take the union of each of those shadows.
1054Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
1055 Instruction *Pos) {
1056 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1057 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1058 AllocaShadowMap.find(AI);
1059 if (i != AllocaShadowMap.end()) {
1060 IRBuilder<> IRB(Pos);
1061 return IRB.CreateLoad(i->second);
1062 }
1063 }
1064
1065 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1066 SmallVector<Value *, 2> Objs;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001067 GetUnderlyingObjects(Addr, Objs, Pos->getModule()->getDataLayout());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001068 bool AllConstants = true;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001069 for (Value *Obj : Objs) {
1070 if (isa<Function>(Obj) || isa<BlockAddress>(Obj))
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001071 continue;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001072 if (isa<GlobalVariable>(Obj) && cast<GlobalVariable>(Obj)->isConstant())
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001073 continue;
1074
1075 AllConstants = false;
1076 break;
1077 }
1078 if (AllConstants)
1079 return DFS.ZeroShadow;
1080
1081 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1082 switch (Size) {
1083 case 0:
1084 return DFS.ZeroShadow;
1085 case 1: {
1086 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
1087 LI->setAlignment(ShadowAlign);
1088 return LI;
1089 }
1090 case 2: {
1091 IRBuilder<> IRB(Pos);
David Blaikie93c54442015-04-03 19:41:44 +00001092 Value *ShadowAddr1 = IRB.CreateGEP(DFS.ShadowTy, ShadowAddr,
1093 ConstantInt::get(DFS.IntptrTy, 1));
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001094 return combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
1095 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign), Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001096 }
1097 }
Peter Collingbournedf240b22014-08-06 00:33:40 +00001098 if (!AvoidNewBlocks && Size % (64 / DFS.ShadowWidth) == 0) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001099 // Fast path for the common case where each byte has identical shadow: load
1100 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
1101 // shadow is non-equal.
1102 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
1103 IRBuilder<> FallbackIRB(FallbackBB);
David Blaikieff6409d2015-05-18 22:13:54 +00001104 CallInst *FallbackCall = FallbackIRB.CreateCall(
1105 DFS.DFSanUnionLoadFn,
1106 {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
Reid Klecknerb5180542017-03-21 16:57:19 +00001107 FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001108
1109 // Compare each of the shadows stored in the loaded 64 bits to each other,
1110 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
1111 IRBuilder<> IRB(Pos);
1112 Value *WideAddr =
1113 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1114 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1115 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
1116 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
1117 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
1118 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1119 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1120
1121 BasicBlock *Head = Pos->getParent();
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001122 BasicBlock *Tail = Head->splitBasicBlock(Pos->getIterator());
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001123
1124 if (DomTreeNode *OldNode = DT.getNode(Head)) {
1125 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1126
1127 DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1128 for (auto Child : Children)
1129 DT.changeImmediateDominator(Child, NewNode);
1130 }
1131
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001132 // In the following code LastBr will refer to the previous basic block's
1133 // conditional branch instruction, whose true successor is fixed up to point
1134 // to the next block during the loop below or to the tail after the final
1135 // iteration.
1136 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1137 ReplaceInstWithInst(Head->getTerminator(), LastBr);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001138 DT.addNewBlock(FallbackBB, Head);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001139
1140 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
1141 Ofs += 64 / DFS.ShadowWidth) {
1142 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001143 DT.addNewBlock(NextBB, LastBr->getParent());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001144 IRBuilder<> NextIRB(NextBB);
David Blaikie93c54442015-04-03 19:41:44 +00001145 WideAddr = NextIRB.CreateGEP(Type::getInt64Ty(*DFS.Ctx), WideAddr,
1146 ConstantInt::get(DFS.IntptrTy, 1));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001147 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1148 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1149 LastBr->setSuccessor(0, NextBB);
1150 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1151 }
1152
1153 LastBr->setSuccessor(0, Tail);
1154 FallbackIRB.CreateBr(Tail);
1155 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1156 Shadow->addIncoming(FallbackCall, FallbackBB);
1157 Shadow->addIncoming(TruncShadow, LastBr->getParent());
1158 return Shadow;
1159 }
1160
1161 IRBuilder<> IRB(Pos);
David Blaikieff6409d2015-05-18 22:13:54 +00001162 CallInst *FallbackCall = IRB.CreateCall(
1163 DFS.DFSanUnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
Reid Klecknerb5180542017-03-21 16:57:19 +00001164 FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001165 return FallbackCall;
1166}
1167
1168void DFSanVisitor::visitLoadInst(LoadInst &LI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001169 auto &DL = LI.getModule()->getDataLayout();
1170 uint64_t Size = DL.getTypeStoreSize(LI.getType());
Peter Collingbourne142fdff2014-08-01 21:18:18 +00001171 if (Size == 0) {
1172 DFSF.setShadow(&LI, DFSF.DFS.ZeroShadow);
1173 return;
1174 }
1175
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001176 uint64_t Align;
1177 if (ClPreserveAlignment) {
1178 Align = LI.getAlignment();
1179 if (Align == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001180 Align = DL.getABITypeAlignment(LI.getType());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001181 } else {
1182 Align = 1;
1183 }
1184 IRBuilder<> IRB(&LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001185 Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
1186 if (ClCombinePointerLabelsOnLoad) {
1187 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001188 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001189 }
1190 if (Shadow != DFSF.DFS.ZeroShadow)
Peter Collingbournefab565a2014-08-22 01:18:18 +00001191 DFSF.NonZeroChecks.push_back(Shadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +00001192
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001193 DFSF.setShadow(&LI, Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001194}
1195
1196void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
1197 Value *Shadow, Instruction *Pos) {
1198 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1199 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1200 AllocaShadowMap.find(AI);
1201 if (i != AllocaShadowMap.end()) {
1202 IRBuilder<> IRB(Pos);
1203 IRB.CreateStore(Shadow, i->second);
1204 return;
1205 }
1206 }
1207
1208 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1209 IRBuilder<> IRB(Pos);
1210 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1211 if (Shadow == DFS.ZeroShadow) {
1212 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1213 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1214 Value *ExtShadowAddr =
1215 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1216 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1217 return;
1218 }
1219
1220 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1221 uint64_t Offset = 0;
1222 if (Size >= ShadowVecSize) {
1223 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1224 Value *ShadowVec = UndefValue::get(ShadowVecTy);
1225 for (unsigned i = 0; i != ShadowVecSize; ++i) {
1226 ShadowVec = IRB.CreateInsertElement(
1227 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1228 }
1229 Value *ShadowVecAddr =
1230 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1231 do {
David Blaikie95d3e532015-04-03 23:03:54 +00001232 Value *CurShadowVecAddr =
1233 IRB.CreateConstGEP1_32(ShadowVecTy, ShadowVecAddr, Offset);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001234 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1235 Size -= ShadowVecSize;
1236 ++Offset;
1237 } while (Size >= ShadowVecSize);
1238 Offset *= ShadowVecSize;
1239 }
1240 while (Size > 0) {
David Blaikie95d3e532015-04-03 23:03:54 +00001241 Value *CurShadowAddr =
1242 IRB.CreateConstGEP1_32(DFS.ShadowTy, ShadowAddr, Offset);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001243 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1244 --Size;
1245 ++Offset;
1246 }
1247}
1248
1249void DFSanVisitor::visitStoreInst(StoreInst &SI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001250 auto &DL = SI.getModule()->getDataLayout();
1251 uint64_t Size = DL.getTypeStoreSize(SI.getValueOperand()->getType());
Peter Collingbourne142fdff2014-08-01 21:18:18 +00001252 if (Size == 0)
1253 return;
1254
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001255 uint64_t Align;
1256 if (ClPreserveAlignment) {
1257 Align = SI.getAlignment();
1258 if (Align == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001259 Align = DL.getABITypeAlignment(SI.getValueOperand()->getType());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001260 } else {
1261 Align = 1;
1262 }
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001263
1264 Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1265 if (ClCombinePointerLabelsOnStore) {
1266 Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001267 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001268 }
1269 DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001270}
1271
1272void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1273 visitOperandShadowInst(BO);
1274}
1275
1276void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1277
1278void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1279
1280void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1281 visitOperandShadowInst(GEPI);
1282}
1283
1284void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1285 visitOperandShadowInst(I);
1286}
1287
1288void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1289 visitOperandShadowInst(I);
1290}
1291
1292void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1293 visitOperandShadowInst(I);
1294}
1295
1296void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1297 visitOperandShadowInst(I);
1298}
1299
1300void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1301 visitOperandShadowInst(I);
1302}
1303
1304void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1305 bool AllLoadsStores = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001306 for (User *U : I.users()) {
1307 if (isa<LoadInst>(U))
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001308 continue;
1309
Chandler Carruthcdf47882014-03-09 03:16:01 +00001310 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001311 if (SI->getPointerOperand() == &I)
1312 continue;
1313 }
1314
1315 AllLoadsStores = false;
1316 break;
1317 }
1318 if (AllLoadsStores) {
1319 IRBuilder<> IRB(&I);
1320 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1321 }
1322 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1323}
1324
1325void DFSanVisitor::visitSelectInst(SelectInst &I) {
1326 Value *CondShadow = DFSF.getShadow(I.getCondition());
1327 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1328 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1329
1330 if (isa<VectorType>(I.getCondition()->getType())) {
1331 DFSF.setShadow(
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001332 &I,
1333 DFSF.combineShadows(
1334 CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001335 } else {
1336 Value *ShadowSel;
1337 if (TrueShadow == FalseShadow) {
1338 ShadowSel = TrueShadow;
1339 } else {
1340 ShadowSel =
1341 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1342 }
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001343 DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001344 }
1345}
1346
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +00001347void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1348 IRBuilder<> IRB(&I);
1349 Value *ValShadow = DFSF.getShadow(I.getValue());
David Blaikieff6409d2015-05-18 22:13:54 +00001350 IRB.CreateCall(DFSF.DFS.DFSanSetLabelFn,
1351 {ValShadow, IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(
1352 *DFSF.DFS.Ctx)),
1353 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +00001354}
1355
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001356void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1357 IRBuilder<> IRB(&I);
1358 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1359 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1360 Value *LenShadow = IRB.CreateMul(
1361 I.getLength(),
1362 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
Pete Cooper67cf9a72015-11-19 05:56:52 +00001363 Value *AlignShadow;
1364 if (ClPreserveAlignment) {
1365 AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1366 ConstantInt::get(I.getAlignmentCst()->getType(),
1367 DFSF.DFS.ShadowWidth / 8));
1368 } else {
1369 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1370 DFSF.DFS.ShadowWidth / 8);
1371 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001372 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1373 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1374 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
Pete Cooper67cf9a72015-11-19 05:56:52 +00001375 IRB.CreateCall(I.getCalledValue(), {DestShadow, SrcShadow, LenShadow,
1376 AlignShadow, I.getVolatileCst()});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001377}
1378
1379void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001380 if (!DFSF.IsNativeABI && RI.getReturnValue()) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001381 switch (DFSF.IA) {
1382 case DataFlowSanitizer::IA_TLS: {
1383 Value *S = DFSF.getShadow(RI.getReturnValue());
1384 IRBuilder<> IRB(&RI);
1385 IRB.CreateStore(S, DFSF.getRetvalTLS());
1386 break;
1387 }
1388 case DataFlowSanitizer::IA_Args: {
1389 IRBuilder<> IRB(&RI);
1390 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1391 Value *InsVal =
1392 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1393 Value *InsShadow =
1394 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1395 RI.setOperand(0, InsShadow);
1396 break;
1397 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001398 }
1399 }
1400}
1401
1402void DFSanVisitor::visitCallSite(CallSite CS) {
1403 Function *F = CS.getCalledFunction();
1404 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1405 visitOperandShadowInst(*CS.getInstruction());
1406 return;
1407 }
1408
Peter Collingbournea1099842014-11-05 17:21:00 +00001409 // Calls to this function are synthesized in wrappers, and we shouldn't
1410 // instrument them.
1411 if (F == DFSF.DFS.DFSanVarargWrapperFn)
1412 return;
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()) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001454 CustomFn->removeAttributes(AttributeList::FunctionIndex,
Peter Collingbourne68162e72013-08-14 18:54:12 +00001455 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(
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001489 LabelVATy, getDataLayout().getAllocaAddrSpace(),
1490 "labelva", &DFSF.F->getEntryBlock().front());
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001491
1492 for (unsigned n = 0; i != CS.arg_end(); ++i, ++n) {
David Blaikie64646022015-04-05 22:41:44 +00001493 auto LabelVAPtr = IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, n);
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001494 IRB.CreateStore(DFSF.getShadow(*i), LabelVAPtr);
1495 }
1496
David Blaikie64646022015-04-05 22:41:44 +00001497 Args.push_back(IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, 0));
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001498 }
1499
Peter Collingbourne68162e72013-08-14 18:54:12 +00001500 if (!FT->getReturnType()->isVoidTy()) {
1501 if (!DFSF.LabelReturnAlloca) {
1502 DFSF.LabelReturnAlloca =
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001503 new AllocaInst(DFSF.DFS.ShadowTy,
1504 getDataLayout().getAllocaAddrSpace(),
1505 "labelreturn", &DFSF.F->getEntryBlock().front());
Peter Collingbourne68162e72013-08-14 18:54:12 +00001506 }
1507 Args.push_back(DFSF.LabelReturnAlloca);
1508 }
1509
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001510 for (i = CS.arg_begin() + FT->getNumParams(); i != CS.arg_end(); ++i)
1511 Args.push_back(*i);
1512
Peter Collingbourne68162e72013-08-14 18:54:12 +00001513 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1514 CustomCI->setCallingConv(CI->getCallingConv());
1515 CustomCI->setAttributes(CI->getAttributes());
1516
1517 if (!FT->getReturnType()->isVoidTy()) {
1518 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1519 DFSF.setShadow(CustomCI, LabelLoad);
1520 }
1521
1522 CI->replaceAllUsesWith(CustomCI);
1523 CI->eraseFromParent();
1524 return;
1525 }
1526 break;
1527 }
1528 }
1529 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001530
1531 FunctionType *FT = cast<FunctionType>(
1532 CS.getCalledValue()->getType()->getPointerElementType());
Peter Collingbourne68162e72013-08-14 18:54:12 +00001533 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001534 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1535 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1536 DFSF.getArgTLS(i, CS.getInstruction()));
1537 }
1538 }
1539
Craig Topperf40110f2014-04-25 05:29:35 +00001540 Instruction *Next = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001541 if (!CS.getType()->isVoidTy()) {
1542 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1543 if (II->getNormalDest()->getSinglePredecessor()) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001544 Next = &II->getNormalDest()->front();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001545 } else {
1546 BasicBlock *NewBB =
Chandler Carruthd4500562015-01-19 12:36:53 +00001547 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001548 Next = &NewBB->front();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001549 }
1550 } else {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001551 assert(CS->getIterator() != CS->getParent()->end());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001552 Next = CS->getNextNode();
1553 }
1554
Peter Collingbourne68162e72013-08-14 18:54:12 +00001555 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001556 IRBuilder<> NextIRB(Next);
1557 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1558 DFSF.SkipInsts.insert(LI);
1559 DFSF.setShadow(CS.getInstruction(), LI);
Peter Collingbournefab565a2014-08-22 01:18:18 +00001560 DFSF.NonZeroChecks.push_back(LI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001561 }
1562 }
1563
1564 // Do all instrumentation for IA_Args down here to defer tampering with the
1565 // CFG in a way that SplitEdge may be able to detect.
Peter Collingbourne68162e72013-08-14 18:54:12 +00001566 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1567 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001568 Value *Func =
1569 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1570 std::vector<Value *> Args;
1571
1572 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1573 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1574 Args.push_back(*i);
1575
1576 i = CS.arg_begin();
1577 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1578 Args.push_back(DFSF.getShadow(*i));
1579
1580 if (FT->isVarArg()) {
1581 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1582 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1583 AllocaInst *VarArgShadow =
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001584 new AllocaInst(VarArgArrayTy, getDataLayout().getAllocaAddrSpace(),
1585 "", &DFSF.F->getEntryBlock().front());
David Blaikie4e5d47f42015-04-04 21:07:10 +00001586 Args.push_back(IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, 0));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001587 for (unsigned n = 0; i != e; ++i, ++n) {
David Blaikie4e5d47f42015-04-04 21:07:10 +00001588 IRB.CreateStore(
1589 DFSF.getShadow(*i),
1590 IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, n));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001591 Args.push_back(*i);
1592 }
1593 }
1594
1595 CallSite NewCS;
1596 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1597 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1598 Args);
1599 } else {
1600 NewCS = IRB.CreateCall(Func, Args);
1601 }
1602 NewCS.setCallingConv(CS.getCallingConv());
1603 NewCS.setAttributes(CS.getAttributes().removeAttributes(
Reid Klecknerb5180542017-03-21 16:57:19 +00001604 *DFSF.DFS.Ctx, AttributeList::ReturnIndex,
Pete Cooper2777d8872015-05-06 23:19:56 +00001605 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType())));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001606
1607 if (Next) {
1608 ExtractValueInst *ExVal =
1609 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1610 DFSF.SkipInsts.insert(ExVal);
1611 ExtractValueInst *ExShadow =
1612 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1613 DFSF.SkipInsts.insert(ExShadow);
1614 DFSF.setShadow(ExVal, ExShadow);
Peter Collingbournefab565a2014-08-22 01:18:18 +00001615 DFSF.NonZeroChecks.push_back(ExShadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001616
1617 CS.getInstruction()->replaceAllUsesWith(ExVal);
1618 }
1619
1620 CS.getInstruction()->eraseFromParent();
1621 }
1622}
1623
1624void DFSanVisitor::visitPHINode(PHINode &PN) {
1625 PHINode *ShadowPN =
1626 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1627
1628 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1629 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1630 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1631 ++i) {
1632 ShadowPN->addIncoming(UndefShadow, *i);
1633 }
1634
1635 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1636 DFSF.setShadow(&PN, ShadowPN);
1637}