106f32e7eSjoerg //===- AddressSanitizer.cpp - memory error detector -----------------------===//
206f32e7eSjoerg //
306f32e7eSjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
406f32e7eSjoerg // See https://llvm.org/LICENSE.txt for license information.
506f32e7eSjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
606f32e7eSjoerg //
706f32e7eSjoerg //===----------------------------------------------------------------------===//
806f32e7eSjoerg //
906f32e7eSjoerg // This file is a part of AddressSanitizer, an address sanity checker.
1006f32e7eSjoerg // Details of the algorithm:
1106f32e7eSjoerg //  https://github.com/google/sanitizers/wiki/AddressSanitizerAlgorithm
1206f32e7eSjoerg //
13*da58b97aSjoerg // FIXME: This sanitizer does not yet handle scalable vectors
14*da58b97aSjoerg //
1506f32e7eSjoerg //===----------------------------------------------------------------------===//
1606f32e7eSjoerg 
1706f32e7eSjoerg #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
1806f32e7eSjoerg #include "llvm/ADT/ArrayRef.h"
1906f32e7eSjoerg #include "llvm/ADT/DenseMap.h"
2006f32e7eSjoerg #include "llvm/ADT/DepthFirstIterator.h"
2106f32e7eSjoerg #include "llvm/ADT/SmallPtrSet.h"
2206f32e7eSjoerg #include "llvm/ADT/SmallVector.h"
2306f32e7eSjoerg #include "llvm/ADT/Statistic.h"
2406f32e7eSjoerg #include "llvm/ADT/StringExtras.h"
2506f32e7eSjoerg #include "llvm/ADT/StringRef.h"
2606f32e7eSjoerg #include "llvm/ADT/Triple.h"
2706f32e7eSjoerg #include "llvm/ADT/Twine.h"
2806f32e7eSjoerg #include "llvm/Analysis/MemoryBuiltins.h"
2906f32e7eSjoerg #include "llvm/Analysis/TargetLibraryInfo.h"
3006f32e7eSjoerg #include "llvm/Analysis/ValueTracking.h"
3106f32e7eSjoerg #include "llvm/BinaryFormat/MachO.h"
3206f32e7eSjoerg #include "llvm/IR/Argument.h"
3306f32e7eSjoerg #include "llvm/IR/Attributes.h"
3406f32e7eSjoerg #include "llvm/IR/BasicBlock.h"
3506f32e7eSjoerg #include "llvm/IR/Comdat.h"
3606f32e7eSjoerg #include "llvm/IR/Constant.h"
3706f32e7eSjoerg #include "llvm/IR/Constants.h"
3806f32e7eSjoerg #include "llvm/IR/DIBuilder.h"
3906f32e7eSjoerg #include "llvm/IR/DataLayout.h"
4006f32e7eSjoerg #include "llvm/IR/DebugInfoMetadata.h"
4106f32e7eSjoerg #include "llvm/IR/DebugLoc.h"
4206f32e7eSjoerg #include "llvm/IR/DerivedTypes.h"
4306f32e7eSjoerg #include "llvm/IR/Dominators.h"
4406f32e7eSjoerg #include "llvm/IR/Function.h"
4506f32e7eSjoerg #include "llvm/IR/GlobalAlias.h"
4606f32e7eSjoerg #include "llvm/IR/GlobalValue.h"
4706f32e7eSjoerg #include "llvm/IR/GlobalVariable.h"
4806f32e7eSjoerg #include "llvm/IR/IRBuilder.h"
4906f32e7eSjoerg #include "llvm/IR/InlineAsm.h"
5006f32e7eSjoerg #include "llvm/IR/InstVisitor.h"
5106f32e7eSjoerg #include "llvm/IR/InstrTypes.h"
5206f32e7eSjoerg #include "llvm/IR/Instruction.h"
5306f32e7eSjoerg #include "llvm/IR/Instructions.h"
5406f32e7eSjoerg #include "llvm/IR/IntrinsicInst.h"
5506f32e7eSjoerg #include "llvm/IR/Intrinsics.h"
5606f32e7eSjoerg #include "llvm/IR/LLVMContext.h"
5706f32e7eSjoerg #include "llvm/IR/MDBuilder.h"
5806f32e7eSjoerg #include "llvm/IR/Metadata.h"
5906f32e7eSjoerg #include "llvm/IR/Module.h"
6006f32e7eSjoerg #include "llvm/IR/Type.h"
6106f32e7eSjoerg #include "llvm/IR/Use.h"
6206f32e7eSjoerg #include "llvm/IR/Value.h"
63*da58b97aSjoerg #include "llvm/InitializePasses.h"
6406f32e7eSjoerg #include "llvm/MC/MCSectionMachO.h"
6506f32e7eSjoerg #include "llvm/Pass.h"
6606f32e7eSjoerg #include "llvm/Support/Casting.h"
6706f32e7eSjoerg #include "llvm/Support/CommandLine.h"
6806f32e7eSjoerg #include "llvm/Support/Debug.h"
6906f32e7eSjoerg #include "llvm/Support/ErrorHandling.h"
7006f32e7eSjoerg #include "llvm/Support/MathExtras.h"
7106f32e7eSjoerg #include "llvm/Support/ScopedPrinter.h"
7206f32e7eSjoerg #include "llvm/Support/raw_ostream.h"
7306f32e7eSjoerg #include "llvm/Transforms/Instrumentation.h"
74*da58b97aSjoerg #include "llvm/Transforms/Instrumentation/AddressSanitizerCommon.h"
7506f32e7eSjoerg #include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
7606f32e7eSjoerg #include "llvm/Transforms/Utils/BasicBlockUtils.h"
7706f32e7eSjoerg #include "llvm/Transforms/Utils/Local.h"
7806f32e7eSjoerg #include "llvm/Transforms/Utils/ModuleUtils.h"
7906f32e7eSjoerg #include "llvm/Transforms/Utils/PromoteMemToReg.h"
8006f32e7eSjoerg #include <algorithm>
8106f32e7eSjoerg #include <cassert>
8206f32e7eSjoerg #include <cstddef>
8306f32e7eSjoerg #include <cstdint>
8406f32e7eSjoerg #include <iomanip>
8506f32e7eSjoerg #include <limits>
8606f32e7eSjoerg #include <memory>
8706f32e7eSjoerg #include <sstream>
8806f32e7eSjoerg #include <string>
8906f32e7eSjoerg #include <tuple>
9006f32e7eSjoerg 
9106f32e7eSjoerg using namespace llvm;
9206f32e7eSjoerg 
9306f32e7eSjoerg #define DEBUG_TYPE "asan"
9406f32e7eSjoerg 
9506f32e7eSjoerg static const uint64_t kDefaultShadowScale = 3;
9606f32e7eSjoerg static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
9706f32e7eSjoerg static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
9806f32e7eSjoerg static const uint64_t kDynamicShadowSentinel =
9906f32e7eSjoerg     std::numeric_limits<uint64_t>::max();
10006f32e7eSjoerg static const uint64_t kSmallX86_64ShadowOffsetBase = 0x7FFFFFFF;  // < 2G.
10106f32e7eSjoerg static const uint64_t kSmallX86_64ShadowOffsetAlignMask = ~0xFFFULL;
10206f32e7eSjoerg static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
10306f32e7eSjoerg static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 44;
10406f32e7eSjoerg static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
10506f32e7eSjoerg static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
10606f32e7eSjoerg static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
10706f32e7eSjoerg static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
108*da58b97aSjoerg static const uint64_t kRISCV64_ShadowOffset64 = 0xd55550000;
10906f32e7eSjoerg static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
11006f32e7eSjoerg static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
111*da58b97aSjoerg static const uint64_t kFreeBSDKasan_ShadowOffset64 = 0xdffff7c000000000;
11206f32e7eSjoerg static const uint64_t kNetBSD_ShadowOffset32 = 1ULL << 30;
11306f32e7eSjoerg static const uint64_t kNetBSD_ShadowOffset64 = 1ULL << 46;
11406f32e7eSjoerg static const uint64_t kNetBSDKasan_ShadowOffset64 = 0xdfff900000000000;
11506f32e7eSjoerg static const uint64_t kPS4CPU_ShadowOffset64 = 1ULL << 40;
11606f32e7eSjoerg static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
11706f32e7eSjoerg static const uint64_t kEmscriptenShadowOffset = 0;
11806f32e7eSjoerg 
11906f32e7eSjoerg static const uint64_t kMyriadShadowScale = 5;
12006f32e7eSjoerg static const uint64_t kMyriadMemoryOffset32 = 0x80000000ULL;
12106f32e7eSjoerg static const uint64_t kMyriadMemorySize32 = 0x20000000ULL;
12206f32e7eSjoerg static const uint64_t kMyriadTagShift = 29;
12306f32e7eSjoerg static const uint64_t kMyriadDDRTag = 4;
12406f32e7eSjoerg static const uint64_t kMyriadCacheBitMask32 = 0x40000000ULL;
12506f32e7eSjoerg 
12606f32e7eSjoerg // The shadow memory space is dynamically allocated.
12706f32e7eSjoerg static const uint64_t kWindowsShadowOffset64 = kDynamicShadowSentinel;
12806f32e7eSjoerg 
12906f32e7eSjoerg static const size_t kMinStackMallocSize = 1 << 6;   // 64B
13006f32e7eSjoerg static const size_t kMaxStackMallocSize = 1 << 16;  // 64K
13106f32e7eSjoerg static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
13206f32e7eSjoerg static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
13306f32e7eSjoerg 
134*da58b97aSjoerg const char kAsanModuleCtorName[] = "asan.module_ctor";
135*da58b97aSjoerg const char kAsanModuleDtorName[] = "asan.module_dtor";
13606f32e7eSjoerg static const uint64_t kAsanCtorAndDtorPriority = 1;
13706f32e7eSjoerg // On Emscripten, the system needs more than one priorities for constructors.
13806f32e7eSjoerg static const uint64_t kAsanEmscriptenCtorAndDtorPriority = 50;
139*da58b97aSjoerg const char kAsanReportErrorTemplate[] = "__asan_report_";
140*da58b97aSjoerg const char kAsanRegisterGlobalsName[] = "__asan_register_globals";
141*da58b97aSjoerg const char kAsanUnregisterGlobalsName[] = "__asan_unregister_globals";
142*da58b97aSjoerg const char kAsanRegisterImageGlobalsName[] = "__asan_register_image_globals";
143*da58b97aSjoerg const char kAsanUnregisterImageGlobalsName[] =
14406f32e7eSjoerg     "__asan_unregister_image_globals";
145*da58b97aSjoerg const char kAsanRegisterElfGlobalsName[] = "__asan_register_elf_globals";
146*da58b97aSjoerg const char kAsanUnregisterElfGlobalsName[] = "__asan_unregister_elf_globals";
147*da58b97aSjoerg const char kAsanPoisonGlobalsName[] = "__asan_before_dynamic_init";
148*da58b97aSjoerg const char kAsanUnpoisonGlobalsName[] = "__asan_after_dynamic_init";
149*da58b97aSjoerg const char kAsanInitName[] = "__asan_init";
150*da58b97aSjoerg const char kAsanVersionCheckNamePrefix[] = "__asan_version_mismatch_check_v";
151*da58b97aSjoerg const char kAsanPtrCmp[] = "__sanitizer_ptr_cmp";
152*da58b97aSjoerg const char kAsanPtrSub[] = "__sanitizer_ptr_sub";
153*da58b97aSjoerg const char kAsanHandleNoReturnName[] = "__asan_handle_no_return";
15406f32e7eSjoerg static const int kMaxAsanStackMallocSizeClass = 10;
155*da58b97aSjoerg const char kAsanStackMallocNameTemplate[] = "__asan_stack_malloc_";
156*da58b97aSjoerg const char kAsanStackFreeNameTemplate[] = "__asan_stack_free_";
157*da58b97aSjoerg const char kAsanGenPrefix[] = "___asan_gen_";
158*da58b97aSjoerg const char kODRGenPrefix[] = "__odr_asan_gen_";
159*da58b97aSjoerg const char kSanCovGenPrefix[] = "__sancov_gen_";
160*da58b97aSjoerg const char kAsanSetShadowPrefix[] = "__asan_set_shadow_";
161*da58b97aSjoerg const char kAsanPoisonStackMemoryName[] = "__asan_poison_stack_memory";
162*da58b97aSjoerg const char kAsanUnpoisonStackMemoryName[] = "__asan_unpoison_stack_memory";
16306f32e7eSjoerg 
16406f32e7eSjoerg // ASan version script has __asan_* wildcard. Triple underscore prevents a
16506f32e7eSjoerg // linker (gold) warning about attempting to export a local symbol.
166*da58b97aSjoerg const char kAsanGlobalsRegisteredFlagName[] = "___asan_globals_registered";
16706f32e7eSjoerg 
168*da58b97aSjoerg const char kAsanOptionDetectUseAfterReturn[] =
16906f32e7eSjoerg     "__asan_option_detect_stack_use_after_return";
17006f32e7eSjoerg 
171*da58b97aSjoerg const char kAsanShadowMemoryDynamicAddress[] =
17206f32e7eSjoerg     "__asan_shadow_memory_dynamic_address";
17306f32e7eSjoerg 
174*da58b97aSjoerg const char kAsanAllocaPoison[] = "__asan_alloca_poison";
175*da58b97aSjoerg const char kAsanAllocasUnpoison[] = "__asan_allocas_unpoison";
176*da58b97aSjoerg 
177*da58b97aSjoerg const char kAMDGPUAddressSharedName[] = "llvm.amdgcn.is.shared";
178*da58b97aSjoerg const char kAMDGPUAddressPrivateName[] = "llvm.amdgcn.is.private";
17906f32e7eSjoerg 
18006f32e7eSjoerg // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
18106f32e7eSjoerg static const size_t kNumberOfAccessSizes = 5;
18206f32e7eSjoerg 
18306f32e7eSjoerg static const unsigned kAllocaRzSize = 32;
18406f32e7eSjoerg 
18506f32e7eSjoerg // Command-line flags.
18606f32e7eSjoerg 
18706f32e7eSjoerg static cl::opt<bool> ClEnableKasan(
18806f32e7eSjoerg     "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
18906f32e7eSjoerg     cl::Hidden, cl::init(false));
19006f32e7eSjoerg 
19106f32e7eSjoerg static cl::opt<bool> ClRecover(
19206f32e7eSjoerg     "asan-recover",
19306f32e7eSjoerg     cl::desc("Enable recovery mode (continue-after-error)."),
19406f32e7eSjoerg     cl::Hidden, cl::init(false));
19506f32e7eSjoerg 
19606f32e7eSjoerg static cl::opt<bool> ClInsertVersionCheck(
19706f32e7eSjoerg     "asan-guard-against-version-mismatch",
19806f32e7eSjoerg     cl::desc("Guard against compiler/runtime version mismatch."),
19906f32e7eSjoerg     cl::Hidden, cl::init(true));
20006f32e7eSjoerg 
20106f32e7eSjoerg // This flag may need to be replaced with -f[no-]asan-reads.
20206f32e7eSjoerg static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
20306f32e7eSjoerg                                        cl::desc("instrument read instructions"),
20406f32e7eSjoerg                                        cl::Hidden, cl::init(true));
20506f32e7eSjoerg 
20606f32e7eSjoerg static cl::opt<bool> ClInstrumentWrites(
20706f32e7eSjoerg     "asan-instrument-writes", cl::desc("instrument write instructions"),
20806f32e7eSjoerg     cl::Hidden, cl::init(true));
20906f32e7eSjoerg 
21006f32e7eSjoerg static cl::opt<bool> ClInstrumentAtomics(
21106f32e7eSjoerg     "asan-instrument-atomics",
21206f32e7eSjoerg     cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
21306f32e7eSjoerg     cl::init(true));
21406f32e7eSjoerg 
215*da58b97aSjoerg static cl::opt<bool>
216*da58b97aSjoerg     ClInstrumentByval("asan-instrument-byval",
217*da58b97aSjoerg                       cl::desc("instrument byval call arguments"), cl::Hidden,
218*da58b97aSjoerg                       cl::init(true));
219*da58b97aSjoerg 
22006f32e7eSjoerg static cl::opt<bool> ClAlwaysSlowPath(
22106f32e7eSjoerg     "asan-always-slow-path",
22206f32e7eSjoerg     cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
22306f32e7eSjoerg     cl::init(false));
22406f32e7eSjoerg 
22506f32e7eSjoerg static cl::opt<bool> ClForceDynamicShadow(
22606f32e7eSjoerg     "asan-force-dynamic-shadow",
22706f32e7eSjoerg     cl::desc("Load shadow address into a local variable for each function"),
22806f32e7eSjoerg     cl::Hidden, cl::init(false));
22906f32e7eSjoerg 
23006f32e7eSjoerg static cl::opt<bool>
23106f32e7eSjoerg     ClWithIfunc("asan-with-ifunc",
23206f32e7eSjoerg                 cl::desc("Access dynamic shadow through an ifunc global on "
23306f32e7eSjoerg                          "platforms that support this"),
23406f32e7eSjoerg                 cl::Hidden, cl::init(true));
23506f32e7eSjoerg 
23606f32e7eSjoerg static cl::opt<bool> ClWithIfuncSuppressRemat(
23706f32e7eSjoerg     "asan-with-ifunc-suppress-remat",
23806f32e7eSjoerg     cl::desc("Suppress rematerialization of dynamic shadow address by passing "
23906f32e7eSjoerg              "it through inline asm in prologue."),
24006f32e7eSjoerg     cl::Hidden, cl::init(true));
24106f32e7eSjoerg 
24206f32e7eSjoerg // This flag limits the number of instructions to be instrumented
24306f32e7eSjoerg // in any given BB. Normally, this should be set to unlimited (INT_MAX),
24406f32e7eSjoerg // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
24506f32e7eSjoerg // set it to 10000.
24606f32e7eSjoerg static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
24706f32e7eSjoerg     "asan-max-ins-per-bb", cl::init(10000),
24806f32e7eSjoerg     cl::desc("maximal number of instructions to instrument in any given BB"),
24906f32e7eSjoerg     cl::Hidden);
25006f32e7eSjoerg 
25106f32e7eSjoerg // This flag may need to be replaced with -f[no]asan-stack.
25206f32e7eSjoerg static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
25306f32e7eSjoerg                              cl::Hidden, cl::init(true));
25406f32e7eSjoerg static cl::opt<uint32_t> ClMaxInlinePoisoningSize(
25506f32e7eSjoerg     "asan-max-inline-poisoning-size",
25606f32e7eSjoerg     cl::desc(
25706f32e7eSjoerg         "Inline shadow poisoning for blocks up to the given size in bytes."),
25806f32e7eSjoerg     cl::Hidden, cl::init(64));
25906f32e7eSjoerg 
26006f32e7eSjoerg static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
26106f32e7eSjoerg                                       cl::desc("Check stack-use-after-return"),
26206f32e7eSjoerg                                       cl::Hidden, cl::init(true));
26306f32e7eSjoerg 
26406f32e7eSjoerg static cl::opt<bool> ClRedzoneByvalArgs("asan-redzone-byval-args",
26506f32e7eSjoerg                                         cl::desc("Create redzones for byval "
26606f32e7eSjoerg                                                  "arguments (extra copy "
26706f32e7eSjoerg                                                  "required)"), cl::Hidden,
26806f32e7eSjoerg                                         cl::init(true));
26906f32e7eSjoerg 
27006f32e7eSjoerg static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
27106f32e7eSjoerg                                      cl::desc("Check stack-use-after-scope"),
27206f32e7eSjoerg                                      cl::Hidden, cl::init(false));
27306f32e7eSjoerg 
27406f32e7eSjoerg // This flag may need to be replaced with -f[no]asan-globals.
27506f32e7eSjoerg static cl::opt<bool> ClGlobals("asan-globals",
27606f32e7eSjoerg                                cl::desc("Handle global objects"), cl::Hidden,
27706f32e7eSjoerg                                cl::init(true));
27806f32e7eSjoerg 
27906f32e7eSjoerg static cl::opt<bool> ClInitializers("asan-initialization-order",
28006f32e7eSjoerg                                     cl::desc("Handle C++ initializer order"),
28106f32e7eSjoerg                                     cl::Hidden, cl::init(true));
28206f32e7eSjoerg 
28306f32e7eSjoerg static cl::opt<bool> ClInvalidPointerPairs(
28406f32e7eSjoerg     "asan-detect-invalid-pointer-pair",
28506f32e7eSjoerg     cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
28606f32e7eSjoerg     cl::init(false));
28706f32e7eSjoerg 
28806f32e7eSjoerg static cl::opt<bool> ClInvalidPointerCmp(
28906f32e7eSjoerg     "asan-detect-invalid-pointer-cmp",
29006f32e7eSjoerg     cl::desc("Instrument <, <=, >, >= with pointer operands"), cl::Hidden,
29106f32e7eSjoerg     cl::init(false));
29206f32e7eSjoerg 
29306f32e7eSjoerg static cl::opt<bool> ClInvalidPointerSub(
29406f32e7eSjoerg     "asan-detect-invalid-pointer-sub",
29506f32e7eSjoerg     cl::desc("Instrument - operations with pointer operands"), cl::Hidden,
29606f32e7eSjoerg     cl::init(false));
29706f32e7eSjoerg 
29806f32e7eSjoerg static cl::opt<unsigned> ClRealignStack(
29906f32e7eSjoerg     "asan-realign-stack",
30006f32e7eSjoerg     cl::desc("Realign stack to the value of this flag (power of two)"),
30106f32e7eSjoerg     cl::Hidden, cl::init(32));
30206f32e7eSjoerg 
30306f32e7eSjoerg static cl::opt<int> ClInstrumentationWithCallsThreshold(
30406f32e7eSjoerg     "asan-instrumentation-with-call-threshold",
30506f32e7eSjoerg     cl::desc(
30606f32e7eSjoerg         "If the function being instrumented contains more than "
30706f32e7eSjoerg         "this number of memory accesses, use callbacks instead of "
30806f32e7eSjoerg         "inline checks (-1 means never use callbacks)."),
30906f32e7eSjoerg     cl::Hidden, cl::init(7000));
31006f32e7eSjoerg 
31106f32e7eSjoerg static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
31206f32e7eSjoerg     "asan-memory-access-callback-prefix",
31306f32e7eSjoerg     cl::desc("Prefix for memory access callbacks"), cl::Hidden,
31406f32e7eSjoerg     cl::init("__asan_"));
31506f32e7eSjoerg 
31606f32e7eSjoerg static cl::opt<bool>
31706f32e7eSjoerg     ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
31806f32e7eSjoerg                                cl::desc("instrument dynamic allocas"),
31906f32e7eSjoerg                                cl::Hidden, cl::init(true));
32006f32e7eSjoerg 
32106f32e7eSjoerg static cl::opt<bool> ClSkipPromotableAllocas(
32206f32e7eSjoerg     "asan-skip-promotable-allocas",
32306f32e7eSjoerg     cl::desc("Do not instrument promotable allocas"), cl::Hidden,
32406f32e7eSjoerg     cl::init(true));
32506f32e7eSjoerg 
32606f32e7eSjoerg // These flags allow to change the shadow mapping.
32706f32e7eSjoerg // The shadow mapping looks like
32806f32e7eSjoerg //    Shadow = (Mem >> scale) + offset
32906f32e7eSjoerg 
33006f32e7eSjoerg static cl::opt<int> ClMappingScale("asan-mapping-scale",
33106f32e7eSjoerg                                    cl::desc("scale of asan shadow mapping"),
33206f32e7eSjoerg                                    cl::Hidden, cl::init(0));
33306f32e7eSjoerg 
33406f32e7eSjoerg static cl::opt<uint64_t>
33506f32e7eSjoerg     ClMappingOffset("asan-mapping-offset",
33606f32e7eSjoerg                     cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"),
33706f32e7eSjoerg                     cl::Hidden, cl::init(0));
33806f32e7eSjoerg 
33906f32e7eSjoerg // Optimization flags. Not user visible, used mostly for testing
34006f32e7eSjoerg // and benchmarking the tool.
34106f32e7eSjoerg 
34206f32e7eSjoerg static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
34306f32e7eSjoerg                            cl::Hidden, cl::init(true));
34406f32e7eSjoerg 
34506f32e7eSjoerg static cl::opt<bool> ClOptSameTemp(
34606f32e7eSjoerg     "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
34706f32e7eSjoerg     cl::Hidden, cl::init(true));
34806f32e7eSjoerg 
34906f32e7eSjoerg static cl::opt<bool> ClOptGlobals("asan-opt-globals",
35006f32e7eSjoerg                                   cl::desc("Don't instrument scalar globals"),
35106f32e7eSjoerg                                   cl::Hidden, cl::init(true));
35206f32e7eSjoerg 
35306f32e7eSjoerg static cl::opt<bool> ClOptStack(
35406f32e7eSjoerg     "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
35506f32e7eSjoerg     cl::Hidden, cl::init(false));
35606f32e7eSjoerg 
35706f32e7eSjoerg static cl::opt<bool> ClDynamicAllocaStack(
35806f32e7eSjoerg     "asan-stack-dynamic-alloca",
35906f32e7eSjoerg     cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
36006f32e7eSjoerg     cl::init(true));
36106f32e7eSjoerg 
36206f32e7eSjoerg static cl::opt<uint32_t> ClForceExperiment(
36306f32e7eSjoerg     "asan-force-experiment",
36406f32e7eSjoerg     cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
36506f32e7eSjoerg     cl::init(0));
36606f32e7eSjoerg 
36706f32e7eSjoerg static cl::opt<bool>
36806f32e7eSjoerg     ClUsePrivateAlias("asan-use-private-alias",
36906f32e7eSjoerg                       cl::desc("Use private aliases for global variables"),
37006f32e7eSjoerg                       cl::Hidden, cl::init(false));
37106f32e7eSjoerg 
37206f32e7eSjoerg static cl::opt<bool>
37306f32e7eSjoerg     ClUseOdrIndicator("asan-use-odr-indicator",
37406f32e7eSjoerg                       cl::desc("Use odr indicators to improve ODR reporting"),
37506f32e7eSjoerg                       cl::Hidden, cl::init(false));
37606f32e7eSjoerg 
37706f32e7eSjoerg static cl::opt<bool>
37806f32e7eSjoerg     ClUseGlobalsGC("asan-globals-live-support",
37906f32e7eSjoerg                    cl::desc("Use linker features to support dead "
38006f32e7eSjoerg                             "code stripping of globals"),
38106f32e7eSjoerg                    cl::Hidden, cl::init(true));
38206f32e7eSjoerg 
38306f32e7eSjoerg // This is on by default even though there is a bug in gold:
38406f32e7eSjoerg // https://sourceware.org/bugzilla/show_bug.cgi?id=19002
38506f32e7eSjoerg static cl::opt<bool>
38606f32e7eSjoerg     ClWithComdat("asan-with-comdat",
38706f32e7eSjoerg                  cl::desc("Place ASan constructors in comdat sections"),
38806f32e7eSjoerg                  cl::Hidden, cl::init(true));
38906f32e7eSjoerg 
390*da58b97aSjoerg static cl::opt<AsanDtorKind> ClOverrideDestructorKind(
391*da58b97aSjoerg     "asan-destructor-kind",
392*da58b97aSjoerg     cl::desc("Sets the ASan destructor kind. The default is to use the value "
393*da58b97aSjoerg              "provided to the pass constructor"),
394*da58b97aSjoerg     cl::values(clEnumValN(AsanDtorKind::None, "none", "No destructors"),
395*da58b97aSjoerg                clEnumValN(AsanDtorKind::Global, "global",
396*da58b97aSjoerg                           "Use global destructors")),
397*da58b97aSjoerg     cl::init(AsanDtorKind::Invalid), cl::Hidden);
398*da58b97aSjoerg 
39906f32e7eSjoerg // Debug flags.
40006f32e7eSjoerg 
40106f32e7eSjoerg static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
40206f32e7eSjoerg                             cl::init(0));
40306f32e7eSjoerg 
40406f32e7eSjoerg static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
40506f32e7eSjoerg                                  cl::Hidden, cl::init(0));
40606f32e7eSjoerg 
40706f32e7eSjoerg static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
40806f32e7eSjoerg                                         cl::desc("Debug func"));
40906f32e7eSjoerg 
41006f32e7eSjoerg static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
41106f32e7eSjoerg                                cl::Hidden, cl::init(-1));
41206f32e7eSjoerg 
41306f32e7eSjoerg static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),
41406f32e7eSjoerg                                cl::Hidden, cl::init(-1));
41506f32e7eSjoerg 
41606f32e7eSjoerg STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
41706f32e7eSjoerg STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
41806f32e7eSjoerg STATISTIC(NumOptimizedAccessesToGlobalVar,
41906f32e7eSjoerg           "Number of optimized accesses to global vars");
42006f32e7eSjoerg STATISTIC(NumOptimizedAccessesToStackVar,
42106f32e7eSjoerg           "Number of optimized accesses to stack vars");
42206f32e7eSjoerg 
42306f32e7eSjoerg namespace {
42406f32e7eSjoerg 
42506f32e7eSjoerg /// This struct defines the shadow mapping using the rule:
42606f32e7eSjoerg ///   shadow = (mem >> Scale) ADD-or-OR Offset.
42706f32e7eSjoerg /// If InGlobal is true, then
42806f32e7eSjoerg ///   extern char __asan_shadow[];
42906f32e7eSjoerg ///   shadow = (mem >> Scale) + &__asan_shadow
43006f32e7eSjoerg struct ShadowMapping {
43106f32e7eSjoerg   int Scale;
43206f32e7eSjoerg   uint64_t Offset;
43306f32e7eSjoerg   bool OrShadowOffset;
43406f32e7eSjoerg   bool InGlobal;
43506f32e7eSjoerg };
43606f32e7eSjoerg 
43706f32e7eSjoerg } // end anonymous namespace
43806f32e7eSjoerg 
getShadowMapping(Triple & TargetTriple,int LongSize,bool IsKasan)43906f32e7eSjoerg static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
44006f32e7eSjoerg                                       bool IsKasan) {
44106f32e7eSjoerg   bool IsAndroid = TargetTriple.isAndroid();
44206f32e7eSjoerg   bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
443*da58b97aSjoerg   bool IsMacOS = TargetTriple.isMacOSX();
44406f32e7eSjoerg   bool IsFreeBSD = TargetTriple.isOSFreeBSD();
44506f32e7eSjoerg   bool IsNetBSD = TargetTriple.isOSNetBSD();
44606f32e7eSjoerg   bool IsPS4CPU = TargetTriple.isPS4CPU();
44706f32e7eSjoerg   bool IsLinux = TargetTriple.isOSLinux();
44806f32e7eSjoerg   bool IsPPC64 = TargetTriple.getArch() == Triple::ppc64 ||
44906f32e7eSjoerg                  TargetTriple.getArch() == Triple::ppc64le;
45006f32e7eSjoerg   bool IsSystemZ = TargetTriple.getArch() == Triple::systemz;
45106f32e7eSjoerg   bool IsX86_64 = TargetTriple.getArch() == Triple::x86_64;
45206f32e7eSjoerg   bool IsMIPS32 = TargetTriple.isMIPS32();
45306f32e7eSjoerg   bool IsMIPS64 = TargetTriple.isMIPS64();
45406f32e7eSjoerg   bool IsArmOrThumb = TargetTriple.isARM() || TargetTriple.isThumb();
45506f32e7eSjoerg   bool IsAArch64 = TargetTriple.getArch() == Triple::aarch64;
456*da58b97aSjoerg   bool IsRISCV64 = TargetTriple.getArch() == Triple::riscv64;
45706f32e7eSjoerg   bool IsWindows = TargetTriple.isOSWindows();
45806f32e7eSjoerg   bool IsFuchsia = TargetTriple.isOSFuchsia();
45906f32e7eSjoerg   bool IsMyriad = TargetTriple.getVendor() == llvm::Triple::Myriad;
46006f32e7eSjoerg   bool IsEmscripten = TargetTriple.isOSEmscripten();
461*da58b97aSjoerg   bool IsAMDGPU = TargetTriple.isAMDGPU();
462*da58b97aSjoerg 
463*da58b97aSjoerg   // Asan support for AMDGPU assumes X86 as the host right now.
464*da58b97aSjoerg   if (IsAMDGPU)
465*da58b97aSjoerg     IsX86_64 = true;
46606f32e7eSjoerg 
46706f32e7eSjoerg   ShadowMapping Mapping;
46806f32e7eSjoerg 
46906f32e7eSjoerg   Mapping.Scale = IsMyriad ? kMyriadShadowScale : kDefaultShadowScale;
47006f32e7eSjoerg   if (ClMappingScale.getNumOccurrences() > 0) {
47106f32e7eSjoerg     Mapping.Scale = ClMappingScale;
47206f32e7eSjoerg   }
47306f32e7eSjoerg 
47406f32e7eSjoerg   if (LongSize == 32) {
47506f32e7eSjoerg     if (IsAndroid)
47606f32e7eSjoerg       Mapping.Offset = kDynamicShadowSentinel;
47706f32e7eSjoerg     else if (IsMIPS32)
47806f32e7eSjoerg       Mapping.Offset = kMIPS32_ShadowOffset32;
47906f32e7eSjoerg     else if (IsFreeBSD)
48006f32e7eSjoerg       Mapping.Offset = kFreeBSD_ShadowOffset32;
48106f32e7eSjoerg     else if (IsNetBSD)
48206f32e7eSjoerg       Mapping.Offset = kNetBSD_ShadowOffset32;
48306f32e7eSjoerg     else if (IsIOS)
48406f32e7eSjoerg       Mapping.Offset = kDynamicShadowSentinel;
48506f32e7eSjoerg     else if (IsWindows)
48606f32e7eSjoerg       Mapping.Offset = kWindowsShadowOffset32;
48706f32e7eSjoerg     else if (IsEmscripten)
48806f32e7eSjoerg       Mapping.Offset = kEmscriptenShadowOffset;
48906f32e7eSjoerg     else if (IsMyriad) {
49006f32e7eSjoerg       uint64_t ShadowOffset = (kMyriadMemoryOffset32 + kMyriadMemorySize32 -
49106f32e7eSjoerg                                (kMyriadMemorySize32 >> Mapping.Scale));
49206f32e7eSjoerg       Mapping.Offset = ShadowOffset - (kMyriadMemoryOffset32 >> Mapping.Scale);
49306f32e7eSjoerg     }
49406f32e7eSjoerg     else
49506f32e7eSjoerg       Mapping.Offset = kDefaultShadowOffset32;
49606f32e7eSjoerg   } else {  // LongSize == 64
49706f32e7eSjoerg     // Fuchsia is always PIE, which means that the beginning of the address
49806f32e7eSjoerg     // space is always available.
49906f32e7eSjoerg     if (IsFuchsia)
50006f32e7eSjoerg       Mapping.Offset = 0;
50106f32e7eSjoerg     else if (IsPPC64)
50206f32e7eSjoerg       Mapping.Offset = kPPC64_ShadowOffset64;
50306f32e7eSjoerg     else if (IsSystemZ)
50406f32e7eSjoerg       Mapping.Offset = kSystemZ_ShadowOffset64;
505*da58b97aSjoerg     else if (IsFreeBSD && !IsMIPS64) {
506*da58b97aSjoerg       if (IsKasan)
507*da58b97aSjoerg         Mapping.Offset = kFreeBSDKasan_ShadowOffset64;
508*da58b97aSjoerg       else
50906f32e7eSjoerg         Mapping.Offset = kFreeBSD_ShadowOffset64;
510*da58b97aSjoerg     } else if (IsNetBSD) {
51106f32e7eSjoerg       if (IsKasan)
51206f32e7eSjoerg         Mapping.Offset = kNetBSDKasan_ShadowOffset64;
51306f32e7eSjoerg       else
51406f32e7eSjoerg         Mapping.Offset = kNetBSD_ShadowOffset64;
51506f32e7eSjoerg     } else if (IsPS4CPU)
51606f32e7eSjoerg       Mapping.Offset = kPS4CPU_ShadowOffset64;
51706f32e7eSjoerg     else if (IsLinux && IsX86_64) {
51806f32e7eSjoerg       if (IsKasan)
51906f32e7eSjoerg         Mapping.Offset = kLinuxKasan_ShadowOffset64;
52006f32e7eSjoerg       else
52106f32e7eSjoerg         Mapping.Offset = (kSmallX86_64ShadowOffsetBase &
52206f32e7eSjoerg                           (kSmallX86_64ShadowOffsetAlignMask << Mapping.Scale));
52306f32e7eSjoerg     } else if (IsWindows && IsX86_64) {
52406f32e7eSjoerg       Mapping.Offset = kWindowsShadowOffset64;
52506f32e7eSjoerg     } else if (IsMIPS64)
52606f32e7eSjoerg       Mapping.Offset = kMIPS64_ShadowOffset64;
52706f32e7eSjoerg     else if (IsIOS)
52806f32e7eSjoerg       Mapping.Offset = kDynamicShadowSentinel;
529*da58b97aSjoerg     else if (IsMacOS && IsAArch64)
530*da58b97aSjoerg       Mapping.Offset = kDynamicShadowSentinel;
53106f32e7eSjoerg     else if (IsAArch64)
53206f32e7eSjoerg       Mapping.Offset = kAArch64_ShadowOffset64;
533*da58b97aSjoerg     else if (IsRISCV64)
534*da58b97aSjoerg       Mapping.Offset = kRISCV64_ShadowOffset64;
53506f32e7eSjoerg     else
53606f32e7eSjoerg       Mapping.Offset = kDefaultShadowOffset64;
53706f32e7eSjoerg   }
53806f32e7eSjoerg 
53906f32e7eSjoerg   if (ClForceDynamicShadow) {
54006f32e7eSjoerg     Mapping.Offset = kDynamicShadowSentinel;
54106f32e7eSjoerg   }
54206f32e7eSjoerg 
54306f32e7eSjoerg   if (ClMappingOffset.getNumOccurrences() > 0) {
54406f32e7eSjoerg     Mapping.Offset = ClMappingOffset;
54506f32e7eSjoerg   }
54606f32e7eSjoerg 
54706f32e7eSjoerg   // OR-ing shadow offset if more efficient (at least on x86) if the offset
54806f32e7eSjoerg   // is a power of two, but on ppc64 we have to use add since the shadow
54906f32e7eSjoerg   // offset is not necessary 1/8-th of the address space.  On SystemZ,
55006f32e7eSjoerg   // we could OR the constant in a single instruction, but it's more
55106f32e7eSjoerg   // efficient to load it once and use indexed addressing.
55206f32e7eSjoerg   Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ && !IsPS4CPU &&
553*da58b97aSjoerg                            !IsRISCV64 &&
55406f32e7eSjoerg                            !(Mapping.Offset & (Mapping.Offset - 1)) &&
55506f32e7eSjoerg                            Mapping.Offset != kDynamicShadowSentinel;
55606f32e7eSjoerg   bool IsAndroidWithIfuncSupport =
55706f32e7eSjoerg       IsAndroid && !TargetTriple.isAndroidVersionLT(21);
55806f32e7eSjoerg   Mapping.InGlobal = ClWithIfunc && IsAndroidWithIfuncSupport && IsArmOrThumb;
55906f32e7eSjoerg 
56006f32e7eSjoerg   return Mapping;
56106f32e7eSjoerg }
56206f32e7eSjoerg 
getRedzoneSizeForScale(int MappingScale)563*da58b97aSjoerg static uint64_t getRedzoneSizeForScale(int MappingScale) {
56406f32e7eSjoerg   // Redzone used for stack and globals is at least 32 bytes.
56506f32e7eSjoerg   // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
56606f32e7eSjoerg   return std::max(32U, 1U << MappingScale);
56706f32e7eSjoerg }
56806f32e7eSjoerg 
GetCtorAndDtorPriority(Triple & TargetTriple)56906f32e7eSjoerg static uint64_t GetCtorAndDtorPriority(Triple &TargetTriple) {
57006f32e7eSjoerg   if (TargetTriple.isOSEmscripten()) {
57106f32e7eSjoerg     return kAsanEmscriptenCtorAndDtorPriority;
57206f32e7eSjoerg   } else {
57306f32e7eSjoerg     return kAsanCtorAndDtorPriority;
57406f32e7eSjoerg   }
57506f32e7eSjoerg }
57606f32e7eSjoerg 
57706f32e7eSjoerg namespace {
57806f32e7eSjoerg 
57906f32e7eSjoerg /// Module analysis for getting various metadata about the module.
58006f32e7eSjoerg class ASanGlobalsMetadataWrapperPass : public ModulePass {
58106f32e7eSjoerg public:
58206f32e7eSjoerg   static char ID;
58306f32e7eSjoerg 
ASanGlobalsMetadataWrapperPass()58406f32e7eSjoerg   ASanGlobalsMetadataWrapperPass() : ModulePass(ID) {
58506f32e7eSjoerg     initializeASanGlobalsMetadataWrapperPassPass(
58606f32e7eSjoerg         *PassRegistry::getPassRegistry());
58706f32e7eSjoerg   }
58806f32e7eSjoerg 
runOnModule(Module & M)58906f32e7eSjoerg   bool runOnModule(Module &M) override {
59006f32e7eSjoerg     GlobalsMD = GlobalsMetadata(M);
59106f32e7eSjoerg     return false;
59206f32e7eSjoerg   }
59306f32e7eSjoerg 
getPassName() const59406f32e7eSjoerg   StringRef getPassName() const override {
59506f32e7eSjoerg     return "ASanGlobalsMetadataWrapperPass";
59606f32e7eSjoerg   }
59706f32e7eSjoerg 
getAnalysisUsage(AnalysisUsage & AU) const59806f32e7eSjoerg   void getAnalysisUsage(AnalysisUsage &AU) const override {
59906f32e7eSjoerg     AU.setPreservesAll();
60006f32e7eSjoerg   }
60106f32e7eSjoerg 
getGlobalsMD()60206f32e7eSjoerg   GlobalsMetadata &getGlobalsMD() { return GlobalsMD; }
60306f32e7eSjoerg 
60406f32e7eSjoerg private:
60506f32e7eSjoerg   GlobalsMetadata GlobalsMD;
60606f32e7eSjoerg };
60706f32e7eSjoerg 
60806f32e7eSjoerg char ASanGlobalsMetadataWrapperPass::ID = 0;
60906f32e7eSjoerg 
61006f32e7eSjoerg /// AddressSanitizer: instrument the code in module to find memory bugs.
61106f32e7eSjoerg struct AddressSanitizer {
AddressSanitizer__anon257350110211::AddressSanitizer61206f32e7eSjoerg   AddressSanitizer(Module &M, const GlobalsMetadata *GlobalsMD,
61306f32e7eSjoerg                    bool CompileKernel = false, bool Recover = false,
61406f32e7eSjoerg                    bool UseAfterScope = false)
615*da58b97aSjoerg       : CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
616*da58b97aSjoerg                                                             : CompileKernel),
617*da58b97aSjoerg         Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
618*da58b97aSjoerg         UseAfterScope(UseAfterScope || ClUseAfterScope), GlobalsMD(*GlobalsMD) {
61906f32e7eSjoerg     C = &(M.getContext());
62006f32e7eSjoerg     LongSize = M.getDataLayout().getPointerSizeInBits();
62106f32e7eSjoerg     IntptrTy = Type::getIntNTy(*C, LongSize);
62206f32e7eSjoerg     TargetTriple = Triple(M.getTargetTriple());
62306f32e7eSjoerg 
62406f32e7eSjoerg     Mapping = getShadowMapping(TargetTriple, LongSize, this->CompileKernel);
62506f32e7eSjoerg   }
62606f32e7eSjoerg 
getAllocaSizeInBytes__anon257350110211::AddressSanitizer62706f32e7eSjoerg   uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
62806f32e7eSjoerg     uint64_t ArraySize = 1;
62906f32e7eSjoerg     if (AI.isArrayAllocation()) {
63006f32e7eSjoerg       const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
63106f32e7eSjoerg       assert(CI && "non-constant array size");
63206f32e7eSjoerg       ArraySize = CI->getZExtValue();
63306f32e7eSjoerg     }
63406f32e7eSjoerg     Type *Ty = AI.getAllocatedType();
63506f32e7eSjoerg     uint64_t SizeInBytes =
63606f32e7eSjoerg         AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
63706f32e7eSjoerg     return SizeInBytes * ArraySize;
63806f32e7eSjoerg   }
63906f32e7eSjoerg 
64006f32e7eSjoerg   /// Check if we want (and can) handle this alloca.
64106f32e7eSjoerg   bool isInterestingAlloca(const AllocaInst &AI);
64206f32e7eSjoerg 
643*da58b97aSjoerg   bool ignoreAccess(Value *Ptr);
644*da58b97aSjoerg   void getInterestingMemoryOperands(
645*da58b97aSjoerg       Instruction *I, SmallVectorImpl<InterestingMemoryOperand> &Interesting);
64606f32e7eSjoerg 
647*da58b97aSjoerg   void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
648*da58b97aSjoerg                      InterestingMemoryOperand &O, bool UseCalls,
649*da58b97aSjoerg                      const DataLayout &DL);
65006f32e7eSjoerg   void instrumentPointerComparisonOrSubtraction(Instruction *I);
65106f32e7eSjoerg   void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
65206f32e7eSjoerg                          Value *Addr, uint32_t TypeSize, bool IsWrite,
65306f32e7eSjoerg                          Value *SizeArgument, bool UseCalls, uint32_t Exp);
654*da58b97aSjoerg   Instruction *instrumentAMDGPUAddress(Instruction *OrigIns,
655*da58b97aSjoerg                                        Instruction *InsertBefore, Value *Addr,
656*da58b97aSjoerg                                        uint32_t TypeSize, bool IsWrite,
657*da58b97aSjoerg                                        Value *SizeArgument);
65806f32e7eSjoerg   void instrumentUnusualSizeOrAlignment(Instruction *I,
65906f32e7eSjoerg                                         Instruction *InsertBefore, Value *Addr,
66006f32e7eSjoerg                                         uint32_t TypeSize, bool IsWrite,
66106f32e7eSjoerg                                         Value *SizeArgument, bool UseCalls,
66206f32e7eSjoerg                                         uint32_t Exp);
66306f32e7eSjoerg   Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
66406f32e7eSjoerg                            Value *ShadowValue, uint32_t TypeSize);
66506f32e7eSjoerg   Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
66606f32e7eSjoerg                                  bool IsWrite, size_t AccessSizeIndex,
66706f32e7eSjoerg                                  Value *SizeArgument, uint32_t Exp);
66806f32e7eSjoerg   void instrumentMemIntrinsic(MemIntrinsic *MI);
66906f32e7eSjoerg   Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
670*da58b97aSjoerg   bool suppressInstrumentationSiteForDebug(int &Instrumented);
67106f32e7eSjoerg   bool instrumentFunction(Function &F, const TargetLibraryInfo *TLI);
67206f32e7eSjoerg   bool maybeInsertAsanInitAtFunctionEntry(Function &F);
673*da58b97aSjoerg   bool maybeInsertDynamicShadowAtFunctionEntry(Function &F);
67406f32e7eSjoerg   void markEscapedLocalAllocas(Function &F);
67506f32e7eSjoerg 
67606f32e7eSjoerg private:
67706f32e7eSjoerg   friend struct FunctionStackPoisoner;
67806f32e7eSjoerg 
67906f32e7eSjoerg   void initializeCallbacks(Module &M);
68006f32e7eSjoerg 
68106f32e7eSjoerg   bool LooksLikeCodeInBug11395(Instruction *I);
68206f32e7eSjoerg   bool GlobalIsLinkerInitialized(GlobalVariable *G);
68306f32e7eSjoerg   bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
68406f32e7eSjoerg                     uint64_t TypeSize) const;
68506f32e7eSjoerg 
68606f32e7eSjoerg   /// Helper to cleanup per-function state.
68706f32e7eSjoerg   struct FunctionStateRAII {
68806f32e7eSjoerg     AddressSanitizer *Pass;
68906f32e7eSjoerg 
FunctionStateRAII__anon257350110211::AddressSanitizer::FunctionStateRAII69006f32e7eSjoerg     FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
69106f32e7eSjoerg       assert(Pass->ProcessedAllocas.empty() &&
69206f32e7eSjoerg              "last pass forgot to clear cache");
69306f32e7eSjoerg       assert(!Pass->LocalDynamicShadow);
69406f32e7eSjoerg     }
69506f32e7eSjoerg 
~FunctionStateRAII__anon257350110211::AddressSanitizer::FunctionStateRAII69606f32e7eSjoerg     ~FunctionStateRAII() {
69706f32e7eSjoerg       Pass->LocalDynamicShadow = nullptr;
69806f32e7eSjoerg       Pass->ProcessedAllocas.clear();
69906f32e7eSjoerg     }
70006f32e7eSjoerg   };
70106f32e7eSjoerg 
70206f32e7eSjoerg   LLVMContext *C;
70306f32e7eSjoerg   Triple TargetTriple;
70406f32e7eSjoerg   int LongSize;
70506f32e7eSjoerg   bool CompileKernel;
70606f32e7eSjoerg   bool Recover;
70706f32e7eSjoerg   bool UseAfterScope;
70806f32e7eSjoerg   Type *IntptrTy;
70906f32e7eSjoerg   ShadowMapping Mapping;
71006f32e7eSjoerg   FunctionCallee AsanHandleNoReturnFunc;
71106f32e7eSjoerg   FunctionCallee AsanPtrCmpFunction, AsanPtrSubFunction;
71206f32e7eSjoerg   Constant *AsanShadowGlobal;
71306f32e7eSjoerg 
71406f32e7eSjoerg   // These arrays is indexed by AccessIsWrite, Experiment and log2(AccessSize).
71506f32e7eSjoerg   FunctionCallee AsanErrorCallback[2][2][kNumberOfAccessSizes];
71606f32e7eSjoerg   FunctionCallee AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
71706f32e7eSjoerg 
71806f32e7eSjoerg   // These arrays is indexed by AccessIsWrite and Experiment.
71906f32e7eSjoerg   FunctionCallee AsanErrorCallbackSized[2][2];
72006f32e7eSjoerg   FunctionCallee AsanMemoryAccessCallbackSized[2][2];
72106f32e7eSjoerg 
72206f32e7eSjoerg   FunctionCallee AsanMemmove, AsanMemcpy, AsanMemset;
72306f32e7eSjoerg   Value *LocalDynamicShadow = nullptr;
72406f32e7eSjoerg   const GlobalsMetadata &GlobalsMD;
72506f32e7eSjoerg   DenseMap<const AllocaInst *, bool> ProcessedAllocas;
726*da58b97aSjoerg 
727*da58b97aSjoerg   FunctionCallee AMDGPUAddressShared;
728*da58b97aSjoerg   FunctionCallee AMDGPUAddressPrivate;
72906f32e7eSjoerg };
73006f32e7eSjoerg 
73106f32e7eSjoerg class AddressSanitizerLegacyPass : public FunctionPass {
73206f32e7eSjoerg public:
73306f32e7eSjoerg   static char ID;
73406f32e7eSjoerg 
AddressSanitizerLegacyPass(bool CompileKernel=false,bool Recover=false,bool UseAfterScope=false)73506f32e7eSjoerg   explicit AddressSanitizerLegacyPass(bool CompileKernel = false,
73606f32e7eSjoerg                                       bool Recover = false,
73706f32e7eSjoerg                                       bool UseAfterScope = false)
73806f32e7eSjoerg       : FunctionPass(ID), CompileKernel(CompileKernel), Recover(Recover),
73906f32e7eSjoerg         UseAfterScope(UseAfterScope) {
74006f32e7eSjoerg     initializeAddressSanitizerLegacyPassPass(*PassRegistry::getPassRegistry());
74106f32e7eSjoerg   }
74206f32e7eSjoerg 
getPassName() const74306f32e7eSjoerg   StringRef getPassName() const override {
74406f32e7eSjoerg     return "AddressSanitizerFunctionPass";
74506f32e7eSjoerg   }
74606f32e7eSjoerg 
getAnalysisUsage(AnalysisUsage & AU) const74706f32e7eSjoerg   void getAnalysisUsage(AnalysisUsage &AU) const override {
74806f32e7eSjoerg     AU.addRequired<ASanGlobalsMetadataWrapperPass>();
74906f32e7eSjoerg     AU.addRequired<TargetLibraryInfoWrapperPass>();
75006f32e7eSjoerg   }
75106f32e7eSjoerg 
runOnFunction(Function & F)75206f32e7eSjoerg   bool runOnFunction(Function &F) override {
75306f32e7eSjoerg     GlobalsMetadata &GlobalsMD =
75406f32e7eSjoerg         getAnalysis<ASanGlobalsMetadataWrapperPass>().getGlobalsMD();
75506f32e7eSjoerg     const TargetLibraryInfo *TLI =
75606f32e7eSjoerg         &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
75706f32e7eSjoerg     AddressSanitizer ASan(*F.getParent(), &GlobalsMD, CompileKernel, Recover,
75806f32e7eSjoerg                           UseAfterScope);
75906f32e7eSjoerg     return ASan.instrumentFunction(F, TLI);
76006f32e7eSjoerg   }
76106f32e7eSjoerg 
76206f32e7eSjoerg private:
76306f32e7eSjoerg   bool CompileKernel;
76406f32e7eSjoerg   bool Recover;
76506f32e7eSjoerg   bool UseAfterScope;
76606f32e7eSjoerg };
76706f32e7eSjoerg 
76806f32e7eSjoerg class ModuleAddressSanitizer {
76906f32e7eSjoerg public:
ModuleAddressSanitizer(Module & M,const GlobalsMetadata * GlobalsMD,bool CompileKernel=false,bool Recover=false,bool UseGlobalsGC=true,bool UseOdrIndicator=false,AsanDtorKind DestructorKind=AsanDtorKind::Global)77006f32e7eSjoerg   ModuleAddressSanitizer(Module &M, const GlobalsMetadata *GlobalsMD,
77106f32e7eSjoerg                          bool CompileKernel = false, bool Recover = false,
772*da58b97aSjoerg                          bool UseGlobalsGC = true, bool UseOdrIndicator = false,
773*da58b97aSjoerg                          AsanDtorKind DestructorKind = AsanDtorKind::Global)
774*da58b97aSjoerg       : GlobalsMD(*GlobalsMD),
775*da58b97aSjoerg         CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
776*da58b97aSjoerg                                                             : CompileKernel),
777*da58b97aSjoerg         Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
778*da58b97aSjoerg         UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC && !this->CompileKernel),
77906f32e7eSjoerg         // Enable aliases as they should have no downside with ODR indicators.
78006f32e7eSjoerg         UsePrivateAlias(UseOdrIndicator || ClUsePrivateAlias),
78106f32e7eSjoerg         UseOdrIndicator(UseOdrIndicator || ClUseOdrIndicator),
78206f32e7eSjoerg         // Not a typo: ClWithComdat is almost completely pointless without
78306f32e7eSjoerg         // ClUseGlobalsGC (because then it only works on modules without
78406f32e7eSjoerg         // globals, which are rare); it is a prerequisite for ClUseGlobalsGC;
78506f32e7eSjoerg         // and both suffer from gold PR19002 for which UseGlobalsGC constructor
78606f32e7eSjoerg         // argument is designed as workaround. Therefore, disable both
78706f32e7eSjoerg         // ClWithComdat and ClUseGlobalsGC unless the frontend says it's ok to
78806f32e7eSjoerg         // do globals-gc.
789*da58b97aSjoerg         UseCtorComdat(UseGlobalsGC && ClWithComdat && !this->CompileKernel),
790*da58b97aSjoerg         DestructorKind(DestructorKind) {
79106f32e7eSjoerg     C = &(M.getContext());
79206f32e7eSjoerg     int LongSize = M.getDataLayout().getPointerSizeInBits();
79306f32e7eSjoerg     IntptrTy = Type::getIntNTy(*C, LongSize);
79406f32e7eSjoerg     TargetTriple = Triple(M.getTargetTriple());
79506f32e7eSjoerg     Mapping = getShadowMapping(TargetTriple, LongSize, this->CompileKernel);
796*da58b97aSjoerg 
797*da58b97aSjoerg     if (ClOverrideDestructorKind != AsanDtorKind::Invalid)
798*da58b97aSjoerg       this->DestructorKind = ClOverrideDestructorKind;
799*da58b97aSjoerg     assert(this->DestructorKind != AsanDtorKind::Invalid);
80006f32e7eSjoerg   }
80106f32e7eSjoerg 
80206f32e7eSjoerg   bool instrumentModule(Module &);
80306f32e7eSjoerg 
80406f32e7eSjoerg private:
80506f32e7eSjoerg   void initializeCallbacks(Module &M);
80606f32e7eSjoerg 
80706f32e7eSjoerg   bool InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat);
80806f32e7eSjoerg   void InstrumentGlobalsCOFF(IRBuilder<> &IRB, Module &M,
80906f32e7eSjoerg                              ArrayRef<GlobalVariable *> ExtendedGlobals,
81006f32e7eSjoerg                              ArrayRef<Constant *> MetadataInitializers);
81106f32e7eSjoerg   void InstrumentGlobalsELF(IRBuilder<> &IRB, Module &M,
81206f32e7eSjoerg                             ArrayRef<GlobalVariable *> ExtendedGlobals,
81306f32e7eSjoerg                             ArrayRef<Constant *> MetadataInitializers,
81406f32e7eSjoerg                             const std::string &UniqueModuleId);
81506f32e7eSjoerg   void InstrumentGlobalsMachO(IRBuilder<> &IRB, Module &M,
81606f32e7eSjoerg                               ArrayRef<GlobalVariable *> ExtendedGlobals,
81706f32e7eSjoerg                               ArrayRef<Constant *> MetadataInitializers);
81806f32e7eSjoerg   void
81906f32e7eSjoerg   InstrumentGlobalsWithMetadataArray(IRBuilder<> &IRB, Module &M,
82006f32e7eSjoerg                                      ArrayRef<GlobalVariable *> ExtendedGlobals,
82106f32e7eSjoerg                                      ArrayRef<Constant *> MetadataInitializers);
82206f32e7eSjoerg 
82306f32e7eSjoerg   GlobalVariable *CreateMetadataGlobal(Module &M, Constant *Initializer,
82406f32e7eSjoerg                                        StringRef OriginalName);
82506f32e7eSjoerg   void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata,
82606f32e7eSjoerg                                   StringRef InternalSuffix);
827*da58b97aSjoerg   Instruction *CreateAsanModuleDtor(Module &M);
82806f32e7eSjoerg 
829*da58b97aSjoerg   const GlobalVariable *getExcludedAliasedGlobal(const GlobalAlias &GA) const;
830*da58b97aSjoerg   bool shouldInstrumentGlobal(GlobalVariable *G) const;
83106f32e7eSjoerg   bool ShouldUseMachOGlobalsSection() const;
83206f32e7eSjoerg   StringRef getGlobalMetadataSection() const;
83306f32e7eSjoerg   void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
83406f32e7eSjoerg   void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
getMinRedzoneSizeForGlobal() const835*da58b97aSjoerg   uint64_t getMinRedzoneSizeForGlobal() const {
836*da58b97aSjoerg     return getRedzoneSizeForScale(Mapping.Scale);
83706f32e7eSjoerg   }
838*da58b97aSjoerg   uint64_t getRedzoneSizeForGlobal(uint64_t SizeInBytes) const;
83906f32e7eSjoerg   int GetAsanVersion(const Module &M) const;
84006f32e7eSjoerg 
84106f32e7eSjoerg   const GlobalsMetadata &GlobalsMD;
84206f32e7eSjoerg   bool CompileKernel;
84306f32e7eSjoerg   bool Recover;
84406f32e7eSjoerg   bool UseGlobalsGC;
84506f32e7eSjoerg   bool UsePrivateAlias;
84606f32e7eSjoerg   bool UseOdrIndicator;
84706f32e7eSjoerg   bool UseCtorComdat;
848*da58b97aSjoerg   AsanDtorKind DestructorKind;
84906f32e7eSjoerg   Type *IntptrTy;
85006f32e7eSjoerg   LLVMContext *C;
85106f32e7eSjoerg   Triple TargetTriple;
85206f32e7eSjoerg   ShadowMapping Mapping;
85306f32e7eSjoerg   FunctionCallee AsanPoisonGlobals;
85406f32e7eSjoerg   FunctionCallee AsanUnpoisonGlobals;
85506f32e7eSjoerg   FunctionCallee AsanRegisterGlobals;
85606f32e7eSjoerg   FunctionCallee AsanUnregisterGlobals;
85706f32e7eSjoerg   FunctionCallee AsanRegisterImageGlobals;
85806f32e7eSjoerg   FunctionCallee AsanUnregisterImageGlobals;
85906f32e7eSjoerg   FunctionCallee AsanRegisterElfGlobals;
86006f32e7eSjoerg   FunctionCallee AsanUnregisterElfGlobals;
86106f32e7eSjoerg 
86206f32e7eSjoerg   Function *AsanCtorFunction = nullptr;
86306f32e7eSjoerg   Function *AsanDtorFunction = nullptr;
86406f32e7eSjoerg };
86506f32e7eSjoerg 
86606f32e7eSjoerg class ModuleAddressSanitizerLegacyPass : public ModulePass {
86706f32e7eSjoerg public:
86806f32e7eSjoerg   static char ID;
86906f32e7eSjoerg 
ModuleAddressSanitizerLegacyPass(bool CompileKernel=false,bool Recover=false,bool UseGlobalGC=true,bool UseOdrIndicator=false,AsanDtorKind DestructorKind=AsanDtorKind::Global)870*da58b97aSjoerg   explicit ModuleAddressSanitizerLegacyPass(
871*da58b97aSjoerg       bool CompileKernel = false, bool Recover = false, bool UseGlobalGC = true,
872*da58b97aSjoerg       bool UseOdrIndicator = false,
873*da58b97aSjoerg       AsanDtorKind DestructorKind = AsanDtorKind::Global)
87406f32e7eSjoerg       : ModulePass(ID), CompileKernel(CompileKernel), Recover(Recover),
875*da58b97aSjoerg         UseGlobalGC(UseGlobalGC), UseOdrIndicator(UseOdrIndicator),
876*da58b97aSjoerg         DestructorKind(DestructorKind) {
87706f32e7eSjoerg     initializeModuleAddressSanitizerLegacyPassPass(
87806f32e7eSjoerg         *PassRegistry::getPassRegistry());
87906f32e7eSjoerg   }
88006f32e7eSjoerg 
getPassName() const88106f32e7eSjoerg   StringRef getPassName() const override { return "ModuleAddressSanitizer"; }
88206f32e7eSjoerg 
getAnalysisUsage(AnalysisUsage & AU) const88306f32e7eSjoerg   void getAnalysisUsage(AnalysisUsage &AU) const override {
88406f32e7eSjoerg     AU.addRequired<ASanGlobalsMetadataWrapperPass>();
88506f32e7eSjoerg   }
88606f32e7eSjoerg 
runOnModule(Module & M)88706f32e7eSjoerg   bool runOnModule(Module &M) override {
88806f32e7eSjoerg     GlobalsMetadata &GlobalsMD =
88906f32e7eSjoerg         getAnalysis<ASanGlobalsMetadataWrapperPass>().getGlobalsMD();
89006f32e7eSjoerg     ModuleAddressSanitizer ASanModule(M, &GlobalsMD, CompileKernel, Recover,
891*da58b97aSjoerg                                       UseGlobalGC, UseOdrIndicator,
892*da58b97aSjoerg                                       DestructorKind);
89306f32e7eSjoerg     return ASanModule.instrumentModule(M);
89406f32e7eSjoerg   }
89506f32e7eSjoerg 
89606f32e7eSjoerg private:
89706f32e7eSjoerg   bool CompileKernel;
89806f32e7eSjoerg   bool Recover;
89906f32e7eSjoerg   bool UseGlobalGC;
90006f32e7eSjoerg   bool UseOdrIndicator;
901*da58b97aSjoerg   AsanDtorKind DestructorKind;
90206f32e7eSjoerg };
90306f32e7eSjoerg 
90406f32e7eSjoerg // Stack poisoning does not play well with exception handling.
90506f32e7eSjoerg // When an exception is thrown, we essentially bypass the code
90606f32e7eSjoerg // that unpoisones the stack. This is why the run-time library has
90706f32e7eSjoerg // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
90806f32e7eSjoerg // stack in the interceptor. This however does not work inside the
90906f32e7eSjoerg // actual function which catches the exception. Most likely because the
91006f32e7eSjoerg // compiler hoists the load of the shadow value somewhere too high.
91106f32e7eSjoerg // This causes asan to report a non-existing bug on 453.povray.
91206f32e7eSjoerg // It sounds like an LLVM bug.
91306f32e7eSjoerg struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
91406f32e7eSjoerg   Function &F;
91506f32e7eSjoerg   AddressSanitizer &ASan;
91606f32e7eSjoerg   DIBuilder DIB;
91706f32e7eSjoerg   LLVMContext *C;
91806f32e7eSjoerg   Type *IntptrTy;
91906f32e7eSjoerg   Type *IntptrPtrTy;
92006f32e7eSjoerg   ShadowMapping Mapping;
92106f32e7eSjoerg 
92206f32e7eSjoerg   SmallVector<AllocaInst *, 16> AllocaVec;
92306f32e7eSjoerg   SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;
92406f32e7eSjoerg   SmallVector<Instruction *, 8> RetVec;
92506f32e7eSjoerg   unsigned StackAlignment;
92606f32e7eSjoerg 
92706f32e7eSjoerg   FunctionCallee AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
92806f32e7eSjoerg       AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
92906f32e7eSjoerg   FunctionCallee AsanSetShadowFunc[0x100] = {};
93006f32e7eSjoerg   FunctionCallee AsanPoisonStackMemoryFunc, AsanUnpoisonStackMemoryFunc;
93106f32e7eSjoerg   FunctionCallee AsanAllocaPoisonFunc, AsanAllocasUnpoisonFunc;
93206f32e7eSjoerg 
93306f32e7eSjoerg   // Stores a place and arguments of poisoning/unpoisoning call for alloca.
93406f32e7eSjoerg   struct AllocaPoisonCall {
93506f32e7eSjoerg     IntrinsicInst *InsBefore;
93606f32e7eSjoerg     AllocaInst *AI;
93706f32e7eSjoerg     uint64_t Size;
93806f32e7eSjoerg     bool DoPoison;
93906f32e7eSjoerg   };
94006f32e7eSjoerg   SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
94106f32e7eSjoerg   SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
94206f32e7eSjoerg   bool HasUntracedLifetimeIntrinsic = false;
94306f32e7eSjoerg 
94406f32e7eSjoerg   SmallVector<AllocaInst *, 1> DynamicAllocaVec;
94506f32e7eSjoerg   SmallVector<IntrinsicInst *, 1> StackRestoreVec;
94606f32e7eSjoerg   AllocaInst *DynamicAllocaLayout = nullptr;
94706f32e7eSjoerg   IntrinsicInst *LocalEscapeCall = nullptr;
94806f32e7eSjoerg 
949*da58b97aSjoerg   bool HasInlineAsm = false;
95006f32e7eSjoerg   bool HasReturnsTwiceCall = false;
951*da58b97aSjoerg   bool PoisonStack;
95206f32e7eSjoerg 
FunctionStackPoisoner__anon257350110211::FunctionStackPoisoner95306f32e7eSjoerg   FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
95406f32e7eSjoerg       : F(F), ASan(ASan), DIB(*F.getParent(), /*AllowUnresolved*/ false),
95506f32e7eSjoerg         C(ASan.C), IntptrTy(ASan.IntptrTy),
95606f32e7eSjoerg         IntptrPtrTy(PointerType::get(IntptrTy, 0)), Mapping(ASan.Mapping),
95706f32e7eSjoerg         StackAlignment(1 << Mapping.Scale),
958*da58b97aSjoerg         PoisonStack(ClStack &&
959*da58b97aSjoerg                     !Triple(F.getParent()->getTargetTriple()).isAMDGPU()) {}
96006f32e7eSjoerg 
runOnFunction__anon257350110211::FunctionStackPoisoner96106f32e7eSjoerg   bool runOnFunction() {
962*da58b97aSjoerg     if (!PoisonStack)
963*da58b97aSjoerg       return false;
96406f32e7eSjoerg 
96506f32e7eSjoerg     if (ClRedzoneByvalArgs)
96606f32e7eSjoerg       copyArgsPassedByValToAllocas();
96706f32e7eSjoerg 
96806f32e7eSjoerg     // Collect alloca, ret, lifetime instructions etc.
96906f32e7eSjoerg     for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
97006f32e7eSjoerg 
97106f32e7eSjoerg     if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
97206f32e7eSjoerg 
97306f32e7eSjoerg     initializeCallbacks(*F.getParent());
97406f32e7eSjoerg 
97506f32e7eSjoerg     if (HasUntracedLifetimeIntrinsic) {
97606f32e7eSjoerg       // If there are lifetime intrinsics which couldn't be traced back to an
97706f32e7eSjoerg       // alloca, we may not know exactly when a variable enters scope, and
97806f32e7eSjoerg       // therefore should "fail safe" by not poisoning them.
97906f32e7eSjoerg       StaticAllocaPoisonCallVec.clear();
98006f32e7eSjoerg       DynamicAllocaPoisonCallVec.clear();
98106f32e7eSjoerg     }
98206f32e7eSjoerg 
98306f32e7eSjoerg     processDynamicAllocas();
98406f32e7eSjoerg     processStaticAllocas();
98506f32e7eSjoerg 
98606f32e7eSjoerg     if (ClDebugStack) {
98706f32e7eSjoerg       LLVM_DEBUG(dbgs() << F);
98806f32e7eSjoerg     }
98906f32e7eSjoerg     return true;
99006f32e7eSjoerg   }
99106f32e7eSjoerg 
99206f32e7eSjoerg   // Arguments marked with the "byval" attribute are implicitly copied without
99306f32e7eSjoerg   // using an alloca instruction.  To produce redzones for those arguments, we
99406f32e7eSjoerg   // copy them a second time into memory allocated with an alloca instruction.
99506f32e7eSjoerg   void copyArgsPassedByValToAllocas();
99606f32e7eSjoerg 
99706f32e7eSjoerg   // Finds all Alloca instructions and puts
99806f32e7eSjoerg   // poisoned red zones around all of them.
99906f32e7eSjoerg   // Then unpoison everything back before the function returns.
100006f32e7eSjoerg   void processStaticAllocas();
100106f32e7eSjoerg   void processDynamicAllocas();
100206f32e7eSjoerg 
100306f32e7eSjoerg   void createDynamicAllocasInitStorage();
100406f32e7eSjoerg 
100506f32e7eSjoerg   // ----------------------- Visitors.
1006*da58b97aSjoerg   /// Collect all Ret instructions, or the musttail call instruction if it
1007*da58b97aSjoerg   /// precedes the return instruction.
visitReturnInst__anon257350110211::FunctionStackPoisoner1008*da58b97aSjoerg   void visitReturnInst(ReturnInst &RI) {
1009*da58b97aSjoerg     if (CallInst *CI = RI.getParent()->getTerminatingMustTailCall())
1010*da58b97aSjoerg       RetVec.push_back(CI);
1011*da58b97aSjoerg     else
1012*da58b97aSjoerg       RetVec.push_back(&RI);
1013*da58b97aSjoerg   }
101406f32e7eSjoerg 
101506f32e7eSjoerg   /// Collect all Resume instructions.
visitResumeInst__anon257350110211::FunctionStackPoisoner101606f32e7eSjoerg   void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
101706f32e7eSjoerg 
101806f32e7eSjoerg   /// Collect all CatchReturnInst instructions.
visitCleanupReturnInst__anon257350110211::FunctionStackPoisoner101906f32e7eSjoerg   void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
102006f32e7eSjoerg 
unpoisonDynamicAllocasBeforeInst__anon257350110211::FunctionStackPoisoner102106f32e7eSjoerg   void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
102206f32e7eSjoerg                                         Value *SavedStack) {
102306f32e7eSjoerg     IRBuilder<> IRB(InstBefore);
102406f32e7eSjoerg     Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
102506f32e7eSjoerg     // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
102606f32e7eSjoerg     // need to adjust extracted SP to compute the address of the most recent
102706f32e7eSjoerg     // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
102806f32e7eSjoerg     // this purpose.
102906f32e7eSjoerg     if (!isa<ReturnInst>(InstBefore)) {
103006f32e7eSjoerg       Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
103106f32e7eSjoerg           InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
103206f32e7eSjoerg           {IntptrTy});
103306f32e7eSjoerg 
103406f32e7eSjoerg       Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
103506f32e7eSjoerg 
103606f32e7eSjoerg       DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
103706f32e7eSjoerg                                      DynamicAreaOffset);
103806f32e7eSjoerg     }
103906f32e7eSjoerg 
104006f32e7eSjoerg     IRB.CreateCall(
104106f32e7eSjoerg         AsanAllocasUnpoisonFunc,
104206f32e7eSjoerg         {IRB.CreateLoad(IntptrTy, DynamicAllocaLayout), DynamicAreaPtr});
104306f32e7eSjoerg   }
104406f32e7eSjoerg 
104506f32e7eSjoerg   // Unpoison dynamic allocas redzones.
unpoisonDynamicAllocas__anon257350110211::FunctionStackPoisoner104606f32e7eSjoerg   void unpoisonDynamicAllocas() {
1047*da58b97aSjoerg     for (Instruction *Ret : RetVec)
104806f32e7eSjoerg       unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
104906f32e7eSjoerg 
1050*da58b97aSjoerg     for (Instruction *StackRestoreInst : StackRestoreVec)
105106f32e7eSjoerg       unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
105206f32e7eSjoerg                                        StackRestoreInst->getOperand(0));
105306f32e7eSjoerg   }
105406f32e7eSjoerg 
105506f32e7eSjoerg   // Deploy and poison redzones around dynamic alloca call. To do this, we
105606f32e7eSjoerg   // should replace this call with another one with changed parameters and
105706f32e7eSjoerg   // replace all its uses with new address, so
105806f32e7eSjoerg   //   addr = alloca type, old_size, align
105906f32e7eSjoerg   // is replaced by
106006f32e7eSjoerg   //   new_size = (old_size + additional_size) * sizeof(type)
106106f32e7eSjoerg   //   tmp = alloca i8, new_size, max(align, 32)
106206f32e7eSjoerg   //   addr = tmp + 32 (first 32 bytes are for the left redzone).
106306f32e7eSjoerg   // Additional_size is added to make new memory allocation contain not only
106406f32e7eSjoerg   // requested memory, but also left, partial and right redzones.
106506f32e7eSjoerg   void handleDynamicAllocaCall(AllocaInst *AI);
106606f32e7eSjoerg 
106706f32e7eSjoerg   /// Collect Alloca instructions we want (and can) handle.
visitAllocaInst__anon257350110211::FunctionStackPoisoner106806f32e7eSjoerg   void visitAllocaInst(AllocaInst &AI) {
106906f32e7eSjoerg     if (!ASan.isInterestingAlloca(AI)) {
107006f32e7eSjoerg       if (AI.isStaticAlloca()) {
107106f32e7eSjoerg         // Skip over allocas that are present *before* the first instrumented
107206f32e7eSjoerg         // alloca, we don't want to move those around.
107306f32e7eSjoerg         if (AllocaVec.empty())
107406f32e7eSjoerg           return;
107506f32e7eSjoerg 
107606f32e7eSjoerg         StaticAllocasToMoveUp.push_back(&AI);
107706f32e7eSjoerg       }
107806f32e7eSjoerg       return;
107906f32e7eSjoerg     }
108006f32e7eSjoerg 
108106f32e7eSjoerg     StackAlignment = std::max(StackAlignment, AI.getAlignment());
108206f32e7eSjoerg     if (!AI.isStaticAlloca())
108306f32e7eSjoerg       DynamicAllocaVec.push_back(&AI);
108406f32e7eSjoerg     else
108506f32e7eSjoerg       AllocaVec.push_back(&AI);
108606f32e7eSjoerg   }
108706f32e7eSjoerg 
108806f32e7eSjoerg   /// Collect lifetime intrinsic calls to check for use-after-scope
108906f32e7eSjoerg   /// errors.
visitIntrinsicInst__anon257350110211::FunctionStackPoisoner109006f32e7eSjoerg   void visitIntrinsicInst(IntrinsicInst &II) {
109106f32e7eSjoerg     Intrinsic::ID ID = II.getIntrinsicID();
109206f32e7eSjoerg     if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
109306f32e7eSjoerg     if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
109406f32e7eSjoerg     if (!ASan.UseAfterScope)
109506f32e7eSjoerg       return;
109606f32e7eSjoerg     if (!II.isLifetimeStartOrEnd())
109706f32e7eSjoerg       return;
109806f32e7eSjoerg     // Found lifetime intrinsic, add ASan instrumentation if necessary.
109906f32e7eSjoerg     auto *Size = cast<ConstantInt>(II.getArgOperand(0));
110006f32e7eSjoerg     // If size argument is undefined, don't do anything.
110106f32e7eSjoerg     if (Size->isMinusOne()) return;
110206f32e7eSjoerg     // Check that size doesn't saturate uint64_t and can
110306f32e7eSjoerg     // be stored in IntptrTy.
110406f32e7eSjoerg     const uint64_t SizeValue = Size->getValue().getLimitedValue();
110506f32e7eSjoerg     if (SizeValue == ~0ULL ||
110606f32e7eSjoerg         !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
110706f32e7eSjoerg       return;
110806f32e7eSjoerg     // Find alloca instruction that corresponds to llvm.lifetime argument.
1109*da58b97aSjoerg     // Currently we can only handle lifetime markers pointing to the
1110*da58b97aSjoerg     // beginning of the alloca.
1111*da58b97aSjoerg     AllocaInst *AI = findAllocaForValue(II.getArgOperand(1), true);
111206f32e7eSjoerg     if (!AI) {
111306f32e7eSjoerg       HasUntracedLifetimeIntrinsic = true;
111406f32e7eSjoerg       return;
111506f32e7eSjoerg     }
111606f32e7eSjoerg     // We're interested only in allocas we can handle.
111706f32e7eSjoerg     if (!ASan.isInterestingAlloca(*AI))
111806f32e7eSjoerg       return;
111906f32e7eSjoerg     bool DoPoison = (ID == Intrinsic::lifetime_end);
112006f32e7eSjoerg     AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
112106f32e7eSjoerg     if (AI->isStaticAlloca())
112206f32e7eSjoerg       StaticAllocaPoisonCallVec.push_back(APC);
112306f32e7eSjoerg     else if (ClInstrumentDynamicAllocas)
112406f32e7eSjoerg       DynamicAllocaPoisonCallVec.push_back(APC);
112506f32e7eSjoerg   }
112606f32e7eSjoerg 
visitCallBase__anon257350110211::FunctionStackPoisoner1127*da58b97aSjoerg   void visitCallBase(CallBase &CB) {
1128*da58b97aSjoerg     if (CallInst *CI = dyn_cast<CallInst>(&CB)) {
1129*da58b97aSjoerg       HasInlineAsm |= CI->isInlineAsm() && &CB != ASan.LocalDynamicShadow;
113006f32e7eSjoerg       HasReturnsTwiceCall |= CI->canReturnTwice();
113106f32e7eSjoerg     }
113206f32e7eSjoerg   }
113306f32e7eSjoerg 
113406f32e7eSjoerg   // ---------------------- Helpers.
113506f32e7eSjoerg   void initializeCallbacks(Module &M);
113606f32e7eSjoerg 
113706f32e7eSjoerg   // Copies bytes from ShadowBytes into shadow memory for indexes where
113806f32e7eSjoerg   // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
113906f32e7eSjoerg   // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
114006f32e7eSjoerg   void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
114106f32e7eSjoerg                     IRBuilder<> &IRB, Value *ShadowBase);
114206f32e7eSjoerg   void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
114306f32e7eSjoerg                     size_t Begin, size_t End, IRBuilder<> &IRB,
114406f32e7eSjoerg                     Value *ShadowBase);
114506f32e7eSjoerg   void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
114606f32e7eSjoerg                           ArrayRef<uint8_t> ShadowBytes, size_t Begin,
114706f32e7eSjoerg                           size_t End, IRBuilder<> &IRB, Value *ShadowBase);
114806f32e7eSjoerg 
114906f32e7eSjoerg   void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
115006f32e7eSjoerg 
115106f32e7eSjoerg   Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
115206f32e7eSjoerg                                bool Dynamic);
115306f32e7eSjoerg   PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
115406f32e7eSjoerg                      Instruction *ThenTerm, Value *ValueIfFalse);
115506f32e7eSjoerg };
115606f32e7eSjoerg 
115706f32e7eSjoerg } // end anonymous namespace
115806f32e7eSjoerg 
parse(MDNode * MDN)115906f32e7eSjoerg void LocationMetadata::parse(MDNode *MDN) {
116006f32e7eSjoerg   assert(MDN->getNumOperands() == 3);
116106f32e7eSjoerg   MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
116206f32e7eSjoerg   Filename = DIFilename->getString();
116306f32e7eSjoerg   LineNo = mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
116406f32e7eSjoerg   ColumnNo =
116506f32e7eSjoerg       mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
116606f32e7eSjoerg }
116706f32e7eSjoerg 
116806f32e7eSjoerg // FIXME: It would be cleaner to instead attach relevant metadata to the globals
116906f32e7eSjoerg // we want to sanitize instead and reading this metadata on each pass over a
117006f32e7eSjoerg // function instead of reading module level metadata at first.
GlobalsMetadata(Module & M)117106f32e7eSjoerg GlobalsMetadata::GlobalsMetadata(Module &M) {
117206f32e7eSjoerg   NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
117306f32e7eSjoerg   if (!Globals)
117406f32e7eSjoerg     return;
117506f32e7eSjoerg   for (auto MDN : Globals->operands()) {
117606f32e7eSjoerg     // Metadata node contains the global and the fields of "Entry".
117706f32e7eSjoerg     assert(MDN->getNumOperands() == 5);
117806f32e7eSjoerg     auto *V = mdconst::extract_or_null<Constant>(MDN->getOperand(0));
117906f32e7eSjoerg     // The optimizer may optimize away a global entirely.
118006f32e7eSjoerg     if (!V)
118106f32e7eSjoerg       continue;
118206f32e7eSjoerg     auto *StrippedV = V->stripPointerCasts();
118306f32e7eSjoerg     auto *GV = dyn_cast<GlobalVariable>(StrippedV);
118406f32e7eSjoerg     if (!GV)
118506f32e7eSjoerg       continue;
118606f32e7eSjoerg     // We can already have an entry for GV if it was merged with another
118706f32e7eSjoerg     // global.
118806f32e7eSjoerg     Entry &E = Entries[GV];
118906f32e7eSjoerg     if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
119006f32e7eSjoerg       E.SourceLoc.parse(Loc);
119106f32e7eSjoerg     if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
119206f32e7eSjoerg       E.Name = Name->getString();
119306f32e7eSjoerg     ConstantInt *IsDynInit = mdconst::extract<ConstantInt>(MDN->getOperand(3));
119406f32e7eSjoerg     E.IsDynInit |= IsDynInit->isOne();
1195*da58b97aSjoerg     ConstantInt *IsExcluded =
119606f32e7eSjoerg         mdconst::extract<ConstantInt>(MDN->getOperand(4));
1197*da58b97aSjoerg     E.IsExcluded |= IsExcluded->isOne();
119806f32e7eSjoerg   }
119906f32e7eSjoerg }
120006f32e7eSjoerg 
120106f32e7eSjoerg AnalysisKey ASanGlobalsMetadataAnalysis::Key;
120206f32e7eSjoerg 
run(Module & M,ModuleAnalysisManager & AM)120306f32e7eSjoerg GlobalsMetadata ASanGlobalsMetadataAnalysis::run(Module &M,
120406f32e7eSjoerg                                                  ModuleAnalysisManager &AM) {
120506f32e7eSjoerg   return GlobalsMetadata(M);
120606f32e7eSjoerg }
120706f32e7eSjoerg 
AddressSanitizerPass(bool CompileKernel,bool Recover,bool UseAfterScope)120806f32e7eSjoerg AddressSanitizerPass::AddressSanitizerPass(bool CompileKernel, bool Recover,
120906f32e7eSjoerg                                            bool UseAfterScope)
121006f32e7eSjoerg     : CompileKernel(CompileKernel), Recover(Recover),
121106f32e7eSjoerg       UseAfterScope(UseAfterScope) {}
121206f32e7eSjoerg 
run(Function & F,AnalysisManager<Function> & AM)121306f32e7eSjoerg PreservedAnalyses AddressSanitizerPass::run(Function &F,
121406f32e7eSjoerg                                             AnalysisManager<Function> &AM) {
121506f32e7eSjoerg   auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
121606f32e7eSjoerg   Module &M = *F.getParent();
1217*da58b97aSjoerg   if (auto *R = MAMProxy.getCachedResult<ASanGlobalsMetadataAnalysis>(M)) {
121806f32e7eSjoerg     const TargetLibraryInfo *TLI = &AM.getResult<TargetLibraryAnalysis>(F);
121906f32e7eSjoerg     AddressSanitizer Sanitizer(M, R, CompileKernel, Recover, UseAfterScope);
122006f32e7eSjoerg     if (Sanitizer.instrumentFunction(F, TLI))
122106f32e7eSjoerg       return PreservedAnalyses::none();
122206f32e7eSjoerg     return PreservedAnalyses::all();
122306f32e7eSjoerg   }
122406f32e7eSjoerg 
122506f32e7eSjoerg   report_fatal_error(
122606f32e7eSjoerg       "The ASanGlobalsMetadataAnalysis is required to run before "
122706f32e7eSjoerg       "AddressSanitizer can run");
122806f32e7eSjoerg   return PreservedAnalyses::all();
122906f32e7eSjoerg }
123006f32e7eSjoerg 
ModuleAddressSanitizerPass(bool CompileKernel,bool Recover,bool UseGlobalGC,bool UseOdrIndicator,AsanDtorKind DestructorKind)1231*da58b97aSjoerg ModuleAddressSanitizerPass::ModuleAddressSanitizerPass(
1232*da58b97aSjoerg     bool CompileKernel, bool Recover, bool UseGlobalGC, bool UseOdrIndicator,
1233*da58b97aSjoerg     AsanDtorKind DestructorKind)
123406f32e7eSjoerg     : CompileKernel(CompileKernel), Recover(Recover), UseGlobalGC(UseGlobalGC),
1235*da58b97aSjoerg       UseOdrIndicator(UseOdrIndicator), DestructorKind(DestructorKind) {}
123606f32e7eSjoerg 
run(Module & M,AnalysisManager<Module> & AM)123706f32e7eSjoerg PreservedAnalyses ModuleAddressSanitizerPass::run(Module &M,
123806f32e7eSjoerg                                                   AnalysisManager<Module> &AM) {
123906f32e7eSjoerg   GlobalsMetadata &GlobalsMD = AM.getResult<ASanGlobalsMetadataAnalysis>(M);
124006f32e7eSjoerg   ModuleAddressSanitizer Sanitizer(M, &GlobalsMD, CompileKernel, Recover,
1241*da58b97aSjoerg                                    UseGlobalGC, UseOdrIndicator,
1242*da58b97aSjoerg                                    DestructorKind);
124306f32e7eSjoerg   if (Sanitizer.instrumentModule(M))
124406f32e7eSjoerg     return PreservedAnalyses::none();
124506f32e7eSjoerg   return PreservedAnalyses::all();
124606f32e7eSjoerg }
124706f32e7eSjoerg 
124806f32e7eSjoerg INITIALIZE_PASS(ASanGlobalsMetadataWrapperPass, "asan-globals-md",
124906f32e7eSjoerg                 "Read metadata to mark which globals should be instrumented "
125006f32e7eSjoerg                 "when running ASan.",
125106f32e7eSjoerg                 false, true)
125206f32e7eSjoerg 
125306f32e7eSjoerg char AddressSanitizerLegacyPass::ID = 0;
125406f32e7eSjoerg 
125506f32e7eSjoerg INITIALIZE_PASS_BEGIN(
125606f32e7eSjoerg     AddressSanitizerLegacyPass, "asan",
125706f32e7eSjoerg     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
125806f32e7eSjoerg     false)
INITIALIZE_PASS_DEPENDENCY(ASanGlobalsMetadataWrapperPass)125906f32e7eSjoerg INITIALIZE_PASS_DEPENDENCY(ASanGlobalsMetadataWrapperPass)
126006f32e7eSjoerg INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
126106f32e7eSjoerg INITIALIZE_PASS_END(
126206f32e7eSjoerg     AddressSanitizerLegacyPass, "asan",
126306f32e7eSjoerg     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
126406f32e7eSjoerg     false)
126506f32e7eSjoerg 
126606f32e7eSjoerg FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
126706f32e7eSjoerg                                                        bool Recover,
126806f32e7eSjoerg                                                        bool UseAfterScope) {
126906f32e7eSjoerg   assert(!CompileKernel || Recover);
127006f32e7eSjoerg   return new AddressSanitizerLegacyPass(CompileKernel, Recover, UseAfterScope);
127106f32e7eSjoerg }
127206f32e7eSjoerg 
127306f32e7eSjoerg char ModuleAddressSanitizerLegacyPass::ID = 0;
127406f32e7eSjoerg 
127506f32e7eSjoerg INITIALIZE_PASS(
127606f32e7eSjoerg     ModuleAddressSanitizerLegacyPass, "asan-module",
127706f32e7eSjoerg     "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
127806f32e7eSjoerg     "ModulePass",
127906f32e7eSjoerg     false, false)
128006f32e7eSjoerg 
createModuleAddressSanitizerLegacyPassPass(bool CompileKernel,bool Recover,bool UseGlobalsGC,bool UseOdrIndicator,AsanDtorKind Destructor)128106f32e7eSjoerg ModulePass *llvm::createModuleAddressSanitizerLegacyPassPass(
1282*da58b97aSjoerg     bool CompileKernel, bool Recover, bool UseGlobalsGC, bool UseOdrIndicator,
1283*da58b97aSjoerg     AsanDtorKind Destructor) {
128406f32e7eSjoerg   assert(!CompileKernel || Recover);
1285*da58b97aSjoerg   return new ModuleAddressSanitizerLegacyPass(
1286*da58b97aSjoerg       CompileKernel, Recover, UseGlobalsGC, UseOdrIndicator, Destructor);
128706f32e7eSjoerg }
128806f32e7eSjoerg 
TypeSizeToSizeIndex(uint32_t TypeSize)128906f32e7eSjoerg static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
129006f32e7eSjoerg   size_t Res = countTrailingZeros(TypeSize / 8);
129106f32e7eSjoerg   assert(Res < kNumberOfAccessSizes);
129206f32e7eSjoerg   return Res;
129306f32e7eSjoerg }
129406f32e7eSjoerg 
129506f32e7eSjoerg /// Create a global describing a source location.
createPrivateGlobalForSourceLoc(Module & M,LocationMetadata MD)129606f32e7eSjoerg static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
129706f32e7eSjoerg                                                        LocationMetadata MD) {
129806f32e7eSjoerg   Constant *LocData[] = {
129906f32e7eSjoerg       createPrivateGlobalForString(M, MD.Filename, true, kAsanGenPrefix),
130006f32e7eSjoerg       ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
130106f32e7eSjoerg       ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
130206f32e7eSjoerg   };
130306f32e7eSjoerg   auto LocStruct = ConstantStruct::getAnon(LocData);
130406f32e7eSjoerg   auto GV = new GlobalVariable(M, LocStruct->getType(), true,
130506f32e7eSjoerg                                GlobalValue::PrivateLinkage, LocStruct,
130606f32e7eSjoerg                                kAsanGenPrefix);
130706f32e7eSjoerg   GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
130806f32e7eSjoerg   return GV;
130906f32e7eSjoerg }
131006f32e7eSjoerg 
131106f32e7eSjoerg /// Check if \p G has been created by a trusted compiler pass.
GlobalWasGeneratedByCompiler(GlobalVariable * G)131206f32e7eSjoerg static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
131306f32e7eSjoerg   // Do not instrument @llvm.global_ctors, @llvm.used, etc.
131406f32e7eSjoerg   if (G->getName().startswith("llvm."))
131506f32e7eSjoerg     return true;
131606f32e7eSjoerg 
131706f32e7eSjoerg   // Do not instrument asan globals.
131806f32e7eSjoerg   if (G->getName().startswith(kAsanGenPrefix) ||
131906f32e7eSjoerg       G->getName().startswith(kSanCovGenPrefix) ||
132006f32e7eSjoerg       G->getName().startswith(kODRGenPrefix))
132106f32e7eSjoerg     return true;
132206f32e7eSjoerg 
132306f32e7eSjoerg   // Do not instrument gcov counter arrays.
132406f32e7eSjoerg   if (G->getName() == "__llvm_gcov_ctr")
132506f32e7eSjoerg     return true;
132606f32e7eSjoerg 
132706f32e7eSjoerg   return false;
132806f32e7eSjoerg }
132906f32e7eSjoerg 
isUnsupportedAMDGPUAddrspace(Value * Addr)1330*da58b97aSjoerg static bool isUnsupportedAMDGPUAddrspace(Value *Addr) {
1331*da58b97aSjoerg   Type *PtrTy = cast<PointerType>(Addr->getType()->getScalarType());
1332*da58b97aSjoerg   unsigned int AddrSpace = PtrTy->getPointerAddressSpace();
1333*da58b97aSjoerg   if (AddrSpace == 3 || AddrSpace == 5)
1334*da58b97aSjoerg     return true;
1335*da58b97aSjoerg   return false;
1336*da58b97aSjoerg }
1337*da58b97aSjoerg 
memToShadow(Value * Shadow,IRBuilder<> & IRB)133806f32e7eSjoerg Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
133906f32e7eSjoerg   // Shadow >> scale
134006f32e7eSjoerg   Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
134106f32e7eSjoerg   if (Mapping.Offset == 0) return Shadow;
134206f32e7eSjoerg   // (Shadow >> scale) | offset
134306f32e7eSjoerg   Value *ShadowBase;
134406f32e7eSjoerg   if (LocalDynamicShadow)
134506f32e7eSjoerg     ShadowBase = LocalDynamicShadow;
134606f32e7eSjoerg   else
134706f32e7eSjoerg     ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
134806f32e7eSjoerg   if (Mapping.OrShadowOffset)
134906f32e7eSjoerg     return IRB.CreateOr(Shadow, ShadowBase);
135006f32e7eSjoerg   else
135106f32e7eSjoerg     return IRB.CreateAdd(Shadow, ShadowBase);
135206f32e7eSjoerg }
135306f32e7eSjoerg 
135406f32e7eSjoerg // Instrument memset/memmove/memcpy
instrumentMemIntrinsic(MemIntrinsic * MI)135506f32e7eSjoerg void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
135606f32e7eSjoerg   IRBuilder<> IRB(MI);
135706f32e7eSjoerg   if (isa<MemTransferInst>(MI)) {
135806f32e7eSjoerg     IRB.CreateCall(
135906f32e7eSjoerg         isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
136006f32e7eSjoerg         {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
136106f32e7eSjoerg          IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
136206f32e7eSjoerg          IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
136306f32e7eSjoerg   } else if (isa<MemSetInst>(MI)) {
136406f32e7eSjoerg     IRB.CreateCall(
136506f32e7eSjoerg         AsanMemset,
136606f32e7eSjoerg         {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
136706f32e7eSjoerg          IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
136806f32e7eSjoerg          IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
136906f32e7eSjoerg   }
137006f32e7eSjoerg   MI->eraseFromParent();
137106f32e7eSjoerg }
137206f32e7eSjoerg 
137306f32e7eSjoerg /// Check if we want (and can) handle this alloca.
isInterestingAlloca(const AllocaInst & AI)137406f32e7eSjoerg bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
137506f32e7eSjoerg   auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
137606f32e7eSjoerg 
137706f32e7eSjoerg   if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
137806f32e7eSjoerg     return PreviouslySeenAllocaInfo->getSecond();
137906f32e7eSjoerg 
138006f32e7eSjoerg   bool IsInteresting =
138106f32e7eSjoerg       (AI.getAllocatedType()->isSized() &&
138206f32e7eSjoerg        // alloca() may be called with 0 size, ignore it.
138306f32e7eSjoerg        ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
138406f32e7eSjoerg        // We are only interested in allocas not promotable to registers.
138506f32e7eSjoerg        // Promotable allocas are common under -O0.
138606f32e7eSjoerg        (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
138706f32e7eSjoerg        // inalloca allocas are not treated as static, and we don't want
138806f32e7eSjoerg        // dynamic alloca instrumentation for them as well.
138906f32e7eSjoerg        !AI.isUsedWithInAlloca() &&
139006f32e7eSjoerg        // swifterror allocas are register promoted by ISel
139106f32e7eSjoerg        !AI.isSwiftError());
139206f32e7eSjoerg 
139306f32e7eSjoerg   ProcessedAllocas[&AI] = IsInteresting;
139406f32e7eSjoerg   return IsInteresting;
139506f32e7eSjoerg }
139606f32e7eSjoerg 
ignoreAccess(Value * Ptr)1397*da58b97aSjoerg bool AddressSanitizer::ignoreAccess(Value *Ptr) {
1398*da58b97aSjoerg   // Instrument acesses from different address spaces only for AMDGPU.
1399*da58b97aSjoerg   Type *PtrTy = cast<PointerType>(Ptr->getType()->getScalarType());
1400*da58b97aSjoerg   if (PtrTy->getPointerAddressSpace() != 0 &&
1401*da58b97aSjoerg       !(TargetTriple.isAMDGPU() && !isUnsupportedAMDGPUAddrspace(Ptr)))
1402*da58b97aSjoerg     return true;
140306f32e7eSjoerg 
140406f32e7eSjoerg   // Ignore swifterror addresses.
140506f32e7eSjoerg   // swifterror memory addresses are mem2reg promoted by instruction
140606f32e7eSjoerg   // selection. As such they cannot have regular uses like an instrumentation
140706f32e7eSjoerg   // function and it makes no sense to track them as memory.
1408*da58b97aSjoerg   if (Ptr->isSwiftError())
1409*da58b97aSjoerg     return true;
141006f32e7eSjoerg 
141106f32e7eSjoerg   // Treat memory accesses to promotable allocas as non-interesting since they
141206f32e7eSjoerg   // will not cause memory violations. This greatly speeds up the instrumented
141306f32e7eSjoerg   // executable at -O0.
1414*da58b97aSjoerg   if (auto AI = dyn_cast_or_null<AllocaInst>(Ptr))
1415*da58b97aSjoerg     if (ClSkipPromotableAllocas && !isInterestingAlloca(*AI))
1416*da58b97aSjoerg       return true;
141706f32e7eSjoerg 
1418*da58b97aSjoerg   return false;
1419*da58b97aSjoerg }
1420*da58b97aSjoerg 
getInterestingMemoryOperands(Instruction * I,SmallVectorImpl<InterestingMemoryOperand> & Interesting)1421*da58b97aSjoerg void AddressSanitizer::getInterestingMemoryOperands(
1422*da58b97aSjoerg     Instruction *I, SmallVectorImpl<InterestingMemoryOperand> &Interesting) {
1423*da58b97aSjoerg   // Skip memory accesses inserted by another instrumentation.
1424*da58b97aSjoerg   if (I->hasMetadata("nosanitize"))
1425*da58b97aSjoerg     return;
1426*da58b97aSjoerg 
1427*da58b97aSjoerg   // Do not instrument the load fetching the dynamic shadow address.
1428*da58b97aSjoerg   if (LocalDynamicShadow == I)
1429*da58b97aSjoerg     return;
1430*da58b97aSjoerg 
1431*da58b97aSjoerg   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1432*da58b97aSjoerg     if (!ClInstrumentReads || ignoreAccess(LI->getPointerOperand()))
1433*da58b97aSjoerg       return;
1434*da58b97aSjoerg     Interesting.emplace_back(I, LI->getPointerOperandIndex(), false,
1435*da58b97aSjoerg                              LI->getType(), LI->getAlign());
1436*da58b97aSjoerg   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1437*da58b97aSjoerg     if (!ClInstrumentWrites || ignoreAccess(SI->getPointerOperand()))
1438*da58b97aSjoerg       return;
1439*da58b97aSjoerg     Interesting.emplace_back(I, SI->getPointerOperandIndex(), true,
1440*da58b97aSjoerg                              SI->getValueOperand()->getType(), SI->getAlign());
1441*da58b97aSjoerg   } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
1442*da58b97aSjoerg     if (!ClInstrumentAtomics || ignoreAccess(RMW->getPointerOperand()))
1443*da58b97aSjoerg       return;
1444*da58b97aSjoerg     Interesting.emplace_back(I, RMW->getPointerOperandIndex(), true,
1445*da58b97aSjoerg                              RMW->getValOperand()->getType(), None);
1446*da58b97aSjoerg   } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
1447*da58b97aSjoerg     if (!ClInstrumentAtomics || ignoreAccess(XCHG->getPointerOperand()))
1448*da58b97aSjoerg       return;
1449*da58b97aSjoerg     Interesting.emplace_back(I, XCHG->getPointerOperandIndex(), true,
1450*da58b97aSjoerg                              XCHG->getCompareOperand()->getType(), None);
1451*da58b97aSjoerg   } else if (auto CI = dyn_cast<CallInst>(I)) {
1452*da58b97aSjoerg     auto *F = CI->getCalledFunction();
1453*da58b97aSjoerg     if (F && (F->getName().startswith("llvm.masked.load.") ||
1454*da58b97aSjoerg               F->getName().startswith("llvm.masked.store."))) {
1455*da58b97aSjoerg       bool IsWrite = F->getName().startswith("llvm.masked.store.");
1456*da58b97aSjoerg       // Masked store has an initial operand for the value.
1457*da58b97aSjoerg       unsigned OpOffset = IsWrite ? 1 : 0;
1458*da58b97aSjoerg       if (IsWrite ? !ClInstrumentWrites : !ClInstrumentReads)
1459*da58b97aSjoerg         return;
1460*da58b97aSjoerg 
1461*da58b97aSjoerg       auto BasePtr = CI->getOperand(OpOffset);
1462*da58b97aSjoerg       if (ignoreAccess(BasePtr))
1463*da58b97aSjoerg         return;
1464*da58b97aSjoerg       auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
1465*da58b97aSjoerg       MaybeAlign Alignment = Align(1);
1466*da58b97aSjoerg       // Otherwise no alignment guarantees. We probably got Undef.
1467*da58b97aSjoerg       if (auto *Op = dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1468*da58b97aSjoerg         Alignment = Op->getMaybeAlignValue();
1469*da58b97aSjoerg       Value *Mask = CI->getOperand(2 + OpOffset);
1470*da58b97aSjoerg       Interesting.emplace_back(I, OpOffset, IsWrite, Ty, Alignment, Mask);
1471*da58b97aSjoerg     } else {
1472*da58b97aSjoerg       for (unsigned ArgNo = 0; ArgNo < CI->getNumArgOperands(); ArgNo++) {
1473*da58b97aSjoerg         if (!ClInstrumentByval || !CI->isByValArgument(ArgNo) ||
1474*da58b97aSjoerg             ignoreAccess(CI->getArgOperand(ArgNo)))
1475*da58b97aSjoerg           continue;
1476*da58b97aSjoerg         Type *Ty = CI->getParamByValType(ArgNo);
1477*da58b97aSjoerg         Interesting.emplace_back(I, ArgNo, false, Ty, Align(1));
1478*da58b97aSjoerg       }
1479*da58b97aSjoerg     }
1480*da58b97aSjoerg   }
148106f32e7eSjoerg }
148206f32e7eSjoerg 
isPointerOperand(Value * V)148306f32e7eSjoerg static bool isPointerOperand(Value *V) {
148406f32e7eSjoerg   return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
148506f32e7eSjoerg }
148606f32e7eSjoerg 
148706f32e7eSjoerg // This is a rough heuristic; it may cause both false positives and
148806f32e7eSjoerg // false negatives. The proper implementation requires cooperation with
148906f32e7eSjoerg // the frontend.
isInterestingPointerComparison(Instruction * I)149006f32e7eSjoerg static bool isInterestingPointerComparison(Instruction *I) {
149106f32e7eSjoerg   if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
149206f32e7eSjoerg     if (!Cmp->isRelational())
149306f32e7eSjoerg       return false;
149406f32e7eSjoerg   } else {
149506f32e7eSjoerg     return false;
149606f32e7eSjoerg   }
149706f32e7eSjoerg   return isPointerOperand(I->getOperand(0)) &&
149806f32e7eSjoerg          isPointerOperand(I->getOperand(1));
149906f32e7eSjoerg }
150006f32e7eSjoerg 
150106f32e7eSjoerg // This is a rough heuristic; it may cause both false positives and
150206f32e7eSjoerg // false negatives. The proper implementation requires cooperation with
150306f32e7eSjoerg // the frontend.
isInterestingPointerSubtraction(Instruction * I)150406f32e7eSjoerg static bool isInterestingPointerSubtraction(Instruction *I) {
150506f32e7eSjoerg   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
150606f32e7eSjoerg     if (BO->getOpcode() != Instruction::Sub)
150706f32e7eSjoerg       return false;
150806f32e7eSjoerg   } else {
150906f32e7eSjoerg     return false;
151006f32e7eSjoerg   }
151106f32e7eSjoerg   return isPointerOperand(I->getOperand(0)) &&
151206f32e7eSjoerg          isPointerOperand(I->getOperand(1));
151306f32e7eSjoerg }
151406f32e7eSjoerg 
GlobalIsLinkerInitialized(GlobalVariable * G)151506f32e7eSjoerg bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
151606f32e7eSjoerg   // If a global variable does not have dynamic initialization we don't
151706f32e7eSjoerg   // have to instrument it.  However, if a global does not have initializer
151806f32e7eSjoerg   // at all, we assume it has dynamic initializer (in other TU).
151906f32e7eSjoerg   //
152006f32e7eSjoerg   // FIXME: Metadata should be attched directly to the global directly instead
152106f32e7eSjoerg   // of being added to llvm.asan.globals.
152206f32e7eSjoerg   return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
152306f32e7eSjoerg }
152406f32e7eSjoerg 
instrumentPointerComparisonOrSubtraction(Instruction * I)152506f32e7eSjoerg void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
152606f32e7eSjoerg     Instruction *I) {
152706f32e7eSjoerg   IRBuilder<> IRB(I);
152806f32e7eSjoerg   FunctionCallee F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
152906f32e7eSjoerg   Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
153006f32e7eSjoerg   for (Value *&i : Param) {
153106f32e7eSjoerg     if (i->getType()->isPointerTy())
153206f32e7eSjoerg       i = IRB.CreatePointerCast(i, IntptrTy);
153306f32e7eSjoerg   }
153406f32e7eSjoerg   IRB.CreateCall(F, Param);
153506f32e7eSjoerg }
153606f32e7eSjoerg 
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)153706f32e7eSjoerg static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,
153806f32e7eSjoerg                                 Instruction *InsertBefore, Value *Addr,
1539*da58b97aSjoerg                                 MaybeAlign Alignment, unsigned Granularity,
154006f32e7eSjoerg                                 uint32_t TypeSize, bool IsWrite,
154106f32e7eSjoerg                                 Value *SizeArgument, bool UseCalls,
154206f32e7eSjoerg                                 uint32_t Exp) {
154306f32e7eSjoerg   // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
154406f32e7eSjoerg   // if the data is properly aligned.
154506f32e7eSjoerg   if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
154606f32e7eSjoerg        TypeSize == 128) &&
1547*da58b97aSjoerg       (!Alignment || *Alignment >= Granularity || *Alignment >= TypeSize / 8))
154806f32e7eSjoerg     return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
154906f32e7eSjoerg                                    nullptr, UseCalls, Exp);
155006f32e7eSjoerg   Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
155106f32e7eSjoerg                                          IsWrite, nullptr, UseCalls, Exp);
155206f32e7eSjoerg }
155306f32e7eSjoerg 
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)155406f32e7eSjoerg static void instrumentMaskedLoadOrStore(AddressSanitizer *Pass,
155506f32e7eSjoerg                                         const DataLayout &DL, Type *IntptrTy,
155606f32e7eSjoerg                                         Value *Mask, Instruction *I,
1557*da58b97aSjoerg                                         Value *Addr, MaybeAlign Alignment,
155806f32e7eSjoerg                                         unsigned Granularity, uint32_t TypeSize,
155906f32e7eSjoerg                                         bool IsWrite, Value *SizeArgument,
156006f32e7eSjoerg                                         bool UseCalls, uint32_t Exp) {
1561*da58b97aSjoerg   auto *VTy = cast<FixedVectorType>(
1562*da58b97aSjoerg       cast<PointerType>(Addr->getType())->getElementType());
156306f32e7eSjoerg   uint64_t ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
1564*da58b97aSjoerg   unsigned Num = VTy->getNumElements();
156506f32e7eSjoerg   auto Zero = ConstantInt::get(IntptrTy, 0);
156606f32e7eSjoerg   for (unsigned Idx = 0; Idx < Num; ++Idx) {
156706f32e7eSjoerg     Value *InstrumentedAddress = nullptr;
156806f32e7eSjoerg     Instruction *InsertBefore = I;
156906f32e7eSjoerg     if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
157006f32e7eSjoerg       // dyn_cast as we might get UndefValue
157106f32e7eSjoerg       if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
157206f32e7eSjoerg         if (Masked->isZero())
157306f32e7eSjoerg           // Mask is constant false, so no instrumentation needed.
157406f32e7eSjoerg           continue;
157506f32e7eSjoerg         // If we have a true or undef value, fall through to doInstrumentAddress
157606f32e7eSjoerg         // with InsertBefore == I
157706f32e7eSjoerg       }
157806f32e7eSjoerg     } else {
157906f32e7eSjoerg       IRBuilder<> IRB(I);
158006f32e7eSjoerg       Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
158106f32e7eSjoerg       Instruction *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
158206f32e7eSjoerg       InsertBefore = ThenTerm;
158306f32e7eSjoerg     }
158406f32e7eSjoerg 
158506f32e7eSjoerg     IRBuilder<> IRB(InsertBefore);
158606f32e7eSjoerg     InstrumentedAddress =
158706f32e7eSjoerg         IRB.CreateGEP(VTy, Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
158806f32e7eSjoerg     doInstrumentAddress(Pass, I, InsertBefore, InstrumentedAddress, Alignment,
158906f32e7eSjoerg                         Granularity, ElemTypeSize, IsWrite, SizeArgument,
159006f32e7eSjoerg                         UseCalls, Exp);
159106f32e7eSjoerg   }
159206f32e7eSjoerg }
159306f32e7eSjoerg 
instrumentMop(ObjectSizeOffsetVisitor & ObjSizeVis,InterestingMemoryOperand & O,bool UseCalls,const DataLayout & DL)159406f32e7eSjoerg void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
1595*da58b97aSjoerg                                      InterestingMemoryOperand &O, bool UseCalls,
159606f32e7eSjoerg                                      const DataLayout &DL) {
1597*da58b97aSjoerg   Value *Addr = O.getPtr();
159806f32e7eSjoerg 
159906f32e7eSjoerg   // Optimization experiments.
160006f32e7eSjoerg   // The experiments can be used to evaluate potential optimizations that remove
160106f32e7eSjoerg   // instrumentation (assess false negatives). Instead of completely removing
160206f32e7eSjoerg   // some instrumentation, you set Exp to a non-zero value (mask of optimization
160306f32e7eSjoerg   // experiments that want to remove instrumentation of this instruction).
160406f32e7eSjoerg   // If Exp is non-zero, this pass will emit special calls into runtime
160506f32e7eSjoerg   // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
160606f32e7eSjoerg   // make runtime terminate the program in a special way (with a different
160706f32e7eSjoerg   // exit status). Then you run the new compiler on a buggy corpus, collect
160806f32e7eSjoerg   // the special terminations (ideally, you don't see them at all -- no false
160906f32e7eSjoerg   // negatives) and make the decision on the optimization.
161006f32e7eSjoerg   uint32_t Exp = ClForceExperiment;
161106f32e7eSjoerg 
161206f32e7eSjoerg   if (ClOpt && ClOptGlobals) {
161306f32e7eSjoerg     // If initialization order checking is disabled, a simple access to a
161406f32e7eSjoerg     // dynamically initialized global is always valid.
1615*da58b97aSjoerg     GlobalVariable *G = dyn_cast<GlobalVariable>(getUnderlyingObject(Addr));
161606f32e7eSjoerg     if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
1617*da58b97aSjoerg         isSafeAccess(ObjSizeVis, Addr, O.TypeSize)) {
161806f32e7eSjoerg       NumOptimizedAccessesToGlobalVar++;
161906f32e7eSjoerg       return;
162006f32e7eSjoerg     }
162106f32e7eSjoerg   }
162206f32e7eSjoerg 
162306f32e7eSjoerg   if (ClOpt && ClOptStack) {
162406f32e7eSjoerg     // A direct inbounds access to a stack variable is always valid.
1625*da58b97aSjoerg     if (isa<AllocaInst>(getUnderlyingObject(Addr)) &&
1626*da58b97aSjoerg         isSafeAccess(ObjSizeVis, Addr, O.TypeSize)) {
162706f32e7eSjoerg       NumOptimizedAccessesToStackVar++;
162806f32e7eSjoerg       return;
162906f32e7eSjoerg     }
163006f32e7eSjoerg   }
163106f32e7eSjoerg 
1632*da58b97aSjoerg   if (O.IsWrite)
163306f32e7eSjoerg     NumInstrumentedWrites++;
163406f32e7eSjoerg   else
163506f32e7eSjoerg     NumInstrumentedReads++;
163606f32e7eSjoerg 
163706f32e7eSjoerg   unsigned Granularity = 1 << Mapping.Scale;
1638*da58b97aSjoerg   if (O.MaybeMask) {
1639*da58b97aSjoerg     instrumentMaskedLoadOrStore(this, DL, IntptrTy, O.MaybeMask, O.getInsn(),
1640*da58b97aSjoerg                                 Addr, O.Alignment, Granularity, O.TypeSize,
1641*da58b97aSjoerg                                 O.IsWrite, nullptr, UseCalls, Exp);
164206f32e7eSjoerg   } else {
1643*da58b97aSjoerg     doInstrumentAddress(this, O.getInsn(), O.getInsn(), Addr, O.Alignment,
1644*da58b97aSjoerg                         Granularity, O.TypeSize, O.IsWrite, nullptr, UseCalls,
1645*da58b97aSjoerg                         Exp);
164606f32e7eSjoerg   }
164706f32e7eSjoerg }
164806f32e7eSjoerg 
generateCrashCode(Instruction * InsertBefore,Value * Addr,bool IsWrite,size_t AccessSizeIndex,Value * SizeArgument,uint32_t Exp)164906f32e7eSjoerg Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
165006f32e7eSjoerg                                                  Value *Addr, bool IsWrite,
165106f32e7eSjoerg                                                  size_t AccessSizeIndex,
165206f32e7eSjoerg                                                  Value *SizeArgument,
165306f32e7eSjoerg                                                  uint32_t Exp) {
165406f32e7eSjoerg   IRBuilder<> IRB(InsertBefore);
165506f32e7eSjoerg   Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
165606f32e7eSjoerg   CallInst *Call = nullptr;
165706f32e7eSjoerg   if (SizeArgument) {
165806f32e7eSjoerg     if (Exp == 0)
165906f32e7eSjoerg       Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
166006f32e7eSjoerg                             {Addr, SizeArgument});
166106f32e7eSjoerg     else
166206f32e7eSjoerg       Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
166306f32e7eSjoerg                             {Addr, SizeArgument, ExpVal});
166406f32e7eSjoerg   } else {
166506f32e7eSjoerg     if (Exp == 0)
166606f32e7eSjoerg       Call =
166706f32e7eSjoerg           IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
166806f32e7eSjoerg     else
166906f32e7eSjoerg       Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
167006f32e7eSjoerg                             {Addr, ExpVal});
167106f32e7eSjoerg   }
167206f32e7eSjoerg 
1673*da58b97aSjoerg   Call->setCannotMerge();
167406f32e7eSjoerg   return Call;
167506f32e7eSjoerg }
167606f32e7eSjoerg 
createSlowPathCmp(IRBuilder<> & IRB,Value * AddrLong,Value * ShadowValue,uint32_t TypeSize)167706f32e7eSjoerg Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
167806f32e7eSjoerg                                            Value *ShadowValue,
167906f32e7eSjoerg                                            uint32_t TypeSize) {
168006f32e7eSjoerg   size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
168106f32e7eSjoerg   // Addr & (Granularity - 1)
168206f32e7eSjoerg   Value *LastAccessedByte =
168306f32e7eSjoerg       IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
168406f32e7eSjoerg   // (Addr & (Granularity - 1)) + size - 1
168506f32e7eSjoerg   if (TypeSize / 8 > 1)
168606f32e7eSjoerg     LastAccessedByte = IRB.CreateAdd(
168706f32e7eSjoerg         LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
168806f32e7eSjoerg   // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
168906f32e7eSjoerg   LastAccessedByte =
169006f32e7eSjoerg       IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
169106f32e7eSjoerg   // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
169206f32e7eSjoerg   return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
169306f32e7eSjoerg }
169406f32e7eSjoerg 
instrumentAMDGPUAddress(Instruction * OrigIns,Instruction * InsertBefore,Value * Addr,uint32_t TypeSize,bool IsWrite,Value * SizeArgument)1695*da58b97aSjoerg Instruction *AddressSanitizer::instrumentAMDGPUAddress(
1696*da58b97aSjoerg     Instruction *OrigIns, Instruction *InsertBefore, Value *Addr,
1697*da58b97aSjoerg     uint32_t TypeSize, bool IsWrite, Value *SizeArgument) {
1698*da58b97aSjoerg   // Do not instrument unsupported addrspaces.
1699*da58b97aSjoerg   if (isUnsupportedAMDGPUAddrspace(Addr))
1700*da58b97aSjoerg     return nullptr;
1701*da58b97aSjoerg   Type *PtrTy = cast<PointerType>(Addr->getType()->getScalarType());
1702*da58b97aSjoerg   // Follow host instrumentation for global and constant addresses.
1703*da58b97aSjoerg   if (PtrTy->getPointerAddressSpace() != 0)
1704*da58b97aSjoerg     return InsertBefore;
1705*da58b97aSjoerg   // Instrument generic addresses in supported addressspaces.
1706*da58b97aSjoerg   IRBuilder<> IRB(InsertBefore);
1707*da58b97aSjoerg   Value *AddrLong = IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy());
1708*da58b97aSjoerg   Value *IsShared = IRB.CreateCall(AMDGPUAddressShared, {AddrLong});
1709*da58b97aSjoerg   Value *IsPrivate = IRB.CreateCall(AMDGPUAddressPrivate, {AddrLong});
1710*da58b97aSjoerg   Value *IsSharedOrPrivate = IRB.CreateOr(IsShared, IsPrivate);
1711*da58b97aSjoerg   Value *Cmp = IRB.CreateICmpNE(IRB.getTrue(), IsSharedOrPrivate);
1712*da58b97aSjoerg   Value *AddrSpaceZeroLanding =
1713*da58b97aSjoerg       SplitBlockAndInsertIfThen(Cmp, InsertBefore, false);
1714*da58b97aSjoerg   InsertBefore = cast<Instruction>(AddrSpaceZeroLanding);
1715*da58b97aSjoerg   return InsertBefore;
1716*da58b97aSjoerg }
1717*da58b97aSjoerg 
instrumentAddress(Instruction * OrigIns,Instruction * InsertBefore,Value * Addr,uint32_t TypeSize,bool IsWrite,Value * SizeArgument,bool UseCalls,uint32_t Exp)171806f32e7eSjoerg void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
171906f32e7eSjoerg                                          Instruction *InsertBefore, Value *Addr,
172006f32e7eSjoerg                                          uint32_t TypeSize, bool IsWrite,
172106f32e7eSjoerg                                          Value *SizeArgument, bool UseCalls,
172206f32e7eSjoerg                                          uint32_t Exp) {
172306f32e7eSjoerg   bool IsMyriad = TargetTriple.getVendor() == llvm::Triple::Myriad;
172406f32e7eSjoerg 
1725*da58b97aSjoerg   if (TargetTriple.isAMDGPU()) {
1726*da58b97aSjoerg     InsertBefore = instrumentAMDGPUAddress(OrigIns, InsertBefore, Addr,
1727*da58b97aSjoerg                                            TypeSize, IsWrite, SizeArgument);
1728*da58b97aSjoerg     if (!InsertBefore)
1729*da58b97aSjoerg       return;
1730*da58b97aSjoerg   }
1731*da58b97aSjoerg 
173206f32e7eSjoerg   IRBuilder<> IRB(InsertBefore);
173306f32e7eSjoerg   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
173406f32e7eSjoerg   size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
173506f32e7eSjoerg 
173606f32e7eSjoerg   if (UseCalls) {
173706f32e7eSjoerg     if (Exp == 0)
173806f32e7eSjoerg       IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
173906f32e7eSjoerg                      AddrLong);
174006f32e7eSjoerg     else
174106f32e7eSjoerg       IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
174206f32e7eSjoerg                      {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
174306f32e7eSjoerg     return;
174406f32e7eSjoerg   }
174506f32e7eSjoerg 
174606f32e7eSjoerg   if (IsMyriad) {
174706f32e7eSjoerg     // Strip the cache bit and do range check.
174806f32e7eSjoerg     // AddrLong &= ~kMyriadCacheBitMask32
174906f32e7eSjoerg     AddrLong = IRB.CreateAnd(AddrLong, ~kMyriadCacheBitMask32);
175006f32e7eSjoerg     // Tag = AddrLong >> kMyriadTagShift
175106f32e7eSjoerg     Value *Tag = IRB.CreateLShr(AddrLong, kMyriadTagShift);
175206f32e7eSjoerg     // Tag == kMyriadDDRTag
175306f32e7eSjoerg     Value *TagCheck =
175406f32e7eSjoerg         IRB.CreateICmpEQ(Tag, ConstantInt::get(IntptrTy, kMyriadDDRTag));
175506f32e7eSjoerg 
175606f32e7eSjoerg     Instruction *TagCheckTerm =
175706f32e7eSjoerg         SplitBlockAndInsertIfThen(TagCheck, InsertBefore, false,
175806f32e7eSjoerg                                   MDBuilder(*C).createBranchWeights(1, 100000));
175906f32e7eSjoerg     assert(cast<BranchInst>(TagCheckTerm)->isUnconditional());
176006f32e7eSjoerg     IRB.SetInsertPoint(TagCheckTerm);
176106f32e7eSjoerg     InsertBefore = TagCheckTerm;
176206f32e7eSjoerg   }
176306f32e7eSjoerg 
176406f32e7eSjoerg   Type *ShadowTy =
176506f32e7eSjoerg       IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
176606f32e7eSjoerg   Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
176706f32e7eSjoerg   Value *ShadowPtr = memToShadow(AddrLong, IRB);
176806f32e7eSjoerg   Value *CmpVal = Constant::getNullValue(ShadowTy);
176906f32e7eSjoerg   Value *ShadowValue =
177006f32e7eSjoerg       IRB.CreateLoad(ShadowTy, IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
177106f32e7eSjoerg 
177206f32e7eSjoerg   Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
177306f32e7eSjoerg   size_t Granularity = 1ULL << Mapping.Scale;
177406f32e7eSjoerg   Instruction *CrashTerm = nullptr;
177506f32e7eSjoerg 
177606f32e7eSjoerg   if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
177706f32e7eSjoerg     // We use branch weights for the slow path check, to indicate that the slow
177806f32e7eSjoerg     // path is rarely taken. This seems to be the case for SPEC benchmarks.
177906f32e7eSjoerg     Instruction *CheckTerm = SplitBlockAndInsertIfThen(
178006f32e7eSjoerg         Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
178106f32e7eSjoerg     assert(cast<BranchInst>(CheckTerm)->isUnconditional());
178206f32e7eSjoerg     BasicBlock *NextBB = CheckTerm->getSuccessor(0);
178306f32e7eSjoerg     IRB.SetInsertPoint(CheckTerm);
178406f32e7eSjoerg     Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
178506f32e7eSjoerg     if (Recover) {
178606f32e7eSjoerg       CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
178706f32e7eSjoerg     } else {
178806f32e7eSjoerg       BasicBlock *CrashBlock =
178906f32e7eSjoerg         BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
179006f32e7eSjoerg       CrashTerm = new UnreachableInst(*C, CrashBlock);
179106f32e7eSjoerg       BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
179206f32e7eSjoerg       ReplaceInstWithInst(CheckTerm, NewTerm);
179306f32e7eSjoerg     }
179406f32e7eSjoerg   } else {
179506f32e7eSjoerg     CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
179606f32e7eSjoerg   }
179706f32e7eSjoerg 
179806f32e7eSjoerg   Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
179906f32e7eSjoerg                                          AccessSizeIndex, SizeArgument, Exp);
180006f32e7eSjoerg   Crash->setDebugLoc(OrigIns->getDebugLoc());
180106f32e7eSjoerg }
180206f32e7eSjoerg 
180306f32e7eSjoerg // Instrument unusual size or unusual alignment.
180406f32e7eSjoerg // We can not do it with a single check, so we do 1-byte check for the first
180506f32e7eSjoerg // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
180606f32e7eSjoerg // 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)180706f32e7eSjoerg void AddressSanitizer::instrumentUnusualSizeOrAlignment(
180806f32e7eSjoerg     Instruction *I, Instruction *InsertBefore, Value *Addr, uint32_t TypeSize,
180906f32e7eSjoerg     bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp) {
181006f32e7eSjoerg   IRBuilder<> IRB(InsertBefore);
181106f32e7eSjoerg   Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
181206f32e7eSjoerg   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
181306f32e7eSjoerg   if (UseCalls) {
181406f32e7eSjoerg     if (Exp == 0)
181506f32e7eSjoerg       IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
181606f32e7eSjoerg                      {AddrLong, Size});
181706f32e7eSjoerg     else
181806f32e7eSjoerg       IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
181906f32e7eSjoerg                      {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
182006f32e7eSjoerg   } else {
182106f32e7eSjoerg     Value *LastByte = IRB.CreateIntToPtr(
182206f32e7eSjoerg         IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
182306f32e7eSjoerg         Addr->getType());
182406f32e7eSjoerg     instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size, false, Exp);
182506f32e7eSjoerg     instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size, false, Exp);
182606f32e7eSjoerg   }
182706f32e7eSjoerg }
182806f32e7eSjoerg 
poisonOneInitializer(Function & GlobalInit,GlobalValue * ModuleName)182906f32e7eSjoerg void ModuleAddressSanitizer::poisonOneInitializer(Function &GlobalInit,
183006f32e7eSjoerg                                                   GlobalValue *ModuleName) {
183106f32e7eSjoerg   // Set up the arguments to our poison/unpoison functions.
183206f32e7eSjoerg   IRBuilder<> IRB(&GlobalInit.front(),
183306f32e7eSjoerg                   GlobalInit.front().getFirstInsertionPt());
183406f32e7eSjoerg 
183506f32e7eSjoerg   // Add a call to poison all external globals before the given function starts.
183606f32e7eSjoerg   Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
183706f32e7eSjoerg   IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
183806f32e7eSjoerg 
183906f32e7eSjoerg   // Add calls to unpoison all globals before each return instruction.
184006f32e7eSjoerg   for (auto &BB : GlobalInit.getBasicBlockList())
184106f32e7eSjoerg     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
184206f32e7eSjoerg       CallInst::Create(AsanUnpoisonGlobals, "", RI);
184306f32e7eSjoerg }
184406f32e7eSjoerg 
createInitializerPoisonCalls(Module & M,GlobalValue * ModuleName)184506f32e7eSjoerg void ModuleAddressSanitizer::createInitializerPoisonCalls(
184606f32e7eSjoerg     Module &M, GlobalValue *ModuleName) {
184706f32e7eSjoerg   GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
184806f32e7eSjoerg   if (!GV)
184906f32e7eSjoerg     return;
185006f32e7eSjoerg 
185106f32e7eSjoerg   ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
185206f32e7eSjoerg   if (!CA)
185306f32e7eSjoerg     return;
185406f32e7eSjoerg 
185506f32e7eSjoerg   for (Use &OP : CA->operands()) {
185606f32e7eSjoerg     if (isa<ConstantAggregateZero>(OP)) continue;
185706f32e7eSjoerg     ConstantStruct *CS = cast<ConstantStruct>(OP);
185806f32e7eSjoerg 
185906f32e7eSjoerg     // Must have a function or null ptr.
186006f32e7eSjoerg     if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
186106f32e7eSjoerg       if (F->getName() == kAsanModuleCtorName) continue;
186206f32e7eSjoerg       auto *Priority = cast<ConstantInt>(CS->getOperand(0));
186306f32e7eSjoerg       // Don't instrument CTORs that will run before asan.module_ctor.
186406f32e7eSjoerg       if (Priority->getLimitedValue() <= GetCtorAndDtorPriority(TargetTriple))
186506f32e7eSjoerg         continue;
186606f32e7eSjoerg       poisonOneInitializer(*F, ModuleName);
186706f32e7eSjoerg     }
186806f32e7eSjoerg   }
186906f32e7eSjoerg }
187006f32e7eSjoerg 
1871*da58b97aSjoerg const GlobalVariable *
getExcludedAliasedGlobal(const GlobalAlias & GA) const1872*da58b97aSjoerg ModuleAddressSanitizer::getExcludedAliasedGlobal(const GlobalAlias &GA) const {
1873*da58b97aSjoerg   // In case this function should be expanded to include rules that do not just
1874*da58b97aSjoerg   // apply when CompileKernel is true, either guard all existing rules with an
1875*da58b97aSjoerg   // 'if (CompileKernel) { ... }' or be absolutely sure that all these rules
1876*da58b97aSjoerg   // should also apply to user space.
1877*da58b97aSjoerg   assert(CompileKernel && "Only expecting to be called when compiling kernel");
1878*da58b97aSjoerg 
1879*da58b97aSjoerg   const Constant *C = GA.getAliasee();
1880*da58b97aSjoerg 
1881*da58b97aSjoerg   // When compiling the kernel, globals that are aliased by symbols prefixed
1882*da58b97aSjoerg   // by "__" are special and cannot be padded with a redzone.
1883*da58b97aSjoerg   if (GA.getName().startswith("__"))
1884*da58b97aSjoerg     return dyn_cast<GlobalVariable>(C->stripPointerCastsAndAliases());
1885*da58b97aSjoerg 
1886*da58b97aSjoerg   return nullptr;
1887*da58b97aSjoerg }
1888*da58b97aSjoerg 
shouldInstrumentGlobal(GlobalVariable * G) const1889*da58b97aSjoerg bool ModuleAddressSanitizer::shouldInstrumentGlobal(GlobalVariable *G) const {
189006f32e7eSjoerg   Type *Ty = G->getValueType();
189106f32e7eSjoerg   LLVM_DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
189206f32e7eSjoerg 
189306f32e7eSjoerg   // FIXME: Metadata should be attched directly to the global directly instead
189406f32e7eSjoerg   // of being added to llvm.asan.globals.
1895*da58b97aSjoerg   if (GlobalsMD.get(G).IsExcluded) return false;
189606f32e7eSjoerg   if (!Ty->isSized()) return false;
189706f32e7eSjoerg   if (!G->hasInitializer()) return false;
1898*da58b97aSjoerg   // Globals in address space 1 and 4 are supported for AMDGPU.
1899*da58b97aSjoerg   if (G->getAddressSpace() &&
1900*da58b97aSjoerg       !(TargetTriple.isAMDGPU() && !isUnsupportedAMDGPUAddrspace(G)))
1901*da58b97aSjoerg     return false;
190206f32e7eSjoerg   if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
190306f32e7eSjoerg   // Two problems with thread-locals:
190406f32e7eSjoerg   //   - The address of the main thread's copy can't be computed at link-time.
190506f32e7eSjoerg   //   - Need to poison all copies, not just the main thread's one.
190606f32e7eSjoerg   if (G->isThreadLocal()) return false;
190706f32e7eSjoerg   // For now, just ignore this Global if the alignment is large.
1908*da58b97aSjoerg   if (G->getAlignment() > getMinRedzoneSizeForGlobal()) return false;
190906f32e7eSjoerg 
191006f32e7eSjoerg   // For non-COFF targets, only instrument globals known to be defined by this
191106f32e7eSjoerg   // TU.
191206f32e7eSjoerg   // FIXME: We can instrument comdat globals on ELF if we are using the
191306f32e7eSjoerg   // GC-friendly metadata scheme.
191406f32e7eSjoerg   if (!TargetTriple.isOSBinFormatCOFF()) {
191506f32e7eSjoerg     if (!G->hasExactDefinition() || G->hasComdat())
191606f32e7eSjoerg       return false;
191706f32e7eSjoerg   } else {
191806f32e7eSjoerg     // On COFF, don't instrument non-ODR linkages.
191906f32e7eSjoerg     if (G->isInterposable())
192006f32e7eSjoerg       return false;
192106f32e7eSjoerg   }
192206f32e7eSjoerg 
192306f32e7eSjoerg   // If a comdat is present, it must have a selection kind that implies ODR
192406f32e7eSjoerg   // semantics: no duplicates, any, or exact match.
192506f32e7eSjoerg   if (Comdat *C = G->getComdat()) {
192606f32e7eSjoerg     switch (C->getSelectionKind()) {
192706f32e7eSjoerg     case Comdat::Any:
192806f32e7eSjoerg     case Comdat::ExactMatch:
192906f32e7eSjoerg     case Comdat::NoDuplicates:
193006f32e7eSjoerg       break;
193106f32e7eSjoerg     case Comdat::Largest:
193206f32e7eSjoerg     case Comdat::SameSize:
193306f32e7eSjoerg       return false;
193406f32e7eSjoerg     }
193506f32e7eSjoerg   }
193606f32e7eSjoerg 
193706f32e7eSjoerg   if (G->hasSection()) {
1938*da58b97aSjoerg     // The kernel uses explicit sections for mostly special global variables
1939*da58b97aSjoerg     // that we should not instrument. E.g. the kernel may rely on their layout
1940*da58b97aSjoerg     // without redzones, or remove them at link time ("discard.*"), etc.
1941*da58b97aSjoerg     if (CompileKernel)
1942*da58b97aSjoerg       return false;
1943*da58b97aSjoerg 
194406f32e7eSjoerg     StringRef Section = G->getSection();
194506f32e7eSjoerg 
194606f32e7eSjoerg     // Globals from llvm.metadata aren't emitted, do not instrument them.
194706f32e7eSjoerg     if (Section == "llvm.metadata") return false;
194806f32e7eSjoerg     // Do not instrument globals from special LLVM sections.
194906f32e7eSjoerg     if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
195006f32e7eSjoerg 
195106f32e7eSjoerg     // Do not instrument function pointers to initialization and termination
195206f32e7eSjoerg     // routines: dynamic linker will not properly handle redzones.
195306f32e7eSjoerg     if (Section.startswith(".preinit_array") ||
195406f32e7eSjoerg         Section.startswith(".init_array") ||
195506f32e7eSjoerg         Section.startswith(".fini_array")) {
195606f32e7eSjoerg       return false;
195706f32e7eSjoerg     }
195806f32e7eSjoerg 
1959*da58b97aSjoerg     // Do not instrument user-defined sections (with names resembling
1960*da58b97aSjoerg     // valid C identifiers)
1961*da58b97aSjoerg     if (TargetTriple.isOSBinFormatELF()) {
1962*da58b97aSjoerg       if (llvm::all_of(Section,
1963*da58b97aSjoerg                        [](char c) { return llvm::isAlnum(c) || c == '_'; }))
1964*da58b97aSjoerg         return false;
1965*da58b97aSjoerg     }
1966*da58b97aSjoerg 
196706f32e7eSjoerg     // On COFF, if the section name contains '$', it is highly likely that the
196806f32e7eSjoerg     // user is using section sorting to create an array of globals similar to
196906f32e7eSjoerg     // the way initialization callbacks are registered in .init_array and
197006f32e7eSjoerg     // .CRT$XCU. The ATL also registers things in .ATL$__[azm]. Adding redzones
197106f32e7eSjoerg     // to such globals is counterproductive, because the intent is that they
197206f32e7eSjoerg     // will form an array, and out-of-bounds accesses are expected.
197306f32e7eSjoerg     // See https://github.com/google/sanitizers/issues/305
197406f32e7eSjoerg     // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
197506f32e7eSjoerg     if (TargetTriple.isOSBinFormatCOFF() && Section.contains('$')) {
197606f32e7eSjoerg       LLVM_DEBUG(dbgs() << "Ignoring global in sorted section (contains '$'): "
197706f32e7eSjoerg                         << *G << "\n");
197806f32e7eSjoerg       return false;
197906f32e7eSjoerg     }
198006f32e7eSjoerg 
198106f32e7eSjoerg     if (TargetTriple.isOSBinFormatMachO()) {
198206f32e7eSjoerg       StringRef ParsedSegment, ParsedSection;
198306f32e7eSjoerg       unsigned TAA = 0, StubSize = 0;
198406f32e7eSjoerg       bool TAAParsed;
1985*da58b97aSjoerg       cantFail(MCSectionMachO::ParseSectionSpecifier(
1986*da58b97aSjoerg           Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize));
198706f32e7eSjoerg 
198806f32e7eSjoerg       // Ignore the globals from the __OBJC section. The ObjC runtime assumes
198906f32e7eSjoerg       // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
199006f32e7eSjoerg       // them.
199106f32e7eSjoerg       if (ParsedSegment == "__OBJC" ||
199206f32e7eSjoerg           (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
199306f32e7eSjoerg         LLVM_DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
199406f32e7eSjoerg         return false;
199506f32e7eSjoerg       }
199606f32e7eSjoerg       // See https://github.com/google/sanitizers/issues/32
199706f32e7eSjoerg       // Constant CFString instances are compiled in the following way:
199806f32e7eSjoerg       //  -- the string buffer is emitted into
199906f32e7eSjoerg       //     __TEXT,__cstring,cstring_literals
200006f32e7eSjoerg       //  -- the constant NSConstantString structure referencing that buffer
200106f32e7eSjoerg       //     is placed into __DATA,__cfstring
200206f32e7eSjoerg       // Therefore there's no point in placing redzones into __DATA,__cfstring.
200306f32e7eSjoerg       // Moreover, it causes the linker to crash on OS X 10.7
200406f32e7eSjoerg       if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
200506f32e7eSjoerg         LLVM_DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
200606f32e7eSjoerg         return false;
200706f32e7eSjoerg       }
200806f32e7eSjoerg       // The linker merges the contents of cstring_literals and removes the
200906f32e7eSjoerg       // trailing zeroes.
201006f32e7eSjoerg       if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
201106f32e7eSjoerg         LLVM_DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
201206f32e7eSjoerg         return false;
201306f32e7eSjoerg       }
201406f32e7eSjoerg     }
201506f32e7eSjoerg   }
201606f32e7eSjoerg 
2017*da58b97aSjoerg   if (CompileKernel) {
2018*da58b97aSjoerg     // Globals that prefixed by "__" are special and cannot be padded with a
2019*da58b97aSjoerg     // redzone.
2020*da58b97aSjoerg     if (G->getName().startswith("__"))
2021*da58b97aSjoerg       return false;
2022*da58b97aSjoerg   }
2023*da58b97aSjoerg 
202406f32e7eSjoerg   return true;
202506f32e7eSjoerg }
202606f32e7eSjoerg 
202706f32e7eSjoerg // On Mach-O platforms, we emit global metadata in a separate section of the
202806f32e7eSjoerg // binary in order to allow the linker to properly dead strip. This is only
202906f32e7eSjoerg // supported on recent versions of ld64.
ShouldUseMachOGlobalsSection() const203006f32e7eSjoerg bool ModuleAddressSanitizer::ShouldUseMachOGlobalsSection() const {
203106f32e7eSjoerg   if (!TargetTriple.isOSBinFormatMachO())
203206f32e7eSjoerg     return false;
203306f32e7eSjoerg 
203406f32e7eSjoerg   if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
203506f32e7eSjoerg     return true;
203606f32e7eSjoerg   if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
203706f32e7eSjoerg     return true;
203806f32e7eSjoerg   if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
203906f32e7eSjoerg     return true;
204006f32e7eSjoerg 
204106f32e7eSjoerg   return false;
204206f32e7eSjoerg }
204306f32e7eSjoerg 
getGlobalMetadataSection() const204406f32e7eSjoerg StringRef ModuleAddressSanitizer::getGlobalMetadataSection() const {
204506f32e7eSjoerg   switch (TargetTriple.getObjectFormat()) {
204606f32e7eSjoerg   case Triple::COFF:  return ".ASAN$GL";
204706f32e7eSjoerg   case Triple::ELF:   return "asan_globals";
204806f32e7eSjoerg   case Triple::MachO: return "__DATA,__asan_globals,regular";
204906f32e7eSjoerg   case Triple::Wasm:
2050*da58b97aSjoerg   case Triple::GOFF:
205106f32e7eSjoerg   case Triple::XCOFF:
205206f32e7eSjoerg     report_fatal_error(
2053*da58b97aSjoerg         "ModuleAddressSanitizer not implemented for object file format");
205406f32e7eSjoerg   case Triple::UnknownObjectFormat:
205506f32e7eSjoerg     break;
205606f32e7eSjoerg   }
205706f32e7eSjoerg   llvm_unreachable("unsupported object format");
205806f32e7eSjoerg }
205906f32e7eSjoerg 
initializeCallbacks(Module & M)206006f32e7eSjoerg void ModuleAddressSanitizer::initializeCallbacks(Module &M) {
206106f32e7eSjoerg   IRBuilder<> IRB(*C);
206206f32e7eSjoerg 
206306f32e7eSjoerg   // Declare our poisoning and unpoisoning functions.
206406f32e7eSjoerg   AsanPoisonGlobals =
206506f32e7eSjoerg       M.getOrInsertFunction(kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy);
206606f32e7eSjoerg   AsanUnpoisonGlobals =
206706f32e7eSjoerg       M.getOrInsertFunction(kAsanUnpoisonGlobalsName, IRB.getVoidTy());
206806f32e7eSjoerg 
206906f32e7eSjoerg   // Declare functions that register/unregister globals.
207006f32e7eSjoerg   AsanRegisterGlobals = M.getOrInsertFunction(
207106f32e7eSjoerg       kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy);
207206f32e7eSjoerg   AsanUnregisterGlobals = M.getOrInsertFunction(
207306f32e7eSjoerg       kAsanUnregisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy);
207406f32e7eSjoerg 
207506f32e7eSjoerg   // Declare the functions that find globals in a shared object and then invoke
207606f32e7eSjoerg   // the (un)register function on them.
207706f32e7eSjoerg   AsanRegisterImageGlobals = M.getOrInsertFunction(
207806f32e7eSjoerg       kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy);
207906f32e7eSjoerg   AsanUnregisterImageGlobals = M.getOrInsertFunction(
208006f32e7eSjoerg       kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy);
208106f32e7eSjoerg 
208206f32e7eSjoerg   AsanRegisterElfGlobals =
208306f32e7eSjoerg       M.getOrInsertFunction(kAsanRegisterElfGlobalsName, IRB.getVoidTy(),
208406f32e7eSjoerg                             IntptrTy, IntptrTy, IntptrTy);
208506f32e7eSjoerg   AsanUnregisterElfGlobals =
208606f32e7eSjoerg       M.getOrInsertFunction(kAsanUnregisterElfGlobalsName, IRB.getVoidTy(),
208706f32e7eSjoerg                             IntptrTy, IntptrTy, IntptrTy);
208806f32e7eSjoerg }
208906f32e7eSjoerg 
209006f32e7eSjoerg // Put the metadata and the instrumented global in the same group. This ensures
209106f32e7eSjoerg // that the metadata is discarded if the instrumented global is discarded.
SetComdatForGlobalMetadata(GlobalVariable * G,GlobalVariable * Metadata,StringRef InternalSuffix)209206f32e7eSjoerg void ModuleAddressSanitizer::SetComdatForGlobalMetadata(
209306f32e7eSjoerg     GlobalVariable *G, GlobalVariable *Metadata, StringRef InternalSuffix) {
209406f32e7eSjoerg   Module &M = *G->getParent();
209506f32e7eSjoerg   Comdat *C = G->getComdat();
209606f32e7eSjoerg   if (!C) {
209706f32e7eSjoerg     if (!G->hasName()) {
209806f32e7eSjoerg       // If G is unnamed, it must be internal. Give it an artificial name
209906f32e7eSjoerg       // so we can put it in a comdat.
210006f32e7eSjoerg       assert(G->hasLocalLinkage());
210106f32e7eSjoerg       G->setName(Twine(kAsanGenPrefix) + "_anon_global");
210206f32e7eSjoerg     }
210306f32e7eSjoerg 
210406f32e7eSjoerg     if (!InternalSuffix.empty() && G->hasLocalLinkage()) {
2105*da58b97aSjoerg       std::string Name = std::string(G->getName());
210606f32e7eSjoerg       Name += InternalSuffix;
210706f32e7eSjoerg       C = M.getOrInsertComdat(Name);
210806f32e7eSjoerg     } else {
210906f32e7eSjoerg       C = M.getOrInsertComdat(G->getName());
211006f32e7eSjoerg     }
211106f32e7eSjoerg 
211206f32e7eSjoerg     // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF. Also upgrade private
211306f32e7eSjoerg     // linkage to internal linkage so that a symbol table entry is emitted. This
211406f32e7eSjoerg     // is necessary in order to create the comdat group.
211506f32e7eSjoerg     if (TargetTriple.isOSBinFormatCOFF()) {
211606f32e7eSjoerg       C->setSelectionKind(Comdat::NoDuplicates);
211706f32e7eSjoerg       if (G->hasPrivateLinkage())
211806f32e7eSjoerg         G->setLinkage(GlobalValue::InternalLinkage);
211906f32e7eSjoerg     }
212006f32e7eSjoerg     G->setComdat(C);
212106f32e7eSjoerg   }
212206f32e7eSjoerg 
212306f32e7eSjoerg   assert(G->hasComdat());
212406f32e7eSjoerg   Metadata->setComdat(G->getComdat());
212506f32e7eSjoerg }
212606f32e7eSjoerg 
212706f32e7eSjoerg // Create a separate metadata global and put it in the appropriate ASan
212806f32e7eSjoerg // global registration section.
212906f32e7eSjoerg GlobalVariable *
CreateMetadataGlobal(Module & M,Constant * Initializer,StringRef OriginalName)213006f32e7eSjoerg ModuleAddressSanitizer::CreateMetadataGlobal(Module &M, Constant *Initializer,
213106f32e7eSjoerg                                              StringRef OriginalName) {
213206f32e7eSjoerg   auto Linkage = TargetTriple.isOSBinFormatMachO()
213306f32e7eSjoerg                      ? GlobalVariable::InternalLinkage
213406f32e7eSjoerg                      : GlobalVariable::PrivateLinkage;
213506f32e7eSjoerg   GlobalVariable *Metadata = new GlobalVariable(
213606f32e7eSjoerg       M, Initializer->getType(), false, Linkage, Initializer,
213706f32e7eSjoerg       Twine("__asan_global_") + GlobalValue::dropLLVMManglingEscape(OriginalName));
213806f32e7eSjoerg   Metadata->setSection(getGlobalMetadataSection());
213906f32e7eSjoerg   return Metadata;
214006f32e7eSjoerg }
214106f32e7eSjoerg 
CreateAsanModuleDtor(Module & M)2142*da58b97aSjoerg Instruction *ModuleAddressSanitizer::CreateAsanModuleDtor(Module &M) {
2143*da58b97aSjoerg   AsanDtorFunction = Function::createWithDefaultAttr(
2144*da58b97aSjoerg       FunctionType::get(Type::getVoidTy(*C), false),
2145*da58b97aSjoerg       GlobalValue::InternalLinkage, 0, kAsanModuleDtorName, &M);
2146*da58b97aSjoerg   AsanDtorFunction->addAttribute(AttributeList::FunctionIndex,
2147*da58b97aSjoerg                                  Attribute::NoUnwind);
214806f32e7eSjoerg   BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
214906f32e7eSjoerg 
2150*da58b97aSjoerg   return ReturnInst::Create(*C, AsanDtorBB);
215106f32e7eSjoerg }
215206f32e7eSjoerg 
InstrumentGlobalsCOFF(IRBuilder<> & IRB,Module & M,ArrayRef<GlobalVariable * > ExtendedGlobals,ArrayRef<Constant * > MetadataInitializers)215306f32e7eSjoerg void ModuleAddressSanitizer::InstrumentGlobalsCOFF(
215406f32e7eSjoerg     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
215506f32e7eSjoerg     ArrayRef<Constant *> MetadataInitializers) {
215606f32e7eSjoerg   assert(ExtendedGlobals.size() == MetadataInitializers.size());
215706f32e7eSjoerg   auto &DL = M.getDataLayout();
215806f32e7eSjoerg 
2159*da58b97aSjoerg   SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
216006f32e7eSjoerg   for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
216106f32e7eSjoerg     Constant *Initializer = MetadataInitializers[i];
216206f32e7eSjoerg     GlobalVariable *G = ExtendedGlobals[i];
216306f32e7eSjoerg     GlobalVariable *Metadata =
216406f32e7eSjoerg         CreateMetadataGlobal(M, Initializer, G->getName());
2165*da58b97aSjoerg     MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
2166*da58b97aSjoerg     Metadata->setMetadata(LLVMContext::MD_associated, MD);
2167*da58b97aSjoerg     MetadataGlobals[i] = Metadata;
216806f32e7eSjoerg 
216906f32e7eSjoerg     // The MSVC linker always inserts padding when linking incrementally. We
217006f32e7eSjoerg     // cope with that by aligning each struct to its size, which must be a power
217106f32e7eSjoerg     // of two.
217206f32e7eSjoerg     unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
217306f32e7eSjoerg     assert(isPowerOf2_32(SizeOfGlobalStruct) &&
217406f32e7eSjoerg            "global metadata will not be padded appropriately");
217506f32e7eSjoerg     Metadata->setAlignment(assumeAligned(SizeOfGlobalStruct));
217606f32e7eSjoerg 
217706f32e7eSjoerg     SetComdatForGlobalMetadata(G, Metadata, "");
217806f32e7eSjoerg   }
2179*da58b97aSjoerg 
2180*da58b97aSjoerg   // Update llvm.compiler.used, adding the new metadata globals. This is
2181*da58b97aSjoerg   // needed so that during LTO these variables stay alive.
2182*da58b97aSjoerg   if (!MetadataGlobals.empty())
2183*da58b97aSjoerg     appendToCompilerUsed(M, MetadataGlobals);
218406f32e7eSjoerg }
218506f32e7eSjoerg 
InstrumentGlobalsELF(IRBuilder<> & IRB,Module & M,ArrayRef<GlobalVariable * > ExtendedGlobals,ArrayRef<Constant * > MetadataInitializers,const std::string & UniqueModuleId)218606f32e7eSjoerg void ModuleAddressSanitizer::InstrumentGlobalsELF(
218706f32e7eSjoerg     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
218806f32e7eSjoerg     ArrayRef<Constant *> MetadataInitializers,
218906f32e7eSjoerg     const std::string &UniqueModuleId) {
219006f32e7eSjoerg   assert(ExtendedGlobals.size() == MetadataInitializers.size());
219106f32e7eSjoerg 
2192*da58b97aSjoerg   // Putting globals in a comdat changes the semantic and potentially cause
2193*da58b97aSjoerg   // false negative odr violations at link time. If odr indicators are used, we
2194*da58b97aSjoerg   // keep the comdat sections, as link time odr violations will be dectected on
2195*da58b97aSjoerg   // the odr indicator symbols.
2196*da58b97aSjoerg   bool UseComdatForGlobalsGC = UseOdrIndicator;
2197*da58b97aSjoerg 
219806f32e7eSjoerg   SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
219906f32e7eSjoerg   for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
220006f32e7eSjoerg     GlobalVariable *G = ExtendedGlobals[i];
220106f32e7eSjoerg     GlobalVariable *Metadata =
220206f32e7eSjoerg         CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());
220306f32e7eSjoerg     MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
220406f32e7eSjoerg     Metadata->setMetadata(LLVMContext::MD_associated, MD);
220506f32e7eSjoerg     MetadataGlobals[i] = Metadata;
220606f32e7eSjoerg 
2207*da58b97aSjoerg     if (UseComdatForGlobalsGC)
220806f32e7eSjoerg       SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
220906f32e7eSjoerg   }
221006f32e7eSjoerg 
221106f32e7eSjoerg   // Update llvm.compiler.used, adding the new metadata globals. This is
221206f32e7eSjoerg   // needed so that during LTO these variables stay alive.
221306f32e7eSjoerg   if (!MetadataGlobals.empty())
221406f32e7eSjoerg     appendToCompilerUsed(M, MetadataGlobals);
221506f32e7eSjoerg 
221606f32e7eSjoerg   // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
221706f32e7eSjoerg   // to look up the loaded image that contains it. Second, we can store in it
221806f32e7eSjoerg   // whether registration has already occurred, to prevent duplicate
221906f32e7eSjoerg   // registration.
222006f32e7eSjoerg   //
222106f32e7eSjoerg   // Common linkage ensures that there is only one global per shared library.
222206f32e7eSjoerg   GlobalVariable *RegisteredFlag = new GlobalVariable(
222306f32e7eSjoerg       M, IntptrTy, false, GlobalVariable::CommonLinkage,
222406f32e7eSjoerg       ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
222506f32e7eSjoerg   RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
222606f32e7eSjoerg 
222706f32e7eSjoerg   // Create start and stop symbols.
222806f32e7eSjoerg   GlobalVariable *StartELFMetadata = new GlobalVariable(
222906f32e7eSjoerg       M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
223006f32e7eSjoerg       "__start_" + getGlobalMetadataSection());
223106f32e7eSjoerg   StartELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
223206f32e7eSjoerg   GlobalVariable *StopELFMetadata = new GlobalVariable(
223306f32e7eSjoerg       M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
223406f32e7eSjoerg       "__stop_" + getGlobalMetadataSection());
223506f32e7eSjoerg   StopELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
223606f32e7eSjoerg 
223706f32e7eSjoerg   // Create a call to register the globals with the runtime.
223806f32e7eSjoerg   IRB.CreateCall(AsanRegisterElfGlobals,
223906f32e7eSjoerg                  {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
224006f32e7eSjoerg                   IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
224106f32e7eSjoerg                   IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
224206f32e7eSjoerg 
224306f32e7eSjoerg   // We also need to unregister globals at the end, e.g., when a shared library
224406f32e7eSjoerg   // gets closed.
2245*da58b97aSjoerg   if (DestructorKind != AsanDtorKind::None) {
2246*da58b97aSjoerg     IRBuilder<> IrbDtor(CreateAsanModuleDtor(M));
2247*da58b97aSjoerg     IrbDtor.CreateCall(AsanUnregisterElfGlobals,
224806f32e7eSjoerg                        {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
224906f32e7eSjoerg                         IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
225006f32e7eSjoerg                         IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
225106f32e7eSjoerg   }
2252*da58b97aSjoerg }
225306f32e7eSjoerg 
InstrumentGlobalsMachO(IRBuilder<> & IRB,Module & M,ArrayRef<GlobalVariable * > ExtendedGlobals,ArrayRef<Constant * > MetadataInitializers)225406f32e7eSjoerg void ModuleAddressSanitizer::InstrumentGlobalsMachO(
225506f32e7eSjoerg     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
225606f32e7eSjoerg     ArrayRef<Constant *> MetadataInitializers) {
225706f32e7eSjoerg   assert(ExtendedGlobals.size() == MetadataInitializers.size());
225806f32e7eSjoerg 
225906f32e7eSjoerg   // On recent Mach-O platforms, use a structure which binds the liveness of
226006f32e7eSjoerg   // the global variable to the metadata struct. Keep the list of "Liveness" GV
226106f32e7eSjoerg   // created to be added to llvm.compiler.used
226206f32e7eSjoerg   StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy);
226306f32e7eSjoerg   SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
226406f32e7eSjoerg 
226506f32e7eSjoerg   for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
226606f32e7eSjoerg     Constant *Initializer = MetadataInitializers[i];
226706f32e7eSjoerg     GlobalVariable *G = ExtendedGlobals[i];
226806f32e7eSjoerg     GlobalVariable *Metadata =
226906f32e7eSjoerg         CreateMetadataGlobal(M, Initializer, G->getName());
227006f32e7eSjoerg 
227106f32e7eSjoerg     // On recent Mach-O platforms, we emit the global metadata in a way that
227206f32e7eSjoerg     // allows the linker to properly strip dead globals.
227306f32e7eSjoerg     auto LivenessBinder =
227406f32e7eSjoerg         ConstantStruct::get(LivenessTy, Initializer->getAggregateElement(0u),
227506f32e7eSjoerg                             ConstantExpr::getPointerCast(Metadata, IntptrTy));
227606f32e7eSjoerg     GlobalVariable *Liveness = new GlobalVariable(
227706f32e7eSjoerg         M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
227806f32e7eSjoerg         Twine("__asan_binder_") + G->getName());
227906f32e7eSjoerg     Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
228006f32e7eSjoerg     LivenessGlobals[i] = Liveness;
228106f32e7eSjoerg   }
228206f32e7eSjoerg 
228306f32e7eSjoerg   // Update llvm.compiler.used, adding the new liveness globals. This is
228406f32e7eSjoerg   // needed so that during LTO these variables stay alive. The alternative
228506f32e7eSjoerg   // would be to have the linker handling the LTO symbols, but libLTO
228606f32e7eSjoerg   // current API does not expose access to the section for each symbol.
228706f32e7eSjoerg   if (!LivenessGlobals.empty())
228806f32e7eSjoerg     appendToCompilerUsed(M, LivenessGlobals);
228906f32e7eSjoerg 
229006f32e7eSjoerg   // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
229106f32e7eSjoerg   // to look up the loaded image that contains it. Second, we can store in it
229206f32e7eSjoerg   // whether registration has already occurred, to prevent duplicate
229306f32e7eSjoerg   // registration.
229406f32e7eSjoerg   //
229506f32e7eSjoerg   // common linkage ensures that there is only one global per shared library.
229606f32e7eSjoerg   GlobalVariable *RegisteredFlag = new GlobalVariable(
229706f32e7eSjoerg       M, IntptrTy, false, GlobalVariable::CommonLinkage,
229806f32e7eSjoerg       ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
229906f32e7eSjoerg   RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
230006f32e7eSjoerg 
230106f32e7eSjoerg   IRB.CreateCall(AsanRegisterImageGlobals,
230206f32e7eSjoerg                  {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
230306f32e7eSjoerg 
230406f32e7eSjoerg   // We also need to unregister globals at the end, e.g., when a shared library
230506f32e7eSjoerg   // gets closed.
2306*da58b97aSjoerg   if (DestructorKind != AsanDtorKind::None) {
2307*da58b97aSjoerg     IRBuilder<> IrbDtor(CreateAsanModuleDtor(M));
2308*da58b97aSjoerg     IrbDtor.CreateCall(AsanUnregisterImageGlobals,
230906f32e7eSjoerg                        {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
231006f32e7eSjoerg   }
2311*da58b97aSjoerg }
231206f32e7eSjoerg 
InstrumentGlobalsWithMetadataArray(IRBuilder<> & IRB,Module & M,ArrayRef<GlobalVariable * > ExtendedGlobals,ArrayRef<Constant * > MetadataInitializers)231306f32e7eSjoerg void ModuleAddressSanitizer::InstrumentGlobalsWithMetadataArray(
231406f32e7eSjoerg     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
231506f32e7eSjoerg     ArrayRef<Constant *> MetadataInitializers) {
231606f32e7eSjoerg   assert(ExtendedGlobals.size() == MetadataInitializers.size());
231706f32e7eSjoerg   unsigned N = ExtendedGlobals.size();
231806f32e7eSjoerg   assert(N > 0);
231906f32e7eSjoerg 
232006f32e7eSjoerg   // On platforms that don't have a custom metadata section, we emit an array
232106f32e7eSjoerg   // of global metadata structures.
232206f32e7eSjoerg   ArrayType *ArrayOfGlobalStructTy =
232306f32e7eSjoerg       ArrayType::get(MetadataInitializers[0]->getType(), N);
232406f32e7eSjoerg   auto AllGlobals = new GlobalVariable(
232506f32e7eSjoerg       M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
232606f32e7eSjoerg       ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
232706f32e7eSjoerg   if (Mapping.Scale > 3)
232806f32e7eSjoerg     AllGlobals->setAlignment(Align(1ULL << Mapping.Scale));
232906f32e7eSjoerg 
233006f32e7eSjoerg   IRB.CreateCall(AsanRegisterGlobals,
233106f32e7eSjoerg                  {IRB.CreatePointerCast(AllGlobals, IntptrTy),
233206f32e7eSjoerg                   ConstantInt::get(IntptrTy, N)});
233306f32e7eSjoerg 
233406f32e7eSjoerg   // We also need to unregister globals at the end, e.g., when a shared library
233506f32e7eSjoerg   // gets closed.
2336*da58b97aSjoerg   if (DestructorKind != AsanDtorKind::None) {
2337*da58b97aSjoerg     IRBuilder<> IrbDtor(CreateAsanModuleDtor(M));
2338*da58b97aSjoerg     IrbDtor.CreateCall(AsanUnregisterGlobals,
233906f32e7eSjoerg                        {IRB.CreatePointerCast(AllGlobals, IntptrTy),
234006f32e7eSjoerg                         ConstantInt::get(IntptrTy, N)});
234106f32e7eSjoerg   }
2342*da58b97aSjoerg }
234306f32e7eSjoerg 
234406f32e7eSjoerg // This function replaces all global variables with new variables that have
234506f32e7eSjoerg // trailing redzones. It also creates a function that poisons
234606f32e7eSjoerg // redzones and inserts this function into llvm.global_ctors.
234706f32e7eSjoerg // Sets *CtorComdat to true if the global registration code emitted into the
234806f32e7eSjoerg // asan constructor is comdat-compatible.
InstrumentGlobals(IRBuilder<> & IRB,Module & M,bool * CtorComdat)234906f32e7eSjoerg bool ModuleAddressSanitizer::InstrumentGlobals(IRBuilder<> &IRB, Module &M,
235006f32e7eSjoerg                                                bool *CtorComdat) {
235106f32e7eSjoerg   *CtorComdat = false;
235206f32e7eSjoerg 
2353*da58b97aSjoerg   // Build set of globals that are aliased by some GA, where
2354*da58b97aSjoerg   // getExcludedAliasedGlobal(GA) returns the relevant GlobalVariable.
2355*da58b97aSjoerg   SmallPtrSet<const GlobalVariable *, 16> AliasedGlobalExclusions;
2356*da58b97aSjoerg   if (CompileKernel) {
2357*da58b97aSjoerg     for (auto &GA : M.aliases()) {
2358*da58b97aSjoerg       if (const GlobalVariable *GV = getExcludedAliasedGlobal(GA))
2359*da58b97aSjoerg         AliasedGlobalExclusions.insert(GV);
2360*da58b97aSjoerg     }
2361*da58b97aSjoerg   }
236206f32e7eSjoerg 
2363*da58b97aSjoerg   SmallVector<GlobalVariable *, 16> GlobalsToChange;
236406f32e7eSjoerg   for (auto &G : M.globals()) {
2365*da58b97aSjoerg     if (!AliasedGlobalExclusions.count(&G) && shouldInstrumentGlobal(&G))
2366*da58b97aSjoerg       GlobalsToChange.push_back(&G);
236706f32e7eSjoerg   }
236806f32e7eSjoerg 
236906f32e7eSjoerg   size_t n = GlobalsToChange.size();
237006f32e7eSjoerg   if (n == 0) {
237106f32e7eSjoerg     *CtorComdat = true;
237206f32e7eSjoerg     return false;
237306f32e7eSjoerg   }
237406f32e7eSjoerg 
237506f32e7eSjoerg   auto &DL = M.getDataLayout();
237606f32e7eSjoerg 
237706f32e7eSjoerg   // A global is described by a structure
237806f32e7eSjoerg   //   size_t beg;
237906f32e7eSjoerg   //   size_t size;
238006f32e7eSjoerg   //   size_t size_with_redzone;
238106f32e7eSjoerg   //   const char *name;
238206f32e7eSjoerg   //   const char *module_name;
238306f32e7eSjoerg   //   size_t has_dynamic_init;
238406f32e7eSjoerg   //   void *source_location;
238506f32e7eSjoerg   //   size_t odr_indicator;
238606f32e7eSjoerg   // We initialize an array of such structures and pass it to a run-time call.
238706f32e7eSjoerg   StructType *GlobalStructTy =
238806f32e7eSjoerg       StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
238906f32e7eSjoerg                       IntptrTy, IntptrTy, IntptrTy);
239006f32e7eSjoerg   SmallVector<GlobalVariable *, 16> NewGlobals(n);
239106f32e7eSjoerg   SmallVector<Constant *, 16> Initializers(n);
239206f32e7eSjoerg 
239306f32e7eSjoerg   bool HasDynamicallyInitializedGlobals = false;
239406f32e7eSjoerg 
239506f32e7eSjoerg   // We shouldn't merge same module names, as this string serves as unique
239606f32e7eSjoerg   // module ID in runtime.
239706f32e7eSjoerg   GlobalVariable *ModuleName = createPrivateGlobalForString(
239806f32e7eSjoerg       M, M.getModuleIdentifier(), /*AllowMerging*/ false, kAsanGenPrefix);
239906f32e7eSjoerg 
240006f32e7eSjoerg   for (size_t i = 0; i < n; i++) {
240106f32e7eSjoerg     GlobalVariable *G = GlobalsToChange[i];
240206f32e7eSjoerg 
240306f32e7eSjoerg     // FIXME: Metadata should be attched directly to the global directly instead
240406f32e7eSjoerg     // of being added to llvm.asan.globals.
240506f32e7eSjoerg     auto MD = GlobalsMD.get(G);
240606f32e7eSjoerg     StringRef NameForGlobal = G->getName();
240706f32e7eSjoerg     // Create string holding the global name (use global name from metadata
240806f32e7eSjoerg     // if it's available, otherwise just write the name of global variable).
240906f32e7eSjoerg     GlobalVariable *Name = createPrivateGlobalForString(
241006f32e7eSjoerg         M, MD.Name.empty() ? NameForGlobal : MD.Name,
241106f32e7eSjoerg         /*AllowMerging*/ true, kAsanGenPrefix);
241206f32e7eSjoerg 
241306f32e7eSjoerg     Type *Ty = G->getValueType();
2414*da58b97aSjoerg     const uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
2415*da58b97aSjoerg     const uint64_t RightRedzoneSize = getRedzoneSizeForGlobal(SizeInBytes);
241606f32e7eSjoerg     Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
241706f32e7eSjoerg 
241806f32e7eSjoerg     StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
241906f32e7eSjoerg     Constant *NewInitializer = ConstantStruct::get(
242006f32e7eSjoerg         NewTy, G->getInitializer(), Constant::getNullValue(RightRedZoneTy));
242106f32e7eSjoerg 
242206f32e7eSjoerg     // Create a new global variable with enough space for a redzone.
242306f32e7eSjoerg     GlobalValue::LinkageTypes Linkage = G->getLinkage();
242406f32e7eSjoerg     if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
242506f32e7eSjoerg       Linkage = GlobalValue::InternalLinkage;
2426*da58b97aSjoerg     GlobalVariable *NewGlobal = new GlobalVariable(
2427*da58b97aSjoerg         M, NewTy, G->isConstant(), Linkage, NewInitializer, "", G,
2428*da58b97aSjoerg         G->getThreadLocalMode(), G->getAddressSpace());
242906f32e7eSjoerg     NewGlobal->copyAttributesFrom(G);
243006f32e7eSjoerg     NewGlobal->setComdat(G->getComdat());
2431*da58b97aSjoerg     NewGlobal->setAlignment(MaybeAlign(getMinRedzoneSizeForGlobal()));
243206f32e7eSjoerg     // Don't fold globals with redzones. ODR violation detector and redzone
243306f32e7eSjoerg     // poisoning implicitly creates a dependence on the global's address, so it
243406f32e7eSjoerg     // is no longer valid for it to be marked unnamed_addr.
243506f32e7eSjoerg     NewGlobal->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
243606f32e7eSjoerg 
243706f32e7eSjoerg     // Move null-terminated C strings to "__asan_cstring" section on Darwin.
243806f32e7eSjoerg     if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
243906f32e7eSjoerg         G->isConstant()) {
244006f32e7eSjoerg       auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
244106f32e7eSjoerg       if (Seq && Seq->isCString())
244206f32e7eSjoerg         NewGlobal->setSection("__TEXT,__asan_cstring,regular");
244306f32e7eSjoerg     }
244406f32e7eSjoerg 
2445*da58b97aSjoerg     // Transfer the debug info and type metadata.  The payload starts at offset
2446*da58b97aSjoerg     // zero so we can copy the metadata over as is.
2447*da58b97aSjoerg     NewGlobal->copyMetadata(G, 0);
244806f32e7eSjoerg 
244906f32e7eSjoerg     Value *Indices2[2];
245006f32e7eSjoerg     Indices2[0] = IRB.getInt32(0);
245106f32e7eSjoerg     Indices2[1] = IRB.getInt32(0);
245206f32e7eSjoerg 
245306f32e7eSjoerg     G->replaceAllUsesWith(
245406f32e7eSjoerg         ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
245506f32e7eSjoerg     NewGlobal->takeName(G);
245606f32e7eSjoerg     G->eraseFromParent();
245706f32e7eSjoerg     NewGlobals[i] = NewGlobal;
245806f32e7eSjoerg 
245906f32e7eSjoerg     Constant *SourceLoc;
246006f32e7eSjoerg     if (!MD.SourceLoc.empty()) {
246106f32e7eSjoerg       auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
246206f32e7eSjoerg       SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
246306f32e7eSjoerg     } else {
246406f32e7eSjoerg       SourceLoc = ConstantInt::get(IntptrTy, 0);
246506f32e7eSjoerg     }
246606f32e7eSjoerg 
246706f32e7eSjoerg     Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
246806f32e7eSjoerg     GlobalValue *InstrumentedGlobal = NewGlobal;
246906f32e7eSjoerg 
247006f32e7eSjoerg     bool CanUsePrivateAliases =
247106f32e7eSjoerg         TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
247206f32e7eSjoerg         TargetTriple.isOSBinFormatWasm();
247306f32e7eSjoerg     if (CanUsePrivateAliases && UsePrivateAlias) {
247406f32e7eSjoerg       // Create local alias for NewGlobal to avoid crash on ODR between
247506f32e7eSjoerg       // instrumented and non-instrumented libraries.
247606f32e7eSjoerg       InstrumentedGlobal =
247706f32e7eSjoerg           GlobalAlias::create(GlobalValue::PrivateLinkage, "", NewGlobal);
247806f32e7eSjoerg     }
247906f32e7eSjoerg 
248006f32e7eSjoerg     // ODR should not happen for local linkage.
248106f32e7eSjoerg     if (NewGlobal->hasLocalLinkage()) {
248206f32e7eSjoerg       ODRIndicator = ConstantExpr::getIntToPtr(ConstantInt::get(IntptrTy, -1),
248306f32e7eSjoerg                                                IRB.getInt8PtrTy());
248406f32e7eSjoerg     } else if (UseOdrIndicator) {
248506f32e7eSjoerg       // With local aliases, we need to provide another externally visible
248606f32e7eSjoerg       // symbol __odr_asan_XXX to detect ODR violation.
248706f32e7eSjoerg       auto *ODRIndicatorSym =
248806f32e7eSjoerg           new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
248906f32e7eSjoerg                              Constant::getNullValue(IRB.getInt8Ty()),
249006f32e7eSjoerg                              kODRGenPrefix + NameForGlobal, nullptr,
249106f32e7eSjoerg                              NewGlobal->getThreadLocalMode());
249206f32e7eSjoerg 
249306f32e7eSjoerg       // Set meaningful attributes for indicator symbol.
249406f32e7eSjoerg       ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
249506f32e7eSjoerg       ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
2496*da58b97aSjoerg       ODRIndicatorSym->setAlignment(Align(1));
249706f32e7eSjoerg       ODRIndicator = ODRIndicatorSym;
249806f32e7eSjoerg     }
249906f32e7eSjoerg 
250006f32e7eSjoerg     Constant *Initializer = ConstantStruct::get(
250106f32e7eSjoerg         GlobalStructTy,
250206f32e7eSjoerg         ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
250306f32e7eSjoerg         ConstantInt::get(IntptrTy, SizeInBytes),
250406f32e7eSjoerg         ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
250506f32e7eSjoerg         ConstantExpr::getPointerCast(Name, IntptrTy),
250606f32e7eSjoerg         ConstantExpr::getPointerCast(ModuleName, IntptrTy),
250706f32e7eSjoerg         ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
250806f32e7eSjoerg         ConstantExpr::getPointerCast(ODRIndicator, IntptrTy));
250906f32e7eSjoerg 
251006f32e7eSjoerg     if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
251106f32e7eSjoerg 
251206f32e7eSjoerg     LLVM_DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
251306f32e7eSjoerg 
251406f32e7eSjoerg     Initializers[i] = Initializer;
251506f32e7eSjoerg   }
251606f32e7eSjoerg 
251706f32e7eSjoerg   // Add instrumented globals to llvm.compiler.used list to avoid LTO from
251806f32e7eSjoerg   // ConstantMerge'ing them.
251906f32e7eSjoerg   SmallVector<GlobalValue *, 16> GlobalsToAddToUsedList;
252006f32e7eSjoerg   for (size_t i = 0; i < n; i++) {
252106f32e7eSjoerg     GlobalVariable *G = NewGlobals[i];
252206f32e7eSjoerg     if (G->getName().empty()) continue;
252306f32e7eSjoerg     GlobalsToAddToUsedList.push_back(G);
252406f32e7eSjoerg   }
252506f32e7eSjoerg   appendToCompilerUsed(M, ArrayRef<GlobalValue *>(GlobalsToAddToUsedList));
252606f32e7eSjoerg 
252706f32e7eSjoerg   std::string ELFUniqueModuleId =
252806f32e7eSjoerg       (UseGlobalsGC && TargetTriple.isOSBinFormatELF()) ? getUniqueModuleId(&M)
252906f32e7eSjoerg                                                         : "";
253006f32e7eSjoerg 
253106f32e7eSjoerg   if (!ELFUniqueModuleId.empty()) {
253206f32e7eSjoerg     InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
253306f32e7eSjoerg     *CtorComdat = true;
253406f32e7eSjoerg   } else if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {
253506f32e7eSjoerg     InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
253606f32e7eSjoerg   } else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
253706f32e7eSjoerg     InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
253806f32e7eSjoerg   } else {
253906f32e7eSjoerg     InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
254006f32e7eSjoerg   }
254106f32e7eSjoerg 
254206f32e7eSjoerg   // Create calls for poisoning before initializers run and unpoisoning after.
254306f32e7eSjoerg   if (HasDynamicallyInitializedGlobals)
254406f32e7eSjoerg     createInitializerPoisonCalls(M, ModuleName);
254506f32e7eSjoerg 
254606f32e7eSjoerg   LLVM_DEBUG(dbgs() << M);
254706f32e7eSjoerg   return true;
254806f32e7eSjoerg }
254906f32e7eSjoerg 
2550*da58b97aSjoerg uint64_t
getRedzoneSizeForGlobal(uint64_t SizeInBytes) const2551*da58b97aSjoerg ModuleAddressSanitizer::getRedzoneSizeForGlobal(uint64_t SizeInBytes) const {
2552*da58b97aSjoerg   constexpr uint64_t kMaxRZ = 1 << 18;
2553*da58b97aSjoerg   const uint64_t MinRZ = getMinRedzoneSizeForGlobal();
2554*da58b97aSjoerg 
2555*da58b97aSjoerg   uint64_t RZ = 0;
2556*da58b97aSjoerg   if (SizeInBytes <= MinRZ / 2) {
2557*da58b97aSjoerg     // Reduce redzone size for small size objects, e.g. int, char[1]. MinRZ is
2558*da58b97aSjoerg     // at least 32 bytes, optimize when SizeInBytes is less than or equal to
2559*da58b97aSjoerg     // half of MinRZ.
2560*da58b97aSjoerg     RZ = MinRZ - SizeInBytes;
2561*da58b97aSjoerg   } else {
2562*da58b97aSjoerg     // Calculate RZ, where MinRZ <= RZ <= MaxRZ, and RZ ~ 1/4 * SizeInBytes.
2563*da58b97aSjoerg     RZ = std::max(MinRZ, std::min(kMaxRZ, (SizeInBytes / MinRZ / 4) * MinRZ));
2564*da58b97aSjoerg 
2565*da58b97aSjoerg     // Round up to multiple of MinRZ.
2566*da58b97aSjoerg     if (SizeInBytes % MinRZ)
2567*da58b97aSjoerg       RZ += MinRZ - (SizeInBytes % MinRZ);
2568*da58b97aSjoerg   }
2569*da58b97aSjoerg 
2570*da58b97aSjoerg   assert((RZ + SizeInBytes) % MinRZ == 0);
2571*da58b97aSjoerg 
2572*da58b97aSjoerg   return RZ;
2573*da58b97aSjoerg }
2574*da58b97aSjoerg 
GetAsanVersion(const Module & M) const257506f32e7eSjoerg int ModuleAddressSanitizer::GetAsanVersion(const Module &M) const {
257606f32e7eSjoerg   int LongSize = M.getDataLayout().getPointerSizeInBits();
257706f32e7eSjoerg   bool isAndroid = Triple(M.getTargetTriple()).isAndroid();
257806f32e7eSjoerg   int Version = 8;
257906f32e7eSjoerg   // 32-bit Android is one version ahead because of the switch to dynamic
258006f32e7eSjoerg   // shadow.
258106f32e7eSjoerg   Version += (LongSize == 32 && isAndroid);
258206f32e7eSjoerg   return Version;
258306f32e7eSjoerg }
258406f32e7eSjoerg 
instrumentModule(Module & M)258506f32e7eSjoerg bool ModuleAddressSanitizer::instrumentModule(Module &M) {
258606f32e7eSjoerg   initializeCallbacks(M);
258706f32e7eSjoerg 
258806f32e7eSjoerg   // Create a module constructor. A destructor is created lazily because not all
258906f32e7eSjoerg   // platforms, and not all modules need it.
2590*da58b97aSjoerg   if (CompileKernel) {
2591*da58b97aSjoerg     // The kernel always builds with its own runtime, and therefore does not
2592*da58b97aSjoerg     // need the init and version check calls.
2593*da58b97aSjoerg     AsanCtorFunction = createSanitizerCtor(M, kAsanModuleCtorName);
2594*da58b97aSjoerg   } else {
259506f32e7eSjoerg     std::string AsanVersion = std::to_string(GetAsanVersion(M));
259606f32e7eSjoerg     std::string VersionCheckName =
259706f32e7eSjoerg         ClInsertVersionCheck ? (kAsanVersionCheckNamePrefix + AsanVersion) : "";
2598*da58b97aSjoerg     std::tie(AsanCtorFunction, std::ignore) =
2599*da58b97aSjoerg         createSanitizerCtorAndInitFunctions(M, kAsanModuleCtorName,
2600*da58b97aSjoerg                                             kAsanInitName, /*InitArgTypes=*/{},
260106f32e7eSjoerg                                             /*InitArgs=*/{}, VersionCheckName);
2602*da58b97aSjoerg   }
260306f32e7eSjoerg 
260406f32e7eSjoerg   bool CtorComdat = true;
260506f32e7eSjoerg   if (ClGlobals) {
260606f32e7eSjoerg     IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
260706f32e7eSjoerg     InstrumentGlobals(IRB, M, &CtorComdat);
260806f32e7eSjoerg   }
260906f32e7eSjoerg 
261006f32e7eSjoerg   const uint64_t Priority = GetCtorAndDtorPriority(TargetTriple);
261106f32e7eSjoerg 
261206f32e7eSjoerg   // Put the constructor and destructor in comdat if both
261306f32e7eSjoerg   // (1) global instrumentation is not TU-specific
261406f32e7eSjoerg   // (2) target is ELF.
261506f32e7eSjoerg   if (UseCtorComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {
261606f32e7eSjoerg     AsanCtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleCtorName));
261706f32e7eSjoerg     appendToGlobalCtors(M, AsanCtorFunction, Priority, AsanCtorFunction);
261806f32e7eSjoerg     if (AsanDtorFunction) {
261906f32e7eSjoerg       AsanDtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleDtorName));
262006f32e7eSjoerg       appendToGlobalDtors(M, AsanDtorFunction, Priority, AsanDtorFunction);
262106f32e7eSjoerg     }
262206f32e7eSjoerg   } else {
262306f32e7eSjoerg     appendToGlobalCtors(M, AsanCtorFunction, Priority);
262406f32e7eSjoerg     if (AsanDtorFunction)
262506f32e7eSjoerg       appendToGlobalDtors(M, AsanDtorFunction, Priority);
262606f32e7eSjoerg   }
262706f32e7eSjoerg 
262806f32e7eSjoerg   return true;
262906f32e7eSjoerg }
263006f32e7eSjoerg 
initializeCallbacks(Module & M)263106f32e7eSjoerg void AddressSanitizer::initializeCallbacks(Module &M) {
263206f32e7eSjoerg   IRBuilder<> IRB(*C);
263306f32e7eSjoerg   // Create __asan_report* callbacks.
263406f32e7eSjoerg   // IsWrite, TypeSize and Exp are encoded in the function name.
263506f32e7eSjoerg   for (int Exp = 0; Exp < 2; Exp++) {
263606f32e7eSjoerg     for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
263706f32e7eSjoerg       const std::string TypeStr = AccessIsWrite ? "store" : "load";
263806f32e7eSjoerg       const std::string ExpStr = Exp ? "exp_" : "";
263906f32e7eSjoerg       const std::string EndingStr = Recover ? "_noabort" : "";
264006f32e7eSjoerg 
264106f32e7eSjoerg       SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};
264206f32e7eSjoerg       SmallVector<Type *, 2> Args1{1, IntptrTy};
264306f32e7eSjoerg       if (Exp) {
264406f32e7eSjoerg         Type *ExpType = Type::getInt32Ty(*C);
264506f32e7eSjoerg         Args2.push_back(ExpType);
264606f32e7eSjoerg         Args1.push_back(ExpType);
264706f32e7eSjoerg       }
264806f32e7eSjoerg       AsanErrorCallbackSized[AccessIsWrite][Exp] = M.getOrInsertFunction(
264906f32e7eSjoerg           kAsanReportErrorTemplate + ExpStr + TypeStr + "_n" + EndingStr,
265006f32e7eSjoerg           FunctionType::get(IRB.getVoidTy(), Args2, false));
265106f32e7eSjoerg 
265206f32e7eSjoerg       AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] = M.getOrInsertFunction(
265306f32e7eSjoerg           ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
265406f32e7eSjoerg           FunctionType::get(IRB.getVoidTy(), Args2, false));
265506f32e7eSjoerg 
265606f32e7eSjoerg       for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
265706f32e7eSjoerg            AccessSizeIndex++) {
265806f32e7eSjoerg         const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
265906f32e7eSjoerg         AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
266006f32e7eSjoerg             M.getOrInsertFunction(
266106f32e7eSjoerg                 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
266206f32e7eSjoerg                 FunctionType::get(IRB.getVoidTy(), Args1, false));
266306f32e7eSjoerg 
266406f32e7eSjoerg         AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
266506f32e7eSjoerg             M.getOrInsertFunction(
266606f32e7eSjoerg                 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
266706f32e7eSjoerg                 FunctionType::get(IRB.getVoidTy(), Args1, false));
266806f32e7eSjoerg       }
266906f32e7eSjoerg     }
267006f32e7eSjoerg   }
267106f32e7eSjoerg 
267206f32e7eSjoerg   const std::string MemIntrinCallbackPrefix =
267306f32e7eSjoerg       CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
267406f32e7eSjoerg   AsanMemmove = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memmove",
267506f32e7eSjoerg                                       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
267606f32e7eSjoerg                                       IRB.getInt8PtrTy(), IntptrTy);
267706f32e7eSjoerg   AsanMemcpy = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memcpy",
267806f32e7eSjoerg                                      IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
267906f32e7eSjoerg                                      IRB.getInt8PtrTy(), IntptrTy);
268006f32e7eSjoerg   AsanMemset = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memset",
268106f32e7eSjoerg                                      IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
268206f32e7eSjoerg                                      IRB.getInt32Ty(), IntptrTy);
268306f32e7eSjoerg 
268406f32e7eSjoerg   AsanHandleNoReturnFunc =
268506f32e7eSjoerg       M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy());
268606f32e7eSjoerg 
268706f32e7eSjoerg   AsanPtrCmpFunction =
268806f32e7eSjoerg       M.getOrInsertFunction(kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy);
268906f32e7eSjoerg   AsanPtrSubFunction =
269006f32e7eSjoerg       M.getOrInsertFunction(kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy);
269106f32e7eSjoerg   if (Mapping.InGlobal)
269206f32e7eSjoerg     AsanShadowGlobal = M.getOrInsertGlobal("__asan_shadow",
269306f32e7eSjoerg                                            ArrayType::get(IRB.getInt8Ty(), 0));
2694*da58b97aSjoerg 
2695*da58b97aSjoerg   AMDGPUAddressShared = M.getOrInsertFunction(
2696*da58b97aSjoerg       kAMDGPUAddressSharedName, IRB.getInt1Ty(), IRB.getInt8PtrTy());
2697*da58b97aSjoerg   AMDGPUAddressPrivate = M.getOrInsertFunction(
2698*da58b97aSjoerg       kAMDGPUAddressPrivateName, IRB.getInt1Ty(), IRB.getInt8PtrTy());
269906f32e7eSjoerg }
270006f32e7eSjoerg 
maybeInsertAsanInitAtFunctionEntry(Function & F)270106f32e7eSjoerg bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
270206f32e7eSjoerg   // For each NSObject descendant having a +load method, this method is invoked
270306f32e7eSjoerg   // by the ObjC runtime before any of the static constructors is called.
270406f32e7eSjoerg   // Therefore we need to instrument such methods with a call to __asan_init
270506f32e7eSjoerg   // at the beginning in order to initialize our runtime before any access to
270606f32e7eSjoerg   // the shadow memory.
270706f32e7eSjoerg   // We cannot just ignore these methods, because they may call other
270806f32e7eSjoerg   // instrumented functions.
270906f32e7eSjoerg   if (F.getName().find(" load]") != std::string::npos) {
271006f32e7eSjoerg     FunctionCallee AsanInitFunction =
271106f32e7eSjoerg         declareSanitizerInitFunction(*F.getParent(), kAsanInitName, {});
271206f32e7eSjoerg     IRBuilder<> IRB(&F.front(), F.front().begin());
271306f32e7eSjoerg     IRB.CreateCall(AsanInitFunction, {});
271406f32e7eSjoerg     return true;
271506f32e7eSjoerg   }
271606f32e7eSjoerg   return false;
271706f32e7eSjoerg }
271806f32e7eSjoerg 
maybeInsertDynamicShadowAtFunctionEntry(Function & F)2719*da58b97aSjoerg bool AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
272006f32e7eSjoerg   // Generate code only when dynamic addressing is needed.
272106f32e7eSjoerg   if (Mapping.Offset != kDynamicShadowSentinel)
2722*da58b97aSjoerg     return false;
272306f32e7eSjoerg 
272406f32e7eSjoerg   IRBuilder<> IRB(&F.front().front());
272506f32e7eSjoerg   if (Mapping.InGlobal) {
272606f32e7eSjoerg     if (ClWithIfuncSuppressRemat) {
272706f32e7eSjoerg       // An empty inline asm with input reg == output reg.
272806f32e7eSjoerg       // An opaque pointer-to-int cast, basically.
272906f32e7eSjoerg       InlineAsm *Asm = InlineAsm::get(
273006f32e7eSjoerg           FunctionType::get(IntptrTy, {AsanShadowGlobal->getType()}, false),
273106f32e7eSjoerg           StringRef(""), StringRef("=r,0"),
273206f32e7eSjoerg           /*hasSideEffects=*/false);
273306f32e7eSjoerg       LocalDynamicShadow =
273406f32e7eSjoerg           IRB.CreateCall(Asm, {AsanShadowGlobal}, ".asan.shadow");
273506f32e7eSjoerg     } else {
273606f32e7eSjoerg       LocalDynamicShadow =
273706f32e7eSjoerg           IRB.CreatePointerCast(AsanShadowGlobal, IntptrTy, ".asan.shadow");
273806f32e7eSjoerg     }
273906f32e7eSjoerg   } else {
274006f32e7eSjoerg     Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
274106f32e7eSjoerg         kAsanShadowMemoryDynamicAddress, IntptrTy);
274206f32e7eSjoerg     LocalDynamicShadow = IRB.CreateLoad(IntptrTy, GlobalDynamicAddress);
274306f32e7eSjoerg   }
2744*da58b97aSjoerg   return true;
274506f32e7eSjoerg }
274606f32e7eSjoerg 
markEscapedLocalAllocas(Function & F)274706f32e7eSjoerg void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
274806f32e7eSjoerg   // Find the one possible call to llvm.localescape and pre-mark allocas passed
274906f32e7eSjoerg   // to it as uninteresting. This assumes we haven't started processing allocas
275006f32e7eSjoerg   // yet. This check is done up front because iterating the use list in
275106f32e7eSjoerg   // isInterestingAlloca would be algorithmically slower.
275206f32e7eSjoerg   assert(ProcessedAllocas.empty() && "must process localescape before allocas");
275306f32e7eSjoerg 
275406f32e7eSjoerg   // Try to get the declaration of llvm.localescape. If it's not in the module,
275506f32e7eSjoerg   // we can exit early.
275606f32e7eSjoerg   if (!F.getParent()->getFunction("llvm.localescape")) return;
275706f32e7eSjoerg 
275806f32e7eSjoerg   // Look for a call to llvm.localescape call in the entry block. It can't be in
275906f32e7eSjoerg   // any other block.
276006f32e7eSjoerg   for (Instruction &I : F.getEntryBlock()) {
276106f32e7eSjoerg     IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
276206f32e7eSjoerg     if (II && II->getIntrinsicID() == Intrinsic::localescape) {
276306f32e7eSjoerg       // We found a call. Mark all the allocas passed in as uninteresting.
276406f32e7eSjoerg       for (Value *Arg : II->arg_operands()) {
276506f32e7eSjoerg         AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
276606f32e7eSjoerg         assert(AI && AI->isStaticAlloca() &&
276706f32e7eSjoerg                "non-static alloca arg to localescape");
276806f32e7eSjoerg         ProcessedAllocas[AI] = false;
276906f32e7eSjoerg       }
277006f32e7eSjoerg       break;
277106f32e7eSjoerg     }
277206f32e7eSjoerg   }
277306f32e7eSjoerg }
277406f32e7eSjoerg 
suppressInstrumentationSiteForDebug(int & Instrumented)2775*da58b97aSjoerg bool AddressSanitizer::suppressInstrumentationSiteForDebug(int &Instrumented) {
2776*da58b97aSjoerg   bool ShouldInstrument =
2777*da58b97aSjoerg       ClDebugMin < 0 || ClDebugMax < 0 ||
2778*da58b97aSjoerg       (Instrumented >= ClDebugMin && Instrumented <= ClDebugMax);
2779*da58b97aSjoerg   Instrumented++;
2780*da58b97aSjoerg   return !ShouldInstrument;
2781*da58b97aSjoerg }
2782*da58b97aSjoerg 
instrumentFunction(Function & F,const TargetLibraryInfo * TLI)278306f32e7eSjoerg bool AddressSanitizer::instrumentFunction(Function &F,
278406f32e7eSjoerg                                           const TargetLibraryInfo *TLI) {
278506f32e7eSjoerg   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
278606f32e7eSjoerg   if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
278706f32e7eSjoerg   if (F.getName().startswith("__asan_")) return false;
278806f32e7eSjoerg 
278906f32e7eSjoerg   bool FunctionModified = false;
279006f32e7eSjoerg 
279106f32e7eSjoerg   // If needed, insert __asan_init before checking for SanitizeAddress attr.
279206f32e7eSjoerg   // This function needs to be called even if the function body is not
279306f32e7eSjoerg   // instrumented.
279406f32e7eSjoerg   if (maybeInsertAsanInitAtFunctionEntry(F))
279506f32e7eSjoerg     FunctionModified = true;
279606f32e7eSjoerg 
279706f32e7eSjoerg   // Leave if the function doesn't need instrumentation.
279806f32e7eSjoerg   if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
279906f32e7eSjoerg 
280006f32e7eSjoerg   LLVM_DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
280106f32e7eSjoerg 
280206f32e7eSjoerg   initializeCallbacks(*F.getParent());
280306f32e7eSjoerg 
280406f32e7eSjoerg   FunctionStateRAII CleanupObj(this);
280506f32e7eSjoerg 
2806*da58b97aSjoerg   FunctionModified |= maybeInsertDynamicShadowAtFunctionEntry(F);
280706f32e7eSjoerg 
280806f32e7eSjoerg   // We can't instrument allocas used with llvm.localescape. Only static allocas
280906f32e7eSjoerg   // can be passed to that intrinsic.
281006f32e7eSjoerg   markEscapedLocalAllocas(F);
281106f32e7eSjoerg 
281206f32e7eSjoerg   // We want to instrument every address only once per basic block (unless there
281306f32e7eSjoerg   // are calls between uses).
281406f32e7eSjoerg   SmallPtrSet<Value *, 16> TempsToInstrument;
2815*da58b97aSjoerg   SmallVector<InterestingMemoryOperand, 16> OperandsToInstrument;
2816*da58b97aSjoerg   SmallVector<MemIntrinsic *, 16> IntrinToInstrument;
281706f32e7eSjoerg   SmallVector<Instruction *, 8> NoReturnCalls;
281806f32e7eSjoerg   SmallVector<BasicBlock *, 16> AllBlocks;
281906f32e7eSjoerg   SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
282006f32e7eSjoerg   int NumAllocas = 0;
282106f32e7eSjoerg 
282206f32e7eSjoerg   // Fill the set of memory operations to instrument.
282306f32e7eSjoerg   for (auto &BB : F) {
282406f32e7eSjoerg     AllBlocks.push_back(&BB);
282506f32e7eSjoerg     TempsToInstrument.clear();
282606f32e7eSjoerg     int NumInsnsPerBB = 0;
282706f32e7eSjoerg     for (auto &Inst : BB) {
282806f32e7eSjoerg       if (LooksLikeCodeInBug11395(&Inst)) return false;
2829*da58b97aSjoerg       SmallVector<InterestingMemoryOperand, 1> InterestingOperands;
2830*da58b97aSjoerg       getInterestingMemoryOperands(&Inst, InterestingOperands);
2831*da58b97aSjoerg 
2832*da58b97aSjoerg       if (!InterestingOperands.empty()) {
2833*da58b97aSjoerg         for (auto &Operand : InterestingOperands) {
283406f32e7eSjoerg           if (ClOpt && ClOptSameTemp) {
2835*da58b97aSjoerg             Value *Ptr = Operand.getPtr();
283606f32e7eSjoerg             // If we have a mask, skip instrumentation if we've already
283706f32e7eSjoerg             // instrumented the full object. But don't add to TempsToInstrument
283806f32e7eSjoerg             // because we might get another load/store with a different mask.
2839*da58b97aSjoerg             if (Operand.MaybeMask) {
2840*da58b97aSjoerg               if (TempsToInstrument.count(Ptr))
284106f32e7eSjoerg                 continue; // We've seen this (whole) temp in the current BB.
284206f32e7eSjoerg             } else {
2843*da58b97aSjoerg               if (!TempsToInstrument.insert(Ptr).second)
284406f32e7eSjoerg                 continue; // We've seen this temp in the current BB.
284506f32e7eSjoerg             }
284606f32e7eSjoerg           }
2847*da58b97aSjoerg           OperandsToInstrument.push_back(Operand);
2848*da58b97aSjoerg           NumInsnsPerBB++;
2849*da58b97aSjoerg         }
285006f32e7eSjoerg       } else if (((ClInvalidPointerPairs || ClInvalidPointerCmp) &&
285106f32e7eSjoerg                   isInterestingPointerComparison(&Inst)) ||
285206f32e7eSjoerg                  ((ClInvalidPointerPairs || ClInvalidPointerSub) &&
285306f32e7eSjoerg                   isInterestingPointerSubtraction(&Inst))) {
285406f32e7eSjoerg         PointerComparisonsOrSubtracts.push_back(&Inst);
2855*da58b97aSjoerg       } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&Inst)) {
285606f32e7eSjoerg         // ok, take it.
2857*da58b97aSjoerg         IntrinToInstrument.push_back(MI);
2858*da58b97aSjoerg         NumInsnsPerBB++;
285906f32e7eSjoerg       } else {
286006f32e7eSjoerg         if (isa<AllocaInst>(Inst)) NumAllocas++;
2861*da58b97aSjoerg         if (auto *CB = dyn_cast<CallBase>(&Inst)) {
286206f32e7eSjoerg           // A call inside BB.
286306f32e7eSjoerg           TempsToInstrument.clear();
2864*da58b97aSjoerg           if (CB->doesNotReturn() && !CB->hasMetadata("nosanitize"))
2865*da58b97aSjoerg             NoReturnCalls.push_back(CB);
286606f32e7eSjoerg         }
286706f32e7eSjoerg         if (CallInst *CI = dyn_cast<CallInst>(&Inst))
286806f32e7eSjoerg           maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
286906f32e7eSjoerg       }
287006f32e7eSjoerg       if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
287106f32e7eSjoerg     }
287206f32e7eSjoerg   }
287306f32e7eSjoerg 
2874*da58b97aSjoerg   bool UseCalls = (ClInstrumentationWithCallsThreshold >= 0 &&
2875*da58b97aSjoerg                    OperandsToInstrument.size() + IntrinToInstrument.size() >
2876*da58b97aSjoerg                        (unsigned)ClInstrumentationWithCallsThreshold);
287706f32e7eSjoerg   const DataLayout &DL = F.getParent()->getDataLayout();
287806f32e7eSjoerg   ObjectSizeOpts ObjSizeOpts;
287906f32e7eSjoerg   ObjSizeOpts.RoundToAlign = true;
288006f32e7eSjoerg   ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);
288106f32e7eSjoerg 
288206f32e7eSjoerg   // Instrument.
288306f32e7eSjoerg   int NumInstrumented = 0;
2884*da58b97aSjoerg   for (auto &Operand : OperandsToInstrument) {
2885*da58b97aSjoerg     if (!suppressInstrumentationSiteForDebug(NumInstrumented))
2886*da58b97aSjoerg       instrumentMop(ObjSizeVis, Operand, UseCalls,
288706f32e7eSjoerg                     F.getParent()->getDataLayout());
2888*da58b97aSjoerg     FunctionModified = true;
288906f32e7eSjoerg   }
2890*da58b97aSjoerg   for (auto Inst : IntrinToInstrument) {
2891*da58b97aSjoerg     if (!suppressInstrumentationSiteForDebug(NumInstrumented))
2892*da58b97aSjoerg       instrumentMemIntrinsic(Inst);
2893*da58b97aSjoerg     FunctionModified = true;
289406f32e7eSjoerg   }
289506f32e7eSjoerg 
289606f32e7eSjoerg   FunctionStackPoisoner FSP(F, *this);
289706f32e7eSjoerg   bool ChangedStack = FSP.runOnFunction();
289806f32e7eSjoerg 
289906f32e7eSjoerg   // We must unpoison the stack before NoReturn calls (throw, _exit, etc).
290006f32e7eSjoerg   // See e.g. https://github.com/google/sanitizers/issues/37
290106f32e7eSjoerg   for (auto CI : NoReturnCalls) {
290206f32e7eSjoerg     IRBuilder<> IRB(CI);
290306f32e7eSjoerg     IRB.CreateCall(AsanHandleNoReturnFunc, {});
290406f32e7eSjoerg   }
290506f32e7eSjoerg 
290606f32e7eSjoerg   for (auto Inst : PointerComparisonsOrSubtracts) {
290706f32e7eSjoerg     instrumentPointerComparisonOrSubtraction(Inst);
2908*da58b97aSjoerg     FunctionModified = true;
290906f32e7eSjoerg   }
291006f32e7eSjoerg 
2911*da58b97aSjoerg   if (ChangedStack || !NoReturnCalls.empty())
291206f32e7eSjoerg     FunctionModified = true;
291306f32e7eSjoerg 
291406f32e7eSjoerg   LLVM_DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
291506f32e7eSjoerg                     << F << "\n");
291606f32e7eSjoerg 
291706f32e7eSjoerg   return FunctionModified;
291806f32e7eSjoerg }
291906f32e7eSjoerg 
292006f32e7eSjoerg // Workaround for bug 11395: we don't want to instrument stack in functions
292106f32e7eSjoerg // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
292206f32e7eSjoerg // FIXME: remove once the bug 11395 is fixed.
LooksLikeCodeInBug11395(Instruction * I)292306f32e7eSjoerg bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
292406f32e7eSjoerg   if (LongSize != 32) return false;
292506f32e7eSjoerg   CallInst *CI = dyn_cast<CallInst>(I);
292606f32e7eSjoerg   if (!CI || !CI->isInlineAsm()) return false;
292706f32e7eSjoerg   if (CI->getNumArgOperands() <= 5) return false;
292806f32e7eSjoerg   // We have inline assembly with quite a few arguments.
292906f32e7eSjoerg   return true;
293006f32e7eSjoerg }
293106f32e7eSjoerg 
initializeCallbacks(Module & M)293206f32e7eSjoerg void FunctionStackPoisoner::initializeCallbacks(Module &M) {
293306f32e7eSjoerg   IRBuilder<> IRB(*C);
293406f32e7eSjoerg   for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
293506f32e7eSjoerg     std::string Suffix = itostr(i);
293606f32e7eSjoerg     AsanStackMallocFunc[i] = M.getOrInsertFunction(
293706f32e7eSjoerg         kAsanStackMallocNameTemplate + Suffix, IntptrTy, IntptrTy);
293806f32e7eSjoerg     AsanStackFreeFunc[i] =
293906f32e7eSjoerg         M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
294006f32e7eSjoerg                               IRB.getVoidTy(), IntptrTy, IntptrTy);
294106f32e7eSjoerg   }
294206f32e7eSjoerg   if (ASan.UseAfterScope) {
294306f32e7eSjoerg     AsanPoisonStackMemoryFunc = M.getOrInsertFunction(
294406f32e7eSjoerg         kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy);
294506f32e7eSjoerg     AsanUnpoisonStackMemoryFunc = M.getOrInsertFunction(
294606f32e7eSjoerg         kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy);
294706f32e7eSjoerg   }
294806f32e7eSjoerg 
294906f32e7eSjoerg   for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
295006f32e7eSjoerg     std::ostringstream Name;
295106f32e7eSjoerg     Name << kAsanSetShadowPrefix;
295206f32e7eSjoerg     Name << std::setw(2) << std::setfill('0') << std::hex << Val;
295306f32e7eSjoerg     AsanSetShadowFunc[Val] =
295406f32e7eSjoerg         M.getOrInsertFunction(Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy);
295506f32e7eSjoerg   }
295606f32e7eSjoerg 
295706f32e7eSjoerg   AsanAllocaPoisonFunc = M.getOrInsertFunction(
295806f32e7eSjoerg       kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy);
295906f32e7eSjoerg   AsanAllocasUnpoisonFunc = M.getOrInsertFunction(
296006f32e7eSjoerg       kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy);
296106f32e7eSjoerg }
296206f32e7eSjoerg 
copyToShadowInline(ArrayRef<uint8_t> ShadowMask,ArrayRef<uint8_t> ShadowBytes,size_t Begin,size_t End,IRBuilder<> & IRB,Value * ShadowBase)296306f32e7eSjoerg void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
296406f32e7eSjoerg                                                ArrayRef<uint8_t> ShadowBytes,
296506f32e7eSjoerg                                                size_t Begin, size_t End,
296606f32e7eSjoerg                                                IRBuilder<> &IRB,
296706f32e7eSjoerg                                                Value *ShadowBase) {
296806f32e7eSjoerg   if (Begin >= End)
296906f32e7eSjoerg     return;
297006f32e7eSjoerg 
297106f32e7eSjoerg   const size_t LargestStoreSizeInBytes =
297206f32e7eSjoerg       std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
297306f32e7eSjoerg 
297406f32e7eSjoerg   const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
297506f32e7eSjoerg 
297606f32e7eSjoerg   // Poison given range in shadow using larges store size with out leading and
297706f32e7eSjoerg   // trailing zeros in ShadowMask. Zeros never change, so they need neither
297806f32e7eSjoerg   // poisoning nor up-poisoning. Still we don't mind if some of them get into a
297906f32e7eSjoerg   // middle of a store.
298006f32e7eSjoerg   for (size_t i = Begin; i < End;) {
298106f32e7eSjoerg     if (!ShadowMask[i]) {
298206f32e7eSjoerg       assert(!ShadowBytes[i]);
298306f32e7eSjoerg       ++i;
298406f32e7eSjoerg       continue;
298506f32e7eSjoerg     }
298606f32e7eSjoerg 
298706f32e7eSjoerg     size_t StoreSizeInBytes = LargestStoreSizeInBytes;
298806f32e7eSjoerg     // Fit store size into the range.
298906f32e7eSjoerg     while (StoreSizeInBytes > End - i)
299006f32e7eSjoerg       StoreSizeInBytes /= 2;
299106f32e7eSjoerg 
299206f32e7eSjoerg     // Minimize store size by trimming trailing zeros.
299306f32e7eSjoerg     for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
299406f32e7eSjoerg       while (j <= StoreSizeInBytes / 2)
299506f32e7eSjoerg         StoreSizeInBytes /= 2;
299606f32e7eSjoerg     }
299706f32e7eSjoerg 
299806f32e7eSjoerg     uint64_t Val = 0;
299906f32e7eSjoerg     for (size_t j = 0; j < StoreSizeInBytes; j++) {
300006f32e7eSjoerg       if (IsLittleEndian)
300106f32e7eSjoerg         Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
300206f32e7eSjoerg       else
300306f32e7eSjoerg         Val = (Val << 8) | ShadowBytes[i + j];
300406f32e7eSjoerg     }
300506f32e7eSjoerg 
300606f32e7eSjoerg     Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
300706f32e7eSjoerg     Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
300806f32e7eSjoerg     IRB.CreateAlignedStore(
3009*da58b97aSjoerg         Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()),
3010*da58b97aSjoerg         Align(1));
301106f32e7eSjoerg 
301206f32e7eSjoerg     i += StoreSizeInBytes;
301306f32e7eSjoerg   }
301406f32e7eSjoerg }
301506f32e7eSjoerg 
copyToShadow(ArrayRef<uint8_t> ShadowMask,ArrayRef<uint8_t> ShadowBytes,IRBuilder<> & IRB,Value * ShadowBase)301606f32e7eSjoerg void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
301706f32e7eSjoerg                                          ArrayRef<uint8_t> ShadowBytes,
301806f32e7eSjoerg                                          IRBuilder<> &IRB, Value *ShadowBase) {
301906f32e7eSjoerg   copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
302006f32e7eSjoerg }
302106f32e7eSjoerg 
copyToShadow(ArrayRef<uint8_t> ShadowMask,ArrayRef<uint8_t> ShadowBytes,size_t Begin,size_t End,IRBuilder<> & IRB,Value * ShadowBase)302206f32e7eSjoerg void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
302306f32e7eSjoerg                                          ArrayRef<uint8_t> ShadowBytes,
302406f32e7eSjoerg                                          size_t Begin, size_t End,
302506f32e7eSjoerg                                          IRBuilder<> &IRB, Value *ShadowBase) {
302606f32e7eSjoerg   assert(ShadowMask.size() == ShadowBytes.size());
302706f32e7eSjoerg   size_t Done = Begin;
302806f32e7eSjoerg   for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
302906f32e7eSjoerg     if (!ShadowMask[i]) {
303006f32e7eSjoerg       assert(!ShadowBytes[i]);
303106f32e7eSjoerg       continue;
303206f32e7eSjoerg     }
303306f32e7eSjoerg     uint8_t Val = ShadowBytes[i];
303406f32e7eSjoerg     if (!AsanSetShadowFunc[Val])
303506f32e7eSjoerg       continue;
303606f32e7eSjoerg 
303706f32e7eSjoerg     // Skip same values.
303806f32e7eSjoerg     for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
303906f32e7eSjoerg     }
304006f32e7eSjoerg 
304106f32e7eSjoerg     if (j - i >= ClMaxInlinePoisoningSize) {
304206f32e7eSjoerg       copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
304306f32e7eSjoerg       IRB.CreateCall(AsanSetShadowFunc[Val],
304406f32e7eSjoerg                      {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
304506f32e7eSjoerg                       ConstantInt::get(IntptrTy, j - i)});
304606f32e7eSjoerg       Done = j;
304706f32e7eSjoerg     }
304806f32e7eSjoerg   }
304906f32e7eSjoerg 
305006f32e7eSjoerg   copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
305106f32e7eSjoerg }
305206f32e7eSjoerg 
305306f32e7eSjoerg // Fake stack allocator (asan_fake_stack.h) has 11 size classes
305406f32e7eSjoerg // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
StackMallocSizeClass(uint64_t LocalStackSize)305506f32e7eSjoerg static int StackMallocSizeClass(uint64_t LocalStackSize) {
305606f32e7eSjoerg   assert(LocalStackSize <= kMaxStackMallocSize);
305706f32e7eSjoerg   uint64_t MaxSize = kMinStackMallocSize;
305806f32e7eSjoerg   for (int i = 0;; i++, MaxSize *= 2)
305906f32e7eSjoerg     if (LocalStackSize <= MaxSize) return i;
306006f32e7eSjoerg   llvm_unreachable("impossible LocalStackSize");
306106f32e7eSjoerg }
306206f32e7eSjoerg 
copyArgsPassedByValToAllocas()306306f32e7eSjoerg void FunctionStackPoisoner::copyArgsPassedByValToAllocas() {
306406f32e7eSjoerg   Instruction *CopyInsertPoint = &F.front().front();
306506f32e7eSjoerg   if (CopyInsertPoint == ASan.LocalDynamicShadow) {
306606f32e7eSjoerg     // Insert after the dynamic shadow location is determined
306706f32e7eSjoerg     CopyInsertPoint = CopyInsertPoint->getNextNode();
306806f32e7eSjoerg     assert(CopyInsertPoint);
306906f32e7eSjoerg   }
307006f32e7eSjoerg   IRBuilder<> IRB(CopyInsertPoint);
307106f32e7eSjoerg   const DataLayout &DL = F.getParent()->getDataLayout();
307206f32e7eSjoerg   for (Argument &Arg : F.args()) {
307306f32e7eSjoerg     if (Arg.hasByValAttr()) {
3074*da58b97aSjoerg       Type *Ty = Arg.getParamByValType();
3075*da58b97aSjoerg       const Align Alignment =
3076*da58b97aSjoerg           DL.getValueOrABITypeAlignment(Arg.getParamAlign(), Ty);
307706f32e7eSjoerg 
307806f32e7eSjoerg       AllocaInst *AI = IRB.CreateAlloca(
307906f32e7eSjoerg           Ty, nullptr,
308006f32e7eSjoerg           (Arg.hasName() ? Arg.getName() : "Arg" + Twine(Arg.getArgNo())) +
308106f32e7eSjoerg               ".byval");
3082*da58b97aSjoerg       AI->setAlignment(Alignment);
308306f32e7eSjoerg       Arg.replaceAllUsesWith(AI);
308406f32e7eSjoerg 
308506f32e7eSjoerg       uint64_t AllocSize = DL.getTypeAllocSize(Ty);
308606f32e7eSjoerg       IRB.CreateMemCpy(AI, Alignment, &Arg, Alignment, AllocSize);
308706f32e7eSjoerg     }
308806f32e7eSjoerg   }
308906f32e7eSjoerg }
309006f32e7eSjoerg 
createPHI(IRBuilder<> & IRB,Value * Cond,Value * ValueIfTrue,Instruction * ThenTerm,Value * ValueIfFalse)309106f32e7eSjoerg PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
309206f32e7eSjoerg                                           Value *ValueIfTrue,
309306f32e7eSjoerg                                           Instruction *ThenTerm,
309406f32e7eSjoerg                                           Value *ValueIfFalse) {
309506f32e7eSjoerg   PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
309606f32e7eSjoerg   BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
309706f32e7eSjoerg   PHI->addIncoming(ValueIfFalse, CondBlock);
309806f32e7eSjoerg   BasicBlock *ThenBlock = ThenTerm->getParent();
309906f32e7eSjoerg   PHI->addIncoming(ValueIfTrue, ThenBlock);
310006f32e7eSjoerg   return PHI;
310106f32e7eSjoerg }
310206f32e7eSjoerg 
createAllocaForLayout(IRBuilder<> & IRB,const ASanStackFrameLayout & L,bool Dynamic)310306f32e7eSjoerg Value *FunctionStackPoisoner::createAllocaForLayout(
310406f32e7eSjoerg     IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
310506f32e7eSjoerg   AllocaInst *Alloca;
310606f32e7eSjoerg   if (Dynamic) {
310706f32e7eSjoerg     Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
310806f32e7eSjoerg                               ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
310906f32e7eSjoerg                               "MyAlloca");
311006f32e7eSjoerg   } else {
311106f32e7eSjoerg     Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
311206f32e7eSjoerg                               nullptr, "MyAlloca");
311306f32e7eSjoerg     assert(Alloca->isStaticAlloca());
311406f32e7eSjoerg   }
311506f32e7eSjoerg   assert((ClRealignStack & (ClRealignStack - 1)) == 0);
311606f32e7eSjoerg   size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
3117*da58b97aSjoerg   Alloca->setAlignment(Align(FrameAlignment));
311806f32e7eSjoerg   return IRB.CreatePointerCast(Alloca, IntptrTy);
311906f32e7eSjoerg }
312006f32e7eSjoerg 
createDynamicAllocasInitStorage()312106f32e7eSjoerg void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
312206f32e7eSjoerg   BasicBlock &FirstBB = *F.begin();
312306f32e7eSjoerg   IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
312406f32e7eSjoerg   DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
312506f32e7eSjoerg   IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
312606f32e7eSjoerg   DynamicAllocaLayout->setAlignment(Align(32));
312706f32e7eSjoerg }
312806f32e7eSjoerg 
processDynamicAllocas()312906f32e7eSjoerg void FunctionStackPoisoner::processDynamicAllocas() {
313006f32e7eSjoerg   if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
313106f32e7eSjoerg     assert(DynamicAllocaPoisonCallVec.empty());
313206f32e7eSjoerg     return;
313306f32e7eSjoerg   }
313406f32e7eSjoerg 
313506f32e7eSjoerg   // Insert poison calls for lifetime intrinsics for dynamic allocas.
313606f32e7eSjoerg   for (const auto &APC : DynamicAllocaPoisonCallVec) {
313706f32e7eSjoerg     assert(APC.InsBefore);
313806f32e7eSjoerg     assert(APC.AI);
313906f32e7eSjoerg     assert(ASan.isInterestingAlloca(*APC.AI));
314006f32e7eSjoerg     assert(!APC.AI->isStaticAlloca());
314106f32e7eSjoerg 
314206f32e7eSjoerg     IRBuilder<> IRB(APC.InsBefore);
314306f32e7eSjoerg     poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
314406f32e7eSjoerg     // Dynamic allocas will be unpoisoned unconditionally below in
314506f32e7eSjoerg     // unpoisonDynamicAllocas.
314606f32e7eSjoerg     // Flag that we need unpoison static allocas.
314706f32e7eSjoerg   }
314806f32e7eSjoerg 
314906f32e7eSjoerg   // Handle dynamic allocas.
315006f32e7eSjoerg   createDynamicAllocasInitStorage();
315106f32e7eSjoerg   for (auto &AI : DynamicAllocaVec)
315206f32e7eSjoerg     handleDynamicAllocaCall(AI);
315306f32e7eSjoerg   unpoisonDynamicAllocas();
315406f32e7eSjoerg }
315506f32e7eSjoerg 
3156*da58b97aSjoerg /// Collect instructions in the entry block after \p InsBefore which initialize
3157*da58b97aSjoerg /// permanent storage for a function argument. These instructions must remain in
3158*da58b97aSjoerg /// the entry block so that uninitialized values do not appear in backtraces. An
3159*da58b97aSjoerg /// added benefit is that this conserves spill slots. This does not move stores
3160*da58b97aSjoerg /// before instrumented / "interesting" allocas.
findStoresToUninstrumentedArgAllocas(AddressSanitizer & ASan,Instruction & InsBefore,SmallVectorImpl<Instruction * > & InitInsts)3161*da58b97aSjoerg static void findStoresToUninstrumentedArgAllocas(
3162*da58b97aSjoerg     AddressSanitizer &ASan, Instruction &InsBefore,
3163*da58b97aSjoerg     SmallVectorImpl<Instruction *> &InitInsts) {
3164*da58b97aSjoerg   Instruction *Start = InsBefore.getNextNonDebugInstruction();
3165*da58b97aSjoerg   for (Instruction *It = Start; It; It = It->getNextNonDebugInstruction()) {
3166*da58b97aSjoerg     // Argument initialization looks like:
3167*da58b97aSjoerg     // 1) store <Argument>, <Alloca> OR
3168*da58b97aSjoerg     // 2) <CastArgument> = cast <Argument> to ...
3169*da58b97aSjoerg     //    store <CastArgument> to <Alloca>
3170*da58b97aSjoerg     // Do not consider any other kind of instruction.
3171*da58b97aSjoerg     //
3172*da58b97aSjoerg     // Note: This covers all known cases, but may not be exhaustive. An
3173*da58b97aSjoerg     // alternative to pattern-matching stores is to DFS over all Argument uses:
3174*da58b97aSjoerg     // this might be more general, but is probably much more complicated.
3175*da58b97aSjoerg     if (isa<AllocaInst>(It) || isa<CastInst>(It))
3176*da58b97aSjoerg       continue;
3177*da58b97aSjoerg     if (auto *Store = dyn_cast<StoreInst>(It)) {
3178*da58b97aSjoerg       // The store destination must be an alloca that isn't interesting for
3179*da58b97aSjoerg       // ASan to instrument. These are moved up before InsBefore, and they're
3180*da58b97aSjoerg       // not interesting because allocas for arguments can be mem2reg'd.
3181*da58b97aSjoerg       auto *Alloca = dyn_cast<AllocaInst>(Store->getPointerOperand());
3182*da58b97aSjoerg       if (!Alloca || ASan.isInterestingAlloca(*Alloca))
3183*da58b97aSjoerg         continue;
3184*da58b97aSjoerg 
3185*da58b97aSjoerg       Value *Val = Store->getValueOperand();
3186*da58b97aSjoerg       bool IsDirectArgInit = isa<Argument>(Val);
3187*da58b97aSjoerg       bool IsArgInitViaCast =
3188*da58b97aSjoerg           isa<CastInst>(Val) &&
3189*da58b97aSjoerg           isa<Argument>(cast<CastInst>(Val)->getOperand(0)) &&
3190*da58b97aSjoerg           // Check that the cast appears directly before the store. Otherwise
3191*da58b97aSjoerg           // moving the cast before InsBefore may break the IR.
3192*da58b97aSjoerg           Val == It->getPrevNonDebugInstruction();
3193*da58b97aSjoerg       bool IsArgInit = IsDirectArgInit || IsArgInitViaCast;
3194*da58b97aSjoerg       if (!IsArgInit)
3195*da58b97aSjoerg         continue;
3196*da58b97aSjoerg 
3197*da58b97aSjoerg       if (IsArgInitViaCast)
3198*da58b97aSjoerg         InitInsts.push_back(cast<Instruction>(Val));
3199*da58b97aSjoerg       InitInsts.push_back(Store);
3200*da58b97aSjoerg       continue;
3201*da58b97aSjoerg     }
3202*da58b97aSjoerg 
3203*da58b97aSjoerg     // Do not reorder past unknown instructions: argument initialization should
3204*da58b97aSjoerg     // only involve casts and stores.
3205*da58b97aSjoerg     return;
3206*da58b97aSjoerg   }
3207*da58b97aSjoerg }
3208*da58b97aSjoerg 
processStaticAllocas()320906f32e7eSjoerg void FunctionStackPoisoner::processStaticAllocas() {
321006f32e7eSjoerg   if (AllocaVec.empty()) {
321106f32e7eSjoerg     assert(StaticAllocaPoisonCallVec.empty());
321206f32e7eSjoerg     return;
321306f32e7eSjoerg   }
321406f32e7eSjoerg 
321506f32e7eSjoerg   int StackMallocIdx = -1;
321606f32e7eSjoerg   DebugLoc EntryDebugLocation;
321706f32e7eSjoerg   if (auto SP = F.getSubprogram())
3218*da58b97aSjoerg     EntryDebugLocation =
3219*da58b97aSjoerg         DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);
322006f32e7eSjoerg 
322106f32e7eSjoerg   Instruction *InsBefore = AllocaVec[0];
322206f32e7eSjoerg   IRBuilder<> IRB(InsBefore);
322306f32e7eSjoerg 
322406f32e7eSjoerg   // Make sure non-instrumented allocas stay in the entry block. Otherwise,
322506f32e7eSjoerg   // debug info is broken, because only entry-block allocas are treated as
322606f32e7eSjoerg   // regular stack slots.
322706f32e7eSjoerg   auto InsBeforeB = InsBefore->getParent();
322806f32e7eSjoerg   assert(InsBeforeB == &F.getEntryBlock());
322906f32e7eSjoerg   for (auto *AI : StaticAllocasToMoveUp)
323006f32e7eSjoerg     if (AI->getParent() == InsBeforeB)
323106f32e7eSjoerg       AI->moveBefore(InsBefore);
323206f32e7eSjoerg 
3233*da58b97aSjoerg   // Move stores of arguments into entry-block allocas as well. This prevents
3234*da58b97aSjoerg   // extra stack slots from being generated (to house the argument values until
3235*da58b97aSjoerg   // they can be stored into the allocas). This also prevents uninitialized
3236*da58b97aSjoerg   // values from being shown in backtraces.
3237*da58b97aSjoerg   SmallVector<Instruction *, 8> ArgInitInsts;
3238*da58b97aSjoerg   findStoresToUninstrumentedArgAllocas(ASan, *InsBefore, ArgInitInsts);
3239*da58b97aSjoerg   for (Instruction *ArgInitInst : ArgInitInsts)
3240*da58b97aSjoerg     ArgInitInst->moveBefore(InsBefore);
3241*da58b97aSjoerg 
324206f32e7eSjoerg   // If we have a call to llvm.localescape, keep it in the entry block.
324306f32e7eSjoerg   if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
324406f32e7eSjoerg 
324506f32e7eSjoerg   SmallVector<ASanStackVariableDescription, 16> SVD;
324606f32e7eSjoerg   SVD.reserve(AllocaVec.size());
324706f32e7eSjoerg   for (AllocaInst *AI : AllocaVec) {
324806f32e7eSjoerg     ASanStackVariableDescription D = {AI->getName().data(),
324906f32e7eSjoerg                                       ASan.getAllocaSizeInBytes(*AI),
325006f32e7eSjoerg                                       0,
325106f32e7eSjoerg                                       AI->getAlignment(),
325206f32e7eSjoerg                                       AI,
325306f32e7eSjoerg                                       0,
325406f32e7eSjoerg                                       0};
325506f32e7eSjoerg     SVD.push_back(D);
325606f32e7eSjoerg   }
325706f32e7eSjoerg 
325806f32e7eSjoerg   // Minimal header size (left redzone) is 4 pointers,
325906f32e7eSjoerg   // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
326006f32e7eSjoerg   size_t Granularity = 1ULL << Mapping.Scale;
326106f32e7eSjoerg   size_t MinHeaderSize = std::max((size_t)ASan.LongSize / 2, Granularity);
326206f32e7eSjoerg   const ASanStackFrameLayout &L =
326306f32e7eSjoerg       ComputeASanStackFrameLayout(SVD, Granularity, MinHeaderSize);
326406f32e7eSjoerg 
326506f32e7eSjoerg   // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
326606f32e7eSjoerg   DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
326706f32e7eSjoerg   for (auto &Desc : SVD)
326806f32e7eSjoerg     AllocaToSVDMap[Desc.AI] = &Desc;
326906f32e7eSjoerg 
327006f32e7eSjoerg   // Update SVD with information from lifetime intrinsics.
327106f32e7eSjoerg   for (const auto &APC : StaticAllocaPoisonCallVec) {
327206f32e7eSjoerg     assert(APC.InsBefore);
327306f32e7eSjoerg     assert(APC.AI);
327406f32e7eSjoerg     assert(ASan.isInterestingAlloca(*APC.AI));
327506f32e7eSjoerg     assert(APC.AI->isStaticAlloca());
327606f32e7eSjoerg 
327706f32e7eSjoerg     ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
327806f32e7eSjoerg     Desc.LifetimeSize = Desc.Size;
327906f32e7eSjoerg     if (const DILocation *FnLoc = EntryDebugLocation.get()) {
328006f32e7eSjoerg       if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
328106f32e7eSjoerg         if (LifetimeLoc->getFile() == FnLoc->getFile())
328206f32e7eSjoerg           if (unsigned Line = LifetimeLoc->getLine())
328306f32e7eSjoerg             Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
328406f32e7eSjoerg       }
328506f32e7eSjoerg     }
328606f32e7eSjoerg   }
328706f32e7eSjoerg 
328806f32e7eSjoerg   auto DescriptionString = ComputeASanStackFrameDescription(SVD);
328906f32e7eSjoerg   LLVM_DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
329006f32e7eSjoerg   uint64_t LocalStackSize = L.FrameSize;
329106f32e7eSjoerg   bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
329206f32e7eSjoerg                        LocalStackSize <= kMaxStackMallocSize;
329306f32e7eSjoerg   bool DoDynamicAlloca = ClDynamicAllocaStack;
329406f32e7eSjoerg   // Don't do dynamic alloca or stack malloc if:
329506f32e7eSjoerg   // 1) There is inline asm: too often it makes assumptions on which registers
329606f32e7eSjoerg   //    are available.
329706f32e7eSjoerg   // 2) There is a returns_twice call (typically setjmp), which is
329806f32e7eSjoerg   //    optimization-hostile, and doesn't play well with introduced indirect
329906f32e7eSjoerg   //    register-relative calculation of local variable addresses.
3300*da58b97aSjoerg   DoDynamicAlloca &= !HasInlineAsm && !HasReturnsTwiceCall;
3301*da58b97aSjoerg   DoStackMalloc &= !HasInlineAsm && !HasReturnsTwiceCall;
330206f32e7eSjoerg 
330306f32e7eSjoerg   Value *StaticAlloca =
330406f32e7eSjoerg       DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
330506f32e7eSjoerg 
330606f32e7eSjoerg   Value *FakeStack;
330706f32e7eSjoerg   Value *LocalStackBase;
330806f32e7eSjoerg   Value *LocalStackBaseAlloca;
330906f32e7eSjoerg   uint8_t DIExprFlags = DIExpression::ApplyOffset;
331006f32e7eSjoerg 
331106f32e7eSjoerg   if (DoStackMalloc) {
331206f32e7eSjoerg     LocalStackBaseAlloca =
331306f32e7eSjoerg         IRB.CreateAlloca(IntptrTy, nullptr, "asan_local_stack_base");
331406f32e7eSjoerg     // void *FakeStack = __asan_option_detect_stack_use_after_return
331506f32e7eSjoerg     //     ? __asan_stack_malloc_N(LocalStackSize)
331606f32e7eSjoerg     //     : nullptr;
331706f32e7eSjoerg     // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
331806f32e7eSjoerg     Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
331906f32e7eSjoerg         kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
332006f32e7eSjoerg     Value *UseAfterReturnIsEnabled = IRB.CreateICmpNE(
332106f32e7eSjoerg         IRB.CreateLoad(IRB.getInt32Ty(), OptionDetectUseAfterReturn),
332206f32e7eSjoerg         Constant::getNullValue(IRB.getInt32Ty()));
332306f32e7eSjoerg     Instruction *Term =
332406f32e7eSjoerg         SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
332506f32e7eSjoerg     IRBuilder<> IRBIf(Term);
332606f32e7eSjoerg     StackMallocIdx = StackMallocSizeClass(LocalStackSize);
332706f32e7eSjoerg     assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
332806f32e7eSjoerg     Value *FakeStackValue =
332906f32e7eSjoerg         IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
333006f32e7eSjoerg                          ConstantInt::get(IntptrTy, LocalStackSize));
333106f32e7eSjoerg     IRB.SetInsertPoint(InsBefore);
333206f32e7eSjoerg     FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
333306f32e7eSjoerg                           ConstantInt::get(IntptrTy, 0));
333406f32e7eSjoerg 
333506f32e7eSjoerg     Value *NoFakeStack =
333606f32e7eSjoerg         IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
333706f32e7eSjoerg     Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
333806f32e7eSjoerg     IRBIf.SetInsertPoint(Term);
333906f32e7eSjoerg     Value *AllocaValue =
334006f32e7eSjoerg         DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
334106f32e7eSjoerg 
334206f32e7eSjoerg     IRB.SetInsertPoint(InsBefore);
334306f32e7eSjoerg     LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
334406f32e7eSjoerg     IRB.CreateStore(LocalStackBase, LocalStackBaseAlloca);
334506f32e7eSjoerg     DIExprFlags |= DIExpression::DerefBefore;
334606f32e7eSjoerg   } else {
334706f32e7eSjoerg     // void *FakeStack = nullptr;
334806f32e7eSjoerg     // void *LocalStackBase = alloca(LocalStackSize);
334906f32e7eSjoerg     FakeStack = ConstantInt::get(IntptrTy, 0);
335006f32e7eSjoerg     LocalStackBase =
335106f32e7eSjoerg         DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
335206f32e7eSjoerg     LocalStackBaseAlloca = LocalStackBase;
335306f32e7eSjoerg   }
335406f32e7eSjoerg 
3355*da58b97aSjoerg   // It shouldn't matter whether we pass an `alloca` or a `ptrtoint` as the
3356*da58b97aSjoerg   // dbg.declare address opereand, but passing a `ptrtoint` seems to confuse
3357*da58b97aSjoerg   // later passes and can result in dropped variable coverage in debug info.
3358*da58b97aSjoerg   Value *LocalStackBaseAllocaPtr =
3359*da58b97aSjoerg       isa<PtrToIntInst>(LocalStackBaseAlloca)
3360*da58b97aSjoerg           ? cast<PtrToIntInst>(LocalStackBaseAlloca)->getPointerOperand()
3361*da58b97aSjoerg           : LocalStackBaseAlloca;
3362*da58b97aSjoerg   assert(isa<AllocaInst>(LocalStackBaseAllocaPtr) &&
3363*da58b97aSjoerg          "Variable descriptions relative to ASan stack base will be dropped");
3364*da58b97aSjoerg 
336506f32e7eSjoerg   // Replace Alloca instructions with base+offset.
336606f32e7eSjoerg   for (const auto &Desc : SVD) {
336706f32e7eSjoerg     AllocaInst *AI = Desc.AI;
3368*da58b97aSjoerg     replaceDbgDeclare(AI, LocalStackBaseAllocaPtr, DIB, DIExprFlags,
336906f32e7eSjoerg                       Desc.Offset);
337006f32e7eSjoerg     Value *NewAllocaPtr = IRB.CreateIntToPtr(
337106f32e7eSjoerg         IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
337206f32e7eSjoerg         AI->getType());
337306f32e7eSjoerg     AI->replaceAllUsesWith(NewAllocaPtr);
337406f32e7eSjoerg   }
337506f32e7eSjoerg 
337606f32e7eSjoerg   // The left-most redzone has enough space for at least 4 pointers.
337706f32e7eSjoerg   // Write the Magic value to redzone[0].
337806f32e7eSjoerg   Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
337906f32e7eSjoerg   IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
338006f32e7eSjoerg                   BasePlus0);
338106f32e7eSjoerg   // Write the frame description constant to redzone[1].
338206f32e7eSjoerg   Value *BasePlus1 = IRB.CreateIntToPtr(
338306f32e7eSjoerg       IRB.CreateAdd(LocalStackBase,
338406f32e7eSjoerg                     ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
338506f32e7eSjoerg       IntptrPtrTy);
338606f32e7eSjoerg   GlobalVariable *StackDescriptionGlobal =
338706f32e7eSjoerg       createPrivateGlobalForString(*F.getParent(), DescriptionString,
338806f32e7eSjoerg                                    /*AllowMerging*/ true, kAsanGenPrefix);
338906f32e7eSjoerg   Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
339006f32e7eSjoerg   IRB.CreateStore(Description, BasePlus1);
339106f32e7eSjoerg   // Write the PC to redzone[2].
339206f32e7eSjoerg   Value *BasePlus2 = IRB.CreateIntToPtr(
339306f32e7eSjoerg       IRB.CreateAdd(LocalStackBase,
339406f32e7eSjoerg                     ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
339506f32e7eSjoerg       IntptrPtrTy);
339606f32e7eSjoerg   IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
339706f32e7eSjoerg 
339806f32e7eSjoerg   const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
339906f32e7eSjoerg 
340006f32e7eSjoerg   // Poison the stack red zones at the entry.
340106f32e7eSjoerg   Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
340206f32e7eSjoerg   // As mask we must use most poisoned case: red zones and after scope.
340306f32e7eSjoerg   // As bytes we can use either the same or just red zones only.
340406f32e7eSjoerg   copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
340506f32e7eSjoerg 
340606f32e7eSjoerg   if (!StaticAllocaPoisonCallVec.empty()) {
340706f32e7eSjoerg     const auto &ShadowInScope = GetShadowBytes(SVD, L);
340806f32e7eSjoerg 
340906f32e7eSjoerg     // Poison static allocas near lifetime intrinsics.
341006f32e7eSjoerg     for (const auto &APC : StaticAllocaPoisonCallVec) {
341106f32e7eSjoerg       const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
341206f32e7eSjoerg       assert(Desc.Offset % L.Granularity == 0);
341306f32e7eSjoerg       size_t Begin = Desc.Offset / L.Granularity;
341406f32e7eSjoerg       size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
341506f32e7eSjoerg 
341606f32e7eSjoerg       IRBuilder<> IRB(APC.InsBefore);
341706f32e7eSjoerg       copyToShadow(ShadowAfterScope,
341806f32e7eSjoerg                    APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
341906f32e7eSjoerg                    IRB, ShadowBase);
342006f32e7eSjoerg     }
342106f32e7eSjoerg   }
342206f32e7eSjoerg 
342306f32e7eSjoerg   SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
342406f32e7eSjoerg   SmallVector<uint8_t, 64> ShadowAfterReturn;
342506f32e7eSjoerg 
342606f32e7eSjoerg   // (Un)poison the stack before all ret instructions.
3427*da58b97aSjoerg   for (Instruction *Ret : RetVec) {
342806f32e7eSjoerg     IRBuilder<> IRBRet(Ret);
342906f32e7eSjoerg     // Mark the current frame as retired.
343006f32e7eSjoerg     IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
343106f32e7eSjoerg                        BasePlus0);
343206f32e7eSjoerg     if (DoStackMalloc) {
343306f32e7eSjoerg       assert(StackMallocIdx >= 0);
343406f32e7eSjoerg       // if FakeStack != 0  // LocalStackBase == FakeStack
343506f32e7eSjoerg       //     // In use-after-return mode, poison the whole stack frame.
343606f32e7eSjoerg       //     if StackMallocIdx <= 4
343706f32e7eSjoerg       //         // For small sizes inline the whole thing:
343806f32e7eSjoerg       //         memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
343906f32e7eSjoerg       //         **SavedFlagPtr(FakeStack) = 0
344006f32e7eSjoerg       //     else
344106f32e7eSjoerg       //         __asan_stack_free_N(FakeStack, LocalStackSize)
344206f32e7eSjoerg       // else
344306f32e7eSjoerg       //     <This is not a fake stack; unpoison the redzones>
344406f32e7eSjoerg       Value *Cmp =
344506f32e7eSjoerg           IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
344606f32e7eSjoerg       Instruction *ThenTerm, *ElseTerm;
344706f32e7eSjoerg       SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
344806f32e7eSjoerg 
344906f32e7eSjoerg       IRBuilder<> IRBPoison(ThenTerm);
345006f32e7eSjoerg       if (StackMallocIdx <= 4) {
345106f32e7eSjoerg         int ClassSize = kMinStackMallocSize << StackMallocIdx;
345206f32e7eSjoerg         ShadowAfterReturn.resize(ClassSize / L.Granularity,
345306f32e7eSjoerg                                  kAsanStackUseAfterReturnMagic);
345406f32e7eSjoerg         copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
345506f32e7eSjoerg                      ShadowBase);
345606f32e7eSjoerg         Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
345706f32e7eSjoerg             FakeStack,
345806f32e7eSjoerg             ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
345906f32e7eSjoerg         Value *SavedFlagPtr = IRBPoison.CreateLoad(
346006f32e7eSjoerg             IntptrTy, IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
346106f32e7eSjoerg         IRBPoison.CreateStore(
346206f32e7eSjoerg             Constant::getNullValue(IRBPoison.getInt8Ty()),
346306f32e7eSjoerg             IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
346406f32e7eSjoerg       } else {
346506f32e7eSjoerg         // For larger frames call __asan_stack_free_*.
346606f32e7eSjoerg         IRBPoison.CreateCall(
346706f32e7eSjoerg             AsanStackFreeFunc[StackMallocIdx],
346806f32e7eSjoerg             {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
346906f32e7eSjoerg       }
347006f32e7eSjoerg 
347106f32e7eSjoerg       IRBuilder<> IRBElse(ElseTerm);
347206f32e7eSjoerg       copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
347306f32e7eSjoerg     } else {
347406f32e7eSjoerg       copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
347506f32e7eSjoerg     }
347606f32e7eSjoerg   }
347706f32e7eSjoerg 
347806f32e7eSjoerg   // We are done. Remove the old unused alloca instructions.
347906f32e7eSjoerg   for (auto AI : AllocaVec) AI->eraseFromParent();
348006f32e7eSjoerg }
348106f32e7eSjoerg 
poisonAlloca(Value * V,uint64_t Size,IRBuilder<> & IRB,bool DoPoison)348206f32e7eSjoerg void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
348306f32e7eSjoerg                                          IRBuilder<> &IRB, bool DoPoison) {
348406f32e7eSjoerg   // For now just insert the call to ASan runtime.
348506f32e7eSjoerg   Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
348606f32e7eSjoerg   Value *SizeArg = ConstantInt::get(IntptrTy, Size);
348706f32e7eSjoerg   IRB.CreateCall(
348806f32e7eSjoerg       DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
348906f32e7eSjoerg       {AddrArg, SizeArg});
349006f32e7eSjoerg }
349106f32e7eSjoerg 
349206f32e7eSjoerg // Handling llvm.lifetime intrinsics for a given %alloca:
349306f32e7eSjoerg // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
349406f32e7eSjoerg // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
349506f32e7eSjoerg //     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
349606f32e7eSjoerg //     could be poisoned by previous llvm.lifetime.end instruction, as the
349706f32e7eSjoerg //     variable may go in and out of scope several times, e.g. in loops).
349806f32e7eSjoerg // (3) if we poisoned at least one %alloca in a function,
349906f32e7eSjoerg //     unpoison the whole stack frame at function exit.
handleDynamicAllocaCall(AllocaInst * AI)350006f32e7eSjoerg void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
350106f32e7eSjoerg   IRBuilder<> IRB(AI);
350206f32e7eSjoerg 
3503*da58b97aSjoerg   const unsigned Alignment = std::max(kAllocaRzSize, AI->getAlignment());
350406f32e7eSjoerg   const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
350506f32e7eSjoerg 
350606f32e7eSjoerg   Value *Zero = Constant::getNullValue(IntptrTy);
350706f32e7eSjoerg   Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
350806f32e7eSjoerg   Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
350906f32e7eSjoerg 
351006f32e7eSjoerg   // Since we need to extend alloca with additional memory to locate
351106f32e7eSjoerg   // redzones, and OldSize is number of allocated blocks with
351206f32e7eSjoerg   // ElementSize size, get allocated memory size in bytes by
351306f32e7eSjoerg   // OldSize * ElementSize.
351406f32e7eSjoerg   const unsigned ElementSize =
351506f32e7eSjoerg       F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
351606f32e7eSjoerg   Value *OldSize =
351706f32e7eSjoerg       IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
351806f32e7eSjoerg                     ConstantInt::get(IntptrTy, ElementSize));
351906f32e7eSjoerg 
352006f32e7eSjoerg   // PartialSize = OldSize % 32
352106f32e7eSjoerg   Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
352206f32e7eSjoerg 
352306f32e7eSjoerg   // Misalign = kAllocaRzSize - PartialSize;
352406f32e7eSjoerg   Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
352506f32e7eSjoerg 
352606f32e7eSjoerg   // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
352706f32e7eSjoerg   Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
352806f32e7eSjoerg   Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
352906f32e7eSjoerg 
3530*da58b97aSjoerg   // AdditionalChunkSize = Alignment + PartialPadding + kAllocaRzSize
3531*da58b97aSjoerg   // Alignment is added to locate left redzone, PartialPadding for possible
353206f32e7eSjoerg   // partial redzone and kAllocaRzSize for right redzone respectively.
353306f32e7eSjoerg   Value *AdditionalChunkSize = IRB.CreateAdd(
3534*da58b97aSjoerg       ConstantInt::get(IntptrTy, Alignment + kAllocaRzSize), PartialPadding);
353506f32e7eSjoerg 
353606f32e7eSjoerg   Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
353706f32e7eSjoerg 
3538*da58b97aSjoerg   // Insert new alloca with new NewSize and Alignment params.
353906f32e7eSjoerg   AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
3540*da58b97aSjoerg   NewAlloca->setAlignment(Align(Alignment));
354106f32e7eSjoerg 
3542*da58b97aSjoerg   // NewAddress = Address + Alignment
354306f32e7eSjoerg   Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
3544*da58b97aSjoerg                                     ConstantInt::get(IntptrTy, Alignment));
354506f32e7eSjoerg 
354606f32e7eSjoerg   // Insert __asan_alloca_poison call for new created alloca.
354706f32e7eSjoerg   IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
354806f32e7eSjoerg 
354906f32e7eSjoerg   // Store the last alloca's address to DynamicAllocaLayout. We'll need this
355006f32e7eSjoerg   // for unpoisoning stuff.
355106f32e7eSjoerg   IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
355206f32e7eSjoerg 
355306f32e7eSjoerg   Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
355406f32e7eSjoerg 
355506f32e7eSjoerg   // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
355606f32e7eSjoerg   AI->replaceAllUsesWith(NewAddressPtr);
355706f32e7eSjoerg 
355806f32e7eSjoerg   // We are done. Erase old alloca from parent.
355906f32e7eSjoerg   AI->eraseFromParent();
356006f32e7eSjoerg }
356106f32e7eSjoerg 
356206f32e7eSjoerg // isSafeAccess returns true if Addr is always inbounds with respect to its
356306f32e7eSjoerg // base object. For example, it is a field access or an array access with
356406f32e7eSjoerg // constant inbounds index.
isSafeAccess(ObjectSizeOffsetVisitor & ObjSizeVis,Value * Addr,uint64_t TypeSize) const356506f32e7eSjoerg bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
356606f32e7eSjoerg                                     Value *Addr, uint64_t TypeSize) const {
356706f32e7eSjoerg   SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
356806f32e7eSjoerg   if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
356906f32e7eSjoerg   uint64_t Size = SizeOffset.first.getZExtValue();
357006f32e7eSjoerg   int64_t Offset = SizeOffset.second.getSExtValue();
357106f32e7eSjoerg   // Three checks are required to ensure safety:
357206f32e7eSjoerg   // . Offset >= 0  (since the offset is given from the base ptr)
357306f32e7eSjoerg   // . Size >= Offset  (unsigned)
357406f32e7eSjoerg   // . Size - Offset >= NeededSize  (unsigned)
357506f32e7eSjoerg   return Offset >= 0 && Size >= uint64_t(Offset) &&
357606f32e7eSjoerg          Size - uint64_t(Offset) >= TypeSize / 8;
357706f32e7eSjoerg }
3578