blob: 790609388c3e2a14346c4de149892a73638a4585 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00006//
7//===----------------------------------------------------------------------===//
Eugene Zelenkofce43572017-10-21 00:57:46 +00008//
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00009/// \file
10/// This file is a part of DataFlowSanitizer, a generalised dynamic data flow
11/// analysis.
12///
13/// Unlike other Sanitizer tools, this tool is not designed to detect a specific
14/// class of bugs on its own. Instead, it provides a generic dynamic data flow
15/// analysis framework to be used by clients to help detect application-specific
16/// issues within their own code.
17///
18/// The analysis is based on automatic propagation of data flow labels (also
19/// known as taint labels) through a program as it performs computation. Each
20/// byte of application memory is backed by two bytes of shadow memory which
21/// hold the label. On Linux/x86_64, memory is laid out as follows:
22///
23/// +--------------------+ 0x800000000000 (top of memory)
24/// | application memory |
25/// +--------------------+ 0x700000008000 (kAppAddr)
26/// | |
27/// | unused |
28/// | |
29/// +--------------------+ 0x200200000000 (kUnusedAddr)
30/// | union table |
31/// +--------------------+ 0x200000000000 (kUnionTableAddr)
32/// | shadow memory |
33/// +--------------------+ 0x000000010000 (kShadowAddr)
34/// | reserved by kernel |
35/// +--------------------+ 0x000000000000
36///
37/// To derive a shadow memory address from an application memory address,
38/// bits 44-46 are cleared to bring the address into the range
39/// [0x000000008000,0x100000000000). Then the address is shifted left by 1 to
40/// account for the double byte representation of shadow labels and move the
41/// address into the shadow memory range. See the function
42/// DataFlowSanitizer::getShadowAddress below.
43///
44/// For more information, please refer to the design document:
45/// http://clang.llvm.org/docs/DataFlowSanitizerDesign.html
Eugene Zelenkofce43572017-10-21 00:57:46 +000046//
47//===----------------------------------------------------------------------===//
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000048
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000049#include "llvm/ADT/DenseMap.h"
50#include "llvm/ADT/DenseSet.h"
51#include "llvm/ADT/DepthFirstIterator.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000052#include "llvm/ADT/None.h"
53#include "llvm/ADT/SmallPtrSet.h"
54#include "llvm/ADT/SmallVector.h"
Peter Collingbourne28a10af2013-08-27 22:09:06 +000055#include "llvm/ADT/StringExtras.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000056#include "llvm/ADT/StringRef.h"
Peter Collingbourne0826e602014-12-05 21:22:32 +000057#include "llvm/ADT/Triple.h"
David Blaikie31b98d22018-06-04 21:23:21 +000058#include "llvm/Transforms/Utils/Local.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000059#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000060#include "llvm/IR/Argument.h"
61#include "llvm/IR/Attributes.h"
62#include "llvm/IR/BasicBlock.h"
63#include "llvm/IR/CallSite.h"
64#include "llvm/IR/Constant.h"
65#include "llvm/IR/Constants.h"
66#include "llvm/IR/DataLayout.h"
67#include "llvm/IR/DerivedTypes.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000068#include "llvm/IR/Dominators.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000069#include "llvm/IR/Function.h"
70#include "llvm/IR/GlobalAlias.h"
71#include "llvm/IR/GlobalValue.h"
72#include "llvm/IR/GlobalVariable.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000073#include "llvm/IR/IRBuilder.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000074#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000075#include "llvm/IR/InstVisitor.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000076#include "llvm/IR/InstrTypes.h"
77#include "llvm/IR/Instruction.h"
78#include "llvm/IR/Instructions.h"
79#include "llvm/IR/IntrinsicInst.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000080#include "llvm/IR/LLVMContext.h"
81#include "llvm/IR/MDBuilder.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000082#include "llvm/IR/Module.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000083#include "llvm/IR/Type.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000084#include "llvm/IR/User.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000085#include "llvm/IR/Value.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000086#include "llvm/Pass.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000087#include "llvm/Support/Casting.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000088#include "llvm/Support/CommandLine.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000089#include "llvm/Support/ErrorHandling.h"
Alexey Samsonovb7dd3292014-07-09 19:40:08 +000090#include "llvm/Support/SpecialCaseList.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000091#include "llvm/Transforms/Instrumentation.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000092#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Peter Collingbourne9947c492014-07-15 22:13:19 +000093#include <algorithm>
Eugene Zelenkofce43572017-10-21 00:57:46 +000094#include <cassert>
95#include <cstddef>
96#include <cstdint>
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000097#include <iterator>
Eugene Zelenkofce43572017-10-21 00:57:46 +000098#include <memory>
Peter Collingbourne9947c492014-07-15 22:13:19 +000099#include <set>
Eugene Zelenkofce43572017-10-21 00:57:46 +0000100#include <string>
Peter Collingbourne9947c492014-07-15 22:13:19 +0000101#include <utility>
Eugene Zelenkofce43572017-10-21 00:57:46 +0000102#include <vector>
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000103
104using namespace llvm;
105
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000106// External symbol to be used when generating the shadow address for
107// architectures with multiple VMAs. Instead of using a constant integer
108// the runtime will set the external mask based on the VMA range.
109static const char *const kDFSanExternShadowPtrMask = "__dfsan_shadow_ptr_mask";
Adhemerval Zanella4754e2d2015-08-24 13:48:10 +0000110
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000111// The -dfsan-preserve-alignment flag controls whether this pass assumes that
112// alignment requirements provided by the input IR are correct. For example,
113// if the input IR contains a load with alignment 8, this flag will cause
114// the shadow load to have alignment 16. This flag is disabled by default as
115// we have unfortunately encountered too much code (including Clang itself;
116// see PR14291) which performs misaligned access.
117static cl::opt<bool> ClPreserveAlignment(
118 "dfsan-preserve-alignment",
119 cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
120 cl::init(false));
121
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000122// The ABI list files control how shadow parameters are passed. The pass treats
Peter Collingbourne68162e72013-08-14 18:54:12 +0000123// every function labelled "uninstrumented" in the ABI list file as conforming
124// to the "native" (i.e. unsanitized) ABI. Unless the ABI list contains
125// additional annotations for those functions, a call to one of those functions
126// will produce a warning message, as the labelling behaviour of the function is
127// unknown. The other supported annotations are "functional" and "discard",
128// which are described below under DataFlowSanitizer::WrapperKind.
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000129static cl::list<std::string> ClABIListFiles(
Peter Collingbourne68162e72013-08-14 18:54:12 +0000130 "dfsan-abilist",
131 cl::desc("File listing native ABI functions and how the pass treats them"),
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000132 cl::Hidden);
133
Peter Collingbourne68162e72013-08-14 18:54:12 +0000134// Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
135// functions (see DataFlowSanitizer::InstrumentedABI below).
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000136static cl::opt<bool> ClArgsABI(
137 "dfsan-args-abi",
138 cl::desc("Use the argument ABI rather than the TLS ABI"),
139 cl::Hidden);
140
Peter Collingbourne0be79e12013-11-21 23:20:54 +0000141// Controls whether the pass includes or ignores the labels of pointers in load
142// instructions.
143static cl::opt<bool> ClCombinePointerLabelsOnLoad(
144 "dfsan-combine-pointer-labels-on-load",
145 cl::desc("Combine the label of the pointer with the label of the data when "
146 "loading from memory."),
147 cl::Hidden, cl::init(true));
148
149// Controls whether the pass includes or ignores the labels of pointers in
150// stores instructions.
151static cl::opt<bool> ClCombinePointerLabelsOnStore(
152 "dfsan-combine-pointer-labels-on-store",
153 cl::desc("Combine the label of the pointer with the label of the data when "
154 "storing in memory."),
155 cl::Hidden, cl::init(false));
156
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000157static cl::opt<bool> ClDebugNonzeroLabels(
158 "dfsan-debug-nonzero-labels",
159 cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
160 "load or return with a nonzero label"),
161 cl::Hidden);
162
Eugene Zelenkofce43572017-10-21 00:57:46 +0000163static StringRef GetGlobalTypeString(const GlobalValue &G) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000164 // Types of GlobalVariables are always pointer types.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000165 Type *GType = G.getValueType();
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000166 // For now we support blacklisting struct types only.
167 if (StructType *SGType = dyn_cast<StructType>(GType)) {
168 if (!SGType->isLiteral())
169 return SGType->getName();
170 }
171 return "<unknown type>";
172}
173
Eugene Zelenkofce43572017-10-21 00:57:46 +0000174namespace {
175
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000176class DFSanABIList {
177 std::unique_ptr<SpecialCaseList> SCL;
178
179 public:
Eugene Zelenkofce43572017-10-21 00:57:46 +0000180 DFSanABIList() = default;
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000181
182 void set(std::unique_ptr<SpecialCaseList> List) { SCL = std::move(List); }
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000183
184 /// Returns whether either this function or its source file are listed in the
185 /// given category.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000186 bool isIn(const Function &F, StringRef Category) const {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000187 return isIn(*F.getParent(), Category) ||
Vlad Tsyrklevich998b2202017-09-25 22:11:11 +0000188 SCL->inSection("dataflow", "fun", F.getName(), Category);
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000189 }
190
191 /// Returns whether this global alias is listed in the given category.
192 ///
193 /// If GA aliases a function, the alias's name is matched as a function name
194 /// would be. Similarly, aliases of globals are matched like globals.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000195 bool isIn(const GlobalAlias &GA, StringRef Category) const {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000196 if (isIn(*GA.getParent(), Category))
197 return true;
198
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000199 if (isa<FunctionType>(GA.getValueType()))
Vlad Tsyrklevich998b2202017-09-25 22:11:11 +0000200 return SCL->inSection("dataflow", "fun", GA.getName(), Category);
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000201
Vlad Tsyrklevich998b2202017-09-25 22:11:11 +0000202 return SCL->inSection("dataflow", "global", GA.getName(), Category) ||
203 SCL->inSection("dataflow", "type", GetGlobalTypeString(GA),
204 Category);
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000205 }
206
207 /// Returns whether this module is listed in the given category.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000208 bool isIn(const Module &M, StringRef Category) const {
Vlad Tsyrklevich998b2202017-09-25 22:11:11 +0000209 return SCL->inSection("dataflow", "src", M.getModuleIdentifier(), Category);
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000210 }
211};
212
Peter Collingbourne32f54052018-02-22 19:09:07 +0000213/// TransformedFunction is used to express the result of transforming one
214/// function type into another. This struct is immutable. It holds metadata
215/// useful for updating calls of the old function to the new type.
216struct TransformedFunction {
217 TransformedFunction(FunctionType* OriginalType,
218 FunctionType* TransformedType,
219 std::vector<unsigned> ArgumentIndexMapping)
220 : OriginalType(OriginalType),
221 TransformedType(TransformedType),
222 ArgumentIndexMapping(ArgumentIndexMapping) {}
223
224 // Disallow copies.
225 TransformedFunction(const TransformedFunction&) = delete;
226 TransformedFunction& operator=(const TransformedFunction&) = delete;
227
228 // Allow moves.
229 TransformedFunction(TransformedFunction&&) = default;
230 TransformedFunction& operator=(TransformedFunction&&) = default;
231
232 /// Type of the function before the transformation.
Vitaly Buka05090702018-09-29 02:17:12 +0000233 FunctionType *OriginalType;
Peter Collingbourne32f54052018-02-22 19:09:07 +0000234
235 /// Type of the function after the transformation.
Vitaly Buka05090702018-09-29 02:17:12 +0000236 FunctionType *TransformedType;
Peter Collingbourne32f54052018-02-22 19:09:07 +0000237
238 /// Transforming a function may change the position of arguments. This
239 /// member records the mapping from each argument's old position to its new
240 /// position. Argument positions are zero-indexed. If the transformation
241 /// from F to F' made the first argument of F into the third argument of F',
242 /// then ArgumentIndexMapping[0] will equal 2.
Vitaly Buka05090702018-09-29 02:17:12 +0000243 std::vector<unsigned> ArgumentIndexMapping;
Peter Collingbourne32f54052018-02-22 19:09:07 +0000244};
245
246/// Given function attributes from a call site for the original function,
247/// return function attributes appropriate for a call to the transformed
248/// function.
249AttributeList TransformFunctionAttributes(
250 const TransformedFunction& TransformedFunction,
251 LLVMContext& Ctx, AttributeList CallSiteAttrs) {
252
253 // Construct a vector of AttributeSet for each function argument.
254 std::vector<llvm::AttributeSet> ArgumentAttributes(
255 TransformedFunction.TransformedType->getNumParams());
256
257 // Copy attributes from the parameter of the original function to the
258 // transformed version. 'ArgumentIndexMapping' holds the mapping from
259 // old argument position to new.
260 for (unsigned i=0, ie = TransformedFunction.ArgumentIndexMapping.size();
261 i < ie; ++i) {
262 unsigned TransformedIndex = TransformedFunction.ArgumentIndexMapping[i];
263 ArgumentAttributes[TransformedIndex] = CallSiteAttrs.getParamAttributes(i);
264 }
265
266 // Copy annotations on varargs arguments.
267 for (unsigned i = TransformedFunction.OriginalType->getNumParams(),
268 ie = CallSiteAttrs.getNumAttrSets(); i<ie; ++i) {
269 ArgumentAttributes.push_back(CallSiteAttrs.getParamAttributes(i));
270 }
271
272 return AttributeList::get(
273 Ctx,
274 CallSiteAttrs.getFnAttributes(),
275 CallSiteAttrs.getRetAttributes(),
276 llvm::makeArrayRef(ArgumentAttributes));
277}
278
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000279class DataFlowSanitizer : public ModulePass {
280 friend struct DFSanFunction;
281 friend class DFSanVisitor;
282
283 enum {
284 ShadowWidth = 16
285 };
286
Peter Collingbourne68162e72013-08-14 18:54:12 +0000287 /// Which ABI should be used for instrumented functions?
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000288 enum InstrumentedABI {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000289 /// Argument and return value labels are passed through additional
290 /// arguments and by modifying the return type.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000291 IA_Args,
Peter Collingbourne68162e72013-08-14 18:54:12 +0000292
293 /// Argument and return value labels are passed through TLS variables
294 /// __dfsan_arg_tls and __dfsan_retval_tls.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000295 IA_TLS
296 };
297
Peter Collingbourne68162e72013-08-14 18:54:12 +0000298 /// How should calls to uninstrumented functions be handled?
299 enum WrapperKind {
300 /// This function is present in an uninstrumented form but we don't know
301 /// how it should be handled. Print a warning and call the function anyway.
302 /// Don't label the return value.
303 WK_Warning,
304
305 /// This function does not write to (user-accessible) memory, and its return
306 /// value is unlabelled.
307 WK_Discard,
308
309 /// This function does not write to (user-accessible) memory, and the label
310 /// of its return value is the union of the label of its arguments.
311 WK_Functional,
312
313 /// Instead of calling the function, a custom wrapper __dfsw_F is called,
314 /// where F is the name of the function. This function may wrap the
315 /// original function or provide its own implementation. This is similar to
316 /// the IA_Args ABI, except that IA_Args uses a struct return type to
317 /// pass the return value shadow in a register, while WK_Custom uses an
318 /// extra pointer argument to return the shadow. This allows the wrapped
319 /// form of the function type to be expressed in C.
320 WK_Custom
321 };
322
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000323 Module *Mod;
324 LLVMContext *Ctx;
325 IntegerType *ShadowTy;
326 PointerType *ShadowPtrTy;
327 IntegerType *IntptrTy;
328 ConstantInt *ZeroShadow;
329 ConstantInt *ShadowPtrMask;
330 ConstantInt *ShadowPtrMul;
331 Constant *ArgTLS;
332 Constant *RetvalTLS;
333 void *(*GetArgTLSPtr)();
334 void *(*GetRetvalTLSPtr)();
335 Constant *GetArgTLS;
336 Constant *GetRetvalTLS;
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000337 Constant *ExternalShadowMask;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000338 FunctionType *DFSanUnionFnTy;
339 FunctionType *DFSanUnionLoadFnTy;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000340 FunctionType *DFSanUnimplementedFnTy;
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000341 FunctionType *DFSanSetLabelFnTy;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000342 FunctionType *DFSanNonzeroLabelFnTy;
Peter Collingbournea1099842014-11-05 17:21:00 +0000343 FunctionType *DFSanVarargWrapperFnTy;
James Y Knightf47d6b32019-01-31 20:35:56 +0000344 FunctionCallee DFSanUnionFn;
345 FunctionCallee DFSanCheckedUnionFn;
346 FunctionCallee DFSanUnionLoadFn;
347 FunctionCallee DFSanUnimplementedFn;
348 FunctionCallee DFSanSetLabelFn;
349 FunctionCallee DFSanNonzeroLabelFn;
350 FunctionCallee DFSanVarargWrapperFn;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000351 MDNode *ColdCallWeights;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000352 DFSanABIList ABIList;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000353 DenseMap<Value *, Function *> UnwrappedFnMap;
Reid Kleckneree4930b2017-05-02 22:07:37 +0000354 AttrBuilder ReadOnlyNoneAttrs;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000355 bool DFSanRuntimeShadowMask = false;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000356
357 Value *getShadowAddress(Value *Addr, Instruction *Pos);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000358 bool isInstrumented(const Function *F);
359 bool isInstrumented(const GlobalAlias *GA);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000360 FunctionType *getArgsFunctionType(FunctionType *T);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000361 FunctionType *getTrampolineFunctionType(FunctionType *T);
Peter Collingbourne32f54052018-02-22 19:09:07 +0000362 TransformedFunction getCustomFunctionType(FunctionType *T);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000363 InstrumentedABI getInstrumentedABI();
364 WrapperKind getWrapperKind(Function *F);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000365 void addGlobalNamePrefix(GlobalValue *GV);
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000366 Function *buildWrapperFunction(Function *F, StringRef NewFName,
367 GlobalValue::LinkageTypes NewFLink,
368 FunctionType *NewFT);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000369 Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000370
Eugene Zelenkofce43572017-10-21 00:57:46 +0000371public:
372 static char ID;
373
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000374 DataFlowSanitizer(
375 const std::vector<std::string> &ABIListFiles = std::vector<std::string>(),
376 void *(*getArgTLS)() = nullptr, void *(*getRetValTLS)() = nullptr);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000377
Craig Topper3e4c6972014-03-05 09:10:37 +0000378 bool doInitialization(Module &M) override;
379 bool runOnModule(Module &M) override;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000380};
381
382struct DFSanFunction {
383 DataFlowSanitizer &DFS;
384 Function *F;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000385 DominatorTree DT;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000386 DataFlowSanitizer::InstrumentedABI IA;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000387 bool IsNativeABI;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000388 Value *ArgTLSPtr = nullptr;
389 Value *RetvalTLSPtr = nullptr;
390 AllocaInst *LabelReturnAlloca = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000391 DenseMap<Value *, Value *> ValShadowMap;
392 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000393 std::vector<std::pair<PHINode *, PHINode *>> PHIFixups;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000394 DenseSet<Instruction *> SkipInsts;
Peter Collingbournefab565a2014-08-22 01:18:18 +0000395 std::vector<Value *> NonZeroChecks;
Peter Collingbournedf240b22014-08-06 00:33:40 +0000396 bool AvoidNewBlocks;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000397
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000398 struct CachedCombinedShadow {
399 BasicBlock *Block;
400 Value *Shadow;
401 };
402 DenseMap<std::pair<Value *, Value *>, CachedCombinedShadow>
403 CachedCombinedShadows;
Peter Collingbourne9947c492014-07-15 22:13:19 +0000404 DenseMap<Value *, std::set<Value *>> ShadowElements;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000405
Peter Collingbourne68162e72013-08-14 18:54:12 +0000406 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
Eugene Zelenkofce43572017-10-21 00:57:46 +0000407 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()), IsNativeABI(IsNativeABI) {
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000408 DT.recalculate(*F);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000409 // FIXME: Need to track down the register allocator issue which causes poor
410 // performance in pathological cases with large numbers of basic blocks.
411 AvoidNewBlocks = F->size() > 1000;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000412 }
Eugene Zelenkofce43572017-10-21 00:57:46 +0000413
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000414 Value *getArgTLSPtr();
415 Value *getArgTLS(unsigned Index, Instruction *Pos);
416 Value *getRetvalTLS();
417 Value *getShadow(Value *V);
418 void setShadow(Instruction *I, Value *Shadow);
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000419 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000420 Value *combineOperandShadows(Instruction *Inst);
421 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
422 Instruction *Pos);
423 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
424 Instruction *Pos);
425};
426
427class DFSanVisitor : public InstVisitor<DFSanVisitor> {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000428public:
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000429 DFSanFunction &DFSF;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000430
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000431 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
432
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000433 const DataLayout &getDataLayout() const {
434 return DFSF.F->getParent()->getDataLayout();
435 }
436
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000437 void visitOperandShadowInst(Instruction &I);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000438 void visitBinaryOperator(BinaryOperator &BO);
439 void visitCastInst(CastInst &CI);
440 void visitCmpInst(CmpInst &CI);
441 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
442 void visitLoadInst(LoadInst &LI);
443 void visitStoreInst(StoreInst &SI);
444 void visitReturnInst(ReturnInst &RI);
445 void visitCallSite(CallSite CS);
446 void visitPHINode(PHINode &PN);
447 void visitExtractElementInst(ExtractElementInst &I);
448 void visitInsertElementInst(InsertElementInst &I);
449 void visitShuffleVectorInst(ShuffleVectorInst &I);
450 void visitExtractValueInst(ExtractValueInst &I);
451 void visitInsertValueInst(InsertValueInst &I);
452 void visitAllocaInst(AllocaInst &I);
453 void visitSelectInst(SelectInst &I);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000454 void visitMemSetInst(MemSetInst &I);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000455 void visitMemTransferInst(MemTransferInst &I);
456};
457
Eugene Zelenkofce43572017-10-21 00:57:46 +0000458} // end anonymous namespace
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000459
460char DataFlowSanitizer::ID;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000461
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000462INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
463 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
464
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000465ModulePass *
466llvm::createDataFlowSanitizerPass(const std::vector<std::string> &ABIListFiles,
467 void *(*getArgTLS)(),
468 void *(*getRetValTLS)()) {
469 return new DataFlowSanitizer(ABIListFiles, getArgTLS, getRetValTLS);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000470}
471
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000472DataFlowSanitizer::DataFlowSanitizer(
473 const std::vector<std::string> &ABIListFiles, void *(*getArgTLS)(),
474 void *(*getRetValTLS)())
Eugene Zelenkofce43572017-10-21 00:57:46 +0000475 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS) {
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000476 std::vector<std::string> AllABIListFiles(std::move(ABIListFiles));
477 AllABIListFiles.insert(AllABIListFiles.end(), ClABIListFiles.begin(),
478 ClABIListFiles.end());
479 ABIList.set(SpecialCaseList::createOrDie(AllABIListFiles));
Peter Collingbourne68162e72013-08-14 18:54:12 +0000480}
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000481
Peter Collingbourne68162e72013-08-14 18:54:12 +0000482FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000483 SmallVector<Type *, 4> ArgTypes(T->param_begin(), T->param_end());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000484 ArgTypes.append(T->getNumParams(), ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000485 if (T->isVarArg())
486 ArgTypes.push_back(ShadowPtrTy);
487 Type *RetType = T->getReturnType();
488 if (!RetType->isVoidTy())
Serge Gueltone38003f2017-05-09 19:31:13 +0000489 RetType = StructType::get(RetType, ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000490 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
491}
492
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000493FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
494 assert(!T->isVarArg());
Eugene Zelenkofce43572017-10-21 00:57:46 +0000495 SmallVector<Type *, 4> ArgTypes;
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000496 ArgTypes.push_back(T->getPointerTo());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000497 ArgTypes.append(T->param_begin(), T->param_end());
498 ArgTypes.append(T->getNumParams(), ShadowTy);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000499 Type *RetType = T->getReturnType();
500 if (!RetType->isVoidTy())
501 ArgTypes.push_back(ShadowPtrTy);
502 return FunctionType::get(T->getReturnType(), ArgTypes, false);
503}
504
Peter Collingbourne32f54052018-02-22 19:09:07 +0000505TransformedFunction DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000506 SmallVector<Type *, 4> ArgTypes;
Peter Collingbourne32f54052018-02-22 19:09:07 +0000507
508 // Some parameters of the custom function being constructed are
509 // parameters of T. Record the mapping from parameters of T to
510 // parameters of the custom function, so that parameter attributes
511 // at call sites can be updated.
512 std::vector<unsigned> ArgumentIndexMapping;
513 for (unsigned i = 0, ie = T->getNumParams(); i != ie; ++i) {
514 Type* param_type = T->getParamType(i);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000515 FunctionType *FT;
Peter Collingbourne32f54052018-02-22 19:09:07 +0000516 if (isa<PointerType>(param_type) && (FT = dyn_cast<FunctionType>(
517 cast<PointerType>(param_type)->getElementType()))) {
518 ArgumentIndexMapping.push_back(ArgTypes.size());
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000519 ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
520 ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
521 } else {
Peter Collingbourne32f54052018-02-22 19:09:07 +0000522 ArgumentIndexMapping.push_back(ArgTypes.size());
523 ArgTypes.push_back(param_type);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000524 }
525 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000526 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
527 ArgTypes.push_back(ShadowTy);
Peter Collingbournedd3486e2014-10-30 13:22:57 +0000528 if (T->isVarArg())
529 ArgTypes.push_back(ShadowPtrTy);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000530 Type *RetType = T->getReturnType();
531 if (!RetType->isVoidTy())
532 ArgTypes.push_back(ShadowPtrTy);
Peter Collingbourne32f54052018-02-22 19:09:07 +0000533 return TransformedFunction(
534 T, FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg()),
535 ArgumentIndexMapping);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000536}
537
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000538bool DataFlowSanitizer::doInitialization(Module &M) {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000539 Triple TargetTriple(M.getTargetTriple());
540 bool IsX86_64 = TargetTriple.getArch() == Triple::x86_64;
Alexander Richardson85e200e2018-06-25 16:49:20 +0000541 bool IsMIPS64 = TargetTriple.isMIPS64();
Eugene Zelenkofce43572017-10-21 00:57:46 +0000542 bool IsAArch64 = TargetTriple.getArch() == Triple::aarch64 ||
543 TargetTriple.getArch() == Triple::aarch64_be;
Peter Collingbourne0826e602014-12-05 21:22:32 +0000544
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000545 const DataLayout &DL = M.getDataLayout();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000546
547 Mod = &M;
548 Ctx = &M.getContext();
549 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
550 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000551 IntptrTy = DL.getIntPtrType(*Ctx);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000552 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000553 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
Peter Collingbourne0826e602014-12-05 21:22:32 +0000554 if (IsX86_64)
555 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
556 else if (IsMIPS64)
557 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0xF000000000LL);
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000558 // AArch64 supports multiple VMAs and the shadow mask is set at runtime.
Adhemerval Zanellabfe1eaf2015-07-30 20:49:35 +0000559 else if (IsAArch64)
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000560 DFSanRuntimeShadowMask = true;
Peter Collingbourne0826e602014-12-05 21:22:32 +0000561 else
562 report_fatal_error("unsupported triple");
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000563
564 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
565 DFSanUnionFnTy =
566 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
567 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
568 DFSanUnionLoadFnTy =
569 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000570 DFSanUnimplementedFnTy = FunctionType::get(
571 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000572 Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
573 DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
574 DFSanSetLabelArgs, /*isVarArg=*/false);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000575 DFSanNonzeroLabelFnTy = FunctionType::get(
Craig Toppere1d12942014-08-27 05:25:25 +0000576 Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
Peter Collingbournea1099842014-11-05 17:21:00 +0000577 DFSanVarargWrapperFnTy = FunctionType::get(
578 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000579
580 if (GetArgTLSPtr) {
581 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
Craig Topperf40110f2014-04-25 05:29:35 +0000582 ArgTLS = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000583 GetArgTLS = ConstantExpr::getIntToPtr(
584 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
585 PointerType::getUnqual(
Serge Guelton778ece82017-05-10 13:24:17 +0000586 FunctionType::get(PointerType::getUnqual(ArgTLSTy), false)));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000587 }
588 if (GetRetvalTLSPtr) {
Craig Topperf40110f2014-04-25 05:29:35 +0000589 RetvalTLS = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000590 GetRetvalTLS = ConstantExpr::getIntToPtr(
591 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
592 PointerType::getUnqual(
Serge Guelton778ece82017-05-10 13:24:17 +0000593 FunctionType::get(PointerType::getUnqual(ShadowTy), false)));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000594 }
595
596 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
597 return true;
598}
599
Peter Collingbourne59b12622013-08-22 20:08:08 +0000600bool DataFlowSanitizer::isInstrumented(const Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000601 return !ABIList.isIn(*F, "uninstrumented");
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000602}
603
Peter Collingbourne59b12622013-08-22 20:08:08 +0000604bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000605 return !ABIList.isIn(*GA, "uninstrumented");
Peter Collingbourne59b12622013-08-22 20:08:08 +0000606}
607
Peter Collingbourne68162e72013-08-14 18:54:12 +0000608DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000609 return ClArgsABI ? IA_Args : IA_TLS;
610}
611
Peter Collingbourne68162e72013-08-14 18:54:12 +0000612DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000613 if (ABIList.isIn(*F, "functional"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000614 return WK_Functional;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000615 if (ABIList.isIn(*F, "discard"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000616 return WK_Discard;
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +0000617 if (ABIList.isIn(*F, "custom"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000618 return WK_Custom;
619
620 return WK_Warning;
621}
622
Peter Collingbourne59b12622013-08-22 20:08:08 +0000623void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
624 std::string GVName = GV->getName(), Prefix = "dfs$";
625 GV->setName(Prefix + GVName);
626
627 // Try to change the name of the function in module inline asm. We only do
628 // this for specific asm directives, currently only ".symver", to try to avoid
629 // corrupting asm which happens to contain the symbol name as a substring.
630 // Note that the substitution for .symver assumes that the versioned symbol
631 // also has an instrumented name.
632 std::string Asm = GV->getParent()->getModuleInlineAsm();
633 std::string SearchStr = ".symver " + GVName + ",";
634 size_t Pos = Asm.find(SearchStr);
635 if (Pos != std::string::npos) {
636 Asm.replace(Pos, SearchStr.size(),
637 ".symver " + Prefix + GVName + "," + Prefix);
638 GV->getParent()->setModuleInlineAsm(Asm);
639 }
640}
641
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000642Function *
643DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
644 GlobalValue::LinkageTypes NewFLink,
645 FunctionType *NewFT) {
646 FunctionType *FT = F->getFunctionType();
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +0000647 Function *NewF = Function::Create(NewFT, NewFLink, F->getAddressSpace(),
648 NewFName, F->getParent());
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000649 NewF->copyAttributesFrom(F);
650 NewF->removeAttributes(
Reid Klecknerb5180542017-03-21 16:57:19 +0000651 AttributeList::ReturnIndex,
Reid Kleckneree4930b2017-05-02 22:07:37 +0000652 AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000653
654 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
Peter Collingbournea1099842014-11-05 17:21:00 +0000655 if (F->isVarArg()) {
Reid Kleckneree4930b2017-05-02 22:07:37 +0000656 NewF->removeAttributes(AttributeList::FunctionIndex,
657 AttrBuilder().addAttribute("split-stack"));
Peter Collingbournea1099842014-11-05 17:21:00 +0000658 CallInst::Create(DFSanVarargWrapperFn,
659 IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "",
660 BB);
661 new UnreachableInst(*Ctx, BB);
662 } else {
663 std::vector<Value *> Args;
664 unsigned n = FT->getNumParams();
665 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
666 Args.push_back(&*ai);
667 CallInst *CI = CallInst::Create(F, Args, "", BB);
668 if (FT->getReturnType()->isVoidTy())
669 ReturnInst::Create(*Ctx, BB);
670 else
671 ReturnInst::Create(*Ctx, CI, BB);
672 }
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000673
674 return NewF;
675}
676
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000677Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
678 StringRef FName) {
679 FunctionType *FTT = getTrampolineFunctionType(FT);
James Y Knightf47d6b32019-01-31 20:35:56 +0000680 FunctionCallee C = Mod->getOrInsertFunction(FName, FTT);
681 Function *F = dyn_cast<Function>(C.getCallee());
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000682 if (F && F->isDeclaration()) {
683 F->setLinkage(GlobalValue::LinkOnceODRLinkage);
684 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
685 std::vector<Value *> Args;
686 Function::arg_iterator AI = F->arg_begin(); ++AI;
687 for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
688 Args.push_back(&*AI);
Reid Kleckner45707d42017-03-16 22:59:15 +0000689 CallInst *CI = CallInst::Create(&*F->arg_begin(), Args, "", BB);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000690 ReturnInst *RI;
691 if (FT->getReturnType()->isVoidTy())
692 RI = ReturnInst::Create(*Ctx, BB);
693 else
694 RI = ReturnInst::Create(*Ctx, CI, BB);
695
696 DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
697 Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
698 for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000699 DFSF.ValShadowMap[&*ValAI] = &*ShadowAI;
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000700 DFSanVisitor(DFSF).visitCallInst(*CI);
701 if (!FT->getReturnType()->isVoidTy())
702 new StoreInst(DFSF.getShadow(RI->getReturnValue()),
Reid Kleckner45707d42017-03-16 22:59:15 +0000703 &*std::prev(F->arg_end()), RI);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000704 }
705
James Y Knightf47d6b32019-01-31 20:35:56 +0000706 return cast<Constant>(C.getCallee());
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000707}
708
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000709bool DataFlowSanitizer::runOnModule(Module &M) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000710 if (ABIList.isIn(M, "skip"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000711 return false;
712
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000713 if (!GetArgTLSPtr) {
714 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
715 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
716 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
717 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
718 }
719 if (!GetRetvalTLSPtr) {
720 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
721 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
722 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
723 }
724
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000725 ExternalShadowMask =
726 Mod->getOrInsertGlobal(kDFSanExternShadowPtrMask, IntptrTy);
727
James Y Knightf47d6b32019-01-31 20:35:56 +0000728 {
729 AttributeList AL;
730 AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
731 Attribute::NoUnwind);
732 AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
733 Attribute::ReadNone);
734 AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
735 Attribute::ZExt);
736 AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
737 AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
738 DFSanUnionFn =
739 Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy, AL);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000740 }
James Y Knightf47d6b32019-01-31 20:35:56 +0000741
742 {
743 AttributeList AL;
744 AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
745 Attribute::NoUnwind);
746 AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
747 Attribute::ReadNone);
748 AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
749 Attribute::ZExt);
750 AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
751 AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
752 DFSanCheckedUnionFn =
753 Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy, AL);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000754 }
James Y Knightf47d6b32019-01-31 20:35:56 +0000755 {
756 AttributeList AL;
757 AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
758 Attribute::NoUnwind);
759 AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
760 Attribute::ReadOnly);
761 AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
762 Attribute::ZExt);
763 DFSanUnionLoadFn =
764 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy, AL);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000765 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000766 DFSanUnimplementedFn =
767 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
James Y Knightf47d6b32019-01-31 20:35:56 +0000768 {
769 AttributeList AL;
770 AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
771 DFSanSetLabelFn =
772 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy, AL);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000773 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000774 DFSanNonzeroLabelFn =
775 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
Peter Collingbournea1099842014-11-05 17:21:00 +0000776 DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper",
777 DFSanVarargWrapperFnTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000778
779 std::vector<Function *> FnsToInstrument;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000780 SmallPtrSet<Function *, 2> FnsWithNativeABI;
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000781 for (Function &i : M) {
782 if (!i.isIntrinsic() &&
James Y Knightf47d6b32019-01-31 20:35:56 +0000783 &i != DFSanUnionFn.getCallee()->stripPointerCasts() &&
784 &i != DFSanCheckedUnionFn.getCallee()->stripPointerCasts() &&
785 &i != DFSanUnionLoadFn.getCallee()->stripPointerCasts() &&
786 &i != DFSanUnimplementedFn.getCallee()->stripPointerCasts() &&
787 &i != DFSanSetLabelFn.getCallee()->stripPointerCasts() &&
788 &i != DFSanNonzeroLabelFn.getCallee()->stripPointerCasts() &&
789 &i != DFSanVarargWrapperFn.getCallee()->stripPointerCasts())
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000790 FnsToInstrument.push_back(&i);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000791 }
792
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000793 // Give function aliases prefixes when necessary, and build wrappers where the
794 // instrumentedness is inconsistent.
Peter Collingbourne59b12622013-08-22 20:08:08 +0000795 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
796 GlobalAlias *GA = &*i;
797 ++i;
798 // Don't stop on weak. We assume people aren't playing games with the
799 // instrumentedness of overridden weak aliases.
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000800 if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000801 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
802 if (GAInst && FInst) {
803 addGlobalNamePrefix(GA);
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000804 } else if (GAInst != FInst) {
805 // Non-instrumented alias of an instrumented function, or vice versa.
806 // Replace the alias with a native-ABI wrapper of the aliasee. The pass
807 // below will take care of instrumenting it.
808 Function *NewF =
809 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000810 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000811 NewF->takeName(GA);
812 GA->eraseFromParent();
813 FnsToInstrument.push_back(NewF);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000814 }
815 }
816 }
817
Reid Kleckneree4930b2017-05-02 22:07:37 +0000818 ReadOnlyNoneAttrs.addAttribute(Attribute::ReadOnly)
819 .addAttribute(Attribute::ReadNone);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000820
821 // First, change the ABI of every function in the module. ABI-listed
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000822 // functions keep their original ABI and get a wrapper function.
823 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
824 e = FnsToInstrument.end();
825 i != e; ++i) {
826 Function &F = **i;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000827 FunctionType *FT = F.getFunctionType();
Peter Collingbourne68162e72013-08-14 18:54:12 +0000828
Peter Collingbourne59b12622013-08-22 20:08:08 +0000829 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
830 FT->getReturnType()->isVoidTy());
Peter Collingbourne68162e72013-08-14 18:54:12 +0000831
832 if (isInstrumented(&F)) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000833 // Instrumented functions get a 'dfs$' prefix. This allows us to more
834 // easily identify cases of mismatching ABIs.
835 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000836 FunctionType *NewFT = getArgsFunctionType(FT);
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +0000837 Function *NewF = Function::Create(NewFT, F.getLinkage(),
838 F.getAddressSpace(), "", &M);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000839 NewF->copyAttributesFrom(&F);
840 NewF->removeAttributes(
Reid Klecknerb5180542017-03-21 16:57:19 +0000841 AttributeList::ReturnIndex,
Reid Kleckneree4930b2017-05-02 22:07:37 +0000842 AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000843 for (Function::arg_iterator FArg = F.arg_begin(),
844 NewFArg = NewF->arg_begin(),
845 FArgEnd = F.arg_end();
846 FArg != FArgEnd; ++FArg, ++NewFArg) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000847 FArg->replaceAllUsesWith(&*NewFArg);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000848 }
849 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
850
Chandler Carruthcdf47882014-03-09 03:16:01 +0000851 for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
852 UI != UE;) {
853 BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
854 ++UI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000855 if (BA) {
856 BA->replaceAllUsesWith(
857 BlockAddress::get(NewF, BA->getBasicBlock()));
858 delete BA;
859 }
860 }
861 F.replaceAllUsesWith(
862 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
863 NewF->takeName(&F);
864 F.eraseFromParent();
865 *i = NewF;
Peter Collingbourne59b12622013-08-22 20:08:08 +0000866 addGlobalNamePrefix(NewF);
867 } else {
868 addGlobalNamePrefix(&F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000869 }
Peter Collingbourne59b12622013-08-22 20:08:08 +0000870 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000871 // Build a wrapper function for F. The wrapper simply calls F, and is
872 // added to FnsToInstrument so that any instrumentation according to its
873 // WrapperKind is done in the second pass below.
874 FunctionType *NewFT = getInstrumentedABI() == IA_Args
875 ? getArgsFunctionType(FT)
876 : FT;
Peter Collingbourned03bf122018-03-30 18:37:55 +0000877
878 // If the function being wrapped has local linkage, then preserve the
879 // function's linkage in the wrapper function.
880 GlobalValue::LinkageTypes wrapperLinkage =
881 F.hasLocalLinkage()
882 ? F.getLinkage()
883 : GlobalValue::LinkOnceODRLinkage;
884
Alexey Samsonov6dae24d2013-08-23 07:42:51 +0000885 Function *NewF = buildWrapperFunction(
886 &F, std::string("dfsw$") + std::string(F.getName()),
Peter Collingbourned03bf122018-03-30 18:37:55 +0000887 wrapperLinkage, NewFT);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000888 if (getInstrumentedABI() == IA_TLS)
Reid Klecknerb5180542017-03-21 16:57:19 +0000889 NewF->removeAttributes(AttributeList::FunctionIndex, ReadOnlyNoneAttrs);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000890
Peter Collingbourne68162e72013-08-14 18:54:12 +0000891 Value *WrappedFnCst =
892 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
893 F.replaceAllUsesWith(WrappedFnCst);
David Blaikiec6c6c7b2014-10-07 22:59:46 +0000894
Peter Collingbourne68162e72013-08-14 18:54:12 +0000895 UnwrappedFnMap[WrappedFnCst] = &F;
896 *i = NewF;
897
898 if (!F.isDeclaration()) {
899 // This function is probably defining an interposition of an
900 // uninstrumented function and hence needs to keep the original ABI.
901 // But any functions it may call need to use the instrumented ABI, so
902 // we instrument it in a mode which preserves the original ABI.
903 FnsWithNativeABI.insert(&F);
904
905 // This code needs to rebuild the iterators, as they may be invalidated
906 // by the push_back, taking care that the new range does not include
907 // any functions added by this code.
908 size_t N = i - FnsToInstrument.begin(),
909 Count = e - FnsToInstrument.begin();
910 FnsToInstrument.push_back(&F);
911 i = FnsToInstrument.begin() + N;
912 e = FnsToInstrument.begin() + Count;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000913 }
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +0000914 // Hopefully, nobody will try to indirectly call a vararg
915 // function... yet.
916 } else if (FT->isVarArg()) {
917 UnwrappedFnMap[&F] = &F;
918 *i = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000919 }
920 }
921
Benjamin Kramer135f7352016-06-26 12:28:59 +0000922 for (Function *i : FnsToInstrument) {
923 if (!i || i->isDeclaration())
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000924 continue;
925
Benjamin Kramer135f7352016-06-26 12:28:59 +0000926 removeUnreachableBlocks(*i);
Peter Collingbourneae66d572013-08-09 21:42:53 +0000927
Benjamin Kramer135f7352016-06-26 12:28:59 +0000928 DFSanFunction DFSF(*this, i, FnsWithNativeABI.count(i));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000929
930 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
931 // Build a copy of the list before iterating over it.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000932 SmallVector<BasicBlock *, 4> BBList(depth_first(&i->getEntryBlock()));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000933
Benjamin Kramer135f7352016-06-26 12:28:59 +0000934 for (BasicBlock *i : BBList) {
935 Instruction *Inst = &i->front();
Eugene Zelenkofce43572017-10-21 00:57:46 +0000936 while (true) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000937 // DFSanVisitor may split the current basic block, changing the current
938 // instruction's next pointer and moving the next instruction to the
939 // tail block from which we should continue.
940 Instruction *Next = Inst->getNextNode();
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000941 // DFSanVisitor may delete Inst, so keep track of whether it was a
942 // terminator.
Chandler Carruth9ae926b2018-08-26 09:51:22 +0000943 bool IsTerminator = Inst->isTerminator();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000944 if (!DFSF.SkipInsts.count(Inst))
945 DFSanVisitor(DFSF).visit(Inst);
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000946 if (IsTerminator)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000947 break;
948 Inst = Next;
949 }
950 }
951
Peter Collingbourne68162e72013-08-14 18:54:12 +0000952 // We will not necessarily be able to compute the shadow for every phi node
953 // until we have visited every block. Therefore, the code that handles phi
954 // nodes adds them to the PHIFixups list so that they can be properly
955 // handled here.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000956 for (std::vector<std::pair<PHINode *, PHINode *>>::iterator
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000957 i = DFSF.PHIFixups.begin(),
958 e = DFSF.PHIFixups.end();
959 i != e; ++i) {
960 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
961 ++val) {
962 i->second->setIncomingValue(
963 val, DFSF.getShadow(i->first->getIncomingValue(val)));
964 }
965 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000966
967 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
968 // places (i.e. instructions in basic blocks we haven't even begun visiting
969 // yet). To make our life easier, do this work in a pass after the main
970 // instrumentation.
971 if (ClDebugNonzeroLabels) {
Peter Collingbournefab565a2014-08-22 01:18:18 +0000972 for (Value *V : DFSF.NonZeroChecks) {
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000973 Instruction *Pos;
Peter Collingbournefab565a2014-08-22 01:18:18 +0000974 if (Instruction *I = dyn_cast<Instruction>(V))
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000975 Pos = I->getNextNode();
976 else
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000977 Pos = &DFSF.F->getEntryBlock().front();
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000978 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
979 Pos = Pos->getNextNode();
980 IRBuilder<> IRB(Pos);
Peter Collingbournefab565a2014-08-22 01:18:18 +0000981 Value *Ne = IRB.CreateICmpNE(V, DFSF.DFS.ZeroShadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000982 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000983 Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000984 IRBuilder<> ThenIRB(BI);
David Blaikieff6409d2015-05-18 22:13:54 +0000985 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn, {});
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000986 }
987 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000988 }
989
990 return false;
991}
992
993Value *DFSanFunction::getArgTLSPtr() {
994 if (ArgTLSPtr)
995 return ArgTLSPtr;
996 if (DFS.ArgTLS)
997 return ArgTLSPtr = DFS.ArgTLS;
998
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000999 IRBuilder<> IRB(&F->getEntryBlock().front());
David Blaikieff6409d2015-05-18 22:13:54 +00001000 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS, {});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001001}
1002
1003Value *DFSanFunction::getRetvalTLS() {
1004 if (RetvalTLSPtr)
1005 return RetvalTLSPtr;
1006 if (DFS.RetvalTLS)
1007 return RetvalTLSPtr = DFS.RetvalTLS;
1008
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001009 IRBuilder<> IRB(&F->getEntryBlock().front());
David Blaikieff6409d2015-05-18 22:13:54 +00001010 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS, {});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001011}
1012
1013Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
1014 IRBuilder<> IRB(Pos);
1015 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
1016}
1017
1018Value *DFSanFunction::getShadow(Value *V) {
1019 if (!isa<Argument>(V) && !isa<Instruction>(V))
1020 return DFS.ZeroShadow;
1021 Value *&Shadow = ValShadowMap[V];
1022 if (!Shadow) {
1023 if (Argument *A = dyn_cast<Argument>(V)) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001024 if (IsNativeABI)
1025 return DFS.ZeroShadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001026 switch (IA) {
1027 case DataFlowSanitizer::IA_TLS: {
1028 Value *ArgTLSPtr = getArgTLSPtr();
1029 Instruction *ArgTLSPos =
1030 DFS.ArgTLS ? &*F->getEntryBlock().begin()
1031 : cast<Instruction>(ArgTLSPtr)->getNextNode();
1032 IRBuilder<> IRB(ArgTLSPos);
1033 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
1034 break;
1035 }
1036 case DataFlowSanitizer::IA_Args: {
Reid Kleckner45707d42017-03-16 22:59:15 +00001037 unsigned ArgIdx = A->getArgNo() + F->arg_size() / 2;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001038 Function::arg_iterator i = F->arg_begin();
1039 while (ArgIdx--)
1040 ++i;
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001041 Shadow = &*i;
Peter Collingbourne68162e72013-08-14 18:54:12 +00001042 assert(Shadow->getType() == DFS.ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001043 break;
1044 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001045 }
Peter Collingbournefab565a2014-08-22 01:18:18 +00001046 NonZeroChecks.push_back(Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001047 } else {
1048 Shadow = DFS.ZeroShadow;
1049 }
1050 }
1051 return Shadow;
1052}
1053
1054void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
1055 assert(!ValShadowMap.count(I));
1056 assert(Shadow->getType() == DFS.ShadowTy);
1057 ValShadowMap[I] = Shadow;
1058}
1059
1060Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
1061 assert(Addr != RetvalTLS && "Reinstrumenting?");
1062 IRBuilder<> IRB(Pos);
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +00001063 Value *ShadowPtrMaskValue;
1064 if (DFSanRuntimeShadowMask)
1065 ShadowPtrMaskValue = IRB.CreateLoad(IntptrTy, ExternalShadowMask);
1066 else
1067 ShadowPtrMaskValue = ShadowPtrMask;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001068 return IRB.CreateIntToPtr(
1069 IRB.CreateMul(
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +00001070 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy),
1071 IRB.CreatePtrToInt(ShadowPtrMaskValue, IntptrTy)),
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001072 ShadowPtrMul),
1073 ShadowPtrTy);
1074}
1075
1076// Generates IR to compute the union of the two given shadows, inserting it
1077// before Pos. Returns the computed union Value.
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001078Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
1079 if (V1 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001080 return V2;
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001081 if (V2 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001082 return V1;
1083 if (V1 == V2)
1084 return V1;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001085
Peter Collingbourne9947c492014-07-15 22:13:19 +00001086 auto V1Elems = ShadowElements.find(V1);
1087 auto V2Elems = ShadowElements.find(V2);
1088 if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
1089 if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
1090 V2Elems->second.begin(), V2Elems->second.end())) {
1091 return V1;
1092 } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
1093 V1Elems->second.begin(), V1Elems->second.end())) {
1094 return V2;
1095 }
1096 } else if (V1Elems != ShadowElements.end()) {
1097 if (V1Elems->second.count(V2))
1098 return V1;
1099 } else if (V2Elems != ShadowElements.end()) {
1100 if (V2Elems->second.count(V1))
1101 return V2;
1102 }
1103
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001104 auto Key = std::make_pair(V1, V2);
1105 if (V1 > V2)
1106 std::swap(Key.first, Key.second);
1107 CachedCombinedShadow &CCS = CachedCombinedShadows[Key];
1108 if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
1109 return CCS.Shadow;
1110
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001111 IRBuilder<> IRB(Pos);
Peter Collingbournedf240b22014-08-06 00:33:40 +00001112 if (AvoidNewBlocks) {
David Blaikieff6409d2015-05-18 22:13:54 +00001113 CallInst *Call = IRB.CreateCall(DFS.DFSanCheckedUnionFn, {V1, V2});
Reid Klecknerb5180542017-03-21 16:57:19 +00001114 Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Reid Klecknera0b45f42017-05-03 18:17:31 +00001115 Call->addParamAttr(0, Attribute::ZExt);
1116 Call->addParamAttr(1, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001117
Peter Collingbournedf240b22014-08-06 00:33:40 +00001118 CCS.Block = Pos->getParent();
1119 CCS.Shadow = Call;
1120 } else {
1121 BasicBlock *Head = Pos->getParent();
1122 Value *Ne = IRB.CreateICmpNE(V1, V2);
1123 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
1124 Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
1125 IRBuilder<> ThenIRB(BI);
David Blaikieff6409d2015-05-18 22:13:54 +00001126 CallInst *Call = ThenIRB.CreateCall(DFS.DFSanUnionFn, {V1, V2});
Reid Klecknerb5180542017-03-21 16:57:19 +00001127 Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Reid Klecknera0b45f42017-05-03 18:17:31 +00001128 Call->addParamAttr(0, Attribute::ZExt);
1129 Call->addParamAttr(1, Attribute::ZExt);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001130
Peter Collingbournedf240b22014-08-06 00:33:40 +00001131 BasicBlock *Tail = BI->getSuccessor(0);
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001132 PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
Peter Collingbournedf240b22014-08-06 00:33:40 +00001133 Phi->addIncoming(Call, Call->getParent());
1134 Phi->addIncoming(V1, Head);
1135
1136 CCS.Block = Tail;
1137 CCS.Shadow = Phi;
1138 }
Peter Collingbourne9947c492014-07-15 22:13:19 +00001139
1140 std::set<Value *> UnionElems;
1141 if (V1Elems != ShadowElements.end()) {
1142 UnionElems = V1Elems->second;
1143 } else {
1144 UnionElems.insert(V1);
1145 }
1146 if (V2Elems != ShadowElements.end()) {
1147 UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
1148 } else {
1149 UnionElems.insert(V2);
1150 }
Peter Collingbournedf240b22014-08-06 00:33:40 +00001151 ShadowElements[CCS.Shadow] = std::move(UnionElems);
Peter Collingbourne9947c492014-07-15 22:13:19 +00001152
Peter Collingbournedf240b22014-08-06 00:33:40 +00001153 return CCS.Shadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001154}
1155
1156// A convenience function which folds the shadows of each of the operands
1157// of the provided instruction Inst, inserting the IR before Inst. Returns
1158// the computed union Value.
1159Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
1160 if (Inst->getNumOperands() == 0)
1161 return DFS.ZeroShadow;
1162
1163 Value *Shadow = getShadow(Inst->getOperand(0));
1164 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001165 Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001166 }
1167 return Shadow;
1168}
1169
1170void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
1171 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1172 DFSF.setShadow(&I, CombinedShadow);
1173}
1174
1175// Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
1176// Addr has alignment Align, and take the union of each of those shadows.
1177Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
1178 Instruction *Pos) {
1179 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001180 const auto i = AllocaShadowMap.find(AI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001181 if (i != AllocaShadowMap.end()) {
1182 IRBuilder<> IRB(Pos);
1183 return IRB.CreateLoad(i->second);
1184 }
1185 }
1186
1187 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1188 SmallVector<Value *, 2> Objs;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001189 GetUnderlyingObjects(Addr, Objs, Pos->getModule()->getDataLayout());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001190 bool AllConstants = true;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001191 for (Value *Obj : Objs) {
1192 if (isa<Function>(Obj) || isa<BlockAddress>(Obj))
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001193 continue;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001194 if (isa<GlobalVariable>(Obj) && cast<GlobalVariable>(Obj)->isConstant())
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001195 continue;
1196
1197 AllConstants = false;
1198 break;
1199 }
1200 if (AllConstants)
1201 return DFS.ZeroShadow;
1202
1203 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1204 switch (Size) {
1205 case 0:
1206 return DFS.ZeroShadow;
1207 case 1: {
1208 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
1209 LI->setAlignment(ShadowAlign);
1210 return LI;
1211 }
1212 case 2: {
1213 IRBuilder<> IRB(Pos);
David Blaikie93c54442015-04-03 19:41:44 +00001214 Value *ShadowAddr1 = IRB.CreateGEP(DFS.ShadowTy, ShadowAddr,
1215 ConstantInt::get(DFS.IntptrTy, 1));
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001216 return combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
1217 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign), Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001218 }
1219 }
Peter Collingbournedf240b22014-08-06 00:33:40 +00001220 if (!AvoidNewBlocks && Size % (64 / DFS.ShadowWidth) == 0) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001221 // Fast path for the common case where each byte has identical shadow: load
1222 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
1223 // shadow is non-equal.
1224 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
1225 IRBuilder<> FallbackIRB(FallbackBB);
David Blaikieff6409d2015-05-18 22:13:54 +00001226 CallInst *FallbackCall = FallbackIRB.CreateCall(
1227 DFS.DFSanUnionLoadFn,
1228 {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
Reid Klecknerb5180542017-03-21 16:57:19 +00001229 FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001230
1231 // Compare each of the shadows stored in the loaded 64 bits to each other,
1232 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
1233 IRBuilder<> IRB(Pos);
1234 Value *WideAddr =
1235 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1236 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1237 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
1238 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
1239 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
1240 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1241 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1242
1243 BasicBlock *Head = Pos->getParent();
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001244 BasicBlock *Tail = Head->splitBasicBlock(Pos->getIterator());
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001245
1246 if (DomTreeNode *OldNode = DT.getNode(Head)) {
1247 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1248
1249 DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1250 for (auto Child : Children)
1251 DT.changeImmediateDominator(Child, NewNode);
1252 }
1253
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001254 // In the following code LastBr will refer to the previous basic block's
1255 // conditional branch instruction, whose true successor is fixed up to point
1256 // to the next block during the loop below or to the tail after the final
1257 // iteration.
1258 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1259 ReplaceInstWithInst(Head->getTerminator(), LastBr);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001260 DT.addNewBlock(FallbackBB, Head);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001261
1262 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
1263 Ofs += 64 / DFS.ShadowWidth) {
1264 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001265 DT.addNewBlock(NextBB, LastBr->getParent());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001266 IRBuilder<> NextIRB(NextBB);
David Blaikie93c54442015-04-03 19:41:44 +00001267 WideAddr = NextIRB.CreateGEP(Type::getInt64Ty(*DFS.Ctx), WideAddr,
1268 ConstantInt::get(DFS.IntptrTy, 1));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001269 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1270 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1271 LastBr->setSuccessor(0, NextBB);
1272 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1273 }
1274
1275 LastBr->setSuccessor(0, Tail);
1276 FallbackIRB.CreateBr(Tail);
1277 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1278 Shadow->addIncoming(FallbackCall, FallbackBB);
1279 Shadow->addIncoming(TruncShadow, LastBr->getParent());
1280 return Shadow;
1281 }
1282
1283 IRBuilder<> IRB(Pos);
David Blaikieff6409d2015-05-18 22:13:54 +00001284 CallInst *FallbackCall = IRB.CreateCall(
1285 DFS.DFSanUnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
Reid Klecknerb5180542017-03-21 16:57:19 +00001286 FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001287 return FallbackCall;
1288}
1289
1290void DFSanVisitor::visitLoadInst(LoadInst &LI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001291 auto &DL = LI.getModule()->getDataLayout();
1292 uint64_t Size = DL.getTypeStoreSize(LI.getType());
Peter Collingbourne142fdff2014-08-01 21:18:18 +00001293 if (Size == 0) {
1294 DFSF.setShadow(&LI, DFSF.DFS.ZeroShadow);
1295 return;
1296 }
1297
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001298 uint64_t Align;
1299 if (ClPreserveAlignment) {
1300 Align = LI.getAlignment();
1301 if (Align == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001302 Align = DL.getABITypeAlignment(LI.getType());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001303 } else {
1304 Align = 1;
1305 }
1306 IRBuilder<> IRB(&LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001307 Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
1308 if (ClCombinePointerLabelsOnLoad) {
1309 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001310 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001311 }
1312 if (Shadow != DFSF.DFS.ZeroShadow)
Peter Collingbournefab565a2014-08-22 01:18:18 +00001313 DFSF.NonZeroChecks.push_back(Shadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +00001314
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001315 DFSF.setShadow(&LI, Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001316}
1317
1318void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
1319 Value *Shadow, Instruction *Pos) {
1320 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001321 const auto i = AllocaShadowMap.find(AI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001322 if (i != AllocaShadowMap.end()) {
1323 IRBuilder<> IRB(Pos);
1324 IRB.CreateStore(Shadow, i->second);
1325 return;
1326 }
1327 }
1328
1329 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1330 IRBuilder<> IRB(Pos);
1331 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1332 if (Shadow == DFS.ZeroShadow) {
1333 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1334 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1335 Value *ExtShadowAddr =
1336 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1337 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1338 return;
1339 }
1340
1341 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1342 uint64_t Offset = 0;
1343 if (Size >= ShadowVecSize) {
1344 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1345 Value *ShadowVec = UndefValue::get(ShadowVecTy);
1346 for (unsigned i = 0; i != ShadowVecSize; ++i) {
1347 ShadowVec = IRB.CreateInsertElement(
1348 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1349 }
1350 Value *ShadowVecAddr =
1351 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1352 do {
David Blaikie95d3e532015-04-03 23:03:54 +00001353 Value *CurShadowVecAddr =
1354 IRB.CreateConstGEP1_32(ShadowVecTy, ShadowVecAddr, Offset);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001355 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1356 Size -= ShadowVecSize;
1357 ++Offset;
1358 } while (Size >= ShadowVecSize);
1359 Offset *= ShadowVecSize;
1360 }
1361 while (Size > 0) {
David Blaikie95d3e532015-04-03 23:03:54 +00001362 Value *CurShadowAddr =
1363 IRB.CreateConstGEP1_32(DFS.ShadowTy, ShadowAddr, Offset);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001364 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1365 --Size;
1366 ++Offset;
1367 }
1368}
1369
1370void DFSanVisitor::visitStoreInst(StoreInst &SI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001371 auto &DL = SI.getModule()->getDataLayout();
1372 uint64_t Size = DL.getTypeStoreSize(SI.getValueOperand()->getType());
Peter Collingbourne142fdff2014-08-01 21:18:18 +00001373 if (Size == 0)
1374 return;
1375
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001376 uint64_t Align;
1377 if (ClPreserveAlignment) {
1378 Align = SI.getAlignment();
1379 if (Align == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001380 Align = DL.getABITypeAlignment(SI.getValueOperand()->getType());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001381 } else {
1382 Align = 1;
1383 }
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001384
1385 Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1386 if (ClCombinePointerLabelsOnStore) {
1387 Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001388 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001389 }
1390 DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001391}
1392
1393void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1394 visitOperandShadowInst(BO);
1395}
1396
1397void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1398
1399void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1400
1401void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1402 visitOperandShadowInst(GEPI);
1403}
1404
1405void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1406 visitOperandShadowInst(I);
1407}
1408
1409void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1410 visitOperandShadowInst(I);
1411}
1412
1413void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1414 visitOperandShadowInst(I);
1415}
1416
1417void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1418 visitOperandShadowInst(I);
1419}
1420
1421void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1422 visitOperandShadowInst(I);
1423}
1424
1425void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1426 bool AllLoadsStores = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001427 for (User *U : I.users()) {
1428 if (isa<LoadInst>(U))
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001429 continue;
1430
Chandler Carruthcdf47882014-03-09 03:16:01 +00001431 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001432 if (SI->getPointerOperand() == &I)
1433 continue;
1434 }
1435
1436 AllLoadsStores = false;
1437 break;
1438 }
1439 if (AllLoadsStores) {
1440 IRBuilder<> IRB(&I);
1441 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1442 }
1443 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1444}
1445
1446void DFSanVisitor::visitSelectInst(SelectInst &I) {
1447 Value *CondShadow = DFSF.getShadow(I.getCondition());
1448 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1449 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1450
1451 if (isa<VectorType>(I.getCondition()->getType())) {
1452 DFSF.setShadow(
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001453 &I,
1454 DFSF.combineShadows(
1455 CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001456 } else {
1457 Value *ShadowSel;
1458 if (TrueShadow == FalseShadow) {
1459 ShadowSel = TrueShadow;
1460 } else {
1461 ShadowSel =
1462 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1463 }
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001464 DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001465 }
1466}
1467
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +00001468void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1469 IRBuilder<> IRB(&I);
1470 Value *ValShadow = DFSF.getShadow(I.getValue());
David Blaikieff6409d2015-05-18 22:13:54 +00001471 IRB.CreateCall(DFSF.DFS.DFSanSetLabelFn,
1472 {ValShadow, IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(
1473 *DFSF.DFS.Ctx)),
1474 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +00001475}
1476
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001477void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1478 IRBuilder<> IRB(&I);
1479 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1480 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1481 Value *LenShadow = IRB.CreateMul(
1482 I.getLength(),
1483 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001484 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1485 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1486 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
Daniel Neilson1e687242018-01-19 17:13:12 +00001487 auto *MTI = cast<MemTransferInst>(
1488 IRB.CreateCall(I.getCalledValue(),
1489 {DestShadow, SrcShadow, LenShadow, I.getVolatileCst()}));
Daniel Neilson1e687242018-01-19 17:13:12 +00001490 if (ClPreserveAlignment) {
Daniel Neilson606cf6f2018-02-08 21:28:26 +00001491 MTI->setDestAlignment(I.getDestAlignment() * (DFSF.DFS.ShadowWidth / 8));
1492 MTI->setSourceAlignment(I.getSourceAlignment() * (DFSF.DFS.ShadowWidth / 8));
Daniel Neilson1e687242018-01-19 17:13:12 +00001493 } else {
Daniel Neilson606cf6f2018-02-08 21:28:26 +00001494 MTI->setDestAlignment(DFSF.DFS.ShadowWidth / 8);
1495 MTI->setSourceAlignment(DFSF.DFS.ShadowWidth / 8);
Daniel Neilson1e687242018-01-19 17:13:12 +00001496 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001497}
1498
1499void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001500 if (!DFSF.IsNativeABI && RI.getReturnValue()) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001501 switch (DFSF.IA) {
1502 case DataFlowSanitizer::IA_TLS: {
1503 Value *S = DFSF.getShadow(RI.getReturnValue());
1504 IRBuilder<> IRB(&RI);
1505 IRB.CreateStore(S, DFSF.getRetvalTLS());
1506 break;
1507 }
1508 case DataFlowSanitizer::IA_Args: {
1509 IRBuilder<> IRB(&RI);
1510 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1511 Value *InsVal =
1512 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1513 Value *InsShadow =
1514 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1515 RI.setOperand(0, InsShadow);
1516 break;
1517 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001518 }
1519 }
1520}
1521
1522void DFSanVisitor::visitCallSite(CallSite CS) {
1523 Function *F = CS.getCalledFunction();
1524 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1525 visitOperandShadowInst(*CS.getInstruction());
1526 return;
1527 }
1528
Peter Collingbournea1099842014-11-05 17:21:00 +00001529 // Calls to this function are synthesized in wrappers, and we shouldn't
1530 // instrument them.
James Y Knightf47d6b32019-01-31 20:35:56 +00001531 if (F == DFSF.DFS.DFSanVarargWrapperFn.getCallee()->stripPointerCasts())
Peter Collingbournea1099842014-11-05 17:21:00 +00001532 return;
1533
Peter Collingbourne68162e72013-08-14 18:54:12 +00001534 IRBuilder<> IRB(CS.getInstruction());
1535
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001536 DenseMap<Value *, Function *>::iterator i =
1537 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1538 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001539 Function *F = i->second;
1540 switch (DFSF.DFS.getWrapperKind(F)) {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001541 case DataFlowSanitizer::WK_Warning:
Peter Collingbourne68162e72013-08-14 18:54:12 +00001542 CS.setCalledFunction(F);
1543 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1544 IRB.CreateGlobalStringPtr(F->getName()));
1545 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1546 return;
Eugene Zelenkofce43572017-10-21 00:57:46 +00001547 case DataFlowSanitizer::WK_Discard:
Peter Collingbourne68162e72013-08-14 18:54:12 +00001548 CS.setCalledFunction(F);
1549 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1550 return;
Eugene Zelenkofce43572017-10-21 00:57:46 +00001551 case DataFlowSanitizer::WK_Functional:
Peter Collingbourne68162e72013-08-14 18:54:12 +00001552 CS.setCalledFunction(F);
1553 visitOperandShadowInst(*CS.getInstruction());
1554 return;
Eugene Zelenkofce43572017-10-21 00:57:46 +00001555 case DataFlowSanitizer::WK_Custom:
Peter Collingbourne68162e72013-08-14 18:54:12 +00001556 // Don't try to handle invokes of custom functions, it's too complicated.
1557 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1558 // wrapper.
1559 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1560 FunctionType *FT = F->getFunctionType();
Peter Collingbourne32f54052018-02-22 19:09:07 +00001561 TransformedFunction CustomFn = DFSF.DFS.getCustomFunctionType(FT);
Peter Collingbourne68162e72013-08-14 18:54:12 +00001562 std::string CustomFName = "__dfsw_";
1563 CustomFName += F->getName();
James Y Knightf47d6b32019-01-31 20:35:56 +00001564 FunctionCallee CustomF = DFSF.DFS.Mod->getOrInsertFunction(
Peter Collingbourne32f54052018-02-22 19:09:07 +00001565 CustomFName, CustomFn.TransformedType);
James Y Knightf47d6b32019-01-31 20:35:56 +00001566 if (Function *CustomFn = dyn_cast<Function>(CustomF.getCallee())) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001567 CustomFn->copyAttributesFrom(F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001568
Peter Collingbourne68162e72013-08-14 18:54:12 +00001569 // Custom functions returning non-void will write to the return label.
1570 if (!FT->getReturnType()->isVoidTy()) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001571 CustomFn->removeAttributes(AttributeList::FunctionIndex,
Peter Collingbourne68162e72013-08-14 18:54:12 +00001572 DFSF.DFS.ReadOnlyNoneAttrs);
1573 }
1574 }
1575
1576 std::vector<Value *> Args;
1577
1578 CallSite::arg_iterator i = CS.arg_begin();
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001579 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +00001580 Type *T = (*i)->getType();
1581 FunctionType *ParamFT;
1582 if (isa<PointerType>(T) &&
1583 (ParamFT = dyn_cast<FunctionType>(
1584 cast<PointerType>(T)->getElementType()))) {
1585 std::string TName = "dfst";
1586 TName += utostr(FT->getNumParams() - n);
1587 TName += "$";
1588 TName += F->getName();
1589 Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1590 Args.push_back(T);
1591 Args.push_back(
1592 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1593 } else {
1594 Args.push_back(*i);
1595 }
1596 }
Peter Collingbourne68162e72013-08-14 18:54:12 +00001597
1598 i = CS.arg_begin();
Simon Dardisb5205c62017-08-17 14:14:25 +00001599 const unsigned ShadowArgStart = Args.size();
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001600 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
Peter Collingbourne68162e72013-08-14 18:54:12 +00001601 Args.push_back(DFSF.getShadow(*i));
1602
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001603 if (FT->isVarArg()) {
David Blaikie1b01e7e2015-04-05 22:44:57 +00001604 auto *LabelVATy = ArrayType::get(DFSF.DFS.ShadowTy,
1605 CS.arg_size() - FT->getNumParams());
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001606 auto *LabelVAAlloca = new AllocaInst(
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001607 LabelVATy, getDataLayout().getAllocaAddrSpace(),
1608 "labelva", &DFSF.F->getEntryBlock().front());
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001609
1610 for (unsigned n = 0; i != CS.arg_end(); ++i, ++n) {
David Blaikie64646022015-04-05 22:41:44 +00001611 auto LabelVAPtr = IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, n);
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001612 IRB.CreateStore(DFSF.getShadow(*i), LabelVAPtr);
1613 }
1614
David Blaikie64646022015-04-05 22:41:44 +00001615 Args.push_back(IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, 0));
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001616 }
1617
Peter Collingbourne68162e72013-08-14 18:54:12 +00001618 if (!FT->getReturnType()->isVoidTy()) {
1619 if (!DFSF.LabelReturnAlloca) {
1620 DFSF.LabelReturnAlloca =
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001621 new AllocaInst(DFSF.DFS.ShadowTy,
1622 getDataLayout().getAllocaAddrSpace(),
1623 "labelreturn", &DFSF.F->getEntryBlock().front());
Peter Collingbourne68162e72013-08-14 18:54:12 +00001624 }
1625 Args.push_back(DFSF.LabelReturnAlloca);
1626 }
1627
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001628 for (i = CS.arg_begin() + FT->getNumParams(); i != CS.arg_end(); ++i)
1629 Args.push_back(*i);
1630
Peter Collingbourne68162e72013-08-14 18:54:12 +00001631 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1632 CustomCI->setCallingConv(CI->getCallingConv());
Peter Collingbourne32f54052018-02-22 19:09:07 +00001633 CustomCI->setAttributes(TransformFunctionAttributes(CustomFn,
1634 CI->getContext(), CI->getAttributes()));
Peter Collingbourne68162e72013-08-14 18:54:12 +00001635
Simon Dardisb5205c62017-08-17 14:14:25 +00001636 // Update the parameter attributes of the custom call instruction to
1637 // zero extend the shadow parameters. This is required for targets
1638 // which consider ShadowTy an illegal type.
1639 for (unsigned n = 0; n < FT->getNumParams(); n++) {
1640 const unsigned ArgNo = ShadowArgStart + n;
1641 if (CustomCI->getArgOperand(ArgNo)->getType() == DFSF.DFS.ShadowTy)
1642 CustomCI->addParamAttr(ArgNo, Attribute::ZExt);
1643 }
1644
Peter Collingbourne68162e72013-08-14 18:54:12 +00001645 if (!FT->getReturnType()->isVoidTy()) {
1646 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1647 DFSF.setShadow(CustomCI, LabelLoad);
1648 }
1649
1650 CI->replaceAllUsesWith(CustomCI);
1651 CI->eraseFromParent();
1652 return;
1653 }
1654 break;
1655 }
Peter Collingbourne68162e72013-08-14 18:54:12 +00001656 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001657
1658 FunctionType *FT = cast<FunctionType>(
1659 CS.getCalledValue()->getType()->getPointerElementType());
Peter Collingbourne68162e72013-08-14 18:54:12 +00001660 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001661 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1662 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1663 DFSF.getArgTLS(i, CS.getInstruction()));
1664 }
1665 }
1666
Craig Topperf40110f2014-04-25 05:29:35 +00001667 Instruction *Next = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001668 if (!CS.getType()->isVoidTy()) {
1669 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1670 if (II->getNormalDest()->getSinglePredecessor()) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001671 Next = &II->getNormalDest()->front();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001672 } else {
1673 BasicBlock *NewBB =
Chandler Carruthd4500562015-01-19 12:36:53 +00001674 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001675 Next = &NewBB->front();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001676 }
1677 } else {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001678 assert(CS->getIterator() != CS->getParent()->end());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001679 Next = CS->getNextNode();
1680 }
1681
Peter Collingbourne68162e72013-08-14 18:54:12 +00001682 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001683 IRBuilder<> NextIRB(Next);
1684 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1685 DFSF.SkipInsts.insert(LI);
1686 DFSF.setShadow(CS.getInstruction(), LI);
Peter Collingbournefab565a2014-08-22 01:18:18 +00001687 DFSF.NonZeroChecks.push_back(LI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001688 }
1689 }
1690
1691 // Do all instrumentation for IA_Args down here to defer tampering with the
1692 // CFG in a way that SplitEdge may be able to detect.
Peter Collingbourne68162e72013-08-14 18:54:12 +00001693 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1694 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001695 Value *Func =
1696 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1697 std::vector<Value *> Args;
1698
1699 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1700 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1701 Args.push_back(*i);
1702
1703 i = CS.arg_begin();
1704 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1705 Args.push_back(DFSF.getShadow(*i));
1706
1707 if (FT->isVarArg()) {
1708 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1709 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1710 AllocaInst *VarArgShadow =
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001711 new AllocaInst(VarArgArrayTy, getDataLayout().getAllocaAddrSpace(),
1712 "", &DFSF.F->getEntryBlock().front());
David Blaikie4e5d47f42015-04-04 21:07:10 +00001713 Args.push_back(IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, 0));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001714 for (unsigned n = 0; i != e; ++i, ++n) {
David Blaikie4e5d47f42015-04-04 21:07:10 +00001715 IRB.CreateStore(
1716 DFSF.getShadow(*i),
1717 IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, n));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001718 Args.push_back(*i);
1719 }
1720 }
1721
1722 CallSite NewCS;
1723 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1724 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1725 Args);
1726 } else {
1727 NewCS = IRB.CreateCall(Func, Args);
1728 }
1729 NewCS.setCallingConv(CS.getCallingConv());
1730 NewCS.setAttributes(CS.getAttributes().removeAttributes(
Reid Klecknerb5180542017-03-21 16:57:19 +00001731 *DFSF.DFS.Ctx, AttributeList::ReturnIndex,
Pete Cooper2777d8872015-05-06 23:19:56 +00001732 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType())));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001733
1734 if (Next) {
1735 ExtractValueInst *ExVal =
1736 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1737 DFSF.SkipInsts.insert(ExVal);
1738 ExtractValueInst *ExShadow =
1739 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1740 DFSF.SkipInsts.insert(ExShadow);
1741 DFSF.setShadow(ExVal, ExShadow);
Peter Collingbournefab565a2014-08-22 01:18:18 +00001742 DFSF.NonZeroChecks.push_back(ExShadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001743
1744 CS.getInstruction()->replaceAllUsesWith(ExVal);
1745 }
1746
1747 CS.getInstruction()->eraseFromParent();
1748 }
1749}
1750
1751void DFSanVisitor::visitPHINode(PHINode &PN) {
1752 PHINode *ShadowPN =
1753 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1754
1755 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1756 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1757 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1758 ++i) {
1759 ShadowPN->addIncoming(UndefShadow, *i);
1760 }
1761
1762 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1763 DFSF.setShadow(&PN, ShadowPN);
1764}