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