blob: 4950d838b294c7326155734ada3dd779961de43b [file] [log] [blame]
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001//===-- 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//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "asan"
17
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000019#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov1c8b8252012-12-27 08:50:58 +000020#include "llvm/ADT/DenseMap.h"
Alexey Samsonov59cca132012-12-25 12:04:36 +000021#include "llvm/ADT/DepthFirstIterator.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000022#include "llvm/ADT/OwningPtr.h"
23#include "llvm/ADT/SmallSet.h"
24#include "llvm/ADT/SmallString.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000027#include "llvm/ADT/Triple.h"
Alexey Samsonov1afbb512012-12-12 14:31:53 +000028#include "llvm/DIBuilder.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000029#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/IntrinsicInst.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/Module.h"
36#include "llvm/IR/Type.h"
Alexey Samsonov59cca132012-12-25 12:04:36 +000037#include "llvm/InstVisitor.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000038#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/DataTypes.h"
40#include "llvm/Support/Debug.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000041#include "llvm/Support/raw_ostream.h"
42#include "llvm/Support/system_error.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000043#include "llvm/Target/TargetMachine.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000044#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chandler Carruth90230c82013-01-19 08:03:47 +000045#include "llvm/Transforms/Utils/BlackList.h"
Alexey Samsonov1afbb512012-12-12 14:31:53 +000046#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000047#include "llvm/Transforms/Utils/ModuleUtils.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000048#include <algorithm>
Chandler Carruthd04a8d42012-12-03 16:50:05 +000049#include <string>
Kostya Serebryany800e03f2011-11-16 01:35:23 +000050
51using namespace llvm;
52
53static const uint64_t kDefaultShadowScale = 3;
54static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
55static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Kostya Serebryany117de482013-02-11 14:36:01 +000056static const uint64_t kDefaultShort64bitShadowOffset = 0x7FFF8000; // < 2G.
Kostya Serebryany48a615f2013-01-23 12:54:55 +000057static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000058
59static const size_t kMaxStackMallocSize = 1 << 16; // 64K
60static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
61static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
62
63static const char *kAsanModuleCtorName = "asan.module_ctor";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000064static const char *kAsanModuleDtorName = "asan.module_dtor";
65static const int kAsanCtorAndCtorPriority = 1;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000066static const char *kAsanReportErrorTemplate = "__asan_report_";
67static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000068static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +000069static const char *kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
70static const char *kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kostya Serebryany0bc55d52013-02-12 11:11:02 +000071static const char *kAsanInitName = "__asan_init_v1";
Kostya Serebryany95e3cf42012-02-08 21:36:17 +000072static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000073static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
74static const char *kAsanMappingScaleName = "__asan_mapping_scale";
75static const char *kAsanStackMallocName = "__asan_stack_malloc";
76static const char *kAsanStackFreeName = "__asan_stack_free";
Kostya Serebryany51c7c652012-11-20 14:16:08 +000077static const char *kAsanGenPrefix = "__asan_gen_";
Alexey Samsonovf985f442012-12-04 01:34:23 +000078static const char *kAsanPoisonStackMemoryName = "__asan_poison_stack_memory";
79static const char *kAsanUnpoisonStackMemoryName =
80 "__asan_unpoison_stack_memory";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000081
82static const int kAsanStackLeftRedzoneMagic = 0xf1;
83static const int kAsanStackMidRedzoneMagic = 0xf2;
84static const int kAsanStackRightRedzoneMagic = 0xf3;
85static const int kAsanStackPartialRedzoneMagic = 0xf4;
86
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000087// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
88static const size_t kNumberOfAccessSizes = 5;
89
Kostya Serebryany800e03f2011-11-16 01:35:23 +000090// Command-line flags.
91
92// This flag may need to be replaced with -f[no-]asan-reads.
93static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
94 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
95static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
96 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +000097static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
98 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
99 cl::Hidden, cl::init(true));
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000100static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
101 cl::desc("use instrumentation with slow path for all accesses"),
102 cl::Hidden, cl::init(false));
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000103// This flag limits the number of instructions to be instrumented
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000104// in any given BB. Normally, this should be set to unlimited (INT_MAX),
105// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
106// set it to 10000.
107static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
108 cl::init(10000),
109 cl::desc("maximal number of instructions to instrument in any given BB"),
110 cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000111// This flag may need to be replaced with -f[no]asan-stack.
112static cl::opt<bool> ClStack("asan-stack",
113 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
114// This flag may need to be replaced with -f[no]asan-use-after-return.
115static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
116 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
117// This flag may need to be replaced with -f[no]asan-globals.
118static cl::opt<bool> ClGlobals("asan-globals",
119 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000120static cl::opt<bool> ClInitializers("asan-initialization-order",
121 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000122static cl::opt<bool> ClMemIntrin("asan-memintrin",
123 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
Kostya Serebryany6c554122012-12-04 06:14:01 +0000124static cl::opt<bool> ClRealignStack("asan-realign-stack",
125 cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true));
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000126static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
127 cl::desc("File containing the list of objects to ignore "
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000128 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000129
130// These flags allow to change the shadow mapping.
131// The shadow mapping looks like
132// Shadow = (Mem >> scale) + (1 << offset_log)
133static cl::opt<int> ClMappingScale("asan-mapping-scale",
134 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
135static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
136 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
Kostya Serebryany117de482013-02-11 14:36:01 +0000137static cl::opt<bool> ClShort64BitOffset("asan-short-64bit-mapping-offset",
138 cl::desc("Use short immediate constant as the mapping offset for 64bit"),
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000139 cl::Hidden, cl::init(true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000140
141// Optimization flags. Not user visible, used mostly for testing
142// and benchmarking the tool.
143static cl::opt<bool> ClOpt("asan-opt",
144 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
145static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
146 cl::desc("Instrument the same temp just once"), cl::Hidden,
147 cl::init(true));
148static cl::opt<bool> ClOptGlobals("asan-opt-globals",
149 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
150
Alexey Samsonovee548272012-11-29 18:14:24 +0000151static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
152 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
153 cl::Hidden, cl::init(false));
154
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000155// Debug flags.
156static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
157 cl::init(0));
158static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
159 cl::Hidden, cl::init(0));
160static cl::opt<std::string> ClDebugFunc("asan-debug-func",
161 cl::Hidden, cl::desc("Debug func"));
162static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
163 cl::Hidden, cl::init(-1));
164static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
165 cl::Hidden, cl::init(-1));
166
167namespace {
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000168/// A set of dynamically initialized globals extracted from metadata.
169class SetOfDynamicallyInitializedGlobals {
170 public:
171 void Init(Module& M) {
172 // Clang generates metadata identifying all dynamically initialized globals.
173 NamedMDNode *DynamicGlobals =
174 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
175 if (!DynamicGlobals)
176 return;
177 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
178 MDNode *MDN = DynamicGlobals->getOperand(i);
179 assert(MDN->getNumOperands() == 1);
180 Value *VG = MDN->getOperand(0);
181 // The optimizer may optimize away a global entirely, in which case we
182 // cannot instrument access to it.
183 if (!VG)
184 continue;
185 DynInitGlobals.insert(cast<GlobalVariable>(VG));
186 }
187 }
188 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
189 private:
190 SmallSet<GlobalValue*, 32> DynInitGlobals;
191};
192
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000193/// This struct defines the shadow mapping using the rule:
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000194/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000195struct ShadowMapping {
196 int Scale;
197 uint64_t Offset;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000198 bool OrShadowOffset;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000199};
200
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000201static ShadowMapping getShadowMapping(const Module &M, int LongSize,
202 bool ZeroBaseShadow) {
203 llvm::Triple TargetTriple(M.getTargetTriple());
204 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Alexander Potapenkoc8a196a2013-02-12 12:41:12 +0000205 bool IsMacOSX = TargetTriple.getOS() == llvm::Triple::MacOSX;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000206 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64;
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000207 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000208
209 ShadowMapping Mapping;
210
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000211 // OR-ing shadow offset if more efficient (at least on x86),
212 // but on ppc64 we have to use add since the shadow offset is not neccesary
213 // 1/8-th of the address space.
Kostya Serebryany117de482013-02-11 14:36:01 +0000214 Mapping.OrShadowOffset = !IsPPC64 && !ClShort64BitOffset;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000215
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000216 Mapping.Offset = (IsAndroid || ZeroBaseShadow) ? 0 :
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000217 (LongSize == 32 ? kDefaultShadowOffset32 :
218 IsPPC64 ? kPPC64_ShadowOffset64 : kDefaultShadowOffset64);
Alexander Potapenkoc8a196a2013-02-12 12:41:12 +0000219 if (!ZeroBaseShadow && ClShort64BitOffset && IsX86_64 && !IsMacOSX) {
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000220 assert(LongSize == 64);
Kostya Serebryany117de482013-02-11 14:36:01 +0000221 Mapping.Offset = kDefaultShort64bitShadowOffset;
222 } if (!ZeroBaseShadow && ClMappingOffsetLog >= 0) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000223 // Zero offset log is the special case.
224 Mapping.Offset = (ClMappingOffsetLog == 0) ? 0 : 1ULL << ClMappingOffsetLog;
225 }
226
227 Mapping.Scale = kDefaultShadowScale;
228 if (ClMappingScale) {
229 Mapping.Scale = ClMappingScale;
230 }
231
232 return Mapping;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000233}
234
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000235static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000236 // Redzone used for stack and globals is at least 32 bytes.
237 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000238 return std::max(32U, 1U << MappingScale);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000239}
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000240
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000241/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000242struct AddressSanitizer : public FunctionPass {
Alexey Samsonovee548272012-11-29 18:14:24 +0000243 AddressSanitizer(bool CheckInitOrder = false,
244 bool CheckUseAfterReturn = false,
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000245 bool CheckLifetime = false,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000246 StringRef BlacklistFile = StringRef(),
247 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000248 : FunctionPass(ID),
249 CheckInitOrder(CheckInitOrder || ClInitializers),
250 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000251 CheckLifetime(CheckLifetime || ClCheckLifetime),
252 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000253 : BlacklistFile),
254 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000255 virtual const char *getPassName() const {
256 return "AddressSanitizerFunctionPass";
257 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000258 void instrumentMop(Instruction *I);
259 void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000260 Value *Addr, uint32_t TypeSize, bool IsWrite);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000261 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
262 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000263 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000264 bool IsWrite, size_t AccessSizeIndex);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000265 bool instrumentMemIntrinsic(MemIntrinsic *MI);
266 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000267 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000268 Instruction *InsertBefore, bool IsWrite);
269 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000270 bool runOnFunction(Function &F);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000271 void createInitializerPoisonCalls(Module &M,
272 Value *FirstAddr, Value *LastAddr);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000273 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000274 void emitShadowMapping(Module &M, IRBuilder<> &IRB) const;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000275 virtual bool doInitialization(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000276 static char ID; // Pass identification, replacement for typeid
277
278 private:
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000279 void initializeCallbacks(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000280
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000281 bool ShouldInstrumentGlobal(GlobalVariable *G);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000282 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000283 void FindDynamicInitializers(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000284
Alexey Samsonovee548272012-11-29 18:14:24 +0000285 bool CheckInitOrder;
286 bool CheckUseAfterReturn;
287 bool CheckLifetime;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000288 SmallString<64> BlacklistFile;
289 bool ZeroBaseShadow;
290
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000291 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +0000292 DataLayout *TD;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000293 int LongSize;
294 Type *IntptrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000295 ShadowMapping Mapping;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000296 Function *AsanCtorFunction;
297 Function *AsanInitFunction;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000298 Function *AsanHandleNoReturnFunc;
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +0000299 OwningPtr<BlackList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000300 // This array is indexed by AccessIsWrite and log2(AccessSize).
301 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000302 InlineAsm *EmptyAsm;
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000303 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000304
305 friend struct FunctionStackPoisoner;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000306};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000307
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000308class AddressSanitizerModule : public ModulePass {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000309 public:
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000310 AddressSanitizerModule(bool CheckInitOrder = false,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000311 StringRef BlacklistFile = StringRef(),
312 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000313 : ModulePass(ID),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000314 CheckInitOrder(CheckInitOrder || ClInitializers),
315 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000316 : BlacklistFile),
317 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000318 bool runOnModule(Module &M);
319 static char ID; // Pass identification, replacement for typeid
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000320 virtual const char *getPassName() const {
321 return "AddressSanitizerModule";
322 }
Alexey Samsonovf985f442012-12-04 01:34:23 +0000323
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000324 private:
Alexey Samsonov46848582012-12-25 12:28:20 +0000325 void initializeCallbacks(Module &M);
326
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000327 bool ShouldInstrumentGlobal(GlobalVariable *G);
328 void createInitializerPoisonCalls(Module &M, Value *FirstAddr,
329 Value *LastAddr);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000330 size_t RedzoneSize() const {
331 return RedzoneSizeForScale(Mapping.Scale);
332 }
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000333
Alexey Samsonovee548272012-11-29 18:14:24 +0000334 bool CheckInitOrder;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000335 SmallString<64> BlacklistFile;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000336 bool ZeroBaseShadow;
337
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000338 OwningPtr<BlackList> BL;
339 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
340 Type *IntptrTy;
341 LLVMContext *C;
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000342 DataLayout *TD;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000343 ShadowMapping Mapping;
Alexey Samsonov46848582012-12-25 12:28:20 +0000344 Function *AsanPoisonGlobals;
345 Function *AsanUnpoisonGlobals;
346 Function *AsanRegisterGlobals;
347 Function *AsanUnregisterGlobals;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000348};
349
Alexey Samsonov59cca132012-12-25 12:04:36 +0000350// Stack poisoning does not play well with exception handling.
351// When an exception is thrown, we essentially bypass the code
352// that unpoisones the stack. This is why the run-time library has
353// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
354// stack in the interceptor. This however does not work inside the
355// actual function which catches the exception. Most likely because the
356// compiler hoists the load of the shadow value somewhere too high.
357// This causes asan to report a non-existing bug on 453.povray.
358// It sounds like an LLVM bug.
359struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
360 Function &F;
361 AddressSanitizer &ASan;
362 DIBuilder DIB;
363 LLVMContext *C;
364 Type *IntptrTy;
365 Type *IntptrPtrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000366 ShadowMapping Mapping;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000367
368 SmallVector<AllocaInst*, 16> AllocaVec;
369 SmallVector<Instruction*, 8> RetVec;
370 uint64_t TotalStackSize;
371 unsigned StackAlignment;
372
373 Function *AsanStackMallocFunc, *AsanStackFreeFunc;
374 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
375
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000376 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
377 struct AllocaPoisonCall {
378 IntrinsicInst *InsBefore;
379 uint64_t Size;
380 bool DoPoison;
381 };
382 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
383
384 // Maps Value to an AllocaInst from which the Value is originated.
385 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
386 AllocaForValueMapTy AllocaForValue;
387
Alexey Samsonov59cca132012-12-25 12:04:36 +0000388 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
389 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
390 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000391 Mapping(ASan.Mapping),
392 TotalStackSize(0), StackAlignment(1 << Mapping.Scale) {}
Alexey Samsonov59cca132012-12-25 12:04:36 +0000393
394 bool runOnFunction() {
395 if (!ClStack) return false;
396 // Collect alloca, ret, lifetime instructions etc.
397 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
398 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
399 BasicBlock *BB = *DI;
400 visit(*BB);
401 }
402 if (AllocaVec.empty()) return false;
403
404 initializeCallbacks(*F.getParent());
405
406 poisonStack();
407
408 if (ClDebugStack) {
409 DEBUG(dbgs() << F);
410 }
411 return true;
412 }
413
414 // Finds all static Alloca instructions and puts
415 // poisoned red zones around all of them.
416 // Then unpoison everything back before the function returns.
417 void poisonStack();
418
419 // ----------------------- Visitors.
420 /// \brief Collect all Ret instructions.
421 void visitReturnInst(ReturnInst &RI) {
422 RetVec.push_back(&RI);
423 }
424
425 /// \brief Collect Alloca instructions we want (and can) handle.
426 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000427 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000428
429 StackAlignment = std::max(StackAlignment, AI.getAlignment());
430 AllocaVec.push_back(&AI);
431 uint64_t AlignedSize = getAlignedAllocaSize(&AI);
432 TotalStackSize += AlignedSize;
433 }
434
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000435 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
436 /// errors.
437 void visitIntrinsicInst(IntrinsicInst &II) {
438 if (!ASan.CheckLifetime) return;
439 Intrinsic::ID ID = II.getIntrinsicID();
440 if (ID != Intrinsic::lifetime_start &&
441 ID != Intrinsic::lifetime_end)
442 return;
443 // Found lifetime intrinsic, add ASan instrumentation if necessary.
444 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
445 // If size argument is undefined, don't do anything.
446 if (Size->isMinusOne()) return;
447 // Check that size doesn't saturate uint64_t and can
448 // be stored in IntptrTy.
449 const uint64_t SizeValue = Size->getValue().getLimitedValue();
450 if (SizeValue == ~0ULL ||
451 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
452 return;
453 // Find alloca instruction that corresponds to llvm.lifetime argument.
454 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
455 if (!AI) return;
456 bool DoPoison = (ID == Intrinsic::lifetime_end);
457 AllocaPoisonCall APC = {&II, SizeValue, DoPoison};
458 AllocaPoisonCallVec.push_back(APC);
459 }
460
Alexey Samsonov59cca132012-12-25 12:04:36 +0000461 // ---------------------- Helpers.
462 void initializeCallbacks(Module &M);
463
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000464 // Check if we want (and can) handle this alloca.
465 bool isInterestingAlloca(AllocaInst &AI) {
466 return (!AI.isArrayAllocation() &&
467 AI.isStaticAlloca() &&
468 AI.getAllocatedType()->isSized());
469 }
470
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000471 size_t RedzoneSize() const {
472 return RedzoneSizeForScale(Mapping.Scale);
473 }
Alexey Samsonov59cca132012-12-25 12:04:36 +0000474 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
475 Type *Ty = AI->getAllocatedType();
476 uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty);
477 return SizeInBytes;
478 }
479 uint64_t getAlignedSize(uint64_t SizeInBytes) {
480 size_t RZ = RedzoneSize();
481 return ((SizeInBytes + RZ - 1) / RZ) * RZ;
482 }
483 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
484 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
485 return getAlignedSize(SizeInBytes);
486 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000487 /// Finds alloca where the value comes from.
488 AllocaInst *findAllocaForValue(Value *V);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000489 void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
490 Value *ShadowBase, bool DoPoison);
491 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> IRB, bool DoPoison);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000492};
493
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000494} // namespace
495
496char AddressSanitizer::ID = 0;
497INITIALIZE_PASS(AddressSanitizer, "asan",
498 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
499 false, false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000500FunctionPass *llvm::createAddressSanitizerFunctionPass(
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000501 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000502 StringRef BlacklistFile, bool ZeroBaseShadow) {
Alexey Samsonovee548272012-11-29 18:14:24 +0000503 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000504 CheckLifetime, BlacklistFile, ZeroBaseShadow);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000505}
506
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000507char AddressSanitizerModule::ID = 0;
508INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
509 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
510 "ModulePass", false, false)
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000511ModulePass *llvm::createAddressSanitizerModulePass(
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000512 bool CheckInitOrder, StringRef BlacklistFile, bool ZeroBaseShadow) {
513 return new AddressSanitizerModule(CheckInitOrder, BlacklistFile,
514 ZeroBaseShadow);
Alexander Potapenko25878042012-01-23 11:22:43 +0000515}
516
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000517static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
518 size_t Res = CountTrailingZeros_32(TypeSize / 8);
519 assert(Res < kNumberOfAccessSizes);
520 return Res;
521}
522
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000523// Create a constant for Str so that we can pass it to the run-time lib.
524static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000525 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000526 return new GlobalVariable(M, StrConst->getType(), true,
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000527 GlobalValue::PrivateLinkage, StrConst,
528 kAsanGenPrefix);
529}
530
531static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
532 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000533}
534
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000535Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
536 // Shadow >> scale
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000537 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
538 if (Mapping.Offset == 0)
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000539 return Shadow;
540 // (Shadow >> scale) | offset
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000541 if (Mapping.OrShadowOffset)
542 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
543 else
544 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000545}
546
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000547void AddressSanitizer::instrumentMemIntrinsicParam(
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000548 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000549 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
550 // Check the first byte.
551 {
552 IRBuilder<> IRB(InsertBefore);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000553 instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000554 }
555 // Check the last byte.
556 {
557 IRBuilder<> IRB(InsertBefore);
558 Value *SizeMinusOne = IRB.CreateSub(
559 Size, ConstantInt::get(Size->getType(), 1));
560 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
561 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
562 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000563 instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000564 }
565}
566
567// Instrument memset/memmove/memcpy
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000568bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000569 Value *Dst = MI->getDest();
570 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000571 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000572 Value *Length = MI->getLength();
573
574 Constant *ConstLength = dyn_cast<Constant>(Length);
575 Instruction *InsertBefore = MI;
576 if (ConstLength) {
577 if (ConstLength->isNullValue()) return false;
578 } else {
579 // The size is not a constant so it could be zero -- check at run-time.
580 IRBuilder<> IRB(InsertBefore);
581
582 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000583 Constant::getNullValue(Length->getType()));
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000584 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000585 }
586
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000587 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000588 if (Src)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000589 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000590 return true;
591}
592
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000593// If I is an interesting memory access, return the PointerOperand
594// and set IsWrite. Otherwise return NULL.
595static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000596 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000597 if (!ClInstrumentReads) return NULL;
598 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000599 return LI->getPointerOperand();
600 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000601 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
602 if (!ClInstrumentWrites) return NULL;
603 *IsWrite = true;
604 return SI->getPointerOperand();
605 }
606 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
607 if (!ClInstrumentAtomics) return NULL;
608 *IsWrite = true;
609 return RMW->getPointerOperand();
610 }
611 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
612 if (!ClInstrumentAtomics) return NULL;
613 *IsWrite = true;
614 return XCHG->getPointerOperand();
615 }
616 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000617}
618
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000619void AddressSanitizer::instrumentMop(Instruction *I) {
Axel Naumann3780ad82012-09-17 14:20:57 +0000620 bool IsWrite = false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000621 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
622 assert(Addr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000623 if (ClOpt && ClOptGlobals) {
624 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
625 // If initialization order checking is disabled, a simple access to a
626 // dynamically initialized global is always valid.
Alexey Samsonovee548272012-11-29 18:14:24 +0000627 if (!CheckInitOrder)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000628 return;
629 // If a global variable does not have dynamic initialization we don't
Kostya Serebryany40779062012-11-20 13:11:32 +0000630 // have to instrument it. However, if a global does not have initailizer
631 // at all, we assume it has dynamic initializer (in other TU).
632 if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000633 return;
634 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000635 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000636
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000637 Type *OrigPtrTy = Addr->getType();
638 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
639
640 assert(OrigTy->isSized());
641 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
642
643 if (TypeSize != 8 && TypeSize != 16 &&
644 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
645 // Ignore all unusual sizes.
646 return;
647 }
648
649 IRBuilder<> IRB(I);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000650 instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000651}
652
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000653// Validate the result of Module::getOrInsertFunction called for an interface
654// function of AddressSanitizer. If the instrumented module defines a function
655// with the same name, their prototypes must match, otherwise
656// getOrInsertFunction returns a bitcast.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000657static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000658 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
659 FuncOrBitcast->dump();
660 report_fatal_error("trying to redefine an AddressSanitizer "
661 "interface function");
662}
663
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000664Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000665 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000666 bool IsWrite, size_t AccessSizeIndex) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000667 IRBuilder<> IRB(InsertBefore);
668 CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
669 Addr);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000670 // We don't do Call->setDoesNotReturn() because the BB already has
671 // UnreachableInst at the end.
672 // This EmptyAsm is required to avoid callback merge.
673 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000674 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000675}
676
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000677Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000678 Value *ShadowValue,
679 uint32_t TypeSize) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000680 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000681 // Addr & (Granularity - 1)
682 Value *LastAccessedByte = IRB.CreateAnd(
683 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
684 // (Addr & (Granularity - 1)) + size - 1
685 if (TypeSize / 8 > 1)
686 LastAccessedByte = IRB.CreateAdd(
687 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
688 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
689 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000690 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000691 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
692 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
693}
694
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000695void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000696 IRBuilder<> &IRB, Value *Addr,
697 uint32_t TypeSize, bool IsWrite) {
698 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
699
700 Type *ShadowTy = IntegerType::get(
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000701 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000702 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
703 Value *ShadowPtr = memToShadow(AddrLong, IRB);
704 Value *CmpVal = Constant::getNullValue(ShadowTy);
705 Value *ShadowValue = IRB.CreateLoad(
706 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
707
708 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000709 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000710 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000711 TerminatorInst *CrashTerm = 0;
712
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000713 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000714 TerminatorInst *CheckTerm =
715 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000716 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000717 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000718 IRB.SetInsertPoint(CheckTerm);
719 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000720 BasicBlock *CrashBlock =
721 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000722 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000723 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
724 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000725 } else {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000726 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000727 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000728
729 Instruction *Crash =
730 generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex);
731 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000732}
733
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000734void AddressSanitizerModule::createInitializerPoisonCalls(
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000735 Module &M, Value *FirstAddr, Value *LastAddr) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000736 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
737 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
738 // If that function is not present, this TU contains no globals, or they have
739 // all been optimized away
740 if (!GlobalInit)
741 return;
742
743 // Set up the arguments to our poison/unpoison functions.
744 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
745
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000746 // Add a call to poison all external globals before the given function starts.
747 IRB.CreateCall2(AsanPoisonGlobals, FirstAddr, LastAddr);
748
749 // Add calls to unpoison all globals before each return instruction.
750 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
751 I != E; ++I) {
752 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
753 CallInst::Create(AsanUnpoisonGlobals, "", RI);
754 }
755 }
756}
757
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000758bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000759 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000760 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000761
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000762 if (BL->isIn(*G)) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000763 if (!Ty->isSized()) return false;
764 if (!G->hasInitializer()) return false;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000765 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000766 // Touch only those globals that will not be defined in other modules.
767 // Don't handle ODR type linkages since other modules may be built w/o asan.
768 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
769 G->getLinkage() != GlobalVariable::PrivateLinkage &&
770 G->getLinkage() != GlobalVariable::InternalLinkage)
771 return false;
772 // Two problems with thread-locals:
773 // - The address of the main thread's copy can't be computed at link-time.
774 // - Need to poison all copies, not just the main thread's one.
775 if (G->isThreadLocal())
776 return false;
777 // For now, just ignore this Alloca if the alignment is large.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000778 if (G->getAlignment() > RedzoneSize()) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000779
780 // Ignore all the globals with the names starting with "\01L_OBJC_".
781 // Many of those are put into the .cstring section. The linker compresses
782 // that section by removing the spare \0s after the string terminator, so
783 // our redzones get broken.
784 if ((G->getName().find("\01L_OBJC_") == 0) ||
785 (G->getName().find("\01l_OBJC_") == 0)) {
786 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
787 return false;
788 }
789
790 if (G->hasSection()) {
791 StringRef Section(G->getSection());
792 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
793 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
794 // them.
795 if ((Section.find("__OBJC,") == 0) ||
796 (Section.find("__DATA, __objc_") == 0)) {
797 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
798 return false;
799 }
800 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
801 // Constant CFString instances are compiled in the following way:
802 // -- the string buffer is emitted into
803 // __TEXT,__cstring,cstring_literals
804 // -- the constant NSConstantString structure referencing that buffer
805 // is placed into __DATA,__cfstring
806 // Therefore there's no point in placing redzones into __DATA,__cfstring.
807 // Moreover, it causes the linker to crash on OS X 10.7
808 if (Section.find("__DATA,__cfstring") == 0) {
809 DEBUG(dbgs() << "Ignoring CFString: " << *G);
810 return false;
811 }
812 }
813
814 return true;
815}
816
Alexey Samsonov46848582012-12-25 12:28:20 +0000817void AddressSanitizerModule::initializeCallbacks(Module &M) {
818 IRBuilder<> IRB(*C);
819 // Declare our poisoning and unpoisoning functions.
820 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
821 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
822 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
823 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
824 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
825 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
826 // Declare functions that register/unregister globals.
827 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
828 kAsanRegisterGlobalsName, IRB.getVoidTy(),
829 IntptrTy, IntptrTy, NULL));
830 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
831 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
832 kAsanUnregisterGlobalsName,
833 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
834 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
835}
836
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000837// This function replaces all global variables with new variables that have
838// trailing redzones. It also creates a function that poisons
839// redzones and inserts this function into llvm.global_ctors.
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000840bool AddressSanitizerModule::runOnModule(Module &M) {
841 if (!ClGlobals) return false;
842 TD = getAnalysisIfAvailable<DataLayout>();
843 if (!TD)
844 return false;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000845 BL.reset(new BlackList(BlacklistFile));
Alexey Samsonovd6f62c82012-11-29 18:27:01 +0000846 if (BL->isIn(M)) return false;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000847 C = &(M.getContext());
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000848 int LongSize = TD->getPointerSizeInBits();
849 IntptrTy = Type::getIntNTy(*C, LongSize);
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000850 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov46848582012-12-25 12:28:20 +0000851 initializeCallbacks(M);
852 DynamicallyInitializedGlobals.Init(M);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000853
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000854 SmallVector<GlobalVariable *, 16> GlobalsToChange;
855
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000856 for (Module::GlobalListType::iterator G = M.global_begin(),
857 E = M.global_end(); G != E; ++G) {
858 if (ShouldInstrumentGlobal(G))
859 GlobalsToChange.push_back(G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000860 }
861
862 size_t n = GlobalsToChange.size();
863 if (n == 0) return false;
864
865 // A global is described by a structure
866 // size_t beg;
867 // size_t size;
868 // size_t size_with_redzone;
869 // const char *name;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000870 // size_t has_dynamic_init;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000871 // We initialize an array of such structures and pass it to a run-time call.
872 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000873 IntptrTy, IntptrTy,
874 IntptrTy, NULL);
875 SmallVector<Constant *, 16> Initializers(n), DynamicInit;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000876
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000877
878 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
879 assert(CtorFunc);
880 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000881
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000882 // The addresses of the first and last dynamically initialized globals in
883 // this TU. Used in initialization order checking.
884 Value *FirstDynamic = 0, *LastDynamic = 0;
885
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000886 for (size_t i = 0; i < n; i++) {
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000887 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000888 GlobalVariable *G = GlobalsToChange[i];
889 PointerType *PtrTy = cast<PointerType>(G->getType());
890 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000891 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000892 uint64_t MinRZ = RedzoneSize();
Kostya Serebryany63f08462013-01-24 10:35:40 +0000893 // MinRZ <= RZ <= kMaxGlobalRedzone
894 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000895 uint64_t RZ = std::max(MinRZ,
Kostya Serebryany63f08462013-01-24 10:35:40 +0000896 std::min(kMaxGlobalRedzone,
897 (SizeInBytes / MinRZ / 4) * MinRZ));
898 uint64_t RightRedzoneSize = RZ;
899 // Round up to MinRZ
900 if (SizeInBytes % MinRZ)
901 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
902 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000903 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000904 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000905 bool GlobalHasDynamicInitializer =
906 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000907 // Don't check initialization order if this global is blacklisted.
Kostya Serebryany7dadac62012-09-05 09:00:18 +0000908 GlobalHasDynamicInitializer &= !BL->isInInit(*G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000909
910 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
911 Constant *NewInitializer = ConstantStruct::get(
912 NewTy, G->getInitializer(),
913 Constant::getNullValue(RightRedZoneTy), NULL);
914
Kostya Serebryanya4b2b1d2011-12-15 22:55:55 +0000915 SmallString<2048> DescriptionOfGlobal = G->getName();
916 DescriptionOfGlobal += " (";
917 DescriptionOfGlobal += M.getModuleIdentifier();
918 DescriptionOfGlobal += ")";
919 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000920
921 // Create a new global variable with enough space for a redzone.
922 GlobalVariable *NewGlobal = new GlobalVariable(
923 M, NewTy, G->isConstant(), G->getLinkage(),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000924 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000925 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany63f08462013-01-24 10:35:40 +0000926 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000927
928 Value *Indices2[2];
929 Indices2[0] = IRB.getInt32(0);
930 Indices2[1] = IRB.getInt32(0);
931
932 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000933 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000934 NewGlobal->takeName(G);
935 G->eraseFromParent();
936
937 Initializers[i] = ConstantStruct::get(
938 GlobalStructTy,
939 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
940 ConstantInt::get(IntptrTy, SizeInBytes),
941 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
942 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000943 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000944 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000945
946 // Populate the first and last globals declared in this TU.
Alexey Samsonovee548272012-11-29 18:14:24 +0000947 if (CheckInitOrder && GlobalHasDynamicInitializer) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000948 LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy);
949 if (FirstDynamic == 0)
950 FirstDynamic = LastDynamic;
951 }
952
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000953 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000954 }
955
956 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
957 GlobalVariable *AllGlobals = new GlobalVariable(
958 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
959 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
960
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000961 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonovee548272012-11-29 18:14:24 +0000962 if (CheckInitOrder && FirstDynamic && LastDynamic)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000963 createInitializerPoisonCalls(M, FirstDynamic, LastDynamic);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000964 IRB.CreateCall2(AsanRegisterGlobals,
965 IRB.CreatePointerCast(AllGlobals, IntptrTy),
966 ConstantInt::get(IntptrTy, n));
967
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000968 // We also need to unregister globals at the end, e.g. when a shared library
969 // gets closed.
970 Function *AsanDtorFunction = Function::Create(
971 FunctionType::get(Type::getVoidTy(*C), false),
972 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
973 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
974 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000975 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
976 IRB.CreatePointerCast(AllGlobals, IntptrTy),
977 ConstantInt::get(IntptrTy, n));
978 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
979
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000980 DEBUG(dbgs() << M);
981 return true;
982}
983
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000984void AddressSanitizer::initializeCallbacks(Module &M) {
985 IRBuilder<> IRB(*C);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000986 // Create __asan_report* callbacks.
987 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
988 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
989 AccessSizeIndex++) {
990 // IsWrite and TypeSize are encoded in the function name.
991 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
992 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000993 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany7846c1c2012-11-07 12:42:18 +0000994 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
995 checkInterfaceFunction(M.getOrInsertFunction(
996 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000997 }
998 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000999
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001000 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
1001 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
Kostya Serebryanyf7b08222012-07-20 09:54:50 +00001002 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1003 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1004 StringRef(""), StringRef(""),
1005 /*hasSideEffects=*/true);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001006}
1007
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001008void AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const {
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001009 // Tell the values of mapping offset and scale to the run-time.
1010 GlobalValue *asan_mapping_offset =
1011 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1012 ConstantInt::get(IntptrTy, Mapping.Offset),
1013 kAsanMappingOffsetName);
1014 // Read the global, otherwise it may be optimized away.
1015 IRB.CreateLoad(asan_mapping_offset, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001016
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001017 GlobalValue *asan_mapping_scale =
1018 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1019 ConstantInt::get(IntptrTy, Mapping.Scale),
1020 kAsanMappingScaleName);
1021 // Read the global, otherwise it may be optimized away.
1022 IRB.CreateLoad(asan_mapping_scale, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001023}
1024
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001025// virtual
1026bool AddressSanitizer::doInitialization(Module &M) {
1027 // Initialize the private fields. No one has accessed them before.
1028 TD = getAnalysisIfAvailable<DataLayout>();
1029
1030 if (!TD)
1031 return false;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +00001032 BL.reset(new BlackList(BlacklistFile));
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001033 DynamicallyInitializedGlobals.Init(M);
1034
1035 C = &(M.getContext());
1036 LongSize = TD->getPointerSizeInBits();
1037 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001038
1039 AsanCtorFunction = Function::Create(
1040 FunctionType::get(Type::getVoidTy(*C), false),
1041 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1042 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1043 // call __asan_init in the module ctor.
1044 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1045 AsanInitFunction = checkInterfaceFunction(
1046 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1047 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1048 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001049
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001050 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001051 emitShadowMapping(M, IRB);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001052
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001053 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001054 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001055}
1056
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001057bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1058 // For each NSObject descendant having a +load method, this method is invoked
1059 // by the ObjC runtime before any of the static constructors is called.
1060 // Therefore we need to instrument such methods with a call to __asan_init
1061 // at the beginning in order to initialize our runtime before any access to
1062 // the shadow memory.
1063 // We cannot just ignore these methods, because they may call other
1064 // instrumented functions.
1065 if (F.getName().find(" load]") != std::string::npos) {
1066 IRBuilder<> IRB(F.begin()->begin());
1067 IRB.CreateCall(AsanInitFunction);
1068 return true;
1069 }
1070 return false;
1071}
1072
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001073bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001074 if (BL->isIn(F)) return false;
1075 if (&F == AsanCtorFunction) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001076 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001077 initializeCallbacks(*F.getParent());
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001078
1079 // If needed, insert __asan_init before checking for AddressSafety attr.
1080 maybeInsertAsanInitAtFunctionEntry(F);
1081
Bill Wendling831737d2012-12-30 10:32:01 +00001082 if (!F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1083 Attribute::AddressSafety))
Bill Wendling67658342012-10-09 07:45:08 +00001084 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001085
1086 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1087 return false;
Bill Wendling67658342012-10-09 07:45:08 +00001088
1089 // We want to instrument every address only once per basic block (unless there
1090 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001091 SmallSet<Value*, 16> TempsToInstrument;
1092 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001093 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001094 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001095
1096 // Fill the set of memory operations to instrument.
1097 for (Function::iterator FI = F.begin(), FE = F.end();
1098 FI != FE; ++FI) {
1099 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001100 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001101 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1102 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +00001103 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001104 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001105 if (ClOpt && ClOptSameTemp) {
1106 if (!TempsToInstrument.insert(Addr))
1107 continue; // We've seen this temp in the current BB.
1108 }
1109 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1110 // ok, take it.
1111 } else {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001112 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001113 // A call inside BB.
1114 TempsToInstrument.clear();
Kostya Serebryanya17babb2012-11-30 11:08:59 +00001115 if (CI->doesNotReturn()) {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001116 NoReturnCalls.push_back(CI);
1117 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001118 }
1119 continue;
1120 }
1121 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001122 NumInsnsPerBB++;
1123 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1124 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001125 }
1126 }
1127
1128 // Instrument.
1129 int NumInstrumented = 0;
1130 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1131 Instruction *Inst = ToInstrument[i];
1132 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1133 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001134 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001135 instrumentMop(Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001136 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001137 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001138 }
1139 NumInstrumented++;
1140 }
1141
Alexey Samsonov59cca132012-12-25 12:04:36 +00001142 FunctionStackPoisoner FSP(F, *this);
1143 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001144
1145 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1146 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1147 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1148 Instruction *CI = NoReturnCalls[i];
1149 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001150 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001151 }
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001152 DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n");
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001153
1154 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001155}
1156
1157static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1158 if (ShadowRedzoneSize == 1) return PoisonByte;
1159 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1160 if (ShadowRedzoneSize == 4)
1161 return (PoisonByte << 24) + (PoisonByte << 16) +
1162 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +00001163 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001164}
1165
1166static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1167 size_t Size,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001168 size_t RZSize,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001169 size_t ShadowGranularity,
1170 uint8_t Magic) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001171 for (size_t i = 0; i < RZSize;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001172 i+= ShadowGranularity, Shadow++) {
1173 if (i + ShadowGranularity <= Size) {
1174 *Shadow = 0; // fully addressable
1175 } else if (i >= Size) {
1176 *Shadow = Magic; // unaddressable
1177 } else {
1178 *Shadow = Size - i; // first Size-i bytes are addressable
1179 }
1180 }
1181}
1182
Alexey Samsonov59cca132012-12-25 12:04:36 +00001183// Workaround for bug 11395: we don't want to instrument stack in functions
1184// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1185// FIXME: remove once the bug 11395 is fixed.
1186bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1187 if (LongSize != 32) return false;
1188 CallInst *CI = dyn_cast<CallInst>(I);
1189 if (!CI || !CI->isInlineAsm()) return false;
1190 if (CI->getNumArgOperands() <= 5) return false;
1191 // We have inline assembly with quite a few arguments.
1192 return true;
1193}
1194
1195void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1196 IRBuilder<> IRB(*C);
1197 AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
1198 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
1199 AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
1200 kAsanStackFreeName, IRB.getVoidTy(),
1201 IntptrTy, IntptrTy, IntptrTy, NULL));
1202 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1203 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1204 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1205 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1206}
1207
1208void FunctionStackPoisoner::poisonRedZones(
1209 const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB, Value *ShadowBase,
1210 bool DoPoison) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001211 size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001212 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1213 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1214 Type *RZPtrTy = PointerType::get(RZTy, 0);
1215
1216 Value *PoisonLeft = ConstantInt::get(RZTy,
1217 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1218 Value *PoisonMid = ConstantInt::get(RZTy,
1219 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1220 Value *PoisonRight = ConstantInt::get(RZTy,
1221 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1222
1223 // poison the first red zone.
1224 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1225
1226 // poison all other red zones.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001227 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001228 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1229 AllocaInst *AI = AllocaVec[i];
1230 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1231 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001232 assert(AlignedSize - SizeInBytes < RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001233 Value *Ptr = NULL;
1234
1235 Pos += AlignedSize;
1236
1237 assert(ShadowBase->getType() == IntptrTy);
1238 if (SizeInBytes < AlignedSize) {
1239 // Poison the partial redzone at right
1240 Ptr = IRB.CreateAdd(
1241 ShadowBase, ConstantInt::get(IntptrTy,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001242 (Pos >> Mapping.Scale) - ShadowRZSize));
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001243 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001244 uint32_t Poison = 0;
1245 if (DoPoison) {
1246 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001247 RedzoneSize(),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001248 1ULL << Mapping.Scale,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001249 kAsanStackPartialRedzoneMagic);
1250 }
1251 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1252 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1253 }
1254
1255 // Poison the full redzone at right.
1256 Ptr = IRB.CreateAdd(ShadowBase,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001257 ConstantInt::get(IntptrTy, Pos >> Mapping.Scale));
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001258 bool LastAlloca = (i == AllocaVec.size() - 1);
1259 Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001260 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1261
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001262 Pos += RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001263 }
1264}
1265
Alexey Samsonov59cca132012-12-25 12:04:36 +00001266void FunctionStackPoisoner::poisonStack() {
Alexey Samsonov59cca132012-12-25 12:04:36 +00001267 uint64_t LocalStackSize = TotalStackSize +
1268 (AllocaVec.size() + 1) * RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001269
Alexey Samsonov59cca132012-12-25 12:04:36 +00001270 bool DoStackMalloc = ASan.CheckUseAfterReturn
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001271 && LocalStackSize <= kMaxStackMallocSize;
1272
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001273 assert(AllocaVec.size() > 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001274 Instruction *InsBefore = AllocaVec[0];
1275 IRBuilder<> IRB(InsBefore);
1276
1277
1278 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1279 AllocaInst *MyAlloca =
1280 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Alexey Samsonov59cca132012-12-25 12:04:36 +00001281 if (ClRealignStack && StackAlignment < RedzoneSize())
1282 StackAlignment = RedzoneSize();
1283 MyAlloca->setAlignment(StackAlignment);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001284 assert(MyAlloca->isStaticAlloca());
1285 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1286 Value *LocalStackBase = OrigStackBase;
1287
1288 if (DoStackMalloc) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001289 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1290 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1291 }
1292
1293 // This string will be parsed by the run-time (DescribeStackAddress).
1294 SmallString<2048> StackDescriptionStorage;
1295 raw_svector_ostream StackDescription(StackDescriptionStorage);
1296 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1297
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001298 // Insert poison calls for lifetime intrinsics for alloca.
1299 bool HavePoisonedAllocas = false;
1300 for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1301 const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1302 IntrinsicInst *II = APC.InsBefore;
1303 AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
1304 assert(AI);
1305 IRBuilder<> IRB(II);
1306 poisonAlloca(AI, APC.Size, IRB, APC.DoPoison);
1307 HavePoisonedAllocas |= APC.DoPoison;
1308 }
1309
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001310 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001311 // Replace Alloca instructions with base+offset.
1312 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1313 AllocaInst *AI = AllocaVec[i];
1314 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1315 StringRef Name = AI->getName();
1316 StackDescription << Pos << " " << SizeInBytes << " "
1317 << Name.size() << " " << Name << " ";
1318 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001319 assert((AlignedSize % RedzoneSize()) == 0);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001320 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001321 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
Alexey Samsonovf985f442012-12-04 01:34:23 +00001322 AI->getType());
Alexey Samsonov1afbb512012-12-12 14:31:53 +00001323 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001324 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001325 Pos += AlignedSize + RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001326 }
1327 assert(Pos == LocalStackSize);
1328
1329 // Write the Magic value and the frame description constant to the redzone.
1330 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1331 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1332 BasePlus0);
1333 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
Alexey Samsonov59cca132012-12-25 12:04:36 +00001334 ConstantInt::get(IntptrTy,
1335 ASan.LongSize/8));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001336 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
Alexey Samsonov9ce84c12012-11-02 12:20:34 +00001337 GlobalVariable *StackDescriptionGlobal =
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001338 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
Alexey Samsonov59cca132012-12-25 12:04:36 +00001339 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1340 IntptrTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001341 IRB.CreateStore(Description, BasePlus1);
1342
1343 // Poison the stack redzones at the entry.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001344 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1345 poisonRedZones(AllocaVec, IRB, ShadowBase, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001346
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001347 // Unpoison the stack before all ret instructions.
1348 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1349 Instruction *Ret = RetVec[i];
1350 IRBuilder<> IRBRet(Ret);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001351 // Mark the current frame as retired.
1352 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1353 BasePlus0);
1354 // Unpoison the stack.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001355 poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001356 if (DoStackMalloc) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001357 // In use-after-return mode, mark the whole stack frame unaddressable.
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001358 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1359 ConstantInt::get(IntptrTy, LocalStackSize),
1360 OrigStackBase);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001361 } else if (HavePoisonedAllocas) {
1362 // If we poisoned some allocas in llvm.lifetime analysis,
1363 // unpoison whole stack frame now.
1364 assert(LocalStackBase == OrigStackBase);
1365 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001366 }
1367 }
1368
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001369 // We are done. Remove the old unused alloca instructions.
1370 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1371 AllocaVec[i]->eraseFromParent();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001372}
Alexey Samsonovf985f442012-12-04 01:34:23 +00001373
Alexey Samsonov59cca132012-12-25 12:04:36 +00001374void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1375 IRBuilder<> IRB, bool DoPoison) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001376 // For now just insert the call to ASan runtime.
1377 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1378 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1379 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1380 : AsanUnpoisonStackMemoryFunc,
1381 AddrArg, SizeArg);
1382}
Alexey Samsonov59cca132012-12-25 12:04:36 +00001383
1384// Handling llvm.lifetime intrinsics for a given %alloca:
1385// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1386// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1387// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1388// could be poisoned by previous llvm.lifetime.end instruction, as the
1389// variable may go in and out of scope several times, e.g. in loops).
1390// (3) if we poisoned at least one %alloca in a function,
1391// unpoison the whole stack frame at function exit.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001392
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001393AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1394 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1395 // We're intested only in allocas we can handle.
1396 return isInterestingAlloca(*AI) ? AI : 0;
1397 // See if we've already calculated (or started to calculate) alloca for a
1398 // given value.
1399 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1400 if (I != AllocaForValue.end())
1401 return I->second;
1402 // Store 0 while we're calculating alloca for value V to avoid
1403 // infinite recursion if the value references itself.
1404 AllocaForValue[V] = 0;
1405 AllocaInst *Res = 0;
1406 if (CastInst *CI = dyn_cast<CastInst>(V))
1407 Res = findAllocaForValue(CI->getOperand(0));
1408 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1409 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1410 Value *IncValue = PN->getIncomingValue(i);
1411 // Allow self-referencing phi-nodes.
1412 if (IncValue == PN) continue;
1413 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1414 // AI for incoming values should exist and should all be equal.
1415 if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1416 return 0;
1417 Res = IncValueAI;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001418 }
Alexey Samsonov59cca132012-12-25 12:04:36 +00001419 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001420 if (Res != 0)
1421 AllocaForValue[V] = Res;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001422 return Res;
1423}