1 //===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file is a part of AddressSanitizer, an address sanity checker.
11 // Details of the algorithm:
12 // http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13 //
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Transforms/Instrumentation.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/DepthFirstIterator.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/IR/CallSite.h"
28 #include "llvm/IR/DIBuilder.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/InlineAsm.h"
33 #include "llvm/IR/InstVisitor.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/IR/MDBuilder.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/DataTypes.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/Endian.h"
43 #include "llvm/Support/SwapByteOrder.h"
44 #include "llvm/Transforms/Scalar.h"
45 #include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
46 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
47 #include "llvm/Transforms/Utils/Cloning.h"
48 #include "llvm/Transforms/Utils/Local.h"
49 #include "llvm/Transforms/Utils/ModuleUtils.h"
50 #include <algorithm>
51 #include <string>
52 #include <system_error>
54 using namespace llvm;
56 #define DEBUG_TYPE "asan"
58 static const uint64_t kDefaultShadowScale = 3;
59 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
60 static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
61 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
62 static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
63 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
64 static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
65 static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 36;
66 static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
67 static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
69 static const size_t kMinStackMallocSize = 1 << 6; // 64B
70 static const size_t kMaxStackMallocSize = 1 << 16; // 64K
71 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
72 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
74 static const char *const kAsanModuleCtorName = "asan.module_ctor";
75 static const char *const kAsanModuleDtorName = "asan.module_dtor";
76 static const uint64_t kAsanCtorAndDtorPriority = 1;
77 static const char *const kAsanReportErrorTemplate = "__asan_report_";
78 static const char *const kAsanReportLoadN = "__asan_report_load_n";
79 static const char *const kAsanReportStoreN = "__asan_report_store_n";
80 static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
81 static const char *const kAsanUnregisterGlobalsName =
82 "__asan_unregister_globals";
83 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
84 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
85 static const char *const kAsanInitName = "__asan_init_v4";
86 static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
87 static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
88 static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
89 static const int kMaxAsanStackMallocSizeClass = 10;
90 static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
91 static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
92 static const char *const kAsanGenPrefix = "__asan_gen_";
93 static const char *const kSanCovGenPrefix = "__sancov_gen_";
94 static const char *const kAsanPoisonStackMemoryName =
95 "__asan_poison_stack_memory";
96 static const char *const kAsanUnpoisonStackMemoryName =
97 "__asan_unpoison_stack_memory";
99 static const char *const kAsanOptionDetectUAR =
100 "__asan_option_detect_stack_use_after_return";
102 #ifndef NDEBUG
103 static const int kAsanStackAfterReturnMagic = 0xf5;
104 #endif
106 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
107 static const size_t kNumberOfAccessSizes = 5;
109 static const unsigned kAllocaRzSize = 32;
110 static const unsigned kAsanAllocaLeftMagic = 0xcacacacaU;
111 static const unsigned kAsanAllocaRightMagic = 0xcbcbcbcbU;
112 static const unsigned kAsanAllocaPartialVal1 = 0xcbcbcb00U;
113 static const unsigned kAsanAllocaPartialVal2 = 0x000000cbU;
115 // Command-line flags.
117 // This flag may need to be replaced with -f[no-]asan-reads.
118 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
119 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
120 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
121 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
122 static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
123 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
124 cl::Hidden, cl::init(true));
125 static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
126 cl::desc("use instrumentation with slow path for all accesses"),
127 cl::Hidden, cl::init(false));
128 // This flag limits the number of instructions to be instrumented
129 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
130 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
131 // set it to 10000.
132 static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
133 cl::init(10000),
134 cl::desc("maximal number of instructions to instrument in any given BB"),
135 cl::Hidden);
136 // This flag may need to be replaced with -f[no]asan-stack.
137 static cl::opt<bool> ClStack("asan-stack",
138 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
139 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
140 cl::desc("Check return-after-free"), cl::Hidden, cl::init(true));
141 // This flag may need to be replaced with -f[no]asan-globals.
142 static cl::opt<bool> ClGlobals("asan-globals",
143 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
144 static cl::opt<bool> ClInitializers("asan-initialization-order",
145 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(true));
146 static cl::opt<bool> ClInvalidPointerPairs("asan-detect-invalid-pointer-pair",
147 cl::desc("Instrument <, <=, >, >=, - with pointer operands"),
148 cl::Hidden, cl::init(false));
149 static cl::opt<unsigned> ClRealignStack("asan-realign-stack",
150 cl::desc("Realign stack to the value of this flag (power of two)"),
151 cl::Hidden, cl::init(32));
152 static cl::opt<int> ClInstrumentationWithCallsThreshold(
153 "asan-instrumentation-with-call-threshold",
154 cl::desc("If the function being instrumented contains more than "
155 "this number of memory accesses, use callbacks instead of "
156 "inline checks (-1 means never use callbacks)."),
157 cl::Hidden, cl::init(7000));
158 static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
159 "asan-memory-access-callback-prefix",
160 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
161 cl::init("__asan_"));
162 static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
163 cl::desc("instrument dynamic allocas"), cl::Hidden, cl::init(false));
165 // These flags allow to change the shadow mapping.
166 // The shadow mapping looks like
167 // Shadow = (Mem >> scale) + (1 << offset_log)
168 static cl::opt<int> ClMappingScale("asan-mapping-scale",
169 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
171 // Optimization flags. Not user visible, used mostly for testing
172 // and benchmarking the tool.
173 static cl::opt<bool> ClOpt("asan-opt",
174 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
175 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
176 cl::desc("Instrument the same temp just once"), cl::Hidden,
177 cl::init(true));
178 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
179 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
181 static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
182 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
183 cl::Hidden, cl::init(false));
185 // Debug flags.
186 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
187 cl::init(0));
188 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
189 cl::Hidden, cl::init(0));
190 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
191 cl::Hidden, cl::desc("Debug func"));
192 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
193 cl::Hidden, cl::init(-1));
194 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
195 cl::Hidden, cl::init(-1));
197 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
198 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
199 STATISTIC(NumInstrumentedDynamicAllocas,
200 "Number of instrumented dynamic allocas");
201 STATISTIC(NumOptimizedAccessesToGlobalArray,
202 "Number of optimized accesses to global arrays");
203 STATISTIC(NumOptimizedAccessesToGlobalVar,
204 "Number of optimized accesses to global vars");
206 namespace {
207 /// Frontend-provided metadata for source location.
208 struct LocationMetadata {
209 StringRef Filename;
210 int LineNo;
211 int ColumnNo;
213 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
215 bool empty() const { return Filename.empty(); }
217 void parse(MDNode *MDN) {
218 assert(MDN->getNumOperands() == 3);
219 MDString *MDFilename = cast<MDString>(MDN->getOperand(0));
220 Filename = MDFilename->getString();
221 LineNo = cast<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
222 ColumnNo = cast<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
223 }
224 };
226 /// Frontend-provided metadata for global variables.
227 class GlobalsMetadata {
228 public:
229 struct Entry {
230 Entry()
231 : SourceLoc(), Name(), IsDynInit(false),
232 IsBlacklisted(false) {}
233 LocationMetadata SourceLoc;
234 StringRef Name;
235 bool IsDynInit;
236 bool IsBlacklisted;
237 };
239 GlobalsMetadata() : inited_(false) {}
241 void init(Module& M) {
242 assert(!inited_);
243 inited_ = true;
244 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
245 if (!Globals)
246 return;
247 for (auto MDN : Globals->operands()) {
248 // Metadata node contains the global and the fields of "Entry".
249 assert(MDN->getNumOperands() == 5);
250 Value *V = MDN->getOperand(0);
251 // The optimizer may optimize away a global entirely.
252 if (!V)
253 continue;
254 GlobalVariable *GV = cast<GlobalVariable>(V);
255 // We can already have an entry for GV if it was merged with another
256 // global.
257 Entry &E = Entries[GV];
258 if (Value *Loc = MDN->getOperand(1))
259 E.SourceLoc.parse(cast<MDNode>(Loc));
260 if (Value *Name = MDN->getOperand(2)) {
261 MDString *MDName = cast<MDString>(Name);
262 E.Name = MDName->getString();
263 }
264 ConstantInt *IsDynInit = cast<ConstantInt>(MDN->getOperand(3));
265 E.IsDynInit |= IsDynInit->isOne();
266 ConstantInt *IsBlacklisted = cast<ConstantInt>(MDN->getOperand(4));
267 E.IsBlacklisted |= IsBlacklisted->isOne();
268 }
269 }
271 /// Returns metadata entry for a given global.
272 Entry get(GlobalVariable *G) const {
273 auto Pos = Entries.find(G);
274 return (Pos != Entries.end()) ? Pos->second : Entry();
275 }
277 private:
278 bool inited_;
279 DenseMap<GlobalVariable*, Entry> Entries;
280 };
282 /// This struct defines the shadow mapping using the rule:
283 /// shadow = (mem >> Scale) ADD-or-OR Offset.
284 struct ShadowMapping {
285 int Scale;
286 uint64_t Offset;
287 bool OrShadowOffset;
288 };
290 static ShadowMapping getShadowMapping(const Module &M, int LongSize) {
291 llvm::Triple TargetTriple(M.getTargetTriple());
292 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
293 bool IsIOS = TargetTriple.isiOS();
294 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
295 bool IsLinux = TargetTriple.isOSLinux();
296 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
297 TargetTriple.getArch() == llvm::Triple::ppc64le;
298 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
299 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
300 TargetTriple.getArch() == llvm::Triple::mipsel;
301 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
302 TargetTriple.getArch() == llvm::Triple::mips64el;
304 ShadowMapping Mapping;
306 if (LongSize == 32) {
307 if (IsAndroid)
308 Mapping.Offset = 0;
309 else if (IsMIPS32)
310 Mapping.Offset = kMIPS32_ShadowOffset32;
311 else if (IsFreeBSD)
312 Mapping.Offset = kFreeBSD_ShadowOffset32;
313 else if (IsIOS)
314 Mapping.Offset = kIOSShadowOffset32;
315 else
316 Mapping.Offset = kDefaultShadowOffset32;
317 } else { // LongSize == 64
318 if (IsPPC64)
319 Mapping.Offset = kPPC64_ShadowOffset64;
320 else if (IsFreeBSD)
321 Mapping.Offset = kFreeBSD_ShadowOffset64;
322 else if (IsLinux && IsX86_64)
323 Mapping.Offset = kSmallX86_64ShadowOffset;
324 else if (IsMIPS64)
325 Mapping.Offset = kMIPS64_ShadowOffset64;
326 else
327 Mapping.Offset = kDefaultShadowOffset64;
328 }
330 Mapping.Scale = kDefaultShadowScale;
331 if (ClMappingScale) {
332 Mapping.Scale = ClMappingScale;
333 }
335 // OR-ing shadow offset if more efficient (at least on x86) if the offset
336 // is a power of two, but on ppc64 we have to use add since the shadow
337 // offset is not necessary 1/8-th of the address space.
338 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
340 return Mapping;
341 }
343 static size_t RedzoneSizeForScale(int MappingScale) {
344 // Redzone used for stack and globals is at least 32 bytes.
345 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
346 return std::max(32U, 1U << MappingScale);
347 }
349 /// AddressSanitizer: instrument the code in module to find memory bugs.
350 struct AddressSanitizer : public FunctionPass {
351 AddressSanitizer() : FunctionPass(ID) {}
352 const char *getPassName() const override {
353 return "AddressSanitizerFunctionPass";
354 }
355 void instrumentMop(Instruction *I, bool UseCalls);
356 void instrumentPointerComparisonOrSubtraction(Instruction *I);
357 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
358 Value *Addr, uint32_t TypeSize, bool IsWrite,
359 Value *SizeArgument, bool UseCalls);
360 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
361 Value *ShadowValue, uint32_t TypeSize);
362 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
363 bool IsWrite, size_t AccessSizeIndex,
364 Value *SizeArgument);
365 void instrumentMemIntrinsic(MemIntrinsic *MI);
366 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
367 bool runOnFunction(Function &F) override;
368 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
369 bool doInitialization(Module &M) override;
370 static char ID; // Pass identification, replacement for typeid
372 private:
373 void initializeCallbacks(Module &M);
375 bool LooksLikeCodeInBug11395(Instruction *I);
376 bool GlobalIsLinkerInitialized(GlobalVariable *G);
378 LLVMContext *C;
379 const DataLayout *DL;
380 int LongSize;
381 Type *IntptrTy;
382 ShadowMapping Mapping;
383 Function *AsanCtorFunction;
384 Function *AsanInitFunction;
385 Function *AsanHandleNoReturnFunc;
386 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
387 // This array is indexed by AccessIsWrite and log2(AccessSize).
388 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
389 Function *AsanMemoryAccessCallback[2][kNumberOfAccessSizes];
390 // This array is indexed by AccessIsWrite.
391 Function *AsanErrorCallbackSized[2],
392 *AsanMemoryAccessCallbackSized[2];
393 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
394 InlineAsm *EmptyAsm;
395 GlobalsMetadata GlobalsMD;
397 friend struct FunctionStackPoisoner;
398 };
400 class AddressSanitizerModule : public ModulePass {
401 public:
402 AddressSanitizerModule() : ModulePass(ID) {}
403 bool runOnModule(Module &M) override;
404 static char ID; // Pass identification, replacement for typeid
405 const char *getPassName() const override {
406 return "AddressSanitizerModule";
407 }
409 private:
410 void initializeCallbacks(Module &M);
412 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
413 bool ShouldInstrumentGlobal(GlobalVariable *G);
414 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
415 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
416 size_t MinRedzoneSizeForGlobal() const {
417 return RedzoneSizeForScale(Mapping.Scale);
418 }
420 GlobalsMetadata GlobalsMD;
421 Type *IntptrTy;
422 LLVMContext *C;
423 const DataLayout *DL;
424 ShadowMapping Mapping;
425 Function *AsanPoisonGlobals;
426 Function *AsanUnpoisonGlobals;
427 Function *AsanRegisterGlobals;
428 Function *AsanUnregisterGlobals;
429 };
431 // Stack poisoning does not play well with exception handling.
432 // When an exception is thrown, we essentially bypass the code
433 // that unpoisones the stack. This is why the run-time library has
434 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
435 // stack in the interceptor. This however does not work inside the
436 // actual function which catches the exception. Most likely because the
437 // compiler hoists the load of the shadow value somewhere too high.
438 // This causes asan to report a non-existing bug on 453.povray.
439 // It sounds like an LLVM bug.
440 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
441 Function &F;
442 AddressSanitizer &ASan;
443 DIBuilder DIB;
444 LLVMContext *C;
445 Type *IntptrTy;
446 Type *IntptrPtrTy;
447 ShadowMapping Mapping;
449 SmallVector<AllocaInst*, 16> AllocaVec;
450 SmallVector<Instruction*, 8> RetVec;
451 unsigned StackAlignment;
453 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
454 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
455 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
457 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
458 struct AllocaPoisonCall {
459 IntrinsicInst *InsBefore;
460 AllocaInst *AI;
461 uint64_t Size;
462 bool DoPoison;
463 };
464 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
466 // Stores left and right redzone shadow addresses for dynamic alloca
467 // and pointer to alloca instruction itself.
468 // LeftRzAddr is a shadow address for alloca left redzone.
469 // RightRzAddr is a shadow address for alloca right redzone.
470 struct DynamicAllocaCall {
471 AllocaInst *AI;
472 Value *LeftRzAddr;
473 Value *RightRzAddr;
474 explicit DynamicAllocaCall(AllocaInst *AI,
475 Value *LeftRzAddr = nullptr,
476 Value *RightRzAddr = nullptr)
477 : AI(AI), LeftRzAddr(LeftRzAddr), RightRzAddr(RightRzAddr)
478 {}
479 };
480 SmallVector<DynamicAllocaCall, 1> DynamicAllocaVec;
482 // Maps Value to an AllocaInst from which the Value is originated.
483 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
484 AllocaForValueMapTy AllocaForValue;
486 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
487 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
488 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
489 Mapping(ASan.Mapping),
490 StackAlignment(1 << Mapping.Scale) {}
492 bool runOnFunction() {
493 if (!ClStack) return false;
494 // Collect alloca, ret, lifetime instructions etc.
495 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
496 visit(*BB);
498 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
500 initializeCallbacks(*F.getParent());
502 poisonStack();
504 if (ClDebugStack) {
505 DEBUG(dbgs() << F);
506 }
507 return true;
508 }
510 // Finds all Alloca instructions and puts
511 // poisoned red zones around all of them.
512 // Then unpoison everything back before the function returns.
513 void poisonStack();
515 // ----------------------- Visitors.
516 /// \brief Collect all Ret instructions.
517 void visitReturnInst(ReturnInst &RI) {
518 RetVec.push_back(&RI);
519 }
521 // Unpoison dynamic allocas redzones.
522 void unpoisonDynamicAlloca(DynamicAllocaCall &AllocaCall) {
523 for (auto Ret : RetVec) {
524 IRBuilder<> IRBRet(Ret);
525 PointerType *Int32PtrTy = PointerType::getUnqual(IRBRet.getInt32Ty());
526 Value *Zero = Constant::getNullValue(IRBRet.getInt32Ty());
527 Value *PartialRzAddr = IRBRet.CreateSub(AllocaCall.RightRzAddr,
528 ConstantInt::get(IntptrTy, 4));
529 IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(AllocaCall.LeftRzAddr,
530 Int32PtrTy));
531 IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(PartialRzAddr,
532 Int32PtrTy));
533 IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(AllocaCall.RightRzAddr,
534 Int32PtrTy));
535 }
536 }
538 // Right shift for BigEndian and left shift for LittleEndian.
539 Value *shiftAllocaMagic(Value *Val, IRBuilder<> &IRB, Value *Shift) {
540 return ASan.DL->isLittleEndian() ? IRB.CreateShl(Val, Shift)
541 : IRB.CreateLShr(Val, Shift);
542 }
544 // Compute PartialRzMagic for dynamic alloca call. Since we don't know the
545 // size of requested memory until runtime, we should compute it dynamically.
546 // If PartialSize is 0, PartialRzMagic would contain kAsanAllocaRightMagic,
547 // otherwise it would contain the value that we will use to poison the
548 // partial redzone for alloca call.
549 Value *computePartialRzMagic(Value *PartialSize, IRBuilder<> &IRB);
551 // Deploy and poison redzones around dynamic alloca call. To do this, we
552 // should replace this call with another one with changed parameters and
553 // replace all its uses with new address, so
554 // addr = alloca type, old_size, align
555 // is replaced by
556 // new_size = (old_size + additional_size) * sizeof(type)
557 // tmp = alloca i8, new_size, max(align, 32)
558 // addr = tmp + 32 (first 32 bytes are for the left redzone).
559 // Additional_size is added to make new memory allocation contain not only
560 // requested memory, but also left, partial and right redzones.
561 // After that, we should poison redzones:
562 // (1) Left redzone with kAsanAllocaLeftMagic.
563 // (2) Partial redzone with the value, computed in runtime by
564 // computePartialRzMagic function.
565 // (3) Right redzone with kAsanAllocaRightMagic.
566 void handleDynamicAllocaCall(DynamicAllocaCall &AllocaCall);
568 /// \brief Collect Alloca instructions we want (and can) handle.
569 void visitAllocaInst(AllocaInst &AI) {
570 if (!isInterestingAlloca(AI)) return;
572 StackAlignment = std::max(StackAlignment, AI.getAlignment());
573 if (isDynamicAlloca(AI))
574 DynamicAllocaVec.push_back(DynamicAllocaCall(&AI));
575 else
576 AllocaVec.push_back(&AI);
577 }
579 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
580 /// errors.
581 void visitIntrinsicInst(IntrinsicInst &II) {
582 if (!ClCheckLifetime) return;
583 Intrinsic::ID ID = II.getIntrinsicID();
584 if (ID != Intrinsic::lifetime_start &&
585 ID != Intrinsic::lifetime_end)
586 return;
587 // Found lifetime intrinsic, add ASan instrumentation if necessary.
588 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
589 // If size argument is undefined, don't do anything.
590 if (Size->isMinusOne()) return;
591 // Check that size doesn't saturate uint64_t and can
592 // be stored in IntptrTy.
593 const uint64_t SizeValue = Size->getValue().getLimitedValue();
594 if (SizeValue == ~0ULL ||
595 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
596 return;
597 // Find alloca instruction that corresponds to llvm.lifetime argument.
598 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
599 if (!AI) return;
600 bool DoPoison = (ID == Intrinsic::lifetime_end);
601 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
602 AllocaPoisonCallVec.push_back(APC);
603 }
605 // ---------------------- Helpers.
606 void initializeCallbacks(Module &M);
608 bool isDynamicAlloca(AllocaInst &AI) const {
609 return AI.isArrayAllocation() || !AI.isStaticAlloca();
610 }
612 // Check if we want (and can) handle this alloca.
613 bool isInterestingAlloca(AllocaInst &AI) const {
614 return (AI.getAllocatedType()->isSized() &&
615 // alloca() may be called with 0 size, ignore it.
616 getAllocaSizeInBytes(&AI) > 0);
617 }
619 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
620 Type *Ty = AI->getAllocatedType();
621 uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
622 return SizeInBytes;
623 }
624 /// Finds alloca where the value comes from.
625 AllocaInst *findAllocaForValue(Value *V);
626 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
627 Value *ShadowBase, bool DoPoison);
628 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
630 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
631 int Size);
632 };
634 } // namespace
636 char AddressSanitizer::ID = 0;
637 INITIALIZE_PASS(AddressSanitizer, "asan",
638 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
639 false, false)
640 FunctionPass *llvm::createAddressSanitizerFunctionPass() {
641 return new AddressSanitizer();
642 }
644 char AddressSanitizerModule::ID = 0;
645 INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
646 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
647 "ModulePass", false, false)
648 ModulePass *llvm::createAddressSanitizerModulePass() {
649 return new AddressSanitizerModule();
650 }
652 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
653 size_t Res = countTrailingZeros(TypeSize / 8);
654 assert(Res < kNumberOfAccessSizes);
655 return Res;
656 }
658 // \brief Create a constant for Str so that we can pass it to the run-time lib.
659 static GlobalVariable *createPrivateGlobalForString(
660 Module &M, StringRef Str, bool AllowMerging) {
661 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
662 // We use private linkage for module-local strings. If they can be merged
663 // with another one, we set the unnamed_addr attribute.
664 GlobalVariable *GV =
665 new GlobalVariable(M, StrConst->getType(), true,
666 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
667 if (AllowMerging)
668 GV->setUnnamedAddr(true);
669 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
670 return GV;
671 }
673 /// \brief Create a global describing a source location.
674 static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
675 LocationMetadata MD) {
676 Constant *LocData[] = {
677 createPrivateGlobalForString(M, MD.Filename, true),
678 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
679 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
680 };
681 auto LocStruct = ConstantStruct::getAnon(LocData);
682 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
683 GlobalValue::PrivateLinkage, LocStruct,
684 kAsanGenPrefix);
685 GV->setUnnamedAddr(true);
686 return GV;
687 }
689 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
690 return G->getName().find(kAsanGenPrefix) == 0 ||
691 G->getName().find(kSanCovGenPrefix) == 0;
692 }
694 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
695 // Shadow >> scale
696 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
697 if (Mapping.Offset == 0)
698 return Shadow;
699 // (Shadow >> scale) | offset
700 if (Mapping.OrShadowOffset)
701 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
702 else
703 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
704 }
706 // Instrument memset/memmove/memcpy
707 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
708 IRBuilder<> IRB(MI);
709 if (isa<MemTransferInst>(MI)) {
710 IRB.CreateCall3(
711 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
712 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
713 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
714 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
715 } else if (isa<MemSetInst>(MI)) {
716 IRB.CreateCall3(
717 AsanMemset,
718 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
719 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
720 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
721 }
722 MI->eraseFromParent();
723 }
725 // If I is an interesting memory access, return the PointerOperand
726 // and set IsWrite/Alignment. Otherwise return nullptr.
727 static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
728 unsigned *Alignment) {
729 // Skip memory accesses inserted by another instrumentation.
730 if (I->getMetadata("nosanitize"))
731 return nullptr;
732 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
733 if (!ClInstrumentReads) return nullptr;
734 *IsWrite = false;
735 *Alignment = LI->getAlignment();
736 return LI->getPointerOperand();
737 }
738 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
739 if (!ClInstrumentWrites) return nullptr;
740 *IsWrite = true;
741 *Alignment = SI->getAlignment();
742 return SI->getPointerOperand();
743 }
744 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
745 if (!ClInstrumentAtomics) return nullptr;
746 *IsWrite = true;
747 *Alignment = 0;
748 return RMW->getPointerOperand();
749 }
750 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
751 if (!ClInstrumentAtomics) return nullptr;
752 *IsWrite = true;
753 *Alignment = 0;
754 return XCHG->getPointerOperand();
755 }
756 return nullptr;
757 }
759 static bool isPointerOperand(Value *V) {
760 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
761 }
763 // This is a rough heuristic; it may cause both false positives and
764 // false negatives. The proper implementation requires cooperation with
765 // the frontend.
766 static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
767 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
768 if (!Cmp->isRelational())
769 return false;
770 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
771 if (BO->getOpcode() != Instruction::Sub)
772 return false;
773 } else {
774 return false;
775 }
776 if (!isPointerOperand(I->getOperand(0)) ||
777 !isPointerOperand(I->getOperand(1)))
778 return false;
779 return true;
780 }
782 bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
783 // If a global variable does not have dynamic initialization we don't
784 // have to instrument it. However, if a global does not have initializer
785 // at all, we assume it has dynamic initializer (in other TU).
786 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
787 }
789 void
790 AddressSanitizer::instrumentPointerComparisonOrSubtraction(Instruction *I) {
791 IRBuilder<> IRB(I);
792 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
793 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
794 for (int i = 0; i < 2; i++) {
795 if (Param[i]->getType()->isPointerTy())
796 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
797 }
798 IRB.CreateCall2(F, Param[0], Param[1]);
799 }
801 void AddressSanitizer::instrumentMop(Instruction *I, bool UseCalls) {
802 bool IsWrite = false;
803 unsigned Alignment = 0;
804 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &Alignment);
805 assert(Addr);
806 if (ClOpt && ClOptGlobals) {
807 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
808 // If initialization order checking is disabled, a simple access to a
809 // dynamically initialized global is always valid.
810 if (!ClInitializers || GlobalIsLinkerInitialized(G)) {
811 NumOptimizedAccessesToGlobalVar++;
812 return;
813 }
814 }
815 ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
816 if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
817 if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
818 if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
819 NumOptimizedAccessesToGlobalArray++;
820 return;
821 }
822 }
823 }
824 }
826 Type *OrigPtrTy = Addr->getType();
827 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
829 assert(OrigTy->isSized());
830 uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
832 assert((TypeSize % 8) == 0);
834 if (IsWrite)
835 NumInstrumentedWrites++;
836 else
837 NumInstrumentedReads++;
839 unsigned Granularity = 1 << Mapping.Scale;
840 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
841 // if the data is properly aligned.
842 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
843 TypeSize == 128) &&
844 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
845 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls);
846 // Instrument unusual size or unusual alignment.
847 // We can not do it with a single check, so we do 1-byte check for the first
848 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
849 // to report the actual access size.
850 IRBuilder<> IRB(I);
851 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
852 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
853 if (UseCalls) {
854 IRB.CreateCall2(AsanMemoryAccessCallbackSized[IsWrite], AddrLong, Size);
855 } else {
856 Value *LastByte = IRB.CreateIntToPtr(
857 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
858 OrigPtrTy);
859 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false);
860 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false);
861 }
862 }
864 // Validate the result of Module::getOrInsertFunction called for an interface
865 // function of AddressSanitizer. If the instrumented module defines a function
866 // with the same name, their prototypes must match, otherwise
867 // getOrInsertFunction returns a bitcast.
868 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
869 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
870 FuncOrBitcast->dump();
871 report_fatal_error("trying to redefine an AddressSanitizer "
872 "interface function");
873 }
875 Instruction *AddressSanitizer::generateCrashCode(
876 Instruction *InsertBefore, Value *Addr,
877 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
878 IRBuilder<> IRB(InsertBefore);
879 CallInst *Call = SizeArgument
880 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
881 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
883 // We don't do Call->setDoesNotReturn() because the BB already has
884 // UnreachableInst at the end.
885 // This EmptyAsm is required to avoid callback merge.
886 IRB.CreateCall(EmptyAsm);
887 return Call;
888 }
890 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
891 Value *ShadowValue,
892 uint32_t TypeSize) {
893 size_t Granularity = 1 << Mapping.Scale;
894 // Addr & (Granularity - 1)
895 Value *LastAccessedByte = IRB.CreateAnd(
896 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
897 // (Addr & (Granularity - 1)) + size - 1
898 if (TypeSize / 8 > 1)
899 LastAccessedByte = IRB.CreateAdd(
900 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
901 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
902 LastAccessedByte = IRB.CreateIntCast(
903 LastAccessedByte, ShadowValue->getType(), false);
904 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
905 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
906 }
908 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
909 Instruction *InsertBefore, Value *Addr,
910 uint32_t TypeSize, bool IsWrite,
911 Value *SizeArgument, bool UseCalls) {
912 IRBuilder<> IRB(InsertBefore);
913 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
914 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
916 if (UseCalls) {
917 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][AccessSizeIndex],
918 AddrLong);
919 return;
920 }
922 Type *ShadowTy = IntegerType::get(
923 *C, std::max(8U, TypeSize >> Mapping.Scale));
924 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
925 Value *ShadowPtr = memToShadow(AddrLong, IRB);
926 Value *CmpVal = Constant::getNullValue(ShadowTy);
927 Value *ShadowValue = IRB.CreateLoad(
928 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
930 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
931 size_t Granularity = 1 << Mapping.Scale;
932 TerminatorInst *CrashTerm = nullptr;
934 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
935 // We use branch weights for the slow path check, to indicate that the slow
936 // path is rarely taken. This seems to be the case for SPEC benchmarks.
937 TerminatorInst *CheckTerm =
938 SplitBlockAndInsertIfThen(Cmp, InsertBefore, false,
939 MDBuilder(*C).createBranchWeights(1, 100000));
940 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
941 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
942 IRB.SetInsertPoint(CheckTerm);
943 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
944 BasicBlock *CrashBlock =
945 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
946 CrashTerm = new UnreachableInst(*C, CrashBlock);
947 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
948 ReplaceInstWithInst(CheckTerm, NewTerm);
949 } else {
950 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
951 }
953 Instruction *Crash = generateCrashCode(
954 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
955 Crash->setDebugLoc(OrigIns->getDebugLoc());
956 }
958 void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
959 GlobalValue *ModuleName) {
960 // Set up the arguments to our poison/unpoison functions.
961 IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
963 // Add a call to poison all external globals before the given function starts.
964 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
965 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
967 // Add calls to unpoison all globals before each return instruction.
968 for (auto &BB : GlobalInit.getBasicBlockList())
969 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
970 CallInst::Create(AsanUnpoisonGlobals, "", RI);
971 }
973 void AddressSanitizerModule::createInitializerPoisonCalls(
974 Module &M, GlobalValue *ModuleName) {
975 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
977 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
978 for (Use &OP : CA->operands()) {
979 if (isa<ConstantAggregateZero>(OP))
980 continue;
981 ConstantStruct *CS = cast<ConstantStruct>(OP);
983 // Must have a function or null ptr.
984 if (Function* F = dyn_cast<Function>(CS->getOperand(1))) {
985 if (F->getName() == kAsanModuleCtorName) continue;
986 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
987 // Don't instrument CTORs that will run before asan.module_ctor.
988 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
989 poisonOneInitializer(*F, ModuleName);
990 }
991 }
992 }
994 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
995 Type *Ty = cast<PointerType>(G->getType())->getElementType();
996 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
998 if (GlobalsMD.get(G).IsBlacklisted) return false;
999 if (!Ty->isSized()) return false;
1000 if (!G->hasInitializer()) return false;
1001 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
1002 // Touch only those globals that will not be defined in other modules.
1003 // Don't handle ODR linkage types and COMDATs since other modules may be built
1004 // without ASan.
1005 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1006 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1007 G->getLinkage() != GlobalVariable::InternalLinkage)
1008 return false;
1009 if (G->hasComdat())
1010 return false;
1011 // Two problems with thread-locals:
1012 // - The address of the main thread's copy can't be computed at link-time.
1013 // - Need to poison all copies, not just the main thread's one.
1014 if (G->isThreadLocal())
1015 return false;
1016 // For now, just ignore this Global if the alignment is large.
1017 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
1019 if (G->hasSection()) {
1020 StringRef Section(G->getSection());
1021 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1022 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1023 // them.
1024 if (Section.startswith("__OBJC,") ||
1025 Section.startswith("__DATA, __objc_")) {
1026 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1027 return false;
1028 }
1029 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1030 // Constant CFString instances are compiled in the following way:
1031 // -- the string buffer is emitted into
1032 // __TEXT,__cstring,cstring_literals
1033 // -- the constant NSConstantString structure referencing that buffer
1034 // is placed into __DATA,__cfstring
1035 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1036 // Moreover, it causes the linker to crash on OS X 10.7
1037 if (Section.startswith("__DATA,__cfstring")) {
1038 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1039 return false;
1040 }
1041 // The linker merges the contents of cstring_literals and removes the
1042 // trailing zeroes.
1043 if (Section.startswith("__TEXT,__cstring,cstring_literals")) {
1044 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1045 return false;
1046 }
1047 if (Section.startswith("__TEXT,__objc_methname,cstring_literals")) {
1048 DEBUG(dbgs() << "Ignoring objc_methname cstring global: " << *G << "\n");
1049 return false;
1050 }
1053 // Callbacks put into the CRT initializer/terminator sections
1054 // should not be instrumented.
1055 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1056 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1057 if (Section.startswith(".CRT")) {
1058 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1059 return false;
1060 }
1062 // Globals from llvm.metadata aren't emitted, do not instrument them.
1063 if (Section == "llvm.metadata") return false;
1064 }
1066 return true;
1067 }
1069 void AddressSanitizerModule::initializeCallbacks(Module &M) {
1070 IRBuilder<> IRB(*C);
1071 // Declare our poisoning and unpoisoning functions.
1072 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1073 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
1074 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1075 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1076 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
1077 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1078 // Declare functions that register/unregister globals.
1079 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1080 kAsanRegisterGlobalsName, IRB.getVoidTy(),
1081 IntptrTy, IntptrTy, nullptr));
1082 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1083 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1084 kAsanUnregisterGlobalsName,
1085 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1086 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1087 }
1089 // This function replaces all global variables with new variables that have
1090 // trailing redzones. It also creates a function that poisons
1091 // redzones and inserts this function into llvm.global_ctors.
1092 bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
1093 GlobalsMD.init(M);
1095 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1097 for (auto &G : M.globals()) {
1098 if (ShouldInstrumentGlobal(&G))
1099 GlobalsToChange.push_back(&G);
1100 }
1102 size_t n = GlobalsToChange.size();
1103 if (n == 0) return false;
1105 // A global is described by a structure
1106 // size_t beg;
1107 // size_t size;
1108 // size_t size_with_redzone;
1109 // const char *name;
1110 // const char *module_name;
1111 // size_t has_dynamic_init;
1112 // void *source_location;
1113 // We initialize an array of such structures and pass it to a run-time call.
1114 StructType *GlobalStructTy =
1115 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
1116 IntptrTy, IntptrTy, nullptr);
1117 SmallVector<Constant *, 16> Initializers(n);
1119 bool HasDynamicallyInitializedGlobals = false;
1121 // We shouldn't merge same module names, as this string serves as unique
1122 // module ID in runtime.
1123 GlobalVariable *ModuleName = createPrivateGlobalForString(
1124 M, M.getModuleIdentifier(), /*AllowMerging*/false);
1126 for (size_t i = 0; i < n; i++) {
1127 static const uint64_t kMaxGlobalRedzone = 1 << 18;
1128 GlobalVariable *G = GlobalsToChange[i];
1130 auto MD = GlobalsMD.get(G);
1131 // Create string holding the global name (use global name from metadata
1132 // if it's available, otherwise just write the name of global variable).
1133 GlobalVariable *Name = createPrivateGlobalForString(
1134 M, MD.Name.empty() ? G->getName() : MD.Name,
1135 /*AllowMerging*/ true);
1137 PointerType *PtrTy = cast<PointerType>(G->getType());
1138 Type *Ty = PtrTy->getElementType();
1139 uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
1140 uint64_t MinRZ = MinRedzoneSizeForGlobal();
1141 // MinRZ <= RZ <= kMaxGlobalRedzone
1142 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
1143 uint64_t RZ = std::max(MinRZ,
1144 std::min(kMaxGlobalRedzone,
1145 (SizeInBytes / MinRZ / 4) * MinRZ));
1146 uint64_t RightRedzoneSize = RZ;
1147 // Round up to MinRZ
1148 if (SizeInBytes % MinRZ)
1149 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1150 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
1151 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1153 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
1154 Constant *NewInitializer = ConstantStruct::get(
1155 NewTy, G->getInitializer(),
1156 Constant::getNullValue(RightRedZoneTy), nullptr);
1158 // Create a new global variable with enough space for a redzone.
1159 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1160 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1161 Linkage = GlobalValue::InternalLinkage;
1162 GlobalVariable *NewGlobal = new GlobalVariable(
1163 M, NewTy, G->isConstant(), Linkage,
1164 NewInitializer, "", G, G->getThreadLocalMode());
1165 NewGlobal->copyAttributesFrom(G);
1166 NewGlobal->setAlignment(MinRZ);
1168 Value *Indices2[2];
1169 Indices2[0] = IRB.getInt32(0);
1170 Indices2[1] = IRB.getInt32(0);
1172 G->replaceAllUsesWith(
1173 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
1174 NewGlobal->takeName(G);
1175 G->eraseFromParent();
1177 Constant *SourceLoc;
1178 if (!MD.SourceLoc.empty()) {
1179 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1180 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1181 } else {
1182 SourceLoc = ConstantInt::get(IntptrTy, 0);
1183 }
1185 Initializers[i] = ConstantStruct::get(
1186 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
1187 ConstantInt::get(IntptrTy, SizeInBytes),
1188 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1189 ConstantExpr::getPointerCast(Name, IntptrTy),
1190 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
1191 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
1193 if (ClInitializers && MD.IsDynInit)
1194 HasDynamicallyInitializedGlobals = true;
1196 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
1197 }
1199 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1200 GlobalVariable *AllGlobals = new GlobalVariable(
1201 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1202 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1204 // Create calls for poisoning before initializers run and unpoisoning after.
1205 if (HasDynamicallyInitializedGlobals)
1206 createInitializerPoisonCalls(M, ModuleName);
1207 IRB.CreateCall2(AsanRegisterGlobals,
1208 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1209 ConstantInt::get(IntptrTy, n));
1211 // We also need to unregister globals at the end, e.g. when a shared library
1212 // gets closed.
1213 Function *AsanDtorFunction = Function::Create(
1214 FunctionType::get(Type::getVoidTy(*C), false),
1215 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1216 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1217 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
1218 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1219 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1220 ConstantInt::get(IntptrTy, n));
1221 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
1223 DEBUG(dbgs() << M);
1224 return true;
1225 }
1227 bool AddressSanitizerModule::runOnModule(Module &M) {
1228 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1229 if (!DLP)
1230 return false;
1231 DL = &DLP->getDataLayout();
1232 C = &(M.getContext());
1233 int LongSize = DL->getPointerSizeInBits();
1234 IntptrTy = Type::getIntNTy(*C, LongSize);
1235 Mapping = getShadowMapping(M, LongSize);
1236 initializeCallbacks(M);
1238 bool Changed = false;
1240 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1241 assert(CtorFunc);
1242 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1244 if (ClGlobals)
1245 Changed |= InstrumentGlobals(IRB, M);
1247 return Changed;
1248 }
1250 void AddressSanitizer::initializeCallbacks(Module &M) {
1251 IRBuilder<> IRB(*C);
1252 // Create __asan_report* callbacks.
1253 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1254 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1255 AccessSizeIndex++) {
1256 // IsWrite and TypeSize are encoded in the function name.
1257 std::string Suffix =
1258 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
1259 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1260 checkInterfaceFunction(
1261 M.getOrInsertFunction(kAsanReportErrorTemplate + Suffix,
1262 IRB.getVoidTy(), IntptrTy, nullptr));
1263 AsanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
1264 checkInterfaceFunction(
1265 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + Suffix,
1266 IRB.getVoidTy(), IntptrTy, nullptr));
1267 }
1268 }
1269 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1270 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1271 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1272 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1274 AsanMemoryAccessCallbackSized[0] = checkInterfaceFunction(
1275 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "loadN",
1276 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1277 AsanMemoryAccessCallbackSized[1] = checkInterfaceFunction(
1278 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "storeN",
1279 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1281 AsanMemmove = checkInterfaceFunction(M.getOrInsertFunction(
1282 ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
1283 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1284 AsanMemcpy = checkInterfaceFunction(M.getOrInsertFunction(
1285 ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
1286 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1287 AsanMemset = checkInterfaceFunction(M.getOrInsertFunction(
1288 ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
1289 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
1291 AsanHandleNoReturnFunc = checkInterfaceFunction(
1292 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
1294 AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
1295 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1296 AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
1297 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1298 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1299 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1300 StringRef(""), StringRef(""),
1301 /*hasSideEffects=*/true);
1302 }
1304 // virtual
1305 bool AddressSanitizer::doInitialization(Module &M) {
1306 // Initialize the private fields. No one has accessed them before.
1307 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1308 if (!DLP)
1309 report_fatal_error("data layout missing");
1310 DL = &DLP->getDataLayout();
1312 GlobalsMD.init(M);
1314 C = &(M.getContext());
1315 LongSize = DL->getPointerSizeInBits();
1316 IntptrTy = Type::getIntNTy(*C, LongSize);
1318 AsanCtorFunction = Function::Create(
1319 FunctionType::get(Type::getVoidTy(*C), false),
1320 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1321 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1322 // call __asan_init in the module ctor.
1323 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1324 AsanInitFunction = checkInterfaceFunction(
1325 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), nullptr));
1326 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1327 IRB.CreateCall(AsanInitFunction);
1329 Mapping = getShadowMapping(M, LongSize);
1331 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1332 return true;
1333 }
1335 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1336 // For each NSObject descendant having a +load method, this method is invoked
1337 // by the ObjC runtime before any of the static constructors is called.
1338 // Therefore we need to instrument such methods with a call to __asan_init
1339 // at the beginning in order to initialize our runtime before any access to
1340 // the shadow memory.
1341 // We cannot just ignore these methods, because they may call other
1342 // instrumented functions.
1343 if (F.getName().find(" load]") != std::string::npos) {
1344 IRBuilder<> IRB(F.begin()->begin());
1345 IRB.CreateCall(AsanInitFunction);
1346 return true;
1347 }
1348 return false;
1349 }
1351 bool AddressSanitizer::runOnFunction(Function &F) {
1352 if (&F == AsanCtorFunction) return false;
1353 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1354 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1355 initializeCallbacks(*F.getParent());
1357 // If needed, insert __asan_init before checking for SanitizeAddress attr.
1358 maybeInsertAsanInitAtFunctionEntry(F);
1360 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
1361 return false;
1363 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1364 return false;
1366 // We want to instrument every address only once per basic block (unless there
1367 // are calls between uses).
1368 SmallSet<Value*, 16> TempsToInstrument;
1369 SmallVector<Instruction*, 16> ToInstrument;
1370 SmallVector<Instruction*, 8> NoReturnCalls;
1371 SmallVector<BasicBlock*, 16> AllBlocks;
1372 SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
1373 int NumAllocas = 0;
1374 bool IsWrite;
1375 unsigned Alignment;
1377 // Fill the set of memory operations to instrument.
1378 for (auto &BB : F) {
1379 AllBlocks.push_back(&BB);
1380 TempsToInstrument.clear();
1381 int NumInsnsPerBB = 0;
1382 for (auto &Inst : BB) {
1383 if (LooksLikeCodeInBug11395(&Inst)) return false;
1384 if (Value *Addr =
1385 isInterestingMemoryAccess(&Inst, &IsWrite, &Alignment)) {
1386 if (ClOpt && ClOptSameTemp) {
1387 if (!TempsToInstrument.insert(Addr).second)
1388 continue; // We've seen this temp in the current BB.
1389 }
1390 } else if (ClInvalidPointerPairs &&
1391 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1392 PointerComparisonsOrSubtracts.push_back(&Inst);
1393 continue;
1394 } else if (isa<MemIntrinsic>(Inst)) {
1395 // ok, take it.
1396 } else {
1397 if (isa<AllocaInst>(Inst))
1398 NumAllocas++;
1399 CallSite CS(&Inst);
1400 if (CS) {
1401 // A call inside BB.
1402 TempsToInstrument.clear();
1403 if (CS.doesNotReturn())
1404 NoReturnCalls.push_back(CS.getInstruction());
1405 }
1406 continue;
1407 }
1408 ToInstrument.push_back(&Inst);
1409 NumInsnsPerBB++;
1410 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1411 break;
1412 }
1413 }
1415 bool UseCalls = false;
1416 if (ClInstrumentationWithCallsThreshold >= 0 &&
1417 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1418 UseCalls = true;
1420 // Instrument.
1421 int NumInstrumented = 0;
1422 for (auto Inst : ToInstrument) {
1423 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1424 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1425 if (isInterestingMemoryAccess(Inst, &IsWrite, &Alignment))
1426 instrumentMop(Inst, UseCalls);
1427 else
1428 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1429 }
1430 NumInstrumented++;
1431 }
1433 FunctionStackPoisoner FSP(F, *this);
1434 bool ChangedStack = FSP.runOnFunction();
1436 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1437 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1438 for (auto CI : NoReturnCalls) {
1439 IRBuilder<> IRB(CI);
1440 IRB.CreateCall(AsanHandleNoReturnFunc);
1441 }
1443 for (auto Inst : PointerComparisonsOrSubtracts) {
1444 instrumentPointerComparisonOrSubtraction(Inst);
1445 NumInstrumented++;
1446 }
1448 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1450 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1452 return res;
1453 }
1455 // Workaround for bug 11395: we don't want to instrument stack in functions
1456 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1457 // FIXME: remove once the bug 11395 is fixed.
1458 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1459 if (LongSize != 32) return false;
1460 CallInst *CI = dyn_cast<CallInst>(I);
1461 if (!CI || !CI->isInlineAsm()) return false;
1462 if (CI->getNumArgOperands() <= 5) return false;
1463 // We have inline assembly with quite a few arguments.
1464 return true;
1465 }
1467 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1468 IRBuilder<> IRB(*C);
1469 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1470 std::string Suffix = itostr(i);
1471 AsanStackMallocFunc[i] = checkInterfaceFunction(
1472 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1473 IntptrTy, IntptrTy, nullptr));
1474 AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1475 kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1476 IntptrTy, IntptrTy, nullptr));
1477 }
1478 AsanPoisonStackMemoryFunc = checkInterfaceFunction(
1479 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1480 IntptrTy, IntptrTy, nullptr));
1481 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(
1482 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1483 IntptrTy, IntptrTy, nullptr));
1484 }
1486 void
1487 FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1488 IRBuilder<> &IRB, Value *ShadowBase,
1489 bool DoPoison) {
1490 size_t n = ShadowBytes.size();
1491 size_t i = 0;
1492 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1493 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1494 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1495 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1496 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1497 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1498 uint64_t Val = 0;
1499 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
1500 if (ASan.DL->isLittleEndian())
1501 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1502 else
1503 Val = (Val << 8) | ShadowBytes[i + j];
1504 }
1505 if (!Val) continue;
1506 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1507 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1508 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1509 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
1510 }
1511 }
1512 }
1514 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
1515 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1516 static int StackMallocSizeClass(uint64_t LocalStackSize) {
1517 assert(LocalStackSize <= kMaxStackMallocSize);
1518 uint64_t MaxSize = kMinStackMallocSize;
1519 for (int i = 0; ; i++, MaxSize *= 2)
1520 if (LocalStackSize <= MaxSize)
1521 return i;
1522 llvm_unreachable("impossible LocalStackSize");
1523 }
1525 // Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1526 // We can not use MemSet intrinsic because it may end up calling the actual
1527 // memset. Size is a multiple of 8.
1528 // Currently this generates 8-byte stores on x86_64; it may be better to
1529 // generate wider stores.
1530 void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1531 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1532 assert(!(Size % 8));
1533 assert(kAsanStackAfterReturnMagic == 0xf5);
1534 for (int i = 0; i < Size; i += 8) {
1535 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1536 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1537 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1538 }
1539 }
1541 static DebugLoc getFunctionEntryDebugLocation(Function &F) {
1542 for (const auto &Inst : F.getEntryBlock())
1543 if (!isa<AllocaInst>(Inst))
1544 return Inst.getDebugLoc();
1545 return DebugLoc();
1546 }
1548 void FunctionStackPoisoner::poisonStack() {
1549 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1551 if (ClInstrumentAllocas)
1552 // Handle dynamic allocas.
1553 for (auto &AllocaCall : DynamicAllocaVec)
1554 handleDynamicAllocaCall(AllocaCall);
1556 if (AllocaVec.size() == 0) return;
1558 int StackMallocIdx = -1;
1559 DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
1561 Instruction *InsBefore = AllocaVec[0];
1562 IRBuilder<> IRB(InsBefore);
1563 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1565 SmallVector<ASanStackVariableDescription, 16> SVD;
1566 SVD.reserve(AllocaVec.size());
1567 for (AllocaInst *AI : AllocaVec) {
1568 ASanStackVariableDescription D = { AI->getName().data(),
1569 getAllocaSizeInBytes(AI),
1570 AI->getAlignment(), AI, 0};
1571 SVD.push_back(D);
1572 }
1573 // Minimal header size (left redzone) is 4 pointers,
1574 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1575 size_t MinHeaderSize = ASan.LongSize / 2;
1576 ASanStackFrameLayout L;
1577 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1578 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1579 uint64_t LocalStackSize = L.FrameSize;
1580 bool DoStackMalloc =
1581 ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
1583 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1584 AllocaInst *MyAlloca =
1585 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1586 MyAlloca->setDebugLoc(EntryDebugLocation);
1587 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1588 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1589 MyAlloca->setAlignment(FrameAlignment);
1590 assert(MyAlloca->isStaticAlloca());
1591 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1592 Value *LocalStackBase = OrigStackBase;
1594 if (DoStackMalloc) {
1595 // LocalStackBase = OrigStackBase
1596 // if (__asan_option_detect_stack_use_after_return)
1597 // LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
1598 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1599 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1600 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1601 kAsanOptionDetectUAR, IRB.getInt32Ty());
1602 Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1603 Constant::getNullValue(IRB.getInt32Ty()));
1604 Instruction *Term = SplitBlockAndInsertIfThen(Cmp, InsBefore, false);
1605 BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1606 IRBuilder<> IRBIf(Term);
1607 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1608 LocalStackBase = IRBIf.CreateCall2(
1609 AsanStackMallocFunc[StackMallocIdx],
1610 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1611 BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1612 IRB.SetInsertPoint(InsBefore);
1613 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1614 PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1615 Phi->addIncoming(OrigStackBase, CmpBlock);
1616 Phi->addIncoming(LocalStackBase, SetBlock);
1617 LocalStackBase = Phi;
1618 }
1620 // Insert poison calls for lifetime intrinsics for alloca.
1621 bool HavePoisonedAllocas = false;
1622 for (const auto &APC : AllocaPoisonCallVec) {
1623 assert(APC.InsBefore);
1624 assert(APC.AI);
1625 IRBuilder<> IRB(APC.InsBefore);
1626 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1627 HavePoisonedAllocas |= APC.DoPoison;
1628 }
1630 // Replace Alloca instructions with base+offset.
1631 for (const auto &Desc : SVD) {
1632 AllocaInst *AI = Desc.AI;
1633 Value *NewAllocaPtr = IRB.CreateIntToPtr(
1634 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
1635 AI->getType());
1636 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
1637 AI->replaceAllUsesWith(NewAllocaPtr);
1638 }
1640 // The left-most redzone has enough space for at least 4 pointers.
1641 // Write the Magic value to redzone[0].
1642 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1643 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1644 BasePlus0);
1645 // Write the frame description constant to redzone[1].
1646 Value *BasePlus1 = IRB.CreateIntToPtr(
1647 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1648 IntptrPtrTy);
1649 GlobalVariable *StackDescriptionGlobal =
1650 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1651 /*AllowMerging*/true);
1652 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1653 IntptrTy);
1654 IRB.CreateStore(Description, BasePlus1);
1655 // Write the PC to redzone[2].
1656 Value *BasePlus2 = IRB.CreateIntToPtr(
1657 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1658 2 * ASan.LongSize/8)),
1659 IntptrPtrTy);
1660 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1662 // Poison the stack redzones at the entry.
1663 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1664 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
1666 // (Un)poison the stack before all ret instructions.
1667 for (auto Ret : RetVec) {
1668 IRBuilder<> IRBRet(Ret);
1669 // Mark the current frame as retired.
1670 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1671 BasePlus0);
1672 if (DoStackMalloc) {
1673 assert(StackMallocIdx >= 0);
1674 // if LocalStackBase != OrigStackBase:
1675 // // In use-after-return mode, poison the whole stack frame.
1676 // if StackMallocIdx <= 4
1677 // // For small sizes inline the whole thing:
1678 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1679 // **SavedFlagPtr(LocalStackBase) = 0
1680 // else
1681 // __asan_stack_free_N(LocalStackBase, OrigStackBase)
1682 // else
1683 // <This is not a fake stack; unpoison the redzones>
1684 Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1685 TerminatorInst *ThenTerm, *ElseTerm;
1686 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1688 IRBuilder<> IRBPoison(ThenTerm);
1689 if (StackMallocIdx <= 4) {
1690 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1691 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1692 ClassSize >> Mapping.Scale);
1693 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1694 LocalStackBase,
1695 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1696 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1697 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1698 IRBPoison.CreateStore(
1699 Constant::getNullValue(IRBPoison.getInt8Ty()),
1700 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1701 } else {
1702 // For larger frames call __asan_stack_free_*.
1703 IRBPoison.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1704 ConstantInt::get(IntptrTy, LocalStackSize),
1705 OrigStackBase);
1706 }
1708 IRBuilder<> IRBElse(ElseTerm);
1709 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
1710 } else if (HavePoisonedAllocas) {
1711 // If we poisoned some allocas in llvm.lifetime analysis,
1712 // unpoison whole stack frame now.
1713 assert(LocalStackBase == OrigStackBase);
1714 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1715 } else {
1716 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
1717 }
1718 }
1720 if (ClInstrumentAllocas)
1721 // Unpoison dynamic allocas.
1722 for (auto &AllocaCall : DynamicAllocaVec)
1723 unpoisonDynamicAlloca(AllocaCall);
1725 // We are done. Remove the old unused alloca instructions.
1726 for (auto AI : AllocaVec)
1727 AI->eraseFromParent();
1728 }
1730 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1731 IRBuilder<> &IRB, bool DoPoison) {
1732 // For now just insert the call to ASan runtime.
1733 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1734 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1735 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1736 : AsanUnpoisonStackMemoryFunc,
1737 AddrArg, SizeArg);
1738 }
1740 // Handling llvm.lifetime intrinsics for a given %alloca:
1741 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1742 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1743 // invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1744 // could be poisoned by previous llvm.lifetime.end instruction, as the
1745 // variable may go in and out of scope several times, e.g. in loops).
1746 // (3) if we poisoned at least one %alloca in a function,
1747 // unpoison the whole stack frame at function exit.
1749 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1750 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1751 // We're intested only in allocas we can handle.
1752 return isInterestingAlloca(*AI) ? AI : nullptr;
1753 // See if we've already calculated (or started to calculate) alloca for a
1754 // given value.
1755 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1756 if (I != AllocaForValue.end())
1757 return I->second;
1758 // Store 0 while we're calculating alloca for value V to avoid
1759 // infinite recursion if the value references itself.
1760 AllocaForValue[V] = nullptr;
1761 AllocaInst *Res = nullptr;
1762 if (CastInst *CI = dyn_cast<CastInst>(V))
1763 Res = findAllocaForValue(CI->getOperand(0));
1764 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1765 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1766 Value *IncValue = PN->getIncomingValue(i);
1767 // Allow self-referencing phi-nodes.
1768 if (IncValue == PN) continue;
1769 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1770 // AI for incoming values should exist and should all be equal.
1771 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1772 return nullptr;
1773 Res = IncValueAI;
1774 }
1775 }
1776 if (Res)
1777 AllocaForValue[V] = Res;
1778 return Res;
1779 }
1781 // Compute PartialRzMagic for dynamic alloca call. PartialRzMagic is
1782 // constructed from two separate 32-bit numbers: PartialRzMagic = Val1 | Val2.
1783 // (1) Val1 is resposible for forming base value for PartialRzMagic, containing
1784 // only 00 for fully addressable and 0xcb for fully poisoned bytes for each
1785 // 8-byte chunk of user memory respectively.
1786 // (2) Val2 forms the value for marking first poisoned byte in shadow memory
1787 // with appropriate value (0x01 - 0x07 or 0xcb if Padding % 8 == 0).
1789 // Shift = Padding & ~7; // the number of bits we need to shift to access first
1790 // chunk in shadow memory, containing nonzero bytes.
1791 // Example:
1792 // Padding = 21 Padding = 16
1793 // Shadow: |00|00|05|cb| Shadow: |00|00|cb|cb|
1794 // ^ ^
1795 // | |
1796 // Shift = 21 & ~7 = 16 Shift = 16 & ~7 = 16
1797 //
1798 // Val1 = 0xcbcbcbcb << Shift;
1799 // PartialBits = Padding ? Padding & 7 : 0xcb;
1800 // Val2 = PartialBits << Shift;
1801 // Result = Val1 | Val2;
1802 Value *FunctionStackPoisoner::computePartialRzMagic(Value *PartialSize,
1803 IRBuilder<> &IRB) {
1804 PartialSize = IRB.CreateIntCast(PartialSize, IRB.getInt32Ty(), false);
1805 Value *Shift = IRB.CreateAnd(PartialSize, IRB.getInt32(~7));
1806 unsigned Val1Int = kAsanAllocaPartialVal1;
1807 unsigned Val2Int = kAsanAllocaPartialVal2;
1808 if (!ASan.DL->isLittleEndian()) {
1809 Val1Int = sys::getSwappedBytes(Val1Int);
1810 Val2Int = sys::getSwappedBytes(Val2Int);
1811 }
1812 Value *Val1 = shiftAllocaMagic(IRB.getInt32(Val1Int), IRB, Shift);
1813 Value *PartialBits = IRB.CreateAnd(PartialSize, IRB.getInt32(7));
1814 // For BigEndian get 0x000000YZ -> 0xYZ000000.
1815 if (ASan.DL->isBigEndian())
1816 PartialBits = IRB.CreateShl(PartialBits, IRB.getInt32(24));
1817 Value *Val2 = IRB.getInt32(Val2Int);
1818 Value *Cond =
1819 IRB.CreateICmpNE(PartialBits, Constant::getNullValue(IRB.getInt32Ty()));
1820 Val2 = IRB.CreateSelect(Cond, shiftAllocaMagic(PartialBits, IRB, Shift),
1821 shiftAllocaMagic(Val2, IRB, Shift));
1822 return IRB.CreateOr(Val1, Val2);
1823 }
1825 void FunctionStackPoisoner::handleDynamicAllocaCall(
1826 DynamicAllocaCall &AllocaCall) {
1827 AllocaInst *AI = AllocaCall.AI;
1828 IRBuilder<> IRB(AI);
1830 PointerType *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
1831 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
1832 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
1834 Value *Zero = Constant::getNullValue(IntptrTy);
1835 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
1836 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
1837 Value *NotAllocaRzMask = ConstantInt::get(IntptrTy, ~AllocaRedzoneMask);
1839 // Since we need to extend alloca with additional memory to locate
1840 // redzones, and OldSize is number of allocated blocks with
1841 // ElementSize size, get allocated memory size in bytes by
1842 // OldSize * ElementSize.
1843 unsigned ElementSize = ASan.DL->getTypeAllocSize(AI->getAllocatedType());
1844 Value *OldSize = IRB.CreateMul(AI->getArraySize(),
1845 ConstantInt::get(IntptrTy, ElementSize));
1847 // PartialSize = OldSize % 32
1848 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
1850 // Misalign = kAllocaRzSize - PartialSize;
1851 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
1853 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
1854 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
1855 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
1857 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
1858 // Align is added to locate left redzone, PartialPadding for possible
1859 // partial redzone and kAllocaRzSize for right redzone respectively.
1860 Value *AdditionalChunkSize = IRB.CreateAdd(
1861 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
1863 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
1865 // Insert new alloca with new NewSize and Align params.
1866 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
1867 NewAlloca->setAlignment(Align);
1869 // NewAddress = Address + Align
1870 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
1871 ConstantInt::get(IntptrTy, Align));
1873 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
1875 // LeftRzAddress = NewAddress - kAllocaRzSize
1876 Value *LeftRzAddress = IRB.CreateSub(NewAddress, AllocaRzSize);
1878 // Poisoning left redzone.
1879 AllocaCall.LeftRzAddr = ASan.memToShadow(LeftRzAddress, IRB);
1880 IRB.CreateStore(ConstantInt::get(IRB.getInt32Ty(), kAsanAllocaLeftMagic),
1881 IRB.CreateIntToPtr(AllocaCall.LeftRzAddr, Int32PtrTy));
1883 // PartialRzAligned = PartialRzAddr & ~AllocaRzMask
1884 Value *PartialRzAddr = IRB.CreateAdd(NewAddress, OldSize);
1885 Value *PartialRzAligned = IRB.CreateAnd(PartialRzAddr, NotAllocaRzMask);
1887 // Poisoning partial redzone.
1888 Value *PartialRzMagic = computePartialRzMagic(PartialSize, IRB);
1889 Value *PartialRzShadowAddr = ASan.memToShadow(PartialRzAligned, IRB);
1890 IRB.CreateStore(PartialRzMagic,
1891 IRB.CreateIntToPtr(PartialRzShadowAddr, Int32PtrTy));
1893 // RightRzAddress
1894 // = (PartialRzAddr + AllocaRzMask) & ~AllocaRzMask
1895 Value *RightRzAddress = IRB.CreateAnd(
1896 IRB.CreateAdd(PartialRzAddr, AllocaRzMask), NotAllocaRzMask);
1898 // Poisoning right redzone.
1899 AllocaCall.RightRzAddr = ASan.memToShadow(RightRzAddress, IRB);
1900 IRB.CreateStore(ConstantInt::get(IRB.getInt32Ty(), kAsanAllocaRightMagic),
1901 IRB.CreateIntToPtr(AllocaCall.RightRzAddr, Int32PtrTy));
1903 // Replace all uses of AddessReturnedByAlloca with NewAddress.
1904 AI->replaceAllUsesWith(NewAddressPtr);
1906 // We are done. Erase old alloca and store left, partial and right redzones
1907 // shadow addresses for future unpoisoning.
1908 AI->eraseFromParent();
1909 NumInstrumentedDynamicAllocas++;
1910 }