]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
Upgrade our copies of clang, llvm and libc++ to r310316 from the
[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 && Mapping.Offset != kDynamicShadowSentinel)
760       copyArgsPassedByValToAllocas();
761
762     // Collect alloca, ret, lifetime instructions etc.
763     for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
764
765     if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
766
767     initializeCallbacks(*F.getParent());
768
769     processDynamicAllocas();
770     processStaticAllocas();
771
772     if (ClDebugStack) {
773       DEBUG(dbgs() << F);
774     }
775     return true;
776   }
777
778   // Arguments marked with the "byval" attribute are implicitly copied without
779   // using an alloca instruction.  To produce redzones for those arguments, we
780   // copy them a second time into memory allocated with an alloca instruction.
781   void copyArgsPassedByValToAllocas();
782
783   // Finds all Alloca instructions and puts
784   // poisoned red zones around all of them.
785   // Then unpoison everything back before the function returns.
786   void processStaticAllocas();
787   void processDynamicAllocas();
788
789   void createDynamicAllocasInitStorage();
790
791   // ----------------------- Visitors.
792   /// \brief Collect all Ret instructions.
793   void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
794
795   /// \brief Collect all Resume instructions.
796   void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
797
798   /// \brief Collect all CatchReturnInst instructions.
799   void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
800
801   void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
802                                         Value *SavedStack) {
803     IRBuilder<> IRB(InstBefore);
804     Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
805     // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
806     // need to adjust extracted SP to compute the address of the most recent
807     // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
808     // this purpose.
809     if (!isa<ReturnInst>(InstBefore)) {
810       Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
811           InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
812           {IntptrTy});
813
814       Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
815
816       DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
817                                      DynamicAreaOffset);
818     }
819
820     IRB.CreateCall(AsanAllocasUnpoisonFunc,
821                    {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
822   }
823
824   // Unpoison dynamic allocas redzones.
825   void unpoisonDynamicAllocas() {
826     for (auto &Ret : RetVec)
827       unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
828
829     for (auto &StackRestoreInst : StackRestoreVec)
830       unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
831                                        StackRestoreInst->getOperand(0));
832   }
833
834   // Deploy and poison redzones around dynamic alloca call. To do this, we
835   // should replace this call with another one with changed parameters and
836   // replace all its uses with new address, so
837   //   addr = alloca type, old_size, align
838   // is replaced by
839   //   new_size = (old_size + additional_size) * sizeof(type)
840   //   tmp = alloca i8, new_size, max(align, 32)
841   //   addr = tmp + 32 (first 32 bytes are for the left redzone).
842   // Additional_size is added to make new memory allocation contain not only
843   // requested memory, but also left, partial and right redzones.
844   void handleDynamicAllocaCall(AllocaInst *AI);
845
846   /// \brief Collect Alloca instructions we want (and can) handle.
847   void visitAllocaInst(AllocaInst &AI) {
848     if (!ASan.isInterestingAlloca(AI)) {
849       if (AI.isStaticAlloca()) {
850         // Skip over allocas that are present *before* the first instrumented
851         // alloca, we don't want to move those around.
852         if (AllocaVec.empty())
853           return;
854
855         StaticAllocasToMoveUp.push_back(&AI);
856       }
857       return;
858     }
859
860     StackAlignment = std::max(StackAlignment, AI.getAlignment());
861     if (!AI.isStaticAlloca())
862       DynamicAllocaVec.push_back(&AI);
863     else
864       AllocaVec.push_back(&AI);
865   }
866
867   /// \brief Collect lifetime intrinsic calls to check for use-after-scope
868   /// errors.
869   void visitIntrinsicInst(IntrinsicInst &II) {
870     Intrinsic::ID ID = II.getIntrinsicID();
871     if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
872     if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
873     if (!ASan.UseAfterScope)
874       return;
875     if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
876       return;
877     // Found lifetime intrinsic, add ASan instrumentation if necessary.
878     ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
879     // If size argument is undefined, don't do anything.
880     if (Size->isMinusOne()) return;
881     // Check that size doesn't saturate uint64_t and can
882     // be stored in IntptrTy.
883     const uint64_t SizeValue = Size->getValue().getLimitedValue();
884     if (SizeValue == ~0ULL ||
885         !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
886       return;
887     // Find alloca instruction that corresponds to llvm.lifetime argument.
888     AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
889     if (!AI || !ASan.isInterestingAlloca(*AI))
890       return;
891     bool DoPoison = (ID == Intrinsic::lifetime_end);
892     AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
893     if (AI->isStaticAlloca())
894       StaticAllocaPoisonCallVec.push_back(APC);
895     else if (ClInstrumentDynamicAllocas)
896       DynamicAllocaPoisonCallVec.push_back(APC);
897   }
898
899   void visitCallSite(CallSite CS) {
900     Instruction *I = CS.getInstruction();
901     if (CallInst *CI = dyn_cast<CallInst>(I)) {
902       HasNonEmptyInlineAsm |=
903           CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
904       HasReturnsTwiceCall |= CI->canReturnTwice();
905     }
906   }
907
908   // ---------------------- Helpers.
909   void initializeCallbacks(Module &M);
910
911   bool doesDominateAllExits(const Instruction *I) const {
912     for (auto Ret : RetVec) {
913       if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
914     }
915     return true;
916   }
917
918   /// Finds alloca where the value comes from.
919   AllocaInst *findAllocaForValue(Value *V);
920
921   // Copies bytes from ShadowBytes into shadow memory for indexes where
922   // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
923   // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
924   void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
925                     IRBuilder<> &IRB, Value *ShadowBase);
926   void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
927                     size_t Begin, size_t End, IRBuilder<> &IRB,
928                     Value *ShadowBase);
929   void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
930                           ArrayRef<uint8_t> ShadowBytes, size_t Begin,
931                           size_t End, IRBuilder<> &IRB, Value *ShadowBase);
932
933   void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
934
935   Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
936                                bool Dynamic);
937   PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
938                      Instruction *ThenTerm, Value *ValueIfFalse);
939 };
940
941 } // anonymous namespace
942
943 char AddressSanitizer::ID = 0;
944 INITIALIZE_PASS_BEGIN(
945     AddressSanitizer, "asan",
946     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
947     false)
948 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
949 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
950 INITIALIZE_PASS_END(
951     AddressSanitizer, "asan",
952     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
953     false)
954 FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
955                                                        bool Recover,
956                                                        bool UseAfterScope) {
957   assert(!CompileKernel || Recover);
958   return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
959 }
960
961 char AddressSanitizerModule::ID = 0;
962 INITIALIZE_PASS(
963     AddressSanitizerModule, "asan-module",
964     "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
965     "ModulePass",
966     false, false)
967 ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
968                                                    bool Recover,
969                                                    bool UseGlobalsGC) {
970   assert(!CompileKernel || Recover);
971   return new AddressSanitizerModule(CompileKernel, Recover, UseGlobalsGC);
972 }
973
974 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
975   size_t Res = countTrailingZeros(TypeSize / 8);
976   assert(Res < kNumberOfAccessSizes);
977   return Res;
978 }
979
980 // \brief Create a constant for Str so that we can pass it to the run-time lib.
981 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
982                                                     bool AllowMerging) {
983   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
984   // We use private linkage for module-local strings. If they can be merged
985   // with another one, we set the unnamed_addr attribute.
986   GlobalVariable *GV =
987       new GlobalVariable(M, StrConst->getType(), true,
988                          GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
989   if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
990   GV->setAlignment(1);  // Strings may not be merged w/o setting align 1.
991   return GV;
992 }
993
994 /// \brief Create a global describing a source location.
995 static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
996                                                        LocationMetadata MD) {
997   Constant *LocData[] = {
998       createPrivateGlobalForString(M, MD.Filename, true),
999       ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
1000       ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
1001   };
1002   auto LocStruct = ConstantStruct::getAnon(LocData);
1003   auto GV = new GlobalVariable(M, LocStruct->getType(), true,
1004                                GlobalValue::PrivateLinkage, LocStruct,
1005                                kAsanGenPrefix);
1006   GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1007   return GV;
1008 }
1009
1010 /// \brief Check if \p G has been created by a trusted compiler pass.
1011 static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
1012   // Do not instrument asan globals.
1013   if (G->getName().startswith(kAsanGenPrefix) ||
1014       G->getName().startswith(kSanCovGenPrefix) ||
1015       G->getName().startswith(kODRGenPrefix))
1016     return true;
1017
1018   // Do not instrument gcov counter arrays.
1019   if (G->getName() == "__llvm_gcov_ctr")
1020     return true;
1021
1022   return false;
1023 }
1024
1025 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
1026   // Shadow >> scale
1027   Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
1028   if (Mapping.Offset == 0) return Shadow;
1029   // (Shadow >> scale) | offset
1030   Value *ShadowBase;
1031   if (LocalDynamicShadow)
1032     ShadowBase = LocalDynamicShadow;
1033   else
1034     ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
1035   if (Mapping.OrShadowOffset)
1036     return IRB.CreateOr(Shadow, ShadowBase);
1037   else
1038     return IRB.CreateAdd(Shadow, ShadowBase);
1039 }
1040
1041 // Instrument memset/memmove/memcpy
1042 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
1043   IRBuilder<> IRB(MI);
1044   if (isa<MemTransferInst>(MI)) {
1045     IRB.CreateCall(
1046         isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
1047         {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1048          IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
1049          IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
1050   } else if (isa<MemSetInst>(MI)) {
1051     IRB.CreateCall(
1052         AsanMemset,
1053         {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1054          IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
1055          IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
1056   }
1057   MI->eraseFromParent();
1058 }
1059
1060 /// Check if we want (and can) handle this alloca.
1061 bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
1062   auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1063
1064   if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1065     return PreviouslySeenAllocaInfo->getSecond();
1066
1067   bool IsInteresting =
1068       (AI.getAllocatedType()->isSized() &&
1069        // alloca() may be called with 0 size, ignore it.
1070        ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
1071        // We are only interested in allocas not promotable to registers.
1072        // Promotable allocas are common under -O0.
1073        (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
1074        // inalloca allocas are not treated as static, and we don't want
1075        // dynamic alloca instrumentation for them as well.
1076        !AI.isUsedWithInAlloca() &&
1077        // swifterror allocas are register promoted by ISel
1078        !AI.isSwiftError());
1079
1080   ProcessedAllocas[&AI] = IsInteresting;
1081   return IsInteresting;
1082 }
1083
1084 Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
1085                                                    bool *IsWrite,
1086                                                    uint64_t *TypeSize,
1087                                                    unsigned *Alignment,
1088                                                    Value **MaybeMask) {
1089   // Skip memory accesses inserted by another instrumentation.
1090   if (I->getMetadata("nosanitize")) return nullptr;
1091
1092   // Do not instrument the load fetching the dynamic shadow address.
1093   if (LocalDynamicShadow == I)
1094     return nullptr;
1095
1096   Value *PtrOperand = nullptr;
1097   const DataLayout &DL = I->getModule()->getDataLayout();
1098   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1099     if (!ClInstrumentReads) return nullptr;
1100     *IsWrite = false;
1101     *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
1102     *Alignment = LI->getAlignment();
1103     PtrOperand = LI->getPointerOperand();
1104   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1105     if (!ClInstrumentWrites) return nullptr;
1106     *IsWrite = true;
1107     *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
1108     *Alignment = SI->getAlignment();
1109     PtrOperand = SI->getPointerOperand();
1110   } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
1111     if (!ClInstrumentAtomics) return nullptr;
1112     *IsWrite = true;
1113     *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
1114     *Alignment = 0;
1115     PtrOperand = RMW->getPointerOperand();
1116   } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
1117     if (!ClInstrumentAtomics) return nullptr;
1118     *IsWrite = true;
1119     *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
1120     *Alignment = 0;
1121     PtrOperand = XCHG->getPointerOperand();
1122   } else if (auto CI = dyn_cast<CallInst>(I)) {
1123     auto *F = dyn_cast<Function>(CI->getCalledValue());
1124     if (F && (F->getName().startswith("llvm.masked.load.") ||
1125               F->getName().startswith("llvm.masked.store."))) {
1126       unsigned OpOffset = 0;
1127       if (F->getName().startswith("llvm.masked.store.")) {
1128         if (!ClInstrumentWrites)
1129           return nullptr;
1130         // Masked store has an initial operand for the value.
1131         OpOffset = 1;
1132         *IsWrite = true;
1133       } else {
1134         if (!ClInstrumentReads)
1135           return nullptr;
1136         *IsWrite = false;
1137       }
1138
1139       auto BasePtr = CI->getOperand(0 + OpOffset);
1140       auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
1141       *TypeSize = DL.getTypeStoreSizeInBits(Ty);
1142       if (auto AlignmentConstant =
1143               dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1144         *Alignment = (unsigned)AlignmentConstant->getZExtValue();
1145       else
1146         *Alignment = 1; // No alignment guarantees. We probably got Undef
1147       if (MaybeMask)
1148         *MaybeMask = CI->getOperand(2 + OpOffset);
1149       PtrOperand = BasePtr;
1150     }
1151   }
1152
1153   if (PtrOperand) {
1154     // Do not instrument acesses from different address spaces; we cannot deal
1155     // with them.
1156     Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1157     if (PtrTy->getPointerAddressSpace() != 0)
1158       return nullptr;
1159
1160     // Ignore swifterror addresses.
1161     // swifterror memory addresses are mem2reg promoted by instruction
1162     // selection. As such they cannot have regular uses like an instrumentation
1163     // function and it makes no sense to track them as memory.
1164     if (PtrOperand->isSwiftError())
1165       return nullptr;
1166   }
1167
1168   // Treat memory accesses to promotable allocas as non-interesting since they
1169   // will not cause memory violations. This greatly speeds up the instrumented
1170   // executable at -O0.
1171   if (ClSkipPromotableAllocas)
1172     if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1173       return isInterestingAlloca(*AI) ? AI : nullptr;
1174
1175   return PtrOperand;
1176 }
1177
1178 static bool isPointerOperand(Value *V) {
1179   return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1180 }
1181
1182 // This is a rough heuristic; it may cause both false positives and
1183 // false negatives. The proper implementation requires cooperation with
1184 // the frontend.
1185 static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1186   if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
1187     if (!Cmp->isRelational()) return false;
1188   } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1189     if (BO->getOpcode() != Instruction::Sub) return false;
1190   } else {
1191     return false;
1192   }
1193   return isPointerOperand(I->getOperand(0)) &&
1194          isPointerOperand(I->getOperand(1));
1195 }
1196
1197 bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1198   // If a global variable does not have dynamic initialization we don't
1199   // have to instrument it.  However, if a global does not have initializer
1200   // at all, we assume it has dynamic initializer (in other TU).
1201   return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
1202 }
1203
1204 void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1205     Instruction *I) {
1206   IRBuilder<> IRB(I);
1207   Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1208   Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
1209   for (Value *&i : Param) {
1210     if (i->getType()->isPointerTy())
1211       i = IRB.CreatePointerCast(i, IntptrTy);
1212   }
1213   IRB.CreateCall(F, Param);
1214 }
1215
1216 static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,
1217                                 Instruction *InsertBefore, Value *Addr,
1218                                 unsigned Alignment, unsigned Granularity,
1219                                 uint32_t TypeSize, bool IsWrite,
1220                                 Value *SizeArgument, bool UseCalls,
1221                                 uint32_t Exp) {
1222   // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1223   // if the data is properly aligned.
1224   if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1225        TypeSize == 128) &&
1226       (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
1227     return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
1228                                    nullptr, UseCalls, Exp);
1229   Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
1230                                          IsWrite, nullptr, UseCalls, Exp);
1231 }
1232
1233 static void instrumentMaskedLoadOrStore(AddressSanitizer *Pass,
1234                                         const DataLayout &DL, Type *IntptrTy,
1235                                         Value *Mask, Instruction *I,
1236                                         Value *Addr, unsigned Alignment,
1237                                         unsigned Granularity, uint32_t TypeSize,
1238                                         bool IsWrite, Value *SizeArgument,
1239                                         bool UseCalls, uint32_t Exp) {
1240   auto *VTy = cast<PointerType>(Addr->getType())->getElementType();
1241   uint64_t ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
1242   unsigned Num = VTy->getVectorNumElements();
1243   auto Zero = ConstantInt::get(IntptrTy, 0);
1244   for (unsigned Idx = 0; Idx < Num; ++Idx) {
1245     Value *InstrumentedAddress = nullptr;
1246     Instruction *InsertBefore = I;
1247     if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
1248       // dyn_cast as we might get UndefValue
1249       if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
1250         if (Masked->isZero())
1251           // Mask is constant false, so no instrumentation needed.
1252           continue;
1253         // If we have a true or undef value, fall through to doInstrumentAddress
1254         // with InsertBefore == I
1255       }
1256     } else {
1257       IRBuilder<> IRB(I);
1258       Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
1259       TerminatorInst *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
1260       InsertBefore = ThenTerm;
1261     }
1262
1263     IRBuilder<> IRB(InsertBefore);
1264     InstrumentedAddress =
1265         IRB.CreateGEP(Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
1266     doInstrumentAddress(Pass, I, InsertBefore, InstrumentedAddress, Alignment,
1267                         Granularity, ElemTypeSize, IsWrite, SizeArgument,
1268                         UseCalls, Exp);
1269   }
1270 }
1271
1272 void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
1273                                      Instruction *I, bool UseCalls,
1274                                      const DataLayout &DL) {
1275   bool IsWrite = false;
1276   unsigned Alignment = 0;
1277   uint64_t TypeSize = 0;
1278   Value *MaybeMask = nullptr;
1279   Value *Addr =
1280       isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
1281   assert(Addr);
1282
1283   // Optimization experiments.
1284   // The experiments can be used to evaluate potential optimizations that remove
1285   // instrumentation (assess false negatives). Instead of completely removing
1286   // some instrumentation, you set Exp to a non-zero value (mask of optimization
1287   // experiments that want to remove instrumentation of this instruction).
1288   // If Exp is non-zero, this pass will emit special calls into runtime
1289   // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1290   // make runtime terminate the program in a special way (with a different
1291   // exit status). Then you run the new compiler on a buggy corpus, collect
1292   // the special terminations (ideally, you don't see them at all -- no false
1293   // negatives) and make the decision on the optimization.
1294   uint32_t Exp = ClForceExperiment;
1295
1296   if (ClOpt && ClOptGlobals) {
1297     // If initialization order checking is disabled, a simple access to a
1298     // dynamically initialized global is always valid.
1299     GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
1300     if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
1301         isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1302       NumOptimizedAccessesToGlobalVar++;
1303       return;
1304     }
1305   }
1306
1307   if (ClOpt && ClOptStack) {
1308     // A direct inbounds access to a stack variable is always valid.
1309     if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
1310         isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1311       NumOptimizedAccessesToStackVar++;
1312       return;
1313     }
1314   }
1315
1316   if (IsWrite)
1317     NumInstrumentedWrites++;
1318   else
1319     NumInstrumentedReads++;
1320
1321   unsigned Granularity = 1 << Mapping.Scale;
1322   if (MaybeMask) {
1323     instrumentMaskedLoadOrStore(this, DL, IntptrTy, MaybeMask, I, Addr,
1324                                 Alignment, Granularity, TypeSize, IsWrite,
1325                                 nullptr, UseCalls, Exp);
1326   } else {
1327     doInstrumentAddress(this, I, I, Addr, Alignment, Granularity, TypeSize,
1328                         IsWrite, nullptr, UseCalls, Exp);
1329   }
1330 }
1331
1332 Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1333                                                  Value *Addr, bool IsWrite,
1334                                                  size_t AccessSizeIndex,
1335                                                  Value *SizeArgument,
1336                                                  uint32_t Exp) {
1337   IRBuilder<> IRB(InsertBefore);
1338   Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1339   CallInst *Call = nullptr;
1340   if (SizeArgument) {
1341     if (Exp == 0)
1342       Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1343                             {Addr, SizeArgument});
1344     else
1345       Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1346                             {Addr, SizeArgument, ExpVal});
1347   } else {
1348     if (Exp == 0)
1349       Call =
1350           IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1351     else
1352       Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1353                             {Addr, ExpVal});
1354   }
1355
1356   // We don't do Call->setDoesNotReturn() because the BB already has
1357   // UnreachableInst at the end.
1358   // This EmptyAsm is required to avoid callback merge.
1359   IRB.CreateCall(EmptyAsm, {});
1360   return Call;
1361 }
1362
1363 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
1364                                            Value *ShadowValue,
1365                                            uint32_t TypeSize) {
1366   size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
1367   // Addr & (Granularity - 1)
1368   Value *LastAccessedByte =
1369       IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
1370   // (Addr & (Granularity - 1)) + size - 1
1371   if (TypeSize / 8 > 1)
1372     LastAccessedByte = IRB.CreateAdd(
1373         LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1374   // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
1375   LastAccessedByte =
1376       IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
1377   // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1378   return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1379 }
1380
1381 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
1382                                          Instruction *InsertBefore, Value *Addr,
1383                                          uint32_t TypeSize, bool IsWrite,
1384                                          Value *SizeArgument, bool UseCalls,
1385                                          uint32_t Exp) {
1386   IRBuilder<> IRB(InsertBefore);
1387   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1388   size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1389
1390   if (UseCalls) {
1391     if (Exp == 0)
1392       IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1393                      AddrLong);
1394     else
1395       IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1396                      {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1397     return;
1398   }
1399
1400   Type *ShadowTy =
1401       IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
1402   Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1403   Value *ShadowPtr = memToShadow(AddrLong, IRB);
1404   Value *CmpVal = Constant::getNullValue(ShadowTy);
1405   Value *ShadowValue =
1406       IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
1407
1408   Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
1409   size_t Granularity = 1ULL << Mapping.Scale;
1410   TerminatorInst *CrashTerm = nullptr;
1411
1412   if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
1413     // We use branch weights for the slow path check, to indicate that the slow
1414     // path is rarely taken. This seems to be the case for SPEC benchmarks.
1415     TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1416         Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
1417     assert(cast<BranchInst>(CheckTerm)->isUnconditional());
1418     BasicBlock *NextBB = CheckTerm->getSuccessor(0);
1419     IRB.SetInsertPoint(CheckTerm);
1420     Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
1421     if (Recover) {
1422       CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1423     } else {
1424       BasicBlock *CrashBlock =
1425         BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
1426       CrashTerm = new UnreachableInst(*C, CrashBlock);
1427       BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1428       ReplaceInstWithInst(CheckTerm, NewTerm);
1429     }
1430   } else {
1431     CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
1432   }
1433
1434   Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
1435                                          AccessSizeIndex, SizeArgument, Exp);
1436   Crash->setDebugLoc(OrigIns->getDebugLoc());
1437 }
1438
1439 // Instrument unusual size or unusual alignment.
1440 // We can not do it with a single check, so we do 1-byte check for the first
1441 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1442 // to report the actual access size.
1443 void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1444     Instruction *I, Instruction *InsertBefore, Value *Addr, uint32_t TypeSize,
1445     bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1446   IRBuilder<> IRB(InsertBefore);
1447   Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1448   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1449   if (UseCalls) {
1450     if (Exp == 0)
1451       IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1452                      {AddrLong, Size});
1453     else
1454       IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1455                      {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1456   } else {
1457     Value *LastByte = IRB.CreateIntToPtr(
1458         IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1459         Addr->getType());
1460     instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size, false, Exp);
1461     instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size, false, Exp);
1462   }
1463 }
1464
1465 void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1466                                                   GlobalValue *ModuleName) {
1467   // Set up the arguments to our poison/unpoison functions.
1468   IRBuilder<> IRB(&GlobalInit.front(),
1469                   GlobalInit.front().getFirstInsertionPt());
1470
1471   // Add a call to poison all external globals before the given function starts.
1472   Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1473   IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
1474
1475   // Add calls to unpoison all globals before each return instruction.
1476   for (auto &BB : GlobalInit.getBasicBlockList())
1477     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1478       CallInst::Create(AsanUnpoisonGlobals, "", RI);
1479 }
1480
1481 void AddressSanitizerModule::createInitializerPoisonCalls(
1482     Module &M, GlobalValue *ModuleName) {
1483   GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1484   if (!GV)
1485     return;
1486
1487   ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
1488   if (!CA)
1489     return;
1490
1491   for (Use &OP : CA->operands()) {
1492     if (isa<ConstantAggregateZero>(OP)) continue;
1493     ConstantStruct *CS = cast<ConstantStruct>(OP);
1494
1495     // Must have a function or null ptr.
1496     if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
1497       if (F->getName() == kAsanModuleCtorName) continue;
1498       ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1499       // Don't instrument CTORs that will run before asan.module_ctor.
1500       if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1501       poisonOneInitializer(*F, ModuleName);
1502     }
1503   }
1504 }
1505
1506 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
1507   Type *Ty = G->getValueType();
1508   DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
1509
1510   if (GlobalsMD.get(G).IsBlacklisted) return false;
1511   if (!Ty->isSized()) return false;
1512   if (!G->hasInitializer()) return false;
1513   if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
1514   // Touch only those globals that will not be defined in other modules.
1515   // Don't handle ODR linkage types and COMDATs since other modules may be built
1516   // without ASan.
1517   if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1518       G->getLinkage() != GlobalVariable::PrivateLinkage &&
1519       G->getLinkage() != GlobalVariable::InternalLinkage)
1520     return false;
1521   if (G->hasComdat()) return false;
1522   // Two problems with thread-locals:
1523   //   - The address of the main thread's copy can't be computed at link-time.
1524   //   - Need to poison all copies, not just the main thread's one.
1525   if (G->isThreadLocal()) return false;
1526   // For now, just ignore this Global if the alignment is large.
1527   if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
1528
1529   if (G->hasSection()) {
1530     StringRef Section = G->getSection();
1531
1532     // Globals from llvm.metadata aren't emitted, do not instrument them.
1533     if (Section == "llvm.metadata") return false;
1534     // Do not instrument globals from special LLVM sections.
1535     if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
1536
1537     // Do not instrument function pointers to initialization and termination
1538     // routines: dynamic linker will not properly handle redzones.
1539     if (Section.startswith(".preinit_array") ||
1540         Section.startswith(".init_array") ||
1541         Section.startswith(".fini_array")) {
1542       return false;
1543     }
1544
1545     // Callbacks put into the CRT initializer/terminator sections
1546     // should not be instrumented.
1547     // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1548     // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1549     if (Section.startswith(".CRT")) {
1550       DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1551       return false;
1552     }
1553
1554     if (TargetTriple.isOSBinFormatMachO()) {
1555       StringRef ParsedSegment, ParsedSection;
1556       unsigned TAA = 0, StubSize = 0;
1557       bool TAAParsed;
1558       std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1559           Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
1560       assert(ErrorCode.empty() && "Invalid section specifier.");
1561
1562       // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1563       // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1564       // them.
1565       if (ParsedSegment == "__OBJC" ||
1566           (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1567         DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1568         return false;
1569       }
1570       // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1571       // Constant CFString instances are compiled in the following way:
1572       //  -- the string buffer is emitted into
1573       //     __TEXT,__cstring,cstring_literals
1574       //  -- the constant NSConstantString structure referencing that buffer
1575       //     is placed into __DATA,__cfstring
1576       // Therefore there's no point in placing redzones into __DATA,__cfstring.
1577       // Moreover, it causes the linker to crash on OS X 10.7
1578       if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1579         DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1580         return false;
1581       }
1582       // The linker merges the contents of cstring_literals and removes the
1583       // trailing zeroes.
1584       if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1585         DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1586         return false;
1587       }
1588     }
1589   }
1590
1591   return true;
1592 }
1593
1594 // On Mach-O platforms, we emit global metadata in a separate section of the
1595 // binary in order to allow the linker to properly dead strip. This is only
1596 // supported on recent versions of ld64.
1597 bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
1598   if (!TargetTriple.isOSBinFormatMachO())
1599     return false;
1600
1601   if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1602     return true;
1603   if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
1604     return true;
1605   if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1606     return true;
1607
1608   return false;
1609 }
1610
1611 StringRef AddressSanitizerModule::getGlobalMetadataSection() const {
1612   switch (TargetTriple.getObjectFormat()) {
1613   case Triple::COFF:  return ".ASAN$GL";
1614   case Triple::ELF:   return "asan_globals";
1615   case Triple::MachO: return "__DATA,__asan_globals,regular";
1616   default: break;
1617   }
1618   llvm_unreachable("unsupported object format");
1619 }
1620
1621 void AddressSanitizerModule::initializeCallbacks(Module &M) {
1622   IRBuilder<> IRB(*C);
1623
1624   // Declare our poisoning and unpoisoning functions.
1625   AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1626       kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy));
1627   AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1628   AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1629       kAsanUnpoisonGlobalsName, IRB.getVoidTy()));
1630   AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1631
1632   // Declare functions that register/unregister globals.
1633   AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1634       kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy));
1635   AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1636   AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
1637       M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1638                             IntptrTy, IntptrTy));
1639   AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1640
1641   // Declare the functions that find globals in a shared object and then invoke
1642   // the (un)register function on them.
1643   AsanRegisterImageGlobals =
1644       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1645           kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
1646   AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
1647
1648   AsanUnregisterImageGlobals =
1649       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1650           kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
1651   AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
1652
1653   AsanRegisterElfGlobals = checkSanitizerInterfaceFunction(
1654       M.getOrInsertFunction(kAsanRegisterElfGlobalsName, IRB.getVoidTy(),
1655                             IntptrTy, IntptrTy, IntptrTy));
1656   AsanRegisterElfGlobals->setLinkage(Function::ExternalLinkage);
1657
1658   AsanUnregisterElfGlobals = checkSanitizerInterfaceFunction(
1659       M.getOrInsertFunction(kAsanUnregisterElfGlobalsName, IRB.getVoidTy(),
1660                             IntptrTy, IntptrTy, IntptrTy));
1661   AsanUnregisterElfGlobals->setLinkage(Function::ExternalLinkage);
1662 }
1663
1664 // Put the metadata and the instrumented global in the same group. This ensures
1665 // that the metadata is discarded if the instrumented global is discarded.
1666 void AddressSanitizerModule::SetComdatForGlobalMetadata(
1667     GlobalVariable *G, GlobalVariable *Metadata, StringRef InternalSuffix) {
1668   Module &M = *G->getParent();
1669   Comdat *C = G->getComdat();
1670   if (!C) {
1671     if (!G->hasName()) {
1672       // If G is unnamed, it must be internal. Give it an artificial name
1673       // so we can put it in a comdat.
1674       assert(G->hasLocalLinkage());
1675       G->setName(Twine(kAsanGenPrefix) + "_anon_global");
1676     }
1677
1678     if (!InternalSuffix.empty() && G->hasLocalLinkage()) {
1679       std::string Name = G->getName();
1680       Name += InternalSuffix;
1681       C = M.getOrInsertComdat(Name);
1682     } else {
1683       C = M.getOrInsertComdat(G->getName());
1684     }
1685
1686     // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF.
1687     if (TargetTriple.isOSBinFormatCOFF())
1688       C->setSelectionKind(Comdat::NoDuplicates);
1689     G->setComdat(C);
1690   }
1691
1692   assert(G->hasComdat());
1693   Metadata->setComdat(G->getComdat());
1694 }
1695
1696 // Create a separate metadata global and put it in the appropriate ASan
1697 // global registration section.
1698 GlobalVariable *
1699 AddressSanitizerModule::CreateMetadataGlobal(Module &M, Constant *Initializer,
1700                                              StringRef OriginalName) {
1701   auto Linkage = TargetTriple.isOSBinFormatMachO()
1702                      ? GlobalVariable::InternalLinkage
1703                      : GlobalVariable::PrivateLinkage;
1704   GlobalVariable *Metadata = new GlobalVariable(
1705       M, Initializer->getType(), false, Linkage, Initializer,
1706       Twine("__asan_global_") + GlobalValue::dropLLVMManglingEscape(OriginalName));
1707   Metadata->setSection(getGlobalMetadataSection());
1708   return Metadata;
1709 }
1710
1711 IRBuilder<> AddressSanitizerModule::CreateAsanModuleDtor(Module &M) {
1712   AsanDtorFunction =
1713       Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1714                        GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1715   BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1716
1717   return IRBuilder<>(ReturnInst::Create(*C, AsanDtorBB));
1718 }
1719
1720 void AddressSanitizerModule::InstrumentGlobalsCOFF(
1721     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1722     ArrayRef<Constant *> MetadataInitializers) {
1723   assert(ExtendedGlobals.size() == MetadataInitializers.size());
1724   auto &DL = M.getDataLayout();
1725
1726   for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1727     Constant *Initializer = MetadataInitializers[i];
1728     GlobalVariable *G = ExtendedGlobals[i];
1729     GlobalVariable *Metadata =
1730         CreateMetadataGlobal(M, Initializer, G->getName());
1731
1732     // The MSVC linker always inserts padding when linking incrementally. We
1733     // cope with that by aligning each struct to its size, which must be a power
1734     // of two.
1735     unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
1736     assert(isPowerOf2_32(SizeOfGlobalStruct) &&
1737            "global metadata will not be padded appropriately");
1738     Metadata->setAlignment(SizeOfGlobalStruct);
1739
1740     SetComdatForGlobalMetadata(G, Metadata, "");
1741   }
1742 }
1743
1744 void AddressSanitizerModule::InstrumentGlobalsELF(
1745     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1746     ArrayRef<Constant *> MetadataInitializers,
1747     const std::string &UniqueModuleId) {
1748   assert(ExtendedGlobals.size() == MetadataInitializers.size());
1749
1750   SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
1751   for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1752     GlobalVariable *G = ExtendedGlobals[i];
1753     GlobalVariable *Metadata =
1754         CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());
1755     MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
1756     Metadata->setMetadata(LLVMContext::MD_associated, MD);
1757     MetadataGlobals[i] = Metadata;
1758
1759     SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
1760   }
1761
1762   // Update llvm.compiler.used, adding the new metadata globals. This is
1763   // needed so that during LTO these variables stay alive.
1764   if (!MetadataGlobals.empty())
1765     appendToCompilerUsed(M, MetadataGlobals);
1766
1767   // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1768   // to look up the loaded image that contains it. Second, we can store in it
1769   // whether registration has already occurred, to prevent duplicate
1770   // registration.
1771   //
1772   // Common linkage ensures that there is only one global per shared library.
1773   GlobalVariable *RegisteredFlag = new GlobalVariable(
1774       M, IntptrTy, false, GlobalVariable::CommonLinkage,
1775       ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1776   RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1777
1778   // Create start and stop symbols.
1779   GlobalVariable *StartELFMetadata = new GlobalVariable(
1780       M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1781       "__start_" + getGlobalMetadataSection());
1782   StartELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1783   GlobalVariable *StopELFMetadata = new GlobalVariable(
1784       M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1785       "__stop_" + getGlobalMetadataSection());
1786   StopELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1787
1788   // Create a call to register the globals with the runtime.
1789   IRB.CreateCall(AsanRegisterElfGlobals,
1790                  {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1791                   IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1792                   IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1793
1794   // We also need to unregister globals at the end, e.g., when a shared library
1795   // gets closed.
1796   IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1797   IRB_Dtor.CreateCall(AsanUnregisterElfGlobals,
1798                       {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1799                        IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1800                        IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1801 }
1802
1803 void AddressSanitizerModule::InstrumentGlobalsMachO(
1804     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1805     ArrayRef<Constant *> MetadataInitializers) {
1806   assert(ExtendedGlobals.size() == MetadataInitializers.size());
1807
1808   // On recent Mach-O platforms, use a structure which binds the liveness of
1809   // the global variable to the metadata struct. Keep the list of "Liveness" GV
1810   // created to be added to llvm.compiler.used
1811   StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy);
1812   SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
1813
1814   for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1815     Constant *Initializer = MetadataInitializers[i];
1816     GlobalVariable *G = ExtendedGlobals[i];
1817     GlobalVariable *Metadata =
1818         CreateMetadataGlobal(M, Initializer, G->getName());
1819
1820     // On recent Mach-O platforms, we emit the global metadata in a way that
1821     // allows the linker to properly strip dead globals.
1822     auto LivenessBinder =
1823         ConstantStruct::get(LivenessTy, Initializer->getAggregateElement(0u),
1824                             ConstantExpr::getPointerCast(Metadata, IntptrTy));
1825     GlobalVariable *Liveness = new GlobalVariable(
1826         M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
1827         Twine("__asan_binder_") + G->getName());
1828     Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1829     LivenessGlobals[i] = Liveness;
1830   }
1831
1832   // Update llvm.compiler.used, adding the new liveness globals. This is
1833   // needed so that during LTO these variables stay alive. The alternative
1834   // would be to have the linker handling the LTO symbols, but libLTO
1835   // current API does not expose access to the section for each symbol.
1836   if (!LivenessGlobals.empty())
1837     appendToCompilerUsed(M, LivenessGlobals);
1838
1839   // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1840   // to look up the loaded image that contains it. Second, we can store in it
1841   // whether registration has already occurred, to prevent duplicate
1842   // registration.
1843   //
1844   // common linkage ensures that there is only one global per shared library.
1845   GlobalVariable *RegisteredFlag = new GlobalVariable(
1846       M, IntptrTy, false, GlobalVariable::CommonLinkage,
1847       ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1848   RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1849
1850   IRB.CreateCall(AsanRegisterImageGlobals,
1851                  {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1852
1853   // We also need to unregister globals at the end, e.g., when a shared library
1854   // gets closed.
1855   IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1856   IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1857                       {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1858 }
1859
1860 void AddressSanitizerModule::InstrumentGlobalsWithMetadataArray(
1861     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1862     ArrayRef<Constant *> MetadataInitializers) {
1863   assert(ExtendedGlobals.size() == MetadataInitializers.size());
1864   unsigned N = ExtendedGlobals.size();
1865   assert(N > 0);
1866
1867   // On platforms that don't have a custom metadata section, we emit an array
1868   // of global metadata structures.
1869   ArrayType *ArrayOfGlobalStructTy =
1870       ArrayType::get(MetadataInitializers[0]->getType(), N);
1871   auto AllGlobals = new GlobalVariable(
1872       M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1873       ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
1874
1875   IRB.CreateCall(AsanRegisterGlobals,
1876                  {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1877                   ConstantInt::get(IntptrTy, N)});
1878
1879   // We also need to unregister globals at the end, e.g., when a shared library
1880   // gets closed.
1881   IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1882   IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1883                       {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1884                        ConstantInt::get(IntptrTy, N)});
1885 }
1886
1887 // This function replaces all global variables with new variables that have
1888 // trailing redzones. It also creates a function that poisons
1889 // redzones and inserts this function into llvm.global_ctors.
1890 // Sets *CtorComdat to true if the global registration code emitted into the
1891 // asan constructor is comdat-compatible.
1892 bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat) {
1893   *CtorComdat = false;
1894   GlobalsMD.init(M);
1895
1896   SmallVector<GlobalVariable *, 16> GlobalsToChange;
1897
1898   for (auto &G : M.globals()) {
1899     if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
1900   }
1901
1902   size_t n = GlobalsToChange.size();
1903   if (n == 0) {
1904     *CtorComdat = true;
1905     return false;
1906   }
1907
1908   auto &DL = M.getDataLayout();
1909
1910   // A global is described by a structure
1911   //   size_t beg;
1912   //   size_t size;
1913   //   size_t size_with_redzone;
1914   //   const char *name;
1915   //   const char *module_name;
1916   //   size_t has_dynamic_init;
1917   //   void *source_location;
1918   //   size_t odr_indicator;
1919   // We initialize an array of such structures and pass it to a run-time call.
1920   StructType *GlobalStructTy =
1921       StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
1922                       IntptrTy, IntptrTy, IntptrTy);
1923   SmallVector<GlobalVariable *, 16> NewGlobals(n);
1924   SmallVector<Constant *, 16> Initializers(n);
1925
1926   bool HasDynamicallyInitializedGlobals = false;
1927
1928   // We shouldn't merge same module names, as this string serves as unique
1929   // module ID in runtime.
1930   GlobalVariable *ModuleName = createPrivateGlobalForString(
1931       M, M.getModuleIdentifier(), /*AllowMerging*/ false);
1932
1933   for (size_t i = 0; i < n; i++) {
1934     static const uint64_t kMaxGlobalRedzone = 1 << 18;
1935     GlobalVariable *G = GlobalsToChange[i];
1936
1937     auto MD = GlobalsMD.get(G);
1938     StringRef NameForGlobal = G->getName();
1939     // Create string holding the global name (use global name from metadata
1940     // if it's available, otherwise just write the name of global variable).
1941     GlobalVariable *Name = createPrivateGlobalForString(
1942         M, MD.Name.empty() ? NameForGlobal : MD.Name,
1943         /*AllowMerging*/ true);
1944
1945     Type *Ty = G->getValueType();
1946     uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
1947     uint64_t MinRZ = MinRedzoneSizeForGlobal();
1948     // MinRZ <= RZ <= kMaxGlobalRedzone
1949     // and trying to make RZ to be ~ 1/4 of SizeInBytes.
1950     uint64_t RZ = std::max(
1951         MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
1952     uint64_t RightRedzoneSize = RZ;
1953     // Round up to MinRZ
1954     if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1955     assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
1956     Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1957
1958     StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
1959     Constant *NewInitializer = ConstantStruct::get(
1960         NewTy, G->getInitializer(), Constant::getNullValue(RightRedZoneTy));
1961
1962     // Create a new global variable with enough space for a redzone.
1963     GlobalValue::LinkageTypes Linkage = G->getLinkage();
1964     if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1965       Linkage = GlobalValue::InternalLinkage;
1966     GlobalVariable *NewGlobal =
1967         new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1968                            "", G, G->getThreadLocalMode());
1969     NewGlobal->copyAttributesFrom(G);
1970     NewGlobal->setAlignment(MinRZ);
1971
1972     // Move null-terminated C strings to "__asan_cstring" section on Darwin.
1973     if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
1974         G->isConstant()) {
1975       auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
1976       if (Seq && Seq->isCString())
1977         NewGlobal->setSection("__TEXT,__asan_cstring,regular");
1978     }
1979
1980     // Transfer the debug info.  The payload starts at offset zero so we can
1981     // copy the debug info over as is.
1982     SmallVector<DIGlobalVariableExpression *, 1> GVs;
1983     G->getDebugInfo(GVs);
1984     for (auto *GV : GVs)
1985       NewGlobal->addDebugInfo(GV);
1986
1987     Value *Indices2[2];
1988     Indices2[0] = IRB.getInt32(0);
1989     Indices2[1] = IRB.getInt32(0);
1990
1991     G->replaceAllUsesWith(
1992         ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
1993     NewGlobal->takeName(G);
1994     G->eraseFromParent();
1995     NewGlobals[i] = NewGlobal;
1996
1997     Constant *SourceLoc;
1998     if (!MD.SourceLoc.empty()) {
1999       auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
2000       SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
2001     } else {
2002       SourceLoc = ConstantInt::get(IntptrTy, 0);
2003     }
2004
2005     Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
2006     GlobalValue *InstrumentedGlobal = NewGlobal;
2007
2008     bool CanUsePrivateAliases =
2009         TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
2010         TargetTriple.isOSBinFormatWasm();
2011     if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
2012       // Create local alias for NewGlobal to avoid crash on ODR between
2013       // instrumented and non-instrumented libraries.
2014       auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
2015                                      NameForGlobal + M.getName(), NewGlobal);
2016
2017       // With local aliases, we need to provide another externally visible
2018       // symbol __odr_asan_XXX to detect ODR violation.
2019       auto *ODRIndicatorSym =
2020           new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
2021                              Constant::getNullValue(IRB.getInt8Ty()),
2022                              kODRGenPrefix + NameForGlobal, nullptr,
2023                              NewGlobal->getThreadLocalMode());
2024
2025       // Set meaningful attributes for indicator symbol.
2026       ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
2027       ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
2028       ODRIndicatorSym->setAlignment(1);
2029       ODRIndicator = ODRIndicatorSym;
2030       InstrumentedGlobal = GA;
2031     }
2032
2033     Constant *Initializer = ConstantStruct::get(
2034         GlobalStructTy,
2035         ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
2036         ConstantInt::get(IntptrTy, SizeInBytes),
2037         ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
2038         ConstantExpr::getPointerCast(Name, IntptrTy),
2039         ConstantExpr::getPointerCast(ModuleName, IntptrTy),
2040         ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
2041         ConstantExpr::getPointerCast(ODRIndicator, IntptrTy));
2042
2043     if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
2044
2045     DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
2046
2047     Initializers[i] = Initializer;
2048   }
2049
2050   std::string ELFUniqueModuleId =
2051       (UseGlobalsGC && TargetTriple.isOSBinFormatELF()) ? getUniqueModuleId(&M)
2052                                                         : "";
2053
2054   if (!ELFUniqueModuleId.empty()) {
2055     InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
2056     *CtorComdat = true;
2057   } else if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {
2058     InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
2059   } else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
2060     InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
2061   } else {
2062     InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
2063   }
2064
2065   // Create calls for poisoning before initializers run and unpoisoning after.
2066   if (HasDynamicallyInitializedGlobals)
2067     createInitializerPoisonCalls(M, ModuleName);
2068
2069   DEBUG(dbgs() << M);
2070   return true;
2071 }
2072
2073 bool AddressSanitizerModule::runOnModule(Module &M) {
2074   C = &(M.getContext());
2075   int LongSize = M.getDataLayout().getPointerSizeInBits();
2076   IntptrTy = Type::getIntNTy(*C, LongSize);
2077   TargetTriple = Triple(M.getTargetTriple());
2078   Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
2079   initializeCallbacks(M);
2080
2081   if (CompileKernel)
2082     return false;
2083
2084   // Create a module constructor. A destructor is created lazily because not all
2085   // platforms, and not all modules need it.
2086   std::tie(AsanCtorFunction, std::ignore) = createSanitizerCtorAndInitFunctions(
2087       M, kAsanModuleCtorName, kAsanInitName, /*InitArgTypes=*/{},
2088       /*InitArgs=*/{}, kAsanVersionCheckName);
2089
2090   bool CtorComdat = true;
2091   bool Changed = false;
2092   // TODO(glider): temporarily disabled globals instrumentation for KASan.
2093   if (ClGlobals) {
2094     IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
2095     Changed |= InstrumentGlobals(IRB, M, &CtorComdat);
2096   }
2097
2098   // Put the constructor and destructor in comdat if both
2099   // (1) global instrumentation is not TU-specific
2100   // (2) target is ELF.
2101   if (UseCtorComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {
2102     AsanCtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleCtorName));
2103     appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority,
2104                         AsanCtorFunction);
2105     if (AsanDtorFunction) {
2106       AsanDtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleDtorName));
2107       appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority,
2108                           AsanDtorFunction);
2109     }
2110   } else {
2111     appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
2112     if (AsanDtorFunction)
2113       appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
2114   }
2115
2116   return Changed;
2117 }
2118
2119 void AddressSanitizer::initializeCallbacks(Module &M) {
2120   IRBuilder<> IRB(*C);
2121   // Create __asan_report* callbacks.
2122   // IsWrite, TypeSize and Exp are encoded in the function name.
2123   for (int Exp = 0; Exp < 2; Exp++) {
2124     for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
2125       const std::string TypeStr = AccessIsWrite ? "store" : "load";
2126       const std::string ExpStr = Exp ? "exp_" : "";
2127       const std::string SuffixStr = CompileKernel ? "N" : "_n";
2128       const std::string EndingStr = Recover ? "_noabort" : "";
2129
2130       SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};
2131       SmallVector<Type *, 2> Args1{1, IntptrTy};
2132       if (Exp) {
2133         Type *ExpType = Type::getInt32Ty(*C);
2134         Args2.push_back(ExpType);
2135         Args1.push_back(ExpType);
2136       }
2137             AsanErrorCallbackSized[AccessIsWrite][Exp] =
2138                 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2139                     kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr +
2140                         EndingStr,
2141                     FunctionType::get(IRB.getVoidTy(), Args2, false)));
2142
2143             AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
2144                 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2145                     ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
2146                     FunctionType::get(IRB.getVoidTy(), Args2, false)));
2147
2148             for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
2149                  AccessSizeIndex++) {
2150               const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
2151               AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2152                   checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2153                       kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
2154                       FunctionType::get(IRB.getVoidTy(), Args1, false)));
2155
2156               AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2157                   checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2158                       ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
2159                       FunctionType::get(IRB.getVoidTy(), Args1, false)));
2160             }
2161           }
2162   }
2163
2164   const std::string MemIntrinCallbackPrefix =
2165       CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
2166   AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2167       MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
2168       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
2169   AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2170       MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
2171       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
2172   AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2173       MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
2174       IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy));
2175
2176   AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
2177       M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy()));
2178
2179   AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2180       kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy));
2181   AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2182       kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy));
2183   // We insert an empty inline asm after __asan_report* to avoid callback merge.
2184   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
2185                             StringRef(""), StringRef(""),
2186                             /*hasSideEffects=*/true);
2187 }
2188
2189 // virtual
2190 bool AddressSanitizer::doInitialization(Module &M) {
2191   // Initialize the private fields. No one has accessed them before.
2192   GlobalsMD.init(M);
2193
2194   C = &(M.getContext());
2195   LongSize = M.getDataLayout().getPointerSizeInBits();
2196   IntptrTy = Type::getIntNTy(*C, LongSize);
2197   TargetTriple = Triple(M.getTargetTriple());
2198
2199   Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
2200   return true;
2201 }
2202
2203 bool AddressSanitizer::doFinalization(Module &M) {
2204   GlobalsMD.reset();
2205   return false;
2206 }
2207
2208 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2209   // For each NSObject descendant having a +load method, this method is invoked
2210   // by the ObjC runtime before any of the static constructors is called.
2211   // Therefore we need to instrument such methods with a call to __asan_init
2212   // at the beginning in order to initialize our runtime before any access to
2213   // the shadow memory.
2214   // We cannot just ignore these methods, because they may call other
2215   // instrumented functions.
2216   if (F.getName().find(" load]") != std::string::npos) {
2217     Function *AsanInitFunction =
2218         declareSanitizerInitFunction(*F.getParent(), kAsanInitName, {});
2219     IRBuilder<> IRB(&F.front(), F.front().begin());
2220     IRB.CreateCall(AsanInitFunction, {});
2221     return true;
2222   }
2223   return false;
2224 }
2225
2226 void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2227   // Generate code only when dynamic addressing is needed.
2228   if (Mapping.Offset != kDynamicShadowSentinel)
2229     return;
2230
2231   IRBuilder<> IRB(&F.front().front());
2232   Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2233       kAsanShadowMemoryDynamicAddress, IntptrTy);
2234   LocalDynamicShadow = IRB.CreateLoad(GlobalDynamicAddress);
2235 }
2236
2237 void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2238   // Find the one possible call to llvm.localescape and pre-mark allocas passed
2239   // to it as uninteresting. This assumes we haven't started processing allocas
2240   // yet. This check is done up front because iterating the use list in
2241   // isInterestingAlloca would be algorithmically slower.
2242   assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2243
2244   // Try to get the declaration of llvm.localescape. If it's not in the module,
2245   // we can exit early.
2246   if (!F.getParent()->getFunction("llvm.localescape")) return;
2247
2248   // Look for a call to llvm.localescape call in the entry block. It can't be in
2249   // any other block.
2250   for (Instruction &I : F.getEntryBlock()) {
2251     IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2252     if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2253       // We found a call. Mark all the allocas passed in as uninteresting.
2254       for (Value *Arg : II->arg_operands()) {
2255         AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2256         assert(AI && AI->isStaticAlloca() &&
2257                "non-static alloca arg to localescape");
2258         ProcessedAllocas[AI] = false;
2259       }
2260       break;
2261     }
2262   }
2263 }
2264
2265 bool AddressSanitizer::runOnFunction(Function &F) {
2266   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
2267   if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
2268   if (F.getName().startswith("__asan_")) return false;
2269
2270   bool FunctionModified = false;
2271
2272   // If needed, insert __asan_init before checking for SanitizeAddress attr.
2273   // This function needs to be called even if the function body is not
2274   // instrumented.  
2275   if (maybeInsertAsanInitAtFunctionEntry(F))
2276     FunctionModified = true;
2277   
2278   // Leave if the function doesn't need instrumentation.
2279   if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
2280
2281   DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
2282
2283   initializeCallbacks(*F.getParent());
2284   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2285
2286   FunctionStateRAII CleanupObj(this);
2287
2288   maybeInsertDynamicShadowAtFunctionEntry(F);
2289
2290   // We can't instrument allocas used with llvm.localescape. Only static allocas
2291   // can be passed to that intrinsic.
2292   markEscapedLocalAllocas(F);
2293
2294   // We want to instrument every address only once per basic block (unless there
2295   // are calls between uses).
2296   SmallSet<Value *, 16> TempsToInstrument;
2297   SmallVector<Instruction *, 16> ToInstrument;
2298   SmallVector<Instruction *, 8> NoReturnCalls;
2299   SmallVector<BasicBlock *, 16> AllBlocks;
2300   SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
2301   int NumAllocas = 0;
2302   bool IsWrite;
2303   unsigned Alignment;
2304   uint64_t TypeSize;
2305   const TargetLibraryInfo *TLI =
2306       &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
2307
2308   // Fill the set of memory operations to instrument.
2309   for (auto &BB : F) {
2310     AllBlocks.push_back(&BB);
2311     TempsToInstrument.clear();
2312     int NumInsnsPerBB = 0;
2313     for (auto &Inst : BB) {
2314       if (LooksLikeCodeInBug11395(&Inst)) return false;
2315       Value *MaybeMask = nullptr;
2316       if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
2317                                                   &Alignment, &MaybeMask)) {
2318         if (ClOpt && ClOptSameTemp) {
2319           // If we have a mask, skip instrumentation if we've already
2320           // instrumented the full object. But don't add to TempsToInstrument
2321           // because we might get another load/store with a different mask.
2322           if (MaybeMask) {
2323             if (TempsToInstrument.count(Addr))
2324               continue; // We've seen this (whole) temp in the current BB.
2325           } else {
2326             if (!TempsToInstrument.insert(Addr).second)
2327               continue; // We've seen this temp in the current BB.
2328           }
2329         }
2330       } else if (ClInvalidPointerPairs &&
2331                  isInterestingPointerComparisonOrSubtraction(&Inst)) {
2332         PointerComparisonsOrSubtracts.push_back(&Inst);
2333         continue;
2334       } else if (isa<MemIntrinsic>(Inst)) {
2335         // ok, take it.
2336       } else {
2337         if (isa<AllocaInst>(Inst)) NumAllocas++;
2338         CallSite CS(&Inst);
2339         if (CS) {
2340           // A call inside BB.
2341           TempsToInstrument.clear();
2342           if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
2343         }
2344         if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2345           maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
2346         continue;
2347       }
2348       ToInstrument.push_back(&Inst);
2349       NumInsnsPerBB++;
2350       if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
2351     }
2352   }
2353
2354   bool UseCalls =
2355       CompileKernel ||
2356       (ClInstrumentationWithCallsThreshold >= 0 &&
2357        ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
2358   const DataLayout &DL = F.getParent()->getDataLayout();
2359   ObjectSizeOpts ObjSizeOpts;
2360   ObjSizeOpts.RoundToAlign = true;
2361   ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);
2362
2363   // Instrument.
2364   int NumInstrumented = 0;
2365   for (auto Inst : ToInstrument) {
2366     if (ClDebugMin < 0 || ClDebugMax < 0 ||
2367         (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
2368       if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
2369         instrumentMop(ObjSizeVis, Inst, UseCalls,
2370                       F.getParent()->getDataLayout());
2371       else
2372         instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
2373     }
2374     NumInstrumented++;
2375   }
2376
2377   FunctionStackPoisoner FSP(F, *this);
2378   bool ChangedStack = FSP.runOnFunction();
2379
2380   // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
2381   // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
2382   for (auto CI : NoReturnCalls) {
2383     IRBuilder<> IRB(CI);
2384     IRB.CreateCall(AsanHandleNoReturnFunc, {});
2385   }
2386
2387   for (auto Inst : PointerComparisonsOrSubtracts) {
2388     instrumentPointerComparisonOrSubtraction(Inst);
2389     NumInstrumented++;
2390   }
2391
2392   if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
2393     FunctionModified = true;
2394
2395   DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2396                << F << "\n");
2397
2398   return FunctionModified;
2399 }
2400
2401 // Workaround for bug 11395: we don't want to instrument stack in functions
2402 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2403 // FIXME: remove once the bug 11395 is fixed.
2404 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2405   if (LongSize != 32) return false;
2406   CallInst *CI = dyn_cast<CallInst>(I);
2407   if (!CI || !CI->isInlineAsm()) return false;
2408   if (CI->getNumArgOperands() <= 5) return false;
2409   // We have inline assembly with quite a few arguments.
2410   return true;
2411 }
2412
2413 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2414   IRBuilder<> IRB(*C);
2415   for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
2416     std::string Suffix = itostr(i);
2417     AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
2418         M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
2419                               IntptrTy));
2420     AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
2421         M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
2422                               IRB.getVoidTy(), IntptrTy, IntptrTy));
2423   }
2424   if (ASan.UseAfterScope) {
2425     AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2426         M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
2427                               IntptrTy, IntptrTy));
2428     AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2429         M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
2430                               IntptrTy, IntptrTy));
2431   }
2432
2433   for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2434     std::ostringstream Name;
2435     Name << kAsanSetShadowPrefix;
2436     Name << std::setw(2) << std::setfill('0') << std::hex << Val;
2437     AsanSetShadowFunc[Val] =
2438         checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2439             Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy));
2440   }
2441
2442   AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2443       kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
2444   AsanAllocasUnpoisonFunc =
2445       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2446           kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
2447 }
2448
2449 void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2450                                                ArrayRef<uint8_t> ShadowBytes,
2451                                                size_t Begin, size_t End,
2452                                                IRBuilder<> &IRB,
2453                                                Value *ShadowBase) {
2454   if (Begin >= End)
2455     return;
2456
2457   const size_t LargestStoreSizeInBytes =
2458       std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2459
2460   const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2461
2462   // Poison given range in shadow using larges store size with out leading and
2463   // trailing zeros in ShadowMask. Zeros never change, so they need neither
2464   // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2465   // middle of a store.
2466   for (size_t i = Begin; i < End;) {
2467     if (!ShadowMask[i]) {
2468       assert(!ShadowBytes[i]);
2469       ++i;
2470       continue;
2471     }
2472
2473     size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2474     // Fit store size into the range.
2475     while (StoreSizeInBytes > End - i)
2476       StoreSizeInBytes /= 2;
2477
2478     // Minimize store size by trimming trailing zeros.
2479     for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
2480       while (j <= StoreSizeInBytes / 2)
2481         StoreSizeInBytes /= 2;
2482     }
2483
2484     uint64_t Val = 0;
2485     for (size_t j = 0; j < StoreSizeInBytes; j++) {
2486       if (IsLittleEndian)
2487         Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2488       else
2489         Val = (Val << 8) | ShadowBytes[i + j];
2490     }
2491
2492     Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2493     Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
2494     IRB.CreateAlignedStore(
2495         Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
2496
2497     i += StoreSizeInBytes;
2498   }
2499 }
2500
2501 void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2502                                          ArrayRef<uint8_t> ShadowBytes,
2503                                          IRBuilder<> &IRB, Value *ShadowBase) {
2504   copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2505 }
2506
2507 void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2508                                          ArrayRef<uint8_t> ShadowBytes,
2509                                          size_t Begin, size_t End,
2510                                          IRBuilder<> &IRB, Value *ShadowBase) {
2511   assert(ShadowMask.size() == ShadowBytes.size());
2512   size_t Done = Begin;
2513   for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2514     if (!ShadowMask[i]) {
2515       assert(!ShadowBytes[i]);
2516       continue;
2517     }
2518     uint8_t Val = ShadowBytes[i];
2519     if (!AsanSetShadowFunc[Val])
2520       continue;
2521
2522     // Skip same values.
2523     for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
2524     }
2525
2526     if (j - i >= ClMaxInlinePoisoningSize) {
2527       copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
2528       IRB.CreateCall(AsanSetShadowFunc[Val],
2529                      {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2530                       ConstantInt::get(IntptrTy, j - i)});
2531       Done = j;
2532     }
2533   }
2534
2535   copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
2536 }
2537
2538 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
2539 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2540 static int StackMallocSizeClass(uint64_t LocalStackSize) {
2541   assert(LocalStackSize <= kMaxStackMallocSize);
2542   uint64_t MaxSize = kMinStackMallocSize;
2543   for (int i = 0;; i++, MaxSize *= 2)
2544     if (LocalStackSize <= MaxSize) return i;
2545   llvm_unreachable("impossible LocalStackSize");
2546 }
2547
2548 void FunctionStackPoisoner::copyArgsPassedByValToAllocas() {
2549   BasicBlock &FirstBB = *F.begin();
2550   IRBuilder<> IRB(&FirstBB, FirstBB.getFirstInsertionPt());
2551   const DataLayout &DL = F.getParent()->getDataLayout();
2552   for (Argument &Arg : F.args()) {
2553     if (Arg.hasByValAttr()) {
2554       Type *Ty = Arg.getType()->getPointerElementType();
2555       unsigned Align = Arg.getParamAlignment();
2556       if (Align == 0) Align = DL.getABITypeAlignment(Ty);
2557
2558       const std::string &Name = Arg.hasName() ? Arg.getName().str() :
2559           "Arg" + llvm::to_string(Arg.getArgNo());
2560       AllocaInst *AI = IRB.CreateAlloca(Ty, nullptr, Twine(Name) + ".byval");
2561       AI->setAlignment(Align);
2562       Arg.replaceAllUsesWith(AI);
2563
2564       uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2565       IRB.CreateMemCpy(AI, &Arg, AllocSize, Align);
2566     }
2567   }
2568 }
2569
2570 PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2571                                           Value *ValueIfTrue,
2572                                           Instruction *ThenTerm,
2573                                           Value *ValueIfFalse) {
2574   PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2575   BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2576   PHI->addIncoming(ValueIfFalse, CondBlock);
2577   BasicBlock *ThenBlock = ThenTerm->getParent();
2578   PHI->addIncoming(ValueIfTrue, ThenBlock);
2579   return PHI;
2580 }
2581
2582 Value *FunctionStackPoisoner::createAllocaForLayout(
2583     IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2584   AllocaInst *Alloca;
2585   if (Dynamic) {
2586     Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2587                               ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2588                               "MyAlloca");
2589   } else {
2590     Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2591                               nullptr, "MyAlloca");
2592     assert(Alloca->isStaticAlloca());
2593   }
2594   assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2595   size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2596   Alloca->setAlignment(FrameAlignment);
2597   return IRB.CreatePointerCast(Alloca, IntptrTy);
2598 }
2599
2600 void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2601   BasicBlock &FirstBB = *F.begin();
2602   IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2603   DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2604   IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2605   DynamicAllocaLayout->setAlignment(32);
2606 }
2607
2608 void FunctionStackPoisoner::processDynamicAllocas() {
2609   if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2610     assert(DynamicAllocaPoisonCallVec.empty());
2611     return;
2612   }
2613
2614   // Insert poison calls for lifetime intrinsics for dynamic allocas.
2615   for (const auto &APC : DynamicAllocaPoisonCallVec) {
2616     assert(APC.InsBefore);
2617     assert(APC.AI);
2618     assert(ASan.isInterestingAlloca(*APC.AI));
2619     assert(!APC.AI->isStaticAlloca());
2620
2621     IRBuilder<> IRB(APC.InsBefore);
2622     poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
2623     // Dynamic allocas will be unpoisoned unconditionally below in
2624     // unpoisonDynamicAllocas.
2625     // Flag that we need unpoison static allocas.
2626   }
2627
2628   // Handle dynamic allocas.
2629   createDynamicAllocasInitStorage();
2630   for (auto &AI : DynamicAllocaVec)
2631     handleDynamicAllocaCall(AI);
2632   unpoisonDynamicAllocas();
2633 }
2634
2635 void FunctionStackPoisoner::processStaticAllocas() {
2636   if (AllocaVec.empty()) {
2637     assert(StaticAllocaPoisonCallVec.empty());
2638     return;
2639   }
2640
2641   int StackMallocIdx = -1;
2642   DebugLoc EntryDebugLocation;
2643   if (auto SP = F.getSubprogram())
2644     EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
2645
2646   Instruction *InsBefore = AllocaVec[0];
2647   IRBuilder<> IRB(InsBefore);
2648   IRB.SetCurrentDebugLocation(EntryDebugLocation);
2649
2650   // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2651   // debug info is broken, because only entry-block allocas are treated as
2652   // regular stack slots.
2653   auto InsBeforeB = InsBefore->getParent();
2654   assert(InsBeforeB == &F.getEntryBlock());
2655   for (auto *AI : StaticAllocasToMoveUp)
2656     if (AI->getParent() == InsBeforeB)
2657       AI->moveBefore(InsBefore);
2658
2659   // If we have a call to llvm.localescape, keep it in the entry block.
2660   if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2661
2662   SmallVector<ASanStackVariableDescription, 16> SVD;
2663   SVD.reserve(AllocaVec.size());
2664   for (AllocaInst *AI : AllocaVec) {
2665     ASanStackVariableDescription D = {AI->getName().data(),
2666                                       ASan.getAllocaSizeInBytes(*AI),
2667                                       0,
2668                                       AI->getAlignment(),
2669                                       AI,
2670                                       0,
2671                                       0};
2672     SVD.push_back(D);
2673   }
2674
2675   // Minimal header size (left redzone) is 4 pointers,
2676   // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2677   size_t MinHeaderSize = ASan.LongSize / 2;
2678   const ASanStackFrameLayout &L =
2679       ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize);
2680
2681   // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
2682   DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
2683   for (auto &Desc : SVD)
2684     AllocaToSVDMap[Desc.AI] = &Desc;
2685
2686   // Update SVD with information from lifetime intrinsics.
2687   for (const auto &APC : StaticAllocaPoisonCallVec) {
2688     assert(APC.InsBefore);
2689     assert(APC.AI);
2690     assert(ASan.isInterestingAlloca(*APC.AI));
2691     assert(APC.AI->isStaticAlloca());
2692
2693     ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
2694     Desc.LifetimeSize = Desc.Size;
2695     if (const DILocation *FnLoc = EntryDebugLocation.get()) {
2696       if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
2697         if (LifetimeLoc->getFile() == FnLoc->getFile())
2698           if (unsigned Line = LifetimeLoc->getLine())
2699             Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
2700       }
2701     }
2702   }
2703
2704   auto DescriptionString = ComputeASanStackFrameDescription(SVD);
2705   DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
2706   uint64_t LocalStackSize = L.FrameSize;
2707   bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2708                        LocalStackSize <= kMaxStackMallocSize;
2709   bool DoDynamicAlloca = ClDynamicAllocaStack;
2710   // Don't do dynamic alloca or stack malloc if:
2711   // 1) There is inline asm: too often it makes assumptions on which registers
2712   //    are available.
2713   // 2) There is a returns_twice call (typically setjmp), which is
2714   //    optimization-hostile, and doesn't play well with introduced indirect
2715   //    register-relative calculation of local variable addresses.
2716   DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2717   DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2718
2719   Value *StaticAlloca =
2720       DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2721
2722   Value *FakeStack;
2723   Value *LocalStackBase;
2724
2725   if (DoStackMalloc) {
2726     // void *FakeStack = __asan_option_detect_stack_use_after_return
2727     //     ? __asan_stack_malloc_N(LocalStackSize)
2728     //     : nullptr;
2729     // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
2730     Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2731         kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2732     Value *UseAfterReturnIsEnabled =
2733         IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
2734                          Constant::getNullValue(IRB.getInt32Ty()));
2735     Instruction *Term =
2736         SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
2737     IRBuilder<> IRBIf(Term);
2738     IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2739     StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2740     assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2741     Value *FakeStackValue =
2742         IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2743                          ConstantInt::get(IntptrTy, LocalStackSize));
2744     IRB.SetInsertPoint(InsBefore);
2745     IRB.SetCurrentDebugLocation(EntryDebugLocation);
2746     FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
2747                           ConstantInt::get(IntptrTy, 0));
2748
2749     Value *NoFakeStack =
2750         IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2751     Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2752     IRBIf.SetInsertPoint(Term);
2753     IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2754     Value *AllocaValue =
2755         DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2756     IRB.SetInsertPoint(InsBefore);
2757     IRB.SetCurrentDebugLocation(EntryDebugLocation);
2758     LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2759   } else {
2760     // void *FakeStack = nullptr;
2761     // void *LocalStackBase = alloca(LocalStackSize);
2762     FakeStack = ConstantInt::get(IntptrTy, 0);
2763     LocalStackBase =
2764         DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
2765   }
2766
2767   // Replace Alloca instructions with base+offset.
2768   for (const auto &Desc : SVD) {
2769     AllocaInst *AI = Desc.AI;
2770     Value *NewAllocaPtr = IRB.CreateIntToPtr(
2771         IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
2772         AI->getType());
2773     replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, DIExpression::NoDeref);
2774     AI->replaceAllUsesWith(NewAllocaPtr);
2775   }
2776
2777   // The left-most redzone has enough space for at least 4 pointers.
2778   // Write the Magic value to redzone[0].
2779   Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2780   IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2781                   BasePlus0);
2782   // Write the frame description constant to redzone[1].
2783   Value *BasePlus1 = IRB.CreateIntToPtr(
2784       IRB.CreateAdd(LocalStackBase,
2785                     ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2786       IntptrPtrTy);
2787   GlobalVariable *StackDescriptionGlobal =
2788       createPrivateGlobalForString(*F.getParent(), DescriptionString,
2789                                    /*AllowMerging*/ true);
2790   Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
2791   IRB.CreateStore(Description, BasePlus1);
2792   // Write the PC to redzone[2].
2793   Value *BasePlus2 = IRB.CreateIntToPtr(
2794       IRB.CreateAdd(LocalStackBase,
2795                     ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2796       IntptrPtrTy);
2797   IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
2798
2799   const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
2800
2801   // Poison the stack red zones at the entry.
2802   Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
2803   // As mask we must use most poisoned case: red zones and after scope.
2804   // As bytes we can use either the same or just red zones only.
2805   copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
2806
2807   if (!StaticAllocaPoisonCallVec.empty()) {
2808     const auto &ShadowInScope = GetShadowBytes(SVD, L);
2809
2810     // Poison static allocas near lifetime intrinsics.
2811     for (const auto &APC : StaticAllocaPoisonCallVec) {
2812       const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
2813       assert(Desc.Offset % L.Granularity == 0);
2814       size_t Begin = Desc.Offset / L.Granularity;
2815       size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
2816
2817       IRBuilder<> IRB(APC.InsBefore);
2818       copyToShadow(ShadowAfterScope,
2819                    APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
2820                    IRB, ShadowBase);
2821     }
2822   }
2823
2824   SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
2825   SmallVector<uint8_t, 64> ShadowAfterReturn;
2826
2827   // (Un)poison the stack before all ret instructions.
2828   for (auto Ret : RetVec) {
2829     IRBuilder<> IRBRet(Ret);
2830     // Mark the current frame as retired.
2831     IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2832                        BasePlus0);
2833     if (DoStackMalloc) {
2834       assert(StackMallocIdx >= 0);
2835       // if FakeStack != 0  // LocalStackBase == FakeStack
2836       //     // In use-after-return mode, poison the whole stack frame.
2837       //     if StackMallocIdx <= 4
2838       //         // For small sizes inline the whole thing:
2839       //         memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
2840       //         **SavedFlagPtr(FakeStack) = 0
2841       //     else
2842       //         __asan_stack_free_N(FakeStack, LocalStackSize)
2843       // else
2844       //     <This is not a fake stack; unpoison the redzones>
2845       Value *Cmp =
2846           IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
2847       TerminatorInst *ThenTerm, *ElseTerm;
2848       SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2849
2850       IRBuilder<> IRBPoison(ThenTerm);
2851       if (StackMallocIdx <= 4) {
2852         int ClassSize = kMinStackMallocSize << StackMallocIdx;
2853         ShadowAfterReturn.resize(ClassSize / L.Granularity,
2854                                  kAsanStackUseAfterReturnMagic);
2855         copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
2856                      ShadowBase);
2857         Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
2858             FakeStack,
2859             ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2860         Value *SavedFlagPtr = IRBPoison.CreateLoad(
2861             IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2862         IRBPoison.CreateStore(
2863             Constant::getNullValue(IRBPoison.getInt8Ty()),
2864             IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2865       } else {
2866         // For larger frames call __asan_stack_free_*.
2867         IRBPoison.CreateCall(
2868             AsanStackFreeFunc[StackMallocIdx],
2869             {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
2870       }
2871
2872       IRBuilder<> IRBElse(ElseTerm);
2873       copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
2874     } else {
2875       copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
2876     }
2877   }
2878
2879   // We are done. Remove the old unused alloca instructions.
2880   for (auto AI : AllocaVec) AI->eraseFromParent();
2881 }
2882
2883 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
2884                                          IRBuilder<> &IRB, bool DoPoison) {
2885   // For now just insert the call to ASan runtime.
2886   Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2887   Value *SizeArg = ConstantInt::get(IntptrTy, Size);
2888   IRB.CreateCall(
2889       DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2890       {AddrArg, SizeArg});
2891 }
2892
2893 // Handling llvm.lifetime intrinsics for a given %alloca:
2894 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2895 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2896 //     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2897 //     could be poisoned by previous llvm.lifetime.end instruction, as the
2898 //     variable may go in and out of scope several times, e.g. in loops).
2899 // (3) if we poisoned at least one %alloca in a function,
2900 //     unpoison the whole stack frame at function exit.
2901
2902 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2903   if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
2904     // We're interested only in allocas we can handle.
2905     return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
2906   // See if we've already calculated (or started to calculate) alloca for a
2907   // given value.
2908   AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
2909   if (I != AllocaForValue.end()) return I->second;
2910   // Store 0 while we're calculating alloca for value V to avoid
2911   // infinite recursion if the value references itself.
2912   AllocaForValue[V] = nullptr;
2913   AllocaInst *Res = nullptr;
2914   if (CastInst *CI = dyn_cast<CastInst>(V))
2915     Res = findAllocaForValue(CI->getOperand(0));
2916   else if (PHINode *PN = dyn_cast<PHINode>(V)) {
2917     for (Value *IncValue : PN->incoming_values()) {
2918       // Allow self-referencing phi-nodes.
2919       if (IncValue == PN) continue;
2920       AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2921       // AI for incoming values should exist and should all be equal.
2922       if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2923         return nullptr;
2924       Res = IncValueAI;
2925     }
2926   } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
2927     Res = findAllocaForValue(EP->getPointerOperand());
2928   } else {
2929     DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V << "\n");
2930   }
2931   if (Res) AllocaForValue[V] = Res;
2932   return Res;
2933 }
2934
2935 void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
2936   IRBuilder<> IRB(AI);
2937
2938   const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2939   const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2940
2941   Value *Zero = Constant::getNullValue(IntptrTy);
2942   Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2943   Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
2944
2945   // Since we need to extend alloca with additional memory to locate
2946   // redzones, and OldSize is number of allocated blocks with
2947   // ElementSize size, get allocated memory size in bytes by
2948   // OldSize * ElementSize.
2949   const unsigned ElementSize =
2950       F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
2951   Value *OldSize =
2952       IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2953                     ConstantInt::get(IntptrTy, ElementSize));
2954
2955   // PartialSize = OldSize % 32
2956   Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2957
2958   // Misalign = kAllocaRzSize - PartialSize;
2959   Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2960
2961   // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2962   Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2963   Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2964
2965   // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2966   // Align is added to locate left redzone, PartialPadding for possible
2967   // partial redzone and kAllocaRzSize for right redzone respectively.
2968   Value *AdditionalChunkSize = IRB.CreateAdd(
2969       ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2970
2971   Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2972
2973   // Insert new alloca with new NewSize and Align params.
2974   AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2975   NewAlloca->setAlignment(Align);
2976
2977   // NewAddress = Address + Align
2978   Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2979                                     ConstantInt::get(IntptrTy, Align));
2980
2981   // Insert __asan_alloca_poison call for new created alloca.
2982   IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
2983
2984   // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2985   // for unpoisoning stuff.
2986   IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2987
2988   Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2989
2990   // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
2991   AI->replaceAllUsesWith(NewAddressPtr);
2992
2993   // We are done. Erase old alloca from parent.
2994   AI->eraseFromParent();
2995 }
2996
2997 // isSafeAccess returns true if Addr is always inbounds with respect to its
2998 // base object. For example, it is a field access or an array access with
2999 // constant inbounds index.
3000 bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
3001                                     Value *Addr, uint64_t TypeSize) const {
3002   SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
3003   if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
3004   uint64_t Size = SizeOffset.first.getZExtValue();
3005   int64_t Offset = SizeOffset.second.getSExtValue();
3006   // Three checks are required to ensure safety:
3007   // . Offset >= 0  (since the offset is given from the base ptr)
3008   // . Size >= Offset  (unsigned)
3009   // . Size - Offset >= NeededSize  (unsigned)
3010   return Offset >= 0 && Size >= uint64_t(Offset) &&
3011          Size - uint64_t(Offset) >= TypeSize / 8;
3012 }