blob: ce06845c66816a7fd3c0e63b87d06e3ea658f886 [file] [log] [blame]
Eugene Zelenkofce43572017-10-21 00:57:46 +00001//===- DataFlowSanitizer.cpp - dynamic data flow analysis -----------------===//
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00002//
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//===----------------------------------------------------------------------===//
Eugene Zelenkofce43572017-10-21 00:57:46 +00009//
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000010/// \file
11/// This file is a part of DataFlowSanitizer, a generalised dynamic data flow
12/// analysis.
13///
14/// Unlike other Sanitizer tools, this tool is not designed to detect a specific
15/// class of bugs on its own. Instead, it provides a generic dynamic data flow
16/// analysis framework to be used by clients to help detect application-specific
17/// issues within their own code.
18///
19/// The analysis is based on automatic propagation of data flow labels (also
20/// known as taint labels) through a program as it performs computation. Each
21/// byte of application memory is backed by two bytes of shadow memory which
22/// hold the label. On Linux/x86_64, memory is laid out as follows:
23///
24/// +--------------------+ 0x800000000000 (top of memory)
25/// | application memory |
26/// +--------------------+ 0x700000008000 (kAppAddr)
27/// | |
28/// | unused |
29/// | |
30/// +--------------------+ 0x200200000000 (kUnusedAddr)
31/// | union table |
32/// +--------------------+ 0x200000000000 (kUnionTableAddr)
33/// | shadow memory |
34/// +--------------------+ 0x000000010000 (kShadowAddr)
35/// | reserved by kernel |
36/// +--------------------+ 0x000000000000
37///
38/// To derive a shadow memory address from an application memory address,
39/// bits 44-46 are cleared to bring the address into the range
40/// [0x000000008000,0x100000000000). Then the address is shifted left by 1 to
41/// account for the double byte representation of shadow labels and move the
42/// address into the shadow memory range. See the function
43/// DataFlowSanitizer::getShadowAddress below.
44///
45/// For more information, please refer to the design document:
46/// http://clang.llvm.org/docs/DataFlowSanitizerDesign.html
Eugene Zelenkofce43572017-10-21 00:57:46 +000047//
48//===----------------------------------------------------------------------===//
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000049
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000050#include "llvm/ADT/DenseMap.h"
51#include "llvm/ADT/DenseSet.h"
52#include "llvm/ADT/DepthFirstIterator.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000053#include "llvm/ADT/None.h"
54#include "llvm/ADT/SmallPtrSet.h"
55#include "llvm/ADT/SmallVector.h"
Peter Collingbourne28a10af2013-08-27 22:09:06 +000056#include "llvm/ADT/StringExtras.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000057#include "llvm/ADT/StringRef.h"
Peter Collingbourne0826e602014-12-05 21:22:32 +000058#include "llvm/ADT/Triple.h"
David Blaikie31b98d22018-06-04 21:23:21 +000059#include "llvm/Transforms/Utils/Local.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000060#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000061#include "llvm/IR/Argument.h"
62#include "llvm/IR/Attributes.h"
63#include "llvm/IR/BasicBlock.h"
64#include "llvm/IR/CallSite.h"
65#include "llvm/IR/Constant.h"
66#include "llvm/IR/Constants.h"
67#include "llvm/IR/DataLayout.h"
68#include "llvm/IR/DerivedTypes.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000069#include "llvm/IR/Dominators.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000070#include "llvm/IR/Function.h"
71#include "llvm/IR/GlobalAlias.h"
72#include "llvm/IR/GlobalValue.h"
73#include "llvm/IR/GlobalVariable.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000074#include "llvm/IR/IRBuilder.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000075#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000076#include "llvm/IR/InstVisitor.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000077#include "llvm/IR/InstrTypes.h"
78#include "llvm/IR/Instruction.h"
79#include "llvm/IR/Instructions.h"
80#include "llvm/IR/IntrinsicInst.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000081#include "llvm/IR/LLVMContext.h"
82#include "llvm/IR/MDBuilder.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000083#include "llvm/IR/Module.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000084#include "llvm/IR/Type.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000085#include "llvm/IR/User.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000086#include "llvm/IR/Value.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000087#include "llvm/Pass.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000088#include "llvm/Support/Casting.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000089#include "llvm/Support/CommandLine.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000090#include "llvm/Support/ErrorHandling.h"
Alexey Samsonovb7dd3292014-07-09 19:40:08 +000091#include "llvm/Support/SpecialCaseList.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000092#include "llvm/Transforms/Instrumentation.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000093#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Peter Collingbourne9947c492014-07-15 22:13:19 +000094#include <algorithm>
Eugene Zelenkofce43572017-10-21 00:57:46 +000095#include <cassert>
96#include <cstddef>
97#include <cstdint>
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000098#include <iterator>
Eugene Zelenkofce43572017-10-21 00:57:46 +000099#include <memory>
Peter Collingbourne9947c492014-07-15 22:13:19 +0000100#include <set>
Eugene Zelenkofce43572017-10-21 00:57:46 +0000101#include <string>
Peter Collingbourne9947c492014-07-15 22:13:19 +0000102#include <utility>
Eugene Zelenkofce43572017-10-21 00:57:46 +0000103#include <vector>
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000104
105using namespace llvm;
106
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000107// External symbol to be used when generating the shadow address for
108// architectures with multiple VMAs. Instead of using a constant integer
109// the runtime will set the external mask based on the VMA range.
110static const char *const kDFSanExternShadowPtrMask = "__dfsan_shadow_ptr_mask";
Adhemerval Zanella4754e2d2015-08-24 13:48:10 +0000111
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000112// The -dfsan-preserve-alignment flag controls whether this pass assumes that
113// alignment requirements provided by the input IR are correct. For example,
114// if the input IR contains a load with alignment 8, this flag will cause
115// the shadow load to have alignment 16. This flag is disabled by default as
116// we have unfortunately encountered too much code (including Clang itself;
117// see PR14291) which performs misaligned access.
118static cl::opt<bool> ClPreserveAlignment(
119 "dfsan-preserve-alignment",
120 cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
121 cl::init(false));
122
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000123// The ABI list files control how shadow parameters are passed. The pass treats
Peter Collingbourne68162e72013-08-14 18:54:12 +0000124// every function labelled "uninstrumented" in the ABI list file as conforming
125// to the "native" (i.e. unsanitized) ABI. Unless the ABI list contains
126// additional annotations for those functions, a call to one of those functions
127// will produce a warning message, as the labelling behaviour of the function is
128// unknown. The other supported annotations are "functional" and "discard",
129// which are described below under DataFlowSanitizer::WrapperKind.
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000130static cl::list<std::string> ClABIListFiles(
Peter Collingbourne68162e72013-08-14 18:54:12 +0000131 "dfsan-abilist",
132 cl::desc("File listing native ABI functions and how the pass treats them"),
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000133 cl::Hidden);
134
Peter Collingbourne68162e72013-08-14 18:54:12 +0000135// Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
136// functions (see DataFlowSanitizer::InstrumentedABI below).
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000137static cl::opt<bool> ClArgsABI(
138 "dfsan-args-abi",
139 cl::desc("Use the argument ABI rather than the TLS ABI"),
140 cl::Hidden);
141
Peter Collingbourne0be79e12013-11-21 23:20:54 +0000142// Controls whether the pass includes or ignores the labels of pointers in load
143// instructions.
144static cl::opt<bool> ClCombinePointerLabelsOnLoad(
145 "dfsan-combine-pointer-labels-on-load",
146 cl::desc("Combine the label of the pointer with the label of the data when "
147 "loading from memory."),
148 cl::Hidden, cl::init(true));
149
150// Controls whether the pass includes or ignores the labels of pointers in
151// stores instructions.
152static cl::opt<bool> ClCombinePointerLabelsOnStore(
153 "dfsan-combine-pointer-labels-on-store",
154 cl::desc("Combine the label of the pointer with the label of the data when "
155 "storing in memory."),
156 cl::Hidden, cl::init(false));
157
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000158static cl::opt<bool> ClDebugNonzeroLabels(
159 "dfsan-debug-nonzero-labels",
160 cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
161 "load or return with a nonzero label"),
162 cl::Hidden);
163
Eugene Zelenkofce43572017-10-21 00:57:46 +0000164static StringRef GetGlobalTypeString(const GlobalValue &G) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000165 // Types of GlobalVariables are always pointer types.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000166 Type *GType = G.getValueType();
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000167 // For now we support blacklisting struct types only.
168 if (StructType *SGType = dyn_cast<StructType>(GType)) {
169 if (!SGType->isLiteral())
170 return SGType->getName();
171 }
172 return "<unknown type>";
173}
174
Eugene Zelenkofce43572017-10-21 00:57:46 +0000175namespace {
176
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000177class DFSanABIList {
178 std::unique_ptr<SpecialCaseList> SCL;
179
180 public:
Eugene Zelenkofce43572017-10-21 00:57:46 +0000181 DFSanABIList() = default;
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000182
183 void set(std::unique_ptr<SpecialCaseList> List) { SCL = std::move(List); }
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000184
185 /// Returns whether either this function or its source file are listed in the
186 /// given category.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000187 bool isIn(const Function &F, StringRef Category) const {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000188 return isIn(*F.getParent(), Category) ||
Vlad Tsyrklevich998b2202017-09-25 22:11:11 +0000189 SCL->inSection("dataflow", "fun", F.getName(), Category);
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000190 }
191
192 /// Returns whether this global alias is listed in the given category.
193 ///
194 /// If GA aliases a function, the alias's name is matched as a function name
195 /// would be. Similarly, aliases of globals are matched like globals.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000196 bool isIn(const GlobalAlias &GA, StringRef Category) const {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000197 if (isIn(*GA.getParent(), Category))
198 return true;
199
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000200 if (isa<FunctionType>(GA.getValueType()))
Vlad Tsyrklevich998b2202017-09-25 22:11:11 +0000201 return SCL->inSection("dataflow", "fun", GA.getName(), Category);
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000202
Vlad Tsyrklevich998b2202017-09-25 22:11:11 +0000203 return SCL->inSection("dataflow", "global", GA.getName(), Category) ||
204 SCL->inSection("dataflow", "type", GetGlobalTypeString(GA),
205 Category);
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000206 }
207
208 /// Returns whether this module is listed in the given category.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000209 bool isIn(const Module &M, StringRef Category) const {
Vlad Tsyrklevich998b2202017-09-25 22:11:11 +0000210 return SCL->inSection("dataflow", "src", M.getModuleIdentifier(), Category);
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000211 }
212};
213
Peter Collingbourne32f54052018-02-22 19:09:07 +0000214/// TransformedFunction is used to express the result of transforming one
215/// function type into another. This struct is immutable. It holds metadata
216/// useful for updating calls of the old function to the new type.
217struct TransformedFunction {
218 TransformedFunction(FunctionType* OriginalType,
219 FunctionType* TransformedType,
220 std::vector<unsigned> ArgumentIndexMapping)
221 : OriginalType(OriginalType),
222 TransformedType(TransformedType),
223 ArgumentIndexMapping(ArgumentIndexMapping) {}
224
225 // Disallow copies.
226 TransformedFunction(const TransformedFunction&) = delete;
227 TransformedFunction& operator=(const TransformedFunction&) = delete;
228
229 // Allow moves.
230 TransformedFunction(TransformedFunction&&) = default;
231 TransformedFunction& operator=(TransformedFunction&&) = default;
232
233 /// Type of the function before the transformation.
234 FunctionType* const OriginalType;
235
236 /// Type of the function after the transformation.
237 FunctionType* const TransformedType;
238
239 /// Transforming a function may change the position of arguments. This
240 /// member records the mapping from each argument's old position to its new
241 /// position. Argument positions are zero-indexed. If the transformation
242 /// from F to F' made the first argument of F into the third argument of F',
243 /// then ArgumentIndexMapping[0] will equal 2.
244 const std::vector<unsigned> ArgumentIndexMapping;
245};
246
247/// Given function attributes from a call site for the original function,
248/// return function attributes appropriate for a call to the transformed
249/// function.
250AttributeList TransformFunctionAttributes(
251 const TransformedFunction& TransformedFunction,
252 LLVMContext& Ctx, AttributeList CallSiteAttrs) {
253
254 // Construct a vector of AttributeSet for each function argument.
255 std::vector<llvm::AttributeSet> ArgumentAttributes(
256 TransformedFunction.TransformedType->getNumParams());
257
258 // Copy attributes from the parameter of the original function to the
259 // transformed version. 'ArgumentIndexMapping' holds the mapping from
260 // old argument position to new.
261 for (unsigned i=0, ie = TransformedFunction.ArgumentIndexMapping.size();
262 i < ie; ++i) {
263 unsigned TransformedIndex = TransformedFunction.ArgumentIndexMapping[i];
264 ArgumentAttributes[TransformedIndex] = CallSiteAttrs.getParamAttributes(i);
265 }
266
267 // Copy annotations on varargs arguments.
268 for (unsigned i = TransformedFunction.OriginalType->getNumParams(),
269 ie = CallSiteAttrs.getNumAttrSets(); i<ie; ++i) {
270 ArgumentAttributes.push_back(CallSiteAttrs.getParamAttributes(i));
271 }
272
273 return AttributeList::get(
274 Ctx,
275 CallSiteAttrs.getFnAttributes(),
276 CallSiteAttrs.getRetAttributes(),
277 llvm::makeArrayRef(ArgumentAttributes));
278}
279
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000280class DataFlowSanitizer : public ModulePass {
281 friend struct DFSanFunction;
282 friend class DFSanVisitor;
283
284 enum {
285 ShadowWidth = 16
286 };
287
Peter Collingbourne68162e72013-08-14 18:54:12 +0000288 /// Which ABI should be used for instrumented functions?
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000289 enum InstrumentedABI {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000290 /// Argument and return value labels are passed through additional
291 /// arguments and by modifying the return type.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000292 IA_Args,
Peter Collingbourne68162e72013-08-14 18:54:12 +0000293
294 /// Argument and return value labels are passed through TLS variables
295 /// __dfsan_arg_tls and __dfsan_retval_tls.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000296 IA_TLS
297 };
298
Peter Collingbourne68162e72013-08-14 18:54:12 +0000299 /// How should calls to uninstrumented functions be handled?
300 enum WrapperKind {
301 /// This function is present in an uninstrumented form but we don't know
302 /// how it should be handled. Print a warning and call the function anyway.
303 /// Don't label the return value.
304 WK_Warning,
305
306 /// This function does not write to (user-accessible) memory, and its return
307 /// value is unlabelled.
308 WK_Discard,
309
310 /// This function does not write to (user-accessible) memory, and the label
311 /// of its return value is the union of the label of its arguments.
312 WK_Functional,
313
314 /// Instead of calling the function, a custom wrapper __dfsw_F is called,
315 /// where F is the name of the function. This function may wrap the
316 /// original function or provide its own implementation. This is similar to
317 /// the IA_Args ABI, except that IA_Args uses a struct return type to
318 /// pass the return value shadow in a register, while WK_Custom uses an
319 /// extra pointer argument to return the shadow. This allows the wrapped
320 /// form of the function type to be expressed in C.
321 WK_Custom
322 };
323
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000324 Module *Mod;
325 LLVMContext *Ctx;
326 IntegerType *ShadowTy;
327 PointerType *ShadowPtrTy;
328 IntegerType *IntptrTy;
329 ConstantInt *ZeroShadow;
330 ConstantInt *ShadowPtrMask;
331 ConstantInt *ShadowPtrMul;
332 Constant *ArgTLS;
333 Constant *RetvalTLS;
334 void *(*GetArgTLSPtr)();
335 void *(*GetRetvalTLSPtr)();
336 Constant *GetArgTLS;
337 Constant *GetRetvalTLS;
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000338 Constant *ExternalShadowMask;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000339 FunctionType *DFSanUnionFnTy;
340 FunctionType *DFSanUnionLoadFnTy;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000341 FunctionType *DFSanUnimplementedFnTy;
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000342 FunctionType *DFSanSetLabelFnTy;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000343 FunctionType *DFSanNonzeroLabelFnTy;
Peter Collingbournea1099842014-11-05 17:21:00 +0000344 FunctionType *DFSanVarargWrapperFnTy;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000345 Constant *DFSanUnionFn;
Peter Collingbournedf240b22014-08-06 00:33:40 +0000346 Constant *DFSanCheckedUnionFn;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000347 Constant *DFSanUnionLoadFn;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000348 Constant *DFSanUnimplementedFn;
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000349 Constant *DFSanSetLabelFn;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000350 Constant *DFSanNonzeroLabelFn;
Peter Collingbournea1099842014-11-05 17:21:00 +0000351 Constant *DFSanVarargWrapperFn;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000352 MDNode *ColdCallWeights;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000353 DFSanABIList ABIList;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000354 DenseMap<Value *, Function *> UnwrappedFnMap;
Reid Kleckneree4930b2017-05-02 22:07:37 +0000355 AttrBuilder ReadOnlyNoneAttrs;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000356 bool DFSanRuntimeShadowMask = false;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000357
358 Value *getShadowAddress(Value *Addr, Instruction *Pos);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000359 bool isInstrumented(const Function *F);
360 bool isInstrumented(const GlobalAlias *GA);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000361 FunctionType *getArgsFunctionType(FunctionType *T);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000362 FunctionType *getTrampolineFunctionType(FunctionType *T);
Peter Collingbourne32f54052018-02-22 19:09:07 +0000363 TransformedFunction getCustomFunctionType(FunctionType *T);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000364 InstrumentedABI getInstrumentedABI();
365 WrapperKind getWrapperKind(Function *F);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000366 void addGlobalNamePrefix(GlobalValue *GV);
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000367 Function *buildWrapperFunction(Function *F, StringRef NewFName,
368 GlobalValue::LinkageTypes NewFLink,
369 FunctionType *NewFT);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000370 Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000371
Eugene Zelenkofce43572017-10-21 00:57:46 +0000372public:
373 static char ID;
374
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000375 DataFlowSanitizer(
376 const std::vector<std::string> &ABIListFiles = std::vector<std::string>(),
377 void *(*getArgTLS)() = nullptr, void *(*getRetValTLS)() = nullptr);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000378
Craig Topper3e4c6972014-03-05 09:10:37 +0000379 bool doInitialization(Module &M) override;
380 bool runOnModule(Module &M) override;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000381};
382
383struct DFSanFunction {
384 DataFlowSanitizer &DFS;
385 Function *F;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000386 DominatorTree DT;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000387 DataFlowSanitizer::InstrumentedABI IA;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000388 bool IsNativeABI;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000389 Value *ArgTLSPtr = nullptr;
390 Value *RetvalTLSPtr = nullptr;
391 AllocaInst *LabelReturnAlloca = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000392 DenseMap<Value *, Value *> ValShadowMap;
393 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000394 std::vector<std::pair<PHINode *, PHINode *>> PHIFixups;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000395 DenseSet<Instruction *> SkipInsts;
Peter Collingbournefab565a2014-08-22 01:18:18 +0000396 std::vector<Value *> NonZeroChecks;
Peter Collingbournedf240b22014-08-06 00:33:40 +0000397 bool AvoidNewBlocks;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000398
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000399 struct CachedCombinedShadow {
400 BasicBlock *Block;
401 Value *Shadow;
402 };
403 DenseMap<std::pair<Value *, Value *>, CachedCombinedShadow>
404 CachedCombinedShadows;
Peter Collingbourne9947c492014-07-15 22:13:19 +0000405 DenseMap<Value *, std::set<Value *>> ShadowElements;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000406
Peter Collingbourne68162e72013-08-14 18:54:12 +0000407 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
Eugene Zelenkofce43572017-10-21 00:57:46 +0000408 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()), IsNativeABI(IsNativeABI) {
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000409 DT.recalculate(*F);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000410 // FIXME: Need to track down the register allocator issue which causes poor
411 // performance in pathological cases with large numbers of basic blocks.
412 AvoidNewBlocks = F->size() > 1000;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000413 }
Eugene Zelenkofce43572017-10-21 00:57:46 +0000414
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000415 Value *getArgTLSPtr();
416 Value *getArgTLS(unsigned Index, Instruction *Pos);
417 Value *getRetvalTLS();
418 Value *getShadow(Value *V);
419 void setShadow(Instruction *I, Value *Shadow);
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000420 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000421 Value *combineOperandShadows(Instruction *Inst);
422 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
423 Instruction *Pos);
424 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
425 Instruction *Pos);
426};
427
428class DFSanVisitor : public InstVisitor<DFSanVisitor> {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000429public:
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000430 DFSanFunction &DFSF;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000431
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000432 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
433
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000434 const DataLayout &getDataLayout() const {
435 return DFSF.F->getParent()->getDataLayout();
436 }
437
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000438 void visitOperandShadowInst(Instruction &I);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000439 void visitBinaryOperator(BinaryOperator &BO);
440 void visitCastInst(CastInst &CI);
441 void visitCmpInst(CmpInst &CI);
442 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
443 void visitLoadInst(LoadInst &LI);
444 void visitStoreInst(StoreInst &SI);
445 void visitReturnInst(ReturnInst &RI);
446 void visitCallSite(CallSite CS);
447 void visitPHINode(PHINode &PN);
448 void visitExtractElementInst(ExtractElementInst &I);
449 void visitInsertElementInst(InsertElementInst &I);
450 void visitShuffleVectorInst(ShuffleVectorInst &I);
451 void visitExtractValueInst(ExtractValueInst &I);
452 void visitInsertValueInst(InsertValueInst &I);
453 void visitAllocaInst(AllocaInst &I);
454 void visitSelectInst(SelectInst &I);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000455 void visitMemSetInst(MemSetInst &I);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000456 void visitMemTransferInst(MemTransferInst &I);
457};
458
Eugene Zelenkofce43572017-10-21 00:57:46 +0000459} // end anonymous namespace
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000460
461char DataFlowSanitizer::ID;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000462
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000463INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
464 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
465
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000466ModulePass *
467llvm::createDataFlowSanitizerPass(const std::vector<std::string> &ABIListFiles,
468 void *(*getArgTLS)(),
469 void *(*getRetValTLS)()) {
470 return new DataFlowSanitizer(ABIListFiles, getArgTLS, getRetValTLS);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000471}
472
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000473DataFlowSanitizer::DataFlowSanitizer(
474 const std::vector<std::string> &ABIListFiles, void *(*getArgTLS)(),
475 void *(*getRetValTLS)())
Eugene Zelenkofce43572017-10-21 00:57:46 +0000476 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS) {
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000477 std::vector<std::string> AllABIListFiles(std::move(ABIListFiles));
478 AllABIListFiles.insert(AllABIListFiles.end(), ClABIListFiles.begin(),
479 ClABIListFiles.end());
480 ABIList.set(SpecialCaseList::createOrDie(AllABIListFiles));
Peter Collingbourne68162e72013-08-14 18:54:12 +0000481}
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000482
Peter Collingbourne68162e72013-08-14 18:54:12 +0000483FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000484 SmallVector<Type *, 4> ArgTypes(T->param_begin(), T->param_end());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000485 ArgTypes.append(T->getNumParams(), ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000486 if (T->isVarArg())
487 ArgTypes.push_back(ShadowPtrTy);
488 Type *RetType = T->getReturnType();
489 if (!RetType->isVoidTy())
Serge Gueltone38003f2017-05-09 19:31:13 +0000490 RetType = StructType::get(RetType, ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000491 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
492}
493
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000494FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
495 assert(!T->isVarArg());
Eugene Zelenkofce43572017-10-21 00:57:46 +0000496 SmallVector<Type *, 4> ArgTypes;
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000497 ArgTypes.push_back(T->getPointerTo());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000498 ArgTypes.append(T->param_begin(), T->param_end());
499 ArgTypes.append(T->getNumParams(), ShadowTy);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000500 Type *RetType = T->getReturnType();
501 if (!RetType->isVoidTy())
502 ArgTypes.push_back(ShadowPtrTy);
503 return FunctionType::get(T->getReturnType(), ArgTypes, false);
504}
505
Peter Collingbourne32f54052018-02-22 19:09:07 +0000506TransformedFunction DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000507 SmallVector<Type *, 4> ArgTypes;
Peter Collingbourne32f54052018-02-22 19:09:07 +0000508
509 // Some parameters of the custom function being constructed are
510 // parameters of T. Record the mapping from parameters of T to
511 // parameters of the custom function, so that parameter attributes
512 // at call sites can be updated.
513 std::vector<unsigned> ArgumentIndexMapping;
514 for (unsigned i = 0, ie = T->getNumParams(); i != ie; ++i) {
515 Type* param_type = T->getParamType(i);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000516 FunctionType *FT;
Peter Collingbourne32f54052018-02-22 19:09:07 +0000517 if (isa<PointerType>(param_type) && (FT = dyn_cast<FunctionType>(
518 cast<PointerType>(param_type)->getElementType()))) {
519 ArgumentIndexMapping.push_back(ArgTypes.size());
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000520 ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
521 ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
522 } else {
Peter Collingbourne32f54052018-02-22 19:09:07 +0000523 ArgumentIndexMapping.push_back(ArgTypes.size());
524 ArgTypes.push_back(param_type);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000525 }
526 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000527 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
528 ArgTypes.push_back(ShadowTy);
Peter Collingbournedd3486e2014-10-30 13:22:57 +0000529 if (T->isVarArg())
530 ArgTypes.push_back(ShadowPtrTy);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000531 Type *RetType = T->getReturnType();
532 if (!RetType->isVoidTy())
533 ArgTypes.push_back(ShadowPtrTy);
Peter Collingbourne32f54052018-02-22 19:09:07 +0000534 return TransformedFunction(
535 T, FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg()),
536 ArgumentIndexMapping);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000537}
538
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000539bool DataFlowSanitizer::doInitialization(Module &M) {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000540 Triple TargetTriple(M.getTargetTriple());
541 bool IsX86_64 = TargetTriple.getArch() == Triple::x86_64;
Alexander Richardson85e200e2018-06-25 16:49:20 +0000542 bool IsMIPS64 = TargetTriple.isMIPS64();
Eugene Zelenkofce43572017-10-21 00:57:46 +0000543 bool IsAArch64 = TargetTriple.getArch() == Triple::aarch64 ||
544 TargetTriple.getArch() == Triple::aarch64_be;
Peter Collingbourne0826e602014-12-05 21:22:32 +0000545
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000546 const DataLayout &DL = M.getDataLayout();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000547
548 Mod = &M;
549 Ctx = &M.getContext();
550 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
551 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000552 IntptrTy = DL.getIntPtrType(*Ctx);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000553 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000554 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
Peter Collingbourne0826e602014-12-05 21:22:32 +0000555 if (IsX86_64)
556 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
557 else if (IsMIPS64)
558 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0xF000000000LL);
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000559 // AArch64 supports multiple VMAs and the shadow mask is set at runtime.
Adhemerval Zanellabfe1eaf2015-07-30 20:49:35 +0000560 else if (IsAArch64)
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000561 DFSanRuntimeShadowMask = true;
Peter Collingbourne0826e602014-12-05 21:22:32 +0000562 else
563 report_fatal_error("unsupported triple");
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000564
565 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
566 DFSanUnionFnTy =
567 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
568 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
569 DFSanUnionLoadFnTy =
570 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000571 DFSanUnimplementedFnTy = FunctionType::get(
572 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000573 Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
574 DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
575 DFSanSetLabelArgs, /*isVarArg=*/false);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000576 DFSanNonzeroLabelFnTy = FunctionType::get(
Craig Toppere1d12942014-08-27 05:25:25 +0000577 Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
Peter Collingbournea1099842014-11-05 17:21:00 +0000578 DFSanVarargWrapperFnTy = FunctionType::get(
579 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000580
581 if (GetArgTLSPtr) {
582 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
Craig Topperf40110f2014-04-25 05:29:35 +0000583 ArgTLS = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000584 GetArgTLS = ConstantExpr::getIntToPtr(
585 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
586 PointerType::getUnqual(
Serge Guelton778ece82017-05-10 13:24:17 +0000587 FunctionType::get(PointerType::getUnqual(ArgTLSTy), false)));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000588 }
589 if (GetRetvalTLSPtr) {
Craig Topperf40110f2014-04-25 05:29:35 +0000590 RetvalTLS = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000591 GetRetvalTLS = ConstantExpr::getIntToPtr(
592 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
593 PointerType::getUnqual(
Serge Guelton778ece82017-05-10 13:24:17 +0000594 FunctionType::get(PointerType::getUnqual(ShadowTy), false)));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000595 }
596
597 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
598 return true;
599}
600
Peter Collingbourne59b12622013-08-22 20:08:08 +0000601bool DataFlowSanitizer::isInstrumented(const Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000602 return !ABIList.isIn(*F, "uninstrumented");
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000603}
604
Peter Collingbourne59b12622013-08-22 20:08:08 +0000605bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000606 return !ABIList.isIn(*GA, "uninstrumented");
Peter Collingbourne59b12622013-08-22 20:08:08 +0000607}
608
Peter Collingbourne68162e72013-08-14 18:54:12 +0000609DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000610 return ClArgsABI ? IA_Args : IA_TLS;
611}
612
Peter Collingbourne68162e72013-08-14 18:54:12 +0000613DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000614 if (ABIList.isIn(*F, "functional"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000615 return WK_Functional;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000616 if (ABIList.isIn(*F, "discard"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000617 return WK_Discard;
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +0000618 if (ABIList.isIn(*F, "custom"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000619 return WK_Custom;
620
621 return WK_Warning;
622}
623
Peter Collingbourne59b12622013-08-22 20:08:08 +0000624void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
625 std::string GVName = GV->getName(), Prefix = "dfs$";
626 GV->setName(Prefix + GVName);
627
628 // Try to change the name of the function in module inline asm. We only do
629 // this for specific asm directives, currently only ".symver", to try to avoid
630 // corrupting asm which happens to contain the symbol name as a substring.
631 // Note that the substitution for .symver assumes that the versioned symbol
632 // also has an instrumented name.
633 std::string Asm = GV->getParent()->getModuleInlineAsm();
634 std::string SearchStr = ".symver " + GVName + ",";
635 size_t Pos = Asm.find(SearchStr);
636 if (Pos != std::string::npos) {
637 Asm.replace(Pos, SearchStr.size(),
638 ".symver " + Prefix + GVName + "," + Prefix);
639 GV->getParent()->setModuleInlineAsm(Asm);
640 }
641}
642
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000643Function *
644DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
645 GlobalValue::LinkageTypes NewFLink,
646 FunctionType *NewFT) {
647 FunctionType *FT = F->getFunctionType();
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +0000648 Function *NewF = Function::Create(NewFT, NewFLink, F->getAddressSpace(),
649 NewFName, F->getParent());
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000650 NewF->copyAttributesFrom(F);
651 NewF->removeAttributes(
Reid Klecknerb5180542017-03-21 16:57:19 +0000652 AttributeList::ReturnIndex,
Reid Kleckneree4930b2017-05-02 22:07:37 +0000653 AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000654
655 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
Peter Collingbournea1099842014-11-05 17:21:00 +0000656 if (F->isVarArg()) {
Reid Kleckneree4930b2017-05-02 22:07:37 +0000657 NewF->removeAttributes(AttributeList::FunctionIndex,
658 AttrBuilder().addAttribute("split-stack"));
Peter Collingbournea1099842014-11-05 17:21:00 +0000659 CallInst::Create(DFSanVarargWrapperFn,
660 IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "",
661 BB);
662 new UnreachableInst(*Ctx, BB);
663 } else {
664 std::vector<Value *> Args;
665 unsigned n = FT->getNumParams();
666 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
667 Args.push_back(&*ai);
668 CallInst *CI = CallInst::Create(F, Args, "", BB);
669 if (FT->getReturnType()->isVoidTy())
670 ReturnInst::Create(*Ctx, BB);
671 else
672 ReturnInst::Create(*Ctx, CI, BB);
673 }
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000674
675 return NewF;
676}
677
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000678Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
679 StringRef FName) {
680 FunctionType *FTT = getTrampolineFunctionType(FT);
681 Constant *C = Mod->getOrInsertFunction(FName, FTT);
682 Function *F = dyn_cast<Function>(C);
683 if (F && F->isDeclaration()) {
684 F->setLinkage(GlobalValue::LinkOnceODRLinkage);
685 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
686 std::vector<Value *> Args;
687 Function::arg_iterator AI = F->arg_begin(); ++AI;
688 for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
689 Args.push_back(&*AI);
Reid Kleckner45707d42017-03-16 22:59:15 +0000690 CallInst *CI = CallInst::Create(&*F->arg_begin(), Args, "", BB);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000691 ReturnInst *RI;
692 if (FT->getReturnType()->isVoidTy())
693 RI = ReturnInst::Create(*Ctx, BB);
694 else
695 RI = ReturnInst::Create(*Ctx, CI, BB);
696
697 DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
698 Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
699 for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000700 DFSF.ValShadowMap[&*ValAI] = &*ShadowAI;
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000701 DFSanVisitor(DFSF).visitCallInst(*CI);
702 if (!FT->getReturnType()->isVoidTy())
703 new StoreInst(DFSF.getShadow(RI->getReturnValue()),
Reid Kleckner45707d42017-03-16 22:59:15 +0000704 &*std::prev(F->arg_end()), RI);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000705 }
706
707 return C;
708}
709
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000710bool DataFlowSanitizer::runOnModule(Module &M) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000711 if (ABIList.isIn(M, "skip"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000712 return false;
713
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000714 if (!GetArgTLSPtr) {
715 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
716 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
717 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
718 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
719 }
720 if (!GetRetvalTLSPtr) {
721 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
722 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
723 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
724 }
725
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000726 ExternalShadowMask =
727 Mod->getOrInsertGlobal(kDFSanExternShadowPtrMask, IntptrTy);
728
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000729 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
730 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000731 F->addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
732 F->addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
733 F->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Reid Klecknera0b45f42017-05-03 18:17:31 +0000734 F->addParamAttr(0, Attribute::ZExt);
735 F->addParamAttr(1, Attribute::ZExt);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000736 }
737 DFSanCheckedUnionFn = Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy);
738 if (Function *F = dyn_cast<Function>(DFSanCheckedUnionFn)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000739 F->addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
740 F->addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
741 F->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Reid Klecknera0b45f42017-05-03 18:17:31 +0000742 F->addParamAttr(0, Attribute::ZExt);
743 F->addParamAttr(1, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000744 }
745 DFSanUnionLoadFn =
746 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
747 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000748 F->addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
749 F->addAttribute(AttributeList::FunctionIndex, Attribute::ReadOnly);
750 F->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000751 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000752 DFSanUnimplementedFn =
753 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000754 DFSanSetLabelFn =
755 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
756 if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
Reid Klecknera0b45f42017-05-03 18:17:31 +0000757 F->addParamAttr(0, Attribute::ZExt);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000758 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000759 DFSanNonzeroLabelFn =
760 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
Peter Collingbournea1099842014-11-05 17:21:00 +0000761 DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper",
762 DFSanVarargWrapperFnTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000763
764 std::vector<Function *> FnsToInstrument;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000765 SmallPtrSet<Function *, 2> FnsWithNativeABI;
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000766 for (Function &i : M) {
767 if (!i.isIntrinsic() &&
768 &i != DFSanUnionFn &&
769 &i != DFSanCheckedUnionFn &&
770 &i != DFSanUnionLoadFn &&
771 &i != DFSanUnimplementedFn &&
772 &i != DFSanSetLabelFn &&
773 &i != DFSanNonzeroLabelFn &&
774 &i != DFSanVarargWrapperFn)
775 FnsToInstrument.push_back(&i);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000776 }
777
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000778 // Give function aliases prefixes when necessary, and build wrappers where the
779 // instrumentedness is inconsistent.
Peter Collingbourne59b12622013-08-22 20:08:08 +0000780 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
781 GlobalAlias *GA = &*i;
782 ++i;
783 // Don't stop on weak. We assume people aren't playing games with the
784 // instrumentedness of overridden weak aliases.
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000785 if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000786 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
787 if (GAInst && FInst) {
788 addGlobalNamePrefix(GA);
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000789 } else if (GAInst != FInst) {
790 // Non-instrumented alias of an instrumented function, or vice versa.
791 // Replace the alias with a native-ABI wrapper of the aliasee. The pass
792 // below will take care of instrumenting it.
793 Function *NewF =
794 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000795 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000796 NewF->takeName(GA);
797 GA->eraseFromParent();
798 FnsToInstrument.push_back(NewF);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000799 }
800 }
801 }
802
Reid Kleckneree4930b2017-05-02 22:07:37 +0000803 ReadOnlyNoneAttrs.addAttribute(Attribute::ReadOnly)
804 .addAttribute(Attribute::ReadNone);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000805
806 // First, change the ABI of every function in the module. ABI-listed
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000807 // functions keep their original ABI and get a wrapper function.
808 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
809 e = FnsToInstrument.end();
810 i != e; ++i) {
811 Function &F = **i;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000812 FunctionType *FT = F.getFunctionType();
Peter Collingbourne68162e72013-08-14 18:54:12 +0000813
Peter Collingbourne59b12622013-08-22 20:08:08 +0000814 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
815 FT->getReturnType()->isVoidTy());
Peter Collingbourne68162e72013-08-14 18:54:12 +0000816
817 if (isInstrumented(&F)) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000818 // Instrumented functions get a 'dfs$' prefix. This allows us to more
819 // easily identify cases of mismatching ABIs.
820 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000821 FunctionType *NewFT = getArgsFunctionType(FT);
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +0000822 Function *NewF = Function::Create(NewFT, F.getLinkage(),
823 F.getAddressSpace(), "", &M);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000824 NewF->copyAttributesFrom(&F);
825 NewF->removeAttributes(
Reid Klecknerb5180542017-03-21 16:57:19 +0000826 AttributeList::ReturnIndex,
Reid Kleckneree4930b2017-05-02 22:07:37 +0000827 AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000828 for (Function::arg_iterator FArg = F.arg_begin(),
829 NewFArg = NewF->arg_begin(),
830 FArgEnd = F.arg_end();
831 FArg != FArgEnd; ++FArg, ++NewFArg) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000832 FArg->replaceAllUsesWith(&*NewFArg);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000833 }
834 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
835
Chandler Carruthcdf47882014-03-09 03:16:01 +0000836 for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
837 UI != UE;) {
838 BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
839 ++UI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000840 if (BA) {
841 BA->replaceAllUsesWith(
842 BlockAddress::get(NewF, BA->getBasicBlock()));
843 delete BA;
844 }
845 }
846 F.replaceAllUsesWith(
847 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
848 NewF->takeName(&F);
849 F.eraseFromParent();
850 *i = NewF;
Peter Collingbourne59b12622013-08-22 20:08:08 +0000851 addGlobalNamePrefix(NewF);
852 } else {
853 addGlobalNamePrefix(&F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000854 }
Peter Collingbourne59b12622013-08-22 20:08:08 +0000855 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000856 // Build a wrapper function for F. The wrapper simply calls F, and is
857 // added to FnsToInstrument so that any instrumentation according to its
858 // WrapperKind is done in the second pass below.
859 FunctionType *NewFT = getInstrumentedABI() == IA_Args
860 ? getArgsFunctionType(FT)
861 : FT;
Peter Collingbourned03bf122018-03-30 18:37:55 +0000862
863 // If the function being wrapped has local linkage, then preserve the
864 // function's linkage in the wrapper function.
865 GlobalValue::LinkageTypes wrapperLinkage =
866 F.hasLocalLinkage()
867 ? F.getLinkage()
868 : GlobalValue::LinkOnceODRLinkage;
869
Alexey Samsonov6dae24d2013-08-23 07:42:51 +0000870 Function *NewF = buildWrapperFunction(
871 &F, std::string("dfsw$") + std::string(F.getName()),
Peter Collingbourned03bf122018-03-30 18:37:55 +0000872 wrapperLinkage, NewFT);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000873 if (getInstrumentedABI() == IA_TLS)
Reid Klecknerb5180542017-03-21 16:57:19 +0000874 NewF->removeAttributes(AttributeList::FunctionIndex, ReadOnlyNoneAttrs);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000875
Peter Collingbourne68162e72013-08-14 18:54:12 +0000876 Value *WrappedFnCst =
877 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
878 F.replaceAllUsesWith(WrappedFnCst);
David Blaikiec6c6c7b2014-10-07 22:59:46 +0000879
Peter Collingbourne68162e72013-08-14 18:54:12 +0000880 UnwrappedFnMap[WrappedFnCst] = &F;
881 *i = NewF;
882
883 if (!F.isDeclaration()) {
884 // This function is probably defining an interposition of an
885 // uninstrumented function and hence needs to keep the original ABI.
886 // But any functions it may call need to use the instrumented ABI, so
887 // we instrument it in a mode which preserves the original ABI.
888 FnsWithNativeABI.insert(&F);
889
890 // This code needs to rebuild the iterators, as they may be invalidated
891 // by the push_back, taking care that the new range does not include
892 // any functions added by this code.
893 size_t N = i - FnsToInstrument.begin(),
894 Count = e - FnsToInstrument.begin();
895 FnsToInstrument.push_back(&F);
896 i = FnsToInstrument.begin() + N;
897 e = FnsToInstrument.begin() + Count;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000898 }
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +0000899 // Hopefully, nobody will try to indirectly call a vararg
900 // function... yet.
901 } else if (FT->isVarArg()) {
902 UnwrappedFnMap[&F] = &F;
903 *i = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000904 }
905 }
906
Benjamin Kramer135f7352016-06-26 12:28:59 +0000907 for (Function *i : FnsToInstrument) {
908 if (!i || i->isDeclaration())
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000909 continue;
910
Benjamin Kramer135f7352016-06-26 12:28:59 +0000911 removeUnreachableBlocks(*i);
Peter Collingbourneae66d572013-08-09 21:42:53 +0000912
Benjamin Kramer135f7352016-06-26 12:28:59 +0000913 DFSanFunction DFSF(*this, i, FnsWithNativeABI.count(i));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000914
915 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
916 // Build a copy of the list before iterating over it.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000917 SmallVector<BasicBlock *, 4> BBList(depth_first(&i->getEntryBlock()));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000918
Benjamin Kramer135f7352016-06-26 12:28:59 +0000919 for (BasicBlock *i : BBList) {
920 Instruction *Inst = &i->front();
Eugene Zelenkofce43572017-10-21 00:57:46 +0000921 while (true) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000922 // DFSanVisitor may split the current basic block, changing the current
923 // instruction's next pointer and moving the next instruction to the
924 // tail block from which we should continue.
925 Instruction *Next = Inst->getNextNode();
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000926 // DFSanVisitor may delete Inst, so keep track of whether it was a
927 // terminator.
Chandler Carruth9ae926b2018-08-26 09:51:22 +0000928 bool IsTerminator = Inst->isTerminator();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000929 if (!DFSF.SkipInsts.count(Inst))
930 DFSanVisitor(DFSF).visit(Inst);
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000931 if (IsTerminator)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000932 break;
933 Inst = Next;
934 }
935 }
936
Peter Collingbourne68162e72013-08-14 18:54:12 +0000937 // We will not necessarily be able to compute the shadow for every phi node
938 // until we have visited every block. Therefore, the code that handles phi
939 // nodes adds them to the PHIFixups list so that they can be properly
940 // handled here.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000941 for (std::vector<std::pair<PHINode *, PHINode *>>::iterator
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000942 i = DFSF.PHIFixups.begin(),
943 e = DFSF.PHIFixups.end();
944 i != e; ++i) {
945 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
946 ++val) {
947 i->second->setIncomingValue(
948 val, DFSF.getShadow(i->first->getIncomingValue(val)));
949 }
950 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000951
952 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
953 // places (i.e. instructions in basic blocks we haven't even begun visiting
954 // yet). To make our life easier, do this work in a pass after the main
955 // instrumentation.
956 if (ClDebugNonzeroLabels) {
Peter Collingbournefab565a2014-08-22 01:18:18 +0000957 for (Value *V : DFSF.NonZeroChecks) {
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000958 Instruction *Pos;
Peter Collingbournefab565a2014-08-22 01:18:18 +0000959 if (Instruction *I = dyn_cast<Instruction>(V))
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000960 Pos = I->getNextNode();
961 else
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000962 Pos = &DFSF.F->getEntryBlock().front();
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000963 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
964 Pos = Pos->getNextNode();
965 IRBuilder<> IRB(Pos);
Peter Collingbournefab565a2014-08-22 01:18:18 +0000966 Value *Ne = IRB.CreateICmpNE(V, DFSF.DFS.ZeroShadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000967 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000968 Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000969 IRBuilder<> ThenIRB(BI);
David Blaikieff6409d2015-05-18 22:13:54 +0000970 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn, {});
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000971 }
972 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000973 }
974
975 return false;
976}
977
978Value *DFSanFunction::getArgTLSPtr() {
979 if (ArgTLSPtr)
980 return ArgTLSPtr;
981 if (DFS.ArgTLS)
982 return ArgTLSPtr = DFS.ArgTLS;
983
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000984 IRBuilder<> IRB(&F->getEntryBlock().front());
David Blaikieff6409d2015-05-18 22:13:54 +0000985 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS, {});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000986}
987
988Value *DFSanFunction::getRetvalTLS() {
989 if (RetvalTLSPtr)
990 return RetvalTLSPtr;
991 if (DFS.RetvalTLS)
992 return RetvalTLSPtr = DFS.RetvalTLS;
993
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000994 IRBuilder<> IRB(&F->getEntryBlock().front());
David Blaikieff6409d2015-05-18 22:13:54 +0000995 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS, {});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000996}
997
998Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
999 IRBuilder<> IRB(Pos);
1000 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
1001}
1002
1003Value *DFSanFunction::getShadow(Value *V) {
1004 if (!isa<Argument>(V) && !isa<Instruction>(V))
1005 return DFS.ZeroShadow;
1006 Value *&Shadow = ValShadowMap[V];
1007 if (!Shadow) {
1008 if (Argument *A = dyn_cast<Argument>(V)) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001009 if (IsNativeABI)
1010 return DFS.ZeroShadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001011 switch (IA) {
1012 case DataFlowSanitizer::IA_TLS: {
1013 Value *ArgTLSPtr = getArgTLSPtr();
1014 Instruction *ArgTLSPos =
1015 DFS.ArgTLS ? &*F->getEntryBlock().begin()
1016 : cast<Instruction>(ArgTLSPtr)->getNextNode();
1017 IRBuilder<> IRB(ArgTLSPos);
1018 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
1019 break;
1020 }
1021 case DataFlowSanitizer::IA_Args: {
Reid Kleckner45707d42017-03-16 22:59:15 +00001022 unsigned ArgIdx = A->getArgNo() + F->arg_size() / 2;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001023 Function::arg_iterator i = F->arg_begin();
1024 while (ArgIdx--)
1025 ++i;
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001026 Shadow = &*i;
Peter Collingbourne68162e72013-08-14 18:54:12 +00001027 assert(Shadow->getType() == DFS.ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001028 break;
1029 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001030 }
Peter Collingbournefab565a2014-08-22 01:18:18 +00001031 NonZeroChecks.push_back(Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001032 } else {
1033 Shadow = DFS.ZeroShadow;
1034 }
1035 }
1036 return Shadow;
1037}
1038
1039void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
1040 assert(!ValShadowMap.count(I));
1041 assert(Shadow->getType() == DFS.ShadowTy);
1042 ValShadowMap[I] = Shadow;
1043}
1044
1045Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
1046 assert(Addr != RetvalTLS && "Reinstrumenting?");
1047 IRBuilder<> IRB(Pos);
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +00001048 Value *ShadowPtrMaskValue;
1049 if (DFSanRuntimeShadowMask)
1050 ShadowPtrMaskValue = IRB.CreateLoad(IntptrTy, ExternalShadowMask);
1051 else
1052 ShadowPtrMaskValue = ShadowPtrMask;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001053 return IRB.CreateIntToPtr(
1054 IRB.CreateMul(
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +00001055 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy),
1056 IRB.CreatePtrToInt(ShadowPtrMaskValue, IntptrTy)),
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001057 ShadowPtrMul),
1058 ShadowPtrTy);
1059}
1060
1061// Generates IR to compute the union of the two given shadows, inserting it
1062// before Pos. Returns the computed union Value.
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001063Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
1064 if (V1 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001065 return V2;
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001066 if (V2 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001067 return V1;
1068 if (V1 == V2)
1069 return V1;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001070
Peter Collingbourne9947c492014-07-15 22:13:19 +00001071 auto V1Elems = ShadowElements.find(V1);
1072 auto V2Elems = ShadowElements.find(V2);
1073 if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
1074 if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
1075 V2Elems->second.begin(), V2Elems->second.end())) {
1076 return V1;
1077 } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
1078 V1Elems->second.begin(), V1Elems->second.end())) {
1079 return V2;
1080 }
1081 } else if (V1Elems != ShadowElements.end()) {
1082 if (V1Elems->second.count(V2))
1083 return V1;
1084 } else if (V2Elems != ShadowElements.end()) {
1085 if (V2Elems->second.count(V1))
1086 return V2;
1087 }
1088
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001089 auto Key = std::make_pair(V1, V2);
1090 if (V1 > V2)
1091 std::swap(Key.first, Key.second);
1092 CachedCombinedShadow &CCS = CachedCombinedShadows[Key];
1093 if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
1094 return CCS.Shadow;
1095
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001096 IRBuilder<> IRB(Pos);
Peter Collingbournedf240b22014-08-06 00:33:40 +00001097 if (AvoidNewBlocks) {
David Blaikieff6409d2015-05-18 22:13:54 +00001098 CallInst *Call = IRB.CreateCall(DFS.DFSanCheckedUnionFn, {V1, V2});
Reid Klecknerb5180542017-03-21 16:57:19 +00001099 Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Reid Klecknera0b45f42017-05-03 18:17:31 +00001100 Call->addParamAttr(0, Attribute::ZExt);
1101 Call->addParamAttr(1, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001102
Peter Collingbournedf240b22014-08-06 00:33:40 +00001103 CCS.Block = Pos->getParent();
1104 CCS.Shadow = Call;
1105 } else {
1106 BasicBlock *Head = Pos->getParent();
1107 Value *Ne = IRB.CreateICmpNE(V1, V2);
1108 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
1109 Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
1110 IRBuilder<> ThenIRB(BI);
David Blaikieff6409d2015-05-18 22:13:54 +00001111 CallInst *Call = ThenIRB.CreateCall(DFS.DFSanUnionFn, {V1, V2});
Reid Klecknerb5180542017-03-21 16:57:19 +00001112 Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Reid Klecknera0b45f42017-05-03 18:17:31 +00001113 Call->addParamAttr(0, Attribute::ZExt);
1114 Call->addParamAttr(1, Attribute::ZExt);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001115
Peter Collingbournedf240b22014-08-06 00:33:40 +00001116 BasicBlock *Tail = BI->getSuccessor(0);
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001117 PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
Peter Collingbournedf240b22014-08-06 00:33:40 +00001118 Phi->addIncoming(Call, Call->getParent());
1119 Phi->addIncoming(V1, Head);
1120
1121 CCS.Block = Tail;
1122 CCS.Shadow = Phi;
1123 }
Peter Collingbourne9947c492014-07-15 22:13:19 +00001124
1125 std::set<Value *> UnionElems;
1126 if (V1Elems != ShadowElements.end()) {
1127 UnionElems = V1Elems->second;
1128 } else {
1129 UnionElems.insert(V1);
1130 }
1131 if (V2Elems != ShadowElements.end()) {
1132 UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
1133 } else {
1134 UnionElems.insert(V2);
1135 }
Peter Collingbournedf240b22014-08-06 00:33:40 +00001136 ShadowElements[CCS.Shadow] = std::move(UnionElems);
Peter Collingbourne9947c492014-07-15 22:13:19 +00001137
Peter Collingbournedf240b22014-08-06 00:33:40 +00001138 return CCS.Shadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001139}
1140
1141// A convenience function which folds the shadows of each of the operands
1142// of the provided instruction Inst, inserting the IR before Inst. Returns
1143// the computed union Value.
1144Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
1145 if (Inst->getNumOperands() == 0)
1146 return DFS.ZeroShadow;
1147
1148 Value *Shadow = getShadow(Inst->getOperand(0));
1149 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001150 Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001151 }
1152 return Shadow;
1153}
1154
1155void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
1156 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1157 DFSF.setShadow(&I, CombinedShadow);
1158}
1159
1160// Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
1161// Addr has alignment Align, and take the union of each of those shadows.
1162Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
1163 Instruction *Pos) {
1164 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001165 const auto i = AllocaShadowMap.find(AI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001166 if (i != AllocaShadowMap.end()) {
1167 IRBuilder<> IRB(Pos);
1168 return IRB.CreateLoad(i->second);
1169 }
1170 }
1171
1172 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1173 SmallVector<Value *, 2> Objs;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001174 GetUnderlyingObjects(Addr, Objs, Pos->getModule()->getDataLayout());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001175 bool AllConstants = true;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001176 for (Value *Obj : Objs) {
1177 if (isa<Function>(Obj) || isa<BlockAddress>(Obj))
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001178 continue;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001179 if (isa<GlobalVariable>(Obj) && cast<GlobalVariable>(Obj)->isConstant())
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001180 continue;
1181
1182 AllConstants = false;
1183 break;
1184 }
1185 if (AllConstants)
1186 return DFS.ZeroShadow;
1187
1188 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1189 switch (Size) {
1190 case 0:
1191 return DFS.ZeroShadow;
1192 case 1: {
1193 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
1194 LI->setAlignment(ShadowAlign);
1195 return LI;
1196 }
1197 case 2: {
1198 IRBuilder<> IRB(Pos);
David Blaikie93c54442015-04-03 19:41:44 +00001199 Value *ShadowAddr1 = IRB.CreateGEP(DFS.ShadowTy, ShadowAddr,
1200 ConstantInt::get(DFS.IntptrTy, 1));
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001201 return combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
1202 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign), Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001203 }
1204 }
Peter Collingbournedf240b22014-08-06 00:33:40 +00001205 if (!AvoidNewBlocks && Size % (64 / DFS.ShadowWidth) == 0) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001206 // Fast path for the common case where each byte has identical shadow: load
1207 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
1208 // shadow is non-equal.
1209 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
1210 IRBuilder<> FallbackIRB(FallbackBB);
David Blaikieff6409d2015-05-18 22:13:54 +00001211 CallInst *FallbackCall = FallbackIRB.CreateCall(
1212 DFS.DFSanUnionLoadFn,
1213 {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
Reid Klecknerb5180542017-03-21 16:57:19 +00001214 FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001215
1216 // Compare each of the shadows stored in the loaded 64 bits to each other,
1217 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
1218 IRBuilder<> IRB(Pos);
1219 Value *WideAddr =
1220 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1221 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1222 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
1223 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
1224 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
1225 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1226 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1227
1228 BasicBlock *Head = Pos->getParent();
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001229 BasicBlock *Tail = Head->splitBasicBlock(Pos->getIterator());
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001230
1231 if (DomTreeNode *OldNode = DT.getNode(Head)) {
1232 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1233
1234 DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1235 for (auto Child : Children)
1236 DT.changeImmediateDominator(Child, NewNode);
1237 }
1238
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001239 // In the following code LastBr will refer to the previous basic block's
1240 // conditional branch instruction, whose true successor is fixed up to point
1241 // to the next block during the loop below or to the tail after the final
1242 // iteration.
1243 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1244 ReplaceInstWithInst(Head->getTerminator(), LastBr);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001245 DT.addNewBlock(FallbackBB, Head);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001246
1247 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
1248 Ofs += 64 / DFS.ShadowWidth) {
1249 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001250 DT.addNewBlock(NextBB, LastBr->getParent());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001251 IRBuilder<> NextIRB(NextBB);
David Blaikie93c54442015-04-03 19:41:44 +00001252 WideAddr = NextIRB.CreateGEP(Type::getInt64Ty(*DFS.Ctx), WideAddr,
1253 ConstantInt::get(DFS.IntptrTy, 1));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001254 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1255 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1256 LastBr->setSuccessor(0, NextBB);
1257 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1258 }
1259
1260 LastBr->setSuccessor(0, Tail);
1261 FallbackIRB.CreateBr(Tail);
1262 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1263 Shadow->addIncoming(FallbackCall, FallbackBB);
1264 Shadow->addIncoming(TruncShadow, LastBr->getParent());
1265 return Shadow;
1266 }
1267
1268 IRBuilder<> IRB(Pos);
David Blaikieff6409d2015-05-18 22:13:54 +00001269 CallInst *FallbackCall = IRB.CreateCall(
1270 DFS.DFSanUnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
Reid Klecknerb5180542017-03-21 16:57:19 +00001271 FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001272 return FallbackCall;
1273}
1274
1275void DFSanVisitor::visitLoadInst(LoadInst &LI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001276 auto &DL = LI.getModule()->getDataLayout();
1277 uint64_t Size = DL.getTypeStoreSize(LI.getType());
Peter Collingbourne142fdff2014-08-01 21:18:18 +00001278 if (Size == 0) {
1279 DFSF.setShadow(&LI, DFSF.DFS.ZeroShadow);
1280 return;
1281 }
1282
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001283 uint64_t Align;
1284 if (ClPreserveAlignment) {
1285 Align = LI.getAlignment();
1286 if (Align == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001287 Align = DL.getABITypeAlignment(LI.getType());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001288 } else {
1289 Align = 1;
1290 }
1291 IRBuilder<> IRB(&LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001292 Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
1293 if (ClCombinePointerLabelsOnLoad) {
1294 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001295 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001296 }
1297 if (Shadow != DFSF.DFS.ZeroShadow)
Peter Collingbournefab565a2014-08-22 01:18:18 +00001298 DFSF.NonZeroChecks.push_back(Shadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +00001299
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001300 DFSF.setShadow(&LI, Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001301}
1302
1303void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
1304 Value *Shadow, Instruction *Pos) {
1305 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001306 const auto i = AllocaShadowMap.find(AI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001307 if (i != AllocaShadowMap.end()) {
1308 IRBuilder<> IRB(Pos);
1309 IRB.CreateStore(Shadow, i->second);
1310 return;
1311 }
1312 }
1313
1314 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1315 IRBuilder<> IRB(Pos);
1316 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1317 if (Shadow == DFS.ZeroShadow) {
1318 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1319 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1320 Value *ExtShadowAddr =
1321 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1322 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1323 return;
1324 }
1325
1326 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1327 uint64_t Offset = 0;
1328 if (Size >= ShadowVecSize) {
1329 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1330 Value *ShadowVec = UndefValue::get(ShadowVecTy);
1331 for (unsigned i = 0; i != ShadowVecSize; ++i) {
1332 ShadowVec = IRB.CreateInsertElement(
1333 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1334 }
1335 Value *ShadowVecAddr =
1336 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1337 do {
David Blaikie95d3e532015-04-03 23:03:54 +00001338 Value *CurShadowVecAddr =
1339 IRB.CreateConstGEP1_32(ShadowVecTy, ShadowVecAddr, Offset);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001340 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1341 Size -= ShadowVecSize;
1342 ++Offset;
1343 } while (Size >= ShadowVecSize);
1344 Offset *= ShadowVecSize;
1345 }
1346 while (Size > 0) {
David Blaikie95d3e532015-04-03 23:03:54 +00001347 Value *CurShadowAddr =
1348 IRB.CreateConstGEP1_32(DFS.ShadowTy, ShadowAddr, Offset);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001349 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1350 --Size;
1351 ++Offset;
1352 }
1353}
1354
1355void DFSanVisitor::visitStoreInst(StoreInst &SI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001356 auto &DL = SI.getModule()->getDataLayout();
1357 uint64_t Size = DL.getTypeStoreSize(SI.getValueOperand()->getType());
Peter Collingbourne142fdff2014-08-01 21:18:18 +00001358 if (Size == 0)
1359 return;
1360
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001361 uint64_t Align;
1362 if (ClPreserveAlignment) {
1363 Align = SI.getAlignment();
1364 if (Align == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001365 Align = DL.getABITypeAlignment(SI.getValueOperand()->getType());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001366 } else {
1367 Align = 1;
1368 }
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001369
1370 Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1371 if (ClCombinePointerLabelsOnStore) {
1372 Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001373 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001374 }
1375 DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001376}
1377
1378void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1379 visitOperandShadowInst(BO);
1380}
1381
1382void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1383
1384void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1385
1386void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1387 visitOperandShadowInst(GEPI);
1388}
1389
1390void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1391 visitOperandShadowInst(I);
1392}
1393
1394void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1395 visitOperandShadowInst(I);
1396}
1397
1398void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1399 visitOperandShadowInst(I);
1400}
1401
1402void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1403 visitOperandShadowInst(I);
1404}
1405
1406void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1407 visitOperandShadowInst(I);
1408}
1409
1410void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1411 bool AllLoadsStores = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001412 for (User *U : I.users()) {
1413 if (isa<LoadInst>(U))
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001414 continue;
1415
Chandler Carruthcdf47882014-03-09 03:16:01 +00001416 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001417 if (SI->getPointerOperand() == &I)
1418 continue;
1419 }
1420
1421 AllLoadsStores = false;
1422 break;
1423 }
1424 if (AllLoadsStores) {
1425 IRBuilder<> IRB(&I);
1426 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1427 }
1428 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1429}
1430
1431void DFSanVisitor::visitSelectInst(SelectInst &I) {
1432 Value *CondShadow = DFSF.getShadow(I.getCondition());
1433 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1434 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1435
1436 if (isa<VectorType>(I.getCondition()->getType())) {
1437 DFSF.setShadow(
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001438 &I,
1439 DFSF.combineShadows(
1440 CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001441 } else {
1442 Value *ShadowSel;
1443 if (TrueShadow == FalseShadow) {
1444 ShadowSel = TrueShadow;
1445 } else {
1446 ShadowSel =
1447 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1448 }
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001449 DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001450 }
1451}
1452
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +00001453void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1454 IRBuilder<> IRB(&I);
1455 Value *ValShadow = DFSF.getShadow(I.getValue());
David Blaikieff6409d2015-05-18 22:13:54 +00001456 IRB.CreateCall(DFSF.DFS.DFSanSetLabelFn,
1457 {ValShadow, IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(
1458 *DFSF.DFS.Ctx)),
1459 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +00001460}
1461
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001462void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1463 IRBuilder<> IRB(&I);
1464 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1465 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1466 Value *LenShadow = IRB.CreateMul(
1467 I.getLength(),
1468 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001469 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1470 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1471 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
Daniel Neilson1e687242018-01-19 17:13:12 +00001472 auto *MTI = cast<MemTransferInst>(
1473 IRB.CreateCall(I.getCalledValue(),
1474 {DestShadow, SrcShadow, LenShadow, I.getVolatileCst()}));
Daniel Neilson1e687242018-01-19 17:13:12 +00001475 if (ClPreserveAlignment) {
Daniel Neilson606cf6f2018-02-08 21:28:26 +00001476 MTI->setDestAlignment(I.getDestAlignment() * (DFSF.DFS.ShadowWidth / 8));
1477 MTI->setSourceAlignment(I.getSourceAlignment() * (DFSF.DFS.ShadowWidth / 8));
Daniel Neilson1e687242018-01-19 17:13:12 +00001478 } else {
Daniel Neilson606cf6f2018-02-08 21:28:26 +00001479 MTI->setDestAlignment(DFSF.DFS.ShadowWidth / 8);
1480 MTI->setSourceAlignment(DFSF.DFS.ShadowWidth / 8);
Daniel Neilson1e687242018-01-19 17:13:12 +00001481 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001482}
1483
1484void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001485 if (!DFSF.IsNativeABI && RI.getReturnValue()) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001486 switch (DFSF.IA) {
1487 case DataFlowSanitizer::IA_TLS: {
1488 Value *S = DFSF.getShadow(RI.getReturnValue());
1489 IRBuilder<> IRB(&RI);
1490 IRB.CreateStore(S, DFSF.getRetvalTLS());
1491 break;
1492 }
1493 case DataFlowSanitizer::IA_Args: {
1494 IRBuilder<> IRB(&RI);
1495 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1496 Value *InsVal =
1497 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1498 Value *InsShadow =
1499 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1500 RI.setOperand(0, InsShadow);
1501 break;
1502 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001503 }
1504 }
1505}
1506
1507void DFSanVisitor::visitCallSite(CallSite CS) {
1508 Function *F = CS.getCalledFunction();
1509 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1510 visitOperandShadowInst(*CS.getInstruction());
1511 return;
1512 }
1513
Peter Collingbournea1099842014-11-05 17:21:00 +00001514 // Calls to this function are synthesized in wrappers, and we shouldn't
1515 // instrument them.
1516 if (F == DFSF.DFS.DFSanVarargWrapperFn)
1517 return;
1518
Peter Collingbourne68162e72013-08-14 18:54:12 +00001519 IRBuilder<> IRB(CS.getInstruction());
1520
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001521 DenseMap<Value *, Function *>::iterator i =
1522 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1523 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001524 Function *F = i->second;
1525 switch (DFSF.DFS.getWrapperKind(F)) {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001526 case DataFlowSanitizer::WK_Warning:
Peter Collingbourne68162e72013-08-14 18:54:12 +00001527 CS.setCalledFunction(F);
1528 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1529 IRB.CreateGlobalStringPtr(F->getName()));
1530 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1531 return;
Eugene Zelenkofce43572017-10-21 00:57:46 +00001532 case DataFlowSanitizer::WK_Discard:
Peter Collingbourne68162e72013-08-14 18:54:12 +00001533 CS.setCalledFunction(F);
1534 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1535 return;
Eugene Zelenkofce43572017-10-21 00:57:46 +00001536 case DataFlowSanitizer::WK_Functional:
Peter Collingbourne68162e72013-08-14 18:54:12 +00001537 CS.setCalledFunction(F);
1538 visitOperandShadowInst(*CS.getInstruction());
1539 return;
Eugene Zelenkofce43572017-10-21 00:57:46 +00001540 case DataFlowSanitizer::WK_Custom:
Peter Collingbourne68162e72013-08-14 18:54:12 +00001541 // Don't try to handle invokes of custom functions, it's too complicated.
1542 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1543 // wrapper.
1544 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1545 FunctionType *FT = F->getFunctionType();
Peter Collingbourne32f54052018-02-22 19:09:07 +00001546 TransformedFunction CustomFn = DFSF.DFS.getCustomFunctionType(FT);
Peter Collingbourne68162e72013-08-14 18:54:12 +00001547 std::string CustomFName = "__dfsw_";
1548 CustomFName += F->getName();
Peter Collingbourne32f54052018-02-22 19:09:07 +00001549 Constant *CustomF = DFSF.DFS.Mod->getOrInsertFunction(
1550 CustomFName, CustomFn.TransformedType);
Peter Collingbourne68162e72013-08-14 18:54:12 +00001551 if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1552 CustomFn->copyAttributesFrom(F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001553
Peter Collingbourne68162e72013-08-14 18:54:12 +00001554 // Custom functions returning non-void will write to the return label.
1555 if (!FT->getReturnType()->isVoidTy()) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001556 CustomFn->removeAttributes(AttributeList::FunctionIndex,
Peter Collingbourne68162e72013-08-14 18:54:12 +00001557 DFSF.DFS.ReadOnlyNoneAttrs);
1558 }
1559 }
1560
1561 std::vector<Value *> Args;
1562
1563 CallSite::arg_iterator i = CS.arg_begin();
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001564 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +00001565 Type *T = (*i)->getType();
1566 FunctionType *ParamFT;
1567 if (isa<PointerType>(T) &&
1568 (ParamFT = dyn_cast<FunctionType>(
1569 cast<PointerType>(T)->getElementType()))) {
1570 std::string TName = "dfst";
1571 TName += utostr(FT->getNumParams() - n);
1572 TName += "$";
1573 TName += F->getName();
1574 Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1575 Args.push_back(T);
1576 Args.push_back(
1577 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1578 } else {
1579 Args.push_back(*i);
1580 }
1581 }
Peter Collingbourne68162e72013-08-14 18:54:12 +00001582
1583 i = CS.arg_begin();
Simon Dardisb5205c62017-08-17 14:14:25 +00001584 const unsigned ShadowArgStart = Args.size();
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001585 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
Peter Collingbourne68162e72013-08-14 18:54:12 +00001586 Args.push_back(DFSF.getShadow(*i));
1587
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001588 if (FT->isVarArg()) {
David Blaikie1b01e7e2015-04-05 22:44:57 +00001589 auto *LabelVATy = ArrayType::get(DFSF.DFS.ShadowTy,
1590 CS.arg_size() - FT->getNumParams());
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001591 auto *LabelVAAlloca = new AllocaInst(
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001592 LabelVATy, getDataLayout().getAllocaAddrSpace(),
1593 "labelva", &DFSF.F->getEntryBlock().front());
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001594
1595 for (unsigned n = 0; i != CS.arg_end(); ++i, ++n) {
David Blaikie64646022015-04-05 22:41:44 +00001596 auto LabelVAPtr = IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, n);
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001597 IRB.CreateStore(DFSF.getShadow(*i), LabelVAPtr);
1598 }
1599
David Blaikie64646022015-04-05 22:41:44 +00001600 Args.push_back(IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, 0));
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001601 }
1602
Peter Collingbourne68162e72013-08-14 18:54:12 +00001603 if (!FT->getReturnType()->isVoidTy()) {
1604 if (!DFSF.LabelReturnAlloca) {
1605 DFSF.LabelReturnAlloca =
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001606 new AllocaInst(DFSF.DFS.ShadowTy,
1607 getDataLayout().getAllocaAddrSpace(),
1608 "labelreturn", &DFSF.F->getEntryBlock().front());
Peter Collingbourne68162e72013-08-14 18:54:12 +00001609 }
1610 Args.push_back(DFSF.LabelReturnAlloca);
1611 }
1612
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001613 for (i = CS.arg_begin() + FT->getNumParams(); i != CS.arg_end(); ++i)
1614 Args.push_back(*i);
1615
Peter Collingbourne68162e72013-08-14 18:54:12 +00001616 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1617 CustomCI->setCallingConv(CI->getCallingConv());
Peter Collingbourne32f54052018-02-22 19:09:07 +00001618 CustomCI->setAttributes(TransformFunctionAttributes(CustomFn,
1619 CI->getContext(), CI->getAttributes()));
Peter Collingbourne68162e72013-08-14 18:54:12 +00001620
Simon Dardisb5205c62017-08-17 14:14:25 +00001621 // Update the parameter attributes of the custom call instruction to
1622 // zero extend the shadow parameters. This is required for targets
1623 // which consider ShadowTy an illegal type.
1624 for (unsigned n = 0; n < FT->getNumParams(); n++) {
1625 const unsigned ArgNo = ShadowArgStart + n;
1626 if (CustomCI->getArgOperand(ArgNo)->getType() == DFSF.DFS.ShadowTy)
1627 CustomCI->addParamAttr(ArgNo, Attribute::ZExt);
1628 }
1629
Peter Collingbourne68162e72013-08-14 18:54:12 +00001630 if (!FT->getReturnType()->isVoidTy()) {
1631 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1632 DFSF.setShadow(CustomCI, LabelLoad);
1633 }
1634
1635 CI->replaceAllUsesWith(CustomCI);
1636 CI->eraseFromParent();
1637 return;
1638 }
1639 break;
1640 }
Peter Collingbourne68162e72013-08-14 18:54:12 +00001641 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001642
1643 FunctionType *FT = cast<FunctionType>(
1644 CS.getCalledValue()->getType()->getPointerElementType());
Peter Collingbourne68162e72013-08-14 18:54:12 +00001645 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001646 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1647 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1648 DFSF.getArgTLS(i, CS.getInstruction()));
1649 }
1650 }
1651
Craig Topperf40110f2014-04-25 05:29:35 +00001652 Instruction *Next = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001653 if (!CS.getType()->isVoidTy()) {
1654 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1655 if (II->getNormalDest()->getSinglePredecessor()) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001656 Next = &II->getNormalDest()->front();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001657 } else {
1658 BasicBlock *NewBB =
Chandler Carruthd4500562015-01-19 12:36:53 +00001659 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001660 Next = &NewBB->front();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001661 }
1662 } else {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001663 assert(CS->getIterator() != CS->getParent()->end());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001664 Next = CS->getNextNode();
1665 }
1666
Peter Collingbourne68162e72013-08-14 18:54:12 +00001667 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001668 IRBuilder<> NextIRB(Next);
1669 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1670 DFSF.SkipInsts.insert(LI);
1671 DFSF.setShadow(CS.getInstruction(), LI);
Peter Collingbournefab565a2014-08-22 01:18:18 +00001672 DFSF.NonZeroChecks.push_back(LI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001673 }
1674 }
1675
1676 // Do all instrumentation for IA_Args down here to defer tampering with the
1677 // CFG in a way that SplitEdge may be able to detect.
Peter Collingbourne68162e72013-08-14 18:54:12 +00001678 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1679 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001680 Value *Func =
1681 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1682 std::vector<Value *> Args;
1683
1684 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1685 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1686 Args.push_back(*i);
1687
1688 i = CS.arg_begin();
1689 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1690 Args.push_back(DFSF.getShadow(*i));
1691
1692 if (FT->isVarArg()) {
1693 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1694 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1695 AllocaInst *VarArgShadow =
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001696 new AllocaInst(VarArgArrayTy, getDataLayout().getAllocaAddrSpace(),
1697 "", &DFSF.F->getEntryBlock().front());
David Blaikie4e5d47f42015-04-04 21:07:10 +00001698 Args.push_back(IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, 0));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001699 for (unsigned n = 0; i != e; ++i, ++n) {
David Blaikie4e5d47f42015-04-04 21:07:10 +00001700 IRB.CreateStore(
1701 DFSF.getShadow(*i),
1702 IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, n));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001703 Args.push_back(*i);
1704 }
1705 }
1706
1707 CallSite NewCS;
1708 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1709 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1710 Args);
1711 } else {
1712 NewCS = IRB.CreateCall(Func, Args);
1713 }
1714 NewCS.setCallingConv(CS.getCallingConv());
1715 NewCS.setAttributes(CS.getAttributes().removeAttributes(
Reid Klecknerb5180542017-03-21 16:57:19 +00001716 *DFSF.DFS.Ctx, AttributeList::ReturnIndex,
Pete Cooper2777d8872015-05-06 23:19:56 +00001717 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType())));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001718
1719 if (Next) {
1720 ExtractValueInst *ExVal =
1721 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1722 DFSF.SkipInsts.insert(ExVal);
1723 ExtractValueInst *ExShadow =
1724 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1725 DFSF.SkipInsts.insert(ExShadow);
1726 DFSF.setShadow(ExVal, ExShadow);
Peter Collingbournefab565a2014-08-22 01:18:18 +00001727 DFSF.NonZeroChecks.push_back(ExShadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001728
1729 CS.getInstruction()->replaceAllUsesWith(ExVal);
1730 }
1731
1732 CS.getInstruction()->eraseFromParent();
1733 }
1734}
1735
1736void DFSanVisitor::visitPHINode(PHINode &PN) {
1737 PHINode *ShadowPN =
1738 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1739
1740 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1741 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1742 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1743 ++i) {
1744 ShadowPN->addIncoming(UndefShadow, *i);
1745 }
1746
1747 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1748 DFSF.setShadow(&PN, ShadowPN);
1749}