blob: 02a8680b6c7bc0ebfc77f023f86a1ebfda03074d [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;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000205 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64;
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000206 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000207
208 ShadowMapping Mapping;
209
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000210 // OR-ing shadow offset if more efficient (at least on x86),
211 // but on ppc64 we have to use add since the shadow offset is not neccesary
212 // 1/8-th of the address space.
Kostya Serebryany117de482013-02-11 14:36:01 +0000213 Mapping.OrShadowOffset = !IsPPC64 && !ClShort64BitOffset;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000214
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000215 Mapping.Offset = (IsAndroid || ZeroBaseShadow) ? 0 :
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000216 (LongSize == 32 ? kDefaultShadowOffset32 :
217 IsPPC64 ? kPPC64_ShadowOffset64 : kDefaultShadowOffset64);
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000218 if (!ZeroBaseShadow && ClShort64BitOffset && IsX86_64) {
219 assert(LongSize == 64);
Kostya Serebryany117de482013-02-11 14:36:01 +0000220 Mapping.Offset = kDefaultShort64bitShadowOffset;
221 } if (!ZeroBaseShadow && ClMappingOffsetLog >= 0) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000222 // Zero offset log is the special case.
223 Mapping.Offset = (ClMappingOffsetLog == 0) ? 0 : 1ULL << ClMappingOffsetLog;
224 }
225
226 Mapping.Scale = kDefaultShadowScale;
227 if (ClMappingScale) {
228 Mapping.Scale = ClMappingScale;
229 }
230
231 return Mapping;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000232}
233
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000234static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000235 // Redzone used for stack and globals is at least 32 bytes.
236 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000237 return std::max(32U, 1U << MappingScale);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000238}
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000239
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000240/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000241struct AddressSanitizer : public FunctionPass {
Alexey Samsonovee548272012-11-29 18:14:24 +0000242 AddressSanitizer(bool CheckInitOrder = false,
243 bool CheckUseAfterReturn = false,
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000244 bool CheckLifetime = false,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000245 StringRef BlacklistFile = StringRef(),
246 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000247 : FunctionPass(ID),
248 CheckInitOrder(CheckInitOrder || ClInitializers),
249 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000250 CheckLifetime(CheckLifetime || ClCheckLifetime),
251 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000252 : BlacklistFile),
253 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000254 virtual const char *getPassName() const {
255 return "AddressSanitizerFunctionPass";
256 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000257 void instrumentMop(Instruction *I);
258 void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000259 Value *Addr, uint32_t TypeSize, bool IsWrite);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000260 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
261 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000262 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000263 bool IsWrite, size_t AccessSizeIndex);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000264 bool instrumentMemIntrinsic(MemIntrinsic *MI);
265 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000266 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000267 Instruction *InsertBefore, bool IsWrite);
268 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000269 bool runOnFunction(Function &F);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000270 void createInitializerPoisonCalls(Module &M,
271 Value *FirstAddr, Value *LastAddr);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000272 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000273 void emitShadowMapping(Module &M, IRBuilder<> &IRB) const;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000274 virtual bool doInitialization(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000275 static char ID; // Pass identification, replacement for typeid
276
277 private:
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000278 void initializeCallbacks(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000279
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000280 bool ShouldInstrumentGlobal(GlobalVariable *G);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000281 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000282 void FindDynamicInitializers(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000283
Alexey Samsonovee548272012-11-29 18:14:24 +0000284 bool CheckInitOrder;
285 bool CheckUseAfterReturn;
286 bool CheckLifetime;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000287 SmallString<64> BlacklistFile;
288 bool ZeroBaseShadow;
289
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000290 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +0000291 DataLayout *TD;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000292 int LongSize;
293 Type *IntptrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000294 ShadowMapping Mapping;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000295 Function *AsanCtorFunction;
296 Function *AsanInitFunction;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000297 Function *AsanHandleNoReturnFunc;
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +0000298 OwningPtr<BlackList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000299 // This array is indexed by AccessIsWrite and log2(AccessSize).
300 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000301 InlineAsm *EmptyAsm;
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000302 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000303
304 friend struct FunctionStackPoisoner;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000305};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000306
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000307class AddressSanitizerModule : public ModulePass {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000308 public:
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000309 AddressSanitizerModule(bool CheckInitOrder = false,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000310 StringRef BlacklistFile = StringRef(),
311 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000312 : ModulePass(ID),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000313 CheckInitOrder(CheckInitOrder || ClInitializers),
314 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000315 : BlacklistFile),
316 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000317 bool runOnModule(Module &M);
318 static char ID; // Pass identification, replacement for typeid
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000319 virtual const char *getPassName() const {
320 return "AddressSanitizerModule";
321 }
Alexey Samsonovf985f442012-12-04 01:34:23 +0000322
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000323 private:
Alexey Samsonov46848582012-12-25 12:28:20 +0000324 void initializeCallbacks(Module &M);
325
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000326 bool ShouldInstrumentGlobal(GlobalVariable *G);
327 void createInitializerPoisonCalls(Module &M, Value *FirstAddr,
328 Value *LastAddr);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000329 size_t RedzoneSize() const {
330 return RedzoneSizeForScale(Mapping.Scale);
331 }
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000332
Alexey Samsonovee548272012-11-29 18:14:24 +0000333 bool CheckInitOrder;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000334 SmallString<64> BlacklistFile;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000335 bool ZeroBaseShadow;
336
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000337 OwningPtr<BlackList> BL;
338 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
339 Type *IntptrTy;
340 LLVMContext *C;
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000341 DataLayout *TD;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000342 ShadowMapping Mapping;
Alexey Samsonov46848582012-12-25 12:28:20 +0000343 Function *AsanPoisonGlobals;
344 Function *AsanUnpoisonGlobals;
345 Function *AsanRegisterGlobals;
346 Function *AsanUnregisterGlobals;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000347};
348
Alexey Samsonov59cca132012-12-25 12:04:36 +0000349// Stack poisoning does not play well with exception handling.
350// When an exception is thrown, we essentially bypass the code
351// that unpoisones the stack. This is why the run-time library has
352// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
353// stack in the interceptor. This however does not work inside the
354// actual function which catches the exception. Most likely because the
355// compiler hoists the load of the shadow value somewhere too high.
356// This causes asan to report a non-existing bug on 453.povray.
357// It sounds like an LLVM bug.
358struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
359 Function &F;
360 AddressSanitizer &ASan;
361 DIBuilder DIB;
362 LLVMContext *C;
363 Type *IntptrTy;
364 Type *IntptrPtrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000365 ShadowMapping Mapping;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000366
367 SmallVector<AllocaInst*, 16> AllocaVec;
368 SmallVector<Instruction*, 8> RetVec;
369 uint64_t TotalStackSize;
370 unsigned StackAlignment;
371
372 Function *AsanStackMallocFunc, *AsanStackFreeFunc;
373 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
374
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000375 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
376 struct AllocaPoisonCall {
377 IntrinsicInst *InsBefore;
378 uint64_t Size;
379 bool DoPoison;
380 };
381 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
382
383 // Maps Value to an AllocaInst from which the Value is originated.
384 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
385 AllocaForValueMapTy AllocaForValue;
386
Alexey Samsonov59cca132012-12-25 12:04:36 +0000387 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
388 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
389 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000390 Mapping(ASan.Mapping),
391 TotalStackSize(0), StackAlignment(1 << Mapping.Scale) {}
Alexey Samsonov59cca132012-12-25 12:04:36 +0000392
393 bool runOnFunction() {
394 if (!ClStack) return false;
395 // Collect alloca, ret, lifetime instructions etc.
396 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
397 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
398 BasicBlock *BB = *DI;
399 visit(*BB);
400 }
401 if (AllocaVec.empty()) return false;
402
403 initializeCallbacks(*F.getParent());
404
405 poisonStack();
406
407 if (ClDebugStack) {
408 DEBUG(dbgs() << F);
409 }
410 return true;
411 }
412
413 // Finds all static Alloca instructions and puts
414 // poisoned red zones around all of them.
415 // Then unpoison everything back before the function returns.
416 void poisonStack();
417
418 // ----------------------- Visitors.
419 /// \brief Collect all Ret instructions.
420 void visitReturnInst(ReturnInst &RI) {
421 RetVec.push_back(&RI);
422 }
423
424 /// \brief Collect Alloca instructions we want (and can) handle.
425 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000426 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000427
428 StackAlignment = std::max(StackAlignment, AI.getAlignment());
429 AllocaVec.push_back(&AI);
430 uint64_t AlignedSize = getAlignedAllocaSize(&AI);
431 TotalStackSize += AlignedSize;
432 }
433
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000434 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
435 /// errors.
436 void visitIntrinsicInst(IntrinsicInst &II) {
437 if (!ASan.CheckLifetime) return;
438 Intrinsic::ID ID = II.getIntrinsicID();
439 if (ID != Intrinsic::lifetime_start &&
440 ID != Intrinsic::lifetime_end)
441 return;
442 // Found lifetime intrinsic, add ASan instrumentation if necessary.
443 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
444 // If size argument is undefined, don't do anything.
445 if (Size->isMinusOne()) return;
446 // Check that size doesn't saturate uint64_t and can
447 // be stored in IntptrTy.
448 const uint64_t SizeValue = Size->getValue().getLimitedValue();
449 if (SizeValue == ~0ULL ||
450 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
451 return;
452 // Find alloca instruction that corresponds to llvm.lifetime argument.
453 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
454 if (!AI) return;
455 bool DoPoison = (ID == Intrinsic::lifetime_end);
456 AllocaPoisonCall APC = {&II, SizeValue, DoPoison};
457 AllocaPoisonCallVec.push_back(APC);
458 }
459
Alexey Samsonov59cca132012-12-25 12:04:36 +0000460 // ---------------------- Helpers.
461 void initializeCallbacks(Module &M);
462
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000463 // Check if we want (and can) handle this alloca.
464 bool isInterestingAlloca(AllocaInst &AI) {
465 return (!AI.isArrayAllocation() &&
466 AI.isStaticAlloca() &&
467 AI.getAllocatedType()->isSized());
468 }
469
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000470 size_t RedzoneSize() const {
471 return RedzoneSizeForScale(Mapping.Scale);
472 }
Alexey Samsonov59cca132012-12-25 12:04:36 +0000473 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
474 Type *Ty = AI->getAllocatedType();
475 uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty);
476 return SizeInBytes;
477 }
478 uint64_t getAlignedSize(uint64_t SizeInBytes) {
479 size_t RZ = RedzoneSize();
480 return ((SizeInBytes + RZ - 1) / RZ) * RZ;
481 }
482 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
483 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
484 return getAlignedSize(SizeInBytes);
485 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000486 /// Finds alloca where the value comes from.
487 AllocaInst *findAllocaForValue(Value *V);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000488 void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
489 Value *ShadowBase, bool DoPoison);
490 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> IRB, bool DoPoison);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000491};
492
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000493} // namespace
494
495char AddressSanitizer::ID = 0;
496INITIALIZE_PASS(AddressSanitizer, "asan",
497 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
498 false, false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000499FunctionPass *llvm::createAddressSanitizerFunctionPass(
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000500 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000501 StringRef BlacklistFile, bool ZeroBaseShadow) {
Alexey Samsonovee548272012-11-29 18:14:24 +0000502 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000503 CheckLifetime, BlacklistFile, ZeroBaseShadow);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000504}
505
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000506char AddressSanitizerModule::ID = 0;
507INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
508 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
509 "ModulePass", false, false)
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000510ModulePass *llvm::createAddressSanitizerModulePass(
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000511 bool CheckInitOrder, StringRef BlacklistFile, bool ZeroBaseShadow) {
512 return new AddressSanitizerModule(CheckInitOrder, BlacklistFile,
513 ZeroBaseShadow);
Alexander Potapenko25878042012-01-23 11:22:43 +0000514}
515
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000516static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
517 size_t Res = CountTrailingZeros_32(TypeSize / 8);
518 assert(Res < kNumberOfAccessSizes);
519 return Res;
520}
521
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000522// Create a constant for Str so that we can pass it to the run-time lib.
523static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000524 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000525 return new GlobalVariable(M, StrConst->getType(), true,
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000526 GlobalValue::PrivateLinkage, StrConst,
527 kAsanGenPrefix);
528}
529
530static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
531 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000532}
533
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000534Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
535 // Shadow >> scale
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000536 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
537 if (Mapping.Offset == 0)
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000538 return Shadow;
539 // (Shadow >> scale) | offset
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000540 if (Mapping.OrShadowOffset)
541 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
542 else
543 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000544}
545
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000546void AddressSanitizer::instrumentMemIntrinsicParam(
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000547 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000548 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
549 // Check the first byte.
550 {
551 IRBuilder<> IRB(InsertBefore);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000552 instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000553 }
554 // Check the last byte.
555 {
556 IRBuilder<> IRB(InsertBefore);
557 Value *SizeMinusOne = IRB.CreateSub(
558 Size, ConstantInt::get(Size->getType(), 1));
559 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
560 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
561 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000562 instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000563 }
564}
565
566// Instrument memset/memmove/memcpy
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000567bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000568 Value *Dst = MI->getDest();
569 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000570 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000571 Value *Length = MI->getLength();
572
573 Constant *ConstLength = dyn_cast<Constant>(Length);
574 Instruction *InsertBefore = MI;
575 if (ConstLength) {
576 if (ConstLength->isNullValue()) return false;
577 } else {
578 // The size is not a constant so it could be zero -- check at run-time.
579 IRBuilder<> IRB(InsertBefore);
580
581 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000582 Constant::getNullValue(Length->getType()));
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000583 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000584 }
585
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000586 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000587 if (Src)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000588 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000589 return true;
590}
591
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000592// If I is an interesting memory access, return the PointerOperand
593// and set IsWrite. Otherwise return NULL.
594static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000595 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000596 if (!ClInstrumentReads) return NULL;
597 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000598 return LI->getPointerOperand();
599 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000600 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
601 if (!ClInstrumentWrites) return NULL;
602 *IsWrite = true;
603 return SI->getPointerOperand();
604 }
605 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
606 if (!ClInstrumentAtomics) return NULL;
607 *IsWrite = true;
608 return RMW->getPointerOperand();
609 }
610 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
611 if (!ClInstrumentAtomics) return NULL;
612 *IsWrite = true;
613 return XCHG->getPointerOperand();
614 }
615 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000616}
617
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000618void AddressSanitizer::instrumentMop(Instruction *I) {
Axel Naumann3780ad82012-09-17 14:20:57 +0000619 bool IsWrite = false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000620 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
621 assert(Addr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000622 if (ClOpt && ClOptGlobals) {
623 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
624 // If initialization order checking is disabled, a simple access to a
625 // dynamically initialized global is always valid.
Alexey Samsonovee548272012-11-29 18:14:24 +0000626 if (!CheckInitOrder)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000627 return;
628 // If a global variable does not have dynamic initialization we don't
Kostya Serebryany40779062012-11-20 13:11:32 +0000629 // have to instrument it. However, if a global does not have initailizer
630 // at all, we assume it has dynamic initializer (in other TU).
631 if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000632 return;
633 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000634 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000635
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000636 Type *OrigPtrTy = Addr->getType();
637 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
638
639 assert(OrigTy->isSized());
640 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
641
642 if (TypeSize != 8 && TypeSize != 16 &&
643 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
644 // Ignore all unusual sizes.
645 return;
646 }
647
648 IRBuilder<> IRB(I);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000649 instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000650}
651
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000652// Validate the result of Module::getOrInsertFunction called for an interface
653// function of AddressSanitizer. If the instrumented module defines a function
654// with the same name, their prototypes must match, otherwise
655// getOrInsertFunction returns a bitcast.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000656static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000657 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
658 FuncOrBitcast->dump();
659 report_fatal_error("trying to redefine an AddressSanitizer "
660 "interface function");
661}
662
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000663Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000664 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000665 bool IsWrite, size_t AccessSizeIndex) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000666 IRBuilder<> IRB(InsertBefore);
667 CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
668 Addr);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000669 // We don't do Call->setDoesNotReturn() because the BB already has
670 // UnreachableInst at the end.
671 // This EmptyAsm is required to avoid callback merge.
672 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000673 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000674}
675
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000676Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000677 Value *ShadowValue,
678 uint32_t TypeSize) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000679 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000680 // Addr & (Granularity - 1)
681 Value *LastAccessedByte = IRB.CreateAnd(
682 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
683 // (Addr & (Granularity - 1)) + size - 1
684 if (TypeSize / 8 > 1)
685 LastAccessedByte = IRB.CreateAdd(
686 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
687 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
688 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000689 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000690 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
691 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
692}
693
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000694void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000695 IRBuilder<> &IRB, Value *Addr,
696 uint32_t TypeSize, bool IsWrite) {
697 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
698
699 Type *ShadowTy = IntegerType::get(
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000700 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000701 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
702 Value *ShadowPtr = memToShadow(AddrLong, IRB);
703 Value *CmpVal = Constant::getNullValue(ShadowTy);
704 Value *ShadowValue = IRB.CreateLoad(
705 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
706
707 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000708 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000709 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000710 TerminatorInst *CrashTerm = 0;
711
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000712 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000713 TerminatorInst *CheckTerm =
714 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000715 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000716 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000717 IRB.SetInsertPoint(CheckTerm);
718 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000719 BasicBlock *CrashBlock =
720 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000721 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000722 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
723 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000724 } else {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000725 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000726 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000727
728 Instruction *Crash =
729 generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex);
730 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000731}
732
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000733void AddressSanitizerModule::createInitializerPoisonCalls(
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000734 Module &M, Value *FirstAddr, Value *LastAddr) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000735 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
736 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
737 // If that function is not present, this TU contains no globals, or they have
738 // all been optimized away
739 if (!GlobalInit)
740 return;
741
742 // Set up the arguments to our poison/unpoison functions.
743 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
744
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000745 // Add a call to poison all external globals before the given function starts.
746 IRB.CreateCall2(AsanPoisonGlobals, FirstAddr, LastAddr);
747
748 // Add calls to unpoison all globals before each return instruction.
749 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
750 I != E; ++I) {
751 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
752 CallInst::Create(AsanUnpoisonGlobals, "", RI);
753 }
754 }
755}
756
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000757bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000758 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000759 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000760
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000761 if (BL->isIn(*G)) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000762 if (!Ty->isSized()) return false;
763 if (!G->hasInitializer()) return false;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000764 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000765 // Touch only those globals that will not be defined in other modules.
766 // Don't handle ODR type linkages since other modules may be built w/o asan.
767 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
768 G->getLinkage() != GlobalVariable::PrivateLinkage &&
769 G->getLinkage() != GlobalVariable::InternalLinkage)
770 return false;
771 // Two problems with thread-locals:
772 // - The address of the main thread's copy can't be computed at link-time.
773 // - Need to poison all copies, not just the main thread's one.
774 if (G->isThreadLocal())
775 return false;
776 // For now, just ignore this Alloca if the alignment is large.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000777 if (G->getAlignment() > RedzoneSize()) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000778
779 // Ignore all the globals with the names starting with "\01L_OBJC_".
780 // Many of those are put into the .cstring section. The linker compresses
781 // that section by removing the spare \0s after the string terminator, so
782 // our redzones get broken.
783 if ((G->getName().find("\01L_OBJC_") == 0) ||
784 (G->getName().find("\01l_OBJC_") == 0)) {
785 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
786 return false;
787 }
788
789 if (G->hasSection()) {
790 StringRef Section(G->getSection());
791 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
792 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
793 // them.
794 if ((Section.find("__OBJC,") == 0) ||
795 (Section.find("__DATA, __objc_") == 0)) {
796 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
797 return false;
798 }
799 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
800 // Constant CFString instances are compiled in the following way:
801 // -- the string buffer is emitted into
802 // __TEXT,__cstring,cstring_literals
803 // -- the constant NSConstantString structure referencing that buffer
804 // is placed into __DATA,__cfstring
805 // Therefore there's no point in placing redzones into __DATA,__cfstring.
806 // Moreover, it causes the linker to crash on OS X 10.7
807 if (Section.find("__DATA,__cfstring") == 0) {
808 DEBUG(dbgs() << "Ignoring CFString: " << *G);
809 return false;
810 }
811 }
812
813 return true;
814}
815
Alexey Samsonov46848582012-12-25 12:28:20 +0000816void AddressSanitizerModule::initializeCallbacks(Module &M) {
817 IRBuilder<> IRB(*C);
818 // Declare our poisoning and unpoisoning functions.
819 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
820 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
821 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
822 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
823 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
824 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
825 // Declare functions that register/unregister globals.
826 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
827 kAsanRegisterGlobalsName, IRB.getVoidTy(),
828 IntptrTy, IntptrTy, NULL));
829 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
830 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
831 kAsanUnregisterGlobalsName,
832 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
833 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
834}
835
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000836// This function replaces all global variables with new variables that have
837// trailing redzones. It also creates a function that poisons
838// redzones and inserts this function into llvm.global_ctors.
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000839bool AddressSanitizerModule::runOnModule(Module &M) {
840 if (!ClGlobals) return false;
841 TD = getAnalysisIfAvailable<DataLayout>();
842 if (!TD)
843 return false;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000844 BL.reset(new BlackList(BlacklistFile));
Alexey Samsonovd6f62c82012-11-29 18:27:01 +0000845 if (BL->isIn(M)) return false;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000846 C = &(M.getContext());
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000847 int LongSize = TD->getPointerSizeInBits();
848 IntptrTy = Type::getIntNTy(*C, LongSize);
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000849 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov46848582012-12-25 12:28:20 +0000850 initializeCallbacks(M);
851 DynamicallyInitializedGlobals.Init(M);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000852
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000853 SmallVector<GlobalVariable *, 16> GlobalsToChange;
854
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000855 for (Module::GlobalListType::iterator G = M.global_begin(),
856 E = M.global_end(); G != E; ++G) {
857 if (ShouldInstrumentGlobal(G))
858 GlobalsToChange.push_back(G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000859 }
860
861 size_t n = GlobalsToChange.size();
862 if (n == 0) return false;
863
864 // A global is described by a structure
865 // size_t beg;
866 // size_t size;
867 // size_t size_with_redzone;
868 // const char *name;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000869 // size_t has_dynamic_init;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000870 // We initialize an array of such structures and pass it to a run-time call.
871 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000872 IntptrTy, IntptrTy,
873 IntptrTy, NULL);
874 SmallVector<Constant *, 16> Initializers(n), DynamicInit;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000875
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000876
877 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
878 assert(CtorFunc);
879 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000880
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000881 // The addresses of the first and last dynamically initialized globals in
882 // this TU. Used in initialization order checking.
883 Value *FirstDynamic = 0, *LastDynamic = 0;
884
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000885 for (size_t i = 0; i < n; i++) {
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000886 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000887 GlobalVariable *G = GlobalsToChange[i];
888 PointerType *PtrTy = cast<PointerType>(G->getType());
889 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000890 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000891 uint64_t MinRZ = RedzoneSize();
Kostya Serebryany63f08462013-01-24 10:35:40 +0000892 // MinRZ <= RZ <= kMaxGlobalRedzone
893 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000894 uint64_t RZ = std::max(MinRZ,
Kostya Serebryany63f08462013-01-24 10:35:40 +0000895 std::min(kMaxGlobalRedzone,
896 (SizeInBytes / MinRZ / 4) * MinRZ));
897 uint64_t RightRedzoneSize = RZ;
898 // Round up to MinRZ
899 if (SizeInBytes % MinRZ)
900 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
901 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000902 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000903 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000904 bool GlobalHasDynamicInitializer =
905 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000906 // Don't check initialization order if this global is blacklisted.
Kostya Serebryany7dadac62012-09-05 09:00:18 +0000907 GlobalHasDynamicInitializer &= !BL->isInInit(*G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000908
909 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
910 Constant *NewInitializer = ConstantStruct::get(
911 NewTy, G->getInitializer(),
912 Constant::getNullValue(RightRedZoneTy), NULL);
913
Kostya Serebryanya4b2b1d2011-12-15 22:55:55 +0000914 SmallString<2048> DescriptionOfGlobal = G->getName();
915 DescriptionOfGlobal += " (";
916 DescriptionOfGlobal += M.getModuleIdentifier();
917 DescriptionOfGlobal += ")";
918 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000919
920 // Create a new global variable with enough space for a redzone.
921 GlobalVariable *NewGlobal = new GlobalVariable(
922 M, NewTy, G->isConstant(), G->getLinkage(),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000923 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000924 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany63f08462013-01-24 10:35:40 +0000925 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000926
927 Value *Indices2[2];
928 Indices2[0] = IRB.getInt32(0);
929 Indices2[1] = IRB.getInt32(0);
930
931 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000932 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000933 NewGlobal->takeName(G);
934 G->eraseFromParent();
935
936 Initializers[i] = ConstantStruct::get(
937 GlobalStructTy,
938 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
939 ConstantInt::get(IntptrTy, SizeInBytes),
940 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
941 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000942 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000943 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000944
945 // Populate the first and last globals declared in this TU.
Alexey Samsonovee548272012-11-29 18:14:24 +0000946 if (CheckInitOrder && GlobalHasDynamicInitializer) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000947 LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy);
948 if (FirstDynamic == 0)
949 FirstDynamic = LastDynamic;
950 }
951
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000952 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000953 }
954
955 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
956 GlobalVariable *AllGlobals = new GlobalVariable(
957 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
958 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
959
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000960 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonovee548272012-11-29 18:14:24 +0000961 if (CheckInitOrder && FirstDynamic && LastDynamic)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000962 createInitializerPoisonCalls(M, FirstDynamic, LastDynamic);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000963 IRB.CreateCall2(AsanRegisterGlobals,
964 IRB.CreatePointerCast(AllGlobals, IntptrTy),
965 ConstantInt::get(IntptrTy, n));
966
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000967 // We also need to unregister globals at the end, e.g. when a shared library
968 // gets closed.
969 Function *AsanDtorFunction = Function::Create(
970 FunctionType::get(Type::getVoidTy(*C), false),
971 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
972 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
973 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000974 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
975 IRB.CreatePointerCast(AllGlobals, IntptrTy),
976 ConstantInt::get(IntptrTy, n));
977 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
978
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000979 DEBUG(dbgs() << M);
980 return true;
981}
982
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000983void AddressSanitizer::initializeCallbacks(Module &M) {
984 IRBuilder<> IRB(*C);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000985 // Create __asan_report* callbacks.
986 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
987 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
988 AccessSizeIndex++) {
989 // IsWrite and TypeSize are encoded in the function name.
990 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
991 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000992 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany7846c1c2012-11-07 12:42:18 +0000993 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
994 checkInterfaceFunction(M.getOrInsertFunction(
995 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000996 }
997 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000998
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000999 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
1000 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
Kostya Serebryanyf7b08222012-07-20 09:54:50 +00001001 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1002 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1003 StringRef(""), StringRef(""),
1004 /*hasSideEffects=*/true);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001005}
1006
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001007void AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const {
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001008 // Tell the values of mapping offset and scale to the run-time.
1009 GlobalValue *asan_mapping_offset =
1010 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1011 ConstantInt::get(IntptrTy, Mapping.Offset),
1012 kAsanMappingOffsetName);
1013 // Read the global, otherwise it may be optimized away.
1014 IRB.CreateLoad(asan_mapping_offset, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001015
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001016 GlobalValue *asan_mapping_scale =
1017 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1018 ConstantInt::get(IntptrTy, Mapping.Scale),
1019 kAsanMappingScaleName);
1020 // Read the global, otherwise it may be optimized away.
1021 IRB.CreateLoad(asan_mapping_scale, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001022}
1023
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001024// virtual
1025bool AddressSanitizer::doInitialization(Module &M) {
1026 // Initialize the private fields. No one has accessed them before.
1027 TD = getAnalysisIfAvailable<DataLayout>();
1028
1029 if (!TD)
1030 return false;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +00001031 BL.reset(new BlackList(BlacklistFile));
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001032 DynamicallyInitializedGlobals.Init(M);
1033
1034 C = &(M.getContext());
1035 LongSize = TD->getPointerSizeInBits();
1036 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001037
1038 AsanCtorFunction = Function::Create(
1039 FunctionType::get(Type::getVoidTy(*C), false),
1040 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1041 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1042 // call __asan_init in the module ctor.
1043 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1044 AsanInitFunction = checkInterfaceFunction(
1045 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1046 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1047 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001048
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001049 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001050 emitShadowMapping(M, IRB);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001051
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001052 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001053 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001054}
1055
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001056bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1057 // For each NSObject descendant having a +load method, this method is invoked
1058 // by the ObjC runtime before any of the static constructors is called.
1059 // Therefore we need to instrument such methods with a call to __asan_init
1060 // at the beginning in order to initialize our runtime before any access to
1061 // the shadow memory.
1062 // We cannot just ignore these methods, because they may call other
1063 // instrumented functions.
1064 if (F.getName().find(" load]") != std::string::npos) {
1065 IRBuilder<> IRB(F.begin()->begin());
1066 IRB.CreateCall(AsanInitFunction);
1067 return true;
1068 }
1069 return false;
1070}
1071
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001072bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001073 if (BL->isIn(F)) return false;
1074 if (&F == AsanCtorFunction) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001075 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001076 initializeCallbacks(*F.getParent());
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001077
1078 // If needed, insert __asan_init before checking for AddressSafety attr.
1079 maybeInsertAsanInitAtFunctionEntry(F);
1080
Bill Wendling831737d2012-12-30 10:32:01 +00001081 if (!F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1082 Attribute::AddressSafety))
Bill Wendling67658342012-10-09 07:45:08 +00001083 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001084
1085 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1086 return false;
Bill Wendling67658342012-10-09 07:45:08 +00001087
1088 // We want to instrument every address only once per basic block (unless there
1089 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001090 SmallSet<Value*, 16> TempsToInstrument;
1091 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001092 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001093 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001094
1095 // Fill the set of memory operations to instrument.
1096 for (Function::iterator FI = F.begin(), FE = F.end();
1097 FI != FE; ++FI) {
1098 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001099 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001100 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1101 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +00001102 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001103 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001104 if (ClOpt && ClOptSameTemp) {
1105 if (!TempsToInstrument.insert(Addr))
1106 continue; // We've seen this temp in the current BB.
1107 }
1108 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1109 // ok, take it.
1110 } else {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001111 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001112 // A call inside BB.
1113 TempsToInstrument.clear();
Kostya Serebryanya17babb2012-11-30 11:08:59 +00001114 if (CI->doesNotReturn()) {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001115 NoReturnCalls.push_back(CI);
1116 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001117 }
1118 continue;
1119 }
1120 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001121 NumInsnsPerBB++;
1122 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1123 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001124 }
1125 }
1126
1127 // Instrument.
1128 int NumInstrumented = 0;
1129 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1130 Instruction *Inst = ToInstrument[i];
1131 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1132 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001133 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001134 instrumentMop(Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001135 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001136 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001137 }
1138 NumInstrumented++;
1139 }
1140
Alexey Samsonov59cca132012-12-25 12:04:36 +00001141 FunctionStackPoisoner FSP(F, *this);
1142 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001143
1144 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1145 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1146 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1147 Instruction *CI = NoReturnCalls[i];
1148 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001149 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001150 }
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001151 DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n");
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001152
1153 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001154}
1155
1156static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1157 if (ShadowRedzoneSize == 1) return PoisonByte;
1158 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1159 if (ShadowRedzoneSize == 4)
1160 return (PoisonByte << 24) + (PoisonByte << 16) +
1161 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +00001162 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001163}
1164
1165static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1166 size_t Size,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001167 size_t RZSize,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001168 size_t ShadowGranularity,
1169 uint8_t Magic) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001170 for (size_t i = 0; i < RZSize;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001171 i+= ShadowGranularity, Shadow++) {
1172 if (i + ShadowGranularity <= Size) {
1173 *Shadow = 0; // fully addressable
1174 } else if (i >= Size) {
1175 *Shadow = Magic; // unaddressable
1176 } else {
1177 *Shadow = Size - i; // first Size-i bytes are addressable
1178 }
1179 }
1180}
1181
Alexey Samsonov59cca132012-12-25 12:04:36 +00001182// Workaround for bug 11395: we don't want to instrument stack in functions
1183// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1184// FIXME: remove once the bug 11395 is fixed.
1185bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1186 if (LongSize != 32) return false;
1187 CallInst *CI = dyn_cast<CallInst>(I);
1188 if (!CI || !CI->isInlineAsm()) return false;
1189 if (CI->getNumArgOperands() <= 5) return false;
1190 // We have inline assembly with quite a few arguments.
1191 return true;
1192}
1193
1194void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1195 IRBuilder<> IRB(*C);
1196 AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
1197 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
1198 AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
1199 kAsanStackFreeName, IRB.getVoidTy(),
1200 IntptrTy, IntptrTy, IntptrTy, NULL));
1201 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1202 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1203 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1204 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1205}
1206
1207void FunctionStackPoisoner::poisonRedZones(
1208 const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB, Value *ShadowBase,
1209 bool DoPoison) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001210 size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001211 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1212 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1213 Type *RZPtrTy = PointerType::get(RZTy, 0);
1214
1215 Value *PoisonLeft = ConstantInt::get(RZTy,
1216 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1217 Value *PoisonMid = ConstantInt::get(RZTy,
1218 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1219 Value *PoisonRight = ConstantInt::get(RZTy,
1220 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1221
1222 // poison the first red zone.
1223 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1224
1225 // poison all other red zones.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001226 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001227 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1228 AllocaInst *AI = AllocaVec[i];
1229 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1230 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001231 assert(AlignedSize - SizeInBytes < RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001232 Value *Ptr = NULL;
1233
1234 Pos += AlignedSize;
1235
1236 assert(ShadowBase->getType() == IntptrTy);
1237 if (SizeInBytes < AlignedSize) {
1238 // Poison the partial redzone at right
1239 Ptr = IRB.CreateAdd(
1240 ShadowBase, ConstantInt::get(IntptrTy,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001241 (Pos >> Mapping.Scale) - ShadowRZSize));
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001242 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001243 uint32_t Poison = 0;
1244 if (DoPoison) {
1245 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001246 RedzoneSize(),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001247 1ULL << Mapping.Scale,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001248 kAsanStackPartialRedzoneMagic);
1249 }
1250 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1251 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1252 }
1253
1254 // Poison the full redzone at right.
1255 Ptr = IRB.CreateAdd(ShadowBase,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001256 ConstantInt::get(IntptrTy, Pos >> Mapping.Scale));
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001257 bool LastAlloca = (i == AllocaVec.size() - 1);
1258 Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001259 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1260
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001261 Pos += RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001262 }
1263}
1264
Alexey Samsonov59cca132012-12-25 12:04:36 +00001265void FunctionStackPoisoner::poisonStack() {
Alexey Samsonov59cca132012-12-25 12:04:36 +00001266 uint64_t LocalStackSize = TotalStackSize +
1267 (AllocaVec.size() + 1) * RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001268
Alexey Samsonov59cca132012-12-25 12:04:36 +00001269 bool DoStackMalloc = ASan.CheckUseAfterReturn
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001270 && LocalStackSize <= kMaxStackMallocSize;
1271
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001272 assert(AllocaVec.size() > 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001273 Instruction *InsBefore = AllocaVec[0];
1274 IRBuilder<> IRB(InsBefore);
1275
1276
1277 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1278 AllocaInst *MyAlloca =
1279 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Alexey Samsonov59cca132012-12-25 12:04:36 +00001280 if (ClRealignStack && StackAlignment < RedzoneSize())
1281 StackAlignment = RedzoneSize();
1282 MyAlloca->setAlignment(StackAlignment);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001283 assert(MyAlloca->isStaticAlloca());
1284 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1285 Value *LocalStackBase = OrigStackBase;
1286
1287 if (DoStackMalloc) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001288 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1289 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1290 }
1291
1292 // This string will be parsed by the run-time (DescribeStackAddress).
1293 SmallString<2048> StackDescriptionStorage;
1294 raw_svector_ostream StackDescription(StackDescriptionStorage);
1295 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1296
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001297 // Insert poison calls for lifetime intrinsics for alloca.
1298 bool HavePoisonedAllocas = false;
1299 for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1300 const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1301 IntrinsicInst *II = APC.InsBefore;
1302 AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
1303 assert(AI);
1304 IRBuilder<> IRB(II);
1305 poisonAlloca(AI, APC.Size, IRB, APC.DoPoison);
1306 HavePoisonedAllocas |= APC.DoPoison;
1307 }
1308
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001309 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001310 // Replace Alloca instructions with base+offset.
1311 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1312 AllocaInst *AI = AllocaVec[i];
1313 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1314 StringRef Name = AI->getName();
1315 StackDescription << Pos << " " << SizeInBytes << " "
1316 << Name.size() << " " << Name << " ";
1317 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001318 assert((AlignedSize % RedzoneSize()) == 0);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001319 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001320 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
Alexey Samsonovf985f442012-12-04 01:34:23 +00001321 AI->getType());
Alexey Samsonov1afbb512012-12-12 14:31:53 +00001322 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001323 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001324 Pos += AlignedSize + RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001325 }
1326 assert(Pos == LocalStackSize);
1327
1328 // Write the Magic value and the frame description constant to the redzone.
1329 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1330 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1331 BasePlus0);
1332 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
Alexey Samsonov59cca132012-12-25 12:04:36 +00001333 ConstantInt::get(IntptrTy,
1334 ASan.LongSize/8));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001335 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
Alexey Samsonov9ce84c12012-11-02 12:20:34 +00001336 GlobalVariable *StackDescriptionGlobal =
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001337 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
Alexey Samsonov59cca132012-12-25 12:04:36 +00001338 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1339 IntptrTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001340 IRB.CreateStore(Description, BasePlus1);
1341
1342 // Poison the stack redzones at the entry.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001343 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1344 poisonRedZones(AllocaVec, IRB, ShadowBase, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001345
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001346 // Unpoison the stack before all ret instructions.
1347 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1348 Instruction *Ret = RetVec[i];
1349 IRBuilder<> IRBRet(Ret);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001350 // Mark the current frame as retired.
1351 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1352 BasePlus0);
1353 // Unpoison the stack.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001354 poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001355 if (DoStackMalloc) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001356 // In use-after-return mode, mark the whole stack frame unaddressable.
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001357 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1358 ConstantInt::get(IntptrTy, LocalStackSize),
1359 OrigStackBase);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001360 } else if (HavePoisonedAllocas) {
1361 // If we poisoned some allocas in llvm.lifetime analysis,
1362 // unpoison whole stack frame now.
1363 assert(LocalStackBase == OrigStackBase);
1364 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001365 }
1366 }
1367
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001368 // We are done. Remove the old unused alloca instructions.
1369 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1370 AllocaVec[i]->eraseFromParent();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001371}
Alexey Samsonovf985f442012-12-04 01:34:23 +00001372
Alexey Samsonov59cca132012-12-25 12:04:36 +00001373void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1374 IRBuilder<> IRB, bool DoPoison) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001375 // For now just insert the call to ASan runtime.
1376 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1377 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1378 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1379 : AsanUnpoisonStackMemoryFunc,
1380 AddrArg, SizeArg);
1381}
Alexey Samsonov59cca132012-12-25 12:04:36 +00001382
1383// Handling llvm.lifetime intrinsics for a given %alloca:
1384// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1385// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1386// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1387// could be poisoned by previous llvm.lifetime.end instruction, as the
1388// variable may go in and out of scope several times, e.g. in loops).
1389// (3) if we poisoned at least one %alloca in a function,
1390// unpoison the whole stack frame at function exit.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001391
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001392AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1393 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1394 // We're intested only in allocas we can handle.
1395 return isInterestingAlloca(*AI) ? AI : 0;
1396 // See if we've already calculated (or started to calculate) alloca for a
1397 // given value.
1398 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1399 if (I != AllocaForValue.end())
1400 return I->second;
1401 // Store 0 while we're calculating alloca for value V to avoid
1402 // infinite recursion if the value references itself.
1403 AllocaForValue[V] = 0;
1404 AllocaInst *Res = 0;
1405 if (CastInst *CI = dyn_cast<CastInst>(V))
1406 Res = findAllocaForValue(CI->getOperand(0));
1407 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1408 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1409 Value *IncValue = PN->getIncomingValue(i);
1410 // Allow self-referencing phi-nodes.
1411 if (IncValue == PN) continue;
1412 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1413 // AI for incoming values should exist and should all be equal.
1414 if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1415 return 0;
1416 Res = IncValueAI;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001417 }
Alexey Samsonov59cca132012-12-25 12:04:36 +00001418 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001419 if (Res != 0)
1420 AllocaForValue[V] = Res;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001421 return Res;
1422}