Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
35266 views
//===- AddressSanitizer.cpp - memory error detector -----------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file is a part of AddressSanitizer, an address basic correctness9// checker.10// Details of the algorithm:11// https://github.com/google/sanitizers/wiki/AddressSanitizerAlgorithm12//13// FIXME: This sanitizer does not yet handle scalable vectors14//15//===----------------------------------------------------------------------===//1617#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"18#include "llvm/ADT/ArrayRef.h"19#include "llvm/ADT/DenseMap.h"20#include "llvm/ADT/DepthFirstIterator.h"21#include "llvm/ADT/SmallPtrSet.h"22#include "llvm/ADT/SmallVector.h"23#include "llvm/ADT/Statistic.h"24#include "llvm/ADT/StringExtras.h"25#include "llvm/ADT/StringRef.h"26#include "llvm/ADT/Twine.h"27#include "llvm/Analysis/GlobalsModRef.h"28#include "llvm/Analysis/MemoryBuiltins.h"29#include "llvm/Analysis/StackSafetyAnalysis.h"30#include "llvm/Analysis/TargetLibraryInfo.h"31#include "llvm/Analysis/ValueTracking.h"32#include "llvm/BinaryFormat/MachO.h"33#include "llvm/Demangle/Demangle.h"34#include "llvm/IR/Argument.h"35#include "llvm/IR/Attributes.h"36#include "llvm/IR/BasicBlock.h"37#include "llvm/IR/Comdat.h"38#include "llvm/IR/Constant.h"39#include "llvm/IR/Constants.h"40#include "llvm/IR/DIBuilder.h"41#include "llvm/IR/DataLayout.h"42#include "llvm/IR/DebugInfoMetadata.h"43#include "llvm/IR/DebugLoc.h"44#include "llvm/IR/DerivedTypes.h"45#include "llvm/IR/EHPersonalities.h"46#include "llvm/IR/Function.h"47#include "llvm/IR/GlobalAlias.h"48#include "llvm/IR/GlobalValue.h"49#include "llvm/IR/GlobalVariable.h"50#include "llvm/IR/IRBuilder.h"51#include "llvm/IR/InlineAsm.h"52#include "llvm/IR/InstVisitor.h"53#include "llvm/IR/InstrTypes.h"54#include "llvm/IR/Instruction.h"55#include "llvm/IR/Instructions.h"56#include "llvm/IR/IntrinsicInst.h"57#include "llvm/IR/Intrinsics.h"58#include "llvm/IR/LLVMContext.h"59#include "llvm/IR/MDBuilder.h"60#include "llvm/IR/Metadata.h"61#include "llvm/IR/Module.h"62#include "llvm/IR/Type.h"63#include "llvm/IR/Use.h"64#include "llvm/IR/Value.h"65#include "llvm/MC/MCSectionMachO.h"66#include "llvm/Support/Casting.h"67#include "llvm/Support/CommandLine.h"68#include "llvm/Support/Debug.h"69#include "llvm/Support/ErrorHandling.h"70#include "llvm/Support/MathExtras.h"71#include "llvm/Support/raw_ostream.h"72#include "llvm/TargetParser/Triple.h"73#include "llvm/Transforms/Instrumentation.h"74#include "llvm/Transforms/Instrumentation/AddressSanitizerCommon.h"75#include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"76#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"77#include "llvm/Transforms/Utils/BasicBlockUtils.h"78#include "llvm/Transforms/Utils/Local.h"79#include "llvm/Transforms/Utils/ModuleUtils.h"80#include "llvm/Transforms/Utils/PromoteMemToReg.h"81#include <algorithm>82#include <cassert>83#include <cstddef>84#include <cstdint>85#include <iomanip>86#include <limits>87#include <sstream>88#include <string>89#include <tuple>9091using namespace llvm;9293#define DEBUG_TYPE "asan"9495static const uint64_t kDefaultShadowScale = 3;96static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;97static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;98static const uint64_t kDynamicShadowSentinel =99std::numeric_limits<uint64_t>::max();100static const uint64_t kSmallX86_64ShadowOffsetBase = 0x7FFFFFFF; // < 2G.101static const uint64_t kSmallX86_64ShadowOffsetAlignMask = ~0xFFFULL;102static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;103static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 44;104static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;105static const uint64_t kMIPS_ShadowOffsetN32 = 1ULL << 29;106static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;107static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;108static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;109static const uint64_t kLoongArch64_ShadowOffset64 = 1ULL << 46;110static const uint64_t kRISCV64_ShadowOffset64 = kDynamicShadowSentinel;111static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;112static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;113static const uint64_t kFreeBSDAArch64_ShadowOffset64 = 1ULL << 47;114static const uint64_t kFreeBSDKasan_ShadowOffset64 = 0xdffff7c000000000;115static const uint64_t kNetBSD_ShadowOffset32 = 1ULL << 30;116static const uint64_t kNetBSD_ShadowOffset64 = 1ULL << 46;117static const uint64_t kNetBSDKasan_ShadowOffset64 = 0xdfff900000000000;118static const uint64_t kPS_ShadowOffset64 = 1ULL << 40;119static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;120static const uint64_t kEmscriptenShadowOffset = 0;121122// The shadow memory space is dynamically allocated.123static const uint64_t kWindowsShadowOffset64 = kDynamicShadowSentinel;124125static const size_t kMinStackMallocSize = 1 << 6; // 64B126static const size_t kMaxStackMallocSize = 1 << 16; // 64K127static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;128static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;129130const char kAsanModuleCtorName[] = "asan.module_ctor";131const char kAsanModuleDtorName[] = "asan.module_dtor";132static const uint64_t kAsanCtorAndDtorPriority = 1;133// On Emscripten, the system needs more than one priorities for constructors.134static const uint64_t kAsanEmscriptenCtorAndDtorPriority = 50;135const char kAsanReportErrorTemplate[] = "__asan_report_";136const char kAsanRegisterGlobalsName[] = "__asan_register_globals";137const char kAsanUnregisterGlobalsName[] = "__asan_unregister_globals";138const char kAsanRegisterImageGlobalsName[] = "__asan_register_image_globals";139const char kAsanUnregisterImageGlobalsName[] =140"__asan_unregister_image_globals";141const char kAsanRegisterElfGlobalsName[] = "__asan_register_elf_globals";142const char kAsanUnregisterElfGlobalsName[] = "__asan_unregister_elf_globals";143const char kAsanPoisonGlobalsName[] = "__asan_before_dynamic_init";144const char kAsanUnpoisonGlobalsName[] = "__asan_after_dynamic_init";145const char kAsanInitName[] = "__asan_init";146const char kAsanVersionCheckNamePrefix[] = "__asan_version_mismatch_check_v";147const char kAsanPtrCmp[] = "__sanitizer_ptr_cmp";148const char kAsanPtrSub[] = "__sanitizer_ptr_sub";149const char kAsanHandleNoReturnName[] = "__asan_handle_no_return";150static const int kMaxAsanStackMallocSizeClass = 10;151const char kAsanStackMallocNameTemplate[] = "__asan_stack_malloc_";152const char kAsanStackMallocAlwaysNameTemplate[] =153"__asan_stack_malloc_always_";154const char kAsanStackFreeNameTemplate[] = "__asan_stack_free_";155const char kAsanGenPrefix[] = "___asan_gen_";156const char kODRGenPrefix[] = "__odr_asan_gen_";157const char kSanCovGenPrefix[] = "__sancov_gen_";158const char kAsanSetShadowPrefix[] = "__asan_set_shadow_";159const char kAsanPoisonStackMemoryName[] = "__asan_poison_stack_memory";160const char kAsanUnpoisonStackMemoryName[] = "__asan_unpoison_stack_memory";161162// ASan version script has __asan_* wildcard. Triple underscore prevents a163// linker (gold) warning about attempting to export a local symbol.164const char kAsanGlobalsRegisteredFlagName[] = "___asan_globals_registered";165166const char kAsanOptionDetectUseAfterReturn[] =167"__asan_option_detect_stack_use_after_return";168169const char kAsanShadowMemoryDynamicAddress[] =170"__asan_shadow_memory_dynamic_address";171172const char kAsanAllocaPoison[] = "__asan_alloca_poison";173const char kAsanAllocasUnpoison[] = "__asan_allocas_unpoison";174175const char kAMDGPUAddressSharedName[] = "llvm.amdgcn.is.shared";176const char kAMDGPUAddressPrivateName[] = "llvm.amdgcn.is.private";177const char kAMDGPUBallotName[] = "llvm.amdgcn.ballot.i64";178const char kAMDGPUUnreachableName[] = "llvm.amdgcn.unreachable";179180// Accesses sizes are powers of two: 1, 2, 4, 8, 16.181static const size_t kNumberOfAccessSizes = 5;182183static const uint64_t kAllocaRzSize = 32;184185// ASanAccessInfo implementation constants.186constexpr size_t kCompileKernelShift = 0;187constexpr size_t kCompileKernelMask = 0x1;188constexpr size_t kAccessSizeIndexShift = 1;189constexpr size_t kAccessSizeIndexMask = 0xf;190constexpr size_t kIsWriteShift = 5;191constexpr size_t kIsWriteMask = 0x1;192193// Command-line flags.194195static cl::opt<bool> ClEnableKasan(196"asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),197cl::Hidden, cl::init(false));198199static cl::opt<bool> ClRecover(200"asan-recover",201cl::desc("Enable recovery mode (continue-after-error)."),202cl::Hidden, cl::init(false));203204static cl::opt<bool> ClInsertVersionCheck(205"asan-guard-against-version-mismatch",206cl::desc("Guard against compiler/runtime version mismatch."), cl::Hidden,207cl::init(true));208209// This flag may need to be replaced with -f[no-]asan-reads.210static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",211cl::desc("instrument read instructions"),212cl::Hidden, cl::init(true));213214static cl::opt<bool> ClInstrumentWrites(215"asan-instrument-writes", cl::desc("instrument write instructions"),216cl::Hidden, cl::init(true));217218static cl::opt<bool>219ClUseStackSafety("asan-use-stack-safety", cl::Hidden, cl::init(true),220cl::Hidden, cl::desc("Use Stack Safety analysis results"),221cl::Optional);222223static cl::opt<bool> ClInstrumentAtomics(224"asan-instrument-atomics",225cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,226cl::init(true));227228static cl::opt<bool>229ClInstrumentByval("asan-instrument-byval",230cl::desc("instrument byval call arguments"), cl::Hidden,231cl::init(true));232233static cl::opt<bool> ClAlwaysSlowPath(234"asan-always-slow-path",235cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,236cl::init(false));237238static cl::opt<bool> ClForceDynamicShadow(239"asan-force-dynamic-shadow",240cl::desc("Load shadow address into a local variable for each function"),241cl::Hidden, cl::init(false));242243static cl::opt<bool>244ClWithIfunc("asan-with-ifunc",245cl::desc("Access dynamic shadow through an ifunc global on "246"platforms that support this"),247cl::Hidden, cl::init(true));248249static cl::opt<bool> ClWithIfuncSuppressRemat(250"asan-with-ifunc-suppress-remat",251cl::desc("Suppress rematerialization of dynamic shadow address by passing "252"it through inline asm in prologue."),253cl::Hidden, cl::init(true));254255// This flag limits the number of instructions to be instrumented256// in any given BB. Normally, this should be set to unlimited (INT_MAX),257// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary258// set it to 10000.259static cl::opt<int> ClMaxInsnsToInstrumentPerBB(260"asan-max-ins-per-bb", cl::init(10000),261cl::desc("maximal number of instructions to instrument in any given BB"),262cl::Hidden);263264// This flag may need to be replaced with -f[no]asan-stack.265static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),266cl::Hidden, cl::init(true));267static cl::opt<uint32_t> ClMaxInlinePoisoningSize(268"asan-max-inline-poisoning-size",269cl::desc(270"Inline shadow poisoning for blocks up to the given size in bytes."),271cl::Hidden, cl::init(64));272273static cl::opt<AsanDetectStackUseAfterReturnMode> ClUseAfterReturn(274"asan-use-after-return",275cl::desc("Sets the mode of detection for stack-use-after-return."),276cl::values(277clEnumValN(AsanDetectStackUseAfterReturnMode::Never, "never",278"Never detect stack use after return."),279clEnumValN(280AsanDetectStackUseAfterReturnMode::Runtime, "runtime",281"Detect stack use after return if "282"binary flag 'ASAN_OPTIONS=detect_stack_use_after_return' is set."),283clEnumValN(AsanDetectStackUseAfterReturnMode::Always, "always",284"Always detect stack use after return.")),285cl::Hidden, cl::init(AsanDetectStackUseAfterReturnMode::Runtime));286287static cl::opt<bool> ClRedzoneByvalArgs("asan-redzone-byval-args",288cl::desc("Create redzones for byval "289"arguments (extra copy "290"required)"), cl::Hidden,291cl::init(true));292293static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",294cl::desc("Check stack-use-after-scope"),295cl::Hidden, cl::init(false));296297// This flag may need to be replaced with -f[no]asan-globals.298static cl::opt<bool> ClGlobals("asan-globals",299cl::desc("Handle global objects"), cl::Hidden,300cl::init(true));301302static cl::opt<bool> ClInitializers("asan-initialization-order",303cl::desc("Handle C++ initializer order"),304cl::Hidden, cl::init(true));305306static cl::opt<bool> ClInvalidPointerPairs(307"asan-detect-invalid-pointer-pair",308cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,309cl::init(false));310311static cl::opt<bool> ClInvalidPointerCmp(312"asan-detect-invalid-pointer-cmp",313cl::desc("Instrument <, <=, >, >= with pointer operands"), cl::Hidden,314cl::init(false));315316static cl::opt<bool> ClInvalidPointerSub(317"asan-detect-invalid-pointer-sub",318cl::desc("Instrument - operations with pointer operands"), cl::Hidden,319cl::init(false));320321static cl::opt<unsigned> ClRealignStack(322"asan-realign-stack",323cl::desc("Realign stack to the value of this flag (power of two)"),324cl::Hidden, cl::init(32));325326static cl::opt<int> ClInstrumentationWithCallsThreshold(327"asan-instrumentation-with-call-threshold",328cl::desc("If the function being instrumented contains more than "329"this number of memory accesses, use callbacks instead of "330"inline checks (-1 means never use callbacks)."),331cl::Hidden, cl::init(7000));332333static cl::opt<std::string> ClMemoryAccessCallbackPrefix(334"asan-memory-access-callback-prefix",335cl::desc("Prefix for memory access callbacks"), cl::Hidden,336cl::init("__asan_"));337338static cl::opt<bool> ClKasanMemIntrinCallbackPrefix(339"asan-kernel-mem-intrinsic-prefix",340cl::desc("Use prefix for memory intrinsics in KASAN mode"), cl::Hidden,341cl::init(false));342343static cl::opt<bool>344ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",345cl::desc("instrument dynamic allocas"),346cl::Hidden, cl::init(true));347348static cl::opt<bool> ClSkipPromotableAllocas(349"asan-skip-promotable-allocas",350cl::desc("Do not instrument promotable allocas"), cl::Hidden,351cl::init(true));352353static cl::opt<AsanCtorKind> ClConstructorKind(354"asan-constructor-kind",355cl::desc("Sets the ASan constructor kind"),356cl::values(clEnumValN(AsanCtorKind::None, "none", "No constructors"),357clEnumValN(AsanCtorKind::Global, "global",358"Use global constructors")),359cl::init(AsanCtorKind::Global), cl::Hidden);360// These flags allow to change the shadow mapping.361// The shadow mapping looks like362// Shadow = (Mem >> scale) + offset363364static cl::opt<int> ClMappingScale("asan-mapping-scale",365cl::desc("scale of asan shadow mapping"),366cl::Hidden, cl::init(0));367368static cl::opt<uint64_t>369ClMappingOffset("asan-mapping-offset",370cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"),371cl::Hidden, cl::init(0));372373// Optimization flags. Not user visible, used mostly for testing374// and benchmarking the tool.375376static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),377cl::Hidden, cl::init(true));378379static cl::opt<bool> ClOptimizeCallbacks("asan-optimize-callbacks",380cl::desc("Optimize callbacks"),381cl::Hidden, cl::init(false));382383static cl::opt<bool> ClOptSameTemp(384"asan-opt-same-temp", cl::desc("Instrument the same temp just once"),385cl::Hidden, cl::init(true));386387static cl::opt<bool> ClOptGlobals("asan-opt-globals",388cl::desc("Don't instrument scalar globals"),389cl::Hidden, cl::init(true));390391static cl::opt<bool> ClOptStack(392"asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),393cl::Hidden, cl::init(false));394395static cl::opt<bool> ClDynamicAllocaStack(396"asan-stack-dynamic-alloca",397cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,398cl::init(true));399400static cl::opt<uint32_t> ClForceExperiment(401"asan-force-experiment",402cl::desc("Force optimization experiment (for testing)"), cl::Hidden,403cl::init(0));404405static cl::opt<bool>406ClUsePrivateAlias("asan-use-private-alias",407cl::desc("Use private aliases for global variables"),408cl::Hidden, cl::init(true));409410static cl::opt<bool>411ClUseOdrIndicator("asan-use-odr-indicator",412cl::desc("Use odr indicators to improve ODR reporting"),413cl::Hidden, cl::init(true));414415static cl::opt<bool>416ClUseGlobalsGC("asan-globals-live-support",417cl::desc("Use linker features to support dead "418"code stripping of globals"),419cl::Hidden, cl::init(true));420421// This is on by default even though there is a bug in gold:422// https://sourceware.org/bugzilla/show_bug.cgi?id=19002423static cl::opt<bool>424ClWithComdat("asan-with-comdat",425cl::desc("Place ASan constructors in comdat sections"),426cl::Hidden, cl::init(true));427428static cl::opt<AsanDtorKind> ClOverrideDestructorKind(429"asan-destructor-kind",430cl::desc("Sets the ASan destructor kind. The default is to use the value "431"provided to the pass constructor"),432cl::values(clEnumValN(AsanDtorKind::None, "none", "No destructors"),433clEnumValN(AsanDtorKind::Global, "global",434"Use global destructors")),435cl::init(AsanDtorKind::Invalid), cl::Hidden);436437// Debug flags.438439static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,440cl::init(0));441442static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),443cl::Hidden, cl::init(0));444445static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,446cl::desc("Debug func"));447448static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),449cl::Hidden, cl::init(-1));450451static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),452cl::Hidden, cl::init(-1));453454STATISTIC(NumInstrumentedReads, "Number of instrumented reads");455STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");456STATISTIC(NumOptimizedAccessesToGlobalVar,457"Number of optimized accesses to global vars");458STATISTIC(NumOptimizedAccessesToStackVar,459"Number of optimized accesses to stack vars");460461namespace {462463/// This struct defines the shadow mapping using the rule:464/// shadow = (mem >> Scale) ADD-or-OR Offset.465/// If InGlobal is true, then466/// extern char __asan_shadow[];467/// shadow = (mem >> Scale) + &__asan_shadow468struct ShadowMapping {469int Scale;470uint64_t Offset;471bool OrShadowOffset;472bool InGlobal;473};474475} // end anonymous namespace476477static ShadowMapping getShadowMapping(const Triple &TargetTriple, int LongSize,478bool IsKasan) {479bool IsAndroid = TargetTriple.isAndroid();480bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS() ||481TargetTriple.isDriverKit();482bool IsMacOS = TargetTriple.isMacOSX();483bool IsFreeBSD = TargetTriple.isOSFreeBSD();484bool IsNetBSD = TargetTriple.isOSNetBSD();485bool IsPS = TargetTriple.isPS();486bool IsLinux = TargetTriple.isOSLinux();487bool IsPPC64 = TargetTriple.getArch() == Triple::ppc64 ||488TargetTriple.getArch() == Triple::ppc64le;489bool IsSystemZ = TargetTriple.getArch() == Triple::systemz;490bool IsX86_64 = TargetTriple.getArch() == Triple::x86_64;491bool IsMIPSN32ABI = TargetTriple.getEnvironment() == Triple::GNUABIN32;492bool IsMIPS32 = TargetTriple.isMIPS32();493bool IsMIPS64 = TargetTriple.isMIPS64();494bool IsArmOrThumb = TargetTriple.isARM() || TargetTriple.isThumb();495bool IsAArch64 = TargetTriple.getArch() == Triple::aarch64 ||496TargetTriple.getArch() == Triple::aarch64_be;497bool IsLoongArch64 = TargetTriple.isLoongArch64();498bool IsRISCV64 = TargetTriple.getArch() == Triple::riscv64;499bool IsWindows = TargetTriple.isOSWindows();500bool IsFuchsia = TargetTriple.isOSFuchsia();501bool IsEmscripten = TargetTriple.isOSEmscripten();502bool IsAMDGPU = TargetTriple.isAMDGPU();503504ShadowMapping Mapping;505506Mapping.Scale = kDefaultShadowScale;507if (ClMappingScale.getNumOccurrences() > 0) {508Mapping.Scale = ClMappingScale;509}510511if (LongSize == 32) {512if (IsAndroid)513Mapping.Offset = kDynamicShadowSentinel;514else if (IsMIPSN32ABI)515Mapping.Offset = kMIPS_ShadowOffsetN32;516else if (IsMIPS32)517Mapping.Offset = kMIPS32_ShadowOffset32;518else if (IsFreeBSD)519Mapping.Offset = kFreeBSD_ShadowOffset32;520else if (IsNetBSD)521Mapping.Offset = kNetBSD_ShadowOffset32;522else if (IsIOS)523Mapping.Offset = kDynamicShadowSentinel;524else if (IsWindows)525Mapping.Offset = kWindowsShadowOffset32;526else if (IsEmscripten)527Mapping.Offset = kEmscriptenShadowOffset;528else529Mapping.Offset = kDefaultShadowOffset32;530} else { // LongSize == 64531// Fuchsia is always PIE, which means that the beginning of the address532// space is always available.533if (IsFuchsia)534Mapping.Offset = 0;535else if (IsPPC64)536Mapping.Offset = kPPC64_ShadowOffset64;537else if (IsSystemZ)538Mapping.Offset = kSystemZ_ShadowOffset64;539else if (IsFreeBSD && IsAArch64)540Mapping.Offset = kFreeBSDAArch64_ShadowOffset64;541else if (IsFreeBSD && !IsMIPS64) {542if (IsKasan)543Mapping.Offset = kFreeBSDKasan_ShadowOffset64;544else545Mapping.Offset = kFreeBSD_ShadowOffset64;546} else if (IsNetBSD) {547if (IsKasan)548Mapping.Offset = kNetBSDKasan_ShadowOffset64;549else550Mapping.Offset = kNetBSD_ShadowOffset64;551} else if (IsPS)552Mapping.Offset = kPS_ShadowOffset64;553else if (IsLinux && IsX86_64) {554if (IsKasan)555Mapping.Offset = kLinuxKasan_ShadowOffset64;556else557Mapping.Offset = (kSmallX86_64ShadowOffsetBase &558(kSmallX86_64ShadowOffsetAlignMask << Mapping.Scale));559} else if (IsWindows && IsX86_64) {560Mapping.Offset = kWindowsShadowOffset64;561} else if (IsMIPS64)562Mapping.Offset = kMIPS64_ShadowOffset64;563else if (IsIOS)564Mapping.Offset = kDynamicShadowSentinel;565else if (IsMacOS && IsAArch64)566Mapping.Offset = kDynamicShadowSentinel;567else if (IsAArch64)568Mapping.Offset = kAArch64_ShadowOffset64;569else if (IsLoongArch64)570Mapping.Offset = kLoongArch64_ShadowOffset64;571else if (IsRISCV64)572Mapping.Offset = kRISCV64_ShadowOffset64;573else if (IsAMDGPU)574Mapping.Offset = (kSmallX86_64ShadowOffsetBase &575(kSmallX86_64ShadowOffsetAlignMask << Mapping.Scale));576else577Mapping.Offset = kDefaultShadowOffset64;578}579580if (ClForceDynamicShadow) {581Mapping.Offset = kDynamicShadowSentinel;582}583584if (ClMappingOffset.getNumOccurrences() > 0) {585Mapping.Offset = ClMappingOffset;586}587588// OR-ing shadow offset if more efficient (at least on x86) if the offset589// is a power of two, but on ppc64 and loongarch64 we have to use add since590// the shadow offset is not necessarily 1/8-th of the address space. On591// SystemZ, we could OR the constant in a single instruction, but it's more592// efficient to load it once and use indexed addressing.593Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ && !IsPS &&594!IsRISCV64 && !IsLoongArch64 &&595!(Mapping.Offset & (Mapping.Offset - 1)) &&596Mapping.Offset != kDynamicShadowSentinel;597bool IsAndroidWithIfuncSupport =598IsAndroid && !TargetTriple.isAndroidVersionLT(21);599Mapping.InGlobal = ClWithIfunc && IsAndroidWithIfuncSupport && IsArmOrThumb;600601return Mapping;602}603604namespace llvm {605void getAddressSanitizerParams(const Triple &TargetTriple, int LongSize,606bool IsKasan, uint64_t *ShadowBase,607int *MappingScale, bool *OrShadowOffset) {608auto Mapping = getShadowMapping(TargetTriple, LongSize, IsKasan);609*ShadowBase = Mapping.Offset;610*MappingScale = Mapping.Scale;611*OrShadowOffset = Mapping.OrShadowOffset;612}613614ASanAccessInfo::ASanAccessInfo(int32_t Packed)615: Packed(Packed),616AccessSizeIndex((Packed >> kAccessSizeIndexShift) & kAccessSizeIndexMask),617IsWrite((Packed >> kIsWriteShift) & kIsWriteMask),618CompileKernel((Packed >> kCompileKernelShift) & kCompileKernelMask) {}619620ASanAccessInfo::ASanAccessInfo(bool IsWrite, bool CompileKernel,621uint8_t AccessSizeIndex)622: Packed((IsWrite << kIsWriteShift) +623(CompileKernel << kCompileKernelShift) +624(AccessSizeIndex << kAccessSizeIndexShift)),625AccessSizeIndex(AccessSizeIndex), IsWrite(IsWrite),626CompileKernel(CompileKernel) {}627628} // namespace llvm629630static uint64_t getRedzoneSizeForScale(int MappingScale) {631// Redzone used for stack and globals is at least 32 bytes.632// For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.633return std::max(32U, 1U << MappingScale);634}635636static uint64_t GetCtorAndDtorPriority(Triple &TargetTriple) {637if (TargetTriple.isOSEmscripten()) {638return kAsanEmscriptenCtorAndDtorPriority;639} else {640return kAsanCtorAndDtorPriority;641}642}643644namespace {645/// Helper RAII class to post-process inserted asan runtime calls during a646/// pass on a single Function. Upon end of scope, detects and applies the647/// required funclet OpBundle.648class RuntimeCallInserter {649Function *OwnerFn = nullptr;650bool TrackInsertedCalls = false;651SmallVector<CallInst *> InsertedCalls;652653public:654RuntimeCallInserter(Function &Fn) : OwnerFn(&Fn) {655if (Fn.hasPersonalityFn()) {656auto Personality = classifyEHPersonality(Fn.getPersonalityFn());657if (isScopedEHPersonality(Personality))658TrackInsertedCalls = true;659}660}661662~RuntimeCallInserter() {663if (InsertedCalls.empty())664return;665assert(TrackInsertedCalls && "Calls were wrongly tracked");666667DenseMap<BasicBlock *, ColorVector> BlockColors = colorEHFunclets(*OwnerFn);668for (CallInst *CI : InsertedCalls) {669BasicBlock *BB = CI->getParent();670assert(BB && "Instruction doesn't belong to a BasicBlock");671assert(BB->getParent() == OwnerFn &&672"Instruction doesn't belong to the expected Function!");673674ColorVector &Colors = BlockColors[BB];675// funclet opbundles are only valid in monochromatic BBs.676// Note that unreachable BBs are seen as colorless by colorEHFunclets()677// and will be DCE'ed later.678if (Colors.empty())679continue;680if (Colors.size() != 1) {681OwnerFn->getContext().emitError(682"Instruction's BasicBlock is not monochromatic");683continue;684}685686BasicBlock *Color = Colors.front();687Instruction *EHPad = Color->getFirstNonPHI();688689if (EHPad && EHPad->isEHPad()) {690// Replace CI with a clone with an added funclet OperandBundle691OperandBundleDef OB("funclet", EHPad);692auto *NewCall =693CallBase::addOperandBundle(CI, LLVMContext::OB_funclet, OB, CI);694NewCall->copyMetadata(*CI);695CI->replaceAllUsesWith(NewCall);696CI->eraseFromParent();697}698}699}700701CallInst *createRuntimeCall(IRBuilder<> &IRB, FunctionCallee Callee,702ArrayRef<Value *> Args = {},703const Twine &Name = "") {704assert(IRB.GetInsertBlock()->getParent() == OwnerFn);705706CallInst *Inst = IRB.CreateCall(Callee, Args, Name, nullptr);707if (TrackInsertedCalls)708InsertedCalls.push_back(Inst);709return Inst;710}711};712713/// AddressSanitizer: instrument the code in module to find memory bugs.714struct AddressSanitizer {715AddressSanitizer(Module &M, const StackSafetyGlobalInfo *SSGI,716int InstrumentationWithCallsThreshold,717uint32_t MaxInlinePoisoningSize, bool CompileKernel = false,718bool Recover = false, bool UseAfterScope = false,719AsanDetectStackUseAfterReturnMode UseAfterReturn =720AsanDetectStackUseAfterReturnMode::Runtime)721: CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan722: CompileKernel),723Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),724UseAfterScope(UseAfterScope || ClUseAfterScope),725UseAfterReturn(ClUseAfterReturn.getNumOccurrences() ? ClUseAfterReturn726: UseAfterReturn),727SSGI(SSGI),728InstrumentationWithCallsThreshold(729ClInstrumentationWithCallsThreshold.getNumOccurrences() > 0730? ClInstrumentationWithCallsThreshold731: InstrumentationWithCallsThreshold),732MaxInlinePoisoningSize(ClMaxInlinePoisoningSize.getNumOccurrences() > 0733? ClMaxInlinePoisoningSize734: MaxInlinePoisoningSize) {735C = &(M.getContext());736DL = &M.getDataLayout();737LongSize = M.getDataLayout().getPointerSizeInBits();738IntptrTy = Type::getIntNTy(*C, LongSize);739PtrTy = PointerType::getUnqual(*C);740Int32Ty = Type::getInt32Ty(*C);741TargetTriple = Triple(M.getTargetTriple());742743Mapping = getShadowMapping(TargetTriple, LongSize, this->CompileKernel);744745assert(this->UseAfterReturn != AsanDetectStackUseAfterReturnMode::Invalid);746}747748TypeSize getAllocaSizeInBytes(const AllocaInst &AI) const {749return *AI.getAllocationSize(AI.getDataLayout());750}751752/// Check if we want (and can) handle this alloca.753bool isInterestingAlloca(const AllocaInst &AI);754755bool ignoreAccess(Instruction *Inst, Value *Ptr);756void getInterestingMemoryOperands(757Instruction *I, SmallVectorImpl<InterestingMemoryOperand> &Interesting);758759void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,760InterestingMemoryOperand &O, bool UseCalls,761const DataLayout &DL, RuntimeCallInserter &RTCI);762void instrumentPointerComparisonOrSubtraction(Instruction *I,763RuntimeCallInserter &RTCI);764void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,765Value *Addr, MaybeAlign Alignment,766uint32_t TypeStoreSize, bool IsWrite,767Value *SizeArgument, bool UseCalls, uint32_t Exp,768RuntimeCallInserter &RTCI);769Instruction *instrumentAMDGPUAddress(Instruction *OrigIns,770Instruction *InsertBefore, Value *Addr,771uint32_t TypeStoreSize, bool IsWrite,772Value *SizeArgument);773Instruction *genAMDGPUReportBlock(IRBuilder<> &IRB, Value *Cond,774bool Recover);775void instrumentUnusualSizeOrAlignment(Instruction *I,776Instruction *InsertBefore, Value *Addr,777TypeSize TypeStoreSize, bool IsWrite,778Value *SizeArgument, bool UseCalls,779uint32_t Exp,780RuntimeCallInserter &RTCI);781void instrumentMaskedLoadOrStore(AddressSanitizer *Pass, const DataLayout &DL,782Type *IntptrTy, Value *Mask, Value *EVL,783Value *Stride, Instruction *I, Value *Addr,784MaybeAlign Alignment, unsigned Granularity,785Type *OpType, bool IsWrite,786Value *SizeArgument, bool UseCalls,787uint32_t Exp, RuntimeCallInserter &RTCI);788Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,789Value *ShadowValue, uint32_t TypeStoreSize);790Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,791bool IsWrite, size_t AccessSizeIndex,792Value *SizeArgument, uint32_t Exp,793RuntimeCallInserter &RTCI);794void instrumentMemIntrinsic(MemIntrinsic *MI, RuntimeCallInserter &RTCI);795Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);796bool suppressInstrumentationSiteForDebug(int &Instrumented);797bool instrumentFunction(Function &F, const TargetLibraryInfo *TLI);798bool maybeInsertAsanInitAtFunctionEntry(Function &F);799bool maybeInsertDynamicShadowAtFunctionEntry(Function &F);800void markEscapedLocalAllocas(Function &F);801802private:803friend struct FunctionStackPoisoner;804805void initializeCallbacks(Module &M, const TargetLibraryInfo *TLI);806807bool LooksLikeCodeInBug11395(Instruction *I);808bool GlobalIsLinkerInitialized(GlobalVariable *G);809bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,810TypeSize TypeStoreSize) const;811812/// Helper to cleanup per-function state.813struct FunctionStateRAII {814AddressSanitizer *Pass;815816FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {817assert(Pass->ProcessedAllocas.empty() &&818"last pass forgot to clear cache");819assert(!Pass->LocalDynamicShadow);820}821822~FunctionStateRAII() {823Pass->LocalDynamicShadow = nullptr;824Pass->ProcessedAllocas.clear();825}826};827828LLVMContext *C;829const DataLayout *DL;830Triple TargetTriple;831int LongSize;832bool CompileKernel;833bool Recover;834bool UseAfterScope;835AsanDetectStackUseAfterReturnMode UseAfterReturn;836Type *IntptrTy;837Type *Int32Ty;838PointerType *PtrTy;839ShadowMapping Mapping;840FunctionCallee AsanHandleNoReturnFunc;841FunctionCallee AsanPtrCmpFunction, AsanPtrSubFunction;842Constant *AsanShadowGlobal;843844// These arrays is indexed by AccessIsWrite, Experiment and log2(AccessSize).845FunctionCallee AsanErrorCallback[2][2][kNumberOfAccessSizes];846FunctionCallee AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];847848// These arrays is indexed by AccessIsWrite and Experiment.849FunctionCallee AsanErrorCallbackSized[2][2];850FunctionCallee AsanMemoryAccessCallbackSized[2][2];851852FunctionCallee AsanMemmove, AsanMemcpy, AsanMemset;853Value *LocalDynamicShadow = nullptr;854const StackSafetyGlobalInfo *SSGI;855DenseMap<const AllocaInst *, bool> ProcessedAllocas;856857FunctionCallee AMDGPUAddressShared;858FunctionCallee AMDGPUAddressPrivate;859int InstrumentationWithCallsThreshold;860uint32_t MaxInlinePoisoningSize;861};862863class ModuleAddressSanitizer {864public:865ModuleAddressSanitizer(Module &M, bool InsertVersionCheck,866bool CompileKernel = false, bool Recover = false,867bool UseGlobalsGC = true, bool UseOdrIndicator = true,868AsanDtorKind DestructorKind = AsanDtorKind::Global,869AsanCtorKind ConstructorKind = AsanCtorKind::Global)870: CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan871: CompileKernel),872InsertVersionCheck(ClInsertVersionCheck.getNumOccurrences() > 0873? ClInsertVersionCheck874: InsertVersionCheck),875Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),876UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC && !this->CompileKernel),877// Enable aliases as they should have no downside with ODR indicators.878UsePrivateAlias(ClUsePrivateAlias.getNumOccurrences() > 0879? ClUsePrivateAlias880: UseOdrIndicator),881UseOdrIndicator(ClUseOdrIndicator.getNumOccurrences() > 0882? ClUseOdrIndicator883: UseOdrIndicator),884// Not a typo: ClWithComdat is almost completely pointless without885// ClUseGlobalsGC (because then it only works on modules without886// globals, which are rare); it is a prerequisite for ClUseGlobalsGC;887// and both suffer from gold PR19002 for which UseGlobalsGC constructor888// argument is designed as workaround. Therefore, disable both889// ClWithComdat and ClUseGlobalsGC unless the frontend says it's ok to890// do globals-gc.891UseCtorComdat(UseGlobalsGC && ClWithComdat && !this->CompileKernel),892DestructorKind(DestructorKind),893ConstructorKind(ClConstructorKind.getNumOccurrences() > 0894? ClConstructorKind895: ConstructorKind) {896C = &(M.getContext());897int LongSize = M.getDataLayout().getPointerSizeInBits();898IntptrTy = Type::getIntNTy(*C, LongSize);899PtrTy = PointerType::getUnqual(*C);900TargetTriple = Triple(M.getTargetTriple());901Mapping = getShadowMapping(TargetTriple, LongSize, this->CompileKernel);902903if (ClOverrideDestructorKind != AsanDtorKind::Invalid)904this->DestructorKind = ClOverrideDestructorKind;905assert(this->DestructorKind != AsanDtorKind::Invalid);906}907908bool instrumentModule(Module &);909910private:911void initializeCallbacks(Module &M);912913void instrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat);914void InstrumentGlobalsCOFF(IRBuilder<> &IRB, Module &M,915ArrayRef<GlobalVariable *> ExtendedGlobals,916ArrayRef<Constant *> MetadataInitializers);917void instrumentGlobalsELF(IRBuilder<> &IRB, Module &M,918ArrayRef<GlobalVariable *> ExtendedGlobals,919ArrayRef<Constant *> MetadataInitializers,920const std::string &UniqueModuleId);921void InstrumentGlobalsMachO(IRBuilder<> &IRB, Module &M,922ArrayRef<GlobalVariable *> ExtendedGlobals,923ArrayRef<Constant *> MetadataInitializers);924void925InstrumentGlobalsWithMetadataArray(IRBuilder<> &IRB, Module &M,926ArrayRef<GlobalVariable *> ExtendedGlobals,927ArrayRef<Constant *> MetadataInitializers);928929GlobalVariable *CreateMetadataGlobal(Module &M, Constant *Initializer,930StringRef OriginalName);931void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata,932StringRef InternalSuffix);933Instruction *CreateAsanModuleDtor(Module &M);934935const GlobalVariable *getExcludedAliasedGlobal(const GlobalAlias &GA) const;936bool shouldInstrumentGlobal(GlobalVariable *G) const;937bool ShouldUseMachOGlobalsSection() const;938StringRef getGlobalMetadataSection() const;939void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);940void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);941uint64_t getMinRedzoneSizeForGlobal() const {942return getRedzoneSizeForScale(Mapping.Scale);943}944uint64_t getRedzoneSizeForGlobal(uint64_t SizeInBytes) const;945int GetAsanVersion(const Module &M) const;946947bool CompileKernel;948bool InsertVersionCheck;949bool Recover;950bool UseGlobalsGC;951bool UsePrivateAlias;952bool UseOdrIndicator;953bool UseCtorComdat;954AsanDtorKind DestructorKind;955AsanCtorKind ConstructorKind;956Type *IntptrTy;957PointerType *PtrTy;958LLVMContext *C;959Triple TargetTriple;960ShadowMapping Mapping;961FunctionCallee AsanPoisonGlobals;962FunctionCallee AsanUnpoisonGlobals;963FunctionCallee AsanRegisterGlobals;964FunctionCallee AsanUnregisterGlobals;965FunctionCallee AsanRegisterImageGlobals;966FunctionCallee AsanUnregisterImageGlobals;967FunctionCallee AsanRegisterElfGlobals;968FunctionCallee AsanUnregisterElfGlobals;969970Function *AsanCtorFunction = nullptr;971Function *AsanDtorFunction = nullptr;972};973974// Stack poisoning does not play well with exception handling.975// When an exception is thrown, we essentially bypass the code976// that unpoisones the stack. This is why the run-time library has977// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire978// stack in the interceptor. This however does not work inside the979// actual function which catches the exception. Most likely because the980// compiler hoists the load of the shadow value somewhere too high.981// This causes asan to report a non-existing bug on 453.povray.982// It sounds like an LLVM bug.983struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {984Function &F;985AddressSanitizer &ASan;986RuntimeCallInserter &RTCI;987DIBuilder DIB;988LLVMContext *C;989Type *IntptrTy;990Type *IntptrPtrTy;991ShadowMapping Mapping;992993SmallVector<AllocaInst *, 16> AllocaVec;994SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;995SmallVector<Instruction *, 8> RetVec;996997FunctionCallee AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],998AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];999FunctionCallee AsanSetShadowFunc[0x100] = {};1000FunctionCallee AsanPoisonStackMemoryFunc, AsanUnpoisonStackMemoryFunc;1001FunctionCallee AsanAllocaPoisonFunc, AsanAllocasUnpoisonFunc;10021003// Stores a place and arguments of poisoning/unpoisoning call for alloca.1004struct AllocaPoisonCall {1005IntrinsicInst *InsBefore;1006AllocaInst *AI;1007uint64_t Size;1008bool DoPoison;1009};1010SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;1011SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;1012bool HasUntracedLifetimeIntrinsic = false;10131014SmallVector<AllocaInst *, 1> DynamicAllocaVec;1015SmallVector<IntrinsicInst *, 1> StackRestoreVec;1016AllocaInst *DynamicAllocaLayout = nullptr;1017IntrinsicInst *LocalEscapeCall = nullptr;10181019bool HasInlineAsm = false;1020bool HasReturnsTwiceCall = false;1021bool PoisonStack;10221023FunctionStackPoisoner(Function &F, AddressSanitizer &ASan,1024RuntimeCallInserter &RTCI)1025: F(F), ASan(ASan), RTCI(RTCI),1026DIB(*F.getParent(), /*AllowUnresolved*/ false), C(ASan.C),1027IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),1028Mapping(ASan.Mapping),1029PoisonStack(ClStack &&1030!Triple(F.getParent()->getTargetTriple()).isAMDGPU()) {}10311032bool runOnFunction() {1033if (!PoisonStack)1034return false;10351036if (ClRedzoneByvalArgs)1037copyArgsPassedByValToAllocas();10381039// Collect alloca, ret, lifetime instructions etc.1040for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);10411042if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;10431044initializeCallbacks(*F.getParent());10451046if (HasUntracedLifetimeIntrinsic) {1047// If there are lifetime intrinsics which couldn't be traced back to an1048// alloca, we may not know exactly when a variable enters scope, and1049// therefore should "fail safe" by not poisoning them.1050StaticAllocaPoisonCallVec.clear();1051DynamicAllocaPoisonCallVec.clear();1052}10531054processDynamicAllocas();1055processStaticAllocas();10561057if (ClDebugStack) {1058LLVM_DEBUG(dbgs() << F);1059}1060return true;1061}10621063// Arguments marked with the "byval" attribute are implicitly copied without1064// using an alloca instruction. To produce redzones for those arguments, we1065// copy them a second time into memory allocated with an alloca instruction.1066void copyArgsPassedByValToAllocas();10671068// Finds all Alloca instructions and puts1069// poisoned red zones around all of them.1070// Then unpoison everything back before the function returns.1071void processStaticAllocas();1072void processDynamicAllocas();10731074void createDynamicAllocasInitStorage();10751076// ----------------------- Visitors.1077/// Collect all Ret instructions, or the musttail call instruction if it1078/// precedes the return instruction.1079void visitReturnInst(ReturnInst &RI) {1080if (CallInst *CI = RI.getParent()->getTerminatingMustTailCall())1081RetVec.push_back(CI);1082else1083RetVec.push_back(&RI);1084}10851086/// Collect all Resume instructions.1087void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }10881089/// Collect all CatchReturnInst instructions.1090void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }10911092void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,1093Value *SavedStack) {1094IRBuilder<> IRB(InstBefore);1095Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);1096// When we insert _asan_allocas_unpoison before @llvm.stackrestore, we1097// need to adjust extracted SP to compute the address of the most recent1098// alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for1099// this purpose.1100if (!isa<ReturnInst>(InstBefore)) {1101Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(1102InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,1103{IntptrTy});11041105Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});11061107DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),1108DynamicAreaOffset);1109}11101111RTCI.createRuntimeCall(1112IRB, AsanAllocasUnpoisonFunc,1113{IRB.CreateLoad(IntptrTy, DynamicAllocaLayout), DynamicAreaPtr});1114}11151116// Unpoison dynamic allocas redzones.1117void unpoisonDynamicAllocas() {1118for (Instruction *Ret : RetVec)1119unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);11201121for (Instruction *StackRestoreInst : StackRestoreVec)1122unpoisonDynamicAllocasBeforeInst(StackRestoreInst,1123StackRestoreInst->getOperand(0));1124}11251126// Deploy and poison redzones around dynamic alloca call. To do this, we1127// should replace this call with another one with changed parameters and1128// replace all its uses with new address, so1129// addr = alloca type, old_size, align1130// is replaced by1131// new_size = (old_size + additional_size) * sizeof(type)1132// tmp = alloca i8, new_size, max(align, 32)1133// addr = tmp + 32 (first 32 bytes are for the left redzone).1134// Additional_size is added to make new memory allocation contain not only1135// requested memory, but also left, partial and right redzones.1136void handleDynamicAllocaCall(AllocaInst *AI);11371138/// Collect Alloca instructions we want (and can) handle.1139void visitAllocaInst(AllocaInst &AI) {1140// FIXME: Handle scalable vectors instead of ignoring them.1141const Type *AllocaType = AI.getAllocatedType();1142const auto *STy = dyn_cast<StructType>(AllocaType);1143if (!ASan.isInterestingAlloca(AI) || isa<ScalableVectorType>(AllocaType) ||1144(STy && STy->containsHomogeneousScalableVectorTypes())) {1145if (AI.isStaticAlloca()) {1146// Skip over allocas that are present *before* the first instrumented1147// alloca, we don't want to move those around.1148if (AllocaVec.empty())1149return;11501151StaticAllocasToMoveUp.push_back(&AI);1152}1153return;1154}11551156if (!AI.isStaticAlloca())1157DynamicAllocaVec.push_back(&AI);1158else1159AllocaVec.push_back(&AI);1160}11611162/// Collect lifetime intrinsic calls to check for use-after-scope1163/// errors.1164void visitIntrinsicInst(IntrinsicInst &II) {1165Intrinsic::ID ID = II.getIntrinsicID();1166if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);1167if (ID == Intrinsic::localescape) LocalEscapeCall = &II;1168if (!ASan.UseAfterScope)1169return;1170if (!II.isLifetimeStartOrEnd())1171return;1172// Found lifetime intrinsic, add ASan instrumentation if necessary.1173auto *Size = cast<ConstantInt>(II.getArgOperand(0));1174// If size argument is undefined, don't do anything.1175if (Size->isMinusOne()) return;1176// Check that size doesn't saturate uint64_t and can1177// be stored in IntptrTy.1178const uint64_t SizeValue = Size->getValue().getLimitedValue();1179if (SizeValue == ~0ULL ||1180!ConstantInt::isValueValidForType(IntptrTy, SizeValue))1181return;1182// Find alloca instruction that corresponds to llvm.lifetime argument.1183// Currently we can only handle lifetime markers pointing to the1184// beginning of the alloca.1185AllocaInst *AI = findAllocaForValue(II.getArgOperand(1), true);1186if (!AI) {1187HasUntracedLifetimeIntrinsic = true;1188return;1189}1190// We're interested only in allocas we can handle.1191if (!ASan.isInterestingAlloca(*AI))1192return;1193bool DoPoison = (ID == Intrinsic::lifetime_end);1194AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};1195if (AI->isStaticAlloca())1196StaticAllocaPoisonCallVec.push_back(APC);1197else if (ClInstrumentDynamicAllocas)1198DynamicAllocaPoisonCallVec.push_back(APC);1199}12001201void visitCallBase(CallBase &CB) {1202if (CallInst *CI = dyn_cast<CallInst>(&CB)) {1203HasInlineAsm |= CI->isInlineAsm() && &CB != ASan.LocalDynamicShadow;1204HasReturnsTwiceCall |= CI->canReturnTwice();1205}1206}12071208// ---------------------- Helpers.1209void initializeCallbacks(Module &M);12101211// Copies bytes from ShadowBytes into shadow memory for indexes where1212// ShadowMask is not zero. If ShadowMask[i] is zero, we assume that1213// ShadowBytes[i] is constantly zero and doesn't need to be overwritten.1214void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,1215IRBuilder<> &IRB, Value *ShadowBase);1216void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,1217size_t Begin, size_t End, IRBuilder<> &IRB,1218Value *ShadowBase);1219void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,1220ArrayRef<uint8_t> ShadowBytes, size_t Begin,1221size_t End, IRBuilder<> &IRB, Value *ShadowBase);12221223void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);12241225Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,1226bool Dynamic);1227PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,1228Instruction *ThenTerm, Value *ValueIfFalse);1229};12301231} // end anonymous namespace12321233void AddressSanitizerPass::printPipeline(1234raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {1235static_cast<PassInfoMixin<AddressSanitizerPass> *>(this)->printPipeline(1236OS, MapClassName2PassName);1237OS << '<';1238if (Options.CompileKernel)1239OS << "kernel";1240OS << '>';1241}12421243AddressSanitizerPass::AddressSanitizerPass(1244const AddressSanitizerOptions &Options, bool UseGlobalGC,1245bool UseOdrIndicator, AsanDtorKind DestructorKind,1246AsanCtorKind ConstructorKind)1247: Options(Options), UseGlobalGC(UseGlobalGC),1248UseOdrIndicator(UseOdrIndicator), DestructorKind(DestructorKind),1249ConstructorKind(ConstructorKind) {}12501251PreservedAnalyses AddressSanitizerPass::run(Module &M,1252ModuleAnalysisManager &MAM) {1253ModuleAddressSanitizer ModuleSanitizer(1254M, Options.InsertVersionCheck, Options.CompileKernel, Options.Recover,1255UseGlobalGC, UseOdrIndicator, DestructorKind, ConstructorKind);1256bool Modified = false;1257auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();1258const StackSafetyGlobalInfo *const SSGI =1259ClUseStackSafety ? &MAM.getResult<StackSafetyGlobalAnalysis>(M) : nullptr;1260for (Function &F : M) {1261AddressSanitizer FunctionSanitizer(1262M, SSGI, Options.InstrumentationWithCallsThreshold,1263Options.MaxInlinePoisoningSize, Options.CompileKernel, Options.Recover,1264Options.UseAfterScope, Options.UseAfterReturn);1265const TargetLibraryInfo &TLI = FAM.getResult<TargetLibraryAnalysis>(F);1266Modified |= FunctionSanitizer.instrumentFunction(F, &TLI);1267}1268Modified |= ModuleSanitizer.instrumentModule(M);1269if (!Modified)1270return PreservedAnalyses::all();12711272PreservedAnalyses PA = PreservedAnalyses::none();1273// GlobalsAA is considered stateless and does not get invalidated unless1274// explicitly invalidated; PreservedAnalyses::none() is not enough. Sanitizers1275// make changes that require GlobalsAA to be invalidated.1276PA.abandon<GlobalsAA>();1277return PA;1278}12791280static size_t TypeStoreSizeToSizeIndex(uint32_t TypeSize) {1281size_t Res = llvm::countr_zero(TypeSize / 8);1282assert(Res < kNumberOfAccessSizes);1283return Res;1284}12851286/// Check if \p G has been created by a trusted compiler pass.1287static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {1288// Do not instrument @llvm.global_ctors, @llvm.used, etc.1289if (G->getName().starts_with("llvm.") ||1290// Do not instrument gcov counter arrays.1291G->getName().starts_with("__llvm_gcov_ctr") ||1292// Do not instrument rtti proxy symbols for function sanitizer.1293G->getName().starts_with("__llvm_rtti_proxy"))1294return true;12951296// Do not instrument asan globals.1297if (G->getName().starts_with(kAsanGenPrefix) ||1298G->getName().starts_with(kSanCovGenPrefix) ||1299G->getName().starts_with(kODRGenPrefix))1300return true;13011302return false;1303}13041305static bool isUnsupportedAMDGPUAddrspace(Value *Addr) {1306Type *PtrTy = cast<PointerType>(Addr->getType()->getScalarType());1307unsigned int AddrSpace = PtrTy->getPointerAddressSpace();1308if (AddrSpace == 3 || AddrSpace == 5)1309return true;1310return false;1311}13121313Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {1314// Shadow >> scale1315Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);1316if (Mapping.Offset == 0) return Shadow;1317// (Shadow >> scale) | offset1318Value *ShadowBase;1319if (LocalDynamicShadow)1320ShadowBase = LocalDynamicShadow;1321else1322ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);1323if (Mapping.OrShadowOffset)1324return IRB.CreateOr(Shadow, ShadowBase);1325else1326return IRB.CreateAdd(Shadow, ShadowBase);1327}13281329// Instrument memset/memmove/memcpy1330void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI,1331RuntimeCallInserter &RTCI) {1332InstrumentationIRBuilder IRB(MI);1333if (isa<MemTransferInst>(MI)) {1334RTCI.createRuntimeCall(1335IRB, isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,1336{IRB.CreateAddrSpaceCast(MI->getOperand(0), PtrTy),1337IRB.CreateAddrSpaceCast(MI->getOperand(1), PtrTy),1338IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});1339} else if (isa<MemSetInst>(MI)) {1340RTCI.createRuntimeCall(1341IRB, AsanMemset,1342{IRB.CreateAddrSpaceCast(MI->getOperand(0), PtrTy),1343IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),1344IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});1345}1346MI->eraseFromParent();1347}13481349/// Check if we want (and can) handle this alloca.1350bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {1351auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);13521353if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())1354return PreviouslySeenAllocaInfo->getSecond();13551356bool IsInteresting =1357(AI.getAllocatedType()->isSized() &&1358// alloca() may be called with 0 size, ignore it.1359((!AI.isStaticAlloca()) || !getAllocaSizeInBytes(AI).isZero()) &&1360// We are only interested in allocas not promotable to registers.1361// Promotable allocas are common under -O0.1362(!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&1363// inalloca allocas are not treated as static, and we don't want1364// dynamic alloca instrumentation for them as well.1365!AI.isUsedWithInAlloca() &&1366// swifterror allocas are register promoted by ISel1367!AI.isSwiftError() &&1368// safe allocas are not interesting1369!(SSGI && SSGI->isSafe(AI)));13701371ProcessedAllocas[&AI] = IsInteresting;1372return IsInteresting;1373}13741375bool AddressSanitizer::ignoreAccess(Instruction *Inst, Value *Ptr) {1376// Instrument accesses from different address spaces only for AMDGPU.1377Type *PtrTy = cast<PointerType>(Ptr->getType()->getScalarType());1378if (PtrTy->getPointerAddressSpace() != 0 &&1379!(TargetTriple.isAMDGPU() && !isUnsupportedAMDGPUAddrspace(Ptr)))1380return true;13811382// Ignore swifterror addresses.1383// swifterror memory addresses are mem2reg promoted by instruction1384// selection. As such they cannot have regular uses like an instrumentation1385// function and it makes no sense to track them as memory.1386if (Ptr->isSwiftError())1387return true;13881389// Treat memory accesses to promotable allocas as non-interesting since they1390// will not cause memory violations. This greatly speeds up the instrumented1391// executable at -O0.1392if (auto AI = dyn_cast_or_null<AllocaInst>(Ptr))1393if (ClSkipPromotableAllocas && !isInterestingAlloca(*AI))1394return true;13951396if (SSGI != nullptr && SSGI->stackAccessIsSafe(*Inst) &&1397findAllocaForValue(Ptr))1398return true;13991400return false;1401}14021403void AddressSanitizer::getInterestingMemoryOperands(1404Instruction *I, SmallVectorImpl<InterestingMemoryOperand> &Interesting) {1405// Do not instrument the load fetching the dynamic shadow address.1406if (LocalDynamicShadow == I)1407return;14081409if (LoadInst *LI = dyn_cast<LoadInst>(I)) {1410if (!ClInstrumentReads || ignoreAccess(I, LI->getPointerOperand()))1411return;1412Interesting.emplace_back(I, LI->getPointerOperandIndex(), false,1413LI->getType(), LI->getAlign());1414} else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {1415if (!ClInstrumentWrites || ignoreAccess(I, SI->getPointerOperand()))1416return;1417Interesting.emplace_back(I, SI->getPointerOperandIndex(), true,1418SI->getValueOperand()->getType(), SI->getAlign());1419} else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {1420if (!ClInstrumentAtomics || ignoreAccess(I, RMW->getPointerOperand()))1421return;1422Interesting.emplace_back(I, RMW->getPointerOperandIndex(), true,1423RMW->getValOperand()->getType(), std::nullopt);1424} else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {1425if (!ClInstrumentAtomics || ignoreAccess(I, XCHG->getPointerOperand()))1426return;1427Interesting.emplace_back(I, XCHG->getPointerOperandIndex(), true,1428XCHG->getCompareOperand()->getType(),1429std::nullopt);1430} else if (auto CI = dyn_cast<CallInst>(I)) {1431switch (CI->getIntrinsicID()) {1432case Intrinsic::masked_load:1433case Intrinsic::masked_store:1434case Intrinsic::masked_gather:1435case Intrinsic::masked_scatter: {1436bool IsWrite = CI->getType()->isVoidTy();1437// Masked store has an initial operand for the value.1438unsigned OpOffset = IsWrite ? 1 : 0;1439if (IsWrite ? !ClInstrumentWrites : !ClInstrumentReads)1440return;14411442auto BasePtr = CI->getOperand(OpOffset);1443if (ignoreAccess(I, BasePtr))1444return;1445Type *Ty = IsWrite ? CI->getArgOperand(0)->getType() : CI->getType();1446MaybeAlign Alignment = Align(1);1447// Otherwise no alignment guarantees. We probably got Undef.1448if (auto *Op = dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))1449Alignment = Op->getMaybeAlignValue();1450Value *Mask = CI->getOperand(2 + OpOffset);1451Interesting.emplace_back(I, OpOffset, IsWrite, Ty, Alignment, Mask);1452break;1453}1454case Intrinsic::masked_expandload:1455case Intrinsic::masked_compressstore: {1456bool IsWrite = CI->getIntrinsicID() == Intrinsic::masked_compressstore;1457unsigned OpOffset = IsWrite ? 1 : 0;1458if (IsWrite ? !ClInstrumentWrites : !ClInstrumentReads)1459return;1460auto BasePtr = CI->getOperand(OpOffset);1461if (ignoreAccess(I, BasePtr))1462return;1463MaybeAlign Alignment = BasePtr->getPointerAlignment(*DL);1464Type *Ty = IsWrite ? CI->getArgOperand(0)->getType() : CI->getType();14651466IRBuilder IB(I);1467Value *Mask = CI->getOperand(1 + OpOffset);1468// Use the popcount of Mask as the effective vector length.1469Type *ExtTy = VectorType::get(IntptrTy, cast<VectorType>(Ty));1470Value *ExtMask = IB.CreateZExt(Mask, ExtTy);1471Value *EVL = IB.CreateAddReduce(ExtMask);1472Value *TrueMask = ConstantInt::get(Mask->getType(), 1);1473Interesting.emplace_back(I, OpOffset, IsWrite, Ty, Alignment, TrueMask,1474EVL);1475break;1476}1477case Intrinsic::vp_load:1478case Intrinsic::vp_store:1479case Intrinsic::experimental_vp_strided_load:1480case Intrinsic::experimental_vp_strided_store: {1481auto *VPI = cast<VPIntrinsic>(CI);1482unsigned IID = CI->getIntrinsicID();1483bool IsWrite = CI->getType()->isVoidTy();1484if (IsWrite ? !ClInstrumentWrites : !ClInstrumentReads)1485return;1486unsigned PtrOpNo = *VPI->getMemoryPointerParamPos(IID);1487Type *Ty = IsWrite ? CI->getArgOperand(0)->getType() : CI->getType();1488MaybeAlign Alignment = VPI->getOperand(PtrOpNo)->getPointerAlignment(*DL);1489Value *Stride = nullptr;1490if (IID == Intrinsic::experimental_vp_strided_store ||1491IID == Intrinsic::experimental_vp_strided_load) {1492Stride = VPI->getOperand(PtrOpNo + 1);1493// Use the pointer alignment as the element alignment if the stride is a1494// mutiple of the pointer alignment. Otherwise, the element alignment1495// should be Align(1).1496unsigned PointerAlign = Alignment.valueOrOne().value();1497if (!isa<ConstantInt>(Stride) ||1498cast<ConstantInt>(Stride)->getZExtValue() % PointerAlign != 0)1499Alignment = Align(1);1500}1501Interesting.emplace_back(I, PtrOpNo, IsWrite, Ty, Alignment,1502VPI->getMaskParam(), VPI->getVectorLengthParam(),1503Stride);1504break;1505}1506case Intrinsic::vp_gather:1507case Intrinsic::vp_scatter: {1508auto *VPI = cast<VPIntrinsic>(CI);1509unsigned IID = CI->getIntrinsicID();1510bool IsWrite = IID == Intrinsic::vp_scatter;1511if (IsWrite ? !ClInstrumentWrites : !ClInstrumentReads)1512return;1513unsigned PtrOpNo = *VPI->getMemoryPointerParamPos(IID);1514Type *Ty = IsWrite ? CI->getArgOperand(0)->getType() : CI->getType();1515MaybeAlign Alignment = VPI->getPointerAlignment();1516Interesting.emplace_back(I, PtrOpNo, IsWrite, Ty, Alignment,1517VPI->getMaskParam(),1518VPI->getVectorLengthParam());1519break;1520}1521default:1522for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ArgNo++) {1523if (!ClInstrumentByval || !CI->isByValArgument(ArgNo) ||1524ignoreAccess(I, CI->getArgOperand(ArgNo)))1525continue;1526Type *Ty = CI->getParamByValType(ArgNo);1527Interesting.emplace_back(I, ArgNo, false, Ty, Align(1));1528}1529}1530}1531}15321533static bool isPointerOperand(Value *V) {1534return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);1535}15361537// This is a rough heuristic; it may cause both false positives and1538// false negatives. The proper implementation requires cooperation with1539// the frontend.1540static bool isInterestingPointerComparison(Instruction *I) {1541if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {1542if (!Cmp->isRelational())1543return false;1544} else {1545return false;1546}1547return isPointerOperand(I->getOperand(0)) &&1548isPointerOperand(I->getOperand(1));1549}15501551// This is a rough heuristic; it may cause both false positives and1552// false negatives. The proper implementation requires cooperation with1553// the frontend.1554static bool isInterestingPointerSubtraction(Instruction *I) {1555if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {1556if (BO->getOpcode() != Instruction::Sub)1557return false;1558} else {1559return false;1560}1561return isPointerOperand(I->getOperand(0)) &&1562isPointerOperand(I->getOperand(1));1563}15641565bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {1566// If a global variable does not have dynamic initialization we don't1567// have to instrument it. However, if a global does not have initializer1568// at all, we assume it has dynamic initializer (in other TU).1569if (!G->hasInitializer())1570return false;15711572if (G->hasSanitizerMetadata() && G->getSanitizerMetadata().IsDynInit)1573return false;15741575return true;1576}15771578void AddressSanitizer::instrumentPointerComparisonOrSubtraction(1579Instruction *I, RuntimeCallInserter &RTCI) {1580IRBuilder<> IRB(I);1581FunctionCallee F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;1582Value *Param[2] = {I->getOperand(0), I->getOperand(1)};1583for (Value *&i : Param) {1584if (i->getType()->isPointerTy())1585i = IRB.CreatePointerCast(i, IntptrTy);1586}1587RTCI.createRuntimeCall(IRB, F, Param);1588}15891590static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,1591Instruction *InsertBefore, Value *Addr,1592MaybeAlign Alignment, unsigned Granularity,1593TypeSize TypeStoreSize, bool IsWrite,1594Value *SizeArgument, bool UseCalls,1595uint32_t Exp, RuntimeCallInserter &RTCI) {1596// Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check1597// if the data is properly aligned.1598if (!TypeStoreSize.isScalable()) {1599const auto FixedSize = TypeStoreSize.getFixedValue();1600switch (FixedSize) {1601case 8:1602case 16:1603case 32:1604case 64:1605case 128:1606if (!Alignment || *Alignment >= Granularity ||1607*Alignment >= FixedSize / 8)1608return Pass->instrumentAddress(I, InsertBefore, Addr, Alignment,1609FixedSize, IsWrite, nullptr, UseCalls,1610Exp, RTCI);1611}1612}1613Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeStoreSize,1614IsWrite, nullptr, UseCalls, Exp, RTCI);1615}16161617void AddressSanitizer::instrumentMaskedLoadOrStore(1618AddressSanitizer *Pass, const DataLayout &DL, Type *IntptrTy, Value *Mask,1619Value *EVL, Value *Stride, Instruction *I, Value *Addr,1620MaybeAlign Alignment, unsigned Granularity, Type *OpType, bool IsWrite,1621Value *SizeArgument, bool UseCalls, uint32_t Exp,1622RuntimeCallInserter &RTCI) {1623auto *VTy = cast<VectorType>(OpType);1624TypeSize ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());1625auto Zero = ConstantInt::get(IntptrTy, 0);16261627IRBuilder IB(I);1628Instruction *LoopInsertBefore = I;1629if (EVL) {1630// The end argument of SplitBlockAndInsertForLane is assumed bigger1631// than zero, so we should check whether EVL is zero here.1632Type *EVLType = EVL->getType();1633Value *IsEVLZero = IB.CreateICmpNE(EVL, ConstantInt::get(EVLType, 0));1634LoopInsertBefore = SplitBlockAndInsertIfThen(IsEVLZero, I, false);1635IB.SetInsertPoint(LoopInsertBefore);1636// Cast EVL to IntptrTy.1637EVL = IB.CreateZExtOrTrunc(EVL, IntptrTy);1638// To avoid undefined behavior for extracting with out of range index, use1639// the minimum of evl and element count as trip count.1640Value *EC = IB.CreateElementCount(IntptrTy, VTy->getElementCount());1641EVL = IB.CreateBinaryIntrinsic(Intrinsic::umin, EVL, EC);1642} else {1643EVL = IB.CreateElementCount(IntptrTy, VTy->getElementCount());1644}16451646// Cast Stride to IntptrTy.1647if (Stride)1648Stride = IB.CreateZExtOrTrunc(Stride, IntptrTy);16491650SplitBlockAndInsertForEachLane(EVL, LoopInsertBefore,1651[&](IRBuilderBase &IRB, Value *Index) {1652Value *MaskElem = IRB.CreateExtractElement(Mask, Index);1653if (auto *MaskElemC = dyn_cast<ConstantInt>(MaskElem)) {1654if (MaskElemC->isZero())1655// No check1656return;1657// Unconditional check1658} else {1659// Conditional check1660Instruction *ThenTerm = SplitBlockAndInsertIfThen(1661MaskElem, &*IRB.GetInsertPoint(), false);1662IRB.SetInsertPoint(ThenTerm);1663}16641665Value *InstrumentedAddress;1666if (isa<VectorType>(Addr->getType())) {1667assert(1668cast<VectorType>(Addr->getType())->getElementType()->isPointerTy() &&1669"Expected vector of pointer.");1670InstrumentedAddress = IRB.CreateExtractElement(Addr, Index);1671} else if (Stride) {1672Index = IRB.CreateMul(Index, Stride);1673InstrumentedAddress = IRB.CreatePtrAdd(Addr, Index);1674} else {1675InstrumentedAddress = IRB.CreateGEP(VTy, Addr, {Zero, Index});1676}1677doInstrumentAddress(Pass, I, &*IRB.GetInsertPoint(), InstrumentedAddress,1678Alignment, Granularity, ElemTypeSize, IsWrite,1679SizeArgument, UseCalls, Exp, RTCI);1680});1681}16821683void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,1684InterestingMemoryOperand &O, bool UseCalls,1685const DataLayout &DL,1686RuntimeCallInserter &RTCI) {1687Value *Addr = O.getPtr();16881689// Optimization experiments.1690// The experiments can be used to evaluate potential optimizations that remove1691// instrumentation (assess false negatives). Instead of completely removing1692// some instrumentation, you set Exp to a non-zero value (mask of optimization1693// experiments that want to remove instrumentation of this instruction).1694// If Exp is non-zero, this pass will emit special calls into runtime1695// (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls1696// make runtime terminate the program in a special way (with a different1697// exit status). Then you run the new compiler on a buggy corpus, collect1698// the special terminations (ideally, you don't see them at all -- no false1699// negatives) and make the decision on the optimization.1700uint32_t Exp = ClForceExperiment;17011702if (ClOpt && ClOptGlobals) {1703// If initialization order checking is disabled, a simple access to a1704// dynamically initialized global is always valid.1705GlobalVariable *G = dyn_cast<GlobalVariable>(getUnderlyingObject(Addr));1706if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&1707isSafeAccess(ObjSizeVis, Addr, O.TypeStoreSize)) {1708NumOptimizedAccessesToGlobalVar++;1709return;1710}1711}17121713if (ClOpt && ClOptStack) {1714// A direct inbounds access to a stack variable is always valid.1715if (isa<AllocaInst>(getUnderlyingObject(Addr)) &&1716isSafeAccess(ObjSizeVis, Addr, O.TypeStoreSize)) {1717NumOptimizedAccessesToStackVar++;1718return;1719}1720}17211722if (O.IsWrite)1723NumInstrumentedWrites++;1724else1725NumInstrumentedReads++;17261727unsigned Granularity = 1 << Mapping.Scale;1728if (O.MaybeMask) {1729instrumentMaskedLoadOrStore(this, DL, IntptrTy, O.MaybeMask, O.MaybeEVL,1730O.MaybeStride, O.getInsn(), Addr, O.Alignment,1731Granularity, O.OpType, O.IsWrite, nullptr,1732UseCalls, Exp, RTCI);1733} else {1734doInstrumentAddress(this, O.getInsn(), O.getInsn(), Addr, O.Alignment,1735Granularity, O.TypeStoreSize, O.IsWrite, nullptr,1736UseCalls, Exp, RTCI);1737}1738}17391740Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,1741Value *Addr, bool IsWrite,1742size_t AccessSizeIndex,1743Value *SizeArgument,1744uint32_t Exp,1745RuntimeCallInserter &RTCI) {1746InstrumentationIRBuilder IRB(InsertBefore);1747Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);1748CallInst *Call = nullptr;1749if (SizeArgument) {1750if (Exp == 0)1751Call = RTCI.createRuntimeCall(IRB, AsanErrorCallbackSized[IsWrite][0],1752{Addr, SizeArgument});1753else1754Call = RTCI.createRuntimeCall(IRB, AsanErrorCallbackSized[IsWrite][1],1755{Addr, SizeArgument, ExpVal});1756} else {1757if (Exp == 0)1758Call = RTCI.createRuntimeCall(1759IRB, AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);1760else1761Call = RTCI.createRuntimeCall(1762IRB, AsanErrorCallback[IsWrite][1][AccessSizeIndex], {Addr, ExpVal});1763}17641765Call->setCannotMerge();1766return Call;1767}17681769Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,1770Value *ShadowValue,1771uint32_t TypeStoreSize) {1772size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;1773// Addr & (Granularity - 1)1774Value *LastAccessedByte =1775IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));1776// (Addr & (Granularity - 1)) + size - 11777if (TypeStoreSize / 8 > 1)1778LastAccessedByte = IRB.CreateAdd(1779LastAccessedByte, ConstantInt::get(IntptrTy, TypeStoreSize / 8 - 1));1780// (uint8_t) ((Addr & (Granularity-1)) + size - 1)1781LastAccessedByte =1782IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);1783// ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue1784return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);1785}17861787Instruction *AddressSanitizer::instrumentAMDGPUAddress(1788Instruction *OrigIns, Instruction *InsertBefore, Value *Addr,1789uint32_t TypeStoreSize, bool IsWrite, Value *SizeArgument) {1790// Do not instrument unsupported addrspaces.1791if (isUnsupportedAMDGPUAddrspace(Addr))1792return nullptr;1793Type *PtrTy = cast<PointerType>(Addr->getType()->getScalarType());1794// Follow host instrumentation for global and constant addresses.1795if (PtrTy->getPointerAddressSpace() != 0)1796return InsertBefore;1797// Instrument generic addresses in supported addressspaces.1798IRBuilder<> IRB(InsertBefore);1799Value *IsShared = IRB.CreateCall(AMDGPUAddressShared, {Addr});1800Value *IsPrivate = IRB.CreateCall(AMDGPUAddressPrivate, {Addr});1801Value *IsSharedOrPrivate = IRB.CreateOr(IsShared, IsPrivate);1802Value *Cmp = IRB.CreateNot(IsSharedOrPrivate);1803Value *AddrSpaceZeroLanding =1804SplitBlockAndInsertIfThen(Cmp, InsertBefore, false);1805InsertBefore = cast<Instruction>(AddrSpaceZeroLanding);1806return InsertBefore;1807}18081809Instruction *AddressSanitizer::genAMDGPUReportBlock(IRBuilder<> &IRB,1810Value *Cond, bool Recover) {1811Module &M = *IRB.GetInsertBlock()->getModule();1812Value *ReportCond = Cond;1813if (!Recover) {1814auto Ballot = M.getOrInsertFunction(kAMDGPUBallotName, IRB.getInt64Ty(),1815IRB.getInt1Ty());1816ReportCond = IRB.CreateIsNotNull(IRB.CreateCall(Ballot, {Cond}));1817}18181819auto *Trm =1820SplitBlockAndInsertIfThen(ReportCond, &*IRB.GetInsertPoint(), false,1821MDBuilder(*C).createUnlikelyBranchWeights());1822Trm->getParent()->setName("asan.report");18231824if (Recover)1825return Trm;18261827Trm = SplitBlockAndInsertIfThen(Cond, Trm, false);1828IRB.SetInsertPoint(Trm);1829return IRB.CreateCall(1830M.getOrInsertFunction(kAMDGPUUnreachableName, IRB.getVoidTy()), {});1831}18321833void AddressSanitizer::instrumentAddress(Instruction *OrigIns,1834Instruction *InsertBefore, Value *Addr,1835MaybeAlign Alignment,1836uint32_t TypeStoreSize, bool IsWrite,1837Value *SizeArgument, bool UseCalls,1838uint32_t Exp,1839RuntimeCallInserter &RTCI) {1840if (TargetTriple.isAMDGPU()) {1841InsertBefore = instrumentAMDGPUAddress(OrigIns, InsertBefore, Addr,1842TypeStoreSize, IsWrite, SizeArgument);1843if (!InsertBefore)1844return;1845}18461847InstrumentationIRBuilder IRB(InsertBefore);1848size_t AccessSizeIndex = TypeStoreSizeToSizeIndex(TypeStoreSize);1849const ASanAccessInfo AccessInfo(IsWrite, CompileKernel, AccessSizeIndex);18501851if (UseCalls && ClOptimizeCallbacks) {1852const ASanAccessInfo AccessInfo(IsWrite, CompileKernel, AccessSizeIndex);1853Module *M = IRB.GetInsertBlock()->getParent()->getParent();1854IRB.CreateCall(1855Intrinsic::getDeclaration(M, Intrinsic::asan_check_memaccess),1856{IRB.CreatePointerCast(Addr, PtrTy),1857ConstantInt::get(Int32Ty, AccessInfo.Packed)});1858return;1859}18601861Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);1862if (UseCalls) {1863if (Exp == 0)1864RTCI.createRuntimeCall(1865IRB, AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex], AddrLong);1866else1867RTCI.createRuntimeCall(1868IRB, AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],1869{AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});1870return;1871}18721873Type *ShadowTy =1874IntegerType::get(*C, std::max(8U, TypeStoreSize >> Mapping.Scale));1875Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);1876Value *ShadowPtr = memToShadow(AddrLong, IRB);1877const uint64_t ShadowAlign =1878std::max<uint64_t>(Alignment.valueOrOne().value() >> Mapping.Scale, 1);1879Value *ShadowValue = IRB.CreateAlignedLoad(1880ShadowTy, IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy), Align(ShadowAlign));18811882Value *Cmp = IRB.CreateIsNotNull(ShadowValue);1883size_t Granularity = 1ULL << Mapping.Scale;1884Instruction *CrashTerm = nullptr;18851886bool GenSlowPath = (ClAlwaysSlowPath || (TypeStoreSize < 8 * Granularity));18871888if (TargetTriple.isAMDGCN()) {1889if (GenSlowPath) {1890auto *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeStoreSize);1891Cmp = IRB.CreateAnd(Cmp, Cmp2);1892}1893CrashTerm = genAMDGPUReportBlock(IRB, Cmp, Recover);1894} else if (GenSlowPath) {1895// We use branch weights for the slow path check, to indicate that the slow1896// path is rarely taken. This seems to be the case for SPEC benchmarks.1897Instruction *CheckTerm = SplitBlockAndInsertIfThen(1898Cmp, InsertBefore, false, MDBuilder(*C).createUnlikelyBranchWeights());1899assert(cast<BranchInst>(CheckTerm)->isUnconditional());1900BasicBlock *NextBB = CheckTerm->getSuccessor(0);1901IRB.SetInsertPoint(CheckTerm);1902Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeStoreSize);1903if (Recover) {1904CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);1905} else {1906BasicBlock *CrashBlock =1907BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);1908CrashTerm = new UnreachableInst(*C, CrashBlock);1909BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);1910ReplaceInstWithInst(CheckTerm, NewTerm);1911}1912} else {1913CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);1914}19151916Instruction *Crash = generateCrashCode(1917CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument, Exp, RTCI);1918if (OrigIns->getDebugLoc())1919Crash->setDebugLoc(OrigIns->getDebugLoc());1920}19211922// Instrument unusual size or unusual alignment.1923// We can not do it with a single check, so we do 1-byte check for the first1924// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able1925// to report the actual access size.1926void AddressSanitizer::instrumentUnusualSizeOrAlignment(1927Instruction *I, Instruction *InsertBefore, Value *Addr,1928TypeSize TypeStoreSize, bool IsWrite, Value *SizeArgument, bool UseCalls,1929uint32_t Exp, RuntimeCallInserter &RTCI) {1930InstrumentationIRBuilder IRB(InsertBefore);1931Value *NumBits = IRB.CreateTypeSize(IntptrTy, TypeStoreSize);1932Value *Size = IRB.CreateLShr(NumBits, ConstantInt::get(IntptrTy, 3));19331934Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);1935if (UseCalls) {1936if (Exp == 0)1937RTCI.createRuntimeCall(IRB, AsanMemoryAccessCallbackSized[IsWrite][0],1938{AddrLong, Size});1939else1940RTCI.createRuntimeCall(1941IRB, AsanMemoryAccessCallbackSized[IsWrite][1],1942{AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});1943} else {1944Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));1945Value *LastByte = IRB.CreateIntToPtr(1946IRB.CreateAdd(AddrLong, SizeMinusOne),1947Addr->getType());1948instrumentAddress(I, InsertBefore, Addr, {}, 8, IsWrite, Size, false, Exp,1949RTCI);1950instrumentAddress(I, InsertBefore, LastByte, {}, 8, IsWrite, Size, false,1951Exp, RTCI);1952}1953}19541955void ModuleAddressSanitizer::poisonOneInitializer(Function &GlobalInit,1956GlobalValue *ModuleName) {1957// Set up the arguments to our poison/unpoison functions.1958IRBuilder<> IRB(&GlobalInit.front(),1959GlobalInit.front().getFirstInsertionPt());19601961// Add a call to poison all external globals before the given function starts.1962Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);1963IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);19641965// Add calls to unpoison all globals before each return instruction.1966for (auto &BB : GlobalInit)1967if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))1968CallInst::Create(AsanUnpoisonGlobals, "", RI->getIterator());1969}19701971void ModuleAddressSanitizer::createInitializerPoisonCalls(1972Module &M, GlobalValue *ModuleName) {1973GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");1974if (!GV)1975return;19761977ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());1978if (!CA)1979return;19801981for (Use &OP : CA->operands()) {1982if (isa<ConstantAggregateZero>(OP)) continue;1983ConstantStruct *CS = cast<ConstantStruct>(OP);19841985// Must have a function or null ptr.1986if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {1987if (F->getName() == kAsanModuleCtorName) continue;1988auto *Priority = cast<ConstantInt>(CS->getOperand(0));1989// Don't instrument CTORs that will run before asan.module_ctor.1990if (Priority->getLimitedValue() <= GetCtorAndDtorPriority(TargetTriple))1991continue;1992poisonOneInitializer(*F, ModuleName);1993}1994}1995}19961997const GlobalVariable *1998ModuleAddressSanitizer::getExcludedAliasedGlobal(const GlobalAlias &GA) const {1999// In case this function should be expanded to include rules that do not just2000// apply when CompileKernel is true, either guard all existing rules with an2001// 'if (CompileKernel) { ... }' or be absolutely sure that all these rules2002// should also apply to user space.2003assert(CompileKernel && "Only expecting to be called when compiling kernel");20042005const Constant *C = GA.getAliasee();20062007// When compiling the kernel, globals that are aliased by symbols prefixed2008// by "__" are special and cannot be padded with a redzone.2009if (GA.getName().starts_with("__"))2010return dyn_cast<GlobalVariable>(C->stripPointerCastsAndAliases());20112012return nullptr;2013}20142015bool ModuleAddressSanitizer::shouldInstrumentGlobal(GlobalVariable *G) const {2016Type *Ty = G->getValueType();2017LLVM_DEBUG(dbgs() << "GLOBAL: " << *G << "\n");20182019if (G->hasSanitizerMetadata() && G->getSanitizerMetadata().NoAddress)2020return false;2021if (!Ty->isSized()) return false;2022if (!G->hasInitializer()) return false;2023// Globals in address space 1 and 4 are supported for AMDGPU.2024if (G->getAddressSpace() &&2025!(TargetTriple.isAMDGPU() && !isUnsupportedAMDGPUAddrspace(G)))2026return false;2027if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.2028// Two problems with thread-locals:2029// - The address of the main thread's copy can't be computed at link-time.2030// - Need to poison all copies, not just the main thread's one.2031if (G->isThreadLocal()) return false;2032// For now, just ignore this Global if the alignment is large.2033if (G->getAlign() && *G->getAlign() > getMinRedzoneSizeForGlobal()) return false;20342035// For non-COFF targets, only instrument globals known to be defined by this2036// TU.2037// FIXME: We can instrument comdat globals on ELF if we are using the2038// GC-friendly metadata scheme.2039if (!TargetTriple.isOSBinFormatCOFF()) {2040if (!G->hasExactDefinition() || G->hasComdat())2041return false;2042} else {2043// On COFF, don't instrument non-ODR linkages.2044if (G->isInterposable())2045return false;2046// If the global has AvailableExternally linkage, then it is not in this2047// module, which means it does not need to be instrumented.2048if (G->hasAvailableExternallyLinkage())2049return false;2050}20512052// If a comdat is present, it must have a selection kind that implies ODR2053// semantics: no duplicates, any, or exact match.2054if (Comdat *C = G->getComdat()) {2055switch (C->getSelectionKind()) {2056case Comdat::Any:2057case Comdat::ExactMatch:2058case Comdat::NoDeduplicate:2059break;2060case Comdat::Largest:2061case Comdat::SameSize:2062return false;2063}2064}20652066if (G->hasSection()) {2067// The kernel uses explicit sections for mostly special global variables2068// that we should not instrument. E.g. the kernel may rely on their layout2069// without redzones, or remove them at link time ("discard.*"), etc.2070if (CompileKernel)2071return false;20722073StringRef Section = G->getSection();20742075// Globals from llvm.metadata aren't emitted, do not instrument them.2076if (Section == "llvm.metadata") return false;2077// Do not instrument globals from special LLVM sections.2078if (Section.contains("__llvm") || Section.contains("__LLVM"))2079return false;20802081// Do not instrument function pointers to initialization and termination2082// routines: dynamic linker will not properly handle redzones.2083if (Section.starts_with(".preinit_array") ||2084Section.starts_with(".init_array") ||2085Section.starts_with(".fini_array")) {2086return false;2087}20882089// Do not instrument user-defined sections (with names resembling2090// valid C identifiers)2091if (TargetTriple.isOSBinFormatELF()) {2092if (llvm::all_of(Section,2093[](char c) { return llvm::isAlnum(c) || c == '_'; }))2094return false;2095}20962097// On COFF, if the section name contains '$', it is highly likely that the2098// user is using section sorting to create an array of globals similar to2099// the way initialization callbacks are registered in .init_array and2100// .CRT$XCU. The ATL also registers things in .ATL$__[azm]. Adding redzones2101// to such globals is counterproductive, because the intent is that they2102// will form an array, and out-of-bounds accesses are expected.2103// See https://github.com/google/sanitizers/issues/3052104// and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx2105if (TargetTriple.isOSBinFormatCOFF() && Section.contains('$')) {2106LLVM_DEBUG(dbgs() << "Ignoring global in sorted section (contains '$'): "2107<< *G << "\n");2108return false;2109}21102111if (TargetTriple.isOSBinFormatMachO()) {2112StringRef ParsedSegment, ParsedSection;2113unsigned TAA = 0, StubSize = 0;2114bool TAAParsed;2115cantFail(MCSectionMachO::ParseSectionSpecifier(2116Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize));21172118// Ignore the globals from the __OBJC section. The ObjC runtime assumes2119// those conform to /usr/lib/objc/runtime.h, so we can't add redzones to2120// them.2121if (ParsedSegment == "__OBJC" ||2122(ParsedSegment == "__DATA" && ParsedSection.starts_with("__objc_"))) {2123LLVM_DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");2124return false;2125}2126// See https://github.com/google/sanitizers/issues/322127// Constant CFString instances are compiled in the following way:2128// -- the string buffer is emitted into2129// __TEXT,__cstring,cstring_literals2130// -- the constant NSConstantString structure referencing that buffer2131// is placed into __DATA,__cfstring2132// Therefore there's no point in placing redzones into __DATA,__cfstring.2133// Moreover, it causes the linker to crash on OS X 10.72134if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {2135LLVM_DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");2136return false;2137}2138// The linker merges the contents of cstring_literals and removes the2139// trailing zeroes.2140if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {2141LLVM_DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");2142return false;2143}2144}2145}21462147if (CompileKernel) {2148// Globals that prefixed by "__" are special and cannot be padded with a2149// redzone.2150if (G->getName().starts_with("__"))2151return false;2152}21532154return true;2155}21562157// On Mach-O platforms, we emit global metadata in a separate section of the2158// binary in order to allow the linker to properly dead strip. This is only2159// supported on recent versions of ld64.2160bool ModuleAddressSanitizer::ShouldUseMachOGlobalsSection() const {2161if (!TargetTriple.isOSBinFormatMachO())2162return false;21632164if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))2165return true;2166if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))2167return true;2168if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))2169return true;2170if (TargetTriple.isDriverKit())2171return true;2172if (TargetTriple.isXROS())2173return true;21742175return false;2176}21772178StringRef ModuleAddressSanitizer::getGlobalMetadataSection() const {2179switch (TargetTriple.getObjectFormat()) {2180case Triple::COFF: return ".ASAN$GL";2181case Triple::ELF: return "asan_globals";2182case Triple::MachO: return "__DATA,__asan_globals,regular";2183case Triple::Wasm:2184case Triple::GOFF:2185case Triple::SPIRV:2186case Triple::XCOFF:2187case Triple::DXContainer:2188report_fatal_error(2189"ModuleAddressSanitizer not implemented for object file format");2190case Triple::UnknownObjectFormat:2191break;2192}2193llvm_unreachable("unsupported object format");2194}21952196void ModuleAddressSanitizer::initializeCallbacks(Module &M) {2197IRBuilder<> IRB(*C);21982199// Declare our poisoning and unpoisoning functions.2200AsanPoisonGlobals =2201M.getOrInsertFunction(kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy);2202AsanUnpoisonGlobals =2203M.getOrInsertFunction(kAsanUnpoisonGlobalsName, IRB.getVoidTy());22042205// Declare functions that register/unregister globals.2206AsanRegisterGlobals = M.getOrInsertFunction(2207kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy);2208AsanUnregisterGlobals = M.getOrInsertFunction(2209kAsanUnregisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy);22102211// Declare the functions that find globals in a shared object and then invoke2212// the (un)register function on them.2213AsanRegisterImageGlobals = M.getOrInsertFunction(2214kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy);2215AsanUnregisterImageGlobals = M.getOrInsertFunction(2216kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy);22172218AsanRegisterElfGlobals =2219M.getOrInsertFunction(kAsanRegisterElfGlobalsName, IRB.getVoidTy(),2220IntptrTy, IntptrTy, IntptrTy);2221AsanUnregisterElfGlobals =2222M.getOrInsertFunction(kAsanUnregisterElfGlobalsName, IRB.getVoidTy(),2223IntptrTy, IntptrTy, IntptrTy);2224}22252226// Put the metadata and the instrumented global in the same group. This ensures2227// that the metadata is discarded if the instrumented global is discarded.2228void ModuleAddressSanitizer::SetComdatForGlobalMetadata(2229GlobalVariable *G, GlobalVariable *Metadata, StringRef InternalSuffix) {2230Module &M = *G->getParent();2231Comdat *C = G->getComdat();2232if (!C) {2233if (!G->hasName()) {2234// If G is unnamed, it must be internal. Give it an artificial name2235// so we can put it in a comdat.2236assert(G->hasLocalLinkage());2237G->setName(Twine(kAsanGenPrefix) + "_anon_global");2238}22392240if (!InternalSuffix.empty() && G->hasLocalLinkage()) {2241std::string Name = std::string(G->getName());2242Name += InternalSuffix;2243C = M.getOrInsertComdat(Name);2244} else {2245C = M.getOrInsertComdat(G->getName());2246}22472248// Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF. Also upgrade private2249// linkage to internal linkage so that a symbol table entry is emitted. This2250// is necessary in order to create the comdat group.2251if (TargetTriple.isOSBinFormatCOFF()) {2252C->setSelectionKind(Comdat::NoDeduplicate);2253if (G->hasPrivateLinkage())2254G->setLinkage(GlobalValue::InternalLinkage);2255}2256G->setComdat(C);2257}22582259assert(G->hasComdat());2260Metadata->setComdat(G->getComdat());2261}22622263// Create a separate metadata global and put it in the appropriate ASan2264// global registration section.2265GlobalVariable *2266ModuleAddressSanitizer::CreateMetadataGlobal(Module &M, Constant *Initializer,2267StringRef OriginalName) {2268auto Linkage = TargetTriple.isOSBinFormatMachO()2269? GlobalVariable::InternalLinkage2270: GlobalVariable::PrivateLinkage;2271GlobalVariable *Metadata = new GlobalVariable(2272M, Initializer->getType(), false, Linkage, Initializer,2273Twine("__asan_global_") + GlobalValue::dropLLVMManglingEscape(OriginalName));2274Metadata->setSection(getGlobalMetadataSection());2275// Place metadata in a large section for x86-64 ELF binaries to mitigate2276// relocation pressure.2277setGlobalVariableLargeSection(TargetTriple, *Metadata);2278return Metadata;2279}22802281Instruction *ModuleAddressSanitizer::CreateAsanModuleDtor(Module &M) {2282AsanDtorFunction = Function::createWithDefaultAttr(2283FunctionType::get(Type::getVoidTy(*C), false),2284GlobalValue::InternalLinkage, 0, kAsanModuleDtorName, &M);2285AsanDtorFunction->addFnAttr(Attribute::NoUnwind);2286// Ensure Dtor cannot be discarded, even if in a comdat.2287appendToUsed(M, {AsanDtorFunction});2288BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);22892290return ReturnInst::Create(*C, AsanDtorBB);2291}22922293void ModuleAddressSanitizer::InstrumentGlobalsCOFF(2294IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,2295ArrayRef<Constant *> MetadataInitializers) {2296assert(ExtendedGlobals.size() == MetadataInitializers.size());2297auto &DL = M.getDataLayout();22982299SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());2300for (size_t i = 0; i < ExtendedGlobals.size(); i++) {2301Constant *Initializer = MetadataInitializers[i];2302GlobalVariable *G = ExtendedGlobals[i];2303GlobalVariable *Metadata =2304CreateMetadataGlobal(M, Initializer, G->getName());2305MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));2306Metadata->setMetadata(LLVMContext::MD_associated, MD);2307MetadataGlobals[i] = Metadata;23082309// The MSVC linker always inserts padding when linking incrementally. We2310// cope with that by aligning each struct to its size, which must be a power2311// of two.2312unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());2313assert(isPowerOf2_32(SizeOfGlobalStruct) &&2314"global metadata will not be padded appropriately");2315Metadata->setAlignment(assumeAligned(SizeOfGlobalStruct));23162317SetComdatForGlobalMetadata(G, Metadata, "");2318}23192320// Update llvm.compiler.used, adding the new metadata globals. This is2321// needed so that during LTO these variables stay alive.2322if (!MetadataGlobals.empty())2323appendToCompilerUsed(M, MetadataGlobals);2324}23252326void ModuleAddressSanitizer::instrumentGlobalsELF(2327IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,2328ArrayRef<Constant *> MetadataInitializers,2329const std::string &UniqueModuleId) {2330assert(ExtendedGlobals.size() == MetadataInitializers.size());23312332// Putting globals in a comdat changes the semantic and potentially cause2333// false negative odr violations at link time. If odr indicators are used, we2334// keep the comdat sections, as link time odr violations will be dectected on2335// the odr indicator symbols.2336bool UseComdatForGlobalsGC = UseOdrIndicator && !UniqueModuleId.empty();23372338SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());2339for (size_t i = 0; i < ExtendedGlobals.size(); i++) {2340GlobalVariable *G = ExtendedGlobals[i];2341GlobalVariable *Metadata =2342CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());2343MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));2344Metadata->setMetadata(LLVMContext::MD_associated, MD);2345MetadataGlobals[i] = Metadata;23462347if (UseComdatForGlobalsGC)2348SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);2349}23502351// Update llvm.compiler.used, adding the new metadata globals. This is2352// needed so that during LTO these variables stay alive.2353if (!MetadataGlobals.empty())2354appendToCompilerUsed(M, MetadataGlobals);23552356// RegisteredFlag serves two purposes. First, we can pass it to dladdr()2357// to look up the loaded image that contains it. Second, we can store in it2358// whether registration has already occurred, to prevent duplicate2359// registration.2360//2361// Common linkage ensures that there is only one global per shared library.2362GlobalVariable *RegisteredFlag = new GlobalVariable(2363M, IntptrTy, false, GlobalVariable::CommonLinkage,2364ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);2365RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);23662367// Create start and stop symbols.2368GlobalVariable *StartELFMetadata = new GlobalVariable(2369M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,2370"__start_" + getGlobalMetadataSection());2371StartELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);2372GlobalVariable *StopELFMetadata = new GlobalVariable(2373M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,2374"__stop_" + getGlobalMetadataSection());2375StopELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);23762377// Create a call to register the globals with the runtime.2378if (ConstructorKind == AsanCtorKind::Global)2379IRB.CreateCall(AsanRegisterElfGlobals,2380{IRB.CreatePointerCast(RegisteredFlag, IntptrTy),2381IRB.CreatePointerCast(StartELFMetadata, IntptrTy),2382IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});23832384// We also need to unregister globals at the end, e.g., when a shared library2385// gets closed.2386if (DestructorKind != AsanDtorKind::None && !MetadataGlobals.empty()) {2387IRBuilder<> IrbDtor(CreateAsanModuleDtor(M));2388IrbDtor.CreateCall(AsanUnregisterElfGlobals,2389{IRB.CreatePointerCast(RegisteredFlag, IntptrTy),2390IRB.CreatePointerCast(StartELFMetadata, IntptrTy),2391IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});2392}2393}23942395void ModuleAddressSanitizer::InstrumentGlobalsMachO(2396IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,2397ArrayRef<Constant *> MetadataInitializers) {2398assert(ExtendedGlobals.size() == MetadataInitializers.size());23992400// On recent Mach-O platforms, use a structure which binds the liveness of2401// the global variable to the metadata struct. Keep the list of "Liveness" GV2402// created to be added to llvm.compiler.used2403StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy);2404SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());24052406for (size_t i = 0; i < ExtendedGlobals.size(); i++) {2407Constant *Initializer = MetadataInitializers[i];2408GlobalVariable *G = ExtendedGlobals[i];2409GlobalVariable *Metadata =2410CreateMetadataGlobal(M, Initializer, G->getName());24112412// On recent Mach-O platforms, we emit the global metadata in a way that2413// allows the linker to properly strip dead globals.2414auto LivenessBinder =2415ConstantStruct::get(LivenessTy, Initializer->getAggregateElement(0u),2416ConstantExpr::getPointerCast(Metadata, IntptrTy));2417GlobalVariable *Liveness = new GlobalVariable(2418M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,2419Twine("__asan_binder_") + G->getName());2420Liveness->setSection("__DATA,__asan_liveness,regular,live_support");2421LivenessGlobals[i] = Liveness;2422}24232424// Update llvm.compiler.used, adding the new liveness globals. This is2425// needed so that during LTO these variables stay alive. The alternative2426// would be to have the linker handling the LTO symbols, but libLTO2427// current API does not expose access to the section for each symbol.2428if (!LivenessGlobals.empty())2429appendToCompilerUsed(M, LivenessGlobals);24302431// RegisteredFlag serves two purposes. First, we can pass it to dladdr()2432// to look up the loaded image that contains it. Second, we can store in it2433// whether registration has already occurred, to prevent duplicate2434// registration.2435//2436// common linkage ensures that there is only one global per shared library.2437GlobalVariable *RegisteredFlag = new GlobalVariable(2438M, IntptrTy, false, GlobalVariable::CommonLinkage,2439ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);2440RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);24412442if (ConstructorKind == AsanCtorKind::Global)2443IRB.CreateCall(AsanRegisterImageGlobals,2444{IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});24452446// We also need to unregister globals at the end, e.g., when a shared library2447// gets closed.2448if (DestructorKind != AsanDtorKind::None) {2449IRBuilder<> IrbDtor(CreateAsanModuleDtor(M));2450IrbDtor.CreateCall(AsanUnregisterImageGlobals,2451{IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});2452}2453}24542455void ModuleAddressSanitizer::InstrumentGlobalsWithMetadataArray(2456IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,2457ArrayRef<Constant *> MetadataInitializers) {2458assert(ExtendedGlobals.size() == MetadataInitializers.size());2459unsigned N = ExtendedGlobals.size();2460assert(N > 0);24612462// On platforms that don't have a custom metadata section, we emit an array2463// of global metadata structures.2464ArrayType *ArrayOfGlobalStructTy =2465ArrayType::get(MetadataInitializers[0]->getType(), N);2466auto AllGlobals = new GlobalVariable(2467M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,2468ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");2469if (Mapping.Scale > 3)2470AllGlobals->setAlignment(Align(1ULL << Mapping.Scale));24712472if (ConstructorKind == AsanCtorKind::Global)2473IRB.CreateCall(AsanRegisterGlobals,2474{IRB.CreatePointerCast(AllGlobals, IntptrTy),2475ConstantInt::get(IntptrTy, N)});24762477// We also need to unregister globals at the end, e.g., when a shared library2478// gets closed.2479if (DestructorKind != AsanDtorKind::None) {2480IRBuilder<> IrbDtor(CreateAsanModuleDtor(M));2481IrbDtor.CreateCall(AsanUnregisterGlobals,2482{IRB.CreatePointerCast(AllGlobals, IntptrTy),2483ConstantInt::get(IntptrTy, N)});2484}2485}24862487// This function replaces all global variables with new variables that have2488// trailing redzones. It also creates a function that poisons2489// redzones and inserts this function into llvm.global_ctors.2490// Sets *CtorComdat to true if the global registration code emitted into the2491// asan constructor is comdat-compatible.2492void ModuleAddressSanitizer::instrumentGlobals(IRBuilder<> &IRB, Module &M,2493bool *CtorComdat) {2494// Build set of globals that are aliased by some GA, where2495// getExcludedAliasedGlobal(GA) returns the relevant GlobalVariable.2496SmallPtrSet<const GlobalVariable *, 16> AliasedGlobalExclusions;2497if (CompileKernel) {2498for (auto &GA : M.aliases()) {2499if (const GlobalVariable *GV = getExcludedAliasedGlobal(GA))2500AliasedGlobalExclusions.insert(GV);2501}2502}25032504SmallVector<GlobalVariable *, 16> GlobalsToChange;2505for (auto &G : M.globals()) {2506if (!AliasedGlobalExclusions.count(&G) && shouldInstrumentGlobal(&G))2507GlobalsToChange.push_back(&G);2508}25092510size_t n = GlobalsToChange.size();2511auto &DL = M.getDataLayout();25122513// A global is described by a structure2514// size_t beg;2515// size_t size;2516// size_t size_with_redzone;2517// const char *name;2518// const char *module_name;2519// size_t has_dynamic_init;2520// size_t padding_for_windows_msvc_incremental_link;2521// size_t odr_indicator;2522// We initialize an array of such structures and pass it to a run-time call.2523StructType *GlobalStructTy =2524StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,2525IntptrTy, IntptrTy, IntptrTy);2526SmallVector<GlobalVariable *, 16> NewGlobals(n);2527SmallVector<Constant *, 16> Initializers(n);25282529bool HasDynamicallyInitializedGlobals = false;25302531// We shouldn't merge same module names, as this string serves as unique2532// module ID in runtime.2533GlobalVariable *ModuleName =2534n != 02535? createPrivateGlobalForString(M, M.getModuleIdentifier(),2536/*AllowMerging*/ false, kAsanGenPrefix)2537: nullptr;25382539for (size_t i = 0; i < n; i++) {2540GlobalVariable *G = GlobalsToChange[i];25412542GlobalValue::SanitizerMetadata MD;2543if (G->hasSanitizerMetadata())2544MD = G->getSanitizerMetadata();25452546// The runtime library tries demangling symbol names in the descriptor but2547// functionality like __cxa_demangle may be unavailable (e.g.2548// -static-libstdc++). So we demangle the symbol names here.2549std::string NameForGlobal = G->getName().str();2550GlobalVariable *Name =2551createPrivateGlobalForString(M, llvm::demangle(NameForGlobal),2552/*AllowMerging*/ true, kAsanGenPrefix);25532554Type *Ty = G->getValueType();2555const uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);2556const uint64_t RightRedzoneSize = getRedzoneSizeForGlobal(SizeInBytes);2557Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);25582559StructType *NewTy = StructType::get(Ty, RightRedZoneTy);2560Constant *NewInitializer = ConstantStruct::get(2561NewTy, G->getInitializer(), Constant::getNullValue(RightRedZoneTy));25622563// Create a new global variable with enough space for a redzone.2564GlobalValue::LinkageTypes Linkage = G->getLinkage();2565if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)2566Linkage = GlobalValue::InternalLinkage;2567GlobalVariable *NewGlobal = new GlobalVariable(2568M, NewTy, G->isConstant(), Linkage, NewInitializer, "", G,2569G->getThreadLocalMode(), G->getAddressSpace());2570NewGlobal->copyAttributesFrom(G);2571NewGlobal->setComdat(G->getComdat());2572NewGlobal->setAlignment(Align(getMinRedzoneSizeForGlobal()));2573// Don't fold globals with redzones. ODR violation detector and redzone2574// poisoning implicitly creates a dependence on the global's address, so it2575// is no longer valid for it to be marked unnamed_addr.2576NewGlobal->setUnnamedAddr(GlobalValue::UnnamedAddr::None);25772578// Move null-terminated C strings to "__asan_cstring" section on Darwin.2579if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&2580G->isConstant()) {2581auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());2582if (Seq && Seq->isCString())2583NewGlobal->setSection("__TEXT,__asan_cstring,regular");2584}25852586// Transfer the debug info and type metadata. The payload starts at offset2587// zero so we can copy the metadata over as is.2588NewGlobal->copyMetadata(G, 0);25892590Value *Indices2[2];2591Indices2[0] = IRB.getInt32(0);2592Indices2[1] = IRB.getInt32(0);25932594G->replaceAllUsesWith(2595ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));2596NewGlobal->takeName(G);2597G->eraseFromParent();2598NewGlobals[i] = NewGlobal;25992600Constant *ODRIndicator = ConstantPointerNull::get(PtrTy);2601GlobalValue *InstrumentedGlobal = NewGlobal;26022603bool CanUsePrivateAliases =2604TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||2605TargetTriple.isOSBinFormatWasm();2606if (CanUsePrivateAliases && UsePrivateAlias) {2607// Create local alias for NewGlobal to avoid crash on ODR between2608// instrumented and non-instrumented libraries.2609InstrumentedGlobal =2610GlobalAlias::create(GlobalValue::PrivateLinkage, "", NewGlobal);2611}26122613// ODR should not happen for local linkage.2614if (NewGlobal->hasLocalLinkage()) {2615ODRIndicator =2616ConstantExpr::getIntToPtr(ConstantInt::get(IntptrTy, -1), PtrTy);2617} else if (UseOdrIndicator) {2618// With local aliases, we need to provide another externally visible2619// symbol __odr_asan_XXX to detect ODR violation.2620auto *ODRIndicatorSym =2621new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,2622Constant::getNullValue(IRB.getInt8Ty()),2623kODRGenPrefix + NameForGlobal, nullptr,2624NewGlobal->getThreadLocalMode());26252626// Set meaningful attributes for indicator symbol.2627ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());2628ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());2629ODRIndicatorSym->setAlignment(Align(1));2630ODRIndicator = ODRIndicatorSym;2631}26322633Constant *Initializer = ConstantStruct::get(2634GlobalStructTy,2635ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),2636ConstantInt::get(IntptrTy, SizeInBytes),2637ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),2638ConstantExpr::getPointerCast(Name, IntptrTy),2639ConstantExpr::getPointerCast(ModuleName, IntptrTy),2640ConstantInt::get(IntptrTy, MD.IsDynInit),2641Constant::getNullValue(IntptrTy),2642ConstantExpr::getPointerCast(ODRIndicator, IntptrTy));26432644if (ClInitializers && MD.IsDynInit)2645HasDynamicallyInitializedGlobals = true;26462647LLVM_DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");26482649Initializers[i] = Initializer;2650}26512652// Add instrumented globals to llvm.compiler.used list to avoid LTO from2653// ConstantMerge'ing them.2654SmallVector<GlobalValue *, 16> GlobalsToAddToUsedList;2655for (size_t i = 0; i < n; i++) {2656GlobalVariable *G = NewGlobals[i];2657if (G->getName().empty()) continue;2658GlobalsToAddToUsedList.push_back(G);2659}2660appendToCompilerUsed(M, ArrayRef<GlobalValue *>(GlobalsToAddToUsedList));26612662if (UseGlobalsGC && TargetTriple.isOSBinFormatELF()) {2663// Use COMDAT and register globals even if n == 0 to ensure that (a) the2664// linkage unit will only have one module constructor, and (b) the register2665// function will be called. The module destructor is not created when n ==2666// 0.2667*CtorComdat = true;2668instrumentGlobalsELF(IRB, M, NewGlobals, Initializers,2669getUniqueModuleId(&M));2670} else if (n == 0) {2671// When UseGlobalsGC is false, COMDAT can still be used if n == 0, because2672// all compile units will have identical module constructor/destructor.2673*CtorComdat = TargetTriple.isOSBinFormatELF();2674} else {2675*CtorComdat = false;2676if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {2677InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);2678} else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {2679InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);2680} else {2681InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);2682}2683}26842685// Create calls for poisoning before initializers run and unpoisoning after.2686if (HasDynamicallyInitializedGlobals)2687createInitializerPoisonCalls(M, ModuleName);26882689LLVM_DEBUG(dbgs() << M);2690}26912692uint64_t2693ModuleAddressSanitizer::getRedzoneSizeForGlobal(uint64_t SizeInBytes) const {2694constexpr uint64_t kMaxRZ = 1 << 18;2695const uint64_t MinRZ = getMinRedzoneSizeForGlobal();26962697uint64_t RZ = 0;2698if (SizeInBytes <= MinRZ / 2) {2699// Reduce redzone size for small size objects, e.g. int, char[1]. MinRZ is2700// at least 32 bytes, optimize when SizeInBytes is less than or equal to2701// half of MinRZ.2702RZ = MinRZ - SizeInBytes;2703} else {2704// Calculate RZ, where MinRZ <= RZ <= MaxRZ, and RZ ~ 1/4 * SizeInBytes.2705RZ = std::clamp((SizeInBytes / MinRZ / 4) * MinRZ, MinRZ, kMaxRZ);27062707// Round up to multiple of MinRZ.2708if (SizeInBytes % MinRZ)2709RZ += MinRZ - (SizeInBytes % MinRZ);2710}27112712assert((RZ + SizeInBytes) % MinRZ == 0);27132714return RZ;2715}27162717int ModuleAddressSanitizer::GetAsanVersion(const Module &M) const {2718int LongSize = M.getDataLayout().getPointerSizeInBits();2719bool isAndroid = Triple(M.getTargetTriple()).isAndroid();2720int Version = 8;2721// 32-bit Android is one version ahead because of the switch to dynamic2722// shadow.2723Version += (LongSize == 32 && isAndroid);2724return Version;2725}27262727bool ModuleAddressSanitizer::instrumentModule(Module &M) {2728initializeCallbacks(M);27292730// Create a module constructor. A destructor is created lazily because not all2731// platforms, and not all modules need it.2732if (ConstructorKind == AsanCtorKind::Global) {2733if (CompileKernel) {2734// The kernel always builds with its own runtime, and therefore does not2735// need the init and version check calls.2736AsanCtorFunction = createSanitizerCtor(M, kAsanModuleCtorName);2737} else {2738std::string AsanVersion = std::to_string(GetAsanVersion(M));2739std::string VersionCheckName =2740InsertVersionCheck ? (kAsanVersionCheckNamePrefix + AsanVersion) : "";2741std::tie(AsanCtorFunction, std::ignore) =2742createSanitizerCtorAndInitFunctions(M, kAsanModuleCtorName,2743kAsanInitName, /*InitArgTypes=*/{},2744/*InitArgs=*/{}, VersionCheckName);2745}2746}27472748bool CtorComdat = true;2749if (ClGlobals) {2750assert(AsanCtorFunction || ConstructorKind == AsanCtorKind::None);2751if (AsanCtorFunction) {2752IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());2753instrumentGlobals(IRB, M, &CtorComdat);2754} else {2755IRBuilder<> IRB(*C);2756instrumentGlobals(IRB, M, &CtorComdat);2757}2758}27592760const uint64_t Priority = GetCtorAndDtorPriority(TargetTriple);27612762// Put the constructor and destructor in comdat if both2763// (1) global instrumentation is not TU-specific2764// (2) target is ELF.2765if (UseCtorComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {2766if (AsanCtorFunction) {2767AsanCtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleCtorName));2768appendToGlobalCtors(M, AsanCtorFunction, Priority, AsanCtorFunction);2769}2770if (AsanDtorFunction) {2771AsanDtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleDtorName));2772appendToGlobalDtors(M, AsanDtorFunction, Priority, AsanDtorFunction);2773}2774} else {2775if (AsanCtorFunction)2776appendToGlobalCtors(M, AsanCtorFunction, Priority);2777if (AsanDtorFunction)2778appendToGlobalDtors(M, AsanDtorFunction, Priority);2779}27802781return true;2782}27832784void AddressSanitizer::initializeCallbacks(Module &M, const TargetLibraryInfo *TLI) {2785IRBuilder<> IRB(*C);2786// Create __asan_report* callbacks.2787// IsWrite, TypeSize and Exp are encoded in the function name.2788for (int Exp = 0; Exp < 2; Exp++) {2789for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {2790const std::string TypeStr = AccessIsWrite ? "store" : "load";2791const std::string ExpStr = Exp ? "exp_" : "";2792const std::string EndingStr = Recover ? "_noabort" : "";27932794SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};2795SmallVector<Type *, 2> Args1{1, IntptrTy};2796AttributeList AL2;2797AttributeList AL1;2798if (Exp) {2799Type *ExpType = Type::getInt32Ty(*C);2800Args2.push_back(ExpType);2801Args1.push_back(ExpType);2802if (auto AK = TLI->getExtAttrForI32Param(false)) {2803AL2 = AL2.addParamAttribute(*C, 2, AK);2804AL1 = AL1.addParamAttribute(*C, 1, AK);2805}2806}2807AsanErrorCallbackSized[AccessIsWrite][Exp] = M.getOrInsertFunction(2808kAsanReportErrorTemplate + ExpStr + TypeStr + "_n" + EndingStr,2809FunctionType::get(IRB.getVoidTy(), Args2, false), AL2);28102811AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] = M.getOrInsertFunction(2812ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,2813FunctionType::get(IRB.getVoidTy(), Args2, false), AL2);28142815for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;2816AccessSizeIndex++) {2817const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);2818AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =2819M.getOrInsertFunction(2820kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,2821FunctionType::get(IRB.getVoidTy(), Args1, false), AL1);28222823AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =2824M.getOrInsertFunction(2825ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,2826FunctionType::get(IRB.getVoidTy(), Args1, false), AL1);2827}2828}2829}28302831const std::string MemIntrinCallbackPrefix =2832(CompileKernel && !ClKasanMemIntrinCallbackPrefix)2833? std::string("")2834: ClMemoryAccessCallbackPrefix;2835AsanMemmove = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memmove",2836PtrTy, PtrTy, PtrTy, IntptrTy);2837AsanMemcpy = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memcpy", PtrTy,2838PtrTy, PtrTy, IntptrTy);2839AsanMemset = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memset",2840TLI->getAttrList(C, {1}, /*Signed=*/false),2841PtrTy, PtrTy, IRB.getInt32Ty(), IntptrTy);28422843AsanHandleNoReturnFunc =2844M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy());28452846AsanPtrCmpFunction =2847M.getOrInsertFunction(kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy);2848AsanPtrSubFunction =2849M.getOrInsertFunction(kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy);2850if (Mapping.InGlobal)2851AsanShadowGlobal = M.getOrInsertGlobal("__asan_shadow",2852ArrayType::get(IRB.getInt8Ty(), 0));28532854AMDGPUAddressShared =2855M.getOrInsertFunction(kAMDGPUAddressSharedName, IRB.getInt1Ty(), PtrTy);2856AMDGPUAddressPrivate =2857M.getOrInsertFunction(kAMDGPUAddressPrivateName, IRB.getInt1Ty(), PtrTy);2858}28592860bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {2861// For each NSObject descendant having a +load method, this method is invoked2862// by the ObjC runtime before any of the static constructors is called.2863// Therefore we need to instrument such methods with a call to __asan_init2864// at the beginning in order to initialize our runtime before any access to2865// the shadow memory.2866// We cannot just ignore these methods, because they may call other2867// instrumented functions.2868if (F.getName().contains(" load]")) {2869FunctionCallee AsanInitFunction =2870declareSanitizerInitFunction(*F.getParent(), kAsanInitName, {});2871IRBuilder<> IRB(&F.front(), F.front().begin());2872IRB.CreateCall(AsanInitFunction, {});2873return true;2874}2875return false;2876}28772878bool AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {2879// Generate code only when dynamic addressing is needed.2880if (Mapping.Offset != kDynamicShadowSentinel)2881return false;28822883IRBuilder<> IRB(&F.front().front());2884if (Mapping.InGlobal) {2885if (ClWithIfuncSuppressRemat) {2886// An empty inline asm with input reg == output reg.2887// An opaque pointer-to-int cast, basically.2888InlineAsm *Asm = InlineAsm::get(2889FunctionType::get(IntptrTy, {AsanShadowGlobal->getType()}, false),2890StringRef(""), StringRef("=r,0"),2891/*hasSideEffects=*/false);2892LocalDynamicShadow =2893IRB.CreateCall(Asm, {AsanShadowGlobal}, ".asan.shadow");2894} else {2895LocalDynamicShadow =2896IRB.CreatePointerCast(AsanShadowGlobal, IntptrTy, ".asan.shadow");2897}2898} else {2899Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(2900kAsanShadowMemoryDynamicAddress, IntptrTy);2901LocalDynamicShadow = IRB.CreateLoad(IntptrTy, GlobalDynamicAddress);2902}2903return true;2904}29052906void AddressSanitizer::markEscapedLocalAllocas(Function &F) {2907// Find the one possible call to llvm.localescape and pre-mark allocas passed2908// to it as uninteresting. This assumes we haven't started processing allocas2909// yet. This check is done up front because iterating the use list in2910// isInterestingAlloca would be algorithmically slower.2911assert(ProcessedAllocas.empty() && "must process localescape before allocas");29122913// Try to get the declaration of llvm.localescape. If it's not in the module,2914// we can exit early.2915if (!F.getParent()->getFunction("llvm.localescape")) return;29162917// Look for a call to llvm.localescape call in the entry block. It can't be in2918// any other block.2919for (Instruction &I : F.getEntryBlock()) {2920IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);2921if (II && II->getIntrinsicID() == Intrinsic::localescape) {2922// We found a call. Mark all the allocas passed in as uninteresting.2923for (Value *Arg : II->args()) {2924AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());2925assert(AI && AI->isStaticAlloca() &&2926"non-static alloca arg to localescape");2927ProcessedAllocas[AI] = false;2928}2929break;2930}2931}2932}29332934bool AddressSanitizer::suppressInstrumentationSiteForDebug(int &Instrumented) {2935bool ShouldInstrument =2936ClDebugMin < 0 || ClDebugMax < 0 ||2937(Instrumented >= ClDebugMin && Instrumented <= ClDebugMax);2938Instrumented++;2939return !ShouldInstrument;2940}29412942bool AddressSanitizer::instrumentFunction(Function &F,2943const TargetLibraryInfo *TLI) {2944if (F.empty())2945return false;2946if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;2947if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;2948if (F.getName().starts_with("__asan_")) return false;2949if (F.isPresplitCoroutine())2950return false;29512952bool FunctionModified = false;29532954// If needed, insert __asan_init before checking for SanitizeAddress attr.2955// This function needs to be called even if the function body is not2956// instrumented.2957if (maybeInsertAsanInitAtFunctionEntry(F))2958FunctionModified = true;29592960// Leave if the function doesn't need instrumentation.2961if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;29622963if (F.hasFnAttribute(Attribute::DisableSanitizerInstrumentation))2964return FunctionModified;29652966LLVM_DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");29672968initializeCallbacks(*F.getParent(), TLI);29692970FunctionStateRAII CleanupObj(this);29712972RuntimeCallInserter RTCI(F);29732974FunctionModified |= maybeInsertDynamicShadowAtFunctionEntry(F);29752976// We can't instrument allocas used with llvm.localescape. Only static allocas2977// can be passed to that intrinsic.2978markEscapedLocalAllocas(F);29792980// We want to instrument every address only once per basic block (unless there2981// are calls between uses).2982SmallPtrSet<Value *, 16> TempsToInstrument;2983SmallVector<InterestingMemoryOperand, 16> OperandsToInstrument;2984SmallVector<MemIntrinsic *, 16> IntrinToInstrument;2985SmallVector<Instruction *, 8> NoReturnCalls;2986SmallVector<BasicBlock *, 16> AllBlocks;2987SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;29882989// Fill the set of memory operations to instrument.2990for (auto &BB : F) {2991AllBlocks.push_back(&BB);2992TempsToInstrument.clear();2993int NumInsnsPerBB = 0;2994for (auto &Inst : BB) {2995if (LooksLikeCodeInBug11395(&Inst)) return false;2996// Skip instructions inserted by another instrumentation.2997if (Inst.hasMetadata(LLVMContext::MD_nosanitize))2998continue;2999SmallVector<InterestingMemoryOperand, 1> InterestingOperands;3000getInterestingMemoryOperands(&Inst, InterestingOperands);30013002if (!InterestingOperands.empty()) {3003for (auto &Operand : InterestingOperands) {3004if (ClOpt && ClOptSameTemp) {3005Value *Ptr = Operand.getPtr();3006// If we have a mask, skip instrumentation if we've already3007// instrumented the full object. But don't add to TempsToInstrument3008// because we might get another load/store with a different mask.3009if (Operand.MaybeMask) {3010if (TempsToInstrument.count(Ptr))3011continue; // We've seen this (whole) temp in the current BB.3012} else {3013if (!TempsToInstrument.insert(Ptr).second)3014continue; // We've seen this temp in the current BB.3015}3016}3017OperandsToInstrument.push_back(Operand);3018NumInsnsPerBB++;3019}3020} else if (((ClInvalidPointerPairs || ClInvalidPointerCmp) &&3021isInterestingPointerComparison(&Inst)) ||3022((ClInvalidPointerPairs || ClInvalidPointerSub) &&3023isInterestingPointerSubtraction(&Inst))) {3024PointerComparisonsOrSubtracts.push_back(&Inst);3025} else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&Inst)) {3026// ok, take it.3027IntrinToInstrument.push_back(MI);3028NumInsnsPerBB++;3029} else {3030if (auto *CB = dyn_cast<CallBase>(&Inst)) {3031// A call inside BB.3032TempsToInstrument.clear();3033if (CB->doesNotReturn())3034NoReturnCalls.push_back(CB);3035}3036if (CallInst *CI = dyn_cast<CallInst>(&Inst))3037maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);3038}3039if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;3040}3041}30423043bool UseCalls = (InstrumentationWithCallsThreshold >= 0 &&3044OperandsToInstrument.size() + IntrinToInstrument.size() >3045(unsigned)InstrumentationWithCallsThreshold);3046const DataLayout &DL = F.getDataLayout();3047ObjectSizeOpts ObjSizeOpts;3048ObjSizeOpts.RoundToAlign = true;3049ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);30503051// Instrument.3052int NumInstrumented = 0;3053for (auto &Operand : OperandsToInstrument) {3054if (!suppressInstrumentationSiteForDebug(NumInstrumented))3055instrumentMop(ObjSizeVis, Operand, UseCalls,3056F.getDataLayout(), RTCI);3057FunctionModified = true;3058}3059for (auto *Inst : IntrinToInstrument) {3060if (!suppressInstrumentationSiteForDebug(NumInstrumented))3061instrumentMemIntrinsic(Inst, RTCI);3062FunctionModified = true;3063}30643065FunctionStackPoisoner FSP(F, *this, RTCI);3066bool ChangedStack = FSP.runOnFunction();30673068// We must unpoison the stack before NoReturn calls (throw, _exit, etc).3069// See e.g. https://github.com/google/sanitizers/issues/373070for (auto *CI : NoReturnCalls) {3071IRBuilder<> IRB(CI);3072RTCI.createRuntimeCall(IRB, AsanHandleNoReturnFunc, {});3073}30743075for (auto *Inst : PointerComparisonsOrSubtracts) {3076instrumentPointerComparisonOrSubtraction(Inst, RTCI);3077FunctionModified = true;3078}30793080if (ChangedStack || !NoReturnCalls.empty())3081FunctionModified = true;30823083LLVM_DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "3084<< F << "\n");30853086return FunctionModified;3087}30883089// Workaround for bug 11395: we don't want to instrument stack in functions3090// with large assembly blobs (32-bit only), otherwise reg alloc may crash.3091// FIXME: remove once the bug 11395 is fixed.3092bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {3093if (LongSize != 32) return false;3094CallInst *CI = dyn_cast<CallInst>(I);3095if (!CI || !CI->isInlineAsm()) return false;3096if (CI->arg_size() <= 5)3097return false;3098// We have inline assembly with quite a few arguments.3099return true;3100}31013102void FunctionStackPoisoner::initializeCallbacks(Module &M) {3103IRBuilder<> IRB(*C);3104if (ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode::Always ||3105ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode::Runtime) {3106const char *MallocNameTemplate =3107ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode::Always3108? kAsanStackMallocAlwaysNameTemplate3109: kAsanStackMallocNameTemplate;3110for (int Index = 0; Index <= kMaxAsanStackMallocSizeClass; Index++) {3111std::string Suffix = itostr(Index);3112AsanStackMallocFunc[Index] = M.getOrInsertFunction(3113MallocNameTemplate + Suffix, IntptrTy, IntptrTy);3114AsanStackFreeFunc[Index] =3115M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,3116IRB.getVoidTy(), IntptrTy, IntptrTy);3117}3118}3119if (ASan.UseAfterScope) {3120AsanPoisonStackMemoryFunc = M.getOrInsertFunction(3121kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy);3122AsanUnpoisonStackMemoryFunc = M.getOrInsertFunction(3123kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy);3124}31253126for (size_t Val : {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xf1, 0xf2,31270xf3, 0xf5, 0xf8}) {3128std::ostringstream Name;3129Name << kAsanSetShadowPrefix;3130Name << std::setw(2) << std::setfill('0') << std::hex << Val;3131AsanSetShadowFunc[Val] =3132M.getOrInsertFunction(Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy);3133}31343135AsanAllocaPoisonFunc = M.getOrInsertFunction(3136kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy);3137AsanAllocasUnpoisonFunc = M.getOrInsertFunction(3138kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy);3139}31403141void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,3142ArrayRef<uint8_t> ShadowBytes,3143size_t Begin, size_t End,3144IRBuilder<> &IRB,3145Value *ShadowBase) {3146if (Begin >= End)3147return;31483149const size_t LargestStoreSizeInBytes =3150std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);31513152const bool IsLittleEndian = F.getDataLayout().isLittleEndian();31533154// Poison given range in shadow using larges store size with out leading and3155// trailing zeros in ShadowMask. Zeros never change, so they need neither3156// poisoning nor up-poisoning. Still we don't mind if some of them get into a3157// middle of a store.3158for (size_t i = Begin; i < End;) {3159if (!ShadowMask[i]) {3160assert(!ShadowBytes[i]);3161++i;3162continue;3163}31643165size_t StoreSizeInBytes = LargestStoreSizeInBytes;3166// Fit store size into the range.3167while (StoreSizeInBytes > End - i)3168StoreSizeInBytes /= 2;31693170// Minimize store size by trimming trailing zeros.3171for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {3172while (j <= StoreSizeInBytes / 2)3173StoreSizeInBytes /= 2;3174}31753176uint64_t Val = 0;3177for (size_t j = 0; j < StoreSizeInBytes; j++) {3178if (IsLittleEndian)3179Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);3180else3181Val = (Val << 8) | ShadowBytes[i + j];3182}31833184Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));3185Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);3186IRB.CreateAlignedStore(3187Poison, IRB.CreateIntToPtr(Ptr, PointerType::getUnqual(Poison->getContext())),3188Align(1));31893190i += StoreSizeInBytes;3191}3192}31933194void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,3195ArrayRef<uint8_t> ShadowBytes,3196IRBuilder<> &IRB, Value *ShadowBase) {3197copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);3198}31993200void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,3201ArrayRef<uint8_t> ShadowBytes,3202size_t Begin, size_t End,3203IRBuilder<> &IRB, Value *ShadowBase) {3204assert(ShadowMask.size() == ShadowBytes.size());3205size_t Done = Begin;3206for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {3207if (!ShadowMask[i]) {3208assert(!ShadowBytes[i]);3209continue;3210}3211uint8_t Val = ShadowBytes[i];3212if (!AsanSetShadowFunc[Val])3213continue;32143215// Skip same values.3216for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {3217}32183219if (j - i >= ASan.MaxInlinePoisoningSize) {3220copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);3221RTCI.createRuntimeCall(3222IRB, AsanSetShadowFunc[Val],3223{IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),3224ConstantInt::get(IntptrTy, j - i)});3225Done = j;3226}3227}32283229copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);3230}32313232// Fake stack allocator (asan_fake_stack.h) has 11 size classes3233// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass3234static int StackMallocSizeClass(uint64_t LocalStackSize) {3235assert(LocalStackSize <= kMaxStackMallocSize);3236uint64_t MaxSize = kMinStackMallocSize;3237for (int i = 0;; i++, MaxSize *= 2)3238if (LocalStackSize <= MaxSize) return i;3239llvm_unreachable("impossible LocalStackSize");3240}32413242void FunctionStackPoisoner::copyArgsPassedByValToAllocas() {3243Instruction *CopyInsertPoint = &F.front().front();3244if (CopyInsertPoint == ASan.LocalDynamicShadow) {3245// Insert after the dynamic shadow location is determined3246CopyInsertPoint = CopyInsertPoint->getNextNode();3247assert(CopyInsertPoint);3248}3249IRBuilder<> IRB(CopyInsertPoint);3250const DataLayout &DL = F.getDataLayout();3251for (Argument &Arg : F.args()) {3252if (Arg.hasByValAttr()) {3253Type *Ty = Arg.getParamByValType();3254const Align Alignment =3255DL.getValueOrABITypeAlignment(Arg.getParamAlign(), Ty);32563257AllocaInst *AI = IRB.CreateAlloca(3258Ty, nullptr,3259(Arg.hasName() ? Arg.getName() : "Arg" + Twine(Arg.getArgNo())) +3260".byval");3261AI->setAlignment(Alignment);3262Arg.replaceAllUsesWith(AI);32633264uint64_t AllocSize = DL.getTypeAllocSize(Ty);3265IRB.CreateMemCpy(AI, Alignment, &Arg, Alignment, AllocSize);3266}3267}3268}32693270PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,3271Value *ValueIfTrue,3272Instruction *ThenTerm,3273Value *ValueIfFalse) {3274PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);3275BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();3276PHI->addIncoming(ValueIfFalse, CondBlock);3277BasicBlock *ThenBlock = ThenTerm->getParent();3278PHI->addIncoming(ValueIfTrue, ThenBlock);3279return PHI;3280}32813282Value *FunctionStackPoisoner::createAllocaForLayout(3283IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {3284AllocaInst *Alloca;3285if (Dynamic) {3286Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),3287ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),3288"MyAlloca");3289} else {3290Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),3291nullptr, "MyAlloca");3292assert(Alloca->isStaticAlloca());3293}3294assert((ClRealignStack & (ClRealignStack - 1)) == 0);3295uint64_t FrameAlignment = std::max(L.FrameAlignment, uint64_t(ClRealignStack));3296Alloca->setAlignment(Align(FrameAlignment));3297return IRB.CreatePointerCast(Alloca, IntptrTy);3298}32993300void FunctionStackPoisoner::createDynamicAllocasInitStorage() {3301BasicBlock &FirstBB = *F.begin();3302IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));3303DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);3304IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);3305DynamicAllocaLayout->setAlignment(Align(32));3306}33073308void FunctionStackPoisoner::processDynamicAllocas() {3309if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {3310assert(DynamicAllocaPoisonCallVec.empty());3311return;3312}33133314// Insert poison calls for lifetime intrinsics for dynamic allocas.3315for (const auto &APC : DynamicAllocaPoisonCallVec) {3316assert(APC.InsBefore);3317assert(APC.AI);3318assert(ASan.isInterestingAlloca(*APC.AI));3319assert(!APC.AI->isStaticAlloca());33203321IRBuilder<> IRB(APC.InsBefore);3322poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);3323// Dynamic allocas will be unpoisoned unconditionally below in3324// unpoisonDynamicAllocas.3325// Flag that we need unpoison static allocas.3326}33273328// Handle dynamic allocas.3329createDynamicAllocasInitStorage();3330for (auto &AI : DynamicAllocaVec)3331handleDynamicAllocaCall(AI);3332unpoisonDynamicAllocas();3333}33343335/// Collect instructions in the entry block after \p InsBefore which initialize3336/// permanent storage for a function argument. These instructions must remain in3337/// the entry block so that uninitialized values do not appear in backtraces. An3338/// added benefit is that this conserves spill slots. This does not move stores3339/// before instrumented / "interesting" allocas.3340static void findStoresToUninstrumentedArgAllocas(3341AddressSanitizer &ASan, Instruction &InsBefore,3342SmallVectorImpl<Instruction *> &InitInsts) {3343Instruction *Start = InsBefore.getNextNonDebugInstruction();3344for (Instruction *It = Start; It; It = It->getNextNonDebugInstruction()) {3345// Argument initialization looks like:3346// 1) store <Argument>, <Alloca> OR3347// 2) <CastArgument> = cast <Argument> to ...3348// store <CastArgument> to <Alloca>3349// Do not consider any other kind of instruction.3350//3351// Note: This covers all known cases, but may not be exhaustive. An3352// alternative to pattern-matching stores is to DFS over all Argument uses:3353// this might be more general, but is probably much more complicated.3354if (isa<AllocaInst>(It) || isa<CastInst>(It))3355continue;3356if (auto *Store = dyn_cast<StoreInst>(It)) {3357// The store destination must be an alloca that isn't interesting for3358// ASan to instrument. These are moved up before InsBefore, and they're3359// not interesting because allocas for arguments can be mem2reg'd.3360auto *Alloca = dyn_cast<AllocaInst>(Store->getPointerOperand());3361if (!Alloca || ASan.isInterestingAlloca(*Alloca))3362continue;33633364Value *Val = Store->getValueOperand();3365bool IsDirectArgInit = isa<Argument>(Val);3366bool IsArgInitViaCast =3367isa<CastInst>(Val) &&3368isa<Argument>(cast<CastInst>(Val)->getOperand(0)) &&3369// Check that the cast appears directly before the store. Otherwise3370// moving the cast before InsBefore may break the IR.3371Val == It->getPrevNonDebugInstruction();3372bool IsArgInit = IsDirectArgInit || IsArgInitViaCast;3373if (!IsArgInit)3374continue;33753376if (IsArgInitViaCast)3377InitInsts.push_back(cast<Instruction>(Val));3378InitInsts.push_back(Store);3379continue;3380}33813382// Do not reorder past unknown instructions: argument initialization should3383// only involve casts and stores.3384return;3385}3386}33873388void FunctionStackPoisoner::processStaticAllocas() {3389if (AllocaVec.empty()) {3390assert(StaticAllocaPoisonCallVec.empty());3391return;3392}33933394int StackMallocIdx = -1;3395DebugLoc EntryDebugLocation;3396if (auto SP = F.getSubprogram())3397EntryDebugLocation =3398DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);33993400Instruction *InsBefore = AllocaVec[0];3401IRBuilder<> IRB(InsBefore);34023403// Make sure non-instrumented allocas stay in the entry block. Otherwise,3404// debug info is broken, because only entry-block allocas are treated as3405// regular stack slots.3406auto InsBeforeB = InsBefore->getParent();3407assert(InsBeforeB == &F.getEntryBlock());3408for (auto *AI : StaticAllocasToMoveUp)3409if (AI->getParent() == InsBeforeB)3410AI->moveBefore(InsBefore);34113412// Move stores of arguments into entry-block allocas as well. This prevents3413// extra stack slots from being generated (to house the argument values until3414// they can be stored into the allocas). This also prevents uninitialized3415// values from being shown in backtraces.3416SmallVector<Instruction *, 8> ArgInitInsts;3417findStoresToUninstrumentedArgAllocas(ASan, *InsBefore, ArgInitInsts);3418for (Instruction *ArgInitInst : ArgInitInsts)3419ArgInitInst->moveBefore(InsBefore);34203421// If we have a call to llvm.localescape, keep it in the entry block.3422if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);34233424SmallVector<ASanStackVariableDescription, 16> SVD;3425SVD.reserve(AllocaVec.size());3426for (AllocaInst *AI : AllocaVec) {3427ASanStackVariableDescription D = {AI->getName().data(),3428ASan.getAllocaSizeInBytes(*AI),34290,3430AI->getAlign().value(),3431AI,34320,34330};3434SVD.push_back(D);3435}34363437// Minimal header size (left redzone) is 4 pointers,3438// i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.3439uint64_t Granularity = 1ULL << Mapping.Scale;3440uint64_t MinHeaderSize = std::max((uint64_t)ASan.LongSize / 2, Granularity);3441const ASanStackFrameLayout &L =3442ComputeASanStackFrameLayout(SVD, Granularity, MinHeaderSize);34433444// Build AllocaToSVDMap for ASanStackVariableDescription lookup.3445DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;3446for (auto &Desc : SVD)3447AllocaToSVDMap[Desc.AI] = &Desc;34483449// Update SVD with information from lifetime intrinsics.3450for (const auto &APC : StaticAllocaPoisonCallVec) {3451assert(APC.InsBefore);3452assert(APC.AI);3453assert(ASan.isInterestingAlloca(*APC.AI));3454assert(APC.AI->isStaticAlloca());34553456ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];3457Desc.LifetimeSize = Desc.Size;3458if (const DILocation *FnLoc = EntryDebugLocation.get()) {3459if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {3460if (LifetimeLoc->getFile() == FnLoc->getFile())3461if (unsigned Line = LifetimeLoc->getLine())3462Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);3463}3464}3465}34663467auto DescriptionString = ComputeASanStackFrameDescription(SVD);3468LLVM_DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");3469uint64_t LocalStackSize = L.FrameSize;3470bool DoStackMalloc =3471ASan.UseAfterReturn != AsanDetectStackUseAfterReturnMode::Never &&3472!ASan.CompileKernel && LocalStackSize <= kMaxStackMallocSize;3473bool DoDynamicAlloca = ClDynamicAllocaStack;3474// Don't do dynamic alloca or stack malloc if:3475// 1) There is inline asm: too often it makes assumptions on which registers3476// are available.3477// 2) There is a returns_twice call (typically setjmp), which is3478// optimization-hostile, and doesn't play well with introduced indirect3479// register-relative calculation of local variable addresses.3480DoDynamicAlloca &= !HasInlineAsm && !HasReturnsTwiceCall;3481DoStackMalloc &= !HasInlineAsm && !HasReturnsTwiceCall;34823483Value *StaticAlloca =3484DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);34853486Value *FakeStack;3487Value *LocalStackBase;3488Value *LocalStackBaseAlloca;3489uint8_t DIExprFlags = DIExpression::ApplyOffset;34903491if (DoStackMalloc) {3492LocalStackBaseAlloca =3493IRB.CreateAlloca(IntptrTy, nullptr, "asan_local_stack_base");3494if (ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode::Runtime) {3495// void *FakeStack = __asan_option_detect_stack_use_after_return3496// ? __asan_stack_malloc_N(LocalStackSize)3497// : nullptr;3498// void *LocalStackBase = (FakeStack) ? FakeStack :3499// alloca(LocalStackSize);3500Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(3501kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());3502Value *UseAfterReturnIsEnabled = IRB.CreateICmpNE(3503IRB.CreateLoad(IRB.getInt32Ty(), OptionDetectUseAfterReturn),3504Constant::getNullValue(IRB.getInt32Ty()));3505Instruction *Term =3506SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);3507IRBuilder<> IRBIf(Term);3508StackMallocIdx = StackMallocSizeClass(LocalStackSize);3509assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);3510Value *FakeStackValue =3511RTCI.createRuntimeCall(IRBIf, AsanStackMallocFunc[StackMallocIdx],3512ConstantInt::get(IntptrTy, LocalStackSize));3513IRB.SetInsertPoint(InsBefore);3514FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,3515ConstantInt::get(IntptrTy, 0));3516} else {3517// assert(ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode:Always)3518// void *FakeStack = __asan_stack_malloc_N(LocalStackSize);3519// void *LocalStackBase = (FakeStack) ? FakeStack :3520// alloca(LocalStackSize);3521StackMallocIdx = StackMallocSizeClass(LocalStackSize);3522FakeStack =3523RTCI.createRuntimeCall(IRB, AsanStackMallocFunc[StackMallocIdx],3524ConstantInt::get(IntptrTy, LocalStackSize));3525}3526Value *NoFakeStack =3527IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));3528Instruction *Term =3529SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);3530IRBuilder<> IRBIf(Term);3531Value *AllocaValue =3532DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;35333534IRB.SetInsertPoint(InsBefore);3535LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);3536IRB.CreateStore(LocalStackBase, LocalStackBaseAlloca);3537DIExprFlags |= DIExpression::DerefBefore;3538} else {3539// void *FakeStack = nullptr;3540// void *LocalStackBase = alloca(LocalStackSize);3541FakeStack = ConstantInt::get(IntptrTy, 0);3542LocalStackBase =3543DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;3544LocalStackBaseAlloca = LocalStackBase;3545}35463547// It shouldn't matter whether we pass an `alloca` or a `ptrtoint` as the3548// dbg.declare address opereand, but passing a `ptrtoint` seems to confuse3549// later passes and can result in dropped variable coverage in debug info.3550Value *LocalStackBaseAllocaPtr =3551isa<PtrToIntInst>(LocalStackBaseAlloca)3552? cast<PtrToIntInst>(LocalStackBaseAlloca)->getPointerOperand()3553: LocalStackBaseAlloca;3554assert(isa<AllocaInst>(LocalStackBaseAllocaPtr) &&3555"Variable descriptions relative to ASan stack base will be dropped");35563557// Replace Alloca instructions with base+offset.3558for (const auto &Desc : SVD) {3559AllocaInst *AI = Desc.AI;3560replaceDbgDeclare(AI, LocalStackBaseAllocaPtr, DIB, DIExprFlags,3561Desc.Offset);3562Value *NewAllocaPtr = IRB.CreateIntToPtr(3563IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),3564AI->getType());3565AI->replaceAllUsesWith(NewAllocaPtr);3566}35673568// The left-most redzone has enough space for at least 4 pointers.3569// Write the Magic value to redzone[0].3570Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);3571IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),3572BasePlus0);3573// Write the frame description constant to redzone[1].3574Value *BasePlus1 = IRB.CreateIntToPtr(3575IRB.CreateAdd(LocalStackBase,3576ConstantInt::get(IntptrTy, ASan.LongSize / 8)),3577IntptrPtrTy);3578GlobalVariable *StackDescriptionGlobal =3579createPrivateGlobalForString(*F.getParent(), DescriptionString,3580/*AllowMerging*/ true, kAsanGenPrefix);3581Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);3582IRB.CreateStore(Description, BasePlus1);3583// Write the PC to redzone[2].3584Value *BasePlus2 = IRB.CreateIntToPtr(3585IRB.CreateAdd(LocalStackBase,3586ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),3587IntptrPtrTy);3588IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);35893590const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);35913592// Poison the stack red zones at the entry.3593Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);3594// As mask we must use most poisoned case: red zones and after scope.3595// As bytes we can use either the same or just red zones only.3596copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);35973598if (!StaticAllocaPoisonCallVec.empty()) {3599const auto &ShadowInScope = GetShadowBytes(SVD, L);36003601// Poison static allocas near lifetime intrinsics.3602for (const auto &APC : StaticAllocaPoisonCallVec) {3603const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];3604assert(Desc.Offset % L.Granularity == 0);3605size_t Begin = Desc.Offset / L.Granularity;3606size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;36073608IRBuilder<> IRB(APC.InsBefore);3609copyToShadow(ShadowAfterScope,3610APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,3611IRB, ShadowBase);3612}3613}36143615SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);3616SmallVector<uint8_t, 64> ShadowAfterReturn;36173618// (Un)poison the stack before all ret instructions.3619for (Instruction *Ret : RetVec) {3620IRBuilder<> IRBRet(Ret);3621// Mark the current frame as retired.3622IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),3623BasePlus0);3624if (DoStackMalloc) {3625assert(StackMallocIdx >= 0);3626// if FakeStack != 0 // LocalStackBase == FakeStack3627// // In use-after-return mode, poison the whole stack frame.3628// if StackMallocIdx <= 43629// // For small sizes inline the whole thing:3630// memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);3631// **SavedFlagPtr(FakeStack) = 03632// else3633// __asan_stack_free_N(FakeStack, LocalStackSize)3634// else3635// <This is not a fake stack; unpoison the redzones>3636Value *Cmp =3637IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));3638Instruction *ThenTerm, *ElseTerm;3639SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);36403641IRBuilder<> IRBPoison(ThenTerm);3642if (ASan.MaxInlinePoisoningSize != 0 && StackMallocIdx <= 4) {3643int ClassSize = kMinStackMallocSize << StackMallocIdx;3644ShadowAfterReturn.resize(ClassSize / L.Granularity,3645kAsanStackUseAfterReturnMagic);3646copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,3647ShadowBase);3648Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(3649FakeStack,3650ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));3651Value *SavedFlagPtr = IRBPoison.CreateLoad(3652IntptrTy, IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));3653IRBPoison.CreateStore(3654Constant::getNullValue(IRBPoison.getInt8Ty()),3655IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getPtrTy()));3656} else {3657// For larger frames call __asan_stack_free_*.3658RTCI.createRuntimeCall(3659IRBPoison, AsanStackFreeFunc[StackMallocIdx],3660{FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});3661}36623663IRBuilder<> IRBElse(ElseTerm);3664copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);3665} else {3666copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);3667}3668}36693670// We are done. Remove the old unused alloca instructions.3671for (auto *AI : AllocaVec)3672AI->eraseFromParent();3673}36743675void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,3676IRBuilder<> &IRB, bool DoPoison) {3677// For now just insert the call to ASan runtime.3678Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);3679Value *SizeArg = ConstantInt::get(IntptrTy, Size);3680RTCI.createRuntimeCall(3681IRB, DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,3682{AddrArg, SizeArg});3683}36843685// Handling llvm.lifetime intrinsics for a given %alloca:3686// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.3687// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect3688// invalid accesses) and unpoison it for llvm.lifetime.start (the memory3689// could be poisoned by previous llvm.lifetime.end instruction, as the3690// variable may go in and out of scope several times, e.g. in loops).3691// (3) if we poisoned at least one %alloca in a function,3692// unpoison the whole stack frame at function exit.3693void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {3694IRBuilder<> IRB(AI);36953696const Align Alignment = std::max(Align(kAllocaRzSize), AI->getAlign());3697const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;36983699Value *Zero = Constant::getNullValue(IntptrTy);3700Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);3701Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);37023703// Since we need to extend alloca with additional memory to locate3704// redzones, and OldSize is number of allocated blocks with3705// ElementSize size, get allocated memory size in bytes by3706// OldSize * ElementSize.3707const unsigned ElementSize =3708F.getDataLayout().getTypeAllocSize(AI->getAllocatedType());3709Value *OldSize =3710IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),3711ConstantInt::get(IntptrTy, ElementSize));37123713// PartialSize = OldSize % 323714Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);37153716// Misalign = kAllocaRzSize - PartialSize;3717Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);37183719// PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;3720Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);3721Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);37223723// AdditionalChunkSize = Alignment + PartialPadding + kAllocaRzSize3724// Alignment is added to locate left redzone, PartialPadding for possible3725// partial redzone and kAllocaRzSize for right redzone respectively.3726Value *AdditionalChunkSize = IRB.CreateAdd(3727ConstantInt::get(IntptrTy, Alignment.value() + kAllocaRzSize),3728PartialPadding);37293730Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);37313732// Insert new alloca with new NewSize and Alignment params.3733AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);3734NewAlloca->setAlignment(Alignment);37353736// NewAddress = Address + Alignment3737Value *NewAddress =3738IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),3739ConstantInt::get(IntptrTy, Alignment.value()));37403741// Insert __asan_alloca_poison call for new created alloca.3742RTCI.createRuntimeCall(IRB, AsanAllocaPoisonFunc, {NewAddress, OldSize});37433744// Store the last alloca's address to DynamicAllocaLayout. We'll need this3745// for unpoisoning stuff.3746IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);37473748Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());37493750// Replace all uses of AddessReturnedByAlloca with NewAddressPtr.3751AI->replaceAllUsesWith(NewAddressPtr);37523753// We are done. Erase old alloca from parent.3754AI->eraseFromParent();3755}37563757// isSafeAccess returns true if Addr is always inbounds with respect to its3758// base object. For example, it is a field access or an array access with3759// constant inbounds index.3760bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,3761Value *Addr, TypeSize TypeStoreSize) const {3762if (TypeStoreSize.isScalable())3763// TODO: We can use vscale_range to convert a scalable value to an3764// upper bound on the access size.3765return false;37663767SizeOffsetAPInt SizeOffset = ObjSizeVis.compute(Addr);3768if (!SizeOffset.bothKnown())3769return false;37703771uint64_t Size = SizeOffset.Size.getZExtValue();3772int64_t Offset = SizeOffset.Offset.getSExtValue();37733774// Three checks are required to ensure safety:3775// . Offset >= 0 (since the offset is given from the base ptr)3776// . Size >= Offset (unsigned)3777// . Size - Offset >= NeededSize (unsigned)3778return Offset >= 0 && Size >= uint64_t(Offset) &&3779Size - uint64_t(Offset) >= TypeStoreSize / 8;3780}378137823783