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