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