1*9880d681SAndroid Build Coastguard Worker //===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker // The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This file is a part of AddressSanitizer, an address sanity checker.
11*9880d681SAndroid Build Coastguard Worker // Details of the algorithm:
12*9880d681SAndroid Build Coastguard Worker // http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13*9880d681SAndroid Build Coastguard Worker //
14*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
15*9880d681SAndroid Build Coastguard Worker
16*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/ArrayRef.h"
17*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/DenseMap.h"
18*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/DepthFirstIterator.h"
19*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SetVector.h"
20*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SmallSet.h"
21*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SmallVector.h"
22*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Statistic.h"
23*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/StringExtras.h"
24*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Triple.h"
25*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/MemoryBuiltins.h"
26*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/TargetLibraryInfo.h"
27*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ValueTracking.h"
28*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/CallSite.h"
29*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DIBuilder.h"
30*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DataLayout.h"
31*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Dominators.h"
32*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Function.h"
33*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IRBuilder.h"
34*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/InlineAsm.h"
35*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/InstVisitor.h"
36*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IntrinsicInst.h"
37*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/LLVMContext.h"
38*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/MDBuilder.h"
39*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Module.h"
40*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Type.h"
41*9880d681SAndroid Build Coastguard Worker #include "llvm/MC/MCSectionMachO.h"
42*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/CommandLine.h"
43*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/DataTypes.h"
44*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
45*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Endian.h"
46*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/SwapByteOrder.h"
47*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
48*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Instrumentation.h"
49*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar.h"
50*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
51*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/BasicBlockUtils.h"
52*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/Cloning.h"
53*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/Local.h"
54*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/ModuleUtils.h"
55*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/PromoteMemToReg.h"
56*9880d681SAndroid Build Coastguard Worker #include <algorithm>
57*9880d681SAndroid Build Coastguard Worker #include <string>
58*9880d681SAndroid Build Coastguard Worker #include <system_error>
59*9880d681SAndroid Build Coastguard Worker
60*9880d681SAndroid Build Coastguard Worker using namespace llvm;
61*9880d681SAndroid Build Coastguard Worker
62*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "asan"
63*9880d681SAndroid Build Coastguard Worker
64*9880d681SAndroid Build Coastguard Worker static const uint64_t kDefaultShadowScale = 3;
65*9880d681SAndroid Build Coastguard Worker static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
66*9880d681SAndroid Build Coastguard Worker static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
67*9880d681SAndroid Build Coastguard Worker static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
68*9880d681SAndroid Build Coastguard Worker static const uint64_t kIOSShadowOffset64 = 0x120200000;
69*9880d681SAndroid Build Coastguard Worker static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
70*9880d681SAndroid Build Coastguard Worker static const uint64_t kIOSSimShadowOffset64 = kDefaultShadowOffset64;
71*9880d681SAndroid Build Coastguard Worker static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
72*9880d681SAndroid Build Coastguard Worker static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
73*9880d681SAndroid Build Coastguard Worker static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
74*9880d681SAndroid Build Coastguard Worker static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
75*9880d681SAndroid Build Coastguard Worker static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
76*9880d681SAndroid Build Coastguard Worker static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
77*9880d681SAndroid Build Coastguard Worker static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
78*9880d681SAndroid Build Coastguard Worker static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
79*9880d681SAndroid Build Coastguard Worker static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
80*9880d681SAndroid Build Coastguard Worker static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
81*9880d681SAndroid Build Coastguard Worker // TODO(wwchrome): Experimental for asan Win64, may change.
82*9880d681SAndroid Build Coastguard Worker static const uint64_t kWindowsShadowOffset64 = 0x1ULL << 45; // 32TB.
83*9880d681SAndroid Build Coastguard Worker
84*9880d681SAndroid Build Coastguard Worker static const size_t kMinStackMallocSize = 1 << 6; // 64B
85*9880d681SAndroid Build Coastguard Worker static const size_t kMaxStackMallocSize = 1 << 16; // 64K
86*9880d681SAndroid Build Coastguard Worker static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
87*9880d681SAndroid Build Coastguard Worker static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
88*9880d681SAndroid Build Coastguard Worker
89*9880d681SAndroid Build Coastguard Worker static const char *const kAsanModuleCtorName = "asan.module_ctor";
90*9880d681SAndroid Build Coastguard Worker static const char *const kAsanModuleDtorName = "asan.module_dtor";
91*9880d681SAndroid Build Coastguard Worker static const uint64_t kAsanCtorAndDtorPriority = 1;
92*9880d681SAndroid Build Coastguard Worker static const char *const kAsanReportErrorTemplate = "__asan_report_";
93*9880d681SAndroid Build Coastguard Worker static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
94*9880d681SAndroid Build Coastguard Worker static const char *const kAsanUnregisterGlobalsName =
95*9880d681SAndroid Build Coastguard Worker "__asan_unregister_globals";
96*9880d681SAndroid Build Coastguard Worker static const char *const kAsanRegisterImageGlobalsName =
97*9880d681SAndroid Build Coastguard Worker "__asan_register_image_globals";
98*9880d681SAndroid Build Coastguard Worker static const char *const kAsanUnregisterImageGlobalsName =
99*9880d681SAndroid Build Coastguard Worker "__asan_unregister_image_globals";
100*9880d681SAndroid Build Coastguard Worker static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
101*9880d681SAndroid Build Coastguard Worker static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
102*9880d681SAndroid Build Coastguard Worker static const char *const kAsanInitName = "__asan_init";
103*9880d681SAndroid Build Coastguard Worker static const char *const kAsanVersionCheckName =
104*9880d681SAndroid Build Coastguard Worker "__asan_version_mismatch_check_v8";
105*9880d681SAndroid Build Coastguard Worker static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
106*9880d681SAndroid Build Coastguard Worker static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
107*9880d681SAndroid Build Coastguard Worker static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
108*9880d681SAndroid Build Coastguard Worker static const int kMaxAsanStackMallocSizeClass = 10;
109*9880d681SAndroid Build Coastguard Worker static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
110*9880d681SAndroid Build Coastguard Worker static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
111*9880d681SAndroid Build Coastguard Worker static const char *const kAsanGenPrefix = "__asan_gen_";
112*9880d681SAndroid Build Coastguard Worker static const char *const kODRGenPrefix = "__odr_asan_gen_";
113*9880d681SAndroid Build Coastguard Worker static const char *const kSanCovGenPrefix = "__sancov_gen_";
114*9880d681SAndroid Build Coastguard Worker static const char *const kAsanPoisonStackMemoryName =
115*9880d681SAndroid Build Coastguard Worker "__asan_poison_stack_memory";
116*9880d681SAndroid Build Coastguard Worker static const char *const kAsanUnpoisonStackMemoryName =
117*9880d681SAndroid Build Coastguard Worker "__asan_unpoison_stack_memory";
118*9880d681SAndroid Build Coastguard Worker static const char *const kAsanGlobalsRegisteredFlagName =
119*9880d681SAndroid Build Coastguard Worker "__asan_globals_registered";
120*9880d681SAndroid Build Coastguard Worker
121*9880d681SAndroid Build Coastguard Worker static const char *const kAsanOptionDetectUseAfterReturn =
122*9880d681SAndroid Build Coastguard Worker "__asan_option_detect_stack_use_after_return";
123*9880d681SAndroid Build Coastguard Worker
124*9880d681SAndroid Build Coastguard Worker static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
125*9880d681SAndroid Build Coastguard Worker static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
126*9880d681SAndroid Build Coastguard Worker
127*9880d681SAndroid Build Coastguard Worker // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
128*9880d681SAndroid Build Coastguard Worker static const size_t kNumberOfAccessSizes = 5;
129*9880d681SAndroid Build Coastguard Worker
130*9880d681SAndroid Build Coastguard Worker static const unsigned kAllocaRzSize = 32;
131*9880d681SAndroid Build Coastguard Worker
132*9880d681SAndroid Build Coastguard Worker // Command-line flags.
133*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> ClEnableKasan(
134*9880d681SAndroid Build Coastguard Worker "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
135*9880d681SAndroid Build Coastguard Worker cl::Hidden, cl::init(false));
136*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> ClRecover(
137*9880d681SAndroid Build Coastguard Worker "asan-recover",
138*9880d681SAndroid Build Coastguard Worker cl::desc("Enable recovery mode (continue-after-error)."),
139*9880d681SAndroid Build Coastguard Worker cl::Hidden, cl::init(false));
140*9880d681SAndroid Build Coastguard Worker
141*9880d681SAndroid Build Coastguard Worker // This flag may need to be replaced with -f[no-]asan-reads.
142*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
143*9880d681SAndroid Build Coastguard Worker cl::desc("instrument read instructions"),
144*9880d681SAndroid Build Coastguard Worker cl::Hidden, cl::init(true));
145*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> ClInstrumentWrites(
146*9880d681SAndroid Build Coastguard Worker "asan-instrument-writes", cl::desc("instrument write instructions"),
147*9880d681SAndroid Build Coastguard Worker cl::Hidden, cl::init(true));
148*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> ClInstrumentAtomics(
149*9880d681SAndroid Build Coastguard Worker "asan-instrument-atomics",
150*9880d681SAndroid Build Coastguard Worker cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
151*9880d681SAndroid Build Coastguard Worker cl::init(true));
152*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> ClAlwaysSlowPath(
153*9880d681SAndroid Build Coastguard Worker "asan-always-slow-path",
154*9880d681SAndroid Build Coastguard Worker cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
155*9880d681SAndroid Build Coastguard Worker cl::init(false));
156*9880d681SAndroid Build Coastguard Worker // This flag limits the number of instructions to be instrumented
157*9880d681SAndroid Build Coastguard Worker // in any given BB. Normally, this should be set to unlimited (INT_MAX),
158*9880d681SAndroid Build Coastguard Worker // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
159*9880d681SAndroid Build Coastguard Worker // set it to 10000.
160*9880d681SAndroid Build Coastguard Worker static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
161*9880d681SAndroid Build Coastguard Worker "asan-max-ins-per-bb", cl::init(10000),
162*9880d681SAndroid Build Coastguard Worker cl::desc("maximal number of instructions to instrument in any given BB"),
163*9880d681SAndroid Build Coastguard Worker cl::Hidden);
164*9880d681SAndroid Build Coastguard Worker // This flag may need to be replaced with -f[no]asan-stack.
165*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
166*9880d681SAndroid Build Coastguard Worker cl::Hidden, cl::init(true));
167*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
168*9880d681SAndroid Build Coastguard Worker cl::desc("Check stack-use-after-return"),
169*9880d681SAndroid Build Coastguard Worker cl::Hidden, cl::init(true));
170*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
171*9880d681SAndroid Build Coastguard Worker cl::desc("Check stack-use-after-scope"),
172*9880d681SAndroid Build Coastguard Worker cl::Hidden, cl::init(false));
173*9880d681SAndroid Build Coastguard Worker // This flag may need to be replaced with -f[no]asan-globals.
174*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> ClGlobals("asan-globals",
175*9880d681SAndroid Build Coastguard Worker cl::desc("Handle global objects"), cl::Hidden,
176*9880d681SAndroid Build Coastguard Worker cl::init(true));
177*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> ClInitializers("asan-initialization-order",
178*9880d681SAndroid Build Coastguard Worker cl::desc("Handle C++ initializer order"),
179*9880d681SAndroid Build Coastguard Worker cl::Hidden, cl::init(true));
180*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> ClInvalidPointerPairs(
181*9880d681SAndroid Build Coastguard Worker "asan-detect-invalid-pointer-pair",
182*9880d681SAndroid Build Coastguard Worker cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
183*9880d681SAndroid Build Coastguard Worker cl::init(false));
184*9880d681SAndroid Build Coastguard Worker static cl::opt<unsigned> ClRealignStack(
185*9880d681SAndroid Build Coastguard Worker "asan-realign-stack",
186*9880d681SAndroid Build Coastguard Worker cl::desc("Realign stack to the value of this flag (power of two)"),
187*9880d681SAndroid Build Coastguard Worker cl::Hidden, cl::init(32));
188*9880d681SAndroid Build Coastguard Worker static cl::opt<int> ClInstrumentationWithCallsThreshold(
189*9880d681SAndroid Build Coastguard Worker "asan-instrumentation-with-call-threshold",
190*9880d681SAndroid Build Coastguard Worker cl::desc(
191*9880d681SAndroid Build Coastguard Worker "If the function being instrumented contains more than "
192*9880d681SAndroid Build Coastguard Worker "this number of memory accesses, use callbacks instead of "
193*9880d681SAndroid Build Coastguard Worker "inline checks (-1 means never use callbacks)."),
194*9880d681SAndroid Build Coastguard Worker cl::Hidden, cl::init(7000));
195*9880d681SAndroid Build Coastguard Worker static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
196*9880d681SAndroid Build Coastguard Worker "asan-memory-access-callback-prefix",
197*9880d681SAndroid Build Coastguard Worker cl::desc("Prefix for memory access callbacks"), cl::Hidden,
198*9880d681SAndroid Build Coastguard Worker cl::init("__asan_"));
199*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
200*9880d681SAndroid Build Coastguard Worker cl::desc("instrument dynamic allocas"),
201*9880d681SAndroid Build Coastguard Worker cl::Hidden, cl::init(true));
202*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> ClSkipPromotableAllocas(
203*9880d681SAndroid Build Coastguard Worker "asan-skip-promotable-allocas",
204*9880d681SAndroid Build Coastguard Worker cl::desc("Do not instrument promotable allocas"), cl::Hidden,
205*9880d681SAndroid Build Coastguard Worker cl::init(true));
206*9880d681SAndroid Build Coastguard Worker
207*9880d681SAndroid Build Coastguard Worker // These flags allow to change the shadow mapping.
208*9880d681SAndroid Build Coastguard Worker // The shadow mapping looks like
209*9880d681SAndroid Build Coastguard Worker // Shadow = (Mem >> scale) + offset
210*9880d681SAndroid Build Coastguard Worker static cl::opt<int> ClMappingScale("asan-mapping-scale",
211*9880d681SAndroid Build Coastguard Worker cl::desc("scale of asan shadow mapping"),
212*9880d681SAndroid Build Coastguard Worker cl::Hidden, cl::init(0));
213*9880d681SAndroid Build Coastguard Worker static cl::opt<unsigned long long> ClMappingOffset(
214*9880d681SAndroid Build Coastguard Worker "asan-mapping-offset",
215*9880d681SAndroid Build Coastguard Worker cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden,
216*9880d681SAndroid Build Coastguard Worker cl::init(0));
217*9880d681SAndroid Build Coastguard Worker
218*9880d681SAndroid Build Coastguard Worker // Optimization flags. Not user visible, used mostly for testing
219*9880d681SAndroid Build Coastguard Worker // and benchmarking the tool.
220*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
221*9880d681SAndroid Build Coastguard Worker cl::Hidden, cl::init(true));
222*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> ClOptSameTemp(
223*9880d681SAndroid Build Coastguard Worker "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
224*9880d681SAndroid Build Coastguard Worker cl::Hidden, cl::init(true));
225*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> ClOptGlobals("asan-opt-globals",
226*9880d681SAndroid Build Coastguard Worker cl::desc("Don't instrument scalar globals"),
227*9880d681SAndroid Build Coastguard Worker cl::Hidden, cl::init(true));
228*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> ClOptStack(
229*9880d681SAndroid Build Coastguard Worker "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
230*9880d681SAndroid Build Coastguard Worker cl::Hidden, cl::init(false));
231*9880d681SAndroid Build Coastguard Worker
232*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> ClDynamicAllocaStack(
233*9880d681SAndroid Build Coastguard Worker "asan-stack-dynamic-alloca",
234*9880d681SAndroid Build Coastguard Worker cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
235*9880d681SAndroid Build Coastguard Worker cl::init(true));
236*9880d681SAndroid Build Coastguard Worker
237*9880d681SAndroid Build Coastguard Worker static cl::opt<uint32_t> ClForceExperiment(
238*9880d681SAndroid Build Coastguard Worker "asan-force-experiment",
239*9880d681SAndroid Build Coastguard Worker cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
240*9880d681SAndroid Build Coastguard Worker cl::init(0));
241*9880d681SAndroid Build Coastguard Worker
242*9880d681SAndroid Build Coastguard Worker static cl::opt<bool>
243*9880d681SAndroid Build Coastguard Worker ClUsePrivateAliasForGlobals("asan-use-private-alias",
244*9880d681SAndroid Build Coastguard Worker cl::desc("Use private aliases for global"
245*9880d681SAndroid Build Coastguard Worker " variables"),
246*9880d681SAndroid Build Coastguard Worker cl::Hidden, cl::init(false));
247*9880d681SAndroid Build Coastguard Worker
248*9880d681SAndroid Build Coastguard Worker static cl::opt<bool>
249*9880d681SAndroid Build Coastguard Worker ClUseMachOGlobalsSection("asan-globals-live-support",
250*9880d681SAndroid Build Coastguard Worker cl::desc("Use linker features to support dead "
251*9880d681SAndroid Build Coastguard Worker "code stripping of globals "
252*9880d681SAndroid Build Coastguard Worker "(Mach-O only)"),
253*9880d681SAndroid Build Coastguard Worker cl::Hidden, cl::init(false));
254*9880d681SAndroid Build Coastguard Worker
255*9880d681SAndroid Build Coastguard Worker // Debug flags.
256*9880d681SAndroid Build Coastguard Worker static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
257*9880d681SAndroid Build Coastguard Worker cl::init(0));
258*9880d681SAndroid Build Coastguard Worker static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
259*9880d681SAndroid Build Coastguard Worker cl::Hidden, cl::init(0));
260*9880d681SAndroid Build Coastguard Worker static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
261*9880d681SAndroid Build Coastguard Worker cl::desc("Debug func"));
262*9880d681SAndroid Build Coastguard Worker static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
263*9880d681SAndroid Build Coastguard Worker cl::Hidden, cl::init(-1));
264*9880d681SAndroid Build Coastguard Worker static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
265*9880d681SAndroid Build Coastguard Worker cl::Hidden, cl::init(-1));
266*9880d681SAndroid Build Coastguard Worker
267*9880d681SAndroid Build Coastguard Worker STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
268*9880d681SAndroid Build Coastguard Worker STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
269*9880d681SAndroid Build Coastguard Worker STATISTIC(NumOptimizedAccessesToGlobalVar,
270*9880d681SAndroid Build Coastguard Worker "Number of optimized accesses to global vars");
271*9880d681SAndroid Build Coastguard Worker STATISTIC(NumOptimizedAccessesToStackVar,
272*9880d681SAndroid Build Coastguard Worker "Number of optimized accesses to stack vars");
273*9880d681SAndroid Build Coastguard Worker
274*9880d681SAndroid Build Coastguard Worker namespace {
275*9880d681SAndroid Build Coastguard Worker /// Frontend-provided metadata for source location.
276*9880d681SAndroid Build Coastguard Worker struct LocationMetadata {
277*9880d681SAndroid Build Coastguard Worker StringRef Filename;
278*9880d681SAndroid Build Coastguard Worker int LineNo;
279*9880d681SAndroid Build Coastguard Worker int ColumnNo;
280*9880d681SAndroid Build Coastguard Worker
LocationMetadata__anon806e50680111::LocationMetadata281*9880d681SAndroid Build Coastguard Worker LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
282*9880d681SAndroid Build Coastguard Worker
empty__anon806e50680111::LocationMetadata283*9880d681SAndroid Build Coastguard Worker bool empty() const { return Filename.empty(); }
284*9880d681SAndroid Build Coastguard Worker
parse__anon806e50680111::LocationMetadata285*9880d681SAndroid Build Coastguard Worker void parse(MDNode *MDN) {
286*9880d681SAndroid Build Coastguard Worker assert(MDN->getNumOperands() == 3);
287*9880d681SAndroid Build Coastguard Worker MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
288*9880d681SAndroid Build Coastguard Worker Filename = DIFilename->getString();
289*9880d681SAndroid Build Coastguard Worker LineNo =
290*9880d681SAndroid Build Coastguard Worker mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
291*9880d681SAndroid Build Coastguard Worker ColumnNo =
292*9880d681SAndroid Build Coastguard Worker mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
293*9880d681SAndroid Build Coastguard Worker }
294*9880d681SAndroid Build Coastguard Worker };
295*9880d681SAndroid Build Coastguard Worker
296*9880d681SAndroid Build Coastguard Worker /// Frontend-provided metadata for global variables.
297*9880d681SAndroid Build Coastguard Worker class GlobalsMetadata {
298*9880d681SAndroid Build Coastguard Worker public:
299*9880d681SAndroid Build Coastguard Worker struct Entry {
Entry__anon806e50680111::GlobalsMetadata::Entry300*9880d681SAndroid Build Coastguard Worker Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
301*9880d681SAndroid Build Coastguard Worker LocationMetadata SourceLoc;
302*9880d681SAndroid Build Coastguard Worker StringRef Name;
303*9880d681SAndroid Build Coastguard Worker bool IsDynInit;
304*9880d681SAndroid Build Coastguard Worker bool IsBlacklisted;
305*9880d681SAndroid Build Coastguard Worker };
306*9880d681SAndroid Build Coastguard Worker
GlobalsMetadata()307*9880d681SAndroid Build Coastguard Worker GlobalsMetadata() : inited_(false) {}
308*9880d681SAndroid Build Coastguard Worker
reset()309*9880d681SAndroid Build Coastguard Worker void reset() {
310*9880d681SAndroid Build Coastguard Worker inited_ = false;
311*9880d681SAndroid Build Coastguard Worker Entries.clear();
312*9880d681SAndroid Build Coastguard Worker }
313*9880d681SAndroid Build Coastguard Worker
init(Module & M)314*9880d681SAndroid Build Coastguard Worker void init(Module &M) {
315*9880d681SAndroid Build Coastguard Worker assert(!inited_);
316*9880d681SAndroid Build Coastguard Worker inited_ = true;
317*9880d681SAndroid Build Coastguard Worker NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
318*9880d681SAndroid Build Coastguard Worker if (!Globals) return;
319*9880d681SAndroid Build Coastguard Worker for (auto MDN : Globals->operands()) {
320*9880d681SAndroid Build Coastguard Worker // Metadata node contains the global and the fields of "Entry".
321*9880d681SAndroid Build Coastguard Worker assert(MDN->getNumOperands() == 5);
322*9880d681SAndroid Build Coastguard Worker auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
323*9880d681SAndroid Build Coastguard Worker // The optimizer may optimize away a global entirely.
324*9880d681SAndroid Build Coastguard Worker if (!GV) continue;
325*9880d681SAndroid Build Coastguard Worker // We can already have an entry for GV if it was merged with another
326*9880d681SAndroid Build Coastguard Worker // global.
327*9880d681SAndroid Build Coastguard Worker Entry &E = Entries[GV];
328*9880d681SAndroid Build Coastguard Worker if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
329*9880d681SAndroid Build Coastguard Worker E.SourceLoc.parse(Loc);
330*9880d681SAndroid Build Coastguard Worker if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
331*9880d681SAndroid Build Coastguard Worker E.Name = Name->getString();
332*9880d681SAndroid Build Coastguard Worker ConstantInt *IsDynInit =
333*9880d681SAndroid Build Coastguard Worker mdconst::extract<ConstantInt>(MDN->getOperand(3));
334*9880d681SAndroid Build Coastguard Worker E.IsDynInit |= IsDynInit->isOne();
335*9880d681SAndroid Build Coastguard Worker ConstantInt *IsBlacklisted =
336*9880d681SAndroid Build Coastguard Worker mdconst::extract<ConstantInt>(MDN->getOperand(4));
337*9880d681SAndroid Build Coastguard Worker E.IsBlacklisted |= IsBlacklisted->isOne();
338*9880d681SAndroid Build Coastguard Worker }
339*9880d681SAndroid Build Coastguard Worker }
340*9880d681SAndroid Build Coastguard Worker
341*9880d681SAndroid Build Coastguard Worker /// Returns metadata entry for a given global.
get(GlobalVariable * G) const342*9880d681SAndroid Build Coastguard Worker Entry get(GlobalVariable *G) const {
343*9880d681SAndroid Build Coastguard Worker auto Pos = Entries.find(G);
344*9880d681SAndroid Build Coastguard Worker return (Pos != Entries.end()) ? Pos->second : Entry();
345*9880d681SAndroid Build Coastguard Worker }
346*9880d681SAndroid Build Coastguard Worker
347*9880d681SAndroid Build Coastguard Worker private:
348*9880d681SAndroid Build Coastguard Worker bool inited_;
349*9880d681SAndroid Build Coastguard Worker DenseMap<GlobalVariable *, Entry> Entries;
350*9880d681SAndroid Build Coastguard Worker };
351*9880d681SAndroid Build Coastguard Worker
352*9880d681SAndroid Build Coastguard Worker /// This struct defines the shadow mapping using the rule:
353*9880d681SAndroid Build Coastguard Worker /// shadow = (mem >> Scale) ADD-or-OR Offset.
354*9880d681SAndroid Build Coastguard Worker struct ShadowMapping {
355*9880d681SAndroid Build Coastguard Worker int Scale;
356*9880d681SAndroid Build Coastguard Worker uint64_t Offset;
357*9880d681SAndroid Build Coastguard Worker bool OrShadowOffset;
358*9880d681SAndroid Build Coastguard Worker };
359*9880d681SAndroid Build Coastguard Worker
getShadowMapping(Triple & TargetTriple,int LongSize,bool IsKasan)360*9880d681SAndroid Build Coastguard Worker static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
361*9880d681SAndroid Build Coastguard Worker bool IsKasan) {
362*9880d681SAndroid Build Coastguard Worker bool IsAndroid = TargetTriple.isAndroid();
363*9880d681SAndroid Build Coastguard Worker bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
364*9880d681SAndroid Build Coastguard Worker bool IsFreeBSD = TargetTriple.isOSFreeBSD();
365*9880d681SAndroid Build Coastguard Worker bool IsLinux = TargetTriple.isOSLinux();
366*9880d681SAndroid Build Coastguard Worker bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
367*9880d681SAndroid Build Coastguard Worker TargetTriple.getArch() == llvm::Triple::ppc64le;
368*9880d681SAndroid Build Coastguard Worker bool IsSystemZ = TargetTriple.getArch() == llvm::Triple::systemz;
369*9880d681SAndroid Build Coastguard Worker bool IsX86 = TargetTriple.getArch() == llvm::Triple::x86;
370*9880d681SAndroid Build Coastguard Worker bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
371*9880d681SAndroid Build Coastguard Worker bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
372*9880d681SAndroid Build Coastguard Worker TargetTriple.getArch() == llvm::Triple::mipsel;
373*9880d681SAndroid Build Coastguard Worker bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
374*9880d681SAndroid Build Coastguard Worker TargetTriple.getArch() == llvm::Triple::mips64el;
375*9880d681SAndroid Build Coastguard Worker bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
376*9880d681SAndroid Build Coastguard Worker bool IsWindows = TargetTriple.isOSWindows();
377*9880d681SAndroid Build Coastguard Worker
378*9880d681SAndroid Build Coastguard Worker ShadowMapping Mapping;
379*9880d681SAndroid Build Coastguard Worker
380*9880d681SAndroid Build Coastguard Worker if (LongSize == 32) {
381*9880d681SAndroid Build Coastguard Worker // Android is always PIE, which means that the beginning of the address
382*9880d681SAndroid Build Coastguard Worker // space is always available.
383*9880d681SAndroid Build Coastguard Worker if (IsAndroid)
384*9880d681SAndroid Build Coastguard Worker Mapping.Offset = 0;
385*9880d681SAndroid Build Coastguard Worker else if (IsMIPS32)
386*9880d681SAndroid Build Coastguard Worker Mapping.Offset = kMIPS32_ShadowOffset32;
387*9880d681SAndroid Build Coastguard Worker else if (IsFreeBSD)
388*9880d681SAndroid Build Coastguard Worker Mapping.Offset = kFreeBSD_ShadowOffset32;
389*9880d681SAndroid Build Coastguard Worker else if (IsIOS)
390*9880d681SAndroid Build Coastguard Worker // If we're targeting iOS and x86, the binary is built for iOS simulator.
391*9880d681SAndroid Build Coastguard Worker Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
392*9880d681SAndroid Build Coastguard Worker else if (IsWindows)
393*9880d681SAndroid Build Coastguard Worker Mapping.Offset = kWindowsShadowOffset32;
394*9880d681SAndroid Build Coastguard Worker else
395*9880d681SAndroid Build Coastguard Worker Mapping.Offset = kDefaultShadowOffset32;
396*9880d681SAndroid Build Coastguard Worker } else { // LongSize == 64
397*9880d681SAndroid Build Coastguard Worker if (IsPPC64)
398*9880d681SAndroid Build Coastguard Worker Mapping.Offset = kPPC64_ShadowOffset64;
399*9880d681SAndroid Build Coastguard Worker else if (IsSystemZ)
400*9880d681SAndroid Build Coastguard Worker Mapping.Offset = kSystemZ_ShadowOffset64;
401*9880d681SAndroid Build Coastguard Worker else if (IsFreeBSD)
402*9880d681SAndroid Build Coastguard Worker Mapping.Offset = kFreeBSD_ShadowOffset64;
403*9880d681SAndroid Build Coastguard Worker else if (IsLinux && IsX86_64) {
404*9880d681SAndroid Build Coastguard Worker if (IsKasan)
405*9880d681SAndroid Build Coastguard Worker Mapping.Offset = kLinuxKasan_ShadowOffset64;
406*9880d681SAndroid Build Coastguard Worker else
407*9880d681SAndroid Build Coastguard Worker Mapping.Offset = kSmallX86_64ShadowOffset;
408*9880d681SAndroid Build Coastguard Worker } else if (IsWindows && IsX86_64) {
409*9880d681SAndroid Build Coastguard Worker Mapping.Offset = kWindowsShadowOffset64;
410*9880d681SAndroid Build Coastguard Worker } else if (IsMIPS64)
411*9880d681SAndroid Build Coastguard Worker Mapping.Offset = kMIPS64_ShadowOffset64;
412*9880d681SAndroid Build Coastguard Worker else if (IsIOS)
413*9880d681SAndroid Build Coastguard Worker // If we're targeting iOS and x86, the binary is built for iOS simulator.
414*9880d681SAndroid Build Coastguard Worker Mapping.Offset = IsX86_64 ? kIOSSimShadowOffset64 : kIOSShadowOffset64;
415*9880d681SAndroid Build Coastguard Worker else if (IsAArch64)
416*9880d681SAndroid Build Coastguard Worker Mapping.Offset = kAArch64_ShadowOffset64;
417*9880d681SAndroid Build Coastguard Worker else
418*9880d681SAndroid Build Coastguard Worker Mapping.Offset = kDefaultShadowOffset64;
419*9880d681SAndroid Build Coastguard Worker }
420*9880d681SAndroid Build Coastguard Worker
421*9880d681SAndroid Build Coastguard Worker Mapping.Scale = kDefaultShadowScale;
422*9880d681SAndroid Build Coastguard Worker if (ClMappingScale.getNumOccurrences() > 0) {
423*9880d681SAndroid Build Coastguard Worker Mapping.Scale = ClMappingScale;
424*9880d681SAndroid Build Coastguard Worker }
425*9880d681SAndroid Build Coastguard Worker
426*9880d681SAndroid Build Coastguard Worker if (ClMappingOffset.getNumOccurrences() > 0) {
427*9880d681SAndroid Build Coastguard Worker Mapping.Offset = ClMappingOffset;
428*9880d681SAndroid Build Coastguard Worker }
429*9880d681SAndroid Build Coastguard Worker
430*9880d681SAndroid Build Coastguard Worker // OR-ing shadow offset if more efficient (at least on x86) if the offset
431*9880d681SAndroid Build Coastguard Worker // is a power of two, but on ppc64 we have to use add since the shadow
432*9880d681SAndroid Build Coastguard Worker // offset is not necessary 1/8-th of the address space. On SystemZ,
433*9880d681SAndroid Build Coastguard Worker // we could OR the constant in a single instruction, but it's more
434*9880d681SAndroid Build Coastguard Worker // efficient to load it once and use indexed addressing.
435*9880d681SAndroid Build Coastguard Worker Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ
436*9880d681SAndroid Build Coastguard Worker && !(Mapping.Offset & (Mapping.Offset - 1));
437*9880d681SAndroid Build Coastguard Worker
438*9880d681SAndroid Build Coastguard Worker return Mapping;
439*9880d681SAndroid Build Coastguard Worker }
440*9880d681SAndroid Build Coastguard Worker
RedzoneSizeForScale(int MappingScale)441*9880d681SAndroid Build Coastguard Worker static size_t RedzoneSizeForScale(int MappingScale) {
442*9880d681SAndroid Build Coastguard Worker // Redzone used for stack and globals is at least 32 bytes.
443*9880d681SAndroid Build Coastguard Worker // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
444*9880d681SAndroid Build Coastguard Worker return std::max(32U, 1U << MappingScale);
445*9880d681SAndroid Build Coastguard Worker }
446*9880d681SAndroid Build Coastguard Worker
447*9880d681SAndroid Build Coastguard Worker /// AddressSanitizer: instrument the code in module to find memory bugs.
448*9880d681SAndroid Build Coastguard Worker struct AddressSanitizer : public FunctionPass {
AddressSanitizer__anon806e50680111::AddressSanitizer449*9880d681SAndroid Build Coastguard Worker explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
450*9880d681SAndroid Build Coastguard Worker bool UseAfterScope = false)
451*9880d681SAndroid Build Coastguard Worker : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
452*9880d681SAndroid Build Coastguard Worker Recover(Recover || ClRecover),
453*9880d681SAndroid Build Coastguard Worker UseAfterScope(UseAfterScope || ClUseAfterScope) {
454*9880d681SAndroid Build Coastguard Worker initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
455*9880d681SAndroid Build Coastguard Worker }
getPassName__anon806e50680111::AddressSanitizer456*9880d681SAndroid Build Coastguard Worker const char *getPassName() const override {
457*9880d681SAndroid Build Coastguard Worker return "AddressSanitizerFunctionPass";
458*9880d681SAndroid Build Coastguard Worker }
getAnalysisUsage__anon806e50680111::AddressSanitizer459*9880d681SAndroid Build Coastguard Worker void getAnalysisUsage(AnalysisUsage &AU) const override {
460*9880d681SAndroid Build Coastguard Worker AU.addRequired<DominatorTreeWrapperPass>();
461*9880d681SAndroid Build Coastguard Worker AU.addRequired<TargetLibraryInfoWrapperPass>();
462*9880d681SAndroid Build Coastguard Worker }
getAllocaSizeInBytes__anon806e50680111::AddressSanitizer463*9880d681SAndroid Build Coastguard Worker uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
464*9880d681SAndroid Build Coastguard Worker uint64_t ArraySize = 1;
465*9880d681SAndroid Build Coastguard Worker if (AI->isArrayAllocation()) {
466*9880d681SAndroid Build Coastguard Worker ConstantInt *CI = dyn_cast<ConstantInt>(AI->getArraySize());
467*9880d681SAndroid Build Coastguard Worker assert(CI && "non-constant array size");
468*9880d681SAndroid Build Coastguard Worker ArraySize = CI->getZExtValue();
469*9880d681SAndroid Build Coastguard Worker }
470*9880d681SAndroid Build Coastguard Worker Type *Ty = AI->getAllocatedType();
471*9880d681SAndroid Build Coastguard Worker uint64_t SizeInBytes =
472*9880d681SAndroid Build Coastguard Worker AI->getModule()->getDataLayout().getTypeAllocSize(Ty);
473*9880d681SAndroid Build Coastguard Worker return SizeInBytes * ArraySize;
474*9880d681SAndroid Build Coastguard Worker }
475*9880d681SAndroid Build Coastguard Worker /// Check if we want (and can) handle this alloca.
476*9880d681SAndroid Build Coastguard Worker bool isInterestingAlloca(AllocaInst &AI);
477*9880d681SAndroid Build Coastguard Worker
478*9880d681SAndroid Build Coastguard Worker /// If it is an interesting memory access, return the PointerOperand
479*9880d681SAndroid Build Coastguard Worker /// and set IsWrite/Alignment. Otherwise return nullptr.
480*9880d681SAndroid Build Coastguard Worker Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
481*9880d681SAndroid Build Coastguard Worker uint64_t *TypeSize, unsigned *Alignment);
482*9880d681SAndroid Build Coastguard Worker void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
483*9880d681SAndroid Build Coastguard Worker bool UseCalls, const DataLayout &DL);
484*9880d681SAndroid Build Coastguard Worker void instrumentPointerComparisonOrSubtraction(Instruction *I);
485*9880d681SAndroid Build Coastguard Worker void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
486*9880d681SAndroid Build Coastguard Worker Value *Addr, uint32_t TypeSize, bool IsWrite,
487*9880d681SAndroid Build Coastguard Worker Value *SizeArgument, bool UseCalls, uint32_t Exp);
488*9880d681SAndroid Build Coastguard Worker void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
489*9880d681SAndroid Build Coastguard Worker uint32_t TypeSize, bool IsWrite,
490*9880d681SAndroid Build Coastguard Worker Value *SizeArgument, bool UseCalls,
491*9880d681SAndroid Build Coastguard Worker uint32_t Exp);
492*9880d681SAndroid Build Coastguard Worker Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
493*9880d681SAndroid Build Coastguard Worker Value *ShadowValue, uint32_t TypeSize);
494*9880d681SAndroid Build Coastguard Worker Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
495*9880d681SAndroid Build Coastguard Worker bool IsWrite, size_t AccessSizeIndex,
496*9880d681SAndroid Build Coastguard Worker Value *SizeArgument, uint32_t Exp);
497*9880d681SAndroid Build Coastguard Worker void instrumentMemIntrinsic(MemIntrinsic *MI);
498*9880d681SAndroid Build Coastguard Worker Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
499*9880d681SAndroid Build Coastguard Worker bool runOnFunction(Function &F) override;
500*9880d681SAndroid Build Coastguard Worker bool maybeInsertAsanInitAtFunctionEntry(Function &F);
501*9880d681SAndroid Build Coastguard Worker void markEscapedLocalAllocas(Function &F);
502*9880d681SAndroid Build Coastguard Worker bool doInitialization(Module &M) override;
503*9880d681SAndroid Build Coastguard Worker bool doFinalization(Module &M) override;
504*9880d681SAndroid Build Coastguard Worker static char ID; // Pass identification, replacement for typeid
505*9880d681SAndroid Build Coastguard Worker
getDominatorTree__anon806e50680111::AddressSanitizer506*9880d681SAndroid Build Coastguard Worker DominatorTree &getDominatorTree() const { return *DT; }
507*9880d681SAndroid Build Coastguard Worker
508*9880d681SAndroid Build Coastguard Worker private:
509*9880d681SAndroid Build Coastguard Worker void initializeCallbacks(Module &M);
510*9880d681SAndroid Build Coastguard Worker
511*9880d681SAndroid Build Coastguard Worker bool LooksLikeCodeInBug11395(Instruction *I);
512*9880d681SAndroid Build Coastguard Worker bool GlobalIsLinkerInitialized(GlobalVariable *G);
513*9880d681SAndroid Build Coastguard Worker bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
514*9880d681SAndroid Build Coastguard Worker uint64_t TypeSize) const;
515*9880d681SAndroid Build Coastguard Worker
516*9880d681SAndroid Build Coastguard Worker /// Helper to cleanup per-function state.
517*9880d681SAndroid Build Coastguard Worker struct FunctionStateRAII {
518*9880d681SAndroid Build Coastguard Worker AddressSanitizer *Pass;
FunctionStateRAII__anon806e50680111::AddressSanitizer::FunctionStateRAII519*9880d681SAndroid Build Coastguard Worker FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
520*9880d681SAndroid Build Coastguard Worker assert(Pass->ProcessedAllocas.empty() &&
521*9880d681SAndroid Build Coastguard Worker "last pass forgot to clear cache");
522*9880d681SAndroid Build Coastguard Worker }
~FunctionStateRAII__anon806e50680111::AddressSanitizer::FunctionStateRAII523*9880d681SAndroid Build Coastguard Worker ~FunctionStateRAII() { Pass->ProcessedAllocas.clear(); }
524*9880d681SAndroid Build Coastguard Worker };
525*9880d681SAndroid Build Coastguard Worker
526*9880d681SAndroid Build Coastguard Worker LLVMContext *C;
527*9880d681SAndroid Build Coastguard Worker Triple TargetTriple;
528*9880d681SAndroid Build Coastguard Worker int LongSize;
529*9880d681SAndroid Build Coastguard Worker bool CompileKernel;
530*9880d681SAndroid Build Coastguard Worker bool Recover;
531*9880d681SAndroid Build Coastguard Worker bool UseAfterScope;
532*9880d681SAndroid Build Coastguard Worker Type *IntptrTy;
533*9880d681SAndroid Build Coastguard Worker ShadowMapping Mapping;
534*9880d681SAndroid Build Coastguard Worker DominatorTree *DT;
535*9880d681SAndroid Build Coastguard Worker Function *AsanCtorFunction = nullptr;
536*9880d681SAndroid Build Coastguard Worker Function *AsanInitFunction = nullptr;
537*9880d681SAndroid Build Coastguard Worker Function *AsanHandleNoReturnFunc;
538*9880d681SAndroid Build Coastguard Worker Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
539*9880d681SAndroid Build Coastguard Worker // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
540*9880d681SAndroid Build Coastguard Worker Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
541*9880d681SAndroid Build Coastguard Worker Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
542*9880d681SAndroid Build Coastguard Worker // This array is indexed by AccessIsWrite and Experiment.
543*9880d681SAndroid Build Coastguard Worker Function *AsanErrorCallbackSized[2][2];
544*9880d681SAndroid Build Coastguard Worker Function *AsanMemoryAccessCallbackSized[2][2];
545*9880d681SAndroid Build Coastguard Worker Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
546*9880d681SAndroid Build Coastguard Worker InlineAsm *EmptyAsm;
547*9880d681SAndroid Build Coastguard Worker GlobalsMetadata GlobalsMD;
548*9880d681SAndroid Build Coastguard Worker DenseMap<AllocaInst *, bool> ProcessedAllocas;
549*9880d681SAndroid Build Coastguard Worker
550*9880d681SAndroid Build Coastguard Worker friend struct FunctionStackPoisoner;
551*9880d681SAndroid Build Coastguard Worker };
552*9880d681SAndroid Build Coastguard Worker
553*9880d681SAndroid Build Coastguard Worker class AddressSanitizerModule : public ModulePass {
554*9880d681SAndroid Build Coastguard Worker public:
AddressSanitizerModule(bool CompileKernel=false,bool Recover=false)555*9880d681SAndroid Build Coastguard Worker explicit AddressSanitizerModule(bool CompileKernel = false,
556*9880d681SAndroid Build Coastguard Worker bool Recover = false)
557*9880d681SAndroid Build Coastguard Worker : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
558*9880d681SAndroid Build Coastguard Worker Recover(Recover || ClRecover) {}
559*9880d681SAndroid Build Coastguard Worker bool runOnModule(Module &M) override;
560*9880d681SAndroid Build Coastguard Worker static char ID; // Pass identification, replacement for typeid
getPassName() const561*9880d681SAndroid Build Coastguard Worker const char *getPassName() const override { return "AddressSanitizerModule"; }
562*9880d681SAndroid Build Coastguard Worker
563*9880d681SAndroid Build Coastguard Worker private:
564*9880d681SAndroid Build Coastguard Worker void initializeCallbacks(Module &M);
565*9880d681SAndroid Build Coastguard Worker
566*9880d681SAndroid Build Coastguard Worker bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
567*9880d681SAndroid Build Coastguard Worker bool ShouldInstrumentGlobal(GlobalVariable *G);
568*9880d681SAndroid Build Coastguard Worker bool ShouldUseMachOGlobalsSection() const;
569*9880d681SAndroid Build Coastguard Worker void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
570*9880d681SAndroid Build Coastguard Worker void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
MinRedzoneSizeForGlobal() const571*9880d681SAndroid Build Coastguard Worker size_t MinRedzoneSizeForGlobal() const {
572*9880d681SAndroid Build Coastguard Worker return RedzoneSizeForScale(Mapping.Scale);
573*9880d681SAndroid Build Coastguard Worker }
574*9880d681SAndroid Build Coastguard Worker
575*9880d681SAndroid Build Coastguard Worker GlobalsMetadata GlobalsMD;
576*9880d681SAndroid Build Coastguard Worker bool CompileKernel;
577*9880d681SAndroid Build Coastguard Worker bool Recover;
578*9880d681SAndroid Build Coastguard Worker Type *IntptrTy;
579*9880d681SAndroid Build Coastguard Worker LLVMContext *C;
580*9880d681SAndroid Build Coastguard Worker Triple TargetTriple;
581*9880d681SAndroid Build Coastguard Worker ShadowMapping Mapping;
582*9880d681SAndroid Build Coastguard Worker Function *AsanPoisonGlobals;
583*9880d681SAndroid Build Coastguard Worker Function *AsanUnpoisonGlobals;
584*9880d681SAndroid Build Coastguard Worker Function *AsanRegisterGlobals;
585*9880d681SAndroid Build Coastguard Worker Function *AsanUnregisterGlobals;
586*9880d681SAndroid Build Coastguard Worker Function *AsanRegisterImageGlobals;
587*9880d681SAndroid Build Coastguard Worker Function *AsanUnregisterImageGlobals;
588*9880d681SAndroid Build Coastguard Worker };
589*9880d681SAndroid Build Coastguard Worker
590*9880d681SAndroid Build Coastguard Worker // Stack poisoning does not play well with exception handling.
591*9880d681SAndroid Build Coastguard Worker // When an exception is thrown, we essentially bypass the code
592*9880d681SAndroid Build Coastguard Worker // that unpoisones the stack. This is why the run-time library has
593*9880d681SAndroid Build Coastguard Worker // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
594*9880d681SAndroid Build Coastguard Worker // stack in the interceptor. This however does not work inside the
595*9880d681SAndroid Build Coastguard Worker // actual function which catches the exception. Most likely because the
596*9880d681SAndroid Build Coastguard Worker // compiler hoists the load of the shadow value somewhere too high.
597*9880d681SAndroid Build Coastguard Worker // This causes asan to report a non-existing bug on 453.povray.
598*9880d681SAndroid Build Coastguard Worker // It sounds like an LLVM bug.
599*9880d681SAndroid Build Coastguard Worker struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
600*9880d681SAndroid Build Coastguard Worker Function &F;
601*9880d681SAndroid Build Coastguard Worker AddressSanitizer &ASan;
602*9880d681SAndroid Build Coastguard Worker DIBuilder DIB;
603*9880d681SAndroid Build Coastguard Worker LLVMContext *C;
604*9880d681SAndroid Build Coastguard Worker Type *IntptrTy;
605*9880d681SAndroid Build Coastguard Worker Type *IntptrPtrTy;
606*9880d681SAndroid Build Coastguard Worker ShadowMapping Mapping;
607*9880d681SAndroid Build Coastguard Worker
608*9880d681SAndroid Build Coastguard Worker SmallVector<AllocaInst *, 16> AllocaVec;
609*9880d681SAndroid Build Coastguard Worker SmallSetVector<AllocaInst *, 16> NonInstrumentedStaticAllocaVec;
610*9880d681SAndroid Build Coastguard Worker SmallVector<Instruction *, 8> RetVec;
611*9880d681SAndroid Build Coastguard Worker unsigned StackAlignment;
612*9880d681SAndroid Build Coastguard Worker
613*9880d681SAndroid Build Coastguard Worker Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
614*9880d681SAndroid Build Coastguard Worker *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
615*9880d681SAndroid Build Coastguard Worker Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
616*9880d681SAndroid Build Coastguard Worker Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
617*9880d681SAndroid Build Coastguard Worker
618*9880d681SAndroid Build Coastguard Worker // Stores a place and arguments of poisoning/unpoisoning call for alloca.
619*9880d681SAndroid Build Coastguard Worker struct AllocaPoisonCall {
620*9880d681SAndroid Build Coastguard Worker IntrinsicInst *InsBefore;
621*9880d681SAndroid Build Coastguard Worker AllocaInst *AI;
622*9880d681SAndroid Build Coastguard Worker uint64_t Size;
623*9880d681SAndroid Build Coastguard Worker bool DoPoison;
624*9880d681SAndroid Build Coastguard Worker };
625*9880d681SAndroid Build Coastguard Worker SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
626*9880d681SAndroid Build Coastguard Worker
627*9880d681SAndroid Build Coastguard Worker SmallVector<AllocaInst *, 1> DynamicAllocaVec;
628*9880d681SAndroid Build Coastguard Worker SmallVector<IntrinsicInst *, 1> StackRestoreVec;
629*9880d681SAndroid Build Coastguard Worker AllocaInst *DynamicAllocaLayout = nullptr;
630*9880d681SAndroid Build Coastguard Worker IntrinsicInst *LocalEscapeCall = nullptr;
631*9880d681SAndroid Build Coastguard Worker
632*9880d681SAndroid Build Coastguard Worker // Maps Value to an AllocaInst from which the Value is originated.
633*9880d681SAndroid Build Coastguard Worker typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
634*9880d681SAndroid Build Coastguard Worker AllocaForValueMapTy AllocaForValue;
635*9880d681SAndroid Build Coastguard Worker
636*9880d681SAndroid Build Coastguard Worker bool HasNonEmptyInlineAsm = false;
637*9880d681SAndroid Build Coastguard Worker bool HasReturnsTwiceCall = false;
638*9880d681SAndroid Build Coastguard Worker std::unique_ptr<CallInst> EmptyInlineAsm;
639*9880d681SAndroid Build Coastguard Worker
FunctionStackPoisoner__anon806e50680111::FunctionStackPoisoner640*9880d681SAndroid Build Coastguard Worker FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
641*9880d681SAndroid Build Coastguard Worker : F(F),
642*9880d681SAndroid Build Coastguard Worker ASan(ASan),
643*9880d681SAndroid Build Coastguard Worker DIB(*F.getParent(), /*AllowUnresolved*/ false),
644*9880d681SAndroid Build Coastguard Worker C(ASan.C),
645*9880d681SAndroid Build Coastguard Worker IntptrTy(ASan.IntptrTy),
646*9880d681SAndroid Build Coastguard Worker IntptrPtrTy(PointerType::get(IntptrTy, 0)),
647*9880d681SAndroid Build Coastguard Worker Mapping(ASan.Mapping),
648*9880d681SAndroid Build Coastguard Worker StackAlignment(1 << Mapping.Scale),
649*9880d681SAndroid Build Coastguard Worker EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
650*9880d681SAndroid Build Coastguard Worker
runOnFunction__anon806e50680111::FunctionStackPoisoner651*9880d681SAndroid Build Coastguard Worker bool runOnFunction() {
652*9880d681SAndroid Build Coastguard Worker if (!ClStack) return false;
653*9880d681SAndroid Build Coastguard Worker // Collect alloca, ret, lifetime instructions etc.
654*9880d681SAndroid Build Coastguard Worker for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
655*9880d681SAndroid Build Coastguard Worker
656*9880d681SAndroid Build Coastguard Worker if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
657*9880d681SAndroid Build Coastguard Worker
658*9880d681SAndroid Build Coastguard Worker initializeCallbacks(*F.getParent());
659*9880d681SAndroid Build Coastguard Worker
660*9880d681SAndroid Build Coastguard Worker poisonStack();
661*9880d681SAndroid Build Coastguard Worker
662*9880d681SAndroid Build Coastguard Worker if (ClDebugStack) {
663*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << F);
664*9880d681SAndroid Build Coastguard Worker }
665*9880d681SAndroid Build Coastguard Worker return true;
666*9880d681SAndroid Build Coastguard Worker }
667*9880d681SAndroid Build Coastguard Worker
668*9880d681SAndroid Build Coastguard Worker // Finds all Alloca instructions and puts
669*9880d681SAndroid Build Coastguard Worker // poisoned red zones around all of them.
670*9880d681SAndroid Build Coastguard Worker // Then unpoison everything back before the function returns.
671*9880d681SAndroid Build Coastguard Worker void poisonStack();
672*9880d681SAndroid Build Coastguard Worker
673*9880d681SAndroid Build Coastguard Worker void createDynamicAllocasInitStorage();
674*9880d681SAndroid Build Coastguard Worker
675*9880d681SAndroid Build Coastguard Worker // ----------------------- Visitors.
676*9880d681SAndroid Build Coastguard Worker /// \brief Collect all Ret instructions.
visitReturnInst__anon806e50680111::FunctionStackPoisoner677*9880d681SAndroid Build Coastguard Worker void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
678*9880d681SAndroid Build Coastguard Worker
unpoisonDynamicAllocasBeforeInst__anon806e50680111::FunctionStackPoisoner679*9880d681SAndroid Build Coastguard Worker void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
680*9880d681SAndroid Build Coastguard Worker Value *SavedStack) {
681*9880d681SAndroid Build Coastguard Worker IRBuilder<> IRB(InstBefore);
682*9880d681SAndroid Build Coastguard Worker Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
683*9880d681SAndroid Build Coastguard Worker // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
684*9880d681SAndroid Build Coastguard Worker // need to adjust extracted SP to compute the address of the most recent
685*9880d681SAndroid Build Coastguard Worker // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
686*9880d681SAndroid Build Coastguard Worker // this purpose.
687*9880d681SAndroid Build Coastguard Worker if (!isa<ReturnInst>(InstBefore)) {
688*9880d681SAndroid Build Coastguard Worker Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
689*9880d681SAndroid Build Coastguard Worker InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
690*9880d681SAndroid Build Coastguard Worker {IntptrTy});
691*9880d681SAndroid Build Coastguard Worker
692*9880d681SAndroid Build Coastguard Worker Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
693*9880d681SAndroid Build Coastguard Worker
694*9880d681SAndroid Build Coastguard Worker DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
695*9880d681SAndroid Build Coastguard Worker DynamicAreaOffset);
696*9880d681SAndroid Build Coastguard Worker }
697*9880d681SAndroid Build Coastguard Worker
698*9880d681SAndroid Build Coastguard Worker IRB.CreateCall(AsanAllocasUnpoisonFunc,
699*9880d681SAndroid Build Coastguard Worker {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
700*9880d681SAndroid Build Coastguard Worker }
701*9880d681SAndroid Build Coastguard Worker
702*9880d681SAndroid Build Coastguard Worker // Unpoison dynamic allocas redzones.
unpoisonDynamicAllocas__anon806e50680111::FunctionStackPoisoner703*9880d681SAndroid Build Coastguard Worker void unpoisonDynamicAllocas() {
704*9880d681SAndroid Build Coastguard Worker for (auto &Ret : RetVec)
705*9880d681SAndroid Build Coastguard Worker unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
706*9880d681SAndroid Build Coastguard Worker
707*9880d681SAndroid Build Coastguard Worker for (auto &StackRestoreInst : StackRestoreVec)
708*9880d681SAndroid Build Coastguard Worker unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
709*9880d681SAndroid Build Coastguard Worker StackRestoreInst->getOperand(0));
710*9880d681SAndroid Build Coastguard Worker }
711*9880d681SAndroid Build Coastguard Worker
712*9880d681SAndroid Build Coastguard Worker // Deploy and poison redzones around dynamic alloca call. To do this, we
713*9880d681SAndroid Build Coastguard Worker // should replace this call with another one with changed parameters and
714*9880d681SAndroid Build Coastguard Worker // replace all its uses with new address, so
715*9880d681SAndroid Build Coastguard Worker // addr = alloca type, old_size, align
716*9880d681SAndroid Build Coastguard Worker // is replaced by
717*9880d681SAndroid Build Coastguard Worker // new_size = (old_size + additional_size) * sizeof(type)
718*9880d681SAndroid Build Coastguard Worker // tmp = alloca i8, new_size, max(align, 32)
719*9880d681SAndroid Build Coastguard Worker // addr = tmp + 32 (first 32 bytes are for the left redzone).
720*9880d681SAndroid Build Coastguard Worker // Additional_size is added to make new memory allocation contain not only
721*9880d681SAndroid Build Coastguard Worker // requested memory, but also left, partial and right redzones.
722*9880d681SAndroid Build Coastguard Worker void handleDynamicAllocaCall(AllocaInst *AI);
723*9880d681SAndroid Build Coastguard Worker
724*9880d681SAndroid Build Coastguard Worker /// \brief Collect Alloca instructions we want (and can) handle.
visitAllocaInst__anon806e50680111::FunctionStackPoisoner725*9880d681SAndroid Build Coastguard Worker void visitAllocaInst(AllocaInst &AI) {
726*9880d681SAndroid Build Coastguard Worker if (!ASan.isInterestingAlloca(AI)) {
727*9880d681SAndroid Build Coastguard Worker if (AI.isStaticAlloca()) NonInstrumentedStaticAllocaVec.insert(&AI);
728*9880d681SAndroid Build Coastguard Worker return;
729*9880d681SAndroid Build Coastguard Worker }
730*9880d681SAndroid Build Coastguard Worker
731*9880d681SAndroid Build Coastguard Worker StackAlignment = std::max(StackAlignment, AI.getAlignment());
732*9880d681SAndroid Build Coastguard Worker if (!AI.isStaticAlloca())
733*9880d681SAndroid Build Coastguard Worker DynamicAllocaVec.push_back(&AI);
734*9880d681SAndroid Build Coastguard Worker else
735*9880d681SAndroid Build Coastguard Worker AllocaVec.push_back(&AI);
736*9880d681SAndroid Build Coastguard Worker }
737*9880d681SAndroid Build Coastguard Worker
738*9880d681SAndroid Build Coastguard Worker /// \brief Collect lifetime intrinsic calls to check for use-after-scope
739*9880d681SAndroid Build Coastguard Worker /// errors.
visitIntrinsicInst__anon806e50680111::FunctionStackPoisoner740*9880d681SAndroid Build Coastguard Worker void visitIntrinsicInst(IntrinsicInst &II) {
741*9880d681SAndroid Build Coastguard Worker Intrinsic::ID ID = II.getIntrinsicID();
742*9880d681SAndroid Build Coastguard Worker if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
743*9880d681SAndroid Build Coastguard Worker if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
744*9880d681SAndroid Build Coastguard Worker if (!ASan.UseAfterScope)
745*9880d681SAndroid Build Coastguard Worker return;
746*9880d681SAndroid Build Coastguard Worker if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
747*9880d681SAndroid Build Coastguard Worker return;
748*9880d681SAndroid Build Coastguard Worker // Found lifetime intrinsic, add ASan instrumentation if necessary.
749*9880d681SAndroid Build Coastguard Worker ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
750*9880d681SAndroid Build Coastguard Worker // If size argument is undefined, don't do anything.
751*9880d681SAndroid Build Coastguard Worker if (Size->isMinusOne()) return;
752*9880d681SAndroid Build Coastguard Worker // Check that size doesn't saturate uint64_t and can
753*9880d681SAndroid Build Coastguard Worker // be stored in IntptrTy.
754*9880d681SAndroid Build Coastguard Worker const uint64_t SizeValue = Size->getValue().getLimitedValue();
755*9880d681SAndroid Build Coastguard Worker if (SizeValue == ~0ULL ||
756*9880d681SAndroid Build Coastguard Worker !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
757*9880d681SAndroid Build Coastguard Worker return;
758*9880d681SAndroid Build Coastguard Worker // Find alloca instruction that corresponds to llvm.lifetime argument.
759*9880d681SAndroid Build Coastguard Worker AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
760*9880d681SAndroid Build Coastguard Worker if (!AI || !ASan.isInterestingAlloca(*AI))
761*9880d681SAndroid Build Coastguard Worker return;
762*9880d681SAndroid Build Coastguard Worker bool DoPoison = (ID == Intrinsic::lifetime_end);
763*9880d681SAndroid Build Coastguard Worker AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
764*9880d681SAndroid Build Coastguard Worker AllocaPoisonCallVec.push_back(APC);
765*9880d681SAndroid Build Coastguard Worker }
766*9880d681SAndroid Build Coastguard Worker
visitCallSite__anon806e50680111::FunctionStackPoisoner767*9880d681SAndroid Build Coastguard Worker void visitCallSite(CallSite CS) {
768*9880d681SAndroid Build Coastguard Worker Instruction *I = CS.getInstruction();
769*9880d681SAndroid Build Coastguard Worker if (CallInst *CI = dyn_cast<CallInst>(I)) {
770*9880d681SAndroid Build Coastguard Worker HasNonEmptyInlineAsm |=
771*9880d681SAndroid Build Coastguard Worker CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
772*9880d681SAndroid Build Coastguard Worker HasReturnsTwiceCall |= CI->canReturnTwice();
773*9880d681SAndroid Build Coastguard Worker }
774*9880d681SAndroid Build Coastguard Worker }
775*9880d681SAndroid Build Coastguard Worker
776*9880d681SAndroid Build Coastguard Worker // ---------------------- Helpers.
777*9880d681SAndroid Build Coastguard Worker void initializeCallbacks(Module &M);
778*9880d681SAndroid Build Coastguard Worker
doesDominateAllExits__anon806e50680111::FunctionStackPoisoner779*9880d681SAndroid Build Coastguard Worker bool doesDominateAllExits(const Instruction *I) const {
780*9880d681SAndroid Build Coastguard Worker for (auto Ret : RetVec) {
781*9880d681SAndroid Build Coastguard Worker if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
782*9880d681SAndroid Build Coastguard Worker }
783*9880d681SAndroid Build Coastguard Worker return true;
784*9880d681SAndroid Build Coastguard Worker }
785*9880d681SAndroid Build Coastguard Worker
786*9880d681SAndroid Build Coastguard Worker /// Finds alloca where the value comes from.
787*9880d681SAndroid Build Coastguard Worker AllocaInst *findAllocaForValue(Value *V);
788*9880d681SAndroid Build Coastguard Worker void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
789*9880d681SAndroid Build Coastguard Worker Value *ShadowBase, bool DoPoison);
790*9880d681SAndroid Build Coastguard Worker void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
791*9880d681SAndroid Build Coastguard Worker
792*9880d681SAndroid Build Coastguard Worker void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
793*9880d681SAndroid Build Coastguard Worker int Size);
794*9880d681SAndroid Build Coastguard Worker Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
795*9880d681SAndroid Build Coastguard Worker bool Dynamic);
796*9880d681SAndroid Build Coastguard Worker PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
797*9880d681SAndroid Build Coastguard Worker Instruction *ThenTerm, Value *ValueIfFalse);
798*9880d681SAndroid Build Coastguard Worker };
799*9880d681SAndroid Build Coastguard Worker
800*9880d681SAndroid Build Coastguard Worker } // anonymous namespace
801*9880d681SAndroid Build Coastguard Worker
802*9880d681SAndroid Build Coastguard Worker char AddressSanitizer::ID = 0;
803*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_BEGIN(
804*9880d681SAndroid Build Coastguard Worker AddressSanitizer, "asan",
805*9880d681SAndroid Build Coastguard Worker "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
806*9880d681SAndroid Build Coastguard Worker false)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)807*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
808*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
809*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_END(
810*9880d681SAndroid Build Coastguard Worker AddressSanitizer, "asan",
811*9880d681SAndroid Build Coastguard Worker "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
812*9880d681SAndroid Build Coastguard Worker false)
813*9880d681SAndroid Build Coastguard Worker FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
814*9880d681SAndroid Build Coastguard Worker bool Recover,
815*9880d681SAndroid Build Coastguard Worker bool UseAfterScope) {
816*9880d681SAndroid Build Coastguard Worker assert(!CompileKernel || Recover);
817*9880d681SAndroid Build Coastguard Worker return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
818*9880d681SAndroid Build Coastguard Worker }
819*9880d681SAndroid Build Coastguard Worker
820*9880d681SAndroid Build Coastguard Worker char AddressSanitizerModule::ID = 0;
821*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS(
822*9880d681SAndroid Build Coastguard Worker AddressSanitizerModule, "asan-module",
823*9880d681SAndroid Build Coastguard Worker "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
824*9880d681SAndroid Build Coastguard Worker "ModulePass",
825*9880d681SAndroid Build Coastguard Worker false, false)
createAddressSanitizerModulePass(bool CompileKernel,bool Recover)826*9880d681SAndroid Build Coastguard Worker ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
827*9880d681SAndroid Build Coastguard Worker bool Recover) {
828*9880d681SAndroid Build Coastguard Worker assert(!CompileKernel || Recover);
829*9880d681SAndroid Build Coastguard Worker return new AddressSanitizerModule(CompileKernel, Recover);
830*9880d681SAndroid Build Coastguard Worker }
831*9880d681SAndroid Build Coastguard Worker
TypeSizeToSizeIndex(uint32_t TypeSize)832*9880d681SAndroid Build Coastguard Worker static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
833*9880d681SAndroid Build Coastguard Worker size_t Res = countTrailingZeros(TypeSize / 8);
834*9880d681SAndroid Build Coastguard Worker assert(Res < kNumberOfAccessSizes);
835*9880d681SAndroid Build Coastguard Worker return Res;
836*9880d681SAndroid Build Coastguard Worker }
837*9880d681SAndroid Build Coastguard Worker
838*9880d681SAndroid Build Coastguard Worker // \brief Create a constant for Str so that we can pass it to the run-time lib.
createPrivateGlobalForString(Module & M,StringRef Str,bool AllowMerging)839*9880d681SAndroid Build Coastguard Worker static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
840*9880d681SAndroid Build Coastguard Worker bool AllowMerging) {
841*9880d681SAndroid Build Coastguard Worker Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
842*9880d681SAndroid Build Coastguard Worker // We use private linkage for module-local strings. If they can be merged
843*9880d681SAndroid Build Coastguard Worker // with another one, we set the unnamed_addr attribute.
844*9880d681SAndroid Build Coastguard Worker GlobalVariable *GV =
845*9880d681SAndroid Build Coastguard Worker new GlobalVariable(M, StrConst->getType(), true,
846*9880d681SAndroid Build Coastguard Worker GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
847*9880d681SAndroid Build Coastguard Worker if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
848*9880d681SAndroid Build Coastguard Worker GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
849*9880d681SAndroid Build Coastguard Worker return GV;
850*9880d681SAndroid Build Coastguard Worker }
851*9880d681SAndroid Build Coastguard Worker
852*9880d681SAndroid Build Coastguard Worker /// \brief Create a global describing a source location.
createPrivateGlobalForSourceLoc(Module & M,LocationMetadata MD)853*9880d681SAndroid Build Coastguard Worker static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
854*9880d681SAndroid Build Coastguard Worker LocationMetadata MD) {
855*9880d681SAndroid Build Coastguard Worker Constant *LocData[] = {
856*9880d681SAndroid Build Coastguard Worker createPrivateGlobalForString(M, MD.Filename, true),
857*9880d681SAndroid Build Coastguard Worker ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
858*9880d681SAndroid Build Coastguard Worker ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
859*9880d681SAndroid Build Coastguard Worker };
860*9880d681SAndroid Build Coastguard Worker auto LocStruct = ConstantStruct::getAnon(LocData);
861*9880d681SAndroid Build Coastguard Worker auto GV = new GlobalVariable(M, LocStruct->getType(), true,
862*9880d681SAndroid Build Coastguard Worker GlobalValue::PrivateLinkage, LocStruct,
863*9880d681SAndroid Build Coastguard Worker kAsanGenPrefix);
864*9880d681SAndroid Build Coastguard Worker GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
865*9880d681SAndroid Build Coastguard Worker return GV;
866*9880d681SAndroid Build Coastguard Worker }
867*9880d681SAndroid Build Coastguard Worker
868*9880d681SAndroid Build Coastguard Worker /// \brief Check if \p G has been created by a trusted compiler pass.
GlobalWasGeneratedByCompiler(GlobalVariable * G)869*9880d681SAndroid Build Coastguard Worker static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
870*9880d681SAndroid Build Coastguard Worker // Do not instrument asan globals.
871*9880d681SAndroid Build Coastguard Worker if (G->getName().startswith(kAsanGenPrefix) ||
872*9880d681SAndroid Build Coastguard Worker G->getName().startswith(kSanCovGenPrefix) ||
873*9880d681SAndroid Build Coastguard Worker G->getName().startswith(kODRGenPrefix))
874*9880d681SAndroid Build Coastguard Worker return true;
875*9880d681SAndroid Build Coastguard Worker
876*9880d681SAndroid Build Coastguard Worker // Do not instrument gcov counter arrays.
877*9880d681SAndroid Build Coastguard Worker if (G->getName() == "__llvm_gcov_ctr")
878*9880d681SAndroid Build Coastguard Worker return true;
879*9880d681SAndroid Build Coastguard Worker
880*9880d681SAndroid Build Coastguard Worker return false;
881*9880d681SAndroid Build Coastguard Worker }
882*9880d681SAndroid Build Coastguard Worker
memToShadow(Value * Shadow,IRBuilder<> & IRB)883*9880d681SAndroid Build Coastguard Worker Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
884*9880d681SAndroid Build Coastguard Worker // Shadow >> scale
885*9880d681SAndroid Build Coastguard Worker Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
886*9880d681SAndroid Build Coastguard Worker if (Mapping.Offset == 0) return Shadow;
887*9880d681SAndroid Build Coastguard Worker // (Shadow >> scale) | offset
888*9880d681SAndroid Build Coastguard Worker if (Mapping.OrShadowOffset)
889*9880d681SAndroid Build Coastguard Worker return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
890*9880d681SAndroid Build Coastguard Worker else
891*9880d681SAndroid Build Coastguard Worker return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
892*9880d681SAndroid Build Coastguard Worker }
893*9880d681SAndroid Build Coastguard Worker
894*9880d681SAndroid Build Coastguard Worker // Instrument memset/memmove/memcpy
instrumentMemIntrinsic(MemIntrinsic * MI)895*9880d681SAndroid Build Coastguard Worker void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
896*9880d681SAndroid Build Coastguard Worker IRBuilder<> IRB(MI);
897*9880d681SAndroid Build Coastguard Worker if (isa<MemTransferInst>(MI)) {
898*9880d681SAndroid Build Coastguard Worker IRB.CreateCall(
899*9880d681SAndroid Build Coastguard Worker isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
900*9880d681SAndroid Build Coastguard Worker {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
901*9880d681SAndroid Build Coastguard Worker IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
902*9880d681SAndroid Build Coastguard Worker IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
903*9880d681SAndroid Build Coastguard Worker } else if (isa<MemSetInst>(MI)) {
904*9880d681SAndroid Build Coastguard Worker IRB.CreateCall(
905*9880d681SAndroid Build Coastguard Worker AsanMemset,
906*9880d681SAndroid Build Coastguard Worker {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
907*9880d681SAndroid Build Coastguard Worker IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
908*9880d681SAndroid Build Coastguard Worker IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
909*9880d681SAndroid Build Coastguard Worker }
910*9880d681SAndroid Build Coastguard Worker MI->eraseFromParent();
911*9880d681SAndroid Build Coastguard Worker }
912*9880d681SAndroid Build Coastguard Worker
913*9880d681SAndroid Build Coastguard Worker /// Check if we want (and can) handle this alloca.
isInterestingAlloca(AllocaInst & AI)914*9880d681SAndroid Build Coastguard Worker bool AddressSanitizer::isInterestingAlloca(AllocaInst &AI) {
915*9880d681SAndroid Build Coastguard Worker auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
916*9880d681SAndroid Build Coastguard Worker
917*9880d681SAndroid Build Coastguard Worker if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
918*9880d681SAndroid Build Coastguard Worker return PreviouslySeenAllocaInfo->getSecond();
919*9880d681SAndroid Build Coastguard Worker
920*9880d681SAndroid Build Coastguard Worker bool IsInteresting =
921*9880d681SAndroid Build Coastguard Worker (AI.getAllocatedType()->isSized() &&
922*9880d681SAndroid Build Coastguard Worker // alloca() may be called with 0 size, ignore it.
923*9880d681SAndroid Build Coastguard Worker ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(&AI) > 0) &&
924*9880d681SAndroid Build Coastguard Worker // We are only interested in allocas not promotable to registers.
925*9880d681SAndroid Build Coastguard Worker // Promotable allocas are common under -O0.
926*9880d681SAndroid Build Coastguard Worker (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
927*9880d681SAndroid Build Coastguard Worker // inalloca allocas are not treated as static, and we don't want
928*9880d681SAndroid Build Coastguard Worker // dynamic alloca instrumentation for them as well.
929*9880d681SAndroid Build Coastguard Worker !AI.isUsedWithInAlloca());
930*9880d681SAndroid Build Coastguard Worker
931*9880d681SAndroid Build Coastguard Worker ProcessedAllocas[&AI] = IsInteresting;
932*9880d681SAndroid Build Coastguard Worker return IsInteresting;
933*9880d681SAndroid Build Coastguard Worker }
934*9880d681SAndroid Build Coastguard Worker
935*9880d681SAndroid Build Coastguard Worker /// If I is an interesting memory access, return the PointerOperand
936*9880d681SAndroid Build Coastguard Worker /// and set IsWrite/Alignment. Otherwise return nullptr.
isInterestingMemoryAccess(Instruction * I,bool * IsWrite,uint64_t * TypeSize,unsigned * Alignment)937*9880d681SAndroid Build Coastguard Worker Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
938*9880d681SAndroid Build Coastguard Worker bool *IsWrite,
939*9880d681SAndroid Build Coastguard Worker uint64_t *TypeSize,
940*9880d681SAndroid Build Coastguard Worker unsigned *Alignment) {
941*9880d681SAndroid Build Coastguard Worker // Skip memory accesses inserted by another instrumentation.
942*9880d681SAndroid Build Coastguard Worker if (I->getMetadata("nosanitize")) return nullptr;
943*9880d681SAndroid Build Coastguard Worker
944*9880d681SAndroid Build Coastguard Worker Value *PtrOperand = nullptr;
945*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = I->getModule()->getDataLayout();
946*9880d681SAndroid Build Coastguard Worker if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
947*9880d681SAndroid Build Coastguard Worker if (!ClInstrumentReads) return nullptr;
948*9880d681SAndroid Build Coastguard Worker *IsWrite = false;
949*9880d681SAndroid Build Coastguard Worker *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
950*9880d681SAndroid Build Coastguard Worker *Alignment = LI->getAlignment();
951*9880d681SAndroid Build Coastguard Worker PtrOperand = LI->getPointerOperand();
952*9880d681SAndroid Build Coastguard Worker } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
953*9880d681SAndroid Build Coastguard Worker if (!ClInstrumentWrites) return nullptr;
954*9880d681SAndroid Build Coastguard Worker *IsWrite = true;
955*9880d681SAndroid Build Coastguard Worker *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
956*9880d681SAndroid Build Coastguard Worker *Alignment = SI->getAlignment();
957*9880d681SAndroid Build Coastguard Worker PtrOperand = SI->getPointerOperand();
958*9880d681SAndroid Build Coastguard Worker } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
959*9880d681SAndroid Build Coastguard Worker if (!ClInstrumentAtomics) return nullptr;
960*9880d681SAndroid Build Coastguard Worker *IsWrite = true;
961*9880d681SAndroid Build Coastguard Worker *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
962*9880d681SAndroid Build Coastguard Worker *Alignment = 0;
963*9880d681SAndroid Build Coastguard Worker PtrOperand = RMW->getPointerOperand();
964*9880d681SAndroid Build Coastguard Worker } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
965*9880d681SAndroid Build Coastguard Worker if (!ClInstrumentAtomics) return nullptr;
966*9880d681SAndroid Build Coastguard Worker *IsWrite = true;
967*9880d681SAndroid Build Coastguard Worker *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
968*9880d681SAndroid Build Coastguard Worker *Alignment = 0;
969*9880d681SAndroid Build Coastguard Worker PtrOperand = XCHG->getPointerOperand();
970*9880d681SAndroid Build Coastguard Worker }
971*9880d681SAndroid Build Coastguard Worker
972*9880d681SAndroid Build Coastguard Worker // Do not instrument acesses from different address spaces; we cannot deal
973*9880d681SAndroid Build Coastguard Worker // with them.
974*9880d681SAndroid Build Coastguard Worker if (PtrOperand) {
975*9880d681SAndroid Build Coastguard Worker Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
976*9880d681SAndroid Build Coastguard Worker if (PtrTy->getPointerAddressSpace() != 0)
977*9880d681SAndroid Build Coastguard Worker return nullptr;
978*9880d681SAndroid Build Coastguard Worker }
979*9880d681SAndroid Build Coastguard Worker
980*9880d681SAndroid Build Coastguard Worker // Treat memory accesses to promotable allocas as non-interesting since they
981*9880d681SAndroid Build Coastguard Worker // will not cause memory violations. This greatly speeds up the instrumented
982*9880d681SAndroid Build Coastguard Worker // executable at -O0.
983*9880d681SAndroid Build Coastguard Worker if (ClSkipPromotableAllocas)
984*9880d681SAndroid Build Coastguard Worker if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
985*9880d681SAndroid Build Coastguard Worker return isInterestingAlloca(*AI) ? AI : nullptr;
986*9880d681SAndroid Build Coastguard Worker
987*9880d681SAndroid Build Coastguard Worker return PtrOperand;
988*9880d681SAndroid Build Coastguard Worker }
989*9880d681SAndroid Build Coastguard Worker
isPointerOperand(Value * V)990*9880d681SAndroid Build Coastguard Worker static bool isPointerOperand(Value *V) {
991*9880d681SAndroid Build Coastguard Worker return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
992*9880d681SAndroid Build Coastguard Worker }
993*9880d681SAndroid Build Coastguard Worker
994*9880d681SAndroid Build Coastguard Worker // This is a rough heuristic; it may cause both false positives and
995*9880d681SAndroid Build Coastguard Worker // false negatives. The proper implementation requires cooperation with
996*9880d681SAndroid Build Coastguard Worker // the frontend.
isInterestingPointerComparisonOrSubtraction(Instruction * I)997*9880d681SAndroid Build Coastguard Worker static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
998*9880d681SAndroid Build Coastguard Worker if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
999*9880d681SAndroid Build Coastguard Worker if (!Cmp->isRelational()) return false;
1000*9880d681SAndroid Build Coastguard Worker } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1001*9880d681SAndroid Build Coastguard Worker if (BO->getOpcode() != Instruction::Sub) return false;
1002*9880d681SAndroid Build Coastguard Worker } else {
1003*9880d681SAndroid Build Coastguard Worker return false;
1004*9880d681SAndroid Build Coastguard Worker }
1005*9880d681SAndroid Build Coastguard Worker return isPointerOperand(I->getOperand(0)) &&
1006*9880d681SAndroid Build Coastguard Worker isPointerOperand(I->getOperand(1));
1007*9880d681SAndroid Build Coastguard Worker }
1008*9880d681SAndroid Build Coastguard Worker
GlobalIsLinkerInitialized(GlobalVariable * G)1009*9880d681SAndroid Build Coastguard Worker bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1010*9880d681SAndroid Build Coastguard Worker // If a global variable does not have dynamic initialization we don't
1011*9880d681SAndroid Build Coastguard Worker // have to instrument it. However, if a global does not have initializer
1012*9880d681SAndroid Build Coastguard Worker // at all, we assume it has dynamic initializer (in other TU).
1013*9880d681SAndroid Build Coastguard Worker return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
1014*9880d681SAndroid Build Coastguard Worker }
1015*9880d681SAndroid Build Coastguard Worker
instrumentPointerComparisonOrSubtraction(Instruction * I)1016*9880d681SAndroid Build Coastguard Worker void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1017*9880d681SAndroid Build Coastguard Worker Instruction *I) {
1018*9880d681SAndroid Build Coastguard Worker IRBuilder<> IRB(I);
1019*9880d681SAndroid Build Coastguard Worker Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1020*9880d681SAndroid Build Coastguard Worker Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
1021*9880d681SAndroid Build Coastguard Worker for (Value *&i : Param) {
1022*9880d681SAndroid Build Coastguard Worker if (i->getType()->isPointerTy())
1023*9880d681SAndroid Build Coastguard Worker i = IRB.CreatePointerCast(i, IntptrTy);
1024*9880d681SAndroid Build Coastguard Worker }
1025*9880d681SAndroid Build Coastguard Worker IRB.CreateCall(F, Param);
1026*9880d681SAndroid Build Coastguard Worker }
1027*9880d681SAndroid Build Coastguard Worker
instrumentMop(ObjectSizeOffsetVisitor & ObjSizeVis,Instruction * I,bool UseCalls,const DataLayout & DL)1028*9880d681SAndroid Build Coastguard Worker void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
1029*9880d681SAndroid Build Coastguard Worker Instruction *I, bool UseCalls,
1030*9880d681SAndroid Build Coastguard Worker const DataLayout &DL) {
1031*9880d681SAndroid Build Coastguard Worker bool IsWrite = false;
1032*9880d681SAndroid Build Coastguard Worker unsigned Alignment = 0;
1033*9880d681SAndroid Build Coastguard Worker uint64_t TypeSize = 0;
1034*9880d681SAndroid Build Coastguard Worker Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
1035*9880d681SAndroid Build Coastguard Worker assert(Addr);
1036*9880d681SAndroid Build Coastguard Worker
1037*9880d681SAndroid Build Coastguard Worker // Optimization experiments.
1038*9880d681SAndroid Build Coastguard Worker // The experiments can be used to evaluate potential optimizations that remove
1039*9880d681SAndroid Build Coastguard Worker // instrumentation (assess false negatives). Instead of completely removing
1040*9880d681SAndroid Build Coastguard Worker // some instrumentation, you set Exp to a non-zero value (mask of optimization
1041*9880d681SAndroid Build Coastguard Worker // experiments that want to remove instrumentation of this instruction).
1042*9880d681SAndroid Build Coastguard Worker // If Exp is non-zero, this pass will emit special calls into runtime
1043*9880d681SAndroid Build Coastguard Worker // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1044*9880d681SAndroid Build Coastguard Worker // make runtime terminate the program in a special way (with a different
1045*9880d681SAndroid Build Coastguard Worker // exit status). Then you run the new compiler on a buggy corpus, collect
1046*9880d681SAndroid Build Coastguard Worker // the special terminations (ideally, you don't see them at all -- no false
1047*9880d681SAndroid Build Coastguard Worker // negatives) and make the decision on the optimization.
1048*9880d681SAndroid Build Coastguard Worker uint32_t Exp = ClForceExperiment;
1049*9880d681SAndroid Build Coastguard Worker
1050*9880d681SAndroid Build Coastguard Worker if (ClOpt && ClOptGlobals) {
1051*9880d681SAndroid Build Coastguard Worker // If initialization order checking is disabled, a simple access to a
1052*9880d681SAndroid Build Coastguard Worker // dynamically initialized global is always valid.
1053*9880d681SAndroid Build Coastguard Worker GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
1054*9880d681SAndroid Build Coastguard Worker if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
1055*9880d681SAndroid Build Coastguard Worker isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1056*9880d681SAndroid Build Coastguard Worker NumOptimizedAccessesToGlobalVar++;
1057*9880d681SAndroid Build Coastguard Worker return;
1058*9880d681SAndroid Build Coastguard Worker }
1059*9880d681SAndroid Build Coastguard Worker }
1060*9880d681SAndroid Build Coastguard Worker
1061*9880d681SAndroid Build Coastguard Worker if (ClOpt && ClOptStack) {
1062*9880d681SAndroid Build Coastguard Worker // A direct inbounds access to a stack variable is always valid.
1063*9880d681SAndroid Build Coastguard Worker if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
1064*9880d681SAndroid Build Coastguard Worker isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1065*9880d681SAndroid Build Coastguard Worker NumOptimizedAccessesToStackVar++;
1066*9880d681SAndroid Build Coastguard Worker return;
1067*9880d681SAndroid Build Coastguard Worker }
1068*9880d681SAndroid Build Coastguard Worker }
1069*9880d681SAndroid Build Coastguard Worker
1070*9880d681SAndroid Build Coastguard Worker if (IsWrite)
1071*9880d681SAndroid Build Coastguard Worker NumInstrumentedWrites++;
1072*9880d681SAndroid Build Coastguard Worker else
1073*9880d681SAndroid Build Coastguard Worker NumInstrumentedReads++;
1074*9880d681SAndroid Build Coastguard Worker
1075*9880d681SAndroid Build Coastguard Worker unsigned Granularity = 1 << Mapping.Scale;
1076*9880d681SAndroid Build Coastguard Worker // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1077*9880d681SAndroid Build Coastguard Worker // if the data is properly aligned.
1078*9880d681SAndroid Build Coastguard Worker if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1079*9880d681SAndroid Build Coastguard Worker TypeSize == 128) &&
1080*9880d681SAndroid Build Coastguard Worker (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
1081*9880d681SAndroid Build Coastguard Worker return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
1082*9880d681SAndroid Build Coastguard Worker Exp);
1083*9880d681SAndroid Build Coastguard Worker instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
1084*9880d681SAndroid Build Coastguard Worker UseCalls, Exp);
1085*9880d681SAndroid Build Coastguard Worker }
1086*9880d681SAndroid Build Coastguard Worker
generateCrashCode(Instruction * InsertBefore,Value * Addr,bool IsWrite,size_t AccessSizeIndex,Value * SizeArgument,uint32_t Exp)1087*9880d681SAndroid Build Coastguard Worker Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1088*9880d681SAndroid Build Coastguard Worker Value *Addr, bool IsWrite,
1089*9880d681SAndroid Build Coastguard Worker size_t AccessSizeIndex,
1090*9880d681SAndroid Build Coastguard Worker Value *SizeArgument,
1091*9880d681SAndroid Build Coastguard Worker uint32_t Exp) {
1092*9880d681SAndroid Build Coastguard Worker IRBuilder<> IRB(InsertBefore);
1093*9880d681SAndroid Build Coastguard Worker Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1094*9880d681SAndroid Build Coastguard Worker CallInst *Call = nullptr;
1095*9880d681SAndroid Build Coastguard Worker if (SizeArgument) {
1096*9880d681SAndroid Build Coastguard Worker if (Exp == 0)
1097*9880d681SAndroid Build Coastguard Worker Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1098*9880d681SAndroid Build Coastguard Worker {Addr, SizeArgument});
1099*9880d681SAndroid Build Coastguard Worker else
1100*9880d681SAndroid Build Coastguard Worker Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1101*9880d681SAndroid Build Coastguard Worker {Addr, SizeArgument, ExpVal});
1102*9880d681SAndroid Build Coastguard Worker } else {
1103*9880d681SAndroid Build Coastguard Worker if (Exp == 0)
1104*9880d681SAndroid Build Coastguard Worker Call =
1105*9880d681SAndroid Build Coastguard Worker IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1106*9880d681SAndroid Build Coastguard Worker else
1107*9880d681SAndroid Build Coastguard Worker Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1108*9880d681SAndroid Build Coastguard Worker {Addr, ExpVal});
1109*9880d681SAndroid Build Coastguard Worker }
1110*9880d681SAndroid Build Coastguard Worker
1111*9880d681SAndroid Build Coastguard Worker // We don't do Call->setDoesNotReturn() because the BB already has
1112*9880d681SAndroid Build Coastguard Worker // UnreachableInst at the end.
1113*9880d681SAndroid Build Coastguard Worker // This EmptyAsm is required to avoid callback merge.
1114*9880d681SAndroid Build Coastguard Worker IRB.CreateCall(EmptyAsm, {});
1115*9880d681SAndroid Build Coastguard Worker return Call;
1116*9880d681SAndroid Build Coastguard Worker }
1117*9880d681SAndroid Build Coastguard Worker
createSlowPathCmp(IRBuilder<> & IRB,Value * AddrLong,Value * ShadowValue,uint32_t TypeSize)1118*9880d681SAndroid Build Coastguard Worker Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
1119*9880d681SAndroid Build Coastguard Worker Value *ShadowValue,
1120*9880d681SAndroid Build Coastguard Worker uint32_t TypeSize) {
1121*9880d681SAndroid Build Coastguard Worker size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
1122*9880d681SAndroid Build Coastguard Worker // Addr & (Granularity - 1)
1123*9880d681SAndroid Build Coastguard Worker Value *LastAccessedByte =
1124*9880d681SAndroid Build Coastguard Worker IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
1125*9880d681SAndroid Build Coastguard Worker // (Addr & (Granularity - 1)) + size - 1
1126*9880d681SAndroid Build Coastguard Worker if (TypeSize / 8 > 1)
1127*9880d681SAndroid Build Coastguard Worker LastAccessedByte = IRB.CreateAdd(
1128*9880d681SAndroid Build Coastguard Worker LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1129*9880d681SAndroid Build Coastguard Worker // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
1130*9880d681SAndroid Build Coastguard Worker LastAccessedByte =
1131*9880d681SAndroid Build Coastguard Worker IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
1132*9880d681SAndroid Build Coastguard Worker // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1133*9880d681SAndroid Build Coastguard Worker return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1134*9880d681SAndroid Build Coastguard Worker }
1135*9880d681SAndroid Build Coastguard Worker
instrumentAddress(Instruction * OrigIns,Instruction * InsertBefore,Value * Addr,uint32_t TypeSize,bool IsWrite,Value * SizeArgument,bool UseCalls,uint32_t Exp)1136*9880d681SAndroid Build Coastguard Worker void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
1137*9880d681SAndroid Build Coastguard Worker Instruction *InsertBefore, Value *Addr,
1138*9880d681SAndroid Build Coastguard Worker uint32_t TypeSize, bool IsWrite,
1139*9880d681SAndroid Build Coastguard Worker Value *SizeArgument, bool UseCalls,
1140*9880d681SAndroid Build Coastguard Worker uint32_t Exp) {
1141*9880d681SAndroid Build Coastguard Worker IRBuilder<> IRB(InsertBefore);
1142*9880d681SAndroid Build Coastguard Worker Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1143*9880d681SAndroid Build Coastguard Worker size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1144*9880d681SAndroid Build Coastguard Worker
1145*9880d681SAndroid Build Coastguard Worker if (UseCalls) {
1146*9880d681SAndroid Build Coastguard Worker if (Exp == 0)
1147*9880d681SAndroid Build Coastguard Worker IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1148*9880d681SAndroid Build Coastguard Worker AddrLong);
1149*9880d681SAndroid Build Coastguard Worker else
1150*9880d681SAndroid Build Coastguard Worker IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1151*9880d681SAndroid Build Coastguard Worker {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1152*9880d681SAndroid Build Coastguard Worker return;
1153*9880d681SAndroid Build Coastguard Worker }
1154*9880d681SAndroid Build Coastguard Worker
1155*9880d681SAndroid Build Coastguard Worker Type *ShadowTy =
1156*9880d681SAndroid Build Coastguard Worker IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
1157*9880d681SAndroid Build Coastguard Worker Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1158*9880d681SAndroid Build Coastguard Worker Value *ShadowPtr = memToShadow(AddrLong, IRB);
1159*9880d681SAndroid Build Coastguard Worker Value *CmpVal = Constant::getNullValue(ShadowTy);
1160*9880d681SAndroid Build Coastguard Worker Value *ShadowValue =
1161*9880d681SAndroid Build Coastguard Worker IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
1162*9880d681SAndroid Build Coastguard Worker
1163*9880d681SAndroid Build Coastguard Worker Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
1164*9880d681SAndroid Build Coastguard Worker size_t Granularity = 1ULL << Mapping.Scale;
1165*9880d681SAndroid Build Coastguard Worker TerminatorInst *CrashTerm = nullptr;
1166*9880d681SAndroid Build Coastguard Worker
1167*9880d681SAndroid Build Coastguard Worker if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
1168*9880d681SAndroid Build Coastguard Worker // We use branch weights for the slow path check, to indicate that the slow
1169*9880d681SAndroid Build Coastguard Worker // path is rarely taken. This seems to be the case for SPEC benchmarks.
1170*9880d681SAndroid Build Coastguard Worker TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1171*9880d681SAndroid Build Coastguard Worker Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
1172*9880d681SAndroid Build Coastguard Worker assert(cast<BranchInst>(CheckTerm)->isUnconditional());
1173*9880d681SAndroid Build Coastguard Worker BasicBlock *NextBB = CheckTerm->getSuccessor(0);
1174*9880d681SAndroid Build Coastguard Worker IRB.SetInsertPoint(CheckTerm);
1175*9880d681SAndroid Build Coastguard Worker Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
1176*9880d681SAndroid Build Coastguard Worker if (Recover) {
1177*9880d681SAndroid Build Coastguard Worker CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1178*9880d681SAndroid Build Coastguard Worker } else {
1179*9880d681SAndroid Build Coastguard Worker BasicBlock *CrashBlock =
1180*9880d681SAndroid Build Coastguard Worker BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
1181*9880d681SAndroid Build Coastguard Worker CrashTerm = new UnreachableInst(*C, CrashBlock);
1182*9880d681SAndroid Build Coastguard Worker BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1183*9880d681SAndroid Build Coastguard Worker ReplaceInstWithInst(CheckTerm, NewTerm);
1184*9880d681SAndroid Build Coastguard Worker }
1185*9880d681SAndroid Build Coastguard Worker } else {
1186*9880d681SAndroid Build Coastguard Worker CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
1187*9880d681SAndroid Build Coastguard Worker }
1188*9880d681SAndroid Build Coastguard Worker
1189*9880d681SAndroid Build Coastguard Worker Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
1190*9880d681SAndroid Build Coastguard Worker AccessSizeIndex, SizeArgument, Exp);
1191*9880d681SAndroid Build Coastguard Worker Crash->setDebugLoc(OrigIns->getDebugLoc());
1192*9880d681SAndroid Build Coastguard Worker }
1193*9880d681SAndroid Build Coastguard Worker
1194*9880d681SAndroid Build Coastguard Worker // Instrument unusual size or unusual alignment.
1195*9880d681SAndroid Build Coastguard Worker // We can not do it with a single check, so we do 1-byte check for the first
1196*9880d681SAndroid Build Coastguard Worker // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1197*9880d681SAndroid Build Coastguard Worker // to report the actual access size.
instrumentUnusualSizeOrAlignment(Instruction * I,Value * Addr,uint32_t TypeSize,bool IsWrite,Value * SizeArgument,bool UseCalls,uint32_t Exp)1198*9880d681SAndroid Build Coastguard Worker void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1199*9880d681SAndroid Build Coastguard Worker Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1200*9880d681SAndroid Build Coastguard Worker Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1201*9880d681SAndroid Build Coastguard Worker IRBuilder<> IRB(I);
1202*9880d681SAndroid Build Coastguard Worker Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1203*9880d681SAndroid Build Coastguard Worker Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1204*9880d681SAndroid Build Coastguard Worker if (UseCalls) {
1205*9880d681SAndroid Build Coastguard Worker if (Exp == 0)
1206*9880d681SAndroid Build Coastguard Worker IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1207*9880d681SAndroid Build Coastguard Worker {AddrLong, Size});
1208*9880d681SAndroid Build Coastguard Worker else
1209*9880d681SAndroid Build Coastguard Worker IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1210*9880d681SAndroid Build Coastguard Worker {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1211*9880d681SAndroid Build Coastguard Worker } else {
1212*9880d681SAndroid Build Coastguard Worker Value *LastByte = IRB.CreateIntToPtr(
1213*9880d681SAndroid Build Coastguard Worker IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1214*9880d681SAndroid Build Coastguard Worker Addr->getType());
1215*9880d681SAndroid Build Coastguard Worker instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1216*9880d681SAndroid Build Coastguard Worker instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1217*9880d681SAndroid Build Coastguard Worker }
1218*9880d681SAndroid Build Coastguard Worker }
1219*9880d681SAndroid Build Coastguard Worker
poisonOneInitializer(Function & GlobalInit,GlobalValue * ModuleName)1220*9880d681SAndroid Build Coastguard Worker void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1221*9880d681SAndroid Build Coastguard Worker GlobalValue *ModuleName) {
1222*9880d681SAndroid Build Coastguard Worker // Set up the arguments to our poison/unpoison functions.
1223*9880d681SAndroid Build Coastguard Worker IRBuilder<> IRB(&GlobalInit.front(),
1224*9880d681SAndroid Build Coastguard Worker GlobalInit.front().getFirstInsertionPt());
1225*9880d681SAndroid Build Coastguard Worker
1226*9880d681SAndroid Build Coastguard Worker // Add a call to poison all external globals before the given function starts.
1227*9880d681SAndroid Build Coastguard Worker Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1228*9880d681SAndroid Build Coastguard Worker IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
1229*9880d681SAndroid Build Coastguard Worker
1230*9880d681SAndroid Build Coastguard Worker // Add calls to unpoison all globals before each return instruction.
1231*9880d681SAndroid Build Coastguard Worker for (auto &BB : GlobalInit.getBasicBlockList())
1232*9880d681SAndroid Build Coastguard Worker if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1233*9880d681SAndroid Build Coastguard Worker CallInst::Create(AsanUnpoisonGlobals, "", RI);
1234*9880d681SAndroid Build Coastguard Worker }
1235*9880d681SAndroid Build Coastguard Worker
createInitializerPoisonCalls(Module & M,GlobalValue * ModuleName)1236*9880d681SAndroid Build Coastguard Worker void AddressSanitizerModule::createInitializerPoisonCalls(
1237*9880d681SAndroid Build Coastguard Worker Module &M, GlobalValue *ModuleName) {
1238*9880d681SAndroid Build Coastguard Worker GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1239*9880d681SAndroid Build Coastguard Worker
1240*9880d681SAndroid Build Coastguard Worker ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1241*9880d681SAndroid Build Coastguard Worker for (Use &OP : CA->operands()) {
1242*9880d681SAndroid Build Coastguard Worker if (isa<ConstantAggregateZero>(OP)) continue;
1243*9880d681SAndroid Build Coastguard Worker ConstantStruct *CS = cast<ConstantStruct>(OP);
1244*9880d681SAndroid Build Coastguard Worker
1245*9880d681SAndroid Build Coastguard Worker // Must have a function or null ptr.
1246*9880d681SAndroid Build Coastguard Worker if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
1247*9880d681SAndroid Build Coastguard Worker if (F->getName() == kAsanModuleCtorName) continue;
1248*9880d681SAndroid Build Coastguard Worker ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1249*9880d681SAndroid Build Coastguard Worker // Don't instrument CTORs that will run before asan.module_ctor.
1250*9880d681SAndroid Build Coastguard Worker if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1251*9880d681SAndroid Build Coastguard Worker poisonOneInitializer(*F, ModuleName);
1252*9880d681SAndroid Build Coastguard Worker }
1253*9880d681SAndroid Build Coastguard Worker }
1254*9880d681SAndroid Build Coastguard Worker }
1255*9880d681SAndroid Build Coastguard Worker
ShouldInstrumentGlobal(GlobalVariable * G)1256*9880d681SAndroid Build Coastguard Worker bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
1257*9880d681SAndroid Build Coastguard Worker Type *Ty = G->getValueType();
1258*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
1259*9880d681SAndroid Build Coastguard Worker
1260*9880d681SAndroid Build Coastguard Worker if (GlobalsMD.get(G).IsBlacklisted) return false;
1261*9880d681SAndroid Build Coastguard Worker if (!Ty->isSized()) return false;
1262*9880d681SAndroid Build Coastguard Worker if (!G->hasInitializer()) return false;
1263*9880d681SAndroid Build Coastguard Worker if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
1264*9880d681SAndroid Build Coastguard Worker // Touch only those globals that will not be defined in other modules.
1265*9880d681SAndroid Build Coastguard Worker // Don't handle ODR linkage types and COMDATs since other modules may be built
1266*9880d681SAndroid Build Coastguard Worker // without ASan.
1267*9880d681SAndroid Build Coastguard Worker if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1268*9880d681SAndroid Build Coastguard Worker G->getLinkage() != GlobalVariable::PrivateLinkage &&
1269*9880d681SAndroid Build Coastguard Worker G->getLinkage() != GlobalVariable::InternalLinkage)
1270*9880d681SAndroid Build Coastguard Worker return false;
1271*9880d681SAndroid Build Coastguard Worker if (G->hasComdat()) return false;
1272*9880d681SAndroid Build Coastguard Worker // Two problems with thread-locals:
1273*9880d681SAndroid Build Coastguard Worker // - The address of the main thread's copy can't be computed at link-time.
1274*9880d681SAndroid Build Coastguard Worker // - Need to poison all copies, not just the main thread's one.
1275*9880d681SAndroid Build Coastguard Worker if (G->isThreadLocal()) return false;
1276*9880d681SAndroid Build Coastguard Worker // For now, just ignore this Global if the alignment is large.
1277*9880d681SAndroid Build Coastguard Worker if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
1278*9880d681SAndroid Build Coastguard Worker
1279*9880d681SAndroid Build Coastguard Worker if (G->hasSection()) {
1280*9880d681SAndroid Build Coastguard Worker StringRef Section = G->getSection();
1281*9880d681SAndroid Build Coastguard Worker
1282*9880d681SAndroid Build Coastguard Worker // Globals from llvm.metadata aren't emitted, do not instrument them.
1283*9880d681SAndroid Build Coastguard Worker if (Section == "llvm.metadata") return false;
1284*9880d681SAndroid Build Coastguard Worker // Do not instrument globals from special LLVM sections.
1285*9880d681SAndroid Build Coastguard Worker if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
1286*9880d681SAndroid Build Coastguard Worker
1287*9880d681SAndroid Build Coastguard Worker // Do not instrument function pointers to initialization and termination
1288*9880d681SAndroid Build Coastguard Worker // routines: dynamic linker will not properly handle redzones.
1289*9880d681SAndroid Build Coastguard Worker if (Section.startswith(".preinit_array") ||
1290*9880d681SAndroid Build Coastguard Worker Section.startswith(".init_array") ||
1291*9880d681SAndroid Build Coastguard Worker Section.startswith(".fini_array")) {
1292*9880d681SAndroid Build Coastguard Worker return false;
1293*9880d681SAndroid Build Coastguard Worker }
1294*9880d681SAndroid Build Coastguard Worker
1295*9880d681SAndroid Build Coastguard Worker // Callbacks put into the CRT initializer/terminator sections
1296*9880d681SAndroid Build Coastguard Worker // should not be instrumented.
1297*9880d681SAndroid Build Coastguard Worker // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1298*9880d681SAndroid Build Coastguard Worker // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1299*9880d681SAndroid Build Coastguard Worker if (Section.startswith(".CRT")) {
1300*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1301*9880d681SAndroid Build Coastguard Worker return false;
1302*9880d681SAndroid Build Coastguard Worker }
1303*9880d681SAndroid Build Coastguard Worker
1304*9880d681SAndroid Build Coastguard Worker if (TargetTriple.isOSBinFormatMachO()) {
1305*9880d681SAndroid Build Coastguard Worker StringRef ParsedSegment, ParsedSection;
1306*9880d681SAndroid Build Coastguard Worker unsigned TAA = 0, StubSize = 0;
1307*9880d681SAndroid Build Coastguard Worker bool TAAParsed;
1308*9880d681SAndroid Build Coastguard Worker std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1309*9880d681SAndroid Build Coastguard Worker Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
1310*9880d681SAndroid Build Coastguard Worker assert(ErrorCode.empty() && "Invalid section specifier.");
1311*9880d681SAndroid Build Coastguard Worker
1312*9880d681SAndroid Build Coastguard Worker // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1313*9880d681SAndroid Build Coastguard Worker // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1314*9880d681SAndroid Build Coastguard Worker // them.
1315*9880d681SAndroid Build Coastguard Worker if (ParsedSegment == "__OBJC" ||
1316*9880d681SAndroid Build Coastguard Worker (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1317*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1318*9880d681SAndroid Build Coastguard Worker return false;
1319*9880d681SAndroid Build Coastguard Worker }
1320*9880d681SAndroid Build Coastguard Worker // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1321*9880d681SAndroid Build Coastguard Worker // Constant CFString instances are compiled in the following way:
1322*9880d681SAndroid Build Coastguard Worker // -- the string buffer is emitted into
1323*9880d681SAndroid Build Coastguard Worker // __TEXT,__cstring,cstring_literals
1324*9880d681SAndroid Build Coastguard Worker // -- the constant NSConstantString structure referencing that buffer
1325*9880d681SAndroid Build Coastguard Worker // is placed into __DATA,__cfstring
1326*9880d681SAndroid Build Coastguard Worker // Therefore there's no point in placing redzones into __DATA,__cfstring.
1327*9880d681SAndroid Build Coastguard Worker // Moreover, it causes the linker to crash on OS X 10.7
1328*9880d681SAndroid Build Coastguard Worker if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1329*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1330*9880d681SAndroid Build Coastguard Worker return false;
1331*9880d681SAndroid Build Coastguard Worker }
1332*9880d681SAndroid Build Coastguard Worker // The linker merges the contents of cstring_literals and removes the
1333*9880d681SAndroid Build Coastguard Worker // trailing zeroes.
1334*9880d681SAndroid Build Coastguard Worker if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1335*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1336*9880d681SAndroid Build Coastguard Worker return false;
1337*9880d681SAndroid Build Coastguard Worker }
1338*9880d681SAndroid Build Coastguard Worker }
1339*9880d681SAndroid Build Coastguard Worker }
1340*9880d681SAndroid Build Coastguard Worker
1341*9880d681SAndroid Build Coastguard Worker return true;
1342*9880d681SAndroid Build Coastguard Worker }
1343*9880d681SAndroid Build Coastguard Worker
1344*9880d681SAndroid Build Coastguard Worker // On Mach-O platforms, we emit global metadata in a separate section of the
1345*9880d681SAndroid Build Coastguard Worker // binary in order to allow the linker to properly dead strip. This is only
1346*9880d681SAndroid Build Coastguard Worker // supported on recent versions of ld64.
ShouldUseMachOGlobalsSection() const1347*9880d681SAndroid Build Coastguard Worker bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
1348*9880d681SAndroid Build Coastguard Worker if (!ClUseMachOGlobalsSection)
1349*9880d681SAndroid Build Coastguard Worker return false;
1350*9880d681SAndroid Build Coastguard Worker
1351*9880d681SAndroid Build Coastguard Worker if (!TargetTriple.isOSBinFormatMachO())
1352*9880d681SAndroid Build Coastguard Worker return false;
1353*9880d681SAndroid Build Coastguard Worker
1354*9880d681SAndroid Build Coastguard Worker if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1355*9880d681SAndroid Build Coastguard Worker return true;
1356*9880d681SAndroid Build Coastguard Worker if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
1357*9880d681SAndroid Build Coastguard Worker return true;
1358*9880d681SAndroid Build Coastguard Worker if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1359*9880d681SAndroid Build Coastguard Worker return true;
1360*9880d681SAndroid Build Coastguard Worker
1361*9880d681SAndroid Build Coastguard Worker return false;
1362*9880d681SAndroid Build Coastguard Worker }
1363*9880d681SAndroid Build Coastguard Worker
initializeCallbacks(Module & M)1364*9880d681SAndroid Build Coastguard Worker void AddressSanitizerModule::initializeCallbacks(Module &M) {
1365*9880d681SAndroid Build Coastguard Worker IRBuilder<> IRB(*C);
1366*9880d681SAndroid Build Coastguard Worker
1367*9880d681SAndroid Build Coastguard Worker // Declare our poisoning and unpoisoning functions.
1368*9880d681SAndroid Build Coastguard Worker AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1369*9880d681SAndroid Build Coastguard Worker kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
1370*9880d681SAndroid Build Coastguard Worker AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1371*9880d681SAndroid Build Coastguard Worker AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1372*9880d681SAndroid Build Coastguard Worker kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
1373*9880d681SAndroid Build Coastguard Worker AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1374*9880d681SAndroid Build Coastguard Worker
1375*9880d681SAndroid Build Coastguard Worker // Declare functions that register/unregister globals.
1376*9880d681SAndroid Build Coastguard Worker AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1377*9880d681SAndroid Build Coastguard Worker kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1378*9880d681SAndroid Build Coastguard Worker AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1379*9880d681SAndroid Build Coastguard Worker AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
1380*9880d681SAndroid Build Coastguard Worker M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1381*9880d681SAndroid Build Coastguard Worker IntptrTy, IntptrTy, nullptr));
1382*9880d681SAndroid Build Coastguard Worker AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1383*9880d681SAndroid Build Coastguard Worker
1384*9880d681SAndroid Build Coastguard Worker // Declare the functions that find globals in a shared object and then invoke
1385*9880d681SAndroid Build Coastguard Worker // the (un)register function on them.
1386*9880d681SAndroid Build Coastguard Worker AsanRegisterImageGlobals = checkSanitizerInterfaceFunction(
1387*9880d681SAndroid Build Coastguard Worker M.getOrInsertFunction(kAsanRegisterImageGlobalsName,
1388*9880d681SAndroid Build Coastguard Worker IRB.getVoidTy(), IntptrTy, nullptr));
1389*9880d681SAndroid Build Coastguard Worker AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
1390*9880d681SAndroid Build Coastguard Worker
1391*9880d681SAndroid Build Coastguard Worker AsanUnregisterImageGlobals = checkSanitizerInterfaceFunction(
1392*9880d681SAndroid Build Coastguard Worker M.getOrInsertFunction(kAsanUnregisterImageGlobalsName,
1393*9880d681SAndroid Build Coastguard Worker IRB.getVoidTy(), IntptrTy, nullptr));
1394*9880d681SAndroid Build Coastguard Worker AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
1395*9880d681SAndroid Build Coastguard Worker }
1396*9880d681SAndroid Build Coastguard Worker
1397*9880d681SAndroid Build Coastguard Worker // This function replaces all global variables with new variables that have
1398*9880d681SAndroid Build Coastguard Worker // trailing redzones. It also creates a function that poisons
1399*9880d681SAndroid Build Coastguard Worker // redzones and inserts this function into llvm.global_ctors.
InstrumentGlobals(IRBuilder<> & IRB,Module & M)1400*9880d681SAndroid Build Coastguard Worker bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
1401*9880d681SAndroid Build Coastguard Worker GlobalsMD.init(M);
1402*9880d681SAndroid Build Coastguard Worker
1403*9880d681SAndroid Build Coastguard Worker SmallVector<GlobalVariable *, 16> GlobalsToChange;
1404*9880d681SAndroid Build Coastguard Worker
1405*9880d681SAndroid Build Coastguard Worker for (auto &G : M.globals()) {
1406*9880d681SAndroid Build Coastguard Worker if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
1407*9880d681SAndroid Build Coastguard Worker }
1408*9880d681SAndroid Build Coastguard Worker
1409*9880d681SAndroid Build Coastguard Worker size_t n = GlobalsToChange.size();
1410*9880d681SAndroid Build Coastguard Worker if (n == 0) return false;
1411*9880d681SAndroid Build Coastguard Worker
1412*9880d681SAndroid Build Coastguard Worker // A global is described by a structure
1413*9880d681SAndroid Build Coastguard Worker // size_t beg;
1414*9880d681SAndroid Build Coastguard Worker // size_t size;
1415*9880d681SAndroid Build Coastguard Worker // size_t size_with_redzone;
1416*9880d681SAndroid Build Coastguard Worker // const char *name;
1417*9880d681SAndroid Build Coastguard Worker // const char *module_name;
1418*9880d681SAndroid Build Coastguard Worker // size_t has_dynamic_init;
1419*9880d681SAndroid Build Coastguard Worker // void *source_location;
1420*9880d681SAndroid Build Coastguard Worker // size_t odr_indicator;
1421*9880d681SAndroid Build Coastguard Worker // We initialize an array of such structures and pass it to a run-time call.
1422*9880d681SAndroid Build Coastguard Worker StructType *GlobalStructTy =
1423*9880d681SAndroid Build Coastguard Worker StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
1424*9880d681SAndroid Build Coastguard Worker IntptrTy, IntptrTy, IntptrTy, nullptr);
1425*9880d681SAndroid Build Coastguard Worker SmallVector<Constant *, 16> Initializers(n);
1426*9880d681SAndroid Build Coastguard Worker
1427*9880d681SAndroid Build Coastguard Worker bool HasDynamicallyInitializedGlobals = false;
1428*9880d681SAndroid Build Coastguard Worker
1429*9880d681SAndroid Build Coastguard Worker // We shouldn't merge same module names, as this string serves as unique
1430*9880d681SAndroid Build Coastguard Worker // module ID in runtime.
1431*9880d681SAndroid Build Coastguard Worker GlobalVariable *ModuleName = createPrivateGlobalForString(
1432*9880d681SAndroid Build Coastguard Worker M, M.getModuleIdentifier(), /*AllowMerging*/ false);
1433*9880d681SAndroid Build Coastguard Worker
1434*9880d681SAndroid Build Coastguard Worker auto &DL = M.getDataLayout();
1435*9880d681SAndroid Build Coastguard Worker for (size_t i = 0; i < n; i++) {
1436*9880d681SAndroid Build Coastguard Worker static const uint64_t kMaxGlobalRedzone = 1 << 18;
1437*9880d681SAndroid Build Coastguard Worker GlobalVariable *G = GlobalsToChange[i];
1438*9880d681SAndroid Build Coastguard Worker
1439*9880d681SAndroid Build Coastguard Worker auto MD = GlobalsMD.get(G);
1440*9880d681SAndroid Build Coastguard Worker StringRef NameForGlobal = G->getName();
1441*9880d681SAndroid Build Coastguard Worker // Create string holding the global name (use global name from metadata
1442*9880d681SAndroid Build Coastguard Worker // if it's available, otherwise just write the name of global variable).
1443*9880d681SAndroid Build Coastguard Worker GlobalVariable *Name = createPrivateGlobalForString(
1444*9880d681SAndroid Build Coastguard Worker M, MD.Name.empty() ? NameForGlobal : MD.Name,
1445*9880d681SAndroid Build Coastguard Worker /*AllowMerging*/ true);
1446*9880d681SAndroid Build Coastguard Worker
1447*9880d681SAndroid Build Coastguard Worker Type *Ty = G->getValueType();
1448*9880d681SAndroid Build Coastguard Worker uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
1449*9880d681SAndroid Build Coastguard Worker uint64_t MinRZ = MinRedzoneSizeForGlobal();
1450*9880d681SAndroid Build Coastguard Worker // MinRZ <= RZ <= kMaxGlobalRedzone
1451*9880d681SAndroid Build Coastguard Worker // and trying to make RZ to be ~ 1/4 of SizeInBytes.
1452*9880d681SAndroid Build Coastguard Worker uint64_t RZ = std::max(
1453*9880d681SAndroid Build Coastguard Worker MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
1454*9880d681SAndroid Build Coastguard Worker uint64_t RightRedzoneSize = RZ;
1455*9880d681SAndroid Build Coastguard Worker // Round up to MinRZ
1456*9880d681SAndroid Build Coastguard Worker if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1457*9880d681SAndroid Build Coastguard Worker assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
1458*9880d681SAndroid Build Coastguard Worker Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1459*9880d681SAndroid Build Coastguard Worker
1460*9880d681SAndroid Build Coastguard Worker StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
1461*9880d681SAndroid Build Coastguard Worker Constant *NewInitializer =
1462*9880d681SAndroid Build Coastguard Worker ConstantStruct::get(NewTy, G->getInitializer(),
1463*9880d681SAndroid Build Coastguard Worker Constant::getNullValue(RightRedZoneTy), nullptr);
1464*9880d681SAndroid Build Coastguard Worker
1465*9880d681SAndroid Build Coastguard Worker // Create a new global variable with enough space for a redzone.
1466*9880d681SAndroid Build Coastguard Worker GlobalValue::LinkageTypes Linkage = G->getLinkage();
1467*9880d681SAndroid Build Coastguard Worker if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1468*9880d681SAndroid Build Coastguard Worker Linkage = GlobalValue::InternalLinkage;
1469*9880d681SAndroid Build Coastguard Worker GlobalVariable *NewGlobal =
1470*9880d681SAndroid Build Coastguard Worker new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1471*9880d681SAndroid Build Coastguard Worker "", G, G->getThreadLocalMode());
1472*9880d681SAndroid Build Coastguard Worker NewGlobal->copyAttributesFrom(G);
1473*9880d681SAndroid Build Coastguard Worker NewGlobal->setAlignment(MinRZ);
1474*9880d681SAndroid Build Coastguard Worker
1475*9880d681SAndroid Build Coastguard Worker Value *Indices2[2];
1476*9880d681SAndroid Build Coastguard Worker Indices2[0] = IRB.getInt32(0);
1477*9880d681SAndroid Build Coastguard Worker Indices2[1] = IRB.getInt32(0);
1478*9880d681SAndroid Build Coastguard Worker
1479*9880d681SAndroid Build Coastguard Worker G->replaceAllUsesWith(
1480*9880d681SAndroid Build Coastguard Worker ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
1481*9880d681SAndroid Build Coastguard Worker NewGlobal->takeName(G);
1482*9880d681SAndroid Build Coastguard Worker G->eraseFromParent();
1483*9880d681SAndroid Build Coastguard Worker
1484*9880d681SAndroid Build Coastguard Worker Constant *SourceLoc;
1485*9880d681SAndroid Build Coastguard Worker if (!MD.SourceLoc.empty()) {
1486*9880d681SAndroid Build Coastguard Worker auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1487*9880d681SAndroid Build Coastguard Worker SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1488*9880d681SAndroid Build Coastguard Worker } else {
1489*9880d681SAndroid Build Coastguard Worker SourceLoc = ConstantInt::get(IntptrTy, 0);
1490*9880d681SAndroid Build Coastguard Worker }
1491*9880d681SAndroid Build Coastguard Worker
1492*9880d681SAndroid Build Coastguard Worker Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
1493*9880d681SAndroid Build Coastguard Worker GlobalValue *InstrumentedGlobal = NewGlobal;
1494*9880d681SAndroid Build Coastguard Worker
1495*9880d681SAndroid Build Coastguard Worker bool CanUsePrivateAliases = TargetTriple.isOSBinFormatELF();
1496*9880d681SAndroid Build Coastguard Worker if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
1497*9880d681SAndroid Build Coastguard Worker // Create local alias for NewGlobal to avoid crash on ODR between
1498*9880d681SAndroid Build Coastguard Worker // instrumented and non-instrumented libraries.
1499*9880d681SAndroid Build Coastguard Worker auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
1500*9880d681SAndroid Build Coastguard Worker NameForGlobal + M.getName(), NewGlobal);
1501*9880d681SAndroid Build Coastguard Worker
1502*9880d681SAndroid Build Coastguard Worker // With local aliases, we need to provide another externally visible
1503*9880d681SAndroid Build Coastguard Worker // symbol __odr_asan_XXX to detect ODR violation.
1504*9880d681SAndroid Build Coastguard Worker auto *ODRIndicatorSym =
1505*9880d681SAndroid Build Coastguard Worker new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
1506*9880d681SAndroid Build Coastguard Worker Constant::getNullValue(IRB.getInt8Ty()),
1507*9880d681SAndroid Build Coastguard Worker kODRGenPrefix + NameForGlobal, nullptr,
1508*9880d681SAndroid Build Coastguard Worker NewGlobal->getThreadLocalMode());
1509*9880d681SAndroid Build Coastguard Worker
1510*9880d681SAndroid Build Coastguard Worker // Set meaningful attributes for indicator symbol.
1511*9880d681SAndroid Build Coastguard Worker ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
1512*9880d681SAndroid Build Coastguard Worker ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
1513*9880d681SAndroid Build Coastguard Worker ODRIndicatorSym->setAlignment(1);
1514*9880d681SAndroid Build Coastguard Worker ODRIndicator = ODRIndicatorSym;
1515*9880d681SAndroid Build Coastguard Worker InstrumentedGlobal = GA;
1516*9880d681SAndroid Build Coastguard Worker }
1517*9880d681SAndroid Build Coastguard Worker
1518*9880d681SAndroid Build Coastguard Worker Initializers[i] = ConstantStruct::get(
1519*9880d681SAndroid Build Coastguard Worker GlobalStructTy,
1520*9880d681SAndroid Build Coastguard Worker ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
1521*9880d681SAndroid Build Coastguard Worker ConstantInt::get(IntptrTy, SizeInBytes),
1522*9880d681SAndroid Build Coastguard Worker ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1523*9880d681SAndroid Build Coastguard Worker ConstantExpr::getPointerCast(Name, IntptrTy),
1524*9880d681SAndroid Build Coastguard Worker ConstantExpr::getPointerCast(ModuleName, IntptrTy),
1525*9880d681SAndroid Build Coastguard Worker ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
1526*9880d681SAndroid Build Coastguard Worker ConstantExpr::getPointerCast(ODRIndicator, IntptrTy), nullptr);
1527*9880d681SAndroid Build Coastguard Worker
1528*9880d681SAndroid Build Coastguard Worker if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
1529*9880d681SAndroid Build Coastguard Worker
1530*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
1531*9880d681SAndroid Build Coastguard Worker }
1532*9880d681SAndroid Build Coastguard Worker
1533*9880d681SAndroid Build Coastguard Worker
1534*9880d681SAndroid Build Coastguard Worker GlobalVariable *AllGlobals = nullptr;
1535*9880d681SAndroid Build Coastguard Worker GlobalVariable *RegisteredFlag = nullptr;
1536*9880d681SAndroid Build Coastguard Worker
1537*9880d681SAndroid Build Coastguard Worker // On recent Mach-O platforms, we emit the global metadata in a way that
1538*9880d681SAndroid Build Coastguard Worker // allows the linker to properly strip dead globals.
1539*9880d681SAndroid Build Coastguard Worker if (ShouldUseMachOGlobalsSection()) {
1540*9880d681SAndroid Build Coastguard Worker // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1541*9880d681SAndroid Build Coastguard Worker // to look up the loaded image that contains it. Second, we can store in it
1542*9880d681SAndroid Build Coastguard Worker // whether registration has already occurred, to prevent duplicate
1543*9880d681SAndroid Build Coastguard Worker // registration.
1544*9880d681SAndroid Build Coastguard Worker //
1545*9880d681SAndroid Build Coastguard Worker // Common linkage allows us to coalesce needles defined in each object
1546*9880d681SAndroid Build Coastguard Worker // file so that there's only one per shared library.
1547*9880d681SAndroid Build Coastguard Worker RegisteredFlag = new GlobalVariable(
1548*9880d681SAndroid Build Coastguard Worker M, IntptrTy, false, GlobalVariable::CommonLinkage,
1549*9880d681SAndroid Build Coastguard Worker ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1550*9880d681SAndroid Build Coastguard Worker
1551*9880d681SAndroid Build Coastguard Worker // We also emit a structure which binds the liveness of the global
1552*9880d681SAndroid Build Coastguard Worker // variable to the metadata struct.
1553*9880d681SAndroid Build Coastguard Worker StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy, nullptr);
1554*9880d681SAndroid Build Coastguard Worker
1555*9880d681SAndroid Build Coastguard Worker for (size_t i = 0; i < n; i++) {
1556*9880d681SAndroid Build Coastguard Worker GlobalVariable *Metadata = new GlobalVariable(
1557*9880d681SAndroid Build Coastguard Worker M, GlobalStructTy, false, GlobalVariable::InternalLinkage,
1558*9880d681SAndroid Build Coastguard Worker Initializers[i], "");
1559*9880d681SAndroid Build Coastguard Worker Metadata->setSection("__DATA,__asan_globals,regular");
1560*9880d681SAndroid Build Coastguard Worker Metadata->setAlignment(1); // don't leave padding in between
1561*9880d681SAndroid Build Coastguard Worker
1562*9880d681SAndroid Build Coastguard Worker auto LivenessBinder = ConstantStruct::get(LivenessTy,
1563*9880d681SAndroid Build Coastguard Worker Initializers[i]->getAggregateElement(0u),
1564*9880d681SAndroid Build Coastguard Worker ConstantExpr::getPointerCast(Metadata, IntptrTy),
1565*9880d681SAndroid Build Coastguard Worker nullptr);
1566*9880d681SAndroid Build Coastguard Worker GlobalVariable *Liveness = new GlobalVariable(
1567*9880d681SAndroid Build Coastguard Worker M, LivenessTy, false, GlobalVariable::InternalLinkage,
1568*9880d681SAndroid Build Coastguard Worker LivenessBinder, "");
1569*9880d681SAndroid Build Coastguard Worker Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1570*9880d681SAndroid Build Coastguard Worker }
1571*9880d681SAndroid Build Coastguard Worker } else {
1572*9880d681SAndroid Build Coastguard Worker // On all other platfoms, we just emit an array of global metadata
1573*9880d681SAndroid Build Coastguard Worker // structures.
1574*9880d681SAndroid Build Coastguard Worker ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1575*9880d681SAndroid Build Coastguard Worker AllGlobals = new GlobalVariable(
1576*9880d681SAndroid Build Coastguard Worker M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1577*9880d681SAndroid Build Coastguard Worker ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1578*9880d681SAndroid Build Coastguard Worker }
1579*9880d681SAndroid Build Coastguard Worker
1580*9880d681SAndroid Build Coastguard Worker // Create calls for poisoning before initializers run and unpoisoning after.
1581*9880d681SAndroid Build Coastguard Worker if (HasDynamicallyInitializedGlobals)
1582*9880d681SAndroid Build Coastguard Worker createInitializerPoisonCalls(M, ModuleName);
1583*9880d681SAndroid Build Coastguard Worker
1584*9880d681SAndroid Build Coastguard Worker // Create a call to register the globals with the runtime.
1585*9880d681SAndroid Build Coastguard Worker if (ShouldUseMachOGlobalsSection()) {
1586*9880d681SAndroid Build Coastguard Worker IRB.CreateCall(AsanRegisterImageGlobals,
1587*9880d681SAndroid Build Coastguard Worker {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1588*9880d681SAndroid Build Coastguard Worker } else {
1589*9880d681SAndroid Build Coastguard Worker IRB.CreateCall(AsanRegisterGlobals,
1590*9880d681SAndroid Build Coastguard Worker {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1591*9880d681SAndroid Build Coastguard Worker ConstantInt::get(IntptrTy, n)});
1592*9880d681SAndroid Build Coastguard Worker }
1593*9880d681SAndroid Build Coastguard Worker
1594*9880d681SAndroid Build Coastguard Worker // We also need to unregister globals at the end, e.g., when a shared library
1595*9880d681SAndroid Build Coastguard Worker // gets closed.
1596*9880d681SAndroid Build Coastguard Worker Function *AsanDtorFunction =
1597*9880d681SAndroid Build Coastguard Worker Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1598*9880d681SAndroid Build Coastguard Worker GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1599*9880d681SAndroid Build Coastguard Worker BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1600*9880d681SAndroid Build Coastguard Worker IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
1601*9880d681SAndroid Build Coastguard Worker
1602*9880d681SAndroid Build Coastguard Worker if (ShouldUseMachOGlobalsSection()) {
1603*9880d681SAndroid Build Coastguard Worker IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1604*9880d681SAndroid Build Coastguard Worker {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1605*9880d681SAndroid Build Coastguard Worker } else {
1606*9880d681SAndroid Build Coastguard Worker IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1607*9880d681SAndroid Build Coastguard Worker {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1608*9880d681SAndroid Build Coastguard Worker ConstantInt::get(IntptrTy, n)});
1609*9880d681SAndroid Build Coastguard Worker }
1610*9880d681SAndroid Build Coastguard Worker
1611*9880d681SAndroid Build Coastguard Worker appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
1612*9880d681SAndroid Build Coastguard Worker
1613*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << M);
1614*9880d681SAndroid Build Coastguard Worker return true;
1615*9880d681SAndroid Build Coastguard Worker }
1616*9880d681SAndroid Build Coastguard Worker
runOnModule(Module & M)1617*9880d681SAndroid Build Coastguard Worker bool AddressSanitizerModule::runOnModule(Module &M) {
1618*9880d681SAndroid Build Coastguard Worker C = &(M.getContext());
1619*9880d681SAndroid Build Coastguard Worker int LongSize = M.getDataLayout().getPointerSizeInBits();
1620*9880d681SAndroid Build Coastguard Worker IntptrTy = Type::getIntNTy(*C, LongSize);
1621*9880d681SAndroid Build Coastguard Worker TargetTriple = Triple(M.getTargetTriple());
1622*9880d681SAndroid Build Coastguard Worker Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
1623*9880d681SAndroid Build Coastguard Worker initializeCallbacks(M);
1624*9880d681SAndroid Build Coastguard Worker
1625*9880d681SAndroid Build Coastguard Worker bool Changed = false;
1626*9880d681SAndroid Build Coastguard Worker
1627*9880d681SAndroid Build Coastguard Worker // TODO(glider): temporarily disabled globals instrumentation for KASan.
1628*9880d681SAndroid Build Coastguard Worker if (ClGlobals && !CompileKernel) {
1629*9880d681SAndroid Build Coastguard Worker Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1630*9880d681SAndroid Build Coastguard Worker assert(CtorFunc);
1631*9880d681SAndroid Build Coastguard Worker IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1632*9880d681SAndroid Build Coastguard Worker Changed |= InstrumentGlobals(IRB, M);
1633*9880d681SAndroid Build Coastguard Worker }
1634*9880d681SAndroid Build Coastguard Worker
1635*9880d681SAndroid Build Coastguard Worker return Changed;
1636*9880d681SAndroid Build Coastguard Worker }
1637*9880d681SAndroid Build Coastguard Worker
initializeCallbacks(Module & M)1638*9880d681SAndroid Build Coastguard Worker void AddressSanitizer::initializeCallbacks(Module &M) {
1639*9880d681SAndroid Build Coastguard Worker IRBuilder<> IRB(*C);
1640*9880d681SAndroid Build Coastguard Worker // Create __asan_report* callbacks.
1641*9880d681SAndroid Build Coastguard Worker // IsWrite, TypeSize and Exp are encoded in the function name.
1642*9880d681SAndroid Build Coastguard Worker for (int Exp = 0; Exp < 2; Exp++) {
1643*9880d681SAndroid Build Coastguard Worker for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1644*9880d681SAndroid Build Coastguard Worker const std::string TypeStr = AccessIsWrite ? "store" : "load";
1645*9880d681SAndroid Build Coastguard Worker const std::string ExpStr = Exp ? "exp_" : "";
1646*9880d681SAndroid Build Coastguard Worker const std::string SuffixStr = CompileKernel ? "N" : "_n";
1647*9880d681SAndroid Build Coastguard Worker const std::string EndingStr = Recover ? "_noabort" : "";
1648*9880d681SAndroid Build Coastguard Worker Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
1649*9880d681SAndroid Build Coastguard Worker AsanErrorCallbackSized[AccessIsWrite][Exp] =
1650*9880d681SAndroid Build Coastguard Worker checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1651*9880d681SAndroid Build Coastguard Worker kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr + EndingStr,
1652*9880d681SAndroid Build Coastguard Worker IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1653*9880d681SAndroid Build Coastguard Worker AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
1654*9880d681SAndroid Build Coastguard Worker checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1655*9880d681SAndroid Build Coastguard Worker ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
1656*9880d681SAndroid Build Coastguard Worker IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1657*9880d681SAndroid Build Coastguard Worker for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1658*9880d681SAndroid Build Coastguard Worker AccessSizeIndex++) {
1659*9880d681SAndroid Build Coastguard Worker const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
1660*9880d681SAndroid Build Coastguard Worker AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
1661*9880d681SAndroid Build Coastguard Worker checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1662*9880d681SAndroid Build Coastguard Worker kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
1663*9880d681SAndroid Build Coastguard Worker IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
1664*9880d681SAndroid Build Coastguard Worker AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
1665*9880d681SAndroid Build Coastguard Worker checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1666*9880d681SAndroid Build Coastguard Worker ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1667*9880d681SAndroid Build Coastguard Worker IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
1668*9880d681SAndroid Build Coastguard Worker }
1669*9880d681SAndroid Build Coastguard Worker }
1670*9880d681SAndroid Build Coastguard Worker }
1671*9880d681SAndroid Build Coastguard Worker
1672*9880d681SAndroid Build Coastguard Worker const std::string MemIntrinCallbackPrefix =
1673*9880d681SAndroid Build Coastguard Worker CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
1674*9880d681SAndroid Build Coastguard Worker AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1675*9880d681SAndroid Build Coastguard Worker MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
1676*9880d681SAndroid Build Coastguard Worker IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1677*9880d681SAndroid Build Coastguard Worker AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1678*9880d681SAndroid Build Coastguard Worker MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
1679*9880d681SAndroid Build Coastguard Worker IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1680*9880d681SAndroid Build Coastguard Worker AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1681*9880d681SAndroid Build Coastguard Worker MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
1682*9880d681SAndroid Build Coastguard Worker IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
1683*9880d681SAndroid Build Coastguard Worker
1684*9880d681SAndroid Build Coastguard Worker AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
1685*9880d681SAndroid Build Coastguard Worker M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
1686*9880d681SAndroid Build Coastguard Worker
1687*9880d681SAndroid Build Coastguard Worker AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1688*9880d681SAndroid Build Coastguard Worker kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1689*9880d681SAndroid Build Coastguard Worker AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1690*9880d681SAndroid Build Coastguard Worker kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1691*9880d681SAndroid Build Coastguard Worker // We insert an empty inline asm after __asan_report* to avoid callback merge.
1692*9880d681SAndroid Build Coastguard Worker EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1693*9880d681SAndroid Build Coastguard Worker StringRef(""), StringRef(""),
1694*9880d681SAndroid Build Coastguard Worker /*hasSideEffects=*/true);
1695*9880d681SAndroid Build Coastguard Worker }
1696*9880d681SAndroid Build Coastguard Worker
1697*9880d681SAndroid Build Coastguard Worker // virtual
doInitialization(Module & M)1698*9880d681SAndroid Build Coastguard Worker bool AddressSanitizer::doInitialization(Module &M) {
1699*9880d681SAndroid Build Coastguard Worker // Initialize the private fields. No one has accessed them before.
1700*9880d681SAndroid Build Coastguard Worker
1701*9880d681SAndroid Build Coastguard Worker GlobalsMD.init(M);
1702*9880d681SAndroid Build Coastguard Worker
1703*9880d681SAndroid Build Coastguard Worker C = &(M.getContext());
1704*9880d681SAndroid Build Coastguard Worker LongSize = M.getDataLayout().getPointerSizeInBits();
1705*9880d681SAndroid Build Coastguard Worker IntptrTy = Type::getIntNTy(*C, LongSize);
1706*9880d681SAndroid Build Coastguard Worker TargetTriple = Triple(M.getTargetTriple());
1707*9880d681SAndroid Build Coastguard Worker
1708*9880d681SAndroid Build Coastguard Worker if (!CompileKernel) {
1709*9880d681SAndroid Build Coastguard Worker std::tie(AsanCtorFunction, AsanInitFunction) =
1710*9880d681SAndroid Build Coastguard Worker createSanitizerCtorAndInitFunctions(
1711*9880d681SAndroid Build Coastguard Worker M, kAsanModuleCtorName, kAsanInitName,
1712*9880d681SAndroid Build Coastguard Worker /*InitArgTypes=*/{}, /*InitArgs=*/{}, kAsanVersionCheckName);
1713*9880d681SAndroid Build Coastguard Worker appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1714*9880d681SAndroid Build Coastguard Worker }
1715*9880d681SAndroid Build Coastguard Worker Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
1716*9880d681SAndroid Build Coastguard Worker return true;
1717*9880d681SAndroid Build Coastguard Worker }
1718*9880d681SAndroid Build Coastguard Worker
doFinalization(Module & M)1719*9880d681SAndroid Build Coastguard Worker bool AddressSanitizer::doFinalization(Module &M) {
1720*9880d681SAndroid Build Coastguard Worker GlobalsMD.reset();
1721*9880d681SAndroid Build Coastguard Worker return false;
1722*9880d681SAndroid Build Coastguard Worker }
1723*9880d681SAndroid Build Coastguard Worker
maybeInsertAsanInitAtFunctionEntry(Function & F)1724*9880d681SAndroid Build Coastguard Worker bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1725*9880d681SAndroid Build Coastguard Worker // For each NSObject descendant having a +load method, this method is invoked
1726*9880d681SAndroid Build Coastguard Worker // by the ObjC runtime before any of the static constructors is called.
1727*9880d681SAndroid Build Coastguard Worker // Therefore we need to instrument such methods with a call to __asan_init
1728*9880d681SAndroid Build Coastguard Worker // at the beginning in order to initialize our runtime before any access to
1729*9880d681SAndroid Build Coastguard Worker // the shadow memory.
1730*9880d681SAndroid Build Coastguard Worker // We cannot just ignore these methods, because they may call other
1731*9880d681SAndroid Build Coastguard Worker // instrumented functions.
1732*9880d681SAndroid Build Coastguard Worker if (F.getName().find(" load]") != std::string::npos) {
1733*9880d681SAndroid Build Coastguard Worker IRBuilder<> IRB(&F.front(), F.front().begin());
1734*9880d681SAndroid Build Coastguard Worker IRB.CreateCall(AsanInitFunction, {});
1735*9880d681SAndroid Build Coastguard Worker return true;
1736*9880d681SAndroid Build Coastguard Worker }
1737*9880d681SAndroid Build Coastguard Worker return false;
1738*9880d681SAndroid Build Coastguard Worker }
1739*9880d681SAndroid Build Coastguard Worker
markEscapedLocalAllocas(Function & F)1740*9880d681SAndroid Build Coastguard Worker void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
1741*9880d681SAndroid Build Coastguard Worker // Find the one possible call to llvm.localescape and pre-mark allocas passed
1742*9880d681SAndroid Build Coastguard Worker // to it as uninteresting. This assumes we haven't started processing allocas
1743*9880d681SAndroid Build Coastguard Worker // yet. This check is done up front because iterating the use list in
1744*9880d681SAndroid Build Coastguard Worker // isInterestingAlloca would be algorithmically slower.
1745*9880d681SAndroid Build Coastguard Worker assert(ProcessedAllocas.empty() && "must process localescape before allocas");
1746*9880d681SAndroid Build Coastguard Worker
1747*9880d681SAndroid Build Coastguard Worker // Try to get the declaration of llvm.localescape. If it's not in the module,
1748*9880d681SAndroid Build Coastguard Worker // we can exit early.
1749*9880d681SAndroid Build Coastguard Worker if (!F.getParent()->getFunction("llvm.localescape")) return;
1750*9880d681SAndroid Build Coastguard Worker
1751*9880d681SAndroid Build Coastguard Worker // Look for a call to llvm.localescape call in the entry block. It can't be in
1752*9880d681SAndroid Build Coastguard Worker // any other block.
1753*9880d681SAndroid Build Coastguard Worker for (Instruction &I : F.getEntryBlock()) {
1754*9880d681SAndroid Build Coastguard Worker IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
1755*9880d681SAndroid Build Coastguard Worker if (II && II->getIntrinsicID() == Intrinsic::localescape) {
1756*9880d681SAndroid Build Coastguard Worker // We found a call. Mark all the allocas passed in as uninteresting.
1757*9880d681SAndroid Build Coastguard Worker for (Value *Arg : II->arg_operands()) {
1758*9880d681SAndroid Build Coastguard Worker AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
1759*9880d681SAndroid Build Coastguard Worker assert(AI && AI->isStaticAlloca() &&
1760*9880d681SAndroid Build Coastguard Worker "non-static alloca arg to localescape");
1761*9880d681SAndroid Build Coastguard Worker ProcessedAllocas[AI] = false;
1762*9880d681SAndroid Build Coastguard Worker }
1763*9880d681SAndroid Build Coastguard Worker break;
1764*9880d681SAndroid Build Coastguard Worker }
1765*9880d681SAndroid Build Coastguard Worker }
1766*9880d681SAndroid Build Coastguard Worker }
1767*9880d681SAndroid Build Coastguard Worker
runOnFunction(Function & F)1768*9880d681SAndroid Build Coastguard Worker bool AddressSanitizer::runOnFunction(Function &F) {
1769*9880d681SAndroid Build Coastguard Worker if (&F == AsanCtorFunction) return false;
1770*9880d681SAndroid Build Coastguard Worker if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1771*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1772*9880d681SAndroid Build Coastguard Worker initializeCallbacks(*F.getParent());
1773*9880d681SAndroid Build Coastguard Worker
1774*9880d681SAndroid Build Coastguard Worker DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1775*9880d681SAndroid Build Coastguard Worker
1776*9880d681SAndroid Build Coastguard Worker // If needed, insert __asan_init before checking for SanitizeAddress attr.
1777*9880d681SAndroid Build Coastguard Worker maybeInsertAsanInitAtFunctionEntry(F);
1778*9880d681SAndroid Build Coastguard Worker
1779*9880d681SAndroid Build Coastguard Worker if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
1780*9880d681SAndroid Build Coastguard Worker
1781*9880d681SAndroid Build Coastguard Worker if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
1782*9880d681SAndroid Build Coastguard Worker
1783*9880d681SAndroid Build Coastguard Worker FunctionStateRAII CleanupObj(this);
1784*9880d681SAndroid Build Coastguard Worker
1785*9880d681SAndroid Build Coastguard Worker // We can't instrument allocas used with llvm.localescape. Only static allocas
1786*9880d681SAndroid Build Coastguard Worker // can be passed to that intrinsic.
1787*9880d681SAndroid Build Coastguard Worker markEscapedLocalAllocas(F);
1788*9880d681SAndroid Build Coastguard Worker
1789*9880d681SAndroid Build Coastguard Worker // We want to instrument every address only once per basic block (unless there
1790*9880d681SAndroid Build Coastguard Worker // are calls between uses).
1791*9880d681SAndroid Build Coastguard Worker SmallSet<Value *, 16> TempsToInstrument;
1792*9880d681SAndroid Build Coastguard Worker SmallVector<Instruction *, 16> ToInstrument;
1793*9880d681SAndroid Build Coastguard Worker SmallVector<Instruction *, 8> NoReturnCalls;
1794*9880d681SAndroid Build Coastguard Worker SmallVector<BasicBlock *, 16> AllBlocks;
1795*9880d681SAndroid Build Coastguard Worker SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
1796*9880d681SAndroid Build Coastguard Worker int NumAllocas = 0;
1797*9880d681SAndroid Build Coastguard Worker bool IsWrite;
1798*9880d681SAndroid Build Coastguard Worker unsigned Alignment;
1799*9880d681SAndroid Build Coastguard Worker uint64_t TypeSize;
1800*9880d681SAndroid Build Coastguard Worker const TargetLibraryInfo *TLI =
1801*9880d681SAndroid Build Coastguard Worker &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1802*9880d681SAndroid Build Coastguard Worker
1803*9880d681SAndroid Build Coastguard Worker // Fill the set of memory operations to instrument.
1804*9880d681SAndroid Build Coastguard Worker for (auto &BB : F) {
1805*9880d681SAndroid Build Coastguard Worker AllBlocks.push_back(&BB);
1806*9880d681SAndroid Build Coastguard Worker TempsToInstrument.clear();
1807*9880d681SAndroid Build Coastguard Worker int NumInsnsPerBB = 0;
1808*9880d681SAndroid Build Coastguard Worker for (auto &Inst : BB) {
1809*9880d681SAndroid Build Coastguard Worker if (LooksLikeCodeInBug11395(&Inst)) return false;
1810*9880d681SAndroid Build Coastguard Worker if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1811*9880d681SAndroid Build Coastguard Worker &Alignment)) {
1812*9880d681SAndroid Build Coastguard Worker if (ClOpt && ClOptSameTemp) {
1813*9880d681SAndroid Build Coastguard Worker if (!TempsToInstrument.insert(Addr).second)
1814*9880d681SAndroid Build Coastguard Worker continue; // We've seen this temp in the current BB.
1815*9880d681SAndroid Build Coastguard Worker }
1816*9880d681SAndroid Build Coastguard Worker } else if (ClInvalidPointerPairs &&
1817*9880d681SAndroid Build Coastguard Worker isInterestingPointerComparisonOrSubtraction(&Inst)) {
1818*9880d681SAndroid Build Coastguard Worker PointerComparisonsOrSubtracts.push_back(&Inst);
1819*9880d681SAndroid Build Coastguard Worker continue;
1820*9880d681SAndroid Build Coastguard Worker } else if (isa<MemIntrinsic>(Inst)) {
1821*9880d681SAndroid Build Coastguard Worker // ok, take it.
1822*9880d681SAndroid Build Coastguard Worker } else {
1823*9880d681SAndroid Build Coastguard Worker if (isa<AllocaInst>(Inst)) NumAllocas++;
1824*9880d681SAndroid Build Coastguard Worker CallSite CS(&Inst);
1825*9880d681SAndroid Build Coastguard Worker if (CS) {
1826*9880d681SAndroid Build Coastguard Worker // A call inside BB.
1827*9880d681SAndroid Build Coastguard Worker TempsToInstrument.clear();
1828*9880d681SAndroid Build Coastguard Worker if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
1829*9880d681SAndroid Build Coastguard Worker }
1830*9880d681SAndroid Build Coastguard Worker if (CallInst *CI = dyn_cast<CallInst>(&Inst))
1831*9880d681SAndroid Build Coastguard Worker maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
1832*9880d681SAndroid Build Coastguard Worker continue;
1833*9880d681SAndroid Build Coastguard Worker }
1834*9880d681SAndroid Build Coastguard Worker ToInstrument.push_back(&Inst);
1835*9880d681SAndroid Build Coastguard Worker NumInsnsPerBB++;
1836*9880d681SAndroid Build Coastguard Worker if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
1837*9880d681SAndroid Build Coastguard Worker }
1838*9880d681SAndroid Build Coastguard Worker }
1839*9880d681SAndroid Build Coastguard Worker
1840*9880d681SAndroid Build Coastguard Worker bool UseCalls =
1841*9880d681SAndroid Build Coastguard Worker CompileKernel ||
1842*9880d681SAndroid Build Coastguard Worker (ClInstrumentationWithCallsThreshold >= 0 &&
1843*9880d681SAndroid Build Coastguard Worker ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
1844*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = F.getParent()->getDataLayout();
1845*9880d681SAndroid Build Coastguard Worker ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1846*9880d681SAndroid Build Coastguard Worker /*RoundToAlign=*/true);
1847*9880d681SAndroid Build Coastguard Worker
1848*9880d681SAndroid Build Coastguard Worker // Instrument.
1849*9880d681SAndroid Build Coastguard Worker int NumInstrumented = 0;
1850*9880d681SAndroid Build Coastguard Worker for (auto Inst : ToInstrument) {
1851*9880d681SAndroid Build Coastguard Worker if (ClDebugMin < 0 || ClDebugMax < 0 ||
1852*9880d681SAndroid Build Coastguard Worker (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1853*9880d681SAndroid Build Coastguard Worker if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
1854*9880d681SAndroid Build Coastguard Worker instrumentMop(ObjSizeVis, Inst, UseCalls,
1855*9880d681SAndroid Build Coastguard Worker F.getParent()->getDataLayout());
1856*9880d681SAndroid Build Coastguard Worker else
1857*9880d681SAndroid Build Coastguard Worker instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1858*9880d681SAndroid Build Coastguard Worker }
1859*9880d681SAndroid Build Coastguard Worker NumInstrumented++;
1860*9880d681SAndroid Build Coastguard Worker }
1861*9880d681SAndroid Build Coastguard Worker
1862*9880d681SAndroid Build Coastguard Worker FunctionStackPoisoner FSP(F, *this);
1863*9880d681SAndroid Build Coastguard Worker bool ChangedStack = FSP.runOnFunction();
1864*9880d681SAndroid Build Coastguard Worker
1865*9880d681SAndroid Build Coastguard Worker // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1866*9880d681SAndroid Build Coastguard Worker // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1867*9880d681SAndroid Build Coastguard Worker for (auto CI : NoReturnCalls) {
1868*9880d681SAndroid Build Coastguard Worker IRBuilder<> IRB(CI);
1869*9880d681SAndroid Build Coastguard Worker IRB.CreateCall(AsanHandleNoReturnFunc, {});
1870*9880d681SAndroid Build Coastguard Worker }
1871*9880d681SAndroid Build Coastguard Worker
1872*9880d681SAndroid Build Coastguard Worker for (auto Inst : PointerComparisonsOrSubtracts) {
1873*9880d681SAndroid Build Coastguard Worker instrumentPointerComparisonOrSubtraction(Inst);
1874*9880d681SAndroid Build Coastguard Worker NumInstrumented++;
1875*9880d681SAndroid Build Coastguard Worker }
1876*9880d681SAndroid Build Coastguard Worker
1877*9880d681SAndroid Build Coastguard Worker bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1878*9880d681SAndroid Build Coastguard Worker
1879*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1880*9880d681SAndroid Build Coastguard Worker
1881*9880d681SAndroid Build Coastguard Worker return res;
1882*9880d681SAndroid Build Coastguard Worker }
1883*9880d681SAndroid Build Coastguard Worker
1884*9880d681SAndroid Build Coastguard Worker // Workaround for bug 11395: we don't want to instrument stack in functions
1885*9880d681SAndroid Build Coastguard Worker // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1886*9880d681SAndroid Build Coastguard Worker // FIXME: remove once the bug 11395 is fixed.
LooksLikeCodeInBug11395(Instruction * I)1887*9880d681SAndroid Build Coastguard Worker bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1888*9880d681SAndroid Build Coastguard Worker if (LongSize != 32) return false;
1889*9880d681SAndroid Build Coastguard Worker CallInst *CI = dyn_cast<CallInst>(I);
1890*9880d681SAndroid Build Coastguard Worker if (!CI || !CI->isInlineAsm()) return false;
1891*9880d681SAndroid Build Coastguard Worker if (CI->getNumArgOperands() <= 5) return false;
1892*9880d681SAndroid Build Coastguard Worker // We have inline assembly with quite a few arguments.
1893*9880d681SAndroid Build Coastguard Worker return true;
1894*9880d681SAndroid Build Coastguard Worker }
1895*9880d681SAndroid Build Coastguard Worker
initializeCallbacks(Module & M)1896*9880d681SAndroid Build Coastguard Worker void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1897*9880d681SAndroid Build Coastguard Worker IRBuilder<> IRB(*C);
1898*9880d681SAndroid Build Coastguard Worker for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1899*9880d681SAndroid Build Coastguard Worker std::string Suffix = itostr(i);
1900*9880d681SAndroid Build Coastguard Worker AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1901*9880d681SAndroid Build Coastguard Worker M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1902*9880d681SAndroid Build Coastguard Worker IntptrTy, nullptr));
1903*9880d681SAndroid Build Coastguard Worker AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
1904*9880d681SAndroid Build Coastguard Worker M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1905*9880d681SAndroid Build Coastguard Worker IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1906*9880d681SAndroid Build Coastguard Worker }
1907*9880d681SAndroid Build Coastguard Worker if (ASan.UseAfterScope) {
1908*9880d681SAndroid Build Coastguard Worker AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
1909*9880d681SAndroid Build Coastguard Worker M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1910*9880d681SAndroid Build Coastguard Worker IntptrTy, IntptrTy, nullptr));
1911*9880d681SAndroid Build Coastguard Worker AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
1912*9880d681SAndroid Build Coastguard Worker M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1913*9880d681SAndroid Build Coastguard Worker IntptrTy, IntptrTy, nullptr));
1914*9880d681SAndroid Build Coastguard Worker }
1915*9880d681SAndroid Build Coastguard Worker
1916*9880d681SAndroid Build Coastguard Worker AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1917*9880d681SAndroid Build Coastguard Worker kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1918*9880d681SAndroid Build Coastguard Worker AsanAllocasUnpoisonFunc =
1919*9880d681SAndroid Build Coastguard Worker checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1920*9880d681SAndroid Build Coastguard Worker kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1921*9880d681SAndroid Build Coastguard Worker }
1922*9880d681SAndroid Build Coastguard Worker
poisonRedZones(ArrayRef<uint8_t> ShadowBytes,IRBuilder<> & IRB,Value * ShadowBase,bool DoPoison)1923*9880d681SAndroid Build Coastguard Worker void FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1924*9880d681SAndroid Build Coastguard Worker IRBuilder<> &IRB, Value *ShadowBase,
1925*9880d681SAndroid Build Coastguard Worker bool DoPoison) {
1926*9880d681SAndroid Build Coastguard Worker size_t n = ShadowBytes.size();
1927*9880d681SAndroid Build Coastguard Worker size_t i = 0;
1928*9880d681SAndroid Build Coastguard Worker // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1929*9880d681SAndroid Build Coastguard Worker // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1930*9880d681SAndroid Build Coastguard Worker // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1931*9880d681SAndroid Build Coastguard Worker for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1932*9880d681SAndroid Build Coastguard Worker LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1933*9880d681SAndroid Build Coastguard Worker for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1934*9880d681SAndroid Build Coastguard Worker uint64_t Val = 0;
1935*9880d681SAndroid Build Coastguard Worker for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
1936*9880d681SAndroid Build Coastguard Worker if (F.getParent()->getDataLayout().isLittleEndian())
1937*9880d681SAndroid Build Coastguard Worker Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1938*9880d681SAndroid Build Coastguard Worker else
1939*9880d681SAndroid Build Coastguard Worker Val = (Val << 8) | ShadowBytes[i + j];
1940*9880d681SAndroid Build Coastguard Worker }
1941*9880d681SAndroid Build Coastguard Worker if (!Val) continue;
1942*9880d681SAndroid Build Coastguard Worker Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1943*9880d681SAndroid Build Coastguard Worker Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1944*9880d681SAndroid Build Coastguard Worker Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1945*9880d681SAndroid Build Coastguard Worker IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
1946*9880d681SAndroid Build Coastguard Worker }
1947*9880d681SAndroid Build Coastguard Worker }
1948*9880d681SAndroid Build Coastguard Worker }
1949*9880d681SAndroid Build Coastguard Worker
1950*9880d681SAndroid Build Coastguard Worker // Fake stack allocator (asan_fake_stack.h) has 11 size classes
1951*9880d681SAndroid Build Coastguard Worker // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
StackMallocSizeClass(uint64_t LocalStackSize)1952*9880d681SAndroid Build Coastguard Worker static int StackMallocSizeClass(uint64_t LocalStackSize) {
1953*9880d681SAndroid Build Coastguard Worker assert(LocalStackSize <= kMaxStackMallocSize);
1954*9880d681SAndroid Build Coastguard Worker uint64_t MaxSize = kMinStackMallocSize;
1955*9880d681SAndroid Build Coastguard Worker for (int i = 0;; i++, MaxSize *= 2)
1956*9880d681SAndroid Build Coastguard Worker if (LocalStackSize <= MaxSize) return i;
1957*9880d681SAndroid Build Coastguard Worker llvm_unreachable("impossible LocalStackSize");
1958*9880d681SAndroid Build Coastguard Worker }
1959*9880d681SAndroid Build Coastguard Worker
1960*9880d681SAndroid Build Coastguard Worker // Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1961*9880d681SAndroid Build Coastguard Worker // We can not use MemSet intrinsic because it may end up calling the actual
1962*9880d681SAndroid Build Coastguard Worker // memset. Size is a multiple of 8.
1963*9880d681SAndroid Build Coastguard Worker // Currently this generates 8-byte stores on x86_64; it may be better to
1964*9880d681SAndroid Build Coastguard Worker // generate wider stores.
SetShadowToStackAfterReturnInlined(IRBuilder<> & IRB,Value * ShadowBase,int Size)1965*9880d681SAndroid Build Coastguard Worker void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1966*9880d681SAndroid Build Coastguard Worker IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1967*9880d681SAndroid Build Coastguard Worker assert(!(Size % 8));
1968*9880d681SAndroid Build Coastguard Worker
1969*9880d681SAndroid Build Coastguard Worker // kAsanStackAfterReturnMagic is 0xf5.
1970*9880d681SAndroid Build Coastguard Worker const uint64_t kAsanStackAfterReturnMagic64 = 0xf5f5f5f5f5f5f5f5ULL;
1971*9880d681SAndroid Build Coastguard Worker
1972*9880d681SAndroid Build Coastguard Worker for (int i = 0; i < Size; i += 8) {
1973*9880d681SAndroid Build Coastguard Worker Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1974*9880d681SAndroid Build Coastguard Worker IRB.CreateStore(
1975*9880d681SAndroid Build Coastguard Worker ConstantInt::get(IRB.getInt64Ty(), kAsanStackAfterReturnMagic64),
1976*9880d681SAndroid Build Coastguard Worker IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1977*9880d681SAndroid Build Coastguard Worker }
1978*9880d681SAndroid Build Coastguard Worker }
1979*9880d681SAndroid Build Coastguard Worker
createPHI(IRBuilder<> & IRB,Value * Cond,Value * ValueIfTrue,Instruction * ThenTerm,Value * ValueIfFalse)1980*9880d681SAndroid Build Coastguard Worker PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1981*9880d681SAndroid Build Coastguard Worker Value *ValueIfTrue,
1982*9880d681SAndroid Build Coastguard Worker Instruction *ThenTerm,
1983*9880d681SAndroid Build Coastguard Worker Value *ValueIfFalse) {
1984*9880d681SAndroid Build Coastguard Worker PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1985*9880d681SAndroid Build Coastguard Worker BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1986*9880d681SAndroid Build Coastguard Worker PHI->addIncoming(ValueIfFalse, CondBlock);
1987*9880d681SAndroid Build Coastguard Worker BasicBlock *ThenBlock = ThenTerm->getParent();
1988*9880d681SAndroid Build Coastguard Worker PHI->addIncoming(ValueIfTrue, ThenBlock);
1989*9880d681SAndroid Build Coastguard Worker return PHI;
1990*9880d681SAndroid Build Coastguard Worker }
1991*9880d681SAndroid Build Coastguard Worker
createAllocaForLayout(IRBuilder<> & IRB,const ASanStackFrameLayout & L,bool Dynamic)1992*9880d681SAndroid Build Coastguard Worker Value *FunctionStackPoisoner::createAllocaForLayout(
1993*9880d681SAndroid Build Coastguard Worker IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
1994*9880d681SAndroid Build Coastguard Worker AllocaInst *Alloca;
1995*9880d681SAndroid Build Coastguard Worker if (Dynamic) {
1996*9880d681SAndroid Build Coastguard Worker Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
1997*9880d681SAndroid Build Coastguard Worker ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
1998*9880d681SAndroid Build Coastguard Worker "MyAlloca");
1999*9880d681SAndroid Build Coastguard Worker } else {
2000*9880d681SAndroid Build Coastguard Worker Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2001*9880d681SAndroid Build Coastguard Worker nullptr, "MyAlloca");
2002*9880d681SAndroid Build Coastguard Worker assert(Alloca->isStaticAlloca());
2003*9880d681SAndroid Build Coastguard Worker }
2004*9880d681SAndroid Build Coastguard Worker assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2005*9880d681SAndroid Build Coastguard Worker size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2006*9880d681SAndroid Build Coastguard Worker Alloca->setAlignment(FrameAlignment);
2007*9880d681SAndroid Build Coastguard Worker return IRB.CreatePointerCast(Alloca, IntptrTy);
2008*9880d681SAndroid Build Coastguard Worker }
2009*9880d681SAndroid Build Coastguard Worker
createDynamicAllocasInitStorage()2010*9880d681SAndroid Build Coastguard Worker void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2011*9880d681SAndroid Build Coastguard Worker BasicBlock &FirstBB = *F.begin();
2012*9880d681SAndroid Build Coastguard Worker IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2013*9880d681SAndroid Build Coastguard Worker DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2014*9880d681SAndroid Build Coastguard Worker IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2015*9880d681SAndroid Build Coastguard Worker DynamicAllocaLayout->setAlignment(32);
2016*9880d681SAndroid Build Coastguard Worker }
2017*9880d681SAndroid Build Coastguard Worker
poisonStack()2018*9880d681SAndroid Build Coastguard Worker void FunctionStackPoisoner::poisonStack() {
2019*9880d681SAndroid Build Coastguard Worker assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
2020*9880d681SAndroid Build Coastguard Worker
2021*9880d681SAndroid Build Coastguard Worker // Insert poison calls for lifetime intrinsics for alloca.
2022*9880d681SAndroid Build Coastguard Worker bool HavePoisonedStaticAllocas = false;
2023*9880d681SAndroid Build Coastguard Worker for (const auto &APC : AllocaPoisonCallVec) {
2024*9880d681SAndroid Build Coastguard Worker assert(APC.InsBefore);
2025*9880d681SAndroid Build Coastguard Worker assert(APC.AI);
2026*9880d681SAndroid Build Coastguard Worker assert(ASan.isInterestingAlloca(*APC.AI));
2027*9880d681SAndroid Build Coastguard Worker bool IsDynamicAlloca = !(*APC.AI).isStaticAlloca();
2028*9880d681SAndroid Build Coastguard Worker if (!ClInstrumentAllocas && IsDynamicAlloca)
2029*9880d681SAndroid Build Coastguard Worker continue;
2030*9880d681SAndroid Build Coastguard Worker
2031*9880d681SAndroid Build Coastguard Worker IRBuilder<> IRB(APC.InsBefore);
2032*9880d681SAndroid Build Coastguard Worker poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
2033*9880d681SAndroid Build Coastguard Worker // Dynamic allocas will be unpoisoned unconditionally below in
2034*9880d681SAndroid Build Coastguard Worker // unpoisonDynamicAllocas.
2035*9880d681SAndroid Build Coastguard Worker // Flag that we need unpoison static allocas.
2036*9880d681SAndroid Build Coastguard Worker HavePoisonedStaticAllocas |= (APC.DoPoison && !IsDynamicAlloca);
2037*9880d681SAndroid Build Coastguard Worker }
2038*9880d681SAndroid Build Coastguard Worker
2039*9880d681SAndroid Build Coastguard Worker if (ClInstrumentAllocas && DynamicAllocaVec.size() > 0) {
2040*9880d681SAndroid Build Coastguard Worker // Handle dynamic allocas.
2041*9880d681SAndroid Build Coastguard Worker createDynamicAllocasInitStorage();
2042*9880d681SAndroid Build Coastguard Worker for (auto &AI : DynamicAllocaVec) handleDynamicAllocaCall(AI);
2043*9880d681SAndroid Build Coastguard Worker
2044*9880d681SAndroid Build Coastguard Worker unpoisonDynamicAllocas();
2045*9880d681SAndroid Build Coastguard Worker }
2046*9880d681SAndroid Build Coastguard Worker
2047*9880d681SAndroid Build Coastguard Worker if (AllocaVec.empty()) return;
2048*9880d681SAndroid Build Coastguard Worker
2049*9880d681SAndroid Build Coastguard Worker int StackMallocIdx = -1;
2050*9880d681SAndroid Build Coastguard Worker DebugLoc EntryDebugLocation;
2051*9880d681SAndroid Build Coastguard Worker if (auto SP = F.getSubprogram())
2052*9880d681SAndroid Build Coastguard Worker EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
2053*9880d681SAndroid Build Coastguard Worker
2054*9880d681SAndroid Build Coastguard Worker Instruction *InsBefore = AllocaVec[0];
2055*9880d681SAndroid Build Coastguard Worker IRBuilder<> IRB(InsBefore);
2056*9880d681SAndroid Build Coastguard Worker IRB.SetCurrentDebugLocation(EntryDebugLocation);
2057*9880d681SAndroid Build Coastguard Worker
2058*9880d681SAndroid Build Coastguard Worker // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2059*9880d681SAndroid Build Coastguard Worker // debug info is broken, because only entry-block allocas are treated as
2060*9880d681SAndroid Build Coastguard Worker // regular stack slots.
2061*9880d681SAndroid Build Coastguard Worker auto InsBeforeB = InsBefore->getParent();
2062*9880d681SAndroid Build Coastguard Worker assert(InsBeforeB == &F.getEntryBlock());
2063*9880d681SAndroid Build Coastguard Worker for (BasicBlock::iterator I(InsBefore); I != InsBeforeB->end(); ++I)
2064*9880d681SAndroid Build Coastguard Worker if (auto *AI = dyn_cast<AllocaInst>(I))
2065*9880d681SAndroid Build Coastguard Worker if (NonInstrumentedStaticAllocaVec.count(AI) > 0)
2066*9880d681SAndroid Build Coastguard Worker AI->moveBefore(InsBefore);
2067*9880d681SAndroid Build Coastguard Worker
2068*9880d681SAndroid Build Coastguard Worker // If we have a call to llvm.localescape, keep it in the entry block.
2069*9880d681SAndroid Build Coastguard Worker if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2070*9880d681SAndroid Build Coastguard Worker
2071*9880d681SAndroid Build Coastguard Worker SmallVector<ASanStackVariableDescription, 16> SVD;
2072*9880d681SAndroid Build Coastguard Worker SVD.reserve(AllocaVec.size());
2073*9880d681SAndroid Build Coastguard Worker for (AllocaInst *AI : AllocaVec) {
2074*9880d681SAndroid Build Coastguard Worker ASanStackVariableDescription D = {AI->getName().data(),
2075*9880d681SAndroid Build Coastguard Worker ASan.getAllocaSizeInBytes(AI),
2076*9880d681SAndroid Build Coastguard Worker AI->getAlignment(), AI, 0};
2077*9880d681SAndroid Build Coastguard Worker SVD.push_back(D);
2078*9880d681SAndroid Build Coastguard Worker }
2079*9880d681SAndroid Build Coastguard Worker // Minimal header size (left redzone) is 4 pointers,
2080*9880d681SAndroid Build Coastguard Worker // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2081*9880d681SAndroid Build Coastguard Worker size_t MinHeaderSize = ASan.LongSize / 2;
2082*9880d681SAndroid Build Coastguard Worker ASanStackFrameLayout L;
2083*9880d681SAndroid Build Coastguard Worker ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize, &L);
2084*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
2085*9880d681SAndroid Build Coastguard Worker uint64_t LocalStackSize = L.FrameSize;
2086*9880d681SAndroid Build Coastguard Worker bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2087*9880d681SAndroid Build Coastguard Worker LocalStackSize <= kMaxStackMallocSize;
2088*9880d681SAndroid Build Coastguard Worker bool DoDynamicAlloca = ClDynamicAllocaStack;
2089*9880d681SAndroid Build Coastguard Worker // Don't do dynamic alloca or stack malloc if:
2090*9880d681SAndroid Build Coastguard Worker // 1) There is inline asm: too often it makes assumptions on which registers
2091*9880d681SAndroid Build Coastguard Worker // are available.
2092*9880d681SAndroid Build Coastguard Worker // 2) There is a returns_twice call (typically setjmp), which is
2093*9880d681SAndroid Build Coastguard Worker // optimization-hostile, and doesn't play well with introduced indirect
2094*9880d681SAndroid Build Coastguard Worker // register-relative calculation of local variable addresses.
2095*9880d681SAndroid Build Coastguard Worker DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2096*9880d681SAndroid Build Coastguard Worker DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2097*9880d681SAndroid Build Coastguard Worker
2098*9880d681SAndroid Build Coastguard Worker Value *StaticAlloca =
2099*9880d681SAndroid Build Coastguard Worker DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2100*9880d681SAndroid Build Coastguard Worker
2101*9880d681SAndroid Build Coastguard Worker Value *FakeStack;
2102*9880d681SAndroid Build Coastguard Worker Value *LocalStackBase;
2103*9880d681SAndroid Build Coastguard Worker
2104*9880d681SAndroid Build Coastguard Worker if (DoStackMalloc) {
2105*9880d681SAndroid Build Coastguard Worker // void *FakeStack = __asan_option_detect_stack_use_after_return
2106*9880d681SAndroid Build Coastguard Worker // ? __asan_stack_malloc_N(LocalStackSize)
2107*9880d681SAndroid Build Coastguard Worker // : nullptr;
2108*9880d681SAndroid Build Coastguard Worker // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
2109*9880d681SAndroid Build Coastguard Worker Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2110*9880d681SAndroid Build Coastguard Worker kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2111*9880d681SAndroid Build Coastguard Worker Value *UseAfterReturnIsEnabled =
2112*9880d681SAndroid Build Coastguard Worker IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
2113*9880d681SAndroid Build Coastguard Worker Constant::getNullValue(IRB.getInt32Ty()));
2114*9880d681SAndroid Build Coastguard Worker Instruction *Term =
2115*9880d681SAndroid Build Coastguard Worker SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
2116*9880d681SAndroid Build Coastguard Worker IRBuilder<> IRBIf(Term);
2117*9880d681SAndroid Build Coastguard Worker IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2118*9880d681SAndroid Build Coastguard Worker StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2119*9880d681SAndroid Build Coastguard Worker assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2120*9880d681SAndroid Build Coastguard Worker Value *FakeStackValue =
2121*9880d681SAndroid Build Coastguard Worker IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2122*9880d681SAndroid Build Coastguard Worker ConstantInt::get(IntptrTy, LocalStackSize));
2123*9880d681SAndroid Build Coastguard Worker IRB.SetInsertPoint(InsBefore);
2124*9880d681SAndroid Build Coastguard Worker IRB.SetCurrentDebugLocation(EntryDebugLocation);
2125*9880d681SAndroid Build Coastguard Worker FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
2126*9880d681SAndroid Build Coastguard Worker ConstantInt::get(IntptrTy, 0));
2127*9880d681SAndroid Build Coastguard Worker
2128*9880d681SAndroid Build Coastguard Worker Value *NoFakeStack =
2129*9880d681SAndroid Build Coastguard Worker IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2130*9880d681SAndroid Build Coastguard Worker Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2131*9880d681SAndroid Build Coastguard Worker IRBIf.SetInsertPoint(Term);
2132*9880d681SAndroid Build Coastguard Worker IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2133*9880d681SAndroid Build Coastguard Worker Value *AllocaValue =
2134*9880d681SAndroid Build Coastguard Worker DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2135*9880d681SAndroid Build Coastguard Worker IRB.SetInsertPoint(InsBefore);
2136*9880d681SAndroid Build Coastguard Worker IRB.SetCurrentDebugLocation(EntryDebugLocation);
2137*9880d681SAndroid Build Coastguard Worker LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2138*9880d681SAndroid Build Coastguard Worker } else {
2139*9880d681SAndroid Build Coastguard Worker // void *FakeStack = nullptr;
2140*9880d681SAndroid Build Coastguard Worker // void *LocalStackBase = alloca(LocalStackSize);
2141*9880d681SAndroid Build Coastguard Worker FakeStack = ConstantInt::get(IntptrTy, 0);
2142*9880d681SAndroid Build Coastguard Worker LocalStackBase =
2143*9880d681SAndroid Build Coastguard Worker DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
2144*9880d681SAndroid Build Coastguard Worker }
2145*9880d681SAndroid Build Coastguard Worker
2146*9880d681SAndroid Build Coastguard Worker // Replace Alloca instructions with base+offset.
2147*9880d681SAndroid Build Coastguard Worker for (const auto &Desc : SVD) {
2148*9880d681SAndroid Build Coastguard Worker AllocaInst *AI = Desc.AI;
2149*9880d681SAndroid Build Coastguard Worker Value *NewAllocaPtr = IRB.CreateIntToPtr(
2150*9880d681SAndroid Build Coastguard Worker IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
2151*9880d681SAndroid Build Coastguard Worker AI->getType());
2152*9880d681SAndroid Build Coastguard Worker replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
2153*9880d681SAndroid Build Coastguard Worker AI->replaceAllUsesWith(NewAllocaPtr);
2154*9880d681SAndroid Build Coastguard Worker }
2155*9880d681SAndroid Build Coastguard Worker
2156*9880d681SAndroid Build Coastguard Worker // The left-most redzone has enough space for at least 4 pointers.
2157*9880d681SAndroid Build Coastguard Worker // Write the Magic value to redzone[0].
2158*9880d681SAndroid Build Coastguard Worker Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2159*9880d681SAndroid Build Coastguard Worker IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2160*9880d681SAndroid Build Coastguard Worker BasePlus0);
2161*9880d681SAndroid Build Coastguard Worker // Write the frame description constant to redzone[1].
2162*9880d681SAndroid Build Coastguard Worker Value *BasePlus1 = IRB.CreateIntToPtr(
2163*9880d681SAndroid Build Coastguard Worker IRB.CreateAdd(LocalStackBase,
2164*9880d681SAndroid Build Coastguard Worker ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2165*9880d681SAndroid Build Coastguard Worker IntptrPtrTy);
2166*9880d681SAndroid Build Coastguard Worker GlobalVariable *StackDescriptionGlobal =
2167*9880d681SAndroid Build Coastguard Worker createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
2168*9880d681SAndroid Build Coastguard Worker /*AllowMerging*/ true);
2169*9880d681SAndroid Build Coastguard Worker Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
2170*9880d681SAndroid Build Coastguard Worker IRB.CreateStore(Description, BasePlus1);
2171*9880d681SAndroid Build Coastguard Worker // Write the PC to redzone[2].
2172*9880d681SAndroid Build Coastguard Worker Value *BasePlus2 = IRB.CreateIntToPtr(
2173*9880d681SAndroid Build Coastguard Worker IRB.CreateAdd(LocalStackBase,
2174*9880d681SAndroid Build Coastguard Worker ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2175*9880d681SAndroid Build Coastguard Worker IntptrPtrTy);
2176*9880d681SAndroid Build Coastguard Worker IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
2177*9880d681SAndroid Build Coastguard Worker
2178*9880d681SAndroid Build Coastguard Worker // Poison the stack redzones at the entry.
2179*9880d681SAndroid Build Coastguard Worker Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
2180*9880d681SAndroid Build Coastguard Worker poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
2181*9880d681SAndroid Build Coastguard Worker
2182*9880d681SAndroid Build Coastguard Worker auto UnpoisonStack = [&](IRBuilder<> &IRB) {
2183*9880d681SAndroid Build Coastguard Worker if (HavePoisonedStaticAllocas) {
2184*9880d681SAndroid Build Coastguard Worker // If we poisoned some allocas in llvm.lifetime analysis,
2185*9880d681SAndroid Build Coastguard Worker // unpoison whole stack frame now.
2186*9880d681SAndroid Build Coastguard Worker poisonAlloca(LocalStackBase, LocalStackSize, IRB, false);
2187*9880d681SAndroid Build Coastguard Worker } else {
2188*9880d681SAndroid Build Coastguard Worker poisonRedZones(L.ShadowBytes, IRB, ShadowBase, false);
2189*9880d681SAndroid Build Coastguard Worker }
2190*9880d681SAndroid Build Coastguard Worker };
2191*9880d681SAndroid Build Coastguard Worker
2192*9880d681SAndroid Build Coastguard Worker // (Un)poison the stack before all ret instructions.
2193*9880d681SAndroid Build Coastguard Worker for (auto Ret : RetVec) {
2194*9880d681SAndroid Build Coastguard Worker IRBuilder<> IRBRet(Ret);
2195*9880d681SAndroid Build Coastguard Worker // Mark the current frame as retired.
2196*9880d681SAndroid Build Coastguard Worker IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2197*9880d681SAndroid Build Coastguard Worker BasePlus0);
2198*9880d681SAndroid Build Coastguard Worker if (DoStackMalloc) {
2199*9880d681SAndroid Build Coastguard Worker assert(StackMallocIdx >= 0);
2200*9880d681SAndroid Build Coastguard Worker // if FakeStack != 0 // LocalStackBase == FakeStack
2201*9880d681SAndroid Build Coastguard Worker // // In use-after-return mode, poison the whole stack frame.
2202*9880d681SAndroid Build Coastguard Worker // if StackMallocIdx <= 4
2203*9880d681SAndroid Build Coastguard Worker // // For small sizes inline the whole thing:
2204*9880d681SAndroid Build Coastguard Worker // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
2205*9880d681SAndroid Build Coastguard Worker // **SavedFlagPtr(FakeStack) = 0
2206*9880d681SAndroid Build Coastguard Worker // else
2207*9880d681SAndroid Build Coastguard Worker // __asan_stack_free_N(FakeStack, LocalStackSize)
2208*9880d681SAndroid Build Coastguard Worker // else
2209*9880d681SAndroid Build Coastguard Worker // <This is not a fake stack; unpoison the redzones>
2210*9880d681SAndroid Build Coastguard Worker Value *Cmp =
2211*9880d681SAndroid Build Coastguard Worker IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
2212*9880d681SAndroid Build Coastguard Worker TerminatorInst *ThenTerm, *ElseTerm;
2213*9880d681SAndroid Build Coastguard Worker SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2214*9880d681SAndroid Build Coastguard Worker
2215*9880d681SAndroid Build Coastguard Worker IRBuilder<> IRBPoison(ThenTerm);
2216*9880d681SAndroid Build Coastguard Worker if (StackMallocIdx <= 4) {
2217*9880d681SAndroid Build Coastguard Worker int ClassSize = kMinStackMallocSize << StackMallocIdx;
2218*9880d681SAndroid Build Coastguard Worker SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
2219*9880d681SAndroid Build Coastguard Worker ClassSize >> Mapping.Scale);
2220*9880d681SAndroid Build Coastguard Worker Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
2221*9880d681SAndroid Build Coastguard Worker FakeStack,
2222*9880d681SAndroid Build Coastguard Worker ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2223*9880d681SAndroid Build Coastguard Worker Value *SavedFlagPtr = IRBPoison.CreateLoad(
2224*9880d681SAndroid Build Coastguard Worker IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2225*9880d681SAndroid Build Coastguard Worker IRBPoison.CreateStore(
2226*9880d681SAndroid Build Coastguard Worker Constant::getNullValue(IRBPoison.getInt8Ty()),
2227*9880d681SAndroid Build Coastguard Worker IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2228*9880d681SAndroid Build Coastguard Worker } else {
2229*9880d681SAndroid Build Coastguard Worker // For larger frames call __asan_stack_free_*.
2230*9880d681SAndroid Build Coastguard Worker IRBPoison.CreateCall(
2231*9880d681SAndroid Build Coastguard Worker AsanStackFreeFunc[StackMallocIdx],
2232*9880d681SAndroid Build Coastguard Worker {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
2233*9880d681SAndroid Build Coastguard Worker }
2234*9880d681SAndroid Build Coastguard Worker
2235*9880d681SAndroid Build Coastguard Worker IRBuilder<> IRBElse(ElseTerm);
2236*9880d681SAndroid Build Coastguard Worker UnpoisonStack(IRBElse);
2237*9880d681SAndroid Build Coastguard Worker } else {
2238*9880d681SAndroid Build Coastguard Worker UnpoisonStack(IRBRet);
2239*9880d681SAndroid Build Coastguard Worker }
2240*9880d681SAndroid Build Coastguard Worker }
2241*9880d681SAndroid Build Coastguard Worker
2242*9880d681SAndroid Build Coastguard Worker // We are done. Remove the old unused alloca instructions.
2243*9880d681SAndroid Build Coastguard Worker for (auto AI : AllocaVec) AI->eraseFromParent();
2244*9880d681SAndroid Build Coastguard Worker }
2245*9880d681SAndroid Build Coastguard Worker
poisonAlloca(Value * V,uint64_t Size,IRBuilder<> & IRB,bool DoPoison)2246*9880d681SAndroid Build Coastguard Worker void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
2247*9880d681SAndroid Build Coastguard Worker IRBuilder<> &IRB, bool DoPoison) {
2248*9880d681SAndroid Build Coastguard Worker // For now just insert the call to ASan runtime.
2249*9880d681SAndroid Build Coastguard Worker Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2250*9880d681SAndroid Build Coastguard Worker Value *SizeArg = ConstantInt::get(IntptrTy, Size);
2251*9880d681SAndroid Build Coastguard Worker IRB.CreateCall(
2252*9880d681SAndroid Build Coastguard Worker DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2253*9880d681SAndroid Build Coastguard Worker {AddrArg, SizeArg});
2254*9880d681SAndroid Build Coastguard Worker }
2255*9880d681SAndroid Build Coastguard Worker
2256*9880d681SAndroid Build Coastguard Worker // Handling llvm.lifetime intrinsics for a given %alloca:
2257*9880d681SAndroid Build Coastguard Worker // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2258*9880d681SAndroid Build Coastguard Worker // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2259*9880d681SAndroid Build Coastguard Worker // invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2260*9880d681SAndroid Build Coastguard Worker // could be poisoned by previous llvm.lifetime.end instruction, as the
2261*9880d681SAndroid Build Coastguard Worker // variable may go in and out of scope several times, e.g. in loops).
2262*9880d681SAndroid Build Coastguard Worker // (3) if we poisoned at least one %alloca in a function,
2263*9880d681SAndroid Build Coastguard Worker // unpoison the whole stack frame at function exit.
2264*9880d681SAndroid Build Coastguard Worker
findAllocaForValue(Value * V)2265*9880d681SAndroid Build Coastguard Worker AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2266*9880d681SAndroid Build Coastguard Worker if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
2267*9880d681SAndroid Build Coastguard Worker // We're intested only in allocas we can handle.
2268*9880d681SAndroid Build Coastguard Worker return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
2269*9880d681SAndroid Build Coastguard Worker // See if we've already calculated (or started to calculate) alloca for a
2270*9880d681SAndroid Build Coastguard Worker // given value.
2271*9880d681SAndroid Build Coastguard Worker AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
2272*9880d681SAndroid Build Coastguard Worker if (I != AllocaForValue.end()) return I->second;
2273*9880d681SAndroid Build Coastguard Worker // Store 0 while we're calculating alloca for value V to avoid
2274*9880d681SAndroid Build Coastguard Worker // infinite recursion if the value references itself.
2275*9880d681SAndroid Build Coastguard Worker AllocaForValue[V] = nullptr;
2276*9880d681SAndroid Build Coastguard Worker AllocaInst *Res = nullptr;
2277*9880d681SAndroid Build Coastguard Worker if (CastInst *CI = dyn_cast<CastInst>(V))
2278*9880d681SAndroid Build Coastguard Worker Res = findAllocaForValue(CI->getOperand(0));
2279*9880d681SAndroid Build Coastguard Worker else if (PHINode *PN = dyn_cast<PHINode>(V)) {
2280*9880d681SAndroid Build Coastguard Worker for (Value *IncValue : PN->incoming_values()) {
2281*9880d681SAndroid Build Coastguard Worker // Allow self-referencing phi-nodes.
2282*9880d681SAndroid Build Coastguard Worker if (IncValue == PN) continue;
2283*9880d681SAndroid Build Coastguard Worker AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2284*9880d681SAndroid Build Coastguard Worker // AI for incoming values should exist and should all be equal.
2285*9880d681SAndroid Build Coastguard Worker if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2286*9880d681SAndroid Build Coastguard Worker return nullptr;
2287*9880d681SAndroid Build Coastguard Worker Res = IncValueAI;
2288*9880d681SAndroid Build Coastguard Worker }
2289*9880d681SAndroid Build Coastguard Worker }
2290*9880d681SAndroid Build Coastguard Worker if (Res) AllocaForValue[V] = Res;
2291*9880d681SAndroid Build Coastguard Worker return Res;
2292*9880d681SAndroid Build Coastguard Worker }
2293*9880d681SAndroid Build Coastguard Worker
handleDynamicAllocaCall(AllocaInst * AI)2294*9880d681SAndroid Build Coastguard Worker void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
2295*9880d681SAndroid Build Coastguard Worker IRBuilder<> IRB(AI);
2296*9880d681SAndroid Build Coastguard Worker
2297*9880d681SAndroid Build Coastguard Worker const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2298*9880d681SAndroid Build Coastguard Worker const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2299*9880d681SAndroid Build Coastguard Worker
2300*9880d681SAndroid Build Coastguard Worker Value *Zero = Constant::getNullValue(IntptrTy);
2301*9880d681SAndroid Build Coastguard Worker Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2302*9880d681SAndroid Build Coastguard Worker Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
2303*9880d681SAndroid Build Coastguard Worker
2304*9880d681SAndroid Build Coastguard Worker // Since we need to extend alloca with additional memory to locate
2305*9880d681SAndroid Build Coastguard Worker // redzones, and OldSize is number of allocated blocks with
2306*9880d681SAndroid Build Coastguard Worker // ElementSize size, get allocated memory size in bytes by
2307*9880d681SAndroid Build Coastguard Worker // OldSize * ElementSize.
2308*9880d681SAndroid Build Coastguard Worker const unsigned ElementSize =
2309*9880d681SAndroid Build Coastguard Worker F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
2310*9880d681SAndroid Build Coastguard Worker Value *OldSize =
2311*9880d681SAndroid Build Coastguard Worker IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2312*9880d681SAndroid Build Coastguard Worker ConstantInt::get(IntptrTy, ElementSize));
2313*9880d681SAndroid Build Coastguard Worker
2314*9880d681SAndroid Build Coastguard Worker // PartialSize = OldSize % 32
2315*9880d681SAndroid Build Coastguard Worker Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2316*9880d681SAndroid Build Coastguard Worker
2317*9880d681SAndroid Build Coastguard Worker // Misalign = kAllocaRzSize - PartialSize;
2318*9880d681SAndroid Build Coastguard Worker Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2319*9880d681SAndroid Build Coastguard Worker
2320*9880d681SAndroid Build Coastguard Worker // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2321*9880d681SAndroid Build Coastguard Worker Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2322*9880d681SAndroid Build Coastguard Worker Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2323*9880d681SAndroid Build Coastguard Worker
2324*9880d681SAndroid Build Coastguard Worker // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2325*9880d681SAndroid Build Coastguard Worker // Align is added to locate left redzone, PartialPadding for possible
2326*9880d681SAndroid Build Coastguard Worker // partial redzone and kAllocaRzSize for right redzone respectively.
2327*9880d681SAndroid Build Coastguard Worker Value *AdditionalChunkSize = IRB.CreateAdd(
2328*9880d681SAndroid Build Coastguard Worker ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2329*9880d681SAndroid Build Coastguard Worker
2330*9880d681SAndroid Build Coastguard Worker Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2331*9880d681SAndroid Build Coastguard Worker
2332*9880d681SAndroid Build Coastguard Worker // Insert new alloca with new NewSize and Align params.
2333*9880d681SAndroid Build Coastguard Worker AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2334*9880d681SAndroid Build Coastguard Worker NewAlloca->setAlignment(Align);
2335*9880d681SAndroid Build Coastguard Worker
2336*9880d681SAndroid Build Coastguard Worker // NewAddress = Address + Align
2337*9880d681SAndroid Build Coastguard Worker Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2338*9880d681SAndroid Build Coastguard Worker ConstantInt::get(IntptrTy, Align));
2339*9880d681SAndroid Build Coastguard Worker
2340*9880d681SAndroid Build Coastguard Worker // Insert __asan_alloca_poison call for new created alloca.
2341*9880d681SAndroid Build Coastguard Worker IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
2342*9880d681SAndroid Build Coastguard Worker
2343*9880d681SAndroid Build Coastguard Worker // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2344*9880d681SAndroid Build Coastguard Worker // for unpoisoning stuff.
2345*9880d681SAndroid Build Coastguard Worker IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2346*9880d681SAndroid Build Coastguard Worker
2347*9880d681SAndroid Build Coastguard Worker Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2348*9880d681SAndroid Build Coastguard Worker
2349*9880d681SAndroid Build Coastguard Worker // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
2350*9880d681SAndroid Build Coastguard Worker AI->replaceAllUsesWith(NewAddressPtr);
2351*9880d681SAndroid Build Coastguard Worker
2352*9880d681SAndroid Build Coastguard Worker // We are done. Erase old alloca from parent.
2353*9880d681SAndroid Build Coastguard Worker AI->eraseFromParent();
2354*9880d681SAndroid Build Coastguard Worker }
2355*9880d681SAndroid Build Coastguard Worker
2356*9880d681SAndroid Build Coastguard Worker // isSafeAccess returns true if Addr is always inbounds with respect to its
2357*9880d681SAndroid Build Coastguard Worker // base object. For example, it is a field access or an array access with
2358*9880d681SAndroid Build Coastguard Worker // constant inbounds index.
isSafeAccess(ObjectSizeOffsetVisitor & ObjSizeVis,Value * Addr,uint64_t TypeSize) const2359*9880d681SAndroid Build Coastguard Worker bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2360*9880d681SAndroid Build Coastguard Worker Value *Addr, uint64_t TypeSize) const {
2361*9880d681SAndroid Build Coastguard Worker SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2362*9880d681SAndroid Build Coastguard Worker if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
2363*9880d681SAndroid Build Coastguard Worker uint64_t Size = SizeOffset.first.getZExtValue();
2364*9880d681SAndroid Build Coastguard Worker int64_t Offset = SizeOffset.second.getSExtValue();
2365*9880d681SAndroid Build Coastguard Worker // Three checks are required to ensure safety:
2366*9880d681SAndroid Build Coastguard Worker // . Offset >= 0 (since the offset is given from the base ptr)
2367*9880d681SAndroid Build Coastguard Worker // . Size >= Offset (unsigned)
2368*9880d681SAndroid Build Coastguard Worker // . Size - Offset >= NeededSize (unsigned)
2369*9880d681SAndroid Build Coastguard Worker return Offset >= 0 && Size >= uint64_t(Offset) &&
2370*9880d681SAndroid Build Coastguard Worker Size - uint64_t(Offset) >= TypeSize / 8;
2371*9880d681SAndroid Build Coastguard Worker }
2372