1 //===- DataFlowSanitizer.cpp - dynamic data flow analysis -----------------===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// This file is a part of DataFlowSanitizer, a generalised dynamic data flow
11 /// analysis.
12 ///
13 /// Unlike other Sanitizer tools, this tool is not designed to detect a specific
14 /// class of bugs on its own.  Instead, it provides a generic dynamic data flow
15 /// analysis framework to be used by clients to help detect application-specific
16 /// issues within their own code.
17 ///
18 /// The analysis is based on automatic propagation of data flow labels (also
19 /// known as taint labels) through a program as it performs computation.
20 ///
21 /// Argument and return value labels are passed through TLS variables
22 /// __dfsan_arg_tls and __dfsan_retval_tls.
23 ///
24 /// Each byte of application memory is backed by a shadow memory byte. The
25 /// shadow byte can represent up to 8 labels. On Linux/x86_64, memory is then
26 /// laid out as follows:
27 ///
28 /// +--------------------+ 0x800000000000 (top of memory)
29 /// |    application 3   |
30 /// +--------------------+ 0x700000000000
31 /// |      invalid       |
32 /// +--------------------+ 0x610000000000
33 /// |      origin 1      |
34 /// +--------------------+ 0x600000000000
35 /// |    application 2   |
36 /// +--------------------+ 0x510000000000
37 /// |      shadow 1      |
38 /// +--------------------+ 0x500000000000
39 /// |      invalid       |
40 /// +--------------------+ 0x400000000000
41 /// |      origin 3      |
42 /// +--------------------+ 0x300000000000
43 /// |      shadow 3      |
44 /// +--------------------+ 0x200000000000
45 /// |      origin 2      |
46 /// +--------------------+ 0x110000000000
47 /// |      invalid       |
48 /// +--------------------+ 0x100000000000
49 /// |      shadow 2      |
50 /// +--------------------+ 0x010000000000
51 /// |    application 1   |
52 /// +--------------------+ 0x000000000000
53 ///
54 /// MEM_TO_SHADOW(mem) = mem ^ 0x500000000000
55 /// SHADOW_TO_ORIGIN(shadow) = shadow + 0x100000000000
56 ///
57 /// For more information, please refer to the design document:
58 /// http://clang.llvm.org/docs/DataFlowSanitizerDesign.html
59 //
60 //===----------------------------------------------------------------------===//
61 
62 #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
63 #include "llvm/ADT/DenseMap.h"
64 #include "llvm/ADT/DenseSet.h"
65 #include "llvm/ADT/DepthFirstIterator.h"
66 #include "llvm/ADT/None.h"
67 #include "llvm/ADT/SmallPtrSet.h"
68 #include "llvm/ADT/SmallVector.h"
69 #include "llvm/ADT/StringExtras.h"
70 #include "llvm/ADT/StringRef.h"
71 #include "llvm/ADT/Triple.h"
72 #include "llvm/ADT/iterator.h"
73 #include "llvm/Analysis/ValueTracking.h"
74 #include "llvm/IR/Argument.h"
75 #include "llvm/IR/Attributes.h"
76 #include "llvm/IR/BasicBlock.h"
77 #include "llvm/IR/Constant.h"
78 #include "llvm/IR/Constants.h"
79 #include "llvm/IR/DataLayout.h"
80 #include "llvm/IR/DerivedTypes.h"
81 #include "llvm/IR/Dominators.h"
82 #include "llvm/IR/Function.h"
83 #include "llvm/IR/GlobalAlias.h"
84 #include "llvm/IR/GlobalValue.h"
85 #include "llvm/IR/GlobalVariable.h"
86 #include "llvm/IR/IRBuilder.h"
87 #include "llvm/IR/InlineAsm.h"
88 #include "llvm/IR/InstVisitor.h"
89 #include "llvm/IR/InstrTypes.h"
90 #include "llvm/IR/Instruction.h"
91 #include "llvm/IR/Instructions.h"
92 #include "llvm/IR/IntrinsicInst.h"
93 #include "llvm/IR/LLVMContext.h"
94 #include "llvm/IR/MDBuilder.h"
95 #include "llvm/IR/Module.h"
96 #include "llvm/IR/PassManager.h"
97 #include "llvm/IR/Type.h"
98 #include "llvm/IR/User.h"
99 #include "llvm/IR/Value.h"
100 #include "llvm/InitializePasses.h"
101 #include "llvm/Pass.h"
102 #include "llvm/Support/Alignment.h"
103 #include "llvm/Support/Casting.h"
104 #include "llvm/Support/CommandLine.h"
105 #include "llvm/Support/ErrorHandling.h"
106 #include "llvm/Support/SpecialCaseList.h"
107 #include "llvm/Support/VirtualFileSystem.h"
108 #include "llvm/Transforms/Instrumentation.h"
109 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
110 #include "llvm/Transforms/Utils/Local.h"
111 #include <algorithm>
112 #include <cassert>
113 #include <cstddef>
114 #include <cstdint>
115 #include <iterator>
116 #include <memory>
117 #include <set>
118 #include <string>
119 #include <utility>
120 #include <vector>
121 
122 using namespace llvm;
123 
124 // This must be consistent with ShadowWidthBits.
125 static const Align ShadowTLSAlignment = Align(2);
126 
127 static const Align MinOriginAlignment = Align(4);
128 
129 // The size of TLS variables. These constants must be kept in sync with the ones
130 // in dfsan.cpp.
131 static const unsigned ArgTLSSize = 800;
132 static const unsigned RetvalTLSSize = 800;
133 
134 // The -dfsan-preserve-alignment flag controls whether this pass assumes that
135 // alignment requirements provided by the input IR are correct.  For example,
136 // if the input IR contains a load with alignment 8, this flag will cause
137 // the shadow load to have alignment 16.  This flag is disabled by default as
138 // we have unfortunately encountered too much code (including Clang itself;
139 // see PR14291) which performs misaligned access.
140 static cl::opt<bool> ClPreserveAlignment(
141     "dfsan-preserve-alignment",
142     cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
143     cl::init(false));
144 
145 // The ABI list files control how shadow parameters are passed. The pass treats
146 // every function labelled "uninstrumented" in the ABI list file as conforming
147 // to the "native" (i.e. unsanitized) ABI.  Unless the ABI list contains
148 // additional annotations for those functions, a call to one of those functions
149 // will produce a warning message, as the labelling behaviour of the function is
150 // unknown. The other supported annotations for uninstrumented functions are
151 // "functional" and "discard", which are described below under
152 // DataFlowSanitizer::WrapperKind.
153 // Functions will often be labelled with both "uninstrumented" and one of
154 // "functional" or "discard". This will leave the function unchanged by this
155 // pass, and create a wrapper function that will call the original.
156 //
157 // Instrumented functions can also be annotated as "force_zero_labels", which
158 // will make all shadow and return values set zero labels.
159 // Functions should never be labelled with both "force_zero_labels" and
160 // "uninstrumented" or any of the unistrumented wrapper kinds.
161 static cl::list<std::string> ClABIListFiles(
162     "dfsan-abilist",
163     cl::desc("File listing native ABI functions and how the pass treats them"),
164     cl::Hidden);
165 
166 // Controls whether the pass includes or ignores the labels of pointers in load
167 // instructions.
168 static cl::opt<bool> ClCombinePointerLabelsOnLoad(
169     "dfsan-combine-pointer-labels-on-load",
170     cl::desc("Combine the label of the pointer with the label of the data when "
171              "loading from memory."),
172     cl::Hidden, cl::init(true));
173 
174 // Controls whether the pass includes or ignores the labels of pointers in
175 // stores instructions.
176 static cl::opt<bool> ClCombinePointerLabelsOnStore(
177     "dfsan-combine-pointer-labels-on-store",
178     cl::desc("Combine the label of the pointer with the label of the data when "
179              "storing in memory."),
180     cl::Hidden, cl::init(false));
181 
182 // Controls whether the pass propagates labels of offsets in GEP instructions.
183 static cl::opt<bool> ClCombineOffsetLabelsOnGEP(
184     "dfsan-combine-offset-labels-on-gep",
185     cl::desc(
186         "Combine the label of the offset with the label of the pointer when "
187         "doing pointer arithmetic."),
188     cl::Hidden, cl::init(true));
189 
190 static cl::opt<bool> ClDebugNonzeroLabels(
191     "dfsan-debug-nonzero-labels",
192     cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
193              "load or return with a nonzero label"),
194     cl::Hidden);
195 
196 // Experimental feature that inserts callbacks for certain data events.
197 // Currently callbacks are only inserted for loads, stores, memory transfers
198 // (i.e. memcpy and memmove), and comparisons.
199 //
200 // If this flag is set to true, the user must provide definitions for the
201 // following callback functions:
202 //   void __dfsan_load_callback(dfsan_label Label, void* addr);
203 //   void __dfsan_store_callback(dfsan_label Label, void* addr);
204 //   void __dfsan_mem_transfer_callback(dfsan_label *Start, size_t Len);
205 //   void __dfsan_cmp_callback(dfsan_label CombinedLabel);
206 static cl::opt<bool> ClEventCallbacks(
207     "dfsan-event-callbacks",
208     cl::desc("Insert calls to __dfsan_*_callback functions on data events."),
209     cl::Hidden, cl::init(false));
210 
211 // Controls whether the pass tracks the control flow of select instructions.
212 static cl::opt<bool> ClTrackSelectControlFlow(
213     "dfsan-track-select-control-flow",
214     cl::desc("Propagate labels from condition values of select instructions "
215              "to results."),
216     cl::Hidden, cl::init(true));
217 
218 // TODO: This default value follows MSan. DFSan may use a different value.
219 static cl::opt<int> ClInstrumentWithCallThreshold(
220     "dfsan-instrument-with-call-threshold",
221     cl::desc("If the function being instrumented requires more than "
222              "this number of origin stores, use callbacks instead of "
223              "inline checks (-1 means never use callbacks)."),
224     cl::Hidden, cl::init(3500));
225 
226 // Controls how to track origins.
227 // * 0: do not track origins.
228 // * 1: track origins at memory store operations.
229 // * 2: track origins at memory load and store operations.
230 //      TODO: track callsites.
231 static cl::opt<int> ClTrackOrigins("dfsan-track-origins",
232                                    cl::desc("Track origins of labels"),
233                                    cl::Hidden, cl::init(0));
234 
getGlobalTypeString(const GlobalValue & G)235 static StringRef getGlobalTypeString(const GlobalValue &G) {
236   // Types of GlobalVariables are always pointer types.
237   Type *GType = G.getValueType();
238   // For now we support excluding struct types only.
239   if (StructType *SGType = dyn_cast<StructType>(GType)) {
240     if (!SGType->isLiteral())
241       return SGType->getName();
242   }
243   return "<unknown type>";
244 }
245 
246 namespace {
247 
248 // Memory map parameters used in application-to-shadow address calculation.
249 // Offset = (Addr & ~AndMask) ^ XorMask
250 // Shadow = ShadowBase + Offset
251 // Origin = (OriginBase + Offset) & ~3ULL
252 struct MemoryMapParams {
253   uint64_t AndMask;
254   uint64_t XorMask;
255   uint64_t ShadowBase;
256   uint64_t OriginBase;
257 };
258 
259 } // end anonymous namespace
260 
261 // x86_64 Linux
262 // NOLINTNEXTLINE(readability-identifier-naming)
263 static const MemoryMapParams Linux_X86_64_MemoryMapParams = {
264     0,              // AndMask (not used)
265     0x500000000000, // XorMask
266     0,              // ShadowBase (not used)
267     0x100000000000, // OriginBase
268 };
269 
270 namespace {
271 
272 class DFSanABIList {
273   std::unique_ptr<SpecialCaseList> SCL;
274 
275 public:
276   DFSanABIList() = default;
277 
set(std::unique_ptr<SpecialCaseList> List)278   void set(std::unique_ptr<SpecialCaseList> List) { SCL = std::move(List); }
279 
280   /// Returns whether either this function or its source file are listed in the
281   /// given category.
isIn(const Function & F,StringRef Category) const282   bool isIn(const Function &F, StringRef Category) const {
283     return isIn(*F.getParent(), Category) ||
284            SCL->inSection("dataflow", "fun", F.getName(), Category);
285   }
286 
287   /// Returns whether this global alias is listed in the given category.
288   ///
289   /// If GA aliases a function, the alias's name is matched as a function name
290   /// would be.  Similarly, aliases of globals are matched like globals.
isIn(const GlobalAlias & GA,StringRef Category) const291   bool isIn(const GlobalAlias &GA, StringRef Category) const {
292     if (isIn(*GA.getParent(), Category))
293       return true;
294 
295     if (isa<FunctionType>(GA.getValueType()))
296       return SCL->inSection("dataflow", "fun", GA.getName(), Category);
297 
298     return SCL->inSection("dataflow", "global", GA.getName(), Category) ||
299            SCL->inSection("dataflow", "type", getGlobalTypeString(GA),
300                           Category);
301   }
302 
303   /// Returns whether this module is listed in the given category.
isIn(const Module & M,StringRef Category) const304   bool isIn(const Module &M, StringRef Category) const {
305     return SCL->inSection("dataflow", "src", M.getModuleIdentifier(), Category);
306   }
307 };
308 
309 /// TransformedFunction is used to express the result of transforming one
310 /// function type into another.  This struct is immutable.  It holds metadata
311 /// useful for updating calls of the old function to the new type.
312 struct TransformedFunction {
TransformedFunction__anond364b4550211::TransformedFunction313   TransformedFunction(FunctionType *OriginalType, FunctionType *TransformedType,
314                       std::vector<unsigned> ArgumentIndexMapping)
315       : OriginalType(OriginalType), TransformedType(TransformedType),
316         ArgumentIndexMapping(ArgumentIndexMapping) {}
317 
318   // Disallow copies.
319   TransformedFunction(const TransformedFunction &) = delete;
320   TransformedFunction &operator=(const TransformedFunction &) = delete;
321 
322   // Allow moves.
323   TransformedFunction(TransformedFunction &&) = default;
324   TransformedFunction &operator=(TransformedFunction &&) = default;
325 
326   /// Type of the function before the transformation.
327   FunctionType *OriginalType;
328 
329   /// Type of the function after the transformation.
330   FunctionType *TransformedType;
331 
332   /// Transforming a function may change the position of arguments.  This
333   /// member records the mapping from each argument's old position to its new
334   /// position.  Argument positions are zero-indexed.  If the transformation
335   /// from F to F' made the first argument of F into the third argument of F',
336   /// then ArgumentIndexMapping[0] will equal 2.
337   std::vector<unsigned> ArgumentIndexMapping;
338 };
339 
340 /// Given function attributes from a call site for the original function,
341 /// return function attributes appropriate for a call to the transformed
342 /// function.
343 AttributeList
transformFunctionAttributes(const TransformedFunction & TransformedFunction,LLVMContext & Ctx,AttributeList CallSiteAttrs)344 transformFunctionAttributes(const TransformedFunction &TransformedFunction,
345                             LLVMContext &Ctx, AttributeList CallSiteAttrs) {
346 
347   // Construct a vector of AttributeSet for each function argument.
348   std::vector<llvm::AttributeSet> ArgumentAttributes(
349       TransformedFunction.TransformedType->getNumParams());
350 
351   // Copy attributes from the parameter of the original function to the
352   // transformed version.  'ArgumentIndexMapping' holds the mapping from
353   // old argument position to new.
354   for (unsigned I = 0, IE = TransformedFunction.ArgumentIndexMapping.size();
355        I < IE; ++I) {
356     unsigned TransformedIndex = TransformedFunction.ArgumentIndexMapping[I];
357     ArgumentAttributes[TransformedIndex] = CallSiteAttrs.getParamAttrs(I);
358   }
359 
360   // Copy annotations on varargs arguments.
361   for (unsigned I = TransformedFunction.OriginalType->getNumParams(),
362                 IE = CallSiteAttrs.getNumAttrSets();
363        I < IE; ++I) {
364     ArgumentAttributes.push_back(CallSiteAttrs.getParamAttrs(I));
365   }
366 
367   return AttributeList::get(Ctx, CallSiteAttrs.getFnAttrs(),
368                             CallSiteAttrs.getRetAttrs(),
369                             llvm::makeArrayRef(ArgumentAttributes));
370 }
371 
372 class DataFlowSanitizer {
373   friend struct DFSanFunction;
374   friend class DFSanVisitor;
375 
376   enum { ShadowWidthBits = 8, ShadowWidthBytes = ShadowWidthBits / 8 };
377 
378   enum { OriginWidthBits = 32, OriginWidthBytes = OriginWidthBits / 8 };
379 
380   /// How should calls to uninstrumented functions be handled?
381   enum WrapperKind {
382     /// This function is present in an uninstrumented form but we don't know
383     /// how it should be handled.  Print a warning and call the function anyway.
384     /// Don't label the return value.
385     WK_Warning,
386 
387     /// This function does not write to (user-accessible) memory, and its return
388     /// value is unlabelled.
389     WK_Discard,
390 
391     /// This function does not write to (user-accessible) memory, and the label
392     /// of its return value is the union of the label of its arguments.
393     WK_Functional,
394 
395     /// Instead of calling the function, a custom wrapper __dfsw_F is called,
396     /// where F is the name of the function.  This function may wrap the
397     /// original function or provide its own implementation. WK_Custom uses an
398     /// extra pointer argument to return the shadow.  This allows the wrapped
399     /// form of the function type to be expressed in C.
400     WK_Custom
401   };
402 
403   Module *Mod;
404   LLVMContext *Ctx;
405   Type *Int8Ptr;
406   IntegerType *OriginTy;
407   PointerType *OriginPtrTy;
408   ConstantInt *ZeroOrigin;
409   /// The shadow type for all primitive types and vector types.
410   IntegerType *PrimitiveShadowTy;
411   PointerType *PrimitiveShadowPtrTy;
412   IntegerType *IntptrTy;
413   ConstantInt *ZeroPrimitiveShadow;
414   Constant *ArgTLS;
415   ArrayType *ArgOriginTLSTy;
416   Constant *ArgOriginTLS;
417   Constant *RetvalTLS;
418   Constant *RetvalOriginTLS;
419   FunctionType *DFSanUnionLoadFnTy;
420   FunctionType *DFSanLoadLabelAndOriginFnTy;
421   FunctionType *DFSanUnimplementedFnTy;
422   FunctionType *DFSanSetLabelFnTy;
423   FunctionType *DFSanNonzeroLabelFnTy;
424   FunctionType *DFSanVarargWrapperFnTy;
425   FunctionType *DFSanCmpCallbackFnTy;
426   FunctionType *DFSanLoadStoreCallbackFnTy;
427   FunctionType *DFSanMemTransferCallbackFnTy;
428   FunctionType *DFSanChainOriginFnTy;
429   FunctionType *DFSanChainOriginIfTaintedFnTy;
430   FunctionType *DFSanMemOriginTransferFnTy;
431   FunctionType *DFSanMaybeStoreOriginFnTy;
432   FunctionCallee DFSanUnionLoadFn;
433   FunctionCallee DFSanLoadLabelAndOriginFn;
434   FunctionCallee DFSanUnimplementedFn;
435   FunctionCallee DFSanSetLabelFn;
436   FunctionCallee DFSanNonzeroLabelFn;
437   FunctionCallee DFSanVarargWrapperFn;
438   FunctionCallee DFSanLoadCallbackFn;
439   FunctionCallee DFSanStoreCallbackFn;
440   FunctionCallee DFSanMemTransferCallbackFn;
441   FunctionCallee DFSanCmpCallbackFn;
442   FunctionCallee DFSanChainOriginFn;
443   FunctionCallee DFSanChainOriginIfTaintedFn;
444   FunctionCallee DFSanMemOriginTransferFn;
445   FunctionCallee DFSanMaybeStoreOriginFn;
446   SmallPtrSet<Value *, 16> DFSanRuntimeFunctions;
447   MDNode *ColdCallWeights;
448   MDNode *OriginStoreWeights;
449   DFSanABIList ABIList;
450   DenseMap<Value *, Function *> UnwrappedFnMap;
451   AttrBuilder ReadOnlyNoneAttrs;
452 
453   /// Memory map parameters used in calculation mapping application addresses
454   /// to shadow addresses and origin addresses.
455   const MemoryMapParams *MapParams;
456 
457   Value *getShadowOffset(Value *Addr, IRBuilder<> &IRB);
458   Value *getShadowAddress(Value *Addr, Instruction *Pos);
459   Value *getShadowAddress(Value *Addr, Instruction *Pos, Value *ShadowOffset);
460   std::pair<Value *, Value *>
461   getShadowOriginAddress(Value *Addr, Align InstAlignment, Instruction *Pos);
462   bool isInstrumented(const Function *F);
463   bool isInstrumented(const GlobalAlias *GA);
464   bool isForceZeroLabels(const Function *F);
465   FunctionType *getTrampolineFunctionType(FunctionType *T);
466   TransformedFunction getCustomFunctionType(FunctionType *T);
467   WrapperKind getWrapperKind(Function *F);
468   void addGlobalNameSuffix(GlobalValue *GV);
469   Function *buildWrapperFunction(Function *F, StringRef NewFName,
470                                  GlobalValue::LinkageTypes NewFLink,
471                                  FunctionType *NewFT);
472   Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
473   void initializeCallbackFunctions(Module &M);
474   void initializeRuntimeFunctions(Module &M);
475   void injectMetadataGlobals(Module &M);
476   bool initializeModule(Module &M);
477 
478   /// Advances \p OriginAddr to point to the next 32-bit origin and then loads
479   /// from it. Returns the origin's loaded value.
480   Value *loadNextOrigin(Instruction *Pos, Align OriginAlign,
481                         Value **OriginAddr);
482 
483   /// Returns whether the given load byte size is amenable to inlined
484   /// optimization patterns.
485   bool hasLoadSizeForFastPath(uint64_t Size);
486 
487   /// Returns whether the pass tracks origins. Supports only TLS ABI mode.
488   bool shouldTrackOrigins();
489 
490   /// Returns a zero constant with the shadow type of OrigTy.
491   ///
492   /// getZeroShadow({T1,T2,...}) = {getZeroShadow(T1),getZeroShadow(T2,...}
493   /// getZeroShadow([n x T]) = [n x getZeroShadow(T)]
494   /// getZeroShadow(other type) = i16(0)
495   Constant *getZeroShadow(Type *OrigTy);
496   /// Returns a zero constant with the shadow type of V's type.
497   Constant *getZeroShadow(Value *V);
498 
499   /// Checks if V is a zero shadow.
500   bool isZeroShadow(Value *V);
501 
502   /// Returns the shadow type of OrigTy.
503   ///
504   /// getShadowTy({T1,T2,...}) = {getShadowTy(T1),getShadowTy(T2),...}
505   /// getShadowTy([n x T]) = [n x getShadowTy(T)]
506   /// getShadowTy(other type) = i16
507   Type *getShadowTy(Type *OrigTy);
508   /// Returns the shadow type of of V's type.
509   Type *getShadowTy(Value *V);
510 
511   const uint64_t NumOfElementsInArgOrgTLS = ArgTLSSize / OriginWidthBytes;
512 
513 public:
514   DataFlowSanitizer(const std::vector<std::string> &ABIListFiles);
515 
516   bool runImpl(Module &M);
517 };
518 
519 struct DFSanFunction {
520   DataFlowSanitizer &DFS;
521   Function *F;
522   DominatorTree DT;
523   bool IsNativeABI;
524   bool IsForceZeroLabels;
525   AllocaInst *LabelReturnAlloca = nullptr;
526   AllocaInst *OriginReturnAlloca = nullptr;
527   DenseMap<Value *, Value *> ValShadowMap;
528   DenseMap<Value *, Value *> ValOriginMap;
529   DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
530   DenseMap<AllocaInst *, AllocaInst *> AllocaOriginMap;
531 
532   struct PHIFixupElement {
533     PHINode *Phi;
534     PHINode *ShadowPhi;
535     PHINode *OriginPhi;
536   };
537   std::vector<PHIFixupElement> PHIFixups;
538 
539   DenseSet<Instruction *> SkipInsts;
540   std::vector<Value *> NonZeroChecks;
541 
542   struct CachedShadow {
543     BasicBlock *Block; // The block where Shadow is defined.
544     Value *Shadow;
545   };
546   /// Maps a value to its latest shadow value in terms of domination tree.
547   DenseMap<std::pair<Value *, Value *>, CachedShadow> CachedShadows;
548   /// Maps a value to its latest collapsed shadow value it was converted to in
549   /// terms of domination tree. When ClDebugNonzeroLabels is on, this cache is
550   /// used at a post process where CFG blocks are split. So it does not cache
551   /// BasicBlock like CachedShadows, but uses domination between values.
552   DenseMap<Value *, Value *> CachedCollapsedShadows;
553   DenseMap<Value *, std::set<Value *>> ShadowElements;
554 
DFSanFunction__anond364b4550211::DFSanFunction555   DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI,
556                 bool IsForceZeroLabels)
557       : DFS(DFS), F(F), IsNativeABI(IsNativeABI),
558         IsForceZeroLabels(IsForceZeroLabels) {
559     DT.recalculate(*F);
560   }
561 
562   /// Computes the shadow address for a given function argument.
563   ///
564   /// Shadow = ArgTLS+ArgOffset.
565   Value *getArgTLS(Type *T, unsigned ArgOffset, IRBuilder<> &IRB);
566 
567   /// Computes the shadow address for a return value.
568   Value *getRetvalTLS(Type *T, IRBuilder<> &IRB);
569 
570   /// Computes the origin address for a given function argument.
571   ///
572   /// Origin = ArgOriginTLS[ArgNo].
573   Value *getArgOriginTLS(unsigned ArgNo, IRBuilder<> &IRB);
574 
575   /// Computes the origin address for a return value.
576   Value *getRetvalOriginTLS();
577 
578   Value *getOrigin(Value *V);
579   void setOrigin(Instruction *I, Value *Origin);
580   /// Generates IR to compute the origin of the last operand with a taint label.
581   Value *combineOperandOrigins(Instruction *Inst);
582   /// Before the instruction Pos, generates IR to compute the last origin with a
583   /// taint label. Labels and origins are from vectors Shadows and Origins
584   /// correspondingly. The generated IR is like
585   ///   Sn-1 != Zero ? On-1: ... S2 != Zero ? O2: S1 != Zero ? O1: O0
586   /// When Zero is nullptr, it uses ZeroPrimitiveShadow. Otherwise it can be
587   /// zeros with other bitwidths.
588   Value *combineOrigins(const std::vector<Value *> &Shadows,
589                         const std::vector<Value *> &Origins, Instruction *Pos,
590                         ConstantInt *Zero = nullptr);
591 
592   Value *getShadow(Value *V);
593   void setShadow(Instruction *I, Value *Shadow);
594   /// Generates IR to compute the union of the two given shadows, inserting it
595   /// before Pos. The combined value is with primitive type.
596   Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
597   /// Combines the shadow values of V1 and V2, then converts the combined value
598   /// with primitive type into a shadow value with the original type T.
599   Value *combineShadowsThenConvert(Type *T, Value *V1, Value *V2,
600                                    Instruction *Pos);
601   Value *combineOperandShadows(Instruction *Inst);
602 
603   /// Generates IR to load shadow and origin corresponding to bytes [\p
604   /// Addr, \p Addr + \p Size), where addr has alignment \p
605   /// InstAlignment, and take the union of each of those shadows. The returned
606   /// shadow always has primitive type.
607   ///
608   /// When tracking loads is enabled, the returned origin is a chain at the
609   /// current stack if the returned shadow is tainted.
610   std::pair<Value *, Value *> loadShadowOrigin(Value *Addr, uint64_t Size,
611                                                Align InstAlignment,
612                                                Instruction *Pos);
613 
614   void storePrimitiveShadowOrigin(Value *Addr, uint64_t Size,
615                                   Align InstAlignment, Value *PrimitiveShadow,
616                                   Value *Origin, Instruction *Pos);
617   /// Applies PrimitiveShadow to all primitive subtypes of T, returning
618   /// the expanded shadow value.
619   ///
620   /// EFP({T1,T2, ...}, PS) = {EFP(T1,PS),EFP(T2,PS),...}
621   /// EFP([n x T], PS) = [n x EFP(T,PS)]
622   /// EFP(other types, PS) = PS
623   Value *expandFromPrimitiveShadow(Type *T, Value *PrimitiveShadow,
624                                    Instruction *Pos);
625   /// Collapses Shadow into a single primitive shadow value, unioning all
626   /// primitive shadow values in the process. Returns the final primitive
627   /// shadow value.
628   ///
629   /// CTP({V1,V2, ...}) = UNION(CFP(V1,PS),CFP(V2,PS),...)
630   /// CTP([V1,V2,...]) = UNION(CFP(V1,PS),CFP(V2,PS),...)
631   /// CTP(other types, PS) = PS
632   Value *collapseToPrimitiveShadow(Value *Shadow, Instruction *Pos);
633 
634   void storeZeroPrimitiveShadow(Value *Addr, uint64_t Size, Align ShadowAlign,
635                                 Instruction *Pos);
636 
637   Align getShadowAlign(Align InstAlignment);
638 
639 private:
640   /// Collapses the shadow with aggregate type into a single primitive shadow
641   /// value.
642   template <class AggregateType>
643   Value *collapseAggregateShadow(AggregateType *AT, Value *Shadow,
644                                  IRBuilder<> &IRB);
645 
646   Value *collapseToPrimitiveShadow(Value *Shadow, IRBuilder<> &IRB);
647 
648   /// Returns the shadow value of an argument A.
649   Value *getShadowForTLSArgument(Argument *A);
650 
651   /// The fast path of loading shadows.
652   std::pair<Value *, Value *>
653   loadShadowFast(Value *ShadowAddr, Value *OriginAddr, uint64_t Size,
654                  Align ShadowAlign, Align OriginAlign, Value *FirstOrigin,
655                  Instruction *Pos);
656 
657   Align getOriginAlign(Align InstAlignment);
658 
659   /// Because 4 contiguous bytes share one 4-byte origin, the most accurate load
660   /// is __dfsan_load_label_and_origin. This function returns the union of all
661   /// labels and the origin of the first taint label. However this is an
662   /// additional call with many instructions. To ensure common cases are fast,
663   /// checks if it is possible to load labels and origins without using the
664   /// callback function.
665   ///
666   /// When enabling tracking load instructions, we always use
667   /// __dfsan_load_label_and_origin to reduce code size.
668   bool useCallbackLoadLabelAndOrigin(uint64_t Size, Align InstAlignment);
669 
670   /// Returns a chain at the current stack with previous origin V.
671   Value *updateOrigin(Value *V, IRBuilder<> &IRB);
672 
673   /// Returns a chain at the current stack with previous origin V if Shadow is
674   /// tainted.
675   Value *updateOriginIfTainted(Value *Shadow, Value *Origin, IRBuilder<> &IRB);
676 
677   /// Creates an Intptr = Origin | Origin << 32 if Intptr's size is 64. Returns
678   /// Origin otherwise.
679   Value *originToIntptr(IRBuilder<> &IRB, Value *Origin);
680 
681   /// Stores Origin into the address range [StoreOriginAddr, StoreOriginAddr +
682   /// Size).
683   void paintOrigin(IRBuilder<> &IRB, Value *Origin, Value *StoreOriginAddr,
684                    uint64_t StoreOriginSize, Align Alignment);
685 
686   /// Stores Origin in terms of its Shadow value.
687   /// * Do not write origins for zero shadows because we do not trace origins
688   ///   for untainted sinks.
689   /// * Use __dfsan_maybe_store_origin if there are too many origin store
690   ///   instrumentations.
691   void storeOrigin(Instruction *Pos, Value *Addr, uint64_t Size, Value *Shadow,
692                    Value *Origin, Value *StoreOriginAddr, Align InstAlignment);
693 
694   /// Convert a scalar value to an i1 by comparing with 0.
695   Value *convertToBool(Value *V, IRBuilder<> &IRB, const Twine &Name = "");
696 
697   bool shouldInstrumentWithCall();
698 
699   /// Generates IR to load shadow and origin corresponding to bytes [\p
700   /// Addr, \p Addr + \p Size), where addr has alignment \p
701   /// InstAlignment, and take the union of each of those shadows. The returned
702   /// shadow always has primitive type.
703   std::pair<Value *, Value *>
704   loadShadowOriginSansLoadTracking(Value *Addr, uint64_t Size,
705                                    Align InstAlignment, Instruction *Pos);
706   int NumOriginStores = 0;
707 };
708 
709 class DFSanVisitor : public InstVisitor<DFSanVisitor> {
710 public:
711   DFSanFunction &DFSF;
712 
DFSanVisitor(DFSanFunction & DFSF)713   DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
714 
getDataLayout() const715   const DataLayout &getDataLayout() const {
716     return DFSF.F->getParent()->getDataLayout();
717   }
718 
719   // Combines shadow values and origins for all of I's operands.
720   void visitInstOperands(Instruction &I);
721 
722   void visitUnaryOperator(UnaryOperator &UO);
723   void visitBinaryOperator(BinaryOperator &BO);
724   void visitBitCastInst(BitCastInst &BCI);
725   void visitCastInst(CastInst &CI);
726   void visitCmpInst(CmpInst &CI);
727   void visitLandingPadInst(LandingPadInst &LPI);
728   void visitGetElementPtrInst(GetElementPtrInst &GEPI);
729   void visitLoadInst(LoadInst &LI);
730   void visitStoreInst(StoreInst &SI);
731   void visitAtomicRMWInst(AtomicRMWInst &I);
732   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I);
733   void visitReturnInst(ReturnInst &RI);
734   void visitCallBase(CallBase &CB);
735   void visitPHINode(PHINode &PN);
736   void visitExtractElementInst(ExtractElementInst &I);
737   void visitInsertElementInst(InsertElementInst &I);
738   void visitShuffleVectorInst(ShuffleVectorInst &I);
739   void visitExtractValueInst(ExtractValueInst &I);
740   void visitInsertValueInst(InsertValueInst &I);
741   void visitAllocaInst(AllocaInst &I);
742   void visitSelectInst(SelectInst &I);
743   void visitMemSetInst(MemSetInst &I);
744   void visitMemTransferInst(MemTransferInst &I);
745 
746 private:
747   void visitCASOrRMW(Align InstAlignment, Instruction &I);
748 
749   // Returns false when this is an invoke of a custom function.
750   bool visitWrappedCallBase(Function &F, CallBase &CB);
751 
752   // Combines origins for all of I's operands.
753   void visitInstOperandOrigins(Instruction &I);
754 
755   void addShadowArguments(Function &F, CallBase &CB, std::vector<Value *> &Args,
756                           IRBuilder<> &IRB);
757 
758   void addOriginArguments(Function &F, CallBase &CB, std::vector<Value *> &Args,
759                           IRBuilder<> &IRB);
760 };
761 
762 } // end anonymous namespace
763 
DataFlowSanitizer(const std::vector<std::string> & ABIListFiles)764 DataFlowSanitizer::DataFlowSanitizer(
765     const std::vector<std::string> &ABIListFiles) {
766   std::vector<std::string> AllABIListFiles(std::move(ABIListFiles));
767   llvm::append_range(AllABIListFiles, ClABIListFiles);
768   // FIXME: should we propagate vfs::FileSystem to this constructor?
769   ABIList.set(
770       SpecialCaseList::createOrDie(AllABIListFiles, *vfs::getRealFileSystem()));
771 }
772 
getTrampolineFunctionType(FunctionType * T)773 FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
774   assert(!T->isVarArg());
775   SmallVector<Type *, 4> ArgTypes;
776   ArgTypes.push_back(T->getPointerTo());
777   ArgTypes.append(T->param_begin(), T->param_end());
778   ArgTypes.append(T->getNumParams(), PrimitiveShadowTy);
779   Type *RetType = T->getReturnType();
780   if (!RetType->isVoidTy())
781     ArgTypes.push_back(PrimitiveShadowPtrTy);
782 
783   if (shouldTrackOrigins()) {
784     ArgTypes.append(T->getNumParams(), OriginTy);
785     if (!RetType->isVoidTy())
786       ArgTypes.push_back(OriginPtrTy);
787   }
788 
789   return FunctionType::get(T->getReturnType(), ArgTypes, false);
790 }
791 
getCustomFunctionType(FunctionType * T)792 TransformedFunction DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
793   SmallVector<Type *, 4> ArgTypes;
794 
795   // Some parameters of the custom function being constructed are
796   // parameters of T.  Record the mapping from parameters of T to
797   // parameters of the custom function, so that parameter attributes
798   // at call sites can be updated.
799   std::vector<unsigned> ArgumentIndexMapping;
800   for (unsigned I = 0, E = T->getNumParams(); I != E; ++I) {
801     Type *ParamType = T->getParamType(I);
802     FunctionType *FT;
803     if (isa<PointerType>(ParamType) &&
804         (FT = dyn_cast<FunctionType>(ParamType->getPointerElementType()))) {
805       ArgumentIndexMapping.push_back(ArgTypes.size());
806       ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
807       ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
808     } else {
809       ArgumentIndexMapping.push_back(ArgTypes.size());
810       ArgTypes.push_back(ParamType);
811     }
812   }
813   for (unsigned I = 0, E = T->getNumParams(); I != E; ++I)
814     ArgTypes.push_back(PrimitiveShadowTy);
815   if (T->isVarArg())
816     ArgTypes.push_back(PrimitiveShadowPtrTy);
817   Type *RetType = T->getReturnType();
818   if (!RetType->isVoidTy())
819     ArgTypes.push_back(PrimitiveShadowPtrTy);
820 
821   if (shouldTrackOrigins()) {
822     for (unsigned I = 0, E = T->getNumParams(); I != E; ++I)
823       ArgTypes.push_back(OriginTy);
824     if (T->isVarArg())
825       ArgTypes.push_back(OriginPtrTy);
826     if (!RetType->isVoidTy())
827       ArgTypes.push_back(OriginPtrTy);
828   }
829 
830   return TransformedFunction(
831       T, FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg()),
832       ArgumentIndexMapping);
833 }
834 
isZeroShadow(Value * V)835 bool DataFlowSanitizer::isZeroShadow(Value *V) {
836   Type *T = V->getType();
837   if (!isa<ArrayType>(T) && !isa<StructType>(T)) {
838     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
839       return CI->isZero();
840     return false;
841   }
842 
843   return isa<ConstantAggregateZero>(V);
844 }
845 
hasLoadSizeForFastPath(uint64_t Size)846 bool DataFlowSanitizer::hasLoadSizeForFastPath(uint64_t Size) {
847   uint64_t ShadowSize = Size * ShadowWidthBytes;
848   return ShadowSize % 8 == 0 || ShadowSize == 4;
849 }
850 
shouldTrackOrigins()851 bool DataFlowSanitizer::shouldTrackOrigins() {
852   static const bool ShouldTrackOrigins = ClTrackOrigins;
853   return ShouldTrackOrigins;
854 }
855 
getZeroShadow(Type * OrigTy)856 Constant *DataFlowSanitizer::getZeroShadow(Type *OrigTy) {
857   if (!isa<ArrayType>(OrigTy) && !isa<StructType>(OrigTy))
858     return ZeroPrimitiveShadow;
859   Type *ShadowTy = getShadowTy(OrigTy);
860   return ConstantAggregateZero::get(ShadowTy);
861 }
862 
getZeroShadow(Value * V)863 Constant *DataFlowSanitizer::getZeroShadow(Value *V) {
864   return getZeroShadow(V->getType());
865 }
866 
expandFromPrimitiveShadowRecursive(Value * Shadow,SmallVector<unsigned,4> & Indices,Type * SubShadowTy,Value * PrimitiveShadow,IRBuilder<> & IRB)867 static Value *expandFromPrimitiveShadowRecursive(
868     Value *Shadow, SmallVector<unsigned, 4> &Indices, Type *SubShadowTy,
869     Value *PrimitiveShadow, IRBuilder<> &IRB) {
870   if (!isa<ArrayType>(SubShadowTy) && !isa<StructType>(SubShadowTy))
871     return IRB.CreateInsertValue(Shadow, PrimitiveShadow, Indices);
872 
873   if (ArrayType *AT = dyn_cast<ArrayType>(SubShadowTy)) {
874     for (unsigned Idx = 0; Idx < AT->getNumElements(); Idx++) {
875       Indices.push_back(Idx);
876       Shadow = expandFromPrimitiveShadowRecursive(
877           Shadow, Indices, AT->getElementType(), PrimitiveShadow, IRB);
878       Indices.pop_back();
879     }
880     return Shadow;
881   }
882 
883   if (StructType *ST = dyn_cast<StructType>(SubShadowTy)) {
884     for (unsigned Idx = 0; Idx < ST->getNumElements(); Idx++) {
885       Indices.push_back(Idx);
886       Shadow = expandFromPrimitiveShadowRecursive(
887           Shadow, Indices, ST->getElementType(Idx), PrimitiveShadow, IRB);
888       Indices.pop_back();
889     }
890     return Shadow;
891   }
892   llvm_unreachable("Unexpected shadow type");
893 }
894 
shouldInstrumentWithCall()895 bool DFSanFunction::shouldInstrumentWithCall() {
896   return ClInstrumentWithCallThreshold >= 0 &&
897          NumOriginStores >= ClInstrumentWithCallThreshold;
898 }
899 
expandFromPrimitiveShadow(Type * T,Value * PrimitiveShadow,Instruction * Pos)900 Value *DFSanFunction::expandFromPrimitiveShadow(Type *T, Value *PrimitiveShadow,
901                                                 Instruction *Pos) {
902   Type *ShadowTy = DFS.getShadowTy(T);
903 
904   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
905     return PrimitiveShadow;
906 
907   if (DFS.isZeroShadow(PrimitiveShadow))
908     return DFS.getZeroShadow(ShadowTy);
909 
910   IRBuilder<> IRB(Pos);
911   SmallVector<unsigned, 4> Indices;
912   Value *Shadow = UndefValue::get(ShadowTy);
913   Shadow = expandFromPrimitiveShadowRecursive(Shadow, Indices, ShadowTy,
914                                               PrimitiveShadow, IRB);
915 
916   // Caches the primitive shadow value that built the shadow value.
917   CachedCollapsedShadows[Shadow] = PrimitiveShadow;
918   return Shadow;
919 }
920 
921 template <class AggregateType>
collapseAggregateShadow(AggregateType * AT,Value * Shadow,IRBuilder<> & IRB)922 Value *DFSanFunction::collapseAggregateShadow(AggregateType *AT, Value *Shadow,
923                                               IRBuilder<> &IRB) {
924   if (!AT->getNumElements())
925     return DFS.ZeroPrimitiveShadow;
926 
927   Value *FirstItem = IRB.CreateExtractValue(Shadow, 0);
928   Value *Aggregator = collapseToPrimitiveShadow(FirstItem, IRB);
929 
930   for (unsigned Idx = 1; Idx < AT->getNumElements(); Idx++) {
931     Value *ShadowItem = IRB.CreateExtractValue(Shadow, Idx);
932     Value *ShadowInner = collapseToPrimitiveShadow(ShadowItem, IRB);
933     Aggregator = IRB.CreateOr(Aggregator, ShadowInner);
934   }
935   return Aggregator;
936 }
937 
collapseToPrimitiveShadow(Value * Shadow,IRBuilder<> & IRB)938 Value *DFSanFunction::collapseToPrimitiveShadow(Value *Shadow,
939                                                 IRBuilder<> &IRB) {
940   Type *ShadowTy = Shadow->getType();
941   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
942     return Shadow;
943   if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy))
944     return collapseAggregateShadow<>(AT, Shadow, IRB);
945   if (StructType *ST = dyn_cast<StructType>(ShadowTy))
946     return collapseAggregateShadow<>(ST, Shadow, IRB);
947   llvm_unreachable("Unexpected shadow type");
948 }
949 
collapseToPrimitiveShadow(Value * Shadow,Instruction * Pos)950 Value *DFSanFunction::collapseToPrimitiveShadow(Value *Shadow,
951                                                 Instruction *Pos) {
952   Type *ShadowTy = Shadow->getType();
953   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
954     return Shadow;
955 
956   // Checks if the cached collapsed shadow value dominates Pos.
957   Value *&CS = CachedCollapsedShadows[Shadow];
958   if (CS && DT.dominates(CS, Pos))
959     return CS;
960 
961   IRBuilder<> IRB(Pos);
962   Value *PrimitiveShadow = collapseToPrimitiveShadow(Shadow, IRB);
963   // Caches the converted primitive shadow value.
964   CS = PrimitiveShadow;
965   return PrimitiveShadow;
966 }
967 
getShadowTy(Type * OrigTy)968 Type *DataFlowSanitizer::getShadowTy(Type *OrigTy) {
969   if (!OrigTy->isSized())
970     return PrimitiveShadowTy;
971   if (isa<IntegerType>(OrigTy))
972     return PrimitiveShadowTy;
973   if (isa<VectorType>(OrigTy))
974     return PrimitiveShadowTy;
975   if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy))
976     return ArrayType::get(getShadowTy(AT->getElementType()),
977                           AT->getNumElements());
978   if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
979     SmallVector<Type *, 4> Elements;
980     for (unsigned I = 0, N = ST->getNumElements(); I < N; ++I)
981       Elements.push_back(getShadowTy(ST->getElementType(I)));
982     return StructType::get(*Ctx, Elements);
983   }
984   return PrimitiveShadowTy;
985 }
986 
getShadowTy(Value * V)987 Type *DataFlowSanitizer::getShadowTy(Value *V) {
988   return getShadowTy(V->getType());
989 }
990 
initializeModule(Module & M)991 bool DataFlowSanitizer::initializeModule(Module &M) {
992   Triple TargetTriple(M.getTargetTriple());
993   const DataLayout &DL = M.getDataLayout();
994 
995   if (TargetTriple.getOS() != Triple::Linux)
996     report_fatal_error("unsupported operating system");
997   if (TargetTriple.getArch() != Triple::x86_64)
998     report_fatal_error("unsupported architecture");
999   MapParams = &Linux_X86_64_MemoryMapParams;
1000 
1001   Mod = &M;
1002   Ctx = &M.getContext();
1003   Int8Ptr = Type::getInt8PtrTy(*Ctx);
1004   OriginTy = IntegerType::get(*Ctx, OriginWidthBits);
1005   OriginPtrTy = PointerType::getUnqual(OriginTy);
1006   PrimitiveShadowTy = IntegerType::get(*Ctx, ShadowWidthBits);
1007   PrimitiveShadowPtrTy = PointerType::getUnqual(PrimitiveShadowTy);
1008   IntptrTy = DL.getIntPtrType(*Ctx);
1009   ZeroPrimitiveShadow = ConstantInt::getSigned(PrimitiveShadowTy, 0);
1010   ZeroOrigin = ConstantInt::getSigned(OriginTy, 0);
1011 
1012   Type *DFSanUnionLoadArgs[2] = {PrimitiveShadowPtrTy, IntptrTy};
1013   DFSanUnionLoadFnTy = FunctionType::get(PrimitiveShadowTy, DFSanUnionLoadArgs,
1014                                          /*isVarArg=*/false);
1015   Type *DFSanLoadLabelAndOriginArgs[2] = {Int8Ptr, IntptrTy};
1016   DFSanLoadLabelAndOriginFnTy =
1017       FunctionType::get(IntegerType::get(*Ctx, 64), DFSanLoadLabelAndOriginArgs,
1018                         /*isVarArg=*/false);
1019   DFSanUnimplementedFnTy = FunctionType::get(
1020       Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
1021   Type *DFSanSetLabelArgs[4] = {PrimitiveShadowTy, OriginTy,
1022                                 Type::getInt8PtrTy(*Ctx), IntptrTy};
1023   DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
1024                                         DFSanSetLabelArgs, /*isVarArg=*/false);
1025   DFSanNonzeroLabelFnTy =
1026       FunctionType::get(Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
1027   DFSanVarargWrapperFnTy = FunctionType::get(
1028       Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
1029   DFSanCmpCallbackFnTy =
1030       FunctionType::get(Type::getVoidTy(*Ctx), PrimitiveShadowTy,
1031                         /*isVarArg=*/false);
1032   DFSanChainOriginFnTy =
1033       FunctionType::get(OriginTy, OriginTy, /*isVarArg=*/false);
1034   Type *DFSanChainOriginIfTaintedArgs[2] = {PrimitiveShadowTy, OriginTy};
1035   DFSanChainOriginIfTaintedFnTy = FunctionType::get(
1036       OriginTy, DFSanChainOriginIfTaintedArgs, /*isVarArg=*/false);
1037   Type *DFSanMaybeStoreOriginArgs[4] = {IntegerType::get(*Ctx, ShadowWidthBits),
1038                                         Int8Ptr, IntptrTy, OriginTy};
1039   DFSanMaybeStoreOriginFnTy = FunctionType::get(
1040       Type::getVoidTy(*Ctx), DFSanMaybeStoreOriginArgs, /*isVarArg=*/false);
1041   Type *DFSanMemOriginTransferArgs[3] = {Int8Ptr, Int8Ptr, IntptrTy};
1042   DFSanMemOriginTransferFnTy = FunctionType::get(
1043       Type::getVoidTy(*Ctx), DFSanMemOriginTransferArgs, /*isVarArg=*/false);
1044   Type *DFSanLoadStoreCallbackArgs[2] = {PrimitiveShadowTy, Int8Ptr};
1045   DFSanLoadStoreCallbackFnTy =
1046       FunctionType::get(Type::getVoidTy(*Ctx), DFSanLoadStoreCallbackArgs,
1047                         /*isVarArg=*/false);
1048   Type *DFSanMemTransferCallbackArgs[2] = {PrimitiveShadowPtrTy, IntptrTy};
1049   DFSanMemTransferCallbackFnTy =
1050       FunctionType::get(Type::getVoidTy(*Ctx), DFSanMemTransferCallbackArgs,
1051                         /*isVarArg=*/false);
1052 
1053   ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
1054   OriginStoreWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
1055   return true;
1056 }
1057 
isInstrumented(const Function * F)1058 bool DataFlowSanitizer::isInstrumented(const Function *F) {
1059   return !ABIList.isIn(*F, "uninstrumented");
1060 }
1061 
isInstrumented(const GlobalAlias * GA)1062 bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
1063   return !ABIList.isIn(*GA, "uninstrumented");
1064 }
1065 
isForceZeroLabels(const Function * F)1066 bool DataFlowSanitizer::isForceZeroLabels(const Function *F) {
1067   return ABIList.isIn(*F, "force_zero_labels");
1068 }
1069 
getWrapperKind(Function * F)1070 DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
1071   if (ABIList.isIn(*F, "functional"))
1072     return WK_Functional;
1073   if (ABIList.isIn(*F, "discard"))
1074     return WK_Discard;
1075   if (ABIList.isIn(*F, "custom"))
1076     return WK_Custom;
1077 
1078   return WK_Warning;
1079 }
1080 
addGlobalNameSuffix(GlobalValue * GV)1081 void DataFlowSanitizer::addGlobalNameSuffix(GlobalValue *GV) {
1082   std::string GVName = std::string(GV->getName()), Suffix = ".dfsan";
1083   GV->setName(GVName + Suffix);
1084 
1085   // Try to change the name of the function in module inline asm.  We only do
1086   // this for specific asm directives, currently only ".symver", to try to avoid
1087   // corrupting asm which happens to contain the symbol name as a substring.
1088   // Note that the substitution for .symver assumes that the versioned symbol
1089   // also has an instrumented name.
1090   std::string Asm = GV->getParent()->getModuleInlineAsm();
1091   std::string SearchStr = ".symver " + GVName + ",";
1092   size_t Pos = Asm.find(SearchStr);
1093   if (Pos != std::string::npos) {
1094     Asm.replace(Pos, SearchStr.size(), ".symver " + GVName + Suffix + ",");
1095     Pos = Asm.find("@");
1096 
1097     if (Pos == std::string::npos)
1098       report_fatal_error(Twine("unsupported .symver: ", Asm));
1099 
1100     Asm.replace(Pos, 1, Suffix + "@");
1101     GV->getParent()->setModuleInlineAsm(Asm);
1102   }
1103 }
1104 
1105 Function *
buildWrapperFunction(Function * F,StringRef NewFName,GlobalValue::LinkageTypes NewFLink,FunctionType * NewFT)1106 DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
1107                                         GlobalValue::LinkageTypes NewFLink,
1108                                         FunctionType *NewFT) {
1109   FunctionType *FT = F->getFunctionType();
1110   Function *NewF = Function::Create(NewFT, NewFLink, F->getAddressSpace(),
1111                                     NewFName, F->getParent());
1112   NewF->copyAttributesFrom(F);
1113   NewF->removeRetAttrs(
1114       AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
1115 
1116   BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
1117   if (F->isVarArg()) {
1118     NewF->removeFnAttrs(AttrBuilder().addAttribute("split-stack"));
1119     CallInst::Create(DFSanVarargWrapperFn,
1120                      IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "",
1121                      BB);
1122     new UnreachableInst(*Ctx, BB);
1123   } else {
1124     auto ArgIt = pointer_iterator<Argument *>(NewF->arg_begin());
1125     std::vector<Value *> Args(ArgIt, ArgIt + FT->getNumParams());
1126 
1127     CallInst *CI = CallInst::Create(F, Args, "", BB);
1128     if (FT->getReturnType()->isVoidTy())
1129       ReturnInst::Create(*Ctx, BB);
1130     else
1131       ReturnInst::Create(*Ctx, CI, BB);
1132   }
1133 
1134   return NewF;
1135 }
1136 
getOrBuildTrampolineFunction(FunctionType * FT,StringRef FName)1137 Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
1138                                                           StringRef FName) {
1139   FunctionType *FTT = getTrampolineFunctionType(FT);
1140   FunctionCallee C = Mod->getOrInsertFunction(FName, FTT);
1141   Function *F = dyn_cast<Function>(C.getCallee());
1142   if (F && F->isDeclaration()) {
1143     F->setLinkage(GlobalValue::LinkOnceODRLinkage);
1144     BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
1145     std::vector<Value *> Args;
1146     Function::arg_iterator AI = F->arg_begin() + 1;
1147     for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
1148       Args.push_back(&*AI);
1149     CallInst *CI = CallInst::Create(FT, &*F->arg_begin(), Args, "", BB);
1150     Type *RetType = FT->getReturnType();
1151     ReturnInst *RI = RetType->isVoidTy() ? ReturnInst::Create(*Ctx, BB)
1152                                          : ReturnInst::Create(*Ctx, CI, BB);
1153 
1154     // F is called by a wrapped custom function with primitive shadows. So
1155     // its arguments and return value need conversion.
1156     DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true,
1157                        /*ForceZeroLabels=*/false);
1158     Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI;
1159     ++ValAI;
1160     for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N) {
1161       Value *Shadow =
1162           DFSF.expandFromPrimitiveShadow(ValAI->getType(), &*ShadowAI, CI);
1163       DFSF.ValShadowMap[&*ValAI] = Shadow;
1164     }
1165     Function::arg_iterator RetShadowAI = ShadowAI;
1166     const bool ShouldTrackOrigins = shouldTrackOrigins();
1167     if (ShouldTrackOrigins) {
1168       ValAI = F->arg_begin();
1169       ++ValAI;
1170       Function::arg_iterator OriginAI = ShadowAI;
1171       if (!RetType->isVoidTy())
1172         ++OriginAI;
1173       for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++OriginAI, --N) {
1174         DFSF.ValOriginMap[&*ValAI] = &*OriginAI;
1175       }
1176     }
1177     DFSanVisitor(DFSF).visitCallInst(*CI);
1178     if (!RetType->isVoidTy()) {
1179       Value *PrimitiveShadow = DFSF.collapseToPrimitiveShadow(
1180           DFSF.getShadow(RI->getReturnValue()), RI);
1181       new StoreInst(PrimitiveShadow, &*RetShadowAI, RI);
1182       if (ShouldTrackOrigins) {
1183         Value *Origin = DFSF.getOrigin(RI->getReturnValue());
1184         new StoreInst(Origin, &*std::prev(F->arg_end()), RI);
1185       }
1186     }
1187   }
1188 
1189   return cast<Constant>(C.getCallee());
1190 }
1191 
1192 // Initialize DataFlowSanitizer runtime functions and declare them in the module
initializeRuntimeFunctions(Module & M)1193 void DataFlowSanitizer::initializeRuntimeFunctions(Module &M) {
1194   {
1195     AttributeList AL;
1196     AL = AL.addFnAttribute(M.getContext(), Attribute::NoUnwind);
1197     AL = AL.addFnAttribute(M.getContext(), Attribute::ReadOnly);
1198     AL = AL.addRetAttribute(M.getContext(), Attribute::ZExt);
1199     DFSanUnionLoadFn =
1200         Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy, AL);
1201   }
1202   {
1203     AttributeList AL;
1204     AL = AL.addFnAttribute(M.getContext(), Attribute::NoUnwind);
1205     AL = AL.addFnAttribute(M.getContext(), Attribute::ReadOnly);
1206     AL = AL.addRetAttribute(M.getContext(), Attribute::ZExt);
1207     DFSanLoadLabelAndOriginFn = Mod->getOrInsertFunction(
1208         "__dfsan_load_label_and_origin", DFSanLoadLabelAndOriginFnTy, AL);
1209   }
1210   DFSanUnimplementedFn =
1211       Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
1212   {
1213     AttributeList AL;
1214     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1215     AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
1216     DFSanSetLabelFn =
1217         Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy, AL);
1218   }
1219   DFSanNonzeroLabelFn =
1220       Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
1221   DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper",
1222                                                   DFSanVarargWrapperFnTy);
1223   {
1224     AttributeList AL;
1225     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1226     AL = AL.addRetAttribute(M.getContext(), Attribute::ZExt);
1227     DFSanChainOriginFn = Mod->getOrInsertFunction("__dfsan_chain_origin",
1228                                                   DFSanChainOriginFnTy, AL);
1229   }
1230   {
1231     AttributeList AL;
1232     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1233     AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
1234     AL = AL.addRetAttribute(M.getContext(), Attribute::ZExt);
1235     DFSanChainOriginIfTaintedFn = Mod->getOrInsertFunction(
1236         "__dfsan_chain_origin_if_tainted", DFSanChainOriginIfTaintedFnTy, AL);
1237   }
1238   DFSanMemOriginTransferFn = Mod->getOrInsertFunction(
1239       "__dfsan_mem_origin_transfer", DFSanMemOriginTransferFnTy);
1240 
1241   {
1242     AttributeList AL;
1243     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1244     AL = AL.addParamAttribute(M.getContext(), 3, Attribute::ZExt);
1245     DFSanMaybeStoreOriginFn = Mod->getOrInsertFunction(
1246         "__dfsan_maybe_store_origin", DFSanMaybeStoreOriginFnTy, AL);
1247   }
1248 
1249   DFSanRuntimeFunctions.insert(
1250       DFSanUnionLoadFn.getCallee()->stripPointerCasts());
1251   DFSanRuntimeFunctions.insert(
1252       DFSanLoadLabelAndOriginFn.getCallee()->stripPointerCasts());
1253   DFSanRuntimeFunctions.insert(
1254       DFSanUnimplementedFn.getCallee()->stripPointerCasts());
1255   DFSanRuntimeFunctions.insert(
1256       DFSanSetLabelFn.getCallee()->stripPointerCasts());
1257   DFSanRuntimeFunctions.insert(
1258       DFSanNonzeroLabelFn.getCallee()->stripPointerCasts());
1259   DFSanRuntimeFunctions.insert(
1260       DFSanVarargWrapperFn.getCallee()->stripPointerCasts());
1261   DFSanRuntimeFunctions.insert(
1262       DFSanLoadCallbackFn.getCallee()->stripPointerCasts());
1263   DFSanRuntimeFunctions.insert(
1264       DFSanStoreCallbackFn.getCallee()->stripPointerCasts());
1265   DFSanRuntimeFunctions.insert(
1266       DFSanMemTransferCallbackFn.getCallee()->stripPointerCasts());
1267   DFSanRuntimeFunctions.insert(
1268       DFSanCmpCallbackFn.getCallee()->stripPointerCasts());
1269   DFSanRuntimeFunctions.insert(
1270       DFSanChainOriginFn.getCallee()->stripPointerCasts());
1271   DFSanRuntimeFunctions.insert(
1272       DFSanChainOriginIfTaintedFn.getCallee()->stripPointerCasts());
1273   DFSanRuntimeFunctions.insert(
1274       DFSanMemOriginTransferFn.getCallee()->stripPointerCasts());
1275   DFSanRuntimeFunctions.insert(
1276       DFSanMaybeStoreOriginFn.getCallee()->stripPointerCasts());
1277 }
1278 
1279 // Initializes event callback functions and declare them in the module
initializeCallbackFunctions(Module & M)1280 void DataFlowSanitizer::initializeCallbackFunctions(Module &M) {
1281   DFSanLoadCallbackFn = Mod->getOrInsertFunction("__dfsan_load_callback",
1282                                                  DFSanLoadStoreCallbackFnTy);
1283   DFSanStoreCallbackFn = Mod->getOrInsertFunction("__dfsan_store_callback",
1284                                                   DFSanLoadStoreCallbackFnTy);
1285   DFSanMemTransferCallbackFn = Mod->getOrInsertFunction(
1286       "__dfsan_mem_transfer_callback", DFSanMemTransferCallbackFnTy);
1287   DFSanCmpCallbackFn =
1288       Mod->getOrInsertFunction("__dfsan_cmp_callback", DFSanCmpCallbackFnTy);
1289 }
1290 
injectMetadataGlobals(Module & M)1291 void DataFlowSanitizer::injectMetadataGlobals(Module &M) {
1292   // These variables can be used:
1293   // - by the runtime (to discover what the shadow width was, during
1294   //   compilation)
1295   // - in testing (to avoid hardcoding the shadow width and type but instead
1296   //   extract them by pattern matching)
1297   Type *IntTy = Type::getInt32Ty(*Ctx);
1298   (void)Mod->getOrInsertGlobal("__dfsan_shadow_width_bits", IntTy, [&] {
1299     return new GlobalVariable(
1300         M, IntTy, /*isConstant=*/true, GlobalValue::WeakODRLinkage,
1301         ConstantInt::get(IntTy, ShadowWidthBits), "__dfsan_shadow_width_bits");
1302   });
1303   (void)Mod->getOrInsertGlobal("__dfsan_shadow_width_bytes", IntTy, [&] {
1304     return new GlobalVariable(M, IntTy, /*isConstant=*/true,
1305                               GlobalValue::WeakODRLinkage,
1306                               ConstantInt::get(IntTy, ShadowWidthBytes),
1307                               "__dfsan_shadow_width_bytes");
1308   });
1309 }
1310 
runImpl(Module & M)1311 bool DataFlowSanitizer::runImpl(Module &M) {
1312   initializeModule(M);
1313 
1314   if (ABIList.isIn(M, "skip"))
1315     return false;
1316 
1317   const unsigned InitialGlobalSize = M.global_size();
1318   const unsigned InitialModuleSize = M.size();
1319 
1320   bool Changed = false;
1321 
1322   auto GetOrInsertGlobal = [this, &Changed](StringRef Name,
1323                                             Type *Ty) -> Constant * {
1324     Constant *C = Mod->getOrInsertGlobal(Name, Ty);
1325     if (GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1326       Changed |= G->getThreadLocalMode() != GlobalVariable::InitialExecTLSModel;
1327       G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
1328     }
1329     return C;
1330   };
1331 
1332   // These globals must be kept in sync with the ones in dfsan.cpp.
1333   ArgTLS =
1334       GetOrInsertGlobal("__dfsan_arg_tls",
1335                         ArrayType::get(Type::getInt64Ty(*Ctx), ArgTLSSize / 8));
1336   RetvalTLS = GetOrInsertGlobal(
1337       "__dfsan_retval_tls",
1338       ArrayType::get(Type::getInt64Ty(*Ctx), RetvalTLSSize / 8));
1339   ArgOriginTLSTy = ArrayType::get(OriginTy, NumOfElementsInArgOrgTLS);
1340   ArgOriginTLS = GetOrInsertGlobal("__dfsan_arg_origin_tls", ArgOriginTLSTy);
1341   RetvalOriginTLS = GetOrInsertGlobal("__dfsan_retval_origin_tls", OriginTy);
1342 
1343   (void)Mod->getOrInsertGlobal("__dfsan_track_origins", OriginTy, [&] {
1344     Changed = true;
1345     return new GlobalVariable(
1346         M, OriginTy, true, GlobalValue::WeakODRLinkage,
1347         ConstantInt::getSigned(OriginTy,
1348                                shouldTrackOrigins() ? ClTrackOrigins : 0),
1349         "__dfsan_track_origins");
1350   });
1351 
1352   injectMetadataGlobals(M);
1353 
1354   initializeCallbackFunctions(M);
1355   initializeRuntimeFunctions(M);
1356 
1357   std::vector<Function *> FnsToInstrument;
1358   SmallPtrSet<Function *, 2> FnsWithNativeABI;
1359   SmallPtrSet<Function *, 2> FnsWithForceZeroLabel;
1360   for (Function &F : M)
1361     if (!F.isIntrinsic() && !DFSanRuntimeFunctions.contains(&F))
1362       FnsToInstrument.push_back(&F);
1363 
1364   // Give function aliases prefixes when necessary, and build wrappers where the
1365   // instrumentedness is inconsistent.
1366   for (Module::alias_iterator AI = M.alias_begin(), AE = M.alias_end();
1367        AI != AE;) {
1368     GlobalAlias *GA = &*AI;
1369     ++AI;
1370     // Don't stop on weak.  We assume people aren't playing games with the
1371     // instrumentedness of overridden weak aliases.
1372     auto *F = dyn_cast<Function>(GA->getAliaseeObject());
1373     if (!F)
1374       continue;
1375 
1376     bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
1377     if (GAInst && FInst) {
1378       addGlobalNameSuffix(GA);
1379     } else if (GAInst != FInst) {
1380       // Non-instrumented alias of an instrumented function, or vice versa.
1381       // Replace the alias with a native-ABI wrapper of the aliasee.  The pass
1382       // below will take care of instrumenting it.
1383       Function *NewF =
1384           buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
1385       GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
1386       NewF->takeName(GA);
1387       GA->eraseFromParent();
1388       FnsToInstrument.push_back(NewF);
1389     }
1390   }
1391 
1392   ReadOnlyNoneAttrs.addAttribute(Attribute::ReadOnly)
1393       .addAttribute(Attribute::ReadNone);
1394 
1395   // First, change the ABI of every function in the module.  ABI-listed
1396   // functions keep their original ABI and get a wrapper function.
1397   for (std::vector<Function *>::iterator FI = FnsToInstrument.begin(),
1398                                          FE = FnsToInstrument.end();
1399        FI != FE; ++FI) {
1400     Function &F = **FI;
1401     FunctionType *FT = F.getFunctionType();
1402 
1403     bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
1404                               FT->getReturnType()->isVoidTy());
1405 
1406     if (isInstrumented(&F)) {
1407       if (isForceZeroLabels(&F))
1408         FnsWithForceZeroLabel.insert(&F);
1409 
1410       // Instrumented functions get a '.dfsan' suffix.  This allows us to more
1411       // easily identify cases of mismatching ABIs. This naming scheme is
1412       // mangling-compatible (see Itanium ABI), using a vendor-specific suffix.
1413       addGlobalNameSuffix(&F);
1414     } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
1415       // Build a wrapper function for F.  The wrapper simply calls F, and is
1416       // added to FnsToInstrument so that any instrumentation according to its
1417       // WrapperKind is done in the second pass below.
1418 
1419       // If the function being wrapped has local linkage, then preserve the
1420       // function's linkage in the wrapper function.
1421       GlobalValue::LinkageTypes WrapperLinkage =
1422           F.hasLocalLinkage() ? F.getLinkage()
1423                               : GlobalValue::LinkOnceODRLinkage;
1424 
1425       Function *NewF = buildWrapperFunction(
1426           &F,
1427           (shouldTrackOrigins() ? std::string("dfso$") : std::string("dfsw$")) +
1428               std::string(F.getName()),
1429           WrapperLinkage, FT);
1430       NewF->removeFnAttrs(ReadOnlyNoneAttrs);
1431 
1432       Value *WrappedFnCst =
1433           ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
1434       F.replaceAllUsesWith(WrappedFnCst);
1435 
1436       UnwrappedFnMap[WrappedFnCst] = &F;
1437       *FI = NewF;
1438 
1439       if (!F.isDeclaration()) {
1440         // This function is probably defining an interposition of an
1441         // uninstrumented function and hence needs to keep the original ABI.
1442         // But any functions it may call need to use the instrumented ABI, so
1443         // we instrument it in a mode which preserves the original ABI.
1444         FnsWithNativeABI.insert(&F);
1445 
1446         // This code needs to rebuild the iterators, as they may be invalidated
1447         // by the push_back, taking care that the new range does not include
1448         // any functions added by this code.
1449         size_t N = FI - FnsToInstrument.begin(),
1450                Count = FE - FnsToInstrument.begin();
1451         FnsToInstrument.push_back(&F);
1452         FI = FnsToInstrument.begin() + N;
1453         FE = FnsToInstrument.begin() + Count;
1454       }
1455       // Hopefully, nobody will try to indirectly call a vararg
1456       // function... yet.
1457     } else if (FT->isVarArg()) {
1458       UnwrappedFnMap[&F] = &F;
1459       *FI = nullptr;
1460     }
1461   }
1462 
1463   for (Function *F : FnsToInstrument) {
1464     if (!F || F->isDeclaration())
1465       continue;
1466 
1467     removeUnreachableBlocks(*F);
1468 
1469     DFSanFunction DFSF(*this, F, FnsWithNativeABI.count(F),
1470                        FnsWithForceZeroLabel.count(F));
1471 
1472     // DFSanVisitor may create new basic blocks, which confuses df_iterator.
1473     // Build a copy of the list before iterating over it.
1474     SmallVector<BasicBlock *, 4> BBList(depth_first(&F->getEntryBlock()));
1475 
1476     for (BasicBlock *BB : BBList) {
1477       Instruction *Inst = &BB->front();
1478       while (true) {
1479         // DFSanVisitor may split the current basic block, changing the current
1480         // instruction's next pointer and moving the next instruction to the
1481         // tail block from which we should continue.
1482         Instruction *Next = Inst->getNextNode();
1483         // DFSanVisitor may delete Inst, so keep track of whether it was a
1484         // terminator.
1485         bool IsTerminator = Inst->isTerminator();
1486         if (!DFSF.SkipInsts.count(Inst))
1487           DFSanVisitor(DFSF).visit(Inst);
1488         if (IsTerminator)
1489           break;
1490         Inst = Next;
1491       }
1492     }
1493 
1494     // We will not necessarily be able to compute the shadow for every phi node
1495     // until we have visited every block.  Therefore, the code that handles phi
1496     // nodes adds them to the PHIFixups list so that they can be properly
1497     // handled here.
1498     for (DFSanFunction::PHIFixupElement &P : DFSF.PHIFixups) {
1499       for (unsigned Val = 0, N = P.Phi->getNumIncomingValues(); Val != N;
1500            ++Val) {
1501         P.ShadowPhi->setIncomingValue(
1502             Val, DFSF.getShadow(P.Phi->getIncomingValue(Val)));
1503         if (P.OriginPhi)
1504           P.OriginPhi->setIncomingValue(
1505               Val, DFSF.getOrigin(P.Phi->getIncomingValue(Val)));
1506       }
1507     }
1508 
1509     // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
1510     // places (i.e. instructions in basic blocks we haven't even begun visiting
1511     // yet).  To make our life easier, do this work in a pass after the main
1512     // instrumentation.
1513     if (ClDebugNonzeroLabels) {
1514       for (Value *V : DFSF.NonZeroChecks) {
1515         Instruction *Pos;
1516         if (Instruction *I = dyn_cast<Instruction>(V))
1517           Pos = I->getNextNode();
1518         else
1519           Pos = &DFSF.F->getEntryBlock().front();
1520         while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
1521           Pos = Pos->getNextNode();
1522         IRBuilder<> IRB(Pos);
1523         Value *PrimitiveShadow = DFSF.collapseToPrimitiveShadow(V, Pos);
1524         Value *Ne =
1525             IRB.CreateICmpNE(PrimitiveShadow, DFSF.DFS.ZeroPrimitiveShadow);
1526         BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
1527             Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
1528         IRBuilder<> ThenIRB(BI);
1529         ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn, {});
1530       }
1531     }
1532   }
1533 
1534   return Changed || !FnsToInstrument.empty() ||
1535          M.global_size() != InitialGlobalSize || M.size() != InitialModuleSize;
1536 }
1537 
getArgTLS(Type * T,unsigned ArgOffset,IRBuilder<> & IRB)1538 Value *DFSanFunction::getArgTLS(Type *T, unsigned ArgOffset, IRBuilder<> &IRB) {
1539   Value *Base = IRB.CreatePointerCast(DFS.ArgTLS, DFS.IntptrTy);
1540   if (ArgOffset)
1541     Base = IRB.CreateAdd(Base, ConstantInt::get(DFS.IntptrTy, ArgOffset));
1542   return IRB.CreateIntToPtr(Base, PointerType::get(DFS.getShadowTy(T), 0),
1543                             "_dfsarg");
1544 }
1545 
getRetvalTLS(Type * T,IRBuilder<> & IRB)1546 Value *DFSanFunction::getRetvalTLS(Type *T, IRBuilder<> &IRB) {
1547   return IRB.CreatePointerCast(
1548       DFS.RetvalTLS, PointerType::get(DFS.getShadowTy(T), 0), "_dfsret");
1549 }
1550 
getRetvalOriginTLS()1551 Value *DFSanFunction::getRetvalOriginTLS() { return DFS.RetvalOriginTLS; }
1552 
getArgOriginTLS(unsigned ArgNo,IRBuilder<> & IRB)1553 Value *DFSanFunction::getArgOriginTLS(unsigned ArgNo, IRBuilder<> &IRB) {
1554   return IRB.CreateConstGEP2_64(DFS.ArgOriginTLSTy, DFS.ArgOriginTLS, 0, ArgNo,
1555                                 "_dfsarg_o");
1556 }
1557 
getOrigin(Value * V)1558 Value *DFSanFunction::getOrigin(Value *V) {
1559   assert(DFS.shouldTrackOrigins());
1560   if (!isa<Argument>(V) && !isa<Instruction>(V))
1561     return DFS.ZeroOrigin;
1562   Value *&Origin = ValOriginMap[V];
1563   if (!Origin) {
1564     if (Argument *A = dyn_cast<Argument>(V)) {
1565       if (IsNativeABI)
1566         return DFS.ZeroOrigin;
1567       if (A->getArgNo() < DFS.NumOfElementsInArgOrgTLS) {
1568         Instruction *ArgOriginTLSPos = &*F->getEntryBlock().begin();
1569         IRBuilder<> IRB(ArgOriginTLSPos);
1570         Value *ArgOriginPtr = getArgOriginTLS(A->getArgNo(), IRB);
1571         Origin = IRB.CreateLoad(DFS.OriginTy, ArgOriginPtr);
1572       } else {
1573         // Overflow
1574         Origin = DFS.ZeroOrigin;
1575       }
1576     } else {
1577       Origin = DFS.ZeroOrigin;
1578     }
1579   }
1580   return Origin;
1581 }
1582 
setOrigin(Instruction * I,Value * Origin)1583 void DFSanFunction::setOrigin(Instruction *I, Value *Origin) {
1584   if (!DFS.shouldTrackOrigins())
1585     return;
1586   assert(!ValOriginMap.count(I));
1587   assert(Origin->getType() == DFS.OriginTy);
1588   ValOriginMap[I] = Origin;
1589 }
1590 
getShadowForTLSArgument(Argument * A)1591 Value *DFSanFunction::getShadowForTLSArgument(Argument *A) {
1592   unsigned ArgOffset = 0;
1593   const DataLayout &DL = F->getParent()->getDataLayout();
1594   for (auto &FArg : F->args()) {
1595     if (!FArg.getType()->isSized()) {
1596       if (A == &FArg)
1597         break;
1598       continue;
1599     }
1600 
1601     unsigned Size = DL.getTypeAllocSize(DFS.getShadowTy(&FArg));
1602     if (A != &FArg) {
1603       ArgOffset += alignTo(Size, ShadowTLSAlignment);
1604       if (ArgOffset > ArgTLSSize)
1605         break; // ArgTLS overflows, uses a zero shadow.
1606       continue;
1607     }
1608 
1609     if (ArgOffset + Size > ArgTLSSize)
1610       break; // ArgTLS overflows, uses a zero shadow.
1611 
1612     Instruction *ArgTLSPos = &*F->getEntryBlock().begin();
1613     IRBuilder<> IRB(ArgTLSPos);
1614     Value *ArgShadowPtr = getArgTLS(FArg.getType(), ArgOffset, IRB);
1615     return IRB.CreateAlignedLoad(DFS.getShadowTy(&FArg), ArgShadowPtr,
1616                                  ShadowTLSAlignment);
1617   }
1618 
1619   return DFS.getZeroShadow(A);
1620 }
1621 
getShadow(Value * V)1622 Value *DFSanFunction::getShadow(Value *V) {
1623   if (!isa<Argument>(V) && !isa<Instruction>(V))
1624     return DFS.getZeroShadow(V);
1625   if (IsForceZeroLabels)
1626     return DFS.getZeroShadow(V);
1627   Value *&Shadow = ValShadowMap[V];
1628   if (!Shadow) {
1629     if (Argument *A = dyn_cast<Argument>(V)) {
1630       if (IsNativeABI)
1631         return DFS.getZeroShadow(V);
1632       Shadow = getShadowForTLSArgument(A);
1633       NonZeroChecks.push_back(Shadow);
1634     } else {
1635       Shadow = DFS.getZeroShadow(V);
1636     }
1637   }
1638   return Shadow;
1639 }
1640 
setShadow(Instruction * I,Value * Shadow)1641 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
1642   assert(!ValShadowMap.count(I));
1643   ValShadowMap[I] = Shadow;
1644 }
1645 
1646 /// Compute the integer shadow offset that corresponds to a given
1647 /// application address.
1648 ///
1649 /// Offset = (Addr & ~AndMask) ^ XorMask
getShadowOffset(Value * Addr,IRBuilder<> & IRB)1650 Value *DataFlowSanitizer::getShadowOffset(Value *Addr, IRBuilder<> &IRB) {
1651   assert(Addr != RetvalTLS && "Reinstrumenting?");
1652   Value *OffsetLong = IRB.CreatePointerCast(Addr, IntptrTy);
1653 
1654   uint64_t AndMask = MapParams->AndMask;
1655   if (AndMask)
1656     OffsetLong =
1657         IRB.CreateAnd(OffsetLong, ConstantInt::get(IntptrTy, ~AndMask));
1658 
1659   uint64_t XorMask = MapParams->XorMask;
1660   if (XorMask)
1661     OffsetLong = IRB.CreateXor(OffsetLong, ConstantInt::get(IntptrTy, XorMask));
1662   return OffsetLong;
1663 }
1664 
1665 std::pair<Value *, Value *>
getShadowOriginAddress(Value * Addr,Align InstAlignment,Instruction * Pos)1666 DataFlowSanitizer::getShadowOriginAddress(Value *Addr, Align InstAlignment,
1667                                           Instruction *Pos) {
1668   // Returns ((Addr & shadow_mask) + origin_base - shadow_base) & ~4UL
1669   IRBuilder<> IRB(Pos);
1670   Value *ShadowOffset = getShadowOffset(Addr, IRB);
1671   Value *ShadowLong = ShadowOffset;
1672   uint64_t ShadowBase = MapParams->ShadowBase;
1673   if (ShadowBase != 0) {
1674     ShadowLong =
1675         IRB.CreateAdd(ShadowLong, ConstantInt::get(IntptrTy, ShadowBase));
1676   }
1677   IntegerType *ShadowTy = IntegerType::get(*Ctx, ShadowWidthBits);
1678   Value *ShadowPtr =
1679       IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
1680   Value *OriginPtr = nullptr;
1681   if (shouldTrackOrigins()) {
1682     Value *OriginLong = ShadowOffset;
1683     uint64_t OriginBase = MapParams->OriginBase;
1684     if (OriginBase != 0)
1685       OriginLong =
1686           IRB.CreateAdd(OriginLong, ConstantInt::get(IntptrTy, OriginBase));
1687     const Align Alignment = llvm::assumeAligned(InstAlignment.value());
1688     // When alignment is >= 4, Addr must be aligned to 4, otherwise it is UB.
1689     // So Mask is unnecessary.
1690     if (Alignment < MinOriginAlignment) {
1691       uint64_t Mask = MinOriginAlignment.value() - 1;
1692       OriginLong = IRB.CreateAnd(OriginLong, ConstantInt::get(IntptrTy, ~Mask));
1693     }
1694     OriginPtr = IRB.CreateIntToPtr(OriginLong, OriginPtrTy);
1695   }
1696   return std::make_pair(ShadowPtr, OriginPtr);
1697 }
1698 
getShadowAddress(Value * Addr,Instruction * Pos,Value * ShadowOffset)1699 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos,
1700                                            Value *ShadowOffset) {
1701   IRBuilder<> IRB(Pos);
1702   return IRB.CreateIntToPtr(ShadowOffset, PrimitiveShadowPtrTy);
1703 }
1704 
getShadowAddress(Value * Addr,Instruction * Pos)1705 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
1706   IRBuilder<> IRB(Pos);
1707   Value *ShadowOffset = getShadowOffset(Addr, IRB);
1708   return getShadowAddress(Addr, Pos, ShadowOffset);
1709 }
1710 
combineShadowsThenConvert(Type * T,Value * V1,Value * V2,Instruction * Pos)1711 Value *DFSanFunction::combineShadowsThenConvert(Type *T, Value *V1, Value *V2,
1712                                                 Instruction *Pos) {
1713   Value *PrimitiveValue = combineShadows(V1, V2, Pos);
1714   return expandFromPrimitiveShadow(T, PrimitiveValue, Pos);
1715 }
1716 
1717 // Generates IR to compute the union of the two given shadows, inserting it
1718 // before Pos. The combined value is with primitive type.
combineShadows(Value * V1,Value * V2,Instruction * Pos)1719 Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
1720   if (DFS.isZeroShadow(V1))
1721     return collapseToPrimitiveShadow(V2, Pos);
1722   if (DFS.isZeroShadow(V2))
1723     return collapseToPrimitiveShadow(V1, Pos);
1724   if (V1 == V2)
1725     return collapseToPrimitiveShadow(V1, Pos);
1726 
1727   auto V1Elems = ShadowElements.find(V1);
1728   auto V2Elems = ShadowElements.find(V2);
1729   if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
1730     if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
1731                       V2Elems->second.begin(), V2Elems->second.end())) {
1732       return collapseToPrimitiveShadow(V1, Pos);
1733     }
1734     if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
1735                       V1Elems->second.begin(), V1Elems->second.end())) {
1736       return collapseToPrimitiveShadow(V2, Pos);
1737     }
1738   } else if (V1Elems != ShadowElements.end()) {
1739     if (V1Elems->second.count(V2))
1740       return collapseToPrimitiveShadow(V1, Pos);
1741   } else if (V2Elems != ShadowElements.end()) {
1742     if (V2Elems->second.count(V1))
1743       return collapseToPrimitiveShadow(V2, Pos);
1744   }
1745 
1746   auto Key = std::make_pair(V1, V2);
1747   if (V1 > V2)
1748     std::swap(Key.first, Key.second);
1749   CachedShadow &CCS = CachedShadows[Key];
1750   if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
1751     return CCS.Shadow;
1752 
1753   // Converts inputs shadows to shadows with primitive types.
1754   Value *PV1 = collapseToPrimitiveShadow(V1, Pos);
1755   Value *PV2 = collapseToPrimitiveShadow(V2, Pos);
1756 
1757   IRBuilder<> IRB(Pos);
1758   CCS.Block = Pos->getParent();
1759   CCS.Shadow = IRB.CreateOr(PV1, PV2);
1760 
1761   std::set<Value *> UnionElems;
1762   if (V1Elems != ShadowElements.end()) {
1763     UnionElems = V1Elems->second;
1764   } else {
1765     UnionElems.insert(V1);
1766   }
1767   if (V2Elems != ShadowElements.end()) {
1768     UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
1769   } else {
1770     UnionElems.insert(V2);
1771   }
1772   ShadowElements[CCS.Shadow] = std::move(UnionElems);
1773 
1774   return CCS.Shadow;
1775 }
1776 
1777 // A convenience function which folds the shadows of each of the operands
1778 // of the provided instruction Inst, inserting the IR before Inst.  Returns
1779 // the computed union Value.
combineOperandShadows(Instruction * Inst)1780 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
1781   if (Inst->getNumOperands() == 0)
1782     return DFS.getZeroShadow(Inst);
1783 
1784   Value *Shadow = getShadow(Inst->getOperand(0));
1785   for (unsigned I = 1, N = Inst->getNumOperands(); I < N; ++I)
1786     Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(I)), Inst);
1787 
1788   return expandFromPrimitiveShadow(Inst->getType(), Shadow, Inst);
1789 }
1790 
visitInstOperands(Instruction & I)1791 void DFSanVisitor::visitInstOperands(Instruction &I) {
1792   Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1793   DFSF.setShadow(&I, CombinedShadow);
1794   visitInstOperandOrigins(I);
1795 }
1796 
combineOrigins(const std::vector<Value * > & Shadows,const std::vector<Value * > & Origins,Instruction * Pos,ConstantInt * Zero)1797 Value *DFSanFunction::combineOrigins(const std::vector<Value *> &Shadows,
1798                                      const std::vector<Value *> &Origins,
1799                                      Instruction *Pos, ConstantInt *Zero) {
1800   assert(Shadows.size() == Origins.size());
1801   size_t Size = Origins.size();
1802   if (Size == 0)
1803     return DFS.ZeroOrigin;
1804   Value *Origin = nullptr;
1805   if (!Zero)
1806     Zero = DFS.ZeroPrimitiveShadow;
1807   for (size_t I = 0; I != Size; ++I) {
1808     Value *OpOrigin = Origins[I];
1809     Constant *ConstOpOrigin = dyn_cast<Constant>(OpOrigin);
1810     if (ConstOpOrigin && ConstOpOrigin->isNullValue())
1811       continue;
1812     if (!Origin) {
1813       Origin = OpOrigin;
1814       continue;
1815     }
1816     Value *OpShadow = Shadows[I];
1817     Value *PrimitiveShadow = collapseToPrimitiveShadow(OpShadow, Pos);
1818     IRBuilder<> IRB(Pos);
1819     Value *Cond = IRB.CreateICmpNE(PrimitiveShadow, Zero);
1820     Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1821   }
1822   return Origin ? Origin : DFS.ZeroOrigin;
1823 }
1824 
combineOperandOrigins(Instruction * Inst)1825 Value *DFSanFunction::combineOperandOrigins(Instruction *Inst) {
1826   size_t Size = Inst->getNumOperands();
1827   std::vector<Value *> Shadows(Size);
1828   std::vector<Value *> Origins(Size);
1829   for (unsigned I = 0; I != Size; ++I) {
1830     Shadows[I] = getShadow(Inst->getOperand(I));
1831     Origins[I] = getOrigin(Inst->getOperand(I));
1832   }
1833   return combineOrigins(Shadows, Origins, Inst);
1834 }
1835 
visitInstOperandOrigins(Instruction & I)1836 void DFSanVisitor::visitInstOperandOrigins(Instruction &I) {
1837   if (!DFSF.DFS.shouldTrackOrigins())
1838     return;
1839   Value *CombinedOrigin = DFSF.combineOperandOrigins(&I);
1840   DFSF.setOrigin(&I, CombinedOrigin);
1841 }
1842 
getShadowAlign(Align InstAlignment)1843 Align DFSanFunction::getShadowAlign(Align InstAlignment) {
1844   const Align Alignment = ClPreserveAlignment ? InstAlignment : Align(1);
1845   return Align(Alignment.value() * DFS.ShadowWidthBytes);
1846 }
1847 
getOriginAlign(Align InstAlignment)1848 Align DFSanFunction::getOriginAlign(Align InstAlignment) {
1849   const Align Alignment = llvm::assumeAligned(InstAlignment.value());
1850   return Align(std::max(MinOriginAlignment, Alignment));
1851 }
1852 
useCallbackLoadLabelAndOrigin(uint64_t Size,Align InstAlignment)1853 bool DFSanFunction::useCallbackLoadLabelAndOrigin(uint64_t Size,
1854                                                   Align InstAlignment) {
1855   // When enabling tracking load instructions, we always use
1856   // __dfsan_load_label_and_origin to reduce code size.
1857   if (ClTrackOrigins == 2)
1858     return true;
1859 
1860   assert(Size != 0);
1861   // * if Size == 1, it is sufficient to load its origin aligned at 4.
1862   // * if Size == 2, we assume most cases Addr % 2 == 0, so it is sufficient to
1863   //   load its origin aligned at 4. If not, although origins may be lost, it
1864   //   should not happen very often.
1865   // * if align >= 4, Addr must be aligned to 4, otherwise it is UB. When
1866   //   Size % 4 == 0, it is more efficient to load origins without callbacks.
1867   // * Otherwise we use __dfsan_load_label_and_origin.
1868   // This should ensure that common cases run efficiently.
1869   if (Size <= 2)
1870     return false;
1871 
1872   const Align Alignment = llvm::assumeAligned(InstAlignment.value());
1873   return Alignment < MinOriginAlignment || !DFS.hasLoadSizeForFastPath(Size);
1874 }
1875 
loadNextOrigin(Instruction * Pos,Align OriginAlign,Value ** OriginAddr)1876 Value *DataFlowSanitizer::loadNextOrigin(Instruction *Pos, Align OriginAlign,
1877                                          Value **OriginAddr) {
1878   IRBuilder<> IRB(Pos);
1879   *OriginAddr =
1880       IRB.CreateGEP(OriginTy, *OriginAddr, ConstantInt::get(IntptrTy, 1));
1881   return IRB.CreateAlignedLoad(OriginTy, *OriginAddr, OriginAlign);
1882 }
1883 
loadShadowFast(Value * ShadowAddr,Value * OriginAddr,uint64_t Size,Align ShadowAlign,Align OriginAlign,Value * FirstOrigin,Instruction * Pos)1884 std::pair<Value *, Value *> DFSanFunction::loadShadowFast(
1885     Value *ShadowAddr, Value *OriginAddr, uint64_t Size, Align ShadowAlign,
1886     Align OriginAlign, Value *FirstOrigin, Instruction *Pos) {
1887   const bool ShouldTrackOrigins = DFS.shouldTrackOrigins();
1888   const uint64_t ShadowSize = Size * DFS.ShadowWidthBytes;
1889 
1890   assert(Size >= 4 && "Not large enough load size for fast path!");
1891 
1892   // Used for origin tracking.
1893   std::vector<Value *> Shadows;
1894   std::vector<Value *> Origins;
1895 
1896   // Load instructions in LLVM can have arbitrary byte sizes (e.g., 3, 12, 20)
1897   // but this function is only used in a subset of cases that make it possible
1898   // to optimize the instrumentation.
1899   //
1900   // Specifically, when the shadow size in bytes (i.e., loaded bytes x shadow
1901   // per byte) is either:
1902   // - a multiple of 8  (common)
1903   // - equal to 4       (only for load32)
1904   //
1905   // For the second case, we can fit the wide shadow in a 32-bit integer. In all
1906   // other cases, we use a 64-bit integer to hold the wide shadow.
1907   Type *WideShadowTy =
1908       ShadowSize == 4 ? Type::getInt32Ty(*DFS.Ctx) : Type::getInt64Ty(*DFS.Ctx);
1909 
1910   IRBuilder<> IRB(Pos);
1911   Value *WideAddr = IRB.CreateBitCast(ShadowAddr, WideShadowTy->getPointerTo());
1912   Value *CombinedWideShadow =
1913       IRB.CreateAlignedLoad(WideShadowTy, WideAddr, ShadowAlign);
1914 
1915   unsigned WideShadowBitWidth = WideShadowTy->getIntegerBitWidth();
1916   const uint64_t BytesPerWideShadow = WideShadowBitWidth / DFS.ShadowWidthBits;
1917 
1918   auto AppendWideShadowAndOrigin = [&](Value *WideShadow, Value *Origin) {
1919     if (BytesPerWideShadow > 4) {
1920       assert(BytesPerWideShadow == 8);
1921       // The wide shadow relates to two origin pointers: one for the first four
1922       // application bytes, and one for the latest four. We use a left shift to
1923       // get just the shadow bytes that correspond to the first origin pointer,
1924       // and then the entire shadow for the second origin pointer (which will be
1925       // chosen by combineOrigins() iff the least-significant half of the wide
1926       // shadow was empty but the other half was not).
1927       Value *WideShadowLo = IRB.CreateShl(
1928           WideShadow, ConstantInt::get(WideShadowTy, WideShadowBitWidth / 2));
1929       Shadows.push_back(WideShadow);
1930       Origins.push_back(DFS.loadNextOrigin(Pos, OriginAlign, &OriginAddr));
1931 
1932       Shadows.push_back(WideShadowLo);
1933       Origins.push_back(Origin);
1934     } else {
1935       Shadows.push_back(WideShadow);
1936       Origins.push_back(Origin);
1937     }
1938   };
1939 
1940   if (ShouldTrackOrigins)
1941     AppendWideShadowAndOrigin(CombinedWideShadow, FirstOrigin);
1942 
1943   // First OR all the WideShadows (i.e., 64bit or 32bit shadow chunks) linearly;
1944   // then OR individual shadows within the combined WideShadow by binary ORing.
1945   // This is fewer instructions than ORing shadows individually, since it
1946   // needs logN shift/or instructions (N being the bytes of the combined wide
1947   // shadow).
1948   for (uint64_t ByteOfs = BytesPerWideShadow; ByteOfs < Size;
1949        ByteOfs += BytesPerWideShadow) {
1950     WideAddr = IRB.CreateGEP(WideShadowTy, WideAddr,
1951                              ConstantInt::get(DFS.IntptrTy, 1));
1952     Value *NextWideShadow =
1953         IRB.CreateAlignedLoad(WideShadowTy, WideAddr, ShadowAlign);
1954     CombinedWideShadow = IRB.CreateOr(CombinedWideShadow, NextWideShadow);
1955     if (ShouldTrackOrigins) {
1956       Value *NextOrigin = DFS.loadNextOrigin(Pos, OriginAlign, &OriginAddr);
1957       AppendWideShadowAndOrigin(NextWideShadow, NextOrigin);
1958     }
1959   }
1960   for (unsigned Width = WideShadowBitWidth / 2; Width >= DFS.ShadowWidthBits;
1961        Width >>= 1) {
1962     Value *ShrShadow = IRB.CreateLShr(CombinedWideShadow, Width);
1963     CombinedWideShadow = IRB.CreateOr(CombinedWideShadow, ShrShadow);
1964   }
1965   return {IRB.CreateTrunc(CombinedWideShadow, DFS.PrimitiveShadowTy),
1966           ShouldTrackOrigins
1967               ? combineOrigins(Shadows, Origins, Pos,
1968                                ConstantInt::getSigned(IRB.getInt64Ty(), 0))
1969               : DFS.ZeroOrigin};
1970 }
1971 
loadShadowOriginSansLoadTracking(Value * Addr,uint64_t Size,Align InstAlignment,Instruction * Pos)1972 std::pair<Value *, Value *> DFSanFunction::loadShadowOriginSansLoadTracking(
1973     Value *Addr, uint64_t Size, Align InstAlignment, Instruction *Pos) {
1974   const bool ShouldTrackOrigins = DFS.shouldTrackOrigins();
1975 
1976   // Non-escaped loads.
1977   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1978     const auto SI = AllocaShadowMap.find(AI);
1979     if (SI != AllocaShadowMap.end()) {
1980       IRBuilder<> IRB(Pos);
1981       Value *ShadowLI = IRB.CreateLoad(DFS.PrimitiveShadowTy, SI->second);
1982       const auto OI = AllocaOriginMap.find(AI);
1983       assert(!ShouldTrackOrigins || OI != AllocaOriginMap.end());
1984       return {ShadowLI, ShouldTrackOrigins
1985                             ? IRB.CreateLoad(DFS.OriginTy, OI->second)
1986                             : nullptr};
1987     }
1988   }
1989 
1990   // Load from constant addresses.
1991   SmallVector<const Value *, 2> Objs;
1992   getUnderlyingObjects(Addr, Objs);
1993   bool AllConstants = true;
1994   for (const Value *Obj : Objs) {
1995     if (isa<Function>(Obj) || isa<BlockAddress>(Obj))
1996       continue;
1997     if (isa<GlobalVariable>(Obj) && cast<GlobalVariable>(Obj)->isConstant())
1998       continue;
1999 
2000     AllConstants = false;
2001     break;
2002   }
2003   if (AllConstants)
2004     return {DFS.ZeroPrimitiveShadow,
2005             ShouldTrackOrigins ? DFS.ZeroOrigin : nullptr};
2006 
2007   if (Size == 0)
2008     return {DFS.ZeroPrimitiveShadow,
2009             ShouldTrackOrigins ? DFS.ZeroOrigin : nullptr};
2010 
2011   // Use callback to load if this is not an optimizable case for origin
2012   // tracking.
2013   if (ShouldTrackOrigins &&
2014       useCallbackLoadLabelAndOrigin(Size, InstAlignment)) {
2015     IRBuilder<> IRB(Pos);
2016     CallInst *Call =
2017         IRB.CreateCall(DFS.DFSanLoadLabelAndOriginFn,
2018                        {IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
2019                         ConstantInt::get(DFS.IntptrTy, Size)});
2020     Call->addRetAttr(Attribute::ZExt);
2021     return {IRB.CreateTrunc(IRB.CreateLShr(Call, DFS.OriginWidthBits),
2022                             DFS.PrimitiveShadowTy),
2023             IRB.CreateTrunc(Call, DFS.OriginTy)};
2024   }
2025 
2026   // Other cases that support loading shadows or origins in a fast way.
2027   Value *ShadowAddr, *OriginAddr;
2028   std::tie(ShadowAddr, OriginAddr) =
2029       DFS.getShadowOriginAddress(Addr, InstAlignment, Pos);
2030 
2031   const Align ShadowAlign = getShadowAlign(InstAlignment);
2032   const Align OriginAlign = getOriginAlign(InstAlignment);
2033   Value *Origin = nullptr;
2034   if (ShouldTrackOrigins) {
2035     IRBuilder<> IRB(Pos);
2036     Origin = IRB.CreateAlignedLoad(DFS.OriginTy, OriginAddr, OriginAlign);
2037   }
2038 
2039   // When the byte size is small enough, we can load the shadow directly with
2040   // just a few instructions.
2041   switch (Size) {
2042   case 1: {
2043     LoadInst *LI = new LoadInst(DFS.PrimitiveShadowTy, ShadowAddr, "", Pos);
2044     LI->setAlignment(ShadowAlign);
2045     return {LI, Origin};
2046   }
2047   case 2: {
2048     IRBuilder<> IRB(Pos);
2049     Value *ShadowAddr1 = IRB.CreateGEP(DFS.PrimitiveShadowTy, ShadowAddr,
2050                                        ConstantInt::get(DFS.IntptrTy, 1));
2051     Value *Load =
2052         IRB.CreateAlignedLoad(DFS.PrimitiveShadowTy, ShadowAddr, ShadowAlign);
2053     Value *Load1 =
2054         IRB.CreateAlignedLoad(DFS.PrimitiveShadowTy, ShadowAddr1, ShadowAlign);
2055     return {combineShadows(Load, Load1, Pos), Origin};
2056   }
2057   }
2058   bool HasSizeForFastPath = DFS.hasLoadSizeForFastPath(Size);
2059 
2060   if (HasSizeForFastPath)
2061     return loadShadowFast(ShadowAddr, OriginAddr, Size, ShadowAlign,
2062                           OriginAlign, Origin, Pos);
2063 
2064   IRBuilder<> IRB(Pos);
2065   CallInst *FallbackCall = IRB.CreateCall(
2066       DFS.DFSanUnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
2067   FallbackCall->addRetAttr(Attribute::ZExt);
2068   return {FallbackCall, Origin};
2069 }
2070 
loadShadowOrigin(Value * Addr,uint64_t Size,Align InstAlignment,Instruction * Pos)2071 std::pair<Value *, Value *> DFSanFunction::loadShadowOrigin(Value *Addr,
2072                                                             uint64_t Size,
2073                                                             Align InstAlignment,
2074                                                             Instruction *Pos) {
2075   Value *PrimitiveShadow, *Origin;
2076   std::tie(PrimitiveShadow, Origin) =
2077       loadShadowOriginSansLoadTracking(Addr, Size, InstAlignment, Pos);
2078   if (DFS.shouldTrackOrigins()) {
2079     if (ClTrackOrigins == 2) {
2080       IRBuilder<> IRB(Pos);
2081       auto *ConstantShadow = dyn_cast<Constant>(PrimitiveShadow);
2082       if (!ConstantShadow || !ConstantShadow->isZeroValue())
2083         Origin = updateOriginIfTainted(PrimitiveShadow, Origin, IRB);
2084     }
2085   }
2086   return {PrimitiveShadow, Origin};
2087 }
2088 
addAcquireOrdering(AtomicOrdering AO)2089 static AtomicOrdering addAcquireOrdering(AtomicOrdering AO) {
2090   switch (AO) {
2091   case AtomicOrdering::NotAtomic:
2092     return AtomicOrdering::NotAtomic;
2093   case AtomicOrdering::Unordered:
2094   case AtomicOrdering::Monotonic:
2095   case AtomicOrdering::Acquire:
2096     return AtomicOrdering::Acquire;
2097   case AtomicOrdering::Release:
2098   case AtomicOrdering::AcquireRelease:
2099     return AtomicOrdering::AcquireRelease;
2100   case AtomicOrdering::SequentiallyConsistent:
2101     return AtomicOrdering::SequentiallyConsistent;
2102   }
2103   llvm_unreachable("Unknown ordering");
2104 }
2105 
visitLoadInst(LoadInst & LI)2106 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
2107   auto &DL = LI.getModule()->getDataLayout();
2108   uint64_t Size = DL.getTypeStoreSize(LI.getType());
2109   if (Size == 0) {
2110     DFSF.setShadow(&LI, DFSF.DFS.getZeroShadow(&LI));
2111     DFSF.setOrigin(&LI, DFSF.DFS.ZeroOrigin);
2112     return;
2113   }
2114 
2115   // When an application load is atomic, increase atomic ordering between
2116   // atomic application loads and stores to ensure happen-before order; load
2117   // shadow data after application data; store zero shadow data before
2118   // application data. This ensure shadow loads return either labels of the
2119   // initial application data or zeros.
2120   if (LI.isAtomic())
2121     LI.setOrdering(addAcquireOrdering(LI.getOrdering()));
2122 
2123   Instruction *Pos = LI.isAtomic() ? LI.getNextNode() : &LI;
2124   std::vector<Value *> Shadows;
2125   std::vector<Value *> Origins;
2126   Value *PrimitiveShadow, *Origin;
2127   std::tie(PrimitiveShadow, Origin) =
2128       DFSF.loadShadowOrigin(LI.getPointerOperand(), Size, LI.getAlign(), Pos);
2129   const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins();
2130   if (ShouldTrackOrigins) {
2131     Shadows.push_back(PrimitiveShadow);
2132     Origins.push_back(Origin);
2133   }
2134   if (ClCombinePointerLabelsOnLoad) {
2135     Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
2136     PrimitiveShadow = DFSF.combineShadows(PrimitiveShadow, PtrShadow, Pos);
2137     if (ShouldTrackOrigins) {
2138       Shadows.push_back(PtrShadow);
2139       Origins.push_back(DFSF.getOrigin(LI.getPointerOperand()));
2140     }
2141   }
2142   if (!DFSF.DFS.isZeroShadow(PrimitiveShadow))
2143     DFSF.NonZeroChecks.push_back(PrimitiveShadow);
2144 
2145   Value *Shadow =
2146       DFSF.expandFromPrimitiveShadow(LI.getType(), PrimitiveShadow, Pos);
2147   DFSF.setShadow(&LI, Shadow);
2148 
2149   if (ShouldTrackOrigins) {
2150     DFSF.setOrigin(&LI, DFSF.combineOrigins(Shadows, Origins, Pos));
2151   }
2152 
2153   if (ClEventCallbacks) {
2154     IRBuilder<> IRB(Pos);
2155     Value *Addr8 = IRB.CreateBitCast(LI.getPointerOperand(), DFSF.DFS.Int8Ptr);
2156     IRB.CreateCall(DFSF.DFS.DFSanLoadCallbackFn, {PrimitiveShadow, Addr8});
2157   }
2158 }
2159 
updateOriginIfTainted(Value * Shadow,Value * Origin,IRBuilder<> & IRB)2160 Value *DFSanFunction::updateOriginIfTainted(Value *Shadow, Value *Origin,
2161                                             IRBuilder<> &IRB) {
2162   assert(DFS.shouldTrackOrigins());
2163   return IRB.CreateCall(DFS.DFSanChainOriginIfTaintedFn, {Shadow, Origin});
2164 }
2165 
updateOrigin(Value * V,IRBuilder<> & IRB)2166 Value *DFSanFunction::updateOrigin(Value *V, IRBuilder<> &IRB) {
2167   if (!DFS.shouldTrackOrigins())
2168     return V;
2169   return IRB.CreateCall(DFS.DFSanChainOriginFn, V);
2170 }
2171 
originToIntptr(IRBuilder<> & IRB,Value * Origin)2172 Value *DFSanFunction::originToIntptr(IRBuilder<> &IRB, Value *Origin) {
2173   const unsigned OriginSize = DataFlowSanitizer::OriginWidthBytes;
2174   const DataLayout &DL = F->getParent()->getDataLayout();
2175   unsigned IntptrSize = DL.getTypeStoreSize(DFS.IntptrTy);
2176   if (IntptrSize == OriginSize)
2177     return Origin;
2178   assert(IntptrSize == OriginSize * 2);
2179   Origin = IRB.CreateIntCast(Origin, DFS.IntptrTy, /* isSigned */ false);
2180   return IRB.CreateOr(Origin, IRB.CreateShl(Origin, OriginSize * 8));
2181 }
2182 
paintOrigin(IRBuilder<> & IRB,Value * Origin,Value * StoreOriginAddr,uint64_t StoreOriginSize,Align Alignment)2183 void DFSanFunction::paintOrigin(IRBuilder<> &IRB, Value *Origin,
2184                                 Value *StoreOriginAddr,
2185                                 uint64_t StoreOriginSize, Align Alignment) {
2186   const unsigned OriginSize = DataFlowSanitizer::OriginWidthBytes;
2187   const DataLayout &DL = F->getParent()->getDataLayout();
2188   const Align IntptrAlignment = DL.getABITypeAlign(DFS.IntptrTy);
2189   unsigned IntptrSize = DL.getTypeStoreSize(DFS.IntptrTy);
2190   assert(IntptrAlignment >= MinOriginAlignment);
2191   assert(IntptrSize >= OriginSize);
2192 
2193   unsigned Ofs = 0;
2194   Align CurrentAlignment = Alignment;
2195   if (Alignment >= IntptrAlignment && IntptrSize > OriginSize) {
2196     Value *IntptrOrigin = originToIntptr(IRB, Origin);
2197     Value *IntptrStoreOriginPtr = IRB.CreatePointerCast(
2198         StoreOriginAddr, PointerType::get(DFS.IntptrTy, 0));
2199     for (unsigned I = 0; I < StoreOriginSize / IntptrSize; ++I) {
2200       Value *Ptr =
2201           I ? IRB.CreateConstGEP1_32(DFS.IntptrTy, IntptrStoreOriginPtr, I)
2202             : IntptrStoreOriginPtr;
2203       IRB.CreateAlignedStore(IntptrOrigin, Ptr, CurrentAlignment);
2204       Ofs += IntptrSize / OriginSize;
2205       CurrentAlignment = IntptrAlignment;
2206     }
2207   }
2208 
2209   for (unsigned I = Ofs; I < (StoreOriginSize + OriginSize - 1) / OriginSize;
2210        ++I) {
2211     Value *GEP = I ? IRB.CreateConstGEP1_32(DFS.OriginTy, StoreOriginAddr, I)
2212                    : StoreOriginAddr;
2213     IRB.CreateAlignedStore(Origin, GEP, CurrentAlignment);
2214     CurrentAlignment = MinOriginAlignment;
2215   }
2216 }
2217 
convertToBool(Value * V,IRBuilder<> & IRB,const Twine & Name)2218 Value *DFSanFunction::convertToBool(Value *V, IRBuilder<> &IRB,
2219                                     const Twine &Name) {
2220   Type *VTy = V->getType();
2221   assert(VTy->isIntegerTy());
2222   if (VTy->getIntegerBitWidth() == 1)
2223     // Just converting a bool to a bool, so do nothing.
2224     return V;
2225   return IRB.CreateICmpNE(V, ConstantInt::get(VTy, 0), Name);
2226 }
2227 
storeOrigin(Instruction * Pos,Value * Addr,uint64_t Size,Value * Shadow,Value * Origin,Value * StoreOriginAddr,Align InstAlignment)2228 void DFSanFunction::storeOrigin(Instruction *Pos, Value *Addr, uint64_t Size,
2229                                 Value *Shadow, Value *Origin,
2230                                 Value *StoreOriginAddr, Align InstAlignment) {
2231   // Do not write origins for zero shadows because we do not trace origins for
2232   // untainted sinks.
2233   const Align OriginAlignment = getOriginAlign(InstAlignment);
2234   Value *CollapsedShadow = collapseToPrimitiveShadow(Shadow, Pos);
2235   IRBuilder<> IRB(Pos);
2236   if (auto *ConstantShadow = dyn_cast<Constant>(CollapsedShadow)) {
2237     if (!ConstantShadow->isZeroValue())
2238       paintOrigin(IRB, updateOrigin(Origin, IRB), StoreOriginAddr, Size,
2239                   OriginAlignment);
2240     return;
2241   }
2242 
2243   if (shouldInstrumentWithCall()) {
2244     IRB.CreateCall(DFS.DFSanMaybeStoreOriginFn,
2245                    {CollapsedShadow,
2246                     IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
2247                     ConstantInt::get(DFS.IntptrTy, Size), Origin});
2248   } else {
2249     Value *Cmp = convertToBool(CollapsedShadow, IRB, "_dfscmp");
2250     Instruction *CheckTerm = SplitBlockAndInsertIfThen(
2251         Cmp, &*IRB.GetInsertPoint(), false, DFS.OriginStoreWeights, &DT);
2252     IRBuilder<> IRBNew(CheckTerm);
2253     paintOrigin(IRBNew, updateOrigin(Origin, IRBNew), StoreOriginAddr, Size,
2254                 OriginAlignment);
2255     ++NumOriginStores;
2256   }
2257 }
2258 
storeZeroPrimitiveShadow(Value * Addr,uint64_t Size,Align ShadowAlign,Instruction * Pos)2259 void DFSanFunction::storeZeroPrimitiveShadow(Value *Addr, uint64_t Size,
2260                                              Align ShadowAlign,
2261                                              Instruction *Pos) {
2262   IRBuilder<> IRB(Pos);
2263   IntegerType *ShadowTy =
2264       IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidthBits);
2265   Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
2266   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
2267   Value *ExtShadowAddr =
2268       IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
2269   IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
2270   // Do not write origins for 0 shadows because we do not trace origins for
2271   // untainted sinks.
2272 }
2273 
storePrimitiveShadowOrigin(Value * Addr,uint64_t Size,Align InstAlignment,Value * PrimitiveShadow,Value * Origin,Instruction * Pos)2274 void DFSanFunction::storePrimitiveShadowOrigin(Value *Addr, uint64_t Size,
2275                                                Align InstAlignment,
2276                                                Value *PrimitiveShadow,
2277                                                Value *Origin,
2278                                                Instruction *Pos) {
2279   const bool ShouldTrackOrigins = DFS.shouldTrackOrigins() && Origin;
2280 
2281   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
2282     const auto SI = AllocaShadowMap.find(AI);
2283     if (SI != AllocaShadowMap.end()) {
2284       IRBuilder<> IRB(Pos);
2285       IRB.CreateStore(PrimitiveShadow, SI->second);
2286 
2287       // Do not write origins for 0 shadows because we do not trace origins for
2288       // untainted sinks.
2289       if (ShouldTrackOrigins && !DFS.isZeroShadow(PrimitiveShadow)) {
2290         const auto OI = AllocaOriginMap.find(AI);
2291         assert(OI != AllocaOriginMap.end() && Origin);
2292         IRB.CreateStore(Origin, OI->second);
2293       }
2294       return;
2295     }
2296   }
2297 
2298   const Align ShadowAlign = getShadowAlign(InstAlignment);
2299   if (DFS.isZeroShadow(PrimitiveShadow)) {
2300     storeZeroPrimitiveShadow(Addr, Size, ShadowAlign, Pos);
2301     return;
2302   }
2303 
2304   IRBuilder<> IRB(Pos);
2305   Value *ShadowAddr, *OriginAddr;
2306   std::tie(ShadowAddr, OriginAddr) =
2307       DFS.getShadowOriginAddress(Addr, InstAlignment, Pos);
2308 
2309   const unsigned ShadowVecSize = 8;
2310   assert(ShadowVecSize * DFS.ShadowWidthBits <= 128 &&
2311          "Shadow vector is too large!");
2312 
2313   uint64_t Offset = 0;
2314   uint64_t LeftSize = Size;
2315   if (LeftSize >= ShadowVecSize) {
2316     auto *ShadowVecTy =
2317         FixedVectorType::get(DFS.PrimitiveShadowTy, ShadowVecSize);
2318     Value *ShadowVec = UndefValue::get(ShadowVecTy);
2319     for (unsigned I = 0; I != ShadowVecSize; ++I) {
2320       ShadowVec = IRB.CreateInsertElement(
2321           ShadowVec, PrimitiveShadow,
2322           ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), I));
2323     }
2324     Value *ShadowVecAddr =
2325         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
2326     do {
2327       Value *CurShadowVecAddr =
2328           IRB.CreateConstGEP1_32(ShadowVecTy, ShadowVecAddr, Offset);
2329       IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
2330       LeftSize -= ShadowVecSize;
2331       ++Offset;
2332     } while (LeftSize >= ShadowVecSize);
2333     Offset *= ShadowVecSize;
2334   }
2335   while (LeftSize > 0) {
2336     Value *CurShadowAddr =
2337         IRB.CreateConstGEP1_32(DFS.PrimitiveShadowTy, ShadowAddr, Offset);
2338     IRB.CreateAlignedStore(PrimitiveShadow, CurShadowAddr, ShadowAlign);
2339     --LeftSize;
2340     ++Offset;
2341   }
2342 
2343   if (ShouldTrackOrigins) {
2344     storeOrigin(Pos, Addr, Size, PrimitiveShadow, Origin, OriginAddr,
2345                 InstAlignment);
2346   }
2347 }
2348 
addReleaseOrdering(AtomicOrdering AO)2349 static AtomicOrdering addReleaseOrdering(AtomicOrdering AO) {
2350   switch (AO) {
2351   case AtomicOrdering::NotAtomic:
2352     return AtomicOrdering::NotAtomic;
2353   case AtomicOrdering::Unordered:
2354   case AtomicOrdering::Monotonic:
2355   case AtomicOrdering::Release:
2356     return AtomicOrdering::Release;
2357   case AtomicOrdering::Acquire:
2358   case AtomicOrdering::AcquireRelease:
2359     return AtomicOrdering::AcquireRelease;
2360   case AtomicOrdering::SequentiallyConsistent:
2361     return AtomicOrdering::SequentiallyConsistent;
2362   }
2363   llvm_unreachable("Unknown ordering");
2364 }
2365 
visitStoreInst(StoreInst & SI)2366 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
2367   auto &DL = SI.getModule()->getDataLayout();
2368   Value *Val = SI.getValueOperand();
2369   uint64_t Size = DL.getTypeStoreSize(Val->getType());
2370   if (Size == 0)
2371     return;
2372 
2373   // When an application store is atomic, increase atomic ordering between
2374   // atomic application loads and stores to ensure happen-before order; load
2375   // shadow data after application data; store zero shadow data before
2376   // application data. This ensure shadow loads return either labels of the
2377   // initial application data or zeros.
2378   if (SI.isAtomic())
2379     SI.setOrdering(addReleaseOrdering(SI.getOrdering()));
2380 
2381   const bool ShouldTrackOrigins =
2382       DFSF.DFS.shouldTrackOrigins() && !SI.isAtomic();
2383   std::vector<Value *> Shadows;
2384   std::vector<Value *> Origins;
2385 
2386   Value *Shadow =
2387       SI.isAtomic() ? DFSF.DFS.getZeroShadow(Val) : DFSF.getShadow(Val);
2388 
2389   if (ShouldTrackOrigins) {
2390     Shadows.push_back(Shadow);
2391     Origins.push_back(DFSF.getOrigin(Val));
2392   }
2393 
2394   Value *PrimitiveShadow;
2395   if (ClCombinePointerLabelsOnStore) {
2396     Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
2397     if (ShouldTrackOrigins) {
2398       Shadows.push_back(PtrShadow);
2399       Origins.push_back(DFSF.getOrigin(SI.getPointerOperand()));
2400     }
2401     PrimitiveShadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
2402   } else {
2403     PrimitiveShadow = DFSF.collapseToPrimitiveShadow(Shadow, &SI);
2404   }
2405   Value *Origin = nullptr;
2406   if (ShouldTrackOrigins)
2407     Origin = DFSF.combineOrigins(Shadows, Origins, &SI);
2408   DFSF.storePrimitiveShadowOrigin(SI.getPointerOperand(), Size, SI.getAlign(),
2409                                   PrimitiveShadow, Origin, &SI);
2410   if (ClEventCallbacks) {
2411     IRBuilder<> IRB(&SI);
2412     Value *Addr8 = IRB.CreateBitCast(SI.getPointerOperand(), DFSF.DFS.Int8Ptr);
2413     IRB.CreateCall(DFSF.DFS.DFSanStoreCallbackFn, {PrimitiveShadow, Addr8});
2414   }
2415 }
2416 
visitCASOrRMW(Align InstAlignment,Instruction & I)2417 void DFSanVisitor::visitCASOrRMW(Align InstAlignment, Instruction &I) {
2418   assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
2419 
2420   Value *Val = I.getOperand(1);
2421   const auto &DL = I.getModule()->getDataLayout();
2422   uint64_t Size = DL.getTypeStoreSize(Val->getType());
2423   if (Size == 0)
2424     return;
2425 
2426   // Conservatively set data at stored addresses and return with zero shadow to
2427   // prevent shadow data races.
2428   IRBuilder<> IRB(&I);
2429   Value *Addr = I.getOperand(0);
2430   const Align ShadowAlign = DFSF.getShadowAlign(InstAlignment);
2431   DFSF.storeZeroPrimitiveShadow(Addr, Size, ShadowAlign, &I);
2432   DFSF.setShadow(&I, DFSF.DFS.getZeroShadow(&I));
2433   DFSF.setOrigin(&I, DFSF.DFS.ZeroOrigin);
2434 }
2435 
visitAtomicRMWInst(AtomicRMWInst & I)2436 void DFSanVisitor::visitAtomicRMWInst(AtomicRMWInst &I) {
2437   visitCASOrRMW(I.getAlign(), I);
2438   // TODO: The ordering change follows MSan. It is possible not to change
2439   // ordering because we always set and use 0 shadows.
2440   I.setOrdering(addReleaseOrdering(I.getOrdering()));
2441 }
2442 
visitAtomicCmpXchgInst(AtomicCmpXchgInst & I)2443 void DFSanVisitor::visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
2444   visitCASOrRMW(I.getAlign(), I);
2445   // TODO: The ordering change follows MSan. It is possible not to change
2446   // ordering because we always set and use 0 shadows.
2447   I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
2448 }
2449 
visitUnaryOperator(UnaryOperator & UO)2450 void DFSanVisitor::visitUnaryOperator(UnaryOperator &UO) {
2451   visitInstOperands(UO);
2452 }
2453 
visitBinaryOperator(BinaryOperator & BO)2454 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
2455   visitInstOperands(BO);
2456 }
2457 
visitBitCastInst(BitCastInst & BCI)2458 void DFSanVisitor::visitBitCastInst(BitCastInst &BCI) {
2459   // Special case: if this is the bitcast (there is exactly 1 allowed) between
2460   // a musttail call and a ret, don't instrument. New instructions are not
2461   // allowed after a musttail call.
2462   if (auto *CI = dyn_cast<CallInst>(BCI.getOperand(0)))
2463     if (CI->isMustTailCall())
2464       return;
2465   visitInstOperands(BCI);
2466 }
2467 
visitCastInst(CastInst & CI)2468 void DFSanVisitor::visitCastInst(CastInst &CI) { visitInstOperands(CI); }
2469 
visitCmpInst(CmpInst & CI)2470 void DFSanVisitor::visitCmpInst(CmpInst &CI) {
2471   visitInstOperands(CI);
2472   if (ClEventCallbacks) {
2473     IRBuilder<> IRB(&CI);
2474     Value *CombinedShadow = DFSF.getShadow(&CI);
2475     IRB.CreateCall(DFSF.DFS.DFSanCmpCallbackFn, CombinedShadow);
2476   }
2477 }
2478 
visitLandingPadInst(LandingPadInst & LPI)2479 void DFSanVisitor::visitLandingPadInst(LandingPadInst &LPI) {
2480   // We do not need to track data through LandingPadInst.
2481   //
2482   // For the C++ exceptions, if a value is thrown, this value will be stored
2483   // in a memory location provided by __cxa_allocate_exception(...) (on the
2484   // throw side) or  __cxa_begin_catch(...) (on the catch side).
2485   // This memory will have a shadow, so with the loads and stores we will be
2486   // able to propagate labels on data thrown through exceptions, without any
2487   // special handling of the LandingPadInst.
2488   //
2489   // The second element in the pair result of the LandingPadInst is a
2490   // register value, but it is for a type ID and should never be tainted.
2491   DFSF.setShadow(&LPI, DFSF.DFS.getZeroShadow(&LPI));
2492   DFSF.setOrigin(&LPI, DFSF.DFS.ZeroOrigin);
2493 }
2494 
visitGetElementPtrInst(GetElementPtrInst & GEPI)2495 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2496   if (ClCombineOffsetLabelsOnGEP) {
2497     visitInstOperands(GEPI);
2498     return;
2499   }
2500 
2501   // Only propagate shadow/origin of base pointer value but ignore those of
2502   // offset operands.
2503   Value *BasePointer = GEPI.getPointerOperand();
2504   DFSF.setShadow(&GEPI, DFSF.getShadow(BasePointer));
2505   if (DFSF.DFS.shouldTrackOrigins())
2506     DFSF.setOrigin(&GEPI, DFSF.getOrigin(BasePointer));
2507 }
2508 
visitExtractElementInst(ExtractElementInst & I)2509 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
2510   visitInstOperands(I);
2511 }
2512 
visitInsertElementInst(InsertElementInst & I)2513 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
2514   visitInstOperands(I);
2515 }
2516 
visitShuffleVectorInst(ShuffleVectorInst & I)2517 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
2518   visitInstOperands(I);
2519 }
2520 
visitExtractValueInst(ExtractValueInst & I)2521 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
2522   IRBuilder<> IRB(&I);
2523   Value *Agg = I.getAggregateOperand();
2524   Value *AggShadow = DFSF.getShadow(Agg);
2525   Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2526   DFSF.setShadow(&I, ResShadow);
2527   visitInstOperandOrigins(I);
2528 }
2529 
visitInsertValueInst(InsertValueInst & I)2530 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
2531   IRBuilder<> IRB(&I);
2532   Value *AggShadow = DFSF.getShadow(I.getAggregateOperand());
2533   Value *InsShadow = DFSF.getShadow(I.getInsertedValueOperand());
2534   Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2535   DFSF.setShadow(&I, Res);
2536   visitInstOperandOrigins(I);
2537 }
2538 
visitAllocaInst(AllocaInst & I)2539 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
2540   bool AllLoadsStores = true;
2541   for (User *U : I.users()) {
2542     if (isa<LoadInst>(U))
2543       continue;
2544 
2545     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
2546       if (SI->getPointerOperand() == &I)
2547         continue;
2548     }
2549 
2550     AllLoadsStores = false;
2551     break;
2552   }
2553   if (AllLoadsStores) {
2554     IRBuilder<> IRB(&I);
2555     DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.PrimitiveShadowTy);
2556     if (DFSF.DFS.shouldTrackOrigins()) {
2557       DFSF.AllocaOriginMap[&I] =
2558           IRB.CreateAlloca(DFSF.DFS.OriginTy, nullptr, "_dfsa");
2559     }
2560   }
2561   DFSF.setShadow(&I, DFSF.DFS.ZeroPrimitiveShadow);
2562   DFSF.setOrigin(&I, DFSF.DFS.ZeroOrigin);
2563 }
2564 
visitSelectInst(SelectInst & I)2565 void DFSanVisitor::visitSelectInst(SelectInst &I) {
2566   Value *CondShadow = DFSF.getShadow(I.getCondition());
2567   Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
2568   Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
2569   Value *ShadowSel = nullptr;
2570   const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins();
2571   std::vector<Value *> Shadows;
2572   std::vector<Value *> Origins;
2573   Value *TrueOrigin =
2574       ShouldTrackOrigins ? DFSF.getOrigin(I.getTrueValue()) : nullptr;
2575   Value *FalseOrigin =
2576       ShouldTrackOrigins ? DFSF.getOrigin(I.getFalseValue()) : nullptr;
2577 
2578   if (isa<VectorType>(I.getCondition()->getType())) {
2579     ShadowSel = DFSF.combineShadowsThenConvert(I.getType(), TrueShadow,
2580                                                FalseShadow, &I);
2581     if (ShouldTrackOrigins) {
2582       Shadows.push_back(TrueShadow);
2583       Shadows.push_back(FalseShadow);
2584       Origins.push_back(TrueOrigin);
2585       Origins.push_back(FalseOrigin);
2586     }
2587   } else {
2588     if (TrueShadow == FalseShadow) {
2589       ShadowSel = TrueShadow;
2590       if (ShouldTrackOrigins) {
2591         Shadows.push_back(TrueShadow);
2592         Origins.push_back(TrueOrigin);
2593       }
2594     } else {
2595       ShadowSel =
2596           SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
2597       if (ShouldTrackOrigins) {
2598         Shadows.push_back(ShadowSel);
2599         Origins.push_back(SelectInst::Create(I.getCondition(), TrueOrigin,
2600                                              FalseOrigin, "", &I));
2601       }
2602     }
2603   }
2604   DFSF.setShadow(&I, ClTrackSelectControlFlow
2605                          ? DFSF.combineShadowsThenConvert(
2606                                I.getType(), CondShadow, ShadowSel, &I)
2607                          : ShadowSel);
2608   if (ShouldTrackOrigins) {
2609     if (ClTrackSelectControlFlow) {
2610       Shadows.push_back(CondShadow);
2611       Origins.push_back(DFSF.getOrigin(I.getCondition()));
2612     }
2613     DFSF.setOrigin(&I, DFSF.combineOrigins(Shadows, Origins, &I));
2614   }
2615 }
2616 
visitMemSetInst(MemSetInst & I)2617 void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
2618   IRBuilder<> IRB(&I);
2619   Value *ValShadow = DFSF.getShadow(I.getValue());
2620   Value *ValOrigin = DFSF.DFS.shouldTrackOrigins()
2621                          ? DFSF.getOrigin(I.getValue())
2622                          : DFSF.DFS.ZeroOrigin;
2623   IRB.CreateCall(
2624       DFSF.DFS.DFSanSetLabelFn,
2625       {ValShadow, ValOrigin,
2626        IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
2627        IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
2628 }
2629 
visitMemTransferInst(MemTransferInst & I)2630 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
2631   IRBuilder<> IRB(&I);
2632 
2633   // CopyOrMoveOrigin transfers origins by refering to their shadows. So we
2634   // need to move origins before moving shadows.
2635   if (DFSF.DFS.shouldTrackOrigins()) {
2636     IRB.CreateCall(
2637         DFSF.DFS.DFSanMemOriginTransferFn,
2638         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
2639          IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
2640          IRB.CreateIntCast(I.getArgOperand(2), DFSF.DFS.IntptrTy, false)});
2641   }
2642 
2643   Value *RawDestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
2644   Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
2645   Value *LenShadow =
2646       IRB.CreateMul(I.getLength(), ConstantInt::get(I.getLength()->getType(),
2647                                                     DFSF.DFS.ShadowWidthBytes));
2648   Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
2649   Value *DestShadow = IRB.CreateBitCast(RawDestShadow, Int8Ptr);
2650   SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
2651   auto *MTI = cast<MemTransferInst>(
2652       IRB.CreateCall(I.getFunctionType(), I.getCalledOperand(),
2653                      {DestShadow, SrcShadow, LenShadow, I.getVolatileCst()}));
2654   if (ClPreserveAlignment) {
2655     MTI->setDestAlignment(I.getDestAlign() * DFSF.DFS.ShadowWidthBytes);
2656     MTI->setSourceAlignment(I.getSourceAlign() * DFSF.DFS.ShadowWidthBytes);
2657   } else {
2658     MTI->setDestAlignment(Align(DFSF.DFS.ShadowWidthBytes));
2659     MTI->setSourceAlignment(Align(DFSF.DFS.ShadowWidthBytes));
2660   }
2661   if (ClEventCallbacks) {
2662     IRB.CreateCall(DFSF.DFS.DFSanMemTransferCallbackFn,
2663                    {RawDestShadow,
2664                     IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
2665   }
2666 }
2667 
isAMustTailRetVal(Value * RetVal)2668 static bool isAMustTailRetVal(Value *RetVal) {
2669   // Tail call may have a bitcast between return.
2670   if (auto *I = dyn_cast<BitCastInst>(RetVal)) {
2671     RetVal = I->getOperand(0);
2672   }
2673   if (auto *I = dyn_cast<CallInst>(RetVal)) {
2674     return I->isMustTailCall();
2675   }
2676   return false;
2677 }
2678 
visitReturnInst(ReturnInst & RI)2679 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
2680   if (!DFSF.IsNativeABI && RI.getReturnValue()) {
2681     // Don't emit the instrumentation for musttail call returns.
2682     if (isAMustTailRetVal(RI.getReturnValue()))
2683       return;
2684 
2685     Value *S = DFSF.getShadow(RI.getReturnValue());
2686     IRBuilder<> IRB(&RI);
2687     Type *RT = DFSF.F->getFunctionType()->getReturnType();
2688     unsigned Size = getDataLayout().getTypeAllocSize(DFSF.DFS.getShadowTy(RT));
2689     if (Size <= RetvalTLSSize) {
2690       // If the size overflows, stores nothing. At callsite, oversized return
2691       // shadows are set to zero.
2692       IRB.CreateAlignedStore(S, DFSF.getRetvalTLS(RT, IRB), ShadowTLSAlignment);
2693     }
2694     if (DFSF.DFS.shouldTrackOrigins()) {
2695       Value *O = DFSF.getOrigin(RI.getReturnValue());
2696       IRB.CreateStore(O, DFSF.getRetvalOriginTLS());
2697     }
2698   }
2699 }
2700 
addShadowArguments(Function & F,CallBase & CB,std::vector<Value * > & Args,IRBuilder<> & IRB)2701 void DFSanVisitor::addShadowArguments(Function &F, CallBase &CB,
2702                                       std::vector<Value *> &Args,
2703                                       IRBuilder<> &IRB) {
2704   FunctionType *FT = F.getFunctionType();
2705 
2706   auto *I = CB.arg_begin();
2707 
2708   // Adds non-variable argument shadows.
2709   for (unsigned N = FT->getNumParams(); N != 0; ++I, --N)
2710     Args.push_back(DFSF.collapseToPrimitiveShadow(DFSF.getShadow(*I), &CB));
2711 
2712   // Adds variable argument shadows.
2713   if (FT->isVarArg()) {
2714     auto *LabelVATy = ArrayType::get(DFSF.DFS.PrimitiveShadowTy,
2715                                      CB.arg_size() - FT->getNumParams());
2716     auto *LabelVAAlloca =
2717         new AllocaInst(LabelVATy, getDataLayout().getAllocaAddrSpace(),
2718                        "labelva", &DFSF.F->getEntryBlock().front());
2719 
2720     for (unsigned N = 0; I != CB.arg_end(); ++I, ++N) {
2721       auto *LabelVAPtr = IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, N);
2722       IRB.CreateStore(DFSF.collapseToPrimitiveShadow(DFSF.getShadow(*I), &CB),
2723                       LabelVAPtr);
2724     }
2725 
2726     Args.push_back(IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, 0));
2727   }
2728 
2729   // Adds the return value shadow.
2730   if (!FT->getReturnType()->isVoidTy()) {
2731     if (!DFSF.LabelReturnAlloca) {
2732       DFSF.LabelReturnAlloca = new AllocaInst(
2733           DFSF.DFS.PrimitiveShadowTy, getDataLayout().getAllocaAddrSpace(),
2734           "labelreturn", &DFSF.F->getEntryBlock().front());
2735     }
2736     Args.push_back(DFSF.LabelReturnAlloca);
2737   }
2738 }
2739 
addOriginArguments(Function & F,CallBase & CB,std::vector<Value * > & Args,IRBuilder<> & IRB)2740 void DFSanVisitor::addOriginArguments(Function &F, CallBase &CB,
2741                                       std::vector<Value *> &Args,
2742                                       IRBuilder<> &IRB) {
2743   FunctionType *FT = F.getFunctionType();
2744 
2745   auto *I = CB.arg_begin();
2746 
2747   // Add non-variable argument origins.
2748   for (unsigned N = FT->getNumParams(); N != 0; ++I, --N)
2749     Args.push_back(DFSF.getOrigin(*I));
2750 
2751   // Add variable argument origins.
2752   if (FT->isVarArg()) {
2753     auto *OriginVATy =
2754         ArrayType::get(DFSF.DFS.OriginTy, CB.arg_size() - FT->getNumParams());
2755     auto *OriginVAAlloca =
2756         new AllocaInst(OriginVATy, getDataLayout().getAllocaAddrSpace(),
2757                        "originva", &DFSF.F->getEntryBlock().front());
2758 
2759     for (unsigned N = 0; I != CB.arg_end(); ++I, ++N) {
2760       auto *OriginVAPtr = IRB.CreateStructGEP(OriginVATy, OriginVAAlloca, N);
2761       IRB.CreateStore(DFSF.getOrigin(*I), OriginVAPtr);
2762     }
2763 
2764     Args.push_back(IRB.CreateStructGEP(OriginVATy, OriginVAAlloca, 0));
2765   }
2766 
2767   // Add the return value origin.
2768   if (!FT->getReturnType()->isVoidTy()) {
2769     if (!DFSF.OriginReturnAlloca) {
2770       DFSF.OriginReturnAlloca = new AllocaInst(
2771           DFSF.DFS.OriginTy, getDataLayout().getAllocaAddrSpace(),
2772           "originreturn", &DFSF.F->getEntryBlock().front());
2773     }
2774     Args.push_back(DFSF.OriginReturnAlloca);
2775   }
2776 }
2777 
visitWrappedCallBase(Function & F,CallBase & CB)2778 bool DFSanVisitor::visitWrappedCallBase(Function &F, CallBase &CB) {
2779   IRBuilder<> IRB(&CB);
2780   switch (DFSF.DFS.getWrapperKind(&F)) {
2781   case DataFlowSanitizer::WK_Warning:
2782     CB.setCalledFunction(&F);
2783     IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
2784                    IRB.CreateGlobalStringPtr(F.getName()));
2785     DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
2786     DFSF.setOrigin(&CB, DFSF.DFS.ZeroOrigin);
2787     return true;
2788   case DataFlowSanitizer::WK_Discard:
2789     CB.setCalledFunction(&F);
2790     DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
2791     DFSF.setOrigin(&CB, DFSF.DFS.ZeroOrigin);
2792     return true;
2793   case DataFlowSanitizer::WK_Functional:
2794     CB.setCalledFunction(&F);
2795     visitInstOperands(CB);
2796     return true;
2797   case DataFlowSanitizer::WK_Custom:
2798     // Don't try to handle invokes of custom functions, it's too complicated.
2799     // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
2800     // wrapper.
2801     CallInst *CI = dyn_cast<CallInst>(&CB);
2802     if (!CI)
2803       return false;
2804 
2805     const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins();
2806     FunctionType *FT = F.getFunctionType();
2807     TransformedFunction CustomFn = DFSF.DFS.getCustomFunctionType(FT);
2808     std::string CustomFName = ShouldTrackOrigins ? "__dfso_" : "__dfsw_";
2809     CustomFName += F.getName();
2810     FunctionCallee CustomF = DFSF.DFS.Mod->getOrInsertFunction(
2811         CustomFName, CustomFn.TransformedType);
2812     if (Function *CustomFn = dyn_cast<Function>(CustomF.getCallee())) {
2813       CustomFn->copyAttributesFrom(&F);
2814 
2815       // Custom functions returning non-void will write to the return label.
2816       if (!FT->getReturnType()->isVoidTy()) {
2817         CustomFn->removeFnAttrs(DFSF.DFS.ReadOnlyNoneAttrs);
2818       }
2819     }
2820 
2821     std::vector<Value *> Args;
2822 
2823     // Adds non-variable arguments.
2824     auto *I = CB.arg_begin();
2825     for (unsigned N = FT->getNumParams(); N != 0; ++I, --N) {
2826       Type *T = (*I)->getType();
2827       FunctionType *ParamFT;
2828       if (isa<PointerType>(T) &&
2829           (ParamFT = dyn_cast<FunctionType>(T->getPointerElementType()))) {
2830         std::string TName = "dfst";
2831         TName += utostr(FT->getNumParams() - N);
2832         TName += "$";
2833         TName += F.getName();
2834         Constant *Trampoline =
2835             DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
2836         Args.push_back(Trampoline);
2837         Args.push_back(
2838             IRB.CreateBitCast(*I, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
2839       } else {
2840         Args.push_back(*I);
2841       }
2842     }
2843 
2844     // Adds shadow arguments.
2845     const unsigned ShadowArgStart = Args.size();
2846     addShadowArguments(F, CB, Args, IRB);
2847 
2848     // Adds origin arguments.
2849     const unsigned OriginArgStart = Args.size();
2850     if (ShouldTrackOrigins)
2851       addOriginArguments(F, CB, Args, IRB);
2852 
2853     // Adds variable arguments.
2854     append_range(Args, drop_begin(CB.args(), FT->getNumParams()));
2855 
2856     CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
2857     CustomCI->setCallingConv(CI->getCallingConv());
2858     CustomCI->setAttributes(transformFunctionAttributes(
2859         CustomFn, CI->getContext(), CI->getAttributes()));
2860 
2861     // Update the parameter attributes of the custom call instruction to
2862     // zero extend the shadow parameters. This is required for targets
2863     // which consider PrimitiveShadowTy an illegal type.
2864     for (unsigned N = 0; N < FT->getNumParams(); N++) {
2865       const unsigned ArgNo = ShadowArgStart + N;
2866       if (CustomCI->getArgOperand(ArgNo)->getType() ==
2867           DFSF.DFS.PrimitiveShadowTy)
2868         CustomCI->addParamAttr(ArgNo, Attribute::ZExt);
2869       if (ShouldTrackOrigins) {
2870         const unsigned OriginArgNo = OriginArgStart + N;
2871         if (CustomCI->getArgOperand(OriginArgNo)->getType() ==
2872             DFSF.DFS.OriginTy)
2873           CustomCI->addParamAttr(OriginArgNo, Attribute::ZExt);
2874       }
2875     }
2876 
2877     // Loads the return value shadow and origin.
2878     if (!FT->getReturnType()->isVoidTy()) {
2879       LoadInst *LabelLoad =
2880           IRB.CreateLoad(DFSF.DFS.PrimitiveShadowTy, DFSF.LabelReturnAlloca);
2881       DFSF.setShadow(CustomCI, DFSF.expandFromPrimitiveShadow(
2882                                    FT->getReturnType(), LabelLoad, &CB));
2883       if (ShouldTrackOrigins) {
2884         LoadInst *OriginLoad =
2885             IRB.CreateLoad(DFSF.DFS.OriginTy, DFSF.OriginReturnAlloca);
2886         DFSF.setOrigin(CustomCI, OriginLoad);
2887       }
2888     }
2889 
2890     CI->replaceAllUsesWith(CustomCI);
2891     CI->eraseFromParent();
2892     return true;
2893   }
2894   return false;
2895 }
2896 
visitCallBase(CallBase & CB)2897 void DFSanVisitor::visitCallBase(CallBase &CB) {
2898   Function *F = CB.getCalledFunction();
2899   if ((F && F->isIntrinsic()) || CB.isInlineAsm()) {
2900     visitInstOperands(CB);
2901     return;
2902   }
2903 
2904   // Calls to this function are synthesized in wrappers, and we shouldn't
2905   // instrument them.
2906   if (F == DFSF.DFS.DFSanVarargWrapperFn.getCallee()->stripPointerCasts())
2907     return;
2908 
2909   DenseMap<Value *, Function *>::iterator UnwrappedFnIt =
2910       DFSF.DFS.UnwrappedFnMap.find(CB.getCalledOperand());
2911   if (UnwrappedFnIt != DFSF.DFS.UnwrappedFnMap.end())
2912     if (visitWrappedCallBase(*UnwrappedFnIt->second, CB))
2913       return;
2914 
2915   IRBuilder<> IRB(&CB);
2916 
2917   const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins();
2918   FunctionType *FT = CB.getFunctionType();
2919   const DataLayout &DL = getDataLayout();
2920 
2921   // Stores argument shadows.
2922   unsigned ArgOffset = 0;
2923   for (unsigned I = 0, N = FT->getNumParams(); I != N; ++I) {
2924     if (ShouldTrackOrigins) {
2925       // Ignore overflowed origins
2926       Value *ArgShadow = DFSF.getShadow(CB.getArgOperand(I));
2927       if (I < DFSF.DFS.NumOfElementsInArgOrgTLS &&
2928           !DFSF.DFS.isZeroShadow(ArgShadow))
2929         IRB.CreateStore(DFSF.getOrigin(CB.getArgOperand(I)),
2930                         DFSF.getArgOriginTLS(I, IRB));
2931     }
2932 
2933     unsigned Size =
2934         DL.getTypeAllocSize(DFSF.DFS.getShadowTy(FT->getParamType(I)));
2935     // Stop storing if arguments' size overflows. Inside a function, arguments
2936     // after overflow have zero shadow values.
2937     if (ArgOffset + Size > ArgTLSSize)
2938       break;
2939     IRB.CreateAlignedStore(DFSF.getShadow(CB.getArgOperand(I)),
2940                            DFSF.getArgTLS(FT->getParamType(I), ArgOffset, IRB),
2941                            ShadowTLSAlignment);
2942     ArgOffset += alignTo(Size, ShadowTLSAlignment);
2943   }
2944 
2945   Instruction *Next = nullptr;
2946   if (!CB.getType()->isVoidTy()) {
2947     if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
2948       if (II->getNormalDest()->getSinglePredecessor()) {
2949         Next = &II->getNormalDest()->front();
2950       } else {
2951         BasicBlock *NewBB =
2952             SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
2953         Next = &NewBB->front();
2954       }
2955     } else {
2956       assert(CB.getIterator() != CB.getParent()->end());
2957       Next = CB.getNextNode();
2958     }
2959 
2960     // Don't emit the epilogue for musttail call returns.
2961     if (isa<CallInst>(CB) && cast<CallInst>(CB).isMustTailCall())
2962       return;
2963 
2964     // Loads the return value shadow.
2965     IRBuilder<> NextIRB(Next);
2966     unsigned Size = DL.getTypeAllocSize(DFSF.DFS.getShadowTy(&CB));
2967     if (Size > RetvalTLSSize) {
2968       // Set overflowed return shadow to be zero.
2969       DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
2970     } else {
2971       LoadInst *LI = NextIRB.CreateAlignedLoad(
2972           DFSF.DFS.getShadowTy(&CB), DFSF.getRetvalTLS(CB.getType(), NextIRB),
2973           ShadowTLSAlignment, "_dfsret");
2974       DFSF.SkipInsts.insert(LI);
2975       DFSF.setShadow(&CB, LI);
2976       DFSF.NonZeroChecks.push_back(LI);
2977     }
2978 
2979     if (ShouldTrackOrigins) {
2980       LoadInst *LI = NextIRB.CreateLoad(DFSF.DFS.OriginTy,
2981                                         DFSF.getRetvalOriginTLS(), "_dfsret_o");
2982       DFSF.SkipInsts.insert(LI);
2983       DFSF.setOrigin(&CB, LI);
2984     }
2985   }
2986 }
2987 
visitPHINode(PHINode & PN)2988 void DFSanVisitor::visitPHINode(PHINode &PN) {
2989   Type *ShadowTy = DFSF.DFS.getShadowTy(&PN);
2990   PHINode *ShadowPN =
2991       PHINode::Create(ShadowTy, PN.getNumIncomingValues(), "", &PN);
2992 
2993   // Give the shadow phi node valid predecessors to fool SplitEdge into working.
2994   Value *UndefShadow = UndefValue::get(ShadowTy);
2995   for (BasicBlock *BB : PN.blocks())
2996     ShadowPN->addIncoming(UndefShadow, BB);
2997 
2998   DFSF.setShadow(&PN, ShadowPN);
2999 
3000   PHINode *OriginPN = nullptr;
3001   if (DFSF.DFS.shouldTrackOrigins()) {
3002     OriginPN =
3003         PHINode::Create(DFSF.DFS.OriginTy, PN.getNumIncomingValues(), "", &PN);
3004     Value *UndefOrigin = UndefValue::get(DFSF.DFS.OriginTy);
3005     for (BasicBlock *BB : PN.blocks())
3006       OriginPN->addIncoming(UndefOrigin, BB);
3007     DFSF.setOrigin(&PN, OriginPN);
3008   }
3009 
3010   DFSF.PHIFixups.push_back({&PN, ShadowPN, OriginPN});
3011 }
3012 
3013 namespace {
3014 class DataFlowSanitizerLegacyPass : public ModulePass {
3015 private:
3016   std::vector<std::string> ABIListFiles;
3017 
3018 public:
3019   static char ID;
3020 
DataFlowSanitizerLegacyPass(const std::vector<std::string> & ABIListFiles=std::vector<std::string> ())3021   DataFlowSanitizerLegacyPass(
3022       const std::vector<std::string> &ABIListFiles = std::vector<std::string>())
3023       : ModulePass(ID), ABIListFiles(ABIListFiles) {}
3024 
runOnModule(Module & M)3025   bool runOnModule(Module &M) override {
3026     return DataFlowSanitizer(ABIListFiles).runImpl(M);
3027   }
3028 };
3029 } // namespace
3030 
3031 char DataFlowSanitizerLegacyPass::ID;
3032 
3033 INITIALIZE_PASS(DataFlowSanitizerLegacyPass, "dfsan",
3034                 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
3035 
createDataFlowSanitizerLegacyPassPass(const std::vector<std::string> & ABIListFiles)3036 ModulePass *llvm::createDataFlowSanitizerLegacyPassPass(
3037     const std::vector<std::string> &ABIListFiles) {
3038   return new DataFlowSanitizerLegacyPass(ABIListFiles);
3039 }
3040 
run(Module & M,ModuleAnalysisManager & AM)3041 PreservedAnalyses DataFlowSanitizerPass::run(Module &M,
3042                                              ModuleAnalysisManager &AM) {
3043   if (DataFlowSanitizer(ABIListFiles).runImpl(M)) {
3044     return PreservedAnalyses::none();
3045   }
3046   return PreservedAnalyses::all();
3047 }
3048