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