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