1 //===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file is a part of AddressSanitizer, an address sanity checker.
11 // Details of the algorithm:
12 //  http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/DepthFirstIterator.h"
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/Analysis/MemoryBuiltins.h"
26 #include "llvm/Analysis/TargetLibraryInfo.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/IR/CallSite.h"
29 #include "llvm/IR/DIBuilder.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/Dominators.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/InlineAsm.h"
35 #include "llvm/IR/InstVisitor.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/IR/MDBuilder.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/IR/Type.h"
41 #include "llvm/MC/MCSectionMachO.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/DataTypes.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/Endian.h"
46 #include "llvm/Support/SwapByteOrder.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Transforms/Instrumentation.h"
49 #include "llvm/Transforms/Scalar.h"
50 #include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
51 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
52 #include "llvm/Transforms/Utils/Cloning.h"
53 #include "llvm/Transforms/Utils/Local.h"
54 #include "llvm/Transforms/Utils/ModuleUtils.h"
55 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
56 #include <algorithm>
57 #include <iomanip>
58 #include <limits>
59 #include <sstream>
60 #include <string>
61 #include <system_error>
62 
63 using namespace llvm;
64 
65 #define DEBUG_TYPE "asan"
66 
67 static const uint64_t kDefaultShadowScale = 3;
68 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
69 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
70 static const uint64_t kDynamicShadowSentinel = ~(uint64_t)0;
71 static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
72 static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
73 static const uint64_t kIOSSimShadowOffset64 = kDefaultShadowOffset64;
74 static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000;  // < 2G.
75 static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
76 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
77 static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
78 static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
79 static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
80 static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
81 static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
82 static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
83 static const uint64_t kPS4CPU_ShadowOffset64 = 1ULL << 40;
84 static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
85 // The shadow memory space is dynamically allocated.
86 static const uint64_t kWindowsShadowOffset64 = kDynamicShadowSentinel;
87 
88 static const size_t kMinStackMallocSize = 1 << 6;   // 64B
89 static const size_t kMaxStackMallocSize = 1 << 16;  // 64K
90 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
91 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
92 
93 static const char *const kAsanModuleCtorName = "asan.module_ctor";
94 static const char *const kAsanModuleDtorName = "asan.module_dtor";
95 static const uint64_t kAsanCtorAndDtorPriority = 1;
96 static const char *const kAsanReportErrorTemplate = "__asan_report_";
97 static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
98 static const char *const kAsanUnregisterGlobalsName =
99     "__asan_unregister_globals";
100 static const char *const kAsanRegisterImageGlobalsName =
101   "__asan_register_image_globals";
102 static const char *const kAsanUnregisterImageGlobalsName =
103   "__asan_unregister_image_globals";
104 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
105 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
106 static const char *const kAsanInitName = "__asan_init";
107 static const char *const kAsanVersionCheckName =
108     "__asan_version_mismatch_check_v8";
109 static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
110 static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
111 static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
112 static const int kMaxAsanStackMallocSizeClass = 10;
113 static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
114 static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
115 static const char *const kAsanGenPrefix = "__asan_gen_";
116 static const char *const kODRGenPrefix = "__odr_asan_gen_";
117 static const char *const kSanCovGenPrefix = "__sancov_gen_";
118 static const char *const kAsanSetShadowPrefix = "__asan_set_shadow_";
119 static const char *const kAsanPoisonStackMemoryName =
120     "__asan_poison_stack_memory";
121 static const char *const kAsanUnpoisonStackMemoryName =
122     "__asan_unpoison_stack_memory";
123 static const char *const kAsanGlobalsRegisteredFlagName =
124     "__asan_globals_registered";
125 
126 static const char *const kAsanOptionDetectUseAfterReturn =
127     "__asan_option_detect_stack_use_after_return";
128 
129 static const char *const kAsanShadowMemoryDynamicAddress =
130     "__asan_shadow_memory_dynamic_address";
131 
132 static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
133 static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
134 
135 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
136 static const size_t kNumberOfAccessSizes = 5;
137 
138 static const unsigned kAllocaRzSize = 32;
139 
140 // Command-line flags.
141 static cl::opt<bool> ClEnableKasan(
142     "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
143     cl::Hidden, cl::init(false));
144 static cl::opt<bool> ClRecover(
145     "asan-recover",
146     cl::desc("Enable recovery mode (continue-after-error)."),
147     cl::Hidden, cl::init(false));
148 
149 // This flag may need to be replaced with -f[no-]asan-reads.
150 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
151                                        cl::desc("instrument read instructions"),
152                                        cl::Hidden, cl::init(true));
153 static cl::opt<bool> ClInstrumentWrites(
154     "asan-instrument-writes", cl::desc("instrument write instructions"),
155     cl::Hidden, cl::init(true));
156 static cl::opt<bool> ClInstrumentAtomics(
157     "asan-instrument-atomics",
158     cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
159     cl::init(true));
160 static cl::opt<bool> ClAlwaysSlowPath(
161     "asan-always-slow-path",
162     cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
163     cl::init(false));
164 static cl::opt<bool> ClForceDynamicShadow(
165     "asan-force-dynamic-shadow",
166     cl::desc("Load shadow address into a local variable for each function"),
167     cl::Hidden, cl::init(false));
168 
169 // This flag limits the number of instructions to be instrumented
170 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
171 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
172 // set it to 10000.
173 static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
174     "asan-max-ins-per-bb", cl::init(10000),
175     cl::desc("maximal number of instructions to instrument in any given BB"),
176     cl::Hidden);
177 // This flag may need to be replaced with -f[no]asan-stack.
178 static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
179                              cl::Hidden, cl::init(true));
180 static cl::opt<uint32_t> ClMaxInlinePoisoningSize(
181     "asan-max-inline-poisoning-size",
182     cl::desc(
183         "Inline shadow poisoning for blocks up to the given size in bytes."),
184     cl::Hidden, cl::init(64));
185 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
186                                       cl::desc("Check stack-use-after-return"),
187                                       cl::Hidden, cl::init(true));
188 static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
189                                      cl::desc("Check stack-use-after-scope"),
190                                      cl::Hidden, cl::init(false));
191 // This flag may need to be replaced with -f[no]asan-globals.
192 static cl::opt<bool> ClGlobals("asan-globals",
193                                cl::desc("Handle global objects"), cl::Hidden,
194                                cl::init(true));
195 static cl::opt<bool> ClInitializers("asan-initialization-order",
196                                     cl::desc("Handle C++ initializer order"),
197                                     cl::Hidden, cl::init(true));
198 static cl::opt<bool> ClInvalidPointerPairs(
199     "asan-detect-invalid-pointer-pair",
200     cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
201     cl::init(false));
202 static cl::opt<unsigned> ClRealignStack(
203     "asan-realign-stack",
204     cl::desc("Realign stack to the value of this flag (power of two)"),
205     cl::Hidden, cl::init(32));
206 static cl::opt<int> ClInstrumentationWithCallsThreshold(
207     "asan-instrumentation-with-call-threshold",
208     cl::desc(
209         "If the function being instrumented contains more than "
210         "this number of memory accesses, use callbacks instead of "
211         "inline checks (-1 means never use callbacks)."),
212     cl::Hidden, cl::init(7000));
213 static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
214     "asan-memory-access-callback-prefix",
215     cl::desc("Prefix for memory access callbacks"), cl::Hidden,
216     cl::init("__asan_"));
217 static cl::opt<bool>
218     ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
219                                cl::desc("instrument dynamic allocas"),
220                                cl::Hidden, cl::init(true));
221 static cl::opt<bool> ClSkipPromotableAllocas(
222     "asan-skip-promotable-allocas",
223     cl::desc("Do not instrument promotable allocas"), cl::Hidden,
224     cl::init(true));
225 
226 // These flags allow to change the shadow mapping.
227 // The shadow mapping looks like
228 //    Shadow = (Mem >> scale) + offset
229 static cl::opt<int> ClMappingScale("asan-mapping-scale",
230                                    cl::desc("scale of asan shadow mapping"),
231                                    cl::Hidden, cl::init(0));
232 static cl::opt<unsigned long long> ClMappingOffset(
233     "asan-mapping-offset",
234     cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden,
235     cl::init(0));
236 
237 // Optimization flags. Not user visible, used mostly for testing
238 // and benchmarking the tool.
239 static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
240                            cl::Hidden, cl::init(true));
241 static cl::opt<bool> ClOptSameTemp(
242     "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
243     cl::Hidden, cl::init(true));
244 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
245                                   cl::desc("Don't instrument scalar globals"),
246                                   cl::Hidden, cl::init(true));
247 static cl::opt<bool> ClOptStack(
248     "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
249     cl::Hidden, cl::init(false));
250 
251 static cl::opt<bool> ClDynamicAllocaStack(
252     "asan-stack-dynamic-alloca",
253     cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
254     cl::init(true));
255 
256 static cl::opt<uint32_t> ClForceExperiment(
257     "asan-force-experiment",
258     cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
259     cl::init(0));
260 
261 static cl::opt<bool>
262     ClUsePrivateAliasForGlobals("asan-use-private-alias",
263                                 cl::desc("Use private aliases for global"
264                                          " variables"),
265                                 cl::Hidden, cl::init(false));
266 
267 static cl::opt<bool>
268     ClUseMachOGlobalsSection("asan-globals-live-support",
269                              cl::desc("Use linker features to support dead "
270                                       "code stripping of globals "
271                                       "(Mach-O only)"),
272                              cl::Hidden, cl::init(true));
273 
274 // Debug flags.
275 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
276                             cl::init(0));
277 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
278                                  cl::Hidden, cl::init(0));
279 static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
280                                         cl::desc("Debug func"));
281 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
282                                cl::Hidden, cl::init(-1));
283 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),
284                                cl::Hidden, cl::init(-1));
285 
286 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
287 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
288 STATISTIC(NumOptimizedAccessesToGlobalVar,
289           "Number of optimized accesses to global vars");
290 STATISTIC(NumOptimizedAccessesToStackVar,
291           "Number of optimized accesses to stack vars");
292 
293 namespace {
294 /// Frontend-provided metadata for source location.
295 struct LocationMetadata {
296   StringRef Filename;
297   int LineNo;
298   int ColumnNo;
299 
300   LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
301 
302   bool empty() const { return Filename.empty(); }
303 
304   void parse(MDNode *MDN) {
305     assert(MDN->getNumOperands() == 3);
306     MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
307     Filename = DIFilename->getString();
308     LineNo =
309         mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
310     ColumnNo =
311         mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
312   }
313 };
314 
315 /// Frontend-provided metadata for global variables.
316 class GlobalsMetadata {
317  public:
318   struct Entry {
319     Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
320     LocationMetadata SourceLoc;
321     StringRef Name;
322     bool IsDynInit;
323     bool IsBlacklisted;
324   };
325 
326   GlobalsMetadata() : inited_(false) {}
327 
328   void reset() {
329     inited_ = false;
330     Entries.clear();
331   }
332 
333   void init(Module &M) {
334     assert(!inited_);
335     inited_ = true;
336     NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
337     if (!Globals) return;
338     for (auto MDN : Globals->operands()) {
339       // Metadata node contains the global and the fields of "Entry".
340       assert(MDN->getNumOperands() == 5);
341       auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
342       // The optimizer may optimize away a global entirely.
343       if (!GV) continue;
344       // We can already have an entry for GV if it was merged with another
345       // global.
346       Entry &E = Entries[GV];
347       if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
348         E.SourceLoc.parse(Loc);
349       if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
350         E.Name = Name->getString();
351       ConstantInt *IsDynInit =
352           mdconst::extract<ConstantInt>(MDN->getOperand(3));
353       E.IsDynInit |= IsDynInit->isOne();
354       ConstantInt *IsBlacklisted =
355           mdconst::extract<ConstantInt>(MDN->getOperand(4));
356       E.IsBlacklisted |= IsBlacklisted->isOne();
357     }
358   }
359 
360   /// Returns metadata entry for a given global.
361   Entry get(GlobalVariable *G) const {
362     auto Pos = Entries.find(G);
363     return (Pos != Entries.end()) ? Pos->second : Entry();
364   }
365 
366  private:
367   bool inited_;
368   DenseMap<GlobalVariable *, Entry> Entries;
369 };
370 
371 /// This struct defines the shadow mapping using the rule:
372 ///   shadow = (mem >> Scale) ADD-or-OR Offset.
373 struct ShadowMapping {
374   int Scale;
375   uint64_t Offset;
376   bool OrShadowOffset;
377 };
378 
379 static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
380                                       bool IsKasan) {
381   bool IsAndroid = TargetTriple.isAndroid();
382   bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
383   bool IsFreeBSD = TargetTriple.isOSFreeBSD();
384   bool IsPS4CPU = TargetTriple.isPS4CPU();
385   bool IsLinux = TargetTriple.isOSLinux();
386   bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
387                  TargetTriple.getArch() == llvm::Triple::ppc64le;
388   bool IsSystemZ = TargetTriple.getArch() == llvm::Triple::systemz;
389   bool IsX86 = TargetTriple.getArch() == llvm::Triple::x86;
390   bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
391   bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
392                   TargetTriple.getArch() == llvm::Triple::mipsel;
393   bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
394                   TargetTriple.getArch() == llvm::Triple::mips64el;
395   bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
396   bool IsWindows = TargetTriple.isOSWindows();
397 
398   ShadowMapping Mapping;
399 
400   if (LongSize == 32) {
401     // Android is always PIE, which means that the beginning of the address
402     // space is always available.
403     if (IsAndroid)
404       Mapping.Offset = 0;
405     else if (IsMIPS32)
406       Mapping.Offset = kMIPS32_ShadowOffset32;
407     else if (IsFreeBSD)
408       Mapping.Offset = kFreeBSD_ShadowOffset32;
409     else if (IsIOS)
410       // If we're targeting iOS and x86, the binary is built for iOS simulator.
411       Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
412     else if (IsWindows)
413       Mapping.Offset = kWindowsShadowOffset32;
414     else
415       Mapping.Offset = kDefaultShadowOffset32;
416   } else {  // LongSize == 64
417     if (IsPPC64)
418       Mapping.Offset = kPPC64_ShadowOffset64;
419     else if (IsSystemZ)
420       Mapping.Offset = kSystemZ_ShadowOffset64;
421     else if (IsFreeBSD)
422       Mapping.Offset = kFreeBSD_ShadowOffset64;
423     else if (IsPS4CPU)
424       Mapping.Offset = kPS4CPU_ShadowOffset64;
425     else if (IsLinux && IsX86_64) {
426       if (IsKasan)
427         Mapping.Offset = kLinuxKasan_ShadowOffset64;
428       else
429         Mapping.Offset = kSmallX86_64ShadowOffset;
430     } else if (IsWindows && IsX86_64) {
431       Mapping.Offset = kWindowsShadowOffset64;
432     } else if (IsMIPS64)
433       Mapping.Offset = kMIPS64_ShadowOffset64;
434     else if (IsIOS)
435       // If we're targeting iOS and x86, the binary is built for iOS simulator.
436       // We are using dynamic shadow offset on the 64-bit devices.
437       Mapping.Offset =
438         IsX86_64 ? kIOSSimShadowOffset64 : kDynamicShadowSentinel;
439     else if (IsAArch64)
440       Mapping.Offset = kAArch64_ShadowOffset64;
441     else
442       Mapping.Offset = kDefaultShadowOffset64;
443   }
444 
445   if (ClForceDynamicShadow) {
446     Mapping.Offset = kDynamicShadowSentinel;
447   }
448 
449   Mapping.Scale = kDefaultShadowScale;
450   if (ClMappingScale.getNumOccurrences() > 0) {
451     Mapping.Scale = ClMappingScale;
452   }
453 
454   if (ClMappingOffset.getNumOccurrences() > 0) {
455     Mapping.Offset = ClMappingOffset;
456   }
457 
458   // OR-ing shadow offset if more efficient (at least on x86) if the offset
459   // is a power of two, but on ppc64 we have to use add since the shadow
460   // offset is not necessary 1/8-th of the address space.  On SystemZ,
461   // we could OR the constant in a single instruction, but it's more
462   // efficient to load it once and use indexed addressing.
463   Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ && !IsPS4CPU &&
464                            !(Mapping.Offset & (Mapping.Offset - 1)) &&
465                            Mapping.Offset != kDynamicShadowSentinel;
466 
467   return Mapping;
468 }
469 
470 static size_t RedzoneSizeForScale(int MappingScale) {
471   // Redzone used for stack and globals is at least 32 bytes.
472   // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
473   return std::max(32U, 1U << MappingScale);
474 }
475 
476 /// AddressSanitizer: instrument the code in module to find memory bugs.
477 struct AddressSanitizer : public FunctionPass {
478   explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
479                             bool UseAfterScope = false)
480       : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
481         Recover(Recover || ClRecover),
482         UseAfterScope(UseAfterScope || ClUseAfterScope),
483         LocalDynamicShadow(nullptr) {
484     initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
485   }
486   StringRef getPassName() const override {
487     return "AddressSanitizerFunctionPass";
488   }
489   void getAnalysisUsage(AnalysisUsage &AU) const override {
490     AU.addRequired<DominatorTreeWrapperPass>();
491     AU.addRequired<TargetLibraryInfoWrapperPass>();
492   }
493   uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
494     uint64_t ArraySize = 1;
495     if (AI.isArrayAllocation()) {
496       const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
497       assert(CI && "non-constant array size");
498       ArraySize = CI->getZExtValue();
499     }
500     Type *Ty = AI.getAllocatedType();
501     uint64_t SizeInBytes =
502         AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
503     return SizeInBytes * ArraySize;
504   }
505   /// Check if we want (and can) handle this alloca.
506   bool isInterestingAlloca(const AllocaInst &AI);
507 
508   /// If it is an interesting memory access, return the PointerOperand
509   /// and set IsWrite/Alignment. Otherwise return nullptr.
510   /// MaybeMask is an output parameter for the mask Value, if we're looking at a
511   /// masked load/store.
512   Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
513                                    uint64_t *TypeSize, unsigned *Alignment,
514                                    Value **MaybeMask = nullptr);
515   void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
516                      bool UseCalls, const DataLayout &DL);
517   void instrumentPointerComparisonOrSubtraction(Instruction *I);
518   void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
519                          Value *Addr, uint32_t TypeSize, bool IsWrite,
520                          Value *SizeArgument, bool UseCalls, uint32_t Exp);
521   void instrumentUnusualSizeOrAlignment(Instruction *I,
522                                         Instruction *InsertBefore, Value *Addr,
523                                         uint32_t TypeSize, bool IsWrite,
524                                         Value *SizeArgument, bool UseCalls,
525                                         uint32_t Exp);
526   Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
527                            Value *ShadowValue, uint32_t TypeSize);
528   Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
529                                  bool IsWrite, size_t AccessSizeIndex,
530                                  Value *SizeArgument, uint32_t Exp);
531   void instrumentMemIntrinsic(MemIntrinsic *MI);
532   Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
533   bool runOnFunction(Function &F) override;
534   bool maybeInsertAsanInitAtFunctionEntry(Function &F);
535   void maybeInsertDynamicShadowAtFunctionEntry(Function &F);
536   void markEscapedLocalAllocas(Function &F);
537   bool doInitialization(Module &M) override;
538   bool doFinalization(Module &M) override;
539   static char ID;  // Pass identification, replacement for typeid
540 
541   DominatorTree &getDominatorTree() const { return *DT; }
542 
543  private:
544   void initializeCallbacks(Module &M);
545 
546   bool LooksLikeCodeInBug11395(Instruction *I);
547   bool GlobalIsLinkerInitialized(GlobalVariable *G);
548   bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
549                     uint64_t TypeSize) const;
550 
551   /// Helper to cleanup per-function state.
552   struct FunctionStateRAII {
553     AddressSanitizer *Pass;
554     FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
555       assert(Pass->ProcessedAllocas.empty() &&
556              "last pass forgot to clear cache");
557       assert(!Pass->LocalDynamicShadow);
558     }
559     ~FunctionStateRAII() {
560       Pass->LocalDynamicShadow = nullptr;
561       Pass->ProcessedAllocas.clear();
562     }
563   };
564 
565   LLVMContext *C;
566   Triple TargetTriple;
567   int LongSize;
568   bool CompileKernel;
569   bool Recover;
570   bool UseAfterScope;
571   Type *IntptrTy;
572   ShadowMapping Mapping;
573   DominatorTree *DT;
574   Function *AsanCtorFunction = nullptr;
575   Function *AsanInitFunction = nullptr;
576   Function *AsanHandleNoReturnFunc;
577   Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
578   // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
579   Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
580   Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
581   // This array is indexed by AccessIsWrite and Experiment.
582   Function *AsanErrorCallbackSized[2][2];
583   Function *AsanMemoryAccessCallbackSized[2][2];
584   Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
585   InlineAsm *EmptyAsm;
586   Value *LocalDynamicShadow;
587   GlobalsMetadata GlobalsMD;
588   DenseMap<const AllocaInst *, bool> ProcessedAllocas;
589 
590   friend struct FunctionStackPoisoner;
591 };
592 
593 class AddressSanitizerModule : public ModulePass {
594  public:
595   explicit AddressSanitizerModule(bool CompileKernel = false,
596                                   bool Recover = false)
597       : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
598         Recover(Recover || ClRecover) {}
599   bool runOnModule(Module &M) override;
600   static char ID;  // Pass identification, replacement for typeid
601   StringRef getPassName() const override { return "AddressSanitizerModule"; }
602 
603 private:
604   void initializeCallbacks(Module &M);
605 
606   bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
607   void InstrumentGlobalsCOFF(IRBuilder<> &IRB, Module &M,
608                              ArrayRef<GlobalVariable *> ExtendedGlobals,
609                              ArrayRef<Constant *> MetadataInitializers);
610   void InstrumentGlobalsMachO(IRBuilder<> &IRB, Module &M,
611                               ArrayRef<GlobalVariable *> ExtendedGlobals,
612                               ArrayRef<Constant *> MetadataInitializers);
613   void
614   InstrumentGlobalsWithMetadataArray(IRBuilder<> &IRB, Module &M,
615                                      ArrayRef<GlobalVariable *> ExtendedGlobals,
616                                      ArrayRef<Constant *> MetadataInitializers);
617 
618   GlobalVariable *CreateMetadataGlobal(Module &M, Constant *Initializer,
619                                        StringRef OriginalName);
620   void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata);
621   IRBuilder<> CreateAsanModuleDtor(Module &M);
622 
623   bool ShouldInstrumentGlobal(GlobalVariable *G);
624   bool ShouldUseMachOGlobalsSection() const;
625   StringRef getGlobalMetadataSection() const;
626   void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
627   void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
628   size_t MinRedzoneSizeForGlobal() const {
629     return RedzoneSizeForScale(Mapping.Scale);
630   }
631 
632   GlobalsMetadata GlobalsMD;
633   bool CompileKernel;
634   bool Recover;
635   Type *IntptrTy;
636   LLVMContext *C;
637   Triple TargetTriple;
638   ShadowMapping Mapping;
639   Function *AsanPoisonGlobals;
640   Function *AsanUnpoisonGlobals;
641   Function *AsanRegisterGlobals;
642   Function *AsanUnregisterGlobals;
643   Function *AsanRegisterImageGlobals;
644   Function *AsanUnregisterImageGlobals;
645 };
646 
647 // Stack poisoning does not play well with exception handling.
648 // When an exception is thrown, we essentially bypass the code
649 // that unpoisones the stack. This is why the run-time library has
650 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
651 // stack in the interceptor. This however does not work inside the
652 // actual function which catches the exception. Most likely because the
653 // compiler hoists the load of the shadow value somewhere too high.
654 // This causes asan to report a non-existing bug on 453.povray.
655 // It sounds like an LLVM bug.
656 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
657   Function &F;
658   AddressSanitizer &ASan;
659   DIBuilder DIB;
660   LLVMContext *C;
661   Type *IntptrTy;
662   Type *IntptrPtrTy;
663   ShadowMapping Mapping;
664 
665   SmallVector<AllocaInst *, 16> AllocaVec;
666   SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;
667   SmallVector<Instruction *, 8> RetVec;
668   unsigned StackAlignment;
669 
670   Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
671       *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
672   Function *AsanSetShadowFunc[0x100] = {};
673   Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
674   Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
675 
676   // Stores a place and arguments of poisoning/unpoisoning call for alloca.
677   struct AllocaPoisonCall {
678     IntrinsicInst *InsBefore;
679     AllocaInst *AI;
680     uint64_t Size;
681     bool DoPoison;
682   };
683   SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
684   SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
685 
686   SmallVector<AllocaInst *, 1> DynamicAllocaVec;
687   SmallVector<IntrinsicInst *, 1> StackRestoreVec;
688   AllocaInst *DynamicAllocaLayout = nullptr;
689   IntrinsicInst *LocalEscapeCall = nullptr;
690 
691   // Maps Value to an AllocaInst from which the Value is originated.
692   typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
693   AllocaForValueMapTy AllocaForValue;
694 
695   bool HasNonEmptyInlineAsm = false;
696   bool HasReturnsTwiceCall = false;
697   std::unique_ptr<CallInst> EmptyInlineAsm;
698 
699   FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
700       : F(F),
701         ASan(ASan),
702         DIB(*F.getParent(), /*AllowUnresolved*/ false),
703         C(ASan.C),
704         IntptrTy(ASan.IntptrTy),
705         IntptrPtrTy(PointerType::get(IntptrTy, 0)),
706         Mapping(ASan.Mapping),
707         StackAlignment(1 << Mapping.Scale),
708         EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
709 
710   bool runOnFunction() {
711     if (!ClStack) return false;
712     // Collect alloca, ret, lifetime instructions etc.
713     for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
714 
715     if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
716 
717     initializeCallbacks(*F.getParent());
718 
719     processDynamicAllocas();
720     processStaticAllocas();
721 
722     if (ClDebugStack) {
723       DEBUG(dbgs() << F);
724     }
725     return true;
726   }
727 
728   // Finds all Alloca instructions and puts
729   // poisoned red zones around all of them.
730   // Then unpoison everything back before the function returns.
731   void processStaticAllocas();
732   void processDynamicAllocas();
733 
734   void createDynamicAllocasInitStorage();
735 
736   // ----------------------- Visitors.
737   /// \brief Collect all Ret instructions.
738   void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
739 
740   /// \brief Collect all Resume instructions.
741   void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
742 
743   /// \brief Collect all CatchReturnInst instructions.
744   void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
745 
746   void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
747                                         Value *SavedStack) {
748     IRBuilder<> IRB(InstBefore);
749     Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
750     // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
751     // need to adjust extracted SP to compute the address of the most recent
752     // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
753     // this purpose.
754     if (!isa<ReturnInst>(InstBefore)) {
755       Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
756           InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
757           {IntptrTy});
758 
759       Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
760 
761       DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
762                                      DynamicAreaOffset);
763     }
764 
765     IRB.CreateCall(AsanAllocasUnpoisonFunc,
766                    {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
767   }
768 
769   // Unpoison dynamic allocas redzones.
770   void unpoisonDynamicAllocas() {
771     for (auto &Ret : RetVec)
772       unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
773 
774     for (auto &StackRestoreInst : StackRestoreVec)
775       unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
776                                        StackRestoreInst->getOperand(0));
777   }
778 
779   // Deploy and poison redzones around dynamic alloca call. To do this, we
780   // should replace this call with another one with changed parameters and
781   // replace all its uses with new address, so
782   //   addr = alloca type, old_size, align
783   // is replaced by
784   //   new_size = (old_size + additional_size) * sizeof(type)
785   //   tmp = alloca i8, new_size, max(align, 32)
786   //   addr = tmp + 32 (first 32 bytes are for the left redzone).
787   // Additional_size is added to make new memory allocation contain not only
788   // requested memory, but also left, partial and right redzones.
789   void handleDynamicAllocaCall(AllocaInst *AI);
790 
791   /// \brief Collect Alloca instructions we want (and can) handle.
792   void visitAllocaInst(AllocaInst &AI) {
793     if (!ASan.isInterestingAlloca(AI)) {
794       if (AI.isStaticAlloca()) {
795         // Skip over allocas that are present *before* the first instrumented
796         // alloca, we don't want to move those around.
797         if (AllocaVec.empty())
798           return;
799 
800         StaticAllocasToMoveUp.push_back(&AI);
801       }
802       return;
803     }
804 
805     StackAlignment = std::max(StackAlignment, AI.getAlignment());
806     if (!AI.isStaticAlloca())
807       DynamicAllocaVec.push_back(&AI);
808     else
809       AllocaVec.push_back(&AI);
810   }
811 
812   /// \brief Collect lifetime intrinsic calls to check for use-after-scope
813   /// errors.
814   void visitIntrinsicInst(IntrinsicInst &II) {
815     Intrinsic::ID ID = II.getIntrinsicID();
816     if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
817     if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
818     if (!ASan.UseAfterScope)
819       return;
820     if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
821       return;
822     // Found lifetime intrinsic, add ASan instrumentation if necessary.
823     ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
824     // If size argument is undefined, don't do anything.
825     if (Size->isMinusOne()) return;
826     // Check that size doesn't saturate uint64_t and can
827     // be stored in IntptrTy.
828     const uint64_t SizeValue = Size->getValue().getLimitedValue();
829     if (SizeValue == ~0ULL ||
830         !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
831       return;
832     // Find alloca instruction that corresponds to llvm.lifetime argument.
833     AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
834     if (!AI || !ASan.isInterestingAlloca(*AI))
835       return;
836     bool DoPoison = (ID == Intrinsic::lifetime_end);
837     AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
838     if (AI->isStaticAlloca())
839       StaticAllocaPoisonCallVec.push_back(APC);
840     else if (ClInstrumentDynamicAllocas)
841       DynamicAllocaPoisonCallVec.push_back(APC);
842   }
843 
844   void visitCallSite(CallSite CS) {
845     Instruction *I = CS.getInstruction();
846     if (CallInst *CI = dyn_cast<CallInst>(I)) {
847       HasNonEmptyInlineAsm |=
848           CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
849       HasReturnsTwiceCall |= CI->canReturnTwice();
850     }
851   }
852 
853   // ---------------------- Helpers.
854   void initializeCallbacks(Module &M);
855 
856   bool doesDominateAllExits(const Instruction *I) const {
857     for (auto Ret : RetVec) {
858       if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
859     }
860     return true;
861   }
862 
863   /// Finds alloca where the value comes from.
864   AllocaInst *findAllocaForValue(Value *V);
865 
866   // Copies bytes from ShadowBytes into shadow memory for indexes where
867   // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
868   // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
869   void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
870                     IRBuilder<> &IRB, Value *ShadowBase);
871   void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
872                     size_t Begin, size_t End, IRBuilder<> &IRB,
873                     Value *ShadowBase);
874   void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
875                           ArrayRef<uint8_t> ShadowBytes, size_t Begin,
876                           size_t End, IRBuilder<> &IRB, Value *ShadowBase);
877 
878   void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
879 
880   Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
881                                bool Dynamic);
882   PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
883                      Instruction *ThenTerm, Value *ValueIfFalse);
884 };
885 
886 } // anonymous namespace
887 
888 char AddressSanitizer::ID = 0;
889 INITIALIZE_PASS_BEGIN(
890     AddressSanitizer, "asan",
891     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
892     false)
893 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
894 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
895 INITIALIZE_PASS_END(
896     AddressSanitizer, "asan",
897     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
898     false)
899 FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
900                                                        bool Recover,
901                                                        bool UseAfterScope) {
902   assert(!CompileKernel || Recover);
903   return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
904 }
905 
906 char AddressSanitizerModule::ID = 0;
907 INITIALIZE_PASS(
908     AddressSanitizerModule, "asan-module",
909     "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
910     "ModulePass",
911     false, false)
912 ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
913                                                    bool Recover) {
914   assert(!CompileKernel || Recover);
915   return new AddressSanitizerModule(CompileKernel, Recover);
916 }
917 
918 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
919   size_t Res = countTrailingZeros(TypeSize / 8);
920   assert(Res < kNumberOfAccessSizes);
921   return Res;
922 }
923 
924 // \brief Create a constant for Str so that we can pass it to the run-time lib.
925 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
926                                                     bool AllowMerging) {
927   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
928   // We use private linkage for module-local strings. If they can be merged
929   // with another one, we set the unnamed_addr attribute.
930   GlobalVariable *GV =
931       new GlobalVariable(M, StrConst->getType(), true,
932                          GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
933   if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
934   GV->setAlignment(1);  // Strings may not be merged w/o setting align 1.
935   return GV;
936 }
937 
938 /// \brief Create a global describing a source location.
939 static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
940                                                        LocationMetadata MD) {
941   Constant *LocData[] = {
942       createPrivateGlobalForString(M, MD.Filename, true),
943       ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
944       ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
945   };
946   auto LocStruct = ConstantStruct::getAnon(LocData);
947   auto GV = new GlobalVariable(M, LocStruct->getType(), true,
948                                GlobalValue::PrivateLinkage, LocStruct,
949                                kAsanGenPrefix);
950   GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
951   return GV;
952 }
953 
954 /// \brief Check if \p G has been created by a trusted compiler pass.
955 static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
956   // Do not instrument asan globals.
957   if (G->getName().startswith(kAsanGenPrefix) ||
958       G->getName().startswith(kSanCovGenPrefix) ||
959       G->getName().startswith(kODRGenPrefix))
960     return true;
961 
962   // Do not instrument gcov counter arrays.
963   if (G->getName() == "__llvm_gcov_ctr")
964     return true;
965 
966   return false;
967 }
968 
969 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
970   // Shadow >> scale
971   Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
972   if (Mapping.Offset == 0) return Shadow;
973   // (Shadow >> scale) | offset
974   Value *ShadowBase;
975   if (LocalDynamicShadow)
976     ShadowBase = LocalDynamicShadow;
977   else
978     ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
979   if (Mapping.OrShadowOffset)
980     return IRB.CreateOr(Shadow, ShadowBase);
981   else
982     return IRB.CreateAdd(Shadow, ShadowBase);
983 }
984 
985 // Instrument memset/memmove/memcpy
986 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
987   IRBuilder<> IRB(MI);
988   if (isa<MemTransferInst>(MI)) {
989     IRB.CreateCall(
990         isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
991         {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
992          IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
993          IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
994   } else if (isa<MemSetInst>(MI)) {
995     IRB.CreateCall(
996         AsanMemset,
997         {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
998          IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
999          IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
1000   }
1001   MI->eraseFromParent();
1002 }
1003 
1004 /// Check if we want (and can) handle this alloca.
1005 bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
1006   auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1007 
1008   if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1009     return PreviouslySeenAllocaInfo->getSecond();
1010 
1011   bool IsInteresting =
1012       (AI.getAllocatedType()->isSized() &&
1013        // alloca() may be called with 0 size, ignore it.
1014        ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
1015        // We are only interested in allocas not promotable to registers.
1016        // Promotable allocas are common under -O0.
1017        (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
1018        // inalloca allocas are not treated as static, and we don't want
1019        // dynamic alloca instrumentation for them as well.
1020        !AI.isUsedWithInAlloca() &&
1021        // swifterror allocas are register promoted by ISel
1022        !AI.isSwiftError());
1023 
1024   ProcessedAllocas[&AI] = IsInteresting;
1025   return IsInteresting;
1026 }
1027 
1028 Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
1029                                                    bool *IsWrite,
1030                                                    uint64_t *TypeSize,
1031                                                    unsigned *Alignment,
1032                                                    Value **MaybeMask) {
1033   // Skip memory accesses inserted by another instrumentation.
1034   if (I->getMetadata("nosanitize")) return nullptr;
1035 
1036   // Do not instrument the load fetching the dynamic shadow address.
1037   if (LocalDynamicShadow == I)
1038     return nullptr;
1039 
1040   Value *PtrOperand = nullptr;
1041   const DataLayout &DL = I->getModule()->getDataLayout();
1042   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1043     if (!ClInstrumentReads) return nullptr;
1044     *IsWrite = false;
1045     *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
1046     *Alignment = LI->getAlignment();
1047     PtrOperand = LI->getPointerOperand();
1048   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1049     if (!ClInstrumentWrites) return nullptr;
1050     *IsWrite = true;
1051     *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
1052     *Alignment = SI->getAlignment();
1053     PtrOperand = SI->getPointerOperand();
1054   } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
1055     if (!ClInstrumentAtomics) return nullptr;
1056     *IsWrite = true;
1057     *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
1058     *Alignment = 0;
1059     PtrOperand = RMW->getPointerOperand();
1060   } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
1061     if (!ClInstrumentAtomics) return nullptr;
1062     *IsWrite = true;
1063     *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
1064     *Alignment = 0;
1065     PtrOperand = XCHG->getPointerOperand();
1066   } else if (auto CI = dyn_cast<CallInst>(I)) {
1067     auto *F = dyn_cast<Function>(CI->getCalledValue());
1068     if (F && (F->getName().startswith("llvm.masked.load.") ||
1069               F->getName().startswith("llvm.masked.store."))) {
1070       unsigned OpOffset = 0;
1071       if (F->getName().startswith("llvm.masked.store.")) {
1072         if (!ClInstrumentWrites)
1073           return nullptr;
1074         // Masked store has an initial operand for the value.
1075         OpOffset = 1;
1076         *IsWrite = true;
1077       } else {
1078         if (!ClInstrumentReads)
1079           return nullptr;
1080         *IsWrite = false;
1081       }
1082 
1083       auto BasePtr = CI->getOperand(0 + OpOffset);
1084       auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
1085       *TypeSize = DL.getTypeStoreSizeInBits(Ty);
1086       if (auto AlignmentConstant =
1087               dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1088         *Alignment = (unsigned)AlignmentConstant->getZExtValue();
1089       else
1090         *Alignment = 1; // No alignment guarantees. We probably got Undef
1091       if (MaybeMask)
1092         *MaybeMask = CI->getOperand(2 + OpOffset);
1093       PtrOperand = BasePtr;
1094     }
1095   }
1096 
1097   if (PtrOperand) {
1098     // Do not instrument acesses from different address spaces; we cannot deal
1099     // with them.
1100     Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1101     if (PtrTy->getPointerAddressSpace() != 0)
1102       return nullptr;
1103 
1104     // Ignore swifterror addresses.
1105     // swifterror memory addresses are mem2reg promoted by instruction
1106     // selection. As such they cannot have regular uses like an instrumentation
1107     // function and it makes no sense to track them as memory.
1108     if (PtrOperand->isSwiftError())
1109       return nullptr;
1110   }
1111 
1112   // Treat memory accesses to promotable allocas as non-interesting since they
1113   // will not cause memory violations. This greatly speeds up the instrumented
1114   // executable at -O0.
1115   if (ClSkipPromotableAllocas)
1116     if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1117       return isInterestingAlloca(*AI) ? AI : nullptr;
1118 
1119   return PtrOperand;
1120 }
1121 
1122 static bool isPointerOperand(Value *V) {
1123   return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1124 }
1125 
1126 // This is a rough heuristic; it may cause both false positives and
1127 // false negatives. The proper implementation requires cooperation with
1128 // the frontend.
1129 static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1130   if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
1131     if (!Cmp->isRelational()) return false;
1132   } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1133     if (BO->getOpcode() != Instruction::Sub) return false;
1134   } else {
1135     return false;
1136   }
1137   return isPointerOperand(I->getOperand(0)) &&
1138          isPointerOperand(I->getOperand(1));
1139 }
1140 
1141 bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1142   // If a global variable does not have dynamic initialization we don't
1143   // have to instrument it.  However, if a global does not have initializer
1144   // at all, we assume it has dynamic initializer (in other TU).
1145   return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
1146 }
1147 
1148 void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1149     Instruction *I) {
1150   IRBuilder<> IRB(I);
1151   Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1152   Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
1153   for (Value *&i : Param) {
1154     if (i->getType()->isPointerTy())
1155       i = IRB.CreatePointerCast(i, IntptrTy);
1156   }
1157   IRB.CreateCall(F, Param);
1158 }
1159 
1160 static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,
1161                                 Instruction *InsertBefore, Value *Addr,
1162                                 unsigned Alignment, unsigned Granularity,
1163                                 uint32_t TypeSize, bool IsWrite,
1164                                 Value *SizeArgument, bool UseCalls,
1165                                 uint32_t Exp) {
1166   // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1167   // if the data is properly aligned.
1168   if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1169        TypeSize == 128) &&
1170       (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
1171     return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
1172                                    nullptr, UseCalls, Exp);
1173   Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
1174                                          IsWrite, nullptr, UseCalls, Exp);
1175 }
1176 
1177 static void instrumentMaskedLoadOrStore(AddressSanitizer *Pass,
1178                                         const DataLayout &DL, Type *IntptrTy,
1179                                         Value *Mask, Instruction *I,
1180                                         Value *Addr, unsigned Alignment,
1181                                         unsigned Granularity, uint32_t TypeSize,
1182                                         bool IsWrite, Value *SizeArgument,
1183                                         bool UseCalls, uint32_t Exp) {
1184   auto *VTy = cast<PointerType>(Addr->getType())->getElementType();
1185   uint64_t ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
1186   unsigned Num = VTy->getVectorNumElements();
1187   auto Zero = ConstantInt::get(IntptrTy, 0);
1188   for (unsigned Idx = 0; Idx < Num; ++Idx) {
1189     Value *InstrumentedAddress = nullptr;
1190     Instruction *InsertBefore = I;
1191     if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
1192       // dyn_cast as we might get UndefValue
1193       if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
1194         if (Masked->isNullValue())
1195           // Mask is constant false, so no instrumentation needed.
1196           continue;
1197         // If we have a true or undef value, fall through to doInstrumentAddress
1198         // with InsertBefore == I
1199       }
1200     } else {
1201       IRBuilder<> IRB(I);
1202       Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
1203       TerminatorInst *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
1204       InsertBefore = ThenTerm;
1205     }
1206 
1207     IRBuilder<> IRB(InsertBefore);
1208     InstrumentedAddress =
1209         IRB.CreateGEP(Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
1210     doInstrumentAddress(Pass, I, InsertBefore, InstrumentedAddress, Alignment,
1211                         Granularity, ElemTypeSize, IsWrite, SizeArgument,
1212                         UseCalls, Exp);
1213   }
1214 }
1215 
1216 void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
1217                                      Instruction *I, bool UseCalls,
1218                                      const DataLayout &DL) {
1219   bool IsWrite = false;
1220   unsigned Alignment = 0;
1221   uint64_t TypeSize = 0;
1222   Value *MaybeMask = nullptr;
1223   Value *Addr =
1224       isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
1225   assert(Addr);
1226 
1227   // Optimization experiments.
1228   // The experiments can be used to evaluate potential optimizations that remove
1229   // instrumentation (assess false negatives). Instead of completely removing
1230   // some instrumentation, you set Exp to a non-zero value (mask of optimization
1231   // experiments that want to remove instrumentation of this instruction).
1232   // If Exp is non-zero, this pass will emit special calls into runtime
1233   // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1234   // make runtime terminate the program in a special way (with a different
1235   // exit status). Then you run the new compiler on a buggy corpus, collect
1236   // the special terminations (ideally, you don't see them at all -- no false
1237   // negatives) and make the decision on the optimization.
1238   uint32_t Exp = ClForceExperiment;
1239 
1240   if (ClOpt && ClOptGlobals) {
1241     // If initialization order checking is disabled, a simple access to a
1242     // dynamically initialized global is always valid.
1243     GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
1244     if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
1245         isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1246       NumOptimizedAccessesToGlobalVar++;
1247       return;
1248     }
1249   }
1250 
1251   if (ClOpt && ClOptStack) {
1252     // A direct inbounds access to a stack variable is always valid.
1253     if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
1254         isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1255       NumOptimizedAccessesToStackVar++;
1256       return;
1257     }
1258   }
1259 
1260   if (IsWrite)
1261     NumInstrumentedWrites++;
1262   else
1263     NumInstrumentedReads++;
1264 
1265   unsigned Granularity = 1 << Mapping.Scale;
1266   if (MaybeMask) {
1267     instrumentMaskedLoadOrStore(this, DL, IntptrTy, MaybeMask, I, Addr,
1268                                 Alignment, Granularity, TypeSize, IsWrite,
1269                                 nullptr, UseCalls, Exp);
1270   } else {
1271     doInstrumentAddress(this, I, I, Addr, Alignment, Granularity, TypeSize,
1272                         IsWrite, nullptr, UseCalls, Exp);
1273   }
1274 }
1275 
1276 Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1277                                                  Value *Addr, bool IsWrite,
1278                                                  size_t AccessSizeIndex,
1279                                                  Value *SizeArgument,
1280                                                  uint32_t Exp) {
1281   IRBuilder<> IRB(InsertBefore);
1282   Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1283   CallInst *Call = nullptr;
1284   if (SizeArgument) {
1285     if (Exp == 0)
1286       Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1287                             {Addr, SizeArgument});
1288     else
1289       Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1290                             {Addr, SizeArgument, ExpVal});
1291   } else {
1292     if (Exp == 0)
1293       Call =
1294           IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1295     else
1296       Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1297                             {Addr, ExpVal});
1298   }
1299 
1300   // We don't do Call->setDoesNotReturn() because the BB already has
1301   // UnreachableInst at the end.
1302   // This EmptyAsm is required to avoid callback merge.
1303   IRB.CreateCall(EmptyAsm, {});
1304   return Call;
1305 }
1306 
1307 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
1308                                            Value *ShadowValue,
1309                                            uint32_t TypeSize) {
1310   size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
1311   // Addr & (Granularity - 1)
1312   Value *LastAccessedByte =
1313       IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
1314   // (Addr & (Granularity - 1)) + size - 1
1315   if (TypeSize / 8 > 1)
1316     LastAccessedByte = IRB.CreateAdd(
1317         LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1318   // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
1319   LastAccessedByte =
1320       IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
1321   // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1322   return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1323 }
1324 
1325 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
1326                                          Instruction *InsertBefore, Value *Addr,
1327                                          uint32_t TypeSize, bool IsWrite,
1328                                          Value *SizeArgument, bool UseCalls,
1329                                          uint32_t Exp) {
1330   IRBuilder<> IRB(InsertBefore);
1331   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1332   size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1333 
1334   if (UseCalls) {
1335     if (Exp == 0)
1336       IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1337                      AddrLong);
1338     else
1339       IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1340                      {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1341     return;
1342   }
1343 
1344   Type *ShadowTy =
1345       IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
1346   Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1347   Value *ShadowPtr = memToShadow(AddrLong, IRB);
1348   Value *CmpVal = Constant::getNullValue(ShadowTy);
1349   Value *ShadowValue =
1350       IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
1351 
1352   Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
1353   size_t Granularity = 1ULL << Mapping.Scale;
1354   TerminatorInst *CrashTerm = nullptr;
1355 
1356   if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
1357     // We use branch weights for the slow path check, to indicate that the slow
1358     // path is rarely taken. This seems to be the case for SPEC benchmarks.
1359     TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1360         Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
1361     assert(cast<BranchInst>(CheckTerm)->isUnconditional());
1362     BasicBlock *NextBB = CheckTerm->getSuccessor(0);
1363     IRB.SetInsertPoint(CheckTerm);
1364     Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
1365     if (Recover) {
1366       CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1367     } else {
1368       BasicBlock *CrashBlock =
1369         BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
1370       CrashTerm = new UnreachableInst(*C, CrashBlock);
1371       BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1372       ReplaceInstWithInst(CheckTerm, NewTerm);
1373     }
1374   } else {
1375     CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
1376   }
1377 
1378   Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
1379                                          AccessSizeIndex, SizeArgument, Exp);
1380   Crash->setDebugLoc(OrigIns->getDebugLoc());
1381 }
1382 
1383 // Instrument unusual size or unusual alignment.
1384 // We can not do it with a single check, so we do 1-byte check for the first
1385 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1386 // to report the actual access size.
1387 void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1388     Instruction *I, Instruction *InsertBefore, Value *Addr, uint32_t TypeSize,
1389     bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1390   IRBuilder<> IRB(InsertBefore);
1391   Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1392   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1393   if (UseCalls) {
1394     if (Exp == 0)
1395       IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1396                      {AddrLong, Size});
1397     else
1398       IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1399                      {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1400   } else {
1401     Value *LastByte = IRB.CreateIntToPtr(
1402         IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1403         Addr->getType());
1404     instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size, false, Exp);
1405     instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size, false, Exp);
1406   }
1407 }
1408 
1409 void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1410                                                   GlobalValue *ModuleName) {
1411   // Set up the arguments to our poison/unpoison functions.
1412   IRBuilder<> IRB(&GlobalInit.front(),
1413                   GlobalInit.front().getFirstInsertionPt());
1414 
1415   // Add a call to poison all external globals before the given function starts.
1416   Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1417   IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
1418 
1419   // Add calls to unpoison all globals before each return instruction.
1420   for (auto &BB : GlobalInit.getBasicBlockList())
1421     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1422       CallInst::Create(AsanUnpoisonGlobals, "", RI);
1423 }
1424 
1425 void AddressSanitizerModule::createInitializerPoisonCalls(
1426     Module &M, GlobalValue *ModuleName) {
1427   GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1428 
1429   ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1430   for (Use &OP : CA->operands()) {
1431     if (isa<ConstantAggregateZero>(OP)) continue;
1432     ConstantStruct *CS = cast<ConstantStruct>(OP);
1433 
1434     // Must have a function or null ptr.
1435     if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
1436       if (F->getName() == kAsanModuleCtorName) continue;
1437       ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1438       // Don't instrument CTORs that will run before asan.module_ctor.
1439       if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1440       poisonOneInitializer(*F, ModuleName);
1441     }
1442   }
1443 }
1444 
1445 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
1446   Type *Ty = G->getValueType();
1447   DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
1448 
1449   if (GlobalsMD.get(G).IsBlacklisted) return false;
1450   if (!Ty->isSized()) return false;
1451   if (!G->hasInitializer()) return false;
1452   if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
1453   // Touch only those globals that will not be defined in other modules.
1454   // Don't handle ODR linkage types and COMDATs since other modules may be built
1455   // without ASan.
1456   if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1457       G->getLinkage() != GlobalVariable::PrivateLinkage &&
1458       G->getLinkage() != GlobalVariable::InternalLinkage)
1459     return false;
1460   if (G->hasComdat()) return false;
1461   // Two problems with thread-locals:
1462   //   - The address of the main thread's copy can't be computed at link-time.
1463   //   - Need to poison all copies, not just the main thread's one.
1464   if (G->isThreadLocal()) return false;
1465   // For now, just ignore this Global if the alignment is large.
1466   if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
1467 
1468   if (G->hasSection()) {
1469     StringRef Section = G->getSection();
1470 
1471     // Globals from llvm.metadata aren't emitted, do not instrument them.
1472     if (Section == "llvm.metadata") return false;
1473     // Do not instrument globals from special LLVM sections.
1474     if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
1475 
1476     // Do not instrument function pointers to initialization and termination
1477     // routines: dynamic linker will not properly handle redzones.
1478     if (Section.startswith(".preinit_array") ||
1479         Section.startswith(".init_array") ||
1480         Section.startswith(".fini_array")) {
1481       return false;
1482     }
1483 
1484     // Callbacks put into the CRT initializer/terminator sections
1485     // should not be instrumented.
1486     // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1487     // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1488     if (Section.startswith(".CRT")) {
1489       DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1490       return false;
1491     }
1492 
1493     if (TargetTriple.isOSBinFormatMachO()) {
1494       StringRef ParsedSegment, ParsedSection;
1495       unsigned TAA = 0, StubSize = 0;
1496       bool TAAParsed;
1497       std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1498           Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
1499       assert(ErrorCode.empty() && "Invalid section specifier.");
1500 
1501       // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1502       // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1503       // them.
1504       if (ParsedSegment == "__OBJC" ||
1505           (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1506         DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1507         return false;
1508       }
1509       // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1510       // Constant CFString instances are compiled in the following way:
1511       //  -- the string buffer is emitted into
1512       //     __TEXT,__cstring,cstring_literals
1513       //  -- the constant NSConstantString structure referencing that buffer
1514       //     is placed into __DATA,__cfstring
1515       // Therefore there's no point in placing redzones into __DATA,__cfstring.
1516       // Moreover, it causes the linker to crash on OS X 10.7
1517       if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1518         DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1519         return false;
1520       }
1521       // The linker merges the contents of cstring_literals and removes the
1522       // trailing zeroes.
1523       if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1524         DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1525         return false;
1526       }
1527     }
1528   }
1529 
1530   return true;
1531 }
1532 
1533 // On Mach-O platforms, we emit global metadata in a separate section of the
1534 // binary in order to allow the linker to properly dead strip. This is only
1535 // supported on recent versions of ld64.
1536 bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
1537   if (!ClUseMachOGlobalsSection)
1538     return false;
1539 
1540   if (!TargetTriple.isOSBinFormatMachO())
1541     return false;
1542 
1543   if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1544     return true;
1545   if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
1546     return true;
1547   if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1548     return true;
1549 
1550   return false;
1551 }
1552 
1553 StringRef AddressSanitizerModule::getGlobalMetadataSection() const {
1554   switch (TargetTriple.getObjectFormat()) {
1555   case Triple::COFF:  return ".ASAN$GL";
1556   case Triple::ELF:   return "asan_globals";
1557   case Triple::MachO: return "__DATA,__asan_globals,regular";
1558   default: break;
1559   }
1560   llvm_unreachable("unsupported object format");
1561 }
1562 
1563 void AddressSanitizerModule::initializeCallbacks(Module &M) {
1564   IRBuilder<> IRB(*C);
1565 
1566   // Declare our poisoning and unpoisoning functions.
1567   AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1568       kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
1569   AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1570   AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1571       kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
1572   AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1573 
1574   // Declare functions that register/unregister globals.
1575   AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1576       kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1577   AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1578   AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
1579       M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1580                             IntptrTy, IntptrTy, nullptr));
1581   AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1582 
1583   // Declare the functions that find globals in a shared object and then invoke
1584   // the (un)register function on them.
1585   AsanRegisterImageGlobals =
1586       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1587           kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
1588   AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
1589 
1590   AsanUnregisterImageGlobals =
1591       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1592           kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
1593   AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
1594 }
1595 
1596 // Put the metadata and the instrumented global in the same group. This ensures
1597 // that the metadata is discarded if the instrumented global is discarded.
1598 void AddressSanitizerModule::SetComdatForGlobalMetadata(
1599     GlobalVariable *G, GlobalVariable *Metadata) {
1600   Module &M = *G->getParent();
1601   Comdat *C = G->getComdat();
1602   if (!C) {
1603     if (!G->hasName()) {
1604       // If G is unnamed, it must be internal. Give it an artificial name
1605       // so we can put it in a comdat.
1606       assert(G->hasLocalLinkage());
1607       G->setName(Twine(kAsanGenPrefix) + "_anon_global");
1608     }
1609     C = M.getOrInsertComdat(G->getName());
1610     // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF.
1611     if (TargetTriple.isOSBinFormatCOFF())
1612       C->setSelectionKind(Comdat::NoDuplicates);
1613     G->setComdat(C);
1614   }
1615 
1616   assert(G->hasComdat());
1617   Metadata->setComdat(G->getComdat());
1618 }
1619 
1620 // Create a separate metadata global and put it in the appropriate ASan
1621 // global registration section.
1622 GlobalVariable *
1623 AddressSanitizerModule::CreateMetadataGlobal(Module &M, Constant *Initializer,
1624                                              StringRef OriginalName) {
1625   GlobalVariable *Metadata =
1626       new GlobalVariable(M, Initializer->getType(), false,
1627                          GlobalVariable::InternalLinkage, Initializer,
1628                          Twine("__asan_global_") +
1629                              GlobalValue::getRealLinkageName(OriginalName));
1630   Metadata->setSection(getGlobalMetadataSection());
1631   return Metadata;
1632 }
1633 
1634 IRBuilder<> AddressSanitizerModule::CreateAsanModuleDtor(Module &M) {
1635   Function *AsanDtorFunction =
1636       Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1637                        GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1638   BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1639   appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
1640 
1641   return IRBuilder<>(ReturnInst::Create(*C, AsanDtorBB));
1642 }
1643 
1644 void AddressSanitizerModule::InstrumentGlobalsCOFF(
1645     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1646     ArrayRef<Constant *> MetadataInitializers) {
1647   assert(ExtendedGlobals.size() == MetadataInitializers.size());
1648   auto &DL = M.getDataLayout();
1649 
1650   for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1651     Constant *Initializer = MetadataInitializers[i];
1652     GlobalVariable *G = ExtendedGlobals[i];
1653     GlobalVariable *Metadata =
1654         CreateMetadataGlobal(M, Initializer, G->getName());
1655 
1656     // The MSVC linker always inserts padding when linking incrementally. We
1657     // cope with that by aligning each struct to its size, which must be a power
1658     // of two.
1659     unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
1660     assert(isPowerOf2_32(SizeOfGlobalStruct) &&
1661            "global metadata will not be padded appropriately");
1662     Metadata->setAlignment(SizeOfGlobalStruct);
1663 
1664     SetComdatForGlobalMetadata(G, Metadata);
1665   }
1666 }
1667 
1668 void AddressSanitizerModule::InstrumentGlobalsMachO(
1669     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1670     ArrayRef<Constant *> MetadataInitializers) {
1671   assert(ExtendedGlobals.size() == MetadataInitializers.size());
1672 
1673   // On recent Mach-O platforms, use a structure which binds the liveness of
1674   // the global variable to the metadata struct. Keep the list of "Liveness" GV
1675   // created to be added to llvm.compiler.used
1676   StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy, nullptr);
1677   SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
1678 
1679   for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1680     Constant *Initializer = MetadataInitializers[i];
1681     GlobalVariable *G = ExtendedGlobals[i];
1682     GlobalVariable *Metadata =
1683         CreateMetadataGlobal(M, Initializer, G->getName());
1684 
1685     // On recent Mach-O platforms, we emit the global metadata in a way that
1686     // allows the linker to properly strip dead globals.
1687     auto LivenessBinder = ConstantStruct::get(
1688         LivenessTy, Initializer->getAggregateElement(0u),
1689         ConstantExpr::getPointerCast(Metadata, IntptrTy), nullptr);
1690     GlobalVariable *Liveness = new GlobalVariable(
1691         M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
1692         Twine("__asan_binder_") + G->getName());
1693     Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1694     LivenessGlobals[i] = Liveness;
1695   }
1696 
1697   // Update llvm.compiler.used, adding the new liveness globals. This is
1698   // needed so that during LTO these variables stay alive. The alternative
1699   // would be to have the linker handling the LTO symbols, but libLTO
1700   // current API does not expose access to the section for each symbol.
1701   if (!LivenessGlobals.empty())
1702     appendToCompilerUsed(M, LivenessGlobals);
1703 
1704   // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1705   // to look up the loaded image that contains it. Second, we can store in it
1706   // whether registration has already occurred, to prevent duplicate
1707   // registration.
1708   //
1709   // common linkage ensures that there is only one global per shared library.
1710   GlobalVariable *RegisteredFlag = new GlobalVariable(
1711       M, IntptrTy, false, GlobalVariable::CommonLinkage,
1712       ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1713   RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1714 
1715   IRB.CreateCall(AsanRegisterImageGlobals,
1716                  {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1717 
1718   // We also need to unregister globals at the end, e.g., when a shared library
1719   // gets closed.
1720   IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1721   IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1722                       {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1723 }
1724 
1725 void AddressSanitizerModule::InstrumentGlobalsWithMetadataArray(
1726     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1727     ArrayRef<Constant *> MetadataInitializers) {
1728   assert(ExtendedGlobals.size() == MetadataInitializers.size());
1729   unsigned N = ExtendedGlobals.size();
1730   assert(N > 0);
1731 
1732   // On platforms that don't have a custom metadata section, we emit an array
1733   // of global metadata structures.
1734   ArrayType *ArrayOfGlobalStructTy =
1735       ArrayType::get(MetadataInitializers[0]->getType(), N);
1736   auto AllGlobals = new GlobalVariable(
1737       M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1738       ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
1739 
1740   IRB.CreateCall(AsanRegisterGlobals,
1741                  {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1742                   ConstantInt::get(IntptrTy, N)});
1743 
1744   // We also need to unregister globals at the end, e.g., when a shared library
1745   // gets closed.
1746   IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1747   IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1748                       {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1749                        ConstantInt::get(IntptrTy, N)});
1750 }
1751 
1752 // This function replaces all global variables with new variables that have
1753 // trailing redzones. It also creates a function that poisons
1754 // redzones and inserts this function into llvm.global_ctors.
1755 bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
1756   GlobalsMD.init(M);
1757 
1758   SmallVector<GlobalVariable *, 16> GlobalsToChange;
1759 
1760   for (auto &G : M.globals()) {
1761     if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
1762   }
1763 
1764   size_t n = GlobalsToChange.size();
1765   if (n == 0) return false;
1766 
1767   auto &DL = M.getDataLayout();
1768 
1769   // A global is described by a structure
1770   //   size_t beg;
1771   //   size_t size;
1772   //   size_t size_with_redzone;
1773   //   const char *name;
1774   //   const char *module_name;
1775   //   size_t has_dynamic_init;
1776   //   void *source_location;
1777   //   size_t odr_indicator;
1778   // We initialize an array of such structures and pass it to a run-time call.
1779   StructType *GlobalStructTy =
1780       StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
1781                       IntptrTy, IntptrTy, IntptrTy, nullptr);
1782   SmallVector<GlobalVariable *, 16> NewGlobals(n);
1783   SmallVector<Constant *, 16> Initializers(n);
1784 
1785   bool HasDynamicallyInitializedGlobals = false;
1786 
1787   // We shouldn't merge same module names, as this string serves as unique
1788   // module ID in runtime.
1789   GlobalVariable *ModuleName = createPrivateGlobalForString(
1790       M, M.getModuleIdentifier(), /*AllowMerging*/ false);
1791 
1792   for (size_t i = 0; i < n; i++) {
1793     static const uint64_t kMaxGlobalRedzone = 1 << 18;
1794     GlobalVariable *G = GlobalsToChange[i];
1795 
1796     auto MD = GlobalsMD.get(G);
1797     StringRef NameForGlobal = G->getName();
1798     // Create string holding the global name (use global name from metadata
1799     // if it's available, otherwise just write the name of global variable).
1800     GlobalVariable *Name = createPrivateGlobalForString(
1801         M, MD.Name.empty() ? NameForGlobal : MD.Name,
1802         /*AllowMerging*/ true);
1803 
1804     Type *Ty = G->getValueType();
1805     uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
1806     uint64_t MinRZ = MinRedzoneSizeForGlobal();
1807     // MinRZ <= RZ <= kMaxGlobalRedzone
1808     // and trying to make RZ to be ~ 1/4 of SizeInBytes.
1809     uint64_t RZ = std::max(
1810         MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
1811     uint64_t RightRedzoneSize = RZ;
1812     // Round up to MinRZ
1813     if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1814     assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
1815     Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1816 
1817     StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
1818     Constant *NewInitializer =
1819         ConstantStruct::get(NewTy, G->getInitializer(),
1820                             Constant::getNullValue(RightRedZoneTy), nullptr);
1821 
1822     // Create a new global variable with enough space for a redzone.
1823     GlobalValue::LinkageTypes Linkage = G->getLinkage();
1824     if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1825       Linkage = GlobalValue::InternalLinkage;
1826     GlobalVariable *NewGlobal =
1827         new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1828                            "", G, G->getThreadLocalMode());
1829     NewGlobal->copyAttributesFrom(G);
1830     NewGlobal->setAlignment(MinRZ);
1831 
1832     // Move null-terminated C strings to "__asan_cstring" section on Darwin.
1833     if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
1834         G->isConstant()) {
1835       auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
1836       if (Seq && Seq->isCString())
1837         NewGlobal->setSection("__TEXT,__asan_cstring,regular");
1838     }
1839 
1840     // Transfer the debug info.  The payload starts at offset zero so we can
1841     // copy the debug info over as is.
1842     SmallVector<DIGlobalVariableExpression *, 1> GVs;
1843     G->getDebugInfo(GVs);
1844     for (auto *GV : GVs)
1845       NewGlobal->addDebugInfo(GV);
1846 
1847     Value *Indices2[2];
1848     Indices2[0] = IRB.getInt32(0);
1849     Indices2[1] = IRB.getInt32(0);
1850 
1851     G->replaceAllUsesWith(
1852         ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
1853     NewGlobal->takeName(G);
1854     G->eraseFromParent();
1855     NewGlobals[i] = NewGlobal;
1856 
1857     Constant *SourceLoc;
1858     if (!MD.SourceLoc.empty()) {
1859       auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1860       SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1861     } else {
1862       SourceLoc = ConstantInt::get(IntptrTy, 0);
1863     }
1864 
1865     Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
1866     GlobalValue *InstrumentedGlobal = NewGlobal;
1867 
1868     bool CanUsePrivateAliases =
1869         TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
1870         TargetTriple.isOSBinFormatWasm();
1871     if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
1872       // Create local alias for NewGlobal to avoid crash on ODR between
1873       // instrumented and non-instrumented libraries.
1874       auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
1875                                      NameForGlobal + M.getName(), NewGlobal);
1876 
1877       // With local aliases, we need to provide another externally visible
1878       // symbol __odr_asan_XXX to detect ODR violation.
1879       auto *ODRIndicatorSym =
1880           new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
1881                              Constant::getNullValue(IRB.getInt8Ty()),
1882                              kODRGenPrefix + NameForGlobal, nullptr,
1883                              NewGlobal->getThreadLocalMode());
1884 
1885       // Set meaningful attributes for indicator symbol.
1886       ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
1887       ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
1888       ODRIndicatorSym->setAlignment(1);
1889       ODRIndicator = ODRIndicatorSym;
1890       InstrumentedGlobal = GA;
1891     }
1892 
1893     Constant *Initializer = ConstantStruct::get(
1894         GlobalStructTy,
1895         ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
1896         ConstantInt::get(IntptrTy, SizeInBytes),
1897         ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1898         ConstantExpr::getPointerCast(Name, IntptrTy),
1899         ConstantExpr::getPointerCast(ModuleName, IntptrTy),
1900         ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
1901         ConstantExpr::getPointerCast(ODRIndicator, IntptrTy), nullptr);
1902 
1903     if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
1904 
1905     DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
1906 
1907     Initializers[i] = Initializer;
1908   }
1909 
1910   if (TargetTriple.isOSBinFormatCOFF()) {
1911     InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
1912   } else if (ShouldUseMachOGlobalsSection()) {
1913     InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
1914   } else {
1915     InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
1916   }
1917 
1918   // Create calls for poisoning before initializers run and unpoisoning after.
1919   if (HasDynamicallyInitializedGlobals)
1920     createInitializerPoisonCalls(M, ModuleName);
1921 
1922   DEBUG(dbgs() << M);
1923   return true;
1924 }
1925 
1926 bool AddressSanitizerModule::runOnModule(Module &M) {
1927   C = &(M.getContext());
1928   int LongSize = M.getDataLayout().getPointerSizeInBits();
1929   IntptrTy = Type::getIntNTy(*C, LongSize);
1930   TargetTriple = Triple(M.getTargetTriple());
1931   Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
1932   initializeCallbacks(M);
1933 
1934   bool Changed = false;
1935 
1936   // TODO(glider): temporarily disabled globals instrumentation for KASan.
1937   if (ClGlobals && !CompileKernel) {
1938     Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1939     assert(CtorFunc);
1940     IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1941     Changed |= InstrumentGlobals(IRB, M);
1942   }
1943 
1944   return Changed;
1945 }
1946 
1947 void AddressSanitizer::initializeCallbacks(Module &M) {
1948   IRBuilder<> IRB(*C);
1949   // Create __asan_report* callbacks.
1950   // IsWrite, TypeSize and Exp are encoded in the function name.
1951   for (int Exp = 0; Exp < 2; Exp++) {
1952     for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1953       const std::string TypeStr = AccessIsWrite ? "store" : "load";
1954       const std::string ExpStr = Exp ? "exp_" : "";
1955       const std::string SuffixStr = CompileKernel ? "N" : "_n";
1956       const std::string EndingStr = Recover ? "_noabort" : "";
1957       Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
1958       AsanErrorCallbackSized[AccessIsWrite][Exp] =
1959           checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1960               kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr + EndingStr,
1961               IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1962       AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
1963           checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1964               ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
1965               IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1966       for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1967            AccessSizeIndex++) {
1968         const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
1969         AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
1970             checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1971                 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
1972                 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
1973         AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
1974             checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1975                 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1976                 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
1977       }
1978     }
1979   }
1980 
1981   const std::string MemIntrinCallbackPrefix =
1982       CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
1983   AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1984       MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
1985       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1986   AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1987       MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
1988       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1989   AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1990       MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
1991       IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
1992 
1993   AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
1994       M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
1995 
1996   AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1997       kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1998   AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1999       kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
2000   // We insert an empty inline asm after __asan_report* to avoid callback merge.
2001   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
2002                             StringRef(""), StringRef(""),
2003                             /*hasSideEffects=*/true);
2004 }
2005 
2006 // virtual
2007 bool AddressSanitizer::doInitialization(Module &M) {
2008   // Initialize the private fields. No one has accessed them before.
2009 
2010   GlobalsMD.init(M);
2011 
2012   C = &(M.getContext());
2013   LongSize = M.getDataLayout().getPointerSizeInBits();
2014   IntptrTy = Type::getIntNTy(*C, LongSize);
2015   TargetTriple = Triple(M.getTargetTriple());
2016 
2017   if (!CompileKernel) {
2018     std::tie(AsanCtorFunction, AsanInitFunction) =
2019         createSanitizerCtorAndInitFunctions(
2020             M, kAsanModuleCtorName, kAsanInitName,
2021             /*InitArgTypes=*/{}, /*InitArgs=*/{}, kAsanVersionCheckName);
2022     appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
2023   }
2024   Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
2025   return true;
2026 }
2027 
2028 bool AddressSanitizer::doFinalization(Module &M) {
2029   GlobalsMD.reset();
2030   return false;
2031 }
2032 
2033 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2034   // For each NSObject descendant having a +load method, this method is invoked
2035   // by the ObjC runtime before any of the static constructors is called.
2036   // Therefore we need to instrument such methods with a call to __asan_init
2037   // at the beginning in order to initialize our runtime before any access to
2038   // the shadow memory.
2039   // We cannot just ignore these methods, because they may call other
2040   // instrumented functions.
2041   if (F.getName().find(" load]") != std::string::npos) {
2042     IRBuilder<> IRB(&F.front(), F.front().begin());
2043     IRB.CreateCall(AsanInitFunction, {});
2044     return true;
2045   }
2046   return false;
2047 }
2048 
2049 void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2050   // Generate code only when dynamic addressing is needed.
2051   if (Mapping.Offset != kDynamicShadowSentinel)
2052     return;
2053 
2054   IRBuilder<> IRB(&F.front().front());
2055   Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2056       kAsanShadowMemoryDynamicAddress, IntptrTy);
2057   LocalDynamicShadow = IRB.CreateLoad(GlobalDynamicAddress);
2058 }
2059 
2060 void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2061   // Find the one possible call to llvm.localescape and pre-mark allocas passed
2062   // to it as uninteresting. This assumes we haven't started processing allocas
2063   // yet. This check is done up front because iterating the use list in
2064   // isInterestingAlloca would be algorithmically slower.
2065   assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2066 
2067   // Try to get the declaration of llvm.localescape. If it's not in the module,
2068   // we can exit early.
2069   if (!F.getParent()->getFunction("llvm.localescape")) return;
2070 
2071   // Look for a call to llvm.localescape call in the entry block. It can't be in
2072   // any other block.
2073   for (Instruction &I : F.getEntryBlock()) {
2074     IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2075     if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2076       // We found a call. Mark all the allocas passed in as uninteresting.
2077       for (Value *Arg : II->arg_operands()) {
2078         AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2079         assert(AI && AI->isStaticAlloca() &&
2080                "non-static alloca arg to localescape");
2081         ProcessedAllocas[AI] = false;
2082       }
2083       break;
2084     }
2085   }
2086 }
2087 
2088 bool AddressSanitizer::runOnFunction(Function &F) {
2089   if (&F == AsanCtorFunction) return false;
2090   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
2091   if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
2092   if (F.getName().startswith("__asan_")) return false;
2093 
2094   bool FunctionModified = false;
2095 
2096   // If needed, insert __asan_init before checking for SanitizeAddress attr.
2097   // This function needs to be called even if the function body is not
2098   // instrumented.
2099   if (maybeInsertAsanInitAtFunctionEntry(F))
2100     FunctionModified = true;
2101 
2102   // Leave if the function doesn't need instrumentation.
2103   if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
2104 
2105   DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
2106 
2107   initializeCallbacks(*F.getParent());
2108   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2109 
2110   FunctionStateRAII CleanupObj(this);
2111 
2112   maybeInsertDynamicShadowAtFunctionEntry(F);
2113 
2114   // We can't instrument allocas used with llvm.localescape. Only static allocas
2115   // can be passed to that intrinsic.
2116   markEscapedLocalAllocas(F);
2117 
2118   // We want to instrument every address only once per basic block (unless there
2119   // are calls between uses).
2120   SmallSet<Value *, 16> TempsToInstrument;
2121   SmallVector<Instruction *, 16> ToInstrument;
2122   SmallVector<Instruction *, 8> NoReturnCalls;
2123   SmallVector<BasicBlock *, 16> AllBlocks;
2124   SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
2125   int NumAllocas = 0;
2126   bool IsWrite;
2127   unsigned Alignment;
2128   uint64_t TypeSize;
2129   const TargetLibraryInfo *TLI =
2130       &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
2131 
2132   // Fill the set of memory operations to instrument.
2133   for (auto &BB : F) {
2134     AllBlocks.push_back(&BB);
2135     TempsToInstrument.clear();
2136     int NumInsnsPerBB = 0;
2137     for (auto &Inst : BB) {
2138       if (LooksLikeCodeInBug11395(&Inst)) return false;
2139       Value *MaybeMask = nullptr;
2140       if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
2141                                                   &Alignment, &MaybeMask)) {
2142         if (ClOpt && ClOptSameTemp) {
2143           // If we have a mask, skip instrumentation if we've already
2144           // instrumented the full object. But don't add to TempsToInstrument
2145           // because we might get another load/store with a different mask.
2146           if (MaybeMask) {
2147             if (TempsToInstrument.count(Addr))
2148               continue; // We've seen this (whole) temp in the current BB.
2149           } else {
2150             if (!TempsToInstrument.insert(Addr).second)
2151               continue; // We've seen this temp in the current BB.
2152           }
2153         }
2154       } else if (ClInvalidPointerPairs &&
2155                  isInterestingPointerComparisonOrSubtraction(&Inst)) {
2156         PointerComparisonsOrSubtracts.push_back(&Inst);
2157         continue;
2158       } else if (isa<MemIntrinsic>(Inst)) {
2159         // ok, take it.
2160       } else {
2161         if (isa<AllocaInst>(Inst)) NumAllocas++;
2162         CallSite CS(&Inst);
2163         if (CS) {
2164           // A call inside BB.
2165           TempsToInstrument.clear();
2166           if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
2167         }
2168         if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2169           maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
2170         continue;
2171       }
2172       ToInstrument.push_back(&Inst);
2173       NumInsnsPerBB++;
2174       if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
2175     }
2176   }
2177 
2178   bool UseCalls =
2179       CompileKernel ||
2180       (ClInstrumentationWithCallsThreshold >= 0 &&
2181        ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
2182   const DataLayout &DL = F.getParent()->getDataLayout();
2183   ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
2184                                      /*RoundToAlign=*/true);
2185 
2186   // Instrument.
2187   int NumInstrumented = 0;
2188   for (auto Inst : ToInstrument) {
2189     if (ClDebugMin < 0 || ClDebugMax < 0 ||
2190         (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
2191       if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
2192         instrumentMop(ObjSizeVis, Inst, UseCalls,
2193                       F.getParent()->getDataLayout());
2194       else
2195         instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
2196     }
2197     NumInstrumented++;
2198   }
2199 
2200   FunctionStackPoisoner FSP(F, *this);
2201   bool ChangedStack = FSP.runOnFunction();
2202 
2203   // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
2204   // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
2205   for (auto CI : NoReturnCalls) {
2206     IRBuilder<> IRB(CI);
2207     IRB.CreateCall(AsanHandleNoReturnFunc, {});
2208   }
2209 
2210   for (auto Inst : PointerComparisonsOrSubtracts) {
2211     instrumentPointerComparisonOrSubtraction(Inst);
2212     NumInstrumented++;
2213   }
2214 
2215   if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
2216     FunctionModified = true;
2217 
2218   DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2219                << F << "\n");
2220 
2221   return FunctionModified;
2222 }
2223 
2224 // Workaround for bug 11395: we don't want to instrument stack in functions
2225 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2226 // FIXME: remove once the bug 11395 is fixed.
2227 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2228   if (LongSize != 32) return false;
2229   CallInst *CI = dyn_cast<CallInst>(I);
2230   if (!CI || !CI->isInlineAsm()) return false;
2231   if (CI->getNumArgOperands() <= 5) return false;
2232   // We have inline assembly with quite a few arguments.
2233   return true;
2234 }
2235 
2236 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2237   IRBuilder<> IRB(*C);
2238   for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
2239     std::string Suffix = itostr(i);
2240     AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
2241         M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
2242                               IntptrTy, nullptr));
2243     AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
2244         M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
2245                               IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
2246   }
2247   if (ASan.UseAfterScope) {
2248     AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2249         M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
2250                               IntptrTy, IntptrTy, nullptr));
2251     AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2252         M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
2253                               IntptrTy, IntptrTy, nullptr));
2254   }
2255 
2256   for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2257     std::ostringstream Name;
2258     Name << kAsanSetShadowPrefix;
2259     Name << std::setw(2) << std::setfill('0') << std::hex << Val;
2260     AsanSetShadowFunc[Val] =
2261         checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2262             Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
2263   }
2264 
2265   AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2266       kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
2267   AsanAllocasUnpoisonFunc =
2268       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2269           kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
2270 }
2271 
2272 void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2273                                                ArrayRef<uint8_t> ShadowBytes,
2274                                                size_t Begin, size_t End,
2275                                                IRBuilder<> &IRB,
2276                                                Value *ShadowBase) {
2277   if (Begin >= End)
2278     return;
2279 
2280   const size_t LargestStoreSizeInBytes =
2281       std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2282 
2283   const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2284 
2285   // Poison given range in shadow using larges store size with out leading and
2286   // trailing zeros in ShadowMask. Zeros never change, so they need neither
2287   // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2288   // middle of a store.
2289   for (size_t i = Begin; i < End;) {
2290     if (!ShadowMask[i]) {
2291       assert(!ShadowBytes[i]);
2292       ++i;
2293       continue;
2294     }
2295 
2296     size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2297     // Fit store size into the range.
2298     while (StoreSizeInBytes > End - i)
2299       StoreSizeInBytes /= 2;
2300 
2301     // Minimize store size by trimming trailing zeros.
2302     for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
2303       while (j <= StoreSizeInBytes / 2)
2304         StoreSizeInBytes /= 2;
2305     }
2306 
2307     uint64_t Val = 0;
2308     for (size_t j = 0; j < StoreSizeInBytes; j++) {
2309       if (IsLittleEndian)
2310         Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2311       else
2312         Val = (Val << 8) | ShadowBytes[i + j];
2313     }
2314 
2315     Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2316     Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
2317     IRB.CreateAlignedStore(
2318         Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
2319 
2320     i += StoreSizeInBytes;
2321   }
2322 }
2323 
2324 void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2325                                          ArrayRef<uint8_t> ShadowBytes,
2326                                          IRBuilder<> &IRB, Value *ShadowBase) {
2327   copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2328 }
2329 
2330 void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2331                                          ArrayRef<uint8_t> ShadowBytes,
2332                                          size_t Begin, size_t End,
2333                                          IRBuilder<> &IRB, Value *ShadowBase) {
2334   assert(ShadowMask.size() == ShadowBytes.size());
2335   size_t Done = Begin;
2336   for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2337     if (!ShadowMask[i]) {
2338       assert(!ShadowBytes[i]);
2339       continue;
2340     }
2341     uint8_t Val = ShadowBytes[i];
2342     if (!AsanSetShadowFunc[Val])
2343       continue;
2344 
2345     // Skip same values.
2346     for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
2347     }
2348 
2349     if (j - i >= ClMaxInlinePoisoningSize) {
2350       copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
2351       IRB.CreateCall(AsanSetShadowFunc[Val],
2352                      {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2353                       ConstantInt::get(IntptrTy, j - i)});
2354       Done = j;
2355     }
2356   }
2357 
2358   copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
2359 }
2360 
2361 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
2362 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2363 static int StackMallocSizeClass(uint64_t LocalStackSize) {
2364   assert(LocalStackSize <= kMaxStackMallocSize);
2365   uint64_t MaxSize = kMinStackMallocSize;
2366   for (int i = 0;; i++, MaxSize *= 2)
2367     if (LocalStackSize <= MaxSize) return i;
2368   llvm_unreachable("impossible LocalStackSize");
2369 }
2370 
2371 PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2372                                           Value *ValueIfTrue,
2373                                           Instruction *ThenTerm,
2374                                           Value *ValueIfFalse) {
2375   PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2376   BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2377   PHI->addIncoming(ValueIfFalse, CondBlock);
2378   BasicBlock *ThenBlock = ThenTerm->getParent();
2379   PHI->addIncoming(ValueIfTrue, ThenBlock);
2380   return PHI;
2381 }
2382 
2383 Value *FunctionStackPoisoner::createAllocaForLayout(
2384     IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2385   AllocaInst *Alloca;
2386   if (Dynamic) {
2387     Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2388                               ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2389                               "MyAlloca");
2390   } else {
2391     Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2392                               nullptr, "MyAlloca");
2393     assert(Alloca->isStaticAlloca());
2394   }
2395   assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2396   size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2397   Alloca->setAlignment(FrameAlignment);
2398   return IRB.CreatePointerCast(Alloca, IntptrTy);
2399 }
2400 
2401 void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2402   BasicBlock &FirstBB = *F.begin();
2403   IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2404   DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2405   IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2406   DynamicAllocaLayout->setAlignment(32);
2407 }
2408 
2409 void FunctionStackPoisoner::processDynamicAllocas() {
2410   if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2411     assert(DynamicAllocaPoisonCallVec.empty());
2412     return;
2413   }
2414 
2415   // Insert poison calls for lifetime intrinsics for dynamic allocas.
2416   for (const auto &APC : DynamicAllocaPoisonCallVec) {
2417     assert(APC.InsBefore);
2418     assert(APC.AI);
2419     assert(ASan.isInterestingAlloca(*APC.AI));
2420     assert(!APC.AI->isStaticAlloca());
2421 
2422     IRBuilder<> IRB(APC.InsBefore);
2423     poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
2424     // Dynamic allocas will be unpoisoned unconditionally below in
2425     // unpoisonDynamicAllocas.
2426     // Flag that we need unpoison static allocas.
2427   }
2428 
2429   // Handle dynamic allocas.
2430   createDynamicAllocasInitStorage();
2431   for (auto &AI : DynamicAllocaVec)
2432     handleDynamicAllocaCall(AI);
2433   unpoisonDynamicAllocas();
2434 }
2435 
2436 void FunctionStackPoisoner::processStaticAllocas() {
2437   if (AllocaVec.empty()) {
2438     assert(StaticAllocaPoisonCallVec.empty());
2439     return;
2440   }
2441 
2442   int StackMallocIdx = -1;
2443   DebugLoc EntryDebugLocation;
2444   if (auto SP = F.getSubprogram())
2445     EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
2446 
2447   Instruction *InsBefore = AllocaVec[0];
2448   IRBuilder<> IRB(InsBefore);
2449   IRB.SetCurrentDebugLocation(EntryDebugLocation);
2450 
2451   // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2452   // debug info is broken, because only entry-block allocas are treated as
2453   // regular stack slots.
2454   auto InsBeforeB = InsBefore->getParent();
2455   assert(InsBeforeB == &F.getEntryBlock());
2456   for (auto *AI : StaticAllocasToMoveUp)
2457     if (AI->getParent() == InsBeforeB)
2458       AI->moveBefore(InsBefore);
2459 
2460   // If we have a call to llvm.localescape, keep it in the entry block.
2461   if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2462 
2463   SmallVector<ASanStackVariableDescription, 16> SVD;
2464   SVD.reserve(AllocaVec.size());
2465   for (AllocaInst *AI : AllocaVec) {
2466     ASanStackVariableDescription D = {AI->getName().data(),
2467                                       ASan.getAllocaSizeInBytes(*AI),
2468                                       0,
2469                                       AI->getAlignment(),
2470                                       AI,
2471                                       0,
2472                                       0};
2473     SVD.push_back(D);
2474   }
2475 
2476   // Minimal header size (left redzone) is 4 pointers,
2477   // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2478   size_t MinHeaderSize = ASan.LongSize / 2;
2479   const ASanStackFrameLayout &L =
2480       ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize);
2481 
2482   // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
2483   DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
2484   for (auto &Desc : SVD)
2485     AllocaToSVDMap[Desc.AI] = &Desc;
2486 
2487   // Update SVD with information from lifetime intrinsics.
2488   for (const auto &APC : StaticAllocaPoisonCallVec) {
2489     assert(APC.InsBefore);
2490     assert(APC.AI);
2491     assert(ASan.isInterestingAlloca(*APC.AI));
2492     assert(APC.AI->isStaticAlloca());
2493 
2494     ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
2495     Desc.LifetimeSize = Desc.Size;
2496     if (const DILocation *FnLoc = EntryDebugLocation.get()) {
2497       if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
2498         if (LifetimeLoc->getFile() == FnLoc->getFile())
2499           if (unsigned Line = LifetimeLoc->getLine())
2500             Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
2501       }
2502     }
2503   }
2504 
2505   auto DescriptionString = ComputeASanStackFrameDescription(SVD);
2506   DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
2507   uint64_t LocalStackSize = L.FrameSize;
2508   bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2509                        LocalStackSize <= kMaxStackMallocSize;
2510   bool DoDynamicAlloca = ClDynamicAllocaStack;
2511   // Don't do dynamic alloca or stack malloc if:
2512   // 1) There is inline asm: too often it makes assumptions on which registers
2513   //    are available.
2514   // 2) There is a returns_twice call (typically setjmp), which is
2515   //    optimization-hostile, and doesn't play well with introduced indirect
2516   //    register-relative calculation of local variable addresses.
2517   DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2518   DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2519 
2520   Value *StaticAlloca =
2521       DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2522 
2523   Value *FakeStack;
2524   Value *LocalStackBase;
2525 
2526   if (DoStackMalloc) {
2527     // void *FakeStack = __asan_option_detect_stack_use_after_return
2528     //     ? __asan_stack_malloc_N(LocalStackSize)
2529     //     : nullptr;
2530     // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
2531     Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2532         kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2533     Value *UseAfterReturnIsEnabled =
2534         IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
2535                          Constant::getNullValue(IRB.getInt32Ty()));
2536     Instruction *Term =
2537         SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
2538     IRBuilder<> IRBIf(Term);
2539     IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2540     StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2541     assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2542     Value *FakeStackValue =
2543         IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2544                          ConstantInt::get(IntptrTy, LocalStackSize));
2545     IRB.SetInsertPoint(InsBefore);
2546     IRB.SetCurrentDebugLocation(EntryDebugLocation);
2547     FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
2548                           ConstantInt::get(IntptrTy, 0));
2549 
2550     Value *NoFakeStack =
2551         IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2552     Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2553     IRBIf.SetInsertPoint(Term);
2554     IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2555     Value *AllocaValue =
2556         DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2557     IRB.SetInsertPoint(InsBefore);
2558     IRB.SetCurrentDebugLocation(EntryDebugLocation);
2559     LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2560   } else {
2561     // void *FakeStack = nullptr;
2562     // void *LocalStackBase = alloca(LocalStackSize);
2563     FakeStack = ConstantInt::get(IntptrTy, 0);
2564     LocalStackBase =
2565         DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
2566   }
2567 
2568   // Replace Alloca instructions with base+offset.
2569   for (const auto &Desc : SVD) {
2570     AllocaInst *AI = Desc.AI;
2571     Value *NewAllocaPtr = IRB.CreateIntToPtr(
2572         IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
2573         AI->getType());
2574     replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
2575     AI->replaceAllUsesWith(NewAllocaPtr);
2576   }
2577 
2578   // The left-most redzone has enough space for at least 4 pointers.
2579   // Write the Magic value to redzone[0].
2580   Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2581   IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2582                   BasePlus0);
2583   // Write the frame description constant to redzone[1].
2584   Value *BasePlus1 = IRB.CreateIntToPtr(
2585       IRB.CreateAdd(LocalStackBase,
2586                     ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2587       IntptrPtrTy);
2588   GlobalVariable *StackDescriptionGlobal =
2589       createPrivateGlobalForString(*F.getParent(), DescriptionString,
2590                                    /*AllowMerging*/ true);
2591   Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
2592   IRB.CreateStore(Description, BasePlus1);
2593   // Write the PC to redzone[2].
2594   Value *BasePlus2 = IRB.CreateIntToPtr(
2595       IRB.CreateAdd(LocalStackBase,
2596                     ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2597       IntptrPtrTy);
2598   IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
2599 
2600   const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
2601 
2602   // Poison the stack red zones at the entry.
2603   Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
2604   // As mask we must use most poisoned case: red zones and after scope.
2605   // As bytes we can use either the same or just red zones only.
2606   copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
2607 
2608   if (!StaticAllocaPoisonCallVec.empty()) {
2609     const auto &ShadowInScope = GetShadowBytes(SVD, L);
2610 
2611     // Poison static allocas near lifetime intrinsics.
2612     for (const auto &APC : StaticAllocaPoisonCallVec) {
2613       const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
2614       assert(Desc.Offset % L.Granularity == 0);
2615       size_t Begin = Desc.Offset / L.Granularity;
2616       size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
2617 
2618       IRBuilder<> IRB(APC.InsBefore);
2619       copyToShadow(ShadowAfterScope,
2620                    APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
2621                    IRB, ShadowBase);
2622     }
2623   }
2624 
2625   SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
2626   SmallVector<uint8_t, 64> ShadowAfterReturn;
2627 
2628   // (Un)poison the stack before all ret instructions.
2629   for (auto Ret : RetVec) {
2630     IRBuilder<> IRBRet(Ret);
2631     // Mark the current frame as retired.
2632     IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2633                        BasePlus0);
2634     if (DoStackMalloc) {
2635       assert(StackMallocIdx >= 0);
2636       // if FakeStack != 0  // LocalStackBase == FakeStack
2637       //     // In use-after-return mode, poison the whole stack frame.
2638       //     if StackMallocIdx <= 4
2639       //         // For small sizes inline the whole thing:
2640       //         memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
2641       //         **SavedFlagPtr(FakeStack) = 0
2642       //     else
2643       //         __asan_stack_free_N(FakeStack, LocalStackSize)
2644       // else
2645       //     <This is not a fake stack; unpoison the redzones>
2646       Value *Cmp =
2647           IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
2648       TerminatorInst *ThenTerm, *ElseTerm;
2649       SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2650 
2651       IRBuilder<> IRBPoison(ThenTerm);
2652       if (StackMallocIdx <= 4) {
2653         int ClassSize = kMinStackMallocSize << StackMallocIdx;
2654         ShadowAfterReturn.resize(ClassSize / L.Granularity,
2655                                  kAsanStackUseAfterReturnMagic);
2656         copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
2657                      ShadowBase);
2658         Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
2659             FakeStack,
2660             ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2661         Value *SavedFlagPtr = IRBPoison.CreateLoad(
2662             IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2663         IRBPoison.CreateStore(
2664             Constant::getNullValue(IRBPoison.getInt8Ty()),
2665             IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2666       } else {
2667         // For larger frames call __asan_stack_free_*.
2668         IRBPoison.CreateCall(
2669             AsanStackFreeFunc[StackMallocIdx],
2670             {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
2671       }
2672 
2673       IRBuilder<> IRBElse(ElseTerm);
2674       copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
2675     } else {
2676       copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
2677     }
2678   }
2679 
2680   // We are done. Remove the old unused alloca instructions.
2681   for (auto AI : AllocaVec) AI->eraseFromParent();
2682 }
2683 
2684 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
2685                                          IRBuilder<> &IRB, bool DoPoison) {
2686   // For now just insert the call to ASan runtime.
2687   Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2688   Value *SizeArg = ConstantInt::get(IntptrTy, Size);
2689   IRB.CreateCall(
2690       DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2691       {AddrArg, SizeArg});
2692 }
2693 
2694 // Handling llvm.lifetime intrinsics for a given %alloca:
2695 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2696 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2697 //     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2698 //     could be poisoned by previous llvm.lifetime.end instruction, as the
2699 //     variable may go in and out of scope several times, e.g. in loops).
2700 // (3) if we poisoned at least one %alloca in a function,
2701 //     unpoison the whole stack frame at function exit.
2702 
2703 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2704   if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
2705     // We're interested only in allocas we can handle.
2706     return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
2707   // See if we've already calculated (or started to calculate) alloca for a
2708   // given value.
2709   AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
2710   if (I != AllocaForValue.end()) return I->second;
2711   // Store 0 while we're calculating alloca for value V to avoid
2712   // infinite recursion if the value references itself.
2713   AllocaForValue[V] = nullptr;
2714   AllocaInst *Res = nullptr;
2715   if (CastInst *CI = dyn_cast<CastInst>(V))
2716     Res = findAllocaForValue(CI->getOperand(0));
2717   else if (PHINode *PN = dyn_cast<PHINode>(V)) {
2718     for (Value *IncValue : PN->incoming_values()) {
2719       // Allow self-referencing phi-nodes.
2720       if (IncValue == PN) continue;
2721       AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2722       // AI for incoming values should exist and should all be equal.
2723       if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2724         return nullptr;
2725       Res = IncValueAI;
2726     }
2727   } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
2728     Res = findAllocaForValue(EP->getPointerOperand());
2729   } else {
2730     DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V << "\n");
2731   }
2732   if (Res) AllocaForValue[V] = Res;
2733   return Res;
2734 }
2735 
2736 void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
2737   IRBuilder<> IRB(AI);
2738 
2739   const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2740   const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2741 
2742   Value *Zero = Constant::getNullValue(IntptrTy);
2743   Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2744   Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
2745 
2746   // Since we need to extend alloca with additional memory to locate
2747   // redzones, and OldSize is number of allocated blocks with
2748   // ElementSize size, get allocated memory size in bytes by
2749   // OldSize * ElementSize.
2750   const unsigned ElementSize =
2751       F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
2752   Value *OldSize =
2753       IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2754                     ConstantInt::get(IntptrTy, ElementSize));
2755 
2756   // PartialSize = OldSize % 32
2757   Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2758 
2759   // Misalign = kAllocaRzSize - PartialSize;
2760   Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2761 
2762   // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2763   Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2764   Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2765 
2766   // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2767   // Align is added to locate left redzone, PartialPadding for possible
2768   // partial redzone and kAllocaRzSize for right redzone respectively.
2769   Value *AdditionalChunkSize = IRB.CreateAdd(
2770       ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2771 
2772   Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2773 
2774   // Insert new alloca with new NewSize and Align params.
2775   AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2776   NewAlloca->setAlignment(Align);
2777 
2778   // NewAddress = Address + Align
2779   Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2780                                     ConstantInt::get(IntptrTy, Align));
2781 
2782   // Insert __asan_alloca_poison call for new created alloca.
2783   IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
2784 
2785   // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2786   // for unpoisoning stuff.
2787   IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2788 
2789   Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2790 
2791   // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
2792   AI->replaceAllUsesWith(NewAddressPtr);
2793 
2794   // We are done. Erase old alloca from parent.
2795   AI->eraseFromParent();
2796 }
2797 
2798 // isSafeAccess returns true if Addr is always inbounds with respect to its
2799 // base object. For example, it is a field access or an array access with
2800 // constant inbounds index.
2801 bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2802                                     Value *Addr, uint64_t TypeSize) const {
2803   SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2804   if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
2805   uint64_t Size = SizeOffset.first.getZExtValue();
2806   int64_t Offset = SizeOffset.second.getSExtValue();
2807   // Three checks are required to ensure safety:
2808   // . Offset >= 0  (since the offset is given from the base ptr)
2809   // . Size >= Offset  (unsigned)
2810   // . Size - Offset >= NeededSize  (unsigned)
2811   return Offset >= 0 && Size >= uint64_t(Offset) &&
2812          Size - uint64_t(Offset) >= TypeSize / 8;
2813 }
2814