blob: 623c4705061ef9cd316cf3edcdfb826a7433675a [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 Serebryany1479c9b2013-02-20 12:35:15 +000038#include "llvm/Support/CallSite.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000039#include "llvm/Support/CommandLine.h"
40#include "llvm/Support/DataTypes.h"
41#include "llvm/Support/Debug.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000042#include "llvm/Support/raw_ostream.h"
43#include "llvm/Support/system_error.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000044#include "llvm/Target/TargetMachine.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chandler Carruth90230c82013-01-19 08:03:47 +000046#include "llvm/Transforms/Utils/BlackList.h"
Alexey Samsonov1afbb512012-12-12 14:31:53 +000047#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000048#include "llvm/Transforms/Utils/ModuleUtils.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000049#include <algorithm>
Chandler Carruthd04a8d42012-12-03 16:50:05 +000050#include <string>
Kostya Serebryany800e03f2011-11-16 01:35:23 +000051
52using namespace llvm;
53
54static const uint64_t kDefaultShadowScale = 3;
55static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
56static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Kostya Serebryany117de482013-02-11 14:36:01 +000057static const uint64_t kDefaultShort64bitShadowOffset = 0x7FFF8000; // < 2G.
Kostya Serebryany48a615f2013-01-23 12:54:55 +000058static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000059
60static const size_t kMaxStackMallocSize = 1 << 16; // 64K
61static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
62static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
63
64static const char *kAsanModuleCtorName = "asan.module_ctor";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000065static const char *kAsanModuleDtorName = "asan.module_dtor";
66static const int kAsanCtorAndCtorPriority = 1;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000067static const char *kAsanReportErrorTemplate = "__asan_report_";
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +000068static const char *kAsanReportLoadN = "__asan_report_load_n";
69static const char *kAsanReportStoreN = "__asan_report_store_n";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000070static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000071static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +000072static const char *kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
73static const char *kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kostya Serebryany30160562013-03-22 10:37:20 +000074static const char *kAsanInitName = "__asan_init_v3";
Kostya Serebryany95e3cf42012-02-08 21:36:17 +000075static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000076static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
77static const char *kAsanMappingScaleName = "__asan_mapping_scale";
78static const char *kAsanStackMallocName = "__asan_stack_malloc";
79static const char *kAsanStackFreeName = "__asan_stack_free";
Kostya Serebryany51c7c652012-11-20 14:16:08 +000080static const char *kAsanGenPrefix = "__asan_gen_";
Alexey Samsonovf985f442012-12-04 01:34:23 +000081static const char *kAsanPoisonStackMemoryName = "__asan_poison_stack_memory";
82static const char *kAsanUnpoisonStackMemoryName =
83 "__asan_unpoison_stack_memory";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000084
85static const int kAsanStackLeftRedzoneMagic = 0xf1;
86static const int kAsanStackMidRedzoneMagic = 0xf2;
87static const int kAsanStackRightRedzoneMagic = 0xf3;
88static const int kAsanStackPartialRedzoneMagic = 0xf4;
89
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000090// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
91static const size_t kNumberOfAccessSizes = 5;
92
Kostya Serebryany800e03f2011-11-16 01:35:23 +000093// Command-line flags.
94
95// This flag may need to be replaced with -f[no-]asan-reads.
96static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
97 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
98static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
99 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000100static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
101 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
102 cl::Hidden, cl::init(true));
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000103static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
104 cl::desc("use instrumentation with slow path for all accesses"),
105 cl::Hidden, cl::init(false));
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000106// This flag limits the number of instructions to be instrumented
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000107// in any given BB. Normally, this should be set to unlimited (INT_MAX),
108// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
109// set it to 10000.
110static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
111 cl::init(10000),
112 cl::desc("maximal number of instructions to instrument in any given BB"),
113 cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000114// This flag may need to be replaced with -f[no]asan-stack.
115static cl::opt<bool> ClStack("asan-stack",
116 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
117// This flag may need to be replaced with -f[no]asan-use-after-return.
118static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
119 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
120// This flag may need to be replaced with -f[no]asan-globals.
121static cl::opt<bool> ClGlobals("asan-globals",
122 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000123static cl::opt<bool> ClInitializers("asan-initialization-order",
124 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000125static cl::opt<bool> ClMemIntrin("asan-memintrin",
126 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
Kostya Serebryany6c554122012-12-04 06:14:01 +0000127static cl::opt<bool> ClRealignStack("asan-realign-stack",
128 cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true));
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000129static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
130 cl::desc("File containing the list of objects to ignore "
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000131 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000132
133// These flags allow to change the shadow mapping.
134// The shadow mapping looks like
135// Shadow = (Mem >> scale) + (1 << offset_log)
136static cl::opt<int> ClMappingScale("asan-mapping-scale",
137 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
138static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
139 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
Kostya Serebryany117de482013-02-11 14:36:01 +0000140static cl::opt<bool> ClShort64BitOffset("asan-short-64bit-mapping-offset",
141 cl::desc("Use short immediate constant as the mapping offset for 64bit"),
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000142 cl::Hidden, cl::init(true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000143
144// Optimization flags. Not user visible, used mostly for testing
145// and benchmarking the tool.
146static cl::opt<bool> ClOpt("asan-opt",
147 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
148static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
149 cl::desc("Instrument the same temp just once"), cl::Hidden,
150 cl::init(true));
151static cl::opt<bool> ClOptGlobals("asan-opt-globals",
152 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
153
Alexey Samsonovee548272012-11-29 18:14:24 +0000154static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
155 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
156 cl::Hidden, cl::init(false));
157
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000158// Debug flags.
159static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
160 cl::init(0));
161static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
162 cl::Hidden, cl::init(0));
163static cl::opt<std::string> ClDebugFunc("asan-debug-func",
164 cl::Hidden, cl::desc("Debug func"));
165static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
166 cl::Hidden, cl::init(-1));
167static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
168 cl::Hidden, cl::init(-1));
169
170namespace {
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000171/// A set of dynamically initialized globals extracted from metadata.
172class SetOfDynamicallyInitializedGlobals {
173 public:
174 void Init(Module& M) {
175 // Clang generates metadata identifying all dynamically initialized globals.
176 NamedMDNode *DynamicGlobals =
177 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
178 if (!DynamicGlobals)
179 return;
180 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
181 MDNode *MDN = DynamicGlobals->getOperand(i);
182 assert(MDN->getNumOperands() == 1);
183 Value *VG = MDN->getOperand(0);
184 // The optimizer may optimize away a global entirely, in which case we
185 // cannot instrument access to it.
186 if (!VG)
187 continue;
188 DynInitGlobals.insert(cast<GlobalVariable>(VG));
189 }
190 }
191 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
192 private:
193 SmallSet<GlobalValue*, 32> DynInitGlobals;
194};
195
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000196/// This struct defines the shadow mapping using the rule:
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000197/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000198struct ShadowMapping {
199 int Scale;
200 uint64_t Offset;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000201 bool OrShadowOffset;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000202};
203
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000204static ShadowMapping getShadowMapping(const Module &M, int LongSize,
205 bool ZeroBaseShadow) {
206 llvm::Triple TargetTriple(M.getTargetTriple());
207 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Alexander Potapenkoc8a196a2013-02-12 12:41:12 +0000208 bool IsMacOSX = TargetTriple.getOS() == llvm::Triple::MacOSX;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000209 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64;
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000210 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000211
212 ShadowMapping Mapping;
213
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000214 // OR-ing shadow offset if more efficient (at least on x86),
215 // but on ppc64 we have to use add since the shadow offset is not neccesary
216 // 1/8-th of the address space.
Kostya Serebryany117de482013-02-11 14:36:01 +0000217 Mapping.OrShadowOffset = !IsPPC64 && !ClShort64BitOffset;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000218
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000219 Mapping.Offset = (IsAndroid || ZeroBaseShadow) ? 0 :
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000220 (LongSize == 32 ? kDefaultShadowOffset32 :
221 IsPPC64 ? kPPC64_ShadowOffset64 : kDefaultShadowOffset64);
Alexander Potapenkoc8a196a2013-02-12 12:41:12 +0000222 if (!ZeroBaseShadow && ClShort64BitOffset && IsX86_64 && !IsMacOSX) {
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000223 assert(LongSize == 64);
Kostya Serebryany117de482013-02-11 14:36:01 +0000224 Mapping.Offset = kDefaultShort64bitShadowOffset;
Kostya Serebryany39f02942013-02-13 05:14:12 +0000225 }
226 if (!ZeroBaseShadow && ClMappingOffsetLog >= 0) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000227 // Zero offset log is the special case.
228 Mapping.Offset = (ClMappingOffsetLog == 0) ? 0 : 1ULL << ClMappingOffsetLog;
229 }
230
231 Mapping.Scale = kDefaultShadowScale;
232 if (ClMappingScale) {
233 Mapping.Scale = ClMappingScale;
234 }
235
236 return Mapping;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000237}
238
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000239static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000240 // Redzone used for stack and globals is at least 32 bytes.
241 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000242 return std::max(32U, 1U << MappingScale);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000243}
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000244
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000245/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000246struct AddressSanitizer : public FunctionPass {
Alexey Samsonovb4ba5e62013-03-14 12:38:58 +0000247 AddressSanitizer(bool CheckInitOrder = true,
Alexey Samsonovee548272012-11-29 18:14:24 +0000248 bool CheckUseAfterReturn = false,
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000249 bool CheckLifetime = false,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000250 StringRef BlacklistFile = StringRef(),
251 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000252 : FunctionPass(ID),
253 CheckInitOrder(CheckInitOrder || ClInitializers),
254 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000255 CheckLifetime(CheckLifetime || ClCheckLifetime),
256 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000257 : BlacklistFile),
258 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000259 virtual const char *getPassName() const {
260 return "AddressSanitizerFunctionPass";
261 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000262 void instrumentMop(Instruction *I);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000263 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
264 Value *Addr, uint32_t TypeSize, bool IsWrite,
265 Value *SizeArgument);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000266 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
267 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000268 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000269 bool IsWrite, size_t AccessSizeIndex,
270 Value *SizeArgument);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000271 bool instrumentMemIntrinsic(MemIntrinsic *MI);
272 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000273 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000274 Instruction *InsertBefore, bool IsWrite);
275 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000276 bool runOnFunction(Function &F);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000277 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000278 void emitShadowMapping(Module &M, IRBuilder<> &IRB) const;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000279 virtual bool doInitialization(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000280 static char ID; // Pass identification, replacement for typeid
281
282 private:
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000283 void initializeCallbacks(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000284
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000285 bool ShouldInstrumentGlobal(GlobalVariable *G);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000286 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000287 void FindDynamicInitializers(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000288
Alexey Samsonovee548272012-11-29 18:14:24 +0000289 bool CheckInitOrder;
290 bool CheckUseAfterReturn;
291 bool CheckLifetime;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000292 SmallString<64> BlacklistFile;
293 bool ZeroBaseShadow;
294
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000295 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +0000296 DataLayout *TD;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000297 int LongSize;
298 Type *IntptrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000299 ShadowMapping Mapping;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000300 Function *AsanCtorFunction;
301 Function *AsanInitFunction;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000302 Function *AsanHandleNoReturnFunc;
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +0000303 OwningPtr<BlackList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000304 // This array is indexed by AccessIsWrite and log2(AccessSize).
305 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000306 // This array is indexed by AccessIsWrite.
307 Function *AsanErrorCallbackSized[2];
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000308 InlineAsm *EmptyAsm;
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000309 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000310
311 friend struct FunctionStackPoisoner;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000312};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000313
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000314class AddressSanitizerModule : public ModulePass {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000315 public:
Alexey Samsonovb4ba5e62013-03-14 12:38:58 +0000316 AddressSanitizerModule(bool CheckInitOrder = true,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000317 StringRef BlacklistFile = StringRef(),
318 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000319 : ModulePass(ID),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000320 CheckInitOrder(CheckInitOrder || ClInitializers),
321 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000322 : BlacklistFile),
323 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000324 bool runOnModule(Module &M);
325 static char ID; // Pass identification, replacement for typeid
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000326 virtual const char *getPassName() const {
327 return "AddressSanitizerModule";
328 }
Alexey Samsonovf985f442012-12-04 01:34:23 +0000329
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000330 private:
Alexey Samsonov46848582012-12-25 12:28:20 +0000331 void initializeCallbacks(Module &M);
332
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000333 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000334 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000335 size_t RedzoneSize() const {
336 return RedzoneSizeForScale(Mapping.Scale);
337 }
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000338
Alexey Samsonovee548272012-11-29 18:14:24 +0000339 bool CheckInitOrder;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000340 SmallString<64> BlacklistFile;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000341 bool ZeroBaseShadow;
342
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000343 OwningPtr<BlackList> BL;
344 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
345 Type *IntptrTy;
346 LLVMContext *C;
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000347 DataLayout *TD;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000348 ShadowMapping Mapping;
Alexey Samsonov46848582012-12-25 12:28:20 +0000349 Function *AsanPoisonGlobals;
350 Function *AsanUnpoisonGlobals;
351 Function *AsanRegisterGlobals;
352 Function *AsanUnregisterGlobals;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000353};
354
Alexey Samsonov59cca132012-12-25 12:04:36 +0000355// Stack poisoning does not play well with exception handling.
356// When an exception is thrown, we essentially bypass the code
357// that unpoisones the stack. This is why the run-time library has
358// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
359// stack in the interceptor. This however does not work inside the
360// actual function which catches the exception. Most likely because the
361// compiler hoists the load of the shadow value somewhere too high.
362// This causes asan to report a non-existing bug on 453.povray.
363// It sounds like an LLVM bug.
364struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
365 Function &F;
366 AddressSanitizer &ASan;
367 DIBuilder DIB;
368 LLVMContext *C;
369 Type *IntptrTy;
370 Type *IntptrPtrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000371 ShadowMapping Mapping;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000372
373 SmallVector<AllocaInst*, 16> AllocaVec;
374 SmallVector<Instruction*, 8> RetVec;
375 uint64_t TotalStackSize;
376 unsigned StackAlignment;
377
378 Function *AsanStackMallocFunc, *AsanStackFreeFunc;
379 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
380
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000381 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
382 struct AllocaPoisonCall {
383 IntrinsicInst *InsBefore;
384 uint64_t Size;
385 bool DoPoison;
386 };
387 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
388
389 // Maps Value to an AllocaInst from which the Value is originated.
390 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
391 AllocaForValueMapTy AllocaForValue;
392
Alexey Samsonov59cca132012-12-25 12:04:36 +0000393 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
394 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
395 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000396 Mapping(ASan.Mapping),
397 TotalStackSize(0), StackAlignment(1 << Mapping.Scale) {}
Alexey Samsonov59cca132012-12-25 12:04:36 +0000398
399 bool runOnFunction() {
400 if (!ClStack) return false;
401 // Collect alloca, ret, lifetime instructions etc.
402 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
403 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
404 BasicBlock *BB = *DI;
405 visit(*BB);
406 }
407 if (AllocaVec.empty()) return false;
408
409 initializeCallbacks(*F.getParent());
410
411 poisonStack();
412
413 if (ClDebugStack) {
414 DEBUG(dbgs() << F);
415 }
416 return true;
417 }
418
419 // Finds all static Alloca instructions and puts
420 // poisoned red zones around all of them.
421 // Then unpoison everything back before the function returns.
422 void poisonStack();
423
424 // ----------------------- Visitors.
425 /// \brief Collect all Ret instructions.
426 void visitReturnInst(ReturnInst &RI) {
427 RetVec.push_back(&RI);
428 }
429
430 /// \brief Collect Alloca instructions we want (and can) handle.
431 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000432 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000433
434 StackAlignment = std::max(StackAlignment, AI.getAlignment());
435 AllocaVec.push_back(&AI);
436 uint64_t AlignedSize = getAlignedAllocaSize(&AI);
437 TotalStackSize += AlignedSize;
438 }
439
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000440 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
441 /// errors.
442 void visitIntrinsicInst(IntrinsicInst &II) {
443 if (!ASan.CheckLifetime) return;
444 Intrinsic::ID ID = II.getIntrinsicID();
445 if (ID != Intrinsic::lifetime_start &&
446 ID != Intrinsic::lifetime_end)
447 return;
448 // Found lifetime intrinsic, add ASan instrumentation if necessary.
449 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
450 // If size argument is undefined, don't do anything.
451 if (Size->isMinusOne()) return;
452 // Check that size doesn't saturate uint64_t and can
453 // be stored in IntptrTy.
454 const uint64_t SizeValue = Size->getValue().getLimitedValue();
455 if (SizeValue == ~0ULL ||
456 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
457 return;
458 // Find alloca instruction that corresponds to llvm.lifetime argument.
459 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
460 if (!AI) return;
461 bool DoPoison = (ID == Intrinsic::lifetime_end);
462 AllocaPoisonCall APC = {&II, SizeValue, DoPoison};
463 AllocaPoisonCallVec.push_back(APC);
464 }
465
Alexey Samsonov59cca132012-12-25 12:04:36 +0000466 // ---------------------- Helpers.
467 void initializeCallbacks(Module &M);
468
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000469 // Check if we want (and can) handle this alloca.
470 bool isInterestingAlloca(AllocaInst &AI) {
471 return (!AI.isArrayAllocation() &&
472 AI.isStaticAlloca() &&
473 AI.getAllocatedType()->isSized());
474 }
475
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000476 size_t RedzoneSize() const {
477 return RedzoneSizeForScale(Mapping.Scale);
478 }
Alexey Samsonov59cca132012-12-25 12:04:36 +0000479 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
480 Type *Ty = AI->getAllocatedType();
481 uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty);
482 return SizeInBytes;
483 }
484 uint64_t getAlignedSize(uint64_t SizeInBytes) {
485 size_t RZ = RedzoneSize();
486 return ((SizeInBytes + RZ - 1) / RZ) * RZ;
487 }
488 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
489 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
490 return getAlignedSize(SizeInBytes);
491 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000492 /// Finds alloca where the value comes from.
493 AllocaInst *findAllocaForValue(Value *V);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000494 void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
495 Value *ShadowBase, bool DoPoison);
496 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> IRB, bool DoPoison);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000497};
498
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000499} // namespace
500
501char AddressSanitizer::ID = 0;
502INITIALIZE_PASS(AddressSanitizer, "asan",
503 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
504 false, false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000505FunctionPass *llvm::createAddressSanitizerFunctionPass(
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000506 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000507 StringRef BlacklistFile, bool ZeroBaseShadow) {
Alexey Samsonovee548272012-11-29 18:14:24 +0000508 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000509 CheckLifetime, BlacklistFile, ZeroBaseShadow);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000510}
511
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000512char AddressSanitizerModule::ID = 0;
513INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
514 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
515 "ModulePass", false, false)
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000516ModulePass *llvm::createAddressSanitizerModulePass(
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000517 bool CheckInitOrder, StringRef BlacklistFile, bool ZeroBaseShadow) {
518 return new AddressSanitizerModule(CheckInitOrder, BlacklistFile,
519 ZeroBaseShadow);
Alexander Potapenko25878042012-01-23 11:22:43 +0000520}
521
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000522static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
523 size_t Res = CountTrailingZeros_32(TypeSize / 8);
524 assert(Res < kNumberOfAccessSizes);
525 return Res;
526}
527
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000528// Create a constant for Str so that we can pass it to the run-time lib.
529static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000530 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany51116272013-03-18 09:38:39 +0000531 GlobalVariable *GV = new GlobalVariable(M, StrConst->getType(), true,
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000532 GlobalValue::PrivateLinkage, StrConst,
533 kAsanGenPrefix);
Kostya Serebryany51116272013-03-18 09:38:39 +0000534 GV->setUnnamedAddr(true); // Ok to merge these.
535 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
536 return GV;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000537}
538
539static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
540 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000541}
542
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000543Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
544 // Shadow >> scale
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000545 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
546 if (Mapping.Offset == 0)
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000547 return Shadow;
548 // (Shadow >> scale) | offset
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000549 if (Mapping.OrShadowOffset)
550 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
551 else
552 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000553}
554
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000555void AddressSanitizer::instrumentMemIntrinsicParam(
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000556 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000557 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000558 IRBuilder<> IRB(InsertBefore);
559 if (Size->getType() != IntptrTy)
560 Size = IRB.CreateIntCast(Size, IntptrTy, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000561 // Check the first byte.
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000562 instrumentAddress(OrigIns, InsertBefore, Addr, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000563 // Check the last byte.
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000564 IRB.SetInsertPoint(InsertBefore);
565 Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));
566 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
567 Value *AddrLast = IRB.CreateAdd(AddrLong, SizeMinusOne);
568 instrumentAddress(OrigIns, InsertBefore, AddrLast, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000569}
570
571// Instrument memset/memmove/memcpy
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000572bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000573 Value *Dst = MI->getDest();
574 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000575 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000576 Value *Length = MI->getLength();
577
578 Constant *ConstLength = dyn_cast<Constant>(Length);
579 Instruction *InsertBefore = MI;
580 if (ConstLength) {
581 if (ConstLength->isNullValue()) return false;
582 } else {
583 // The size is not a constant so it could be zero -- check at run-time.
584 IRBuilder<> IRB(InsertBefore);
585
586 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000587 Constant::getNullValue(Length->getType()));
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000588 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000589 }
590
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000591 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000592 if (Src)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000593 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000594 return true;
595}
596
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000597// If I is an interesting memory access, return the PointerOperand
598// and set IsWrite. Otherwise return NULL.
599static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000600 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000601 if (!ClInstrumentReads) return NULL;
602 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000603 return LI->getPointerOperand();
604 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000605 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
606 if (!ClInstrumentWrites) return NULL;
607 *IsWrite = true;
608 return SI->getPointerOperand();
609 }
610 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
611 if (!ClInstrumentAtomics) return NULL;
612 *IsWrite = true;
613 return RMW->getPointerOperand();
614 }
615 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
616 if (!ClInstrumentAtomics) return NULL;
617 *IsWrite = true;
618 return XCHG->getPointerOperand();
619 }
620 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000621}
622
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000623void AddressSanitizer::instrumentMop(Instruction *I) {
Axel Naumann3780ad82012-09-17 14:20:57 +0000624 bool IsWrite = false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000625 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
626 assert(Addr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000627 if (ClOpt && ClOptGlobals) {
628 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
629 // If initialization order checking is disabled, a simple access to a
630 // dynamically initialized global is always valid.
Alexey Samsonovee548272012-11-29 18:14:24 +0000631 if (!CheckInitOrder)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000632 return;
633 // If a global variable does not have dynamic initialization we don't
Kostya Serebryany40779062012-11-20 13:11:32 +0000634 // have to instrument it. However, if a global does not have initailizer
635 // at all, we assume it has dynamic initializer (in other TU).
636 if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000637 return;
638 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000639 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000640
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000641 Type *OrigPtrTy = Addr->getType();
642 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
643
644 assert(OrigTy->isSized());
Kostya Serebryany605ff662013-02-18 13:47:02 +0000645 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000646
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000647 assert((TypeSize % 8) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000648
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000649 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check.
650 if (TypeSize == 8 || TypeSize == 16 ||
651 TypeSize == 32 || TypeSize == 64 || TypeSize == 128)
652 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, 0);
653 // Instrument unusual size (but still multiple of 8).
654 // We can not do it with a single check, so we do 1-byte check for the first
655 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
656 // to report the actual access size.
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000657 IRBuilder<> IRB(I);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000658 Value *LastByte = IRB.CreateIntToPtr(
659 IRB.CreateAdd(IRB.CreatePointerCast(Addr, IntptrTy),
660 ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
661 OrigPtrTy);
662 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
663 instrumentAddress(I, I, Addr, 8, IsWrite, Size);
664 instrumentAddress(I, I, LastByte, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000665}
666
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000667// Validate the result of Module::getOrInsertFunction called for an interface
668// function of AddressSanitizer. If the instrumented module defines a function
669// with the same name, their prototypes must match, otherwise
670// getOrInsertFunction returns a bitcast.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000671static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000672 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
673 FuncOrBitcast->dump();
674 report_fatal_error("trying to redefine an AddressSanitizer "
675 "interface function");
676}
677
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000678Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000679 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000680 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000681 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000682 CallInst *Call = SizeArgument
683 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
684 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
685
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000686 // We don't do Call->setDoesNotReturn() because the BB already has
687 // UnreachableInst at the end.
688 // This EmptyAsm is required to avoid callback merge.
689 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000690 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000691}
692
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000693Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000694 Value *ShadowValue,
695 uint32_t TypeSize) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000696 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000697 // Addr & (Granularity - 1)
698 Value *LastAccessedByte = IRB.CreateAnd(
699 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
700 // (Addr & (Granularity - 1)) + size - 1
701 if (TypeSize / 8 > 1)
702 LastAccessedByte = IRB.CreateAdd(
703 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
704 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
705 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000706 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000707 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
708 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
709}
710
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000711void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000712 Instruction *InsertBefore,
713 Value *Addr, uint32_t TypeSize,
714 bool IsWrite, Value *SizeArgument) {
715 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000716 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
717
718 Type *ShadowTy = IntegerType::get(
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000719 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000720 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
721 Value *ShadowPtr = memToShadow(AddrLong, IRB);
722 Value *CmpVal = Constant::getNullValue(ShadowTy);
723 Value *ShadowValue = IRB.CreateLoad(
724 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
725
726 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000727 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000728 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000729 TerminatorInst *CrashTerm = 0;
730
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000731 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000732 TerminatorInst *CheckTerm =
733 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000734 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000735 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000736 IRB.SetInsertPoint(CheckTerm);
737 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000738 BasicBlock *CrashBlock =
739 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000740 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000741 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
742 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000743 } else {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000744 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000745 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000746
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000747 Instruction *Crash = generateCrashCode(
748 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000749 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000750}
751
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000752void AddressSanitizerModule::createInitializerPoisonCalls(
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000753 Module &M, GlobalValue *ModuleName) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000754 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
755 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
756 // If that function is not present, this TU contains no globals, or they have
757 // all been optimized away
758 if (!GlobalInit)
759 return;
760
761 // Set up the arguments to our poison/unpoison functions.
762 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
763
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000764 // Add a call to poison all external globals before the given function starts.
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000765 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
766 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000767
768 // Add calls to unpoison all globals before each return instruction.
769 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
770 I != E; ++I) {
771 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
772 CallInst::Create(AsanUnpoisonGlobals, "", RI);
773 }
774 }
775}
776
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000777bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000778 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000779 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000780
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000781 if (BL->isIn(*G)) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000782 if (!Ty->isSized()) return false;
783 if (!G->hasInitializer()) return false;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000784 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000785 // Touch only those globals that will not be defined in other modules.
786 // Don't handle ODR type linkages since other modules may be built w/o asan.
787 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
788 G->getLinkage() != GlobalVariable::PrivateLinkage &&
789 G->getLinkage() != GlobalVariable::InternalLinkage)
790 return false;
791 // Two problems with thread-locals:
792 // - The address of the main thread's copy can't be computed at link-time.
793 // - Need to poison all copies, not just the main thread's one.
794 if (G->isThreadLocal())
795 return false;
796 // For now, just ignore this Alloca if the alignment is large.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000797 if (G->getAlignment() > RedzoneSize()) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000798
799 // Ignore all the globals with the names starting with "\01L_OBJC_".
800 // Many of those are put into the .cstring section. The linker compresses
801 // that section by removing the spare \0s after the string terminator, so
802 // our redzones get broken.
803 if ((G->getName().find("\01L_OBJC_") == 0) ||
804 (G->getName().find("\01l_OBJC_") == 0)) {
805 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
806 return false;
807 }
808
809 if (G->hasSection()) {
810 StringRef Section(G->getSection());
811 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
812 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
813 // them.
814 if ((Section.find("__OBJC,") == 0) ||
815 (Section.find("__DATA, __objc_") == 0)) {
816 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
817 return false;
818 }
819 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
820 // Constant CFString instances are compiled in the following way:
821 // -- the string buffer is emitted into
822 // __TEXT,__cstring,cstring_literals
823 // -- the constant NSConstantString structure referencing that buffer
824 // is placed into __DATA,__cfstring
825 // Therefore there's no point in placing redzones into __DATA,__cfstring.
826 // Moreover, it causes the linker to crash on OS X 10.7
827 if (Section.find("__DATA,__cfstring") == 0) {
828 DEBUG(dbgs() << "Ignoring CFString: " << *G);
829 return false;
830 }
831 }
832
833 return true;
834}
835
Alexey Samsonov46848582012-12-25 12:28:20 +0000836void AddressSanitizerModule::initializeCallbacks(Module &M) {
837 IRBuilder<> IRB(*C);
838 // Declare our poisoning and unpoisoning functions.
839 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000840 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
Alexey Samsonov46848582012-12-25 12:28:20 +0000841 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
842 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
843 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
844 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
845 // Declare functions that register/unregister globals.
846 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
847 kAsanRegisterGlobalsName, IRB.getVoidTy(),
848 IntptrTy, IntptrTy, NULL));
849 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
850 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
851 kAsanUnregisterGlobalsName,
852 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
853 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
854}
855
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000856// This function replaces all global variables with new variables that have
857// trailing redzones. It also creates a function that poisons
858// redzones and inserts this function into llvm.global_ctors.
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000859bool AddressSanitizerModule::runOnModule(Module &M) {
860 if (!ClGlobals) return false;
861 TD = getAnalysisIfAvailable<DataLayout>();
862 if (!TD)
863 return false;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000864 BL.reset(new BlackList(BlacklistFile));
Alexey Samsonovd6f62c82012-11-29 18:27:01 +0000865 if (BL->isIn(M)) return false;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000866 C = &(M.getContext());
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000867 int LongSize = TD->getPointerSizeInBits();
868 IntptrTy = Type::getIntNTy(*C, LongSize);
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000869 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov46848582012-12-25 12:28:20 +0000870 initializeCallbacks(M);
871 DynamicallyInitializedGlobals.Init(M);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000872
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000873 SmallVector<GlobalVariable *, 16> GlobalsToChange;
874
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000875 for (Module::GlobalListType::iterator G = M.global_begin(),
876 E = M.global_end(); G != E; ++G) {
877 if (ShouldInstrumentGlobal(G))
878 GlobalsToChange.push_back(G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000879 }
880
881 size_t n = GlobalsToChange.size();
882 if (n == 0) return false;
883
884 // A global is described by a structure
885 // size_t beg;
886 // size_t size;
887 // size_t size_with_redzone;
888 // const char *name;
Kostya Serebryany086a4722013-03-18 08:05:29 +0000889 // const char *module_name;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000890 // size_t has_dynamic_init;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000891 // We initialize an array of such structures and pass it to a run-time call.
892 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000893 IntptrTy, IntptrTy,
Kostya Serebryany086a4722013-03-18 08:05:29 +0000894 IntptrTy, IntptrTy, NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000895 SmallVector<Constant *, 16> Initializers(n), DynamicInit;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000896
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000897
898 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
899 assert(CtorFunc);
900 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000901
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000902 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000903
Kostya Serebryany086a4722013-03-18 08:05:29 +0000904 GlobalVariable *ModuleName = createPrivateGlobalForString(
905 M, M.getModuleIdentifier());
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000906 // We shouldn't merge same module names, as this string serves as unique
907 // module ID in runtime.
908 ModuleName->setUnnamedAddr(false);
Kostya Serebryany086a4722013-03-18 08:05:29 +0000909
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000910 for (size_t i = 0; i < n; i++) {
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000911 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000912 GlobalVariable *G = GlobalsToChange[i];
913 PointerType *PtrTy = cast<PointerType>(G->getType());
914 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000915 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000916 uint64_t MinRZ = RedzoneSize();
Kostya Serebryany63f08462013-01-24 10:35:40 +0000917 // MinRZ <= RZ <= kMaxGlobalRedzone
918 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000919 uint64_t RZ = std::max(MinRZ,
Kostya Serebryany63f08462013-01-24 10:35:40 +0000920 std::min(kMaxGlobalRedzone,
921 (SizeInBytes / MinRZ / 4) * MinRZ));
922 uint64_t RightRedzoneSize = RZ;
923 // Round up to MinRZ
924 if (SizeInBytes % MinRZ)
925 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
926 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000927 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000928 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000929 bool GlobalHasDynamicInitializer =
930 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000931 // Don't check initialization order if this global is blacklisted.
Kostya Serebryany7dadac62012-09-05 09:00:18 +0000932 GlobalHasDynamicInitializer &= !BL->isInInit(*G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000933
934 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
935 Constant *NewInitializer = ConstantStruct::get(
936 NewTy, G->getInitializer(),
937 Constant::getNullValue(RightRedZoneTy), NULL);
938
Kostya Serebryany086a4722013-03-18 08:05:29 +0000939 GlobalVariable *Name = createPrivateGlobalForString(M, G->getName());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000940
941 // Create a new global variable with enough space for a redzone.
942 GlobalVariable *NewGlobal = new GlobalVariable(
943 M, NewTy, G->isConstant(), G->getLinkage(),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000944 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000945 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany63f08462013-01-24 10:35:40 +0000946 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000947
948 Value *Indices2[2];
949 Indices2[0] = IRB.getInt32(0);
950 Indices2[1] = IRB.getInt32(0);
951
952 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000953 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000954 NewGlobal->takeName(G);
955 G->eraseFromParent();
956
957 Initializers[i] = ConstantStruct::get(
958 GlobalStructTy,
959 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
960 ConstantInt::get(IntptrTy, SizeInBytes),
961 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
962 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany086a4722013-03-18 08:05:29 +0000963 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000964 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000965 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000966
967 // Populate the first and last globals declared in this TU.
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000968 if (CheckInitOrder && GlobalHasDynamicInitializer)
969 HasDynamicallyInitializedGlobals = true;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000970
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000971 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000972 }
973
974 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
975 GlobalVariable *AllGlobals = new GlobalVariable(
976 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
977 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
978
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000979 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000980 if (CheckInitOrder && HasDynamicallyInitializedGlobals)
981 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000982 IRB.CreateCall2(AsanRegisterGlobals,
983 IRB.CreatePointerCast(AllGlobals, IntptrTy),
984 ConstantInt::get(IntptrTy, n));
985
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000986 // We also need to unregister globals at the end, e.g. when a shared library
987 // gets closed.
988 Function *AsanDtorFunction = Function::Create(
989 FunctionType::get(Type::getVoidTy(*C), false),
990 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
991 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
992 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000993 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
994 IRB.CreatePointerCast(AllGlobals, IntptrTy),
995 ConstantInt::get(IntptrTy, n));
996 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
997
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000998 DEBUG(dbgs() << M);
999 return true;
1000}
1001
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001002void AddressSanitizer::initializeCallbacks(Module &M) {
1003 IRBuilder<> IRB(*C);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001004 // Create __asan_report* callbacks.
1005 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1006 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1007 AccessSizeIndex++) {
1008 // IsWrite and TypeSize are encoded in the function name.
1009 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
1010 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +00001011 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany7846c1c2012-11-07 12:42:18 +00001012 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1013 checkInterfaceFunction(M.getOrInsertFunction(
1014 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001015 }
1016 }
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +00001017 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1018 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1019 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1020 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001021
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001022 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
1023 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
Kostya Serebryanyf7b08222012-07-20 09:54:50 +00001024 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1025 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1026 StringRef(""), StringRef(""),
1027 /*hasSideEffects=*/true);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001028}
1029
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001030void AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const {
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001031 // Tell the values of mapping offset and scale to the run-time.
1032 GlobalValue *asan_mapping_offset =
1033 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1034 ConstantInt::get(IntptrTy, Mapping.Offset),
1035 kAsanMappingOffsetName);
1036 // Read the global, otherwise it may be optimized away.
1037 IRB.CreateLoad(asan_mapping_offset, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001038
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001039 GlobalValue *asan_mapping_scale =
1040 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1041 ConstantInt::get(IntptrTy, Mapping.Scale),
1042 kAsanMappingScaleName);
1043 // Read the global, otherwise it may be optimized away.
1044 IRB.CreateLoad(asan_mapping_scale, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001045}
1046
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001047// virtual
1048bool AddressSanitizer::doInitialization(Module &M) {
1049 // Initialize the private fields. No one has accessed them before.
1050 TD = getAnalysisIfAvailable<DataLayout>();
1051
1052 if (!TD)
1053 return false;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +00001054 BL.reset(new BlackList(BlacklistFile));
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001055 DynamicallyInitializedGlobals.Init(M);
1056
1057 C = &(M.getContext());
1058 LongSize = TD->getPointerSizeInBits();
1059 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001060
1061 AsanCtorFunction = Function::Create(
1062 FunctionType::get(Type::getVoidTy(*C), false),
1063 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1064 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1065 // call __asan_init in the module ctor.
1066 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1067 AsanInitFunction = checkInterfaceFunction(
1068 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1069 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1070 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001071
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001072 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001073 emitShadowMapping(M, IRB);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001074
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001075 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001076 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001077}
1078
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001079bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1080 // For each NSObject descendant having a +load method, this method is invoked
1081 // by the ObjC runtime before any of the static constructors is called.
1082 // Therefore we need to instrument such methods with a call to __asan_init
1083 // at the beginning in order to initialize our runtime before any access to
1084 // the shadow memory.
1085 // We cannot just ignore these methods, because they may call other
1086 // instrumented functions.
1087 if (F.getName().find(" load]") != std::string::npos) {
1088 IRBuilder<> IRB(F.begin()->begin());
1089 IRB.CreateCall(AsanInitFunction);
1090 return true;
1091 }
1092 return false;
1093}
1094
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001095bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001096 if (BL->isIn(F)) return false;
1097 if (&F == AsanCtorFunction) return false;
Kostya Serebryany3797adb2013-03-18 07:33:49 +00001098 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001099 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001100 initializeCallbacks(*F.getParent());
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001101
Kostya Serebryany8eec41f2013-02-26 06:58:09 +00001102 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001103 maybeInsertAsanInitAtFunctionEntry(F);
1104
Bill Wendling831737d2012-12-30 10:32:01 +00001105 if (!F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
Kostya Serebryany8eec41f2013-02-26 06:58:09 +00001106 Attribute::SanitizeAddress))
Bill Wendling67658342012-10-09 07:45:08 +00001107 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001108
1109 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1110 return false;
Bill Wendling67658342012-10-09 07:45:08 +00001111
1112 // We want to instrument every address only once per basic block (unless there
1113 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001114 SmallSet<Value*, 16> TempsToInstrument;
1115 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001116 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001117 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001118
1119 // Fill the set of memory operations to instrument.
1120 for (Function::iterator FI = F.begin(), FE = F.end();
1121 FI != FE; ++FI) {
1122 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001123 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001124 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1125 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +00001126 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001127 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001128 if (ClOpt && ClOptSameTemp) {
1129 if (!TempsToInstrument.insert(Addr))
1130 continue; // We've seen this temp in the current BB.
1131 }
1132 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1133 // ok, take it.
1134 } else {
Kostya Serebryany1479c9b2013-02-20 12:35:15 +00001135 CallSite CS(BI);
1136 if (CS) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001137 // A call inside BB.
1138 TempsToInstrument.clear();
Kostya Serebryany1479c9b2013-02-20 12:35:15 +00001139 if (CS.doesNotReturn())
1140 NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001141 }
1142 continue;
1143 }
1144 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001145 NumInsnsPerBB++;
1146 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1147 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001148 }
1149 }
1150
1151 // Instrument.
1152 int NumInstrumented = 0;
1153 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1154 Instruction *Inst = ToInstrument[i];
1155 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1156 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001157 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001158 instrumentMop(Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001159 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001160 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001161 }
1162 NumInstrumented++;
1163 }
1164
Alexey Samsonov59cca132012-12-25 12:04:36 +00001165 FunctionStackPoisoner FSP(F, *this);
1166 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001167
1168 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1169 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1170 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1171 Instruction *CI = NoReturnCalls[i];
1172 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001173 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001174 }
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001175 DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n");
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001176
1177 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001178}
1179
1180static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1181 if (ShadowRedzoneSize == 1) return PoisonByte;
1182 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1183 if (ShadowRedzoneSize == 4)
1184 return (PoisonByte << 24) + (PoisonByte << 16) +
1185 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +00001186 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001187}
1188
1189static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1190 size_t Size,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001191 size_t RZSize,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001192 size_t ShadowGranularity,
1193 uint8_t Magic) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001194 for (size_t i = 0; i < RZSize;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001195 i+= ShadowGranularity, Shadow++) {
1196 if (i + ShadowGranularity <= Size) {
1197 *Shadow = 0; // fully addressable
1198 } else if (i >= Size) {
1199 *Shadow = Magic; // unaddressable
1200 } else {
1201 *Shadow = Size - i; // first Size-i bytes are addressable
1202 }
1203 }
1204}
1205
Alexey Samsonov59cca132012-12-25 12:04:36 +00001206// Workaround for bug 11395: we don't want to instrument stack in functions
1207// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1208// FIXME: remove once the bug 11395 is fixed.
1209bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1210 if (LongSize != 32) return false;
1211 CallInst *CI = dyn_cast<CallInst>(I);
1212 if (!CI || !CI->isInlineAsm()) return false;
1213 if (CI->getNumArgOperands() <= 5) return false;
1214 // We have inline assembly with quite a few arguments.
1215 return true;
1216}
1217
1218void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1219 IRBuilder<> IRB(*C);
1220 AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
1221 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
1222 AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
1223 kAsanStackFreeName, IRB.getVoidTy(),
1224 IntptrTy, IntptrTy, IntptrTy, NULL));
1225 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1226 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1227 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1228 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1229}
1230
1231void FunctionStackPoisoner::poisonRedZones(
1232 const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB, Value *ShadowBase,
1233 bool DoPoison) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001234 size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001235 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1236 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1237 Type *RZPtrTy = PointerType::get(RZTy, 0);
1238
1239 Value *PoisonLeft = ConstantInt::get(RZTy,
1240 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1241 Value *PoisonMid = ConstantInt::get(RZTy,
1242 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1243 Value *PoisonRight = ConstantInt::get(RZTy,
1244 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1245
1246 // poison the first red zone.
1247 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1248
1249 // poison all other red zones.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001250 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001251 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1252 AllocaInst *AI = AllocaVec[i];
1253 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1254 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001255 assert(AlignedSize - SizeInBytes < RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001256 Value *Ptr = NULL;
1257
1258 Pos += AlignedSize;
1259
1260 assert(ShadowBase->getType() == IntptrTy);
1261 if (SizeInBytes < AlignedSize) {
1262 // Poison the partial redzone at right
1263 Ptr = IRB.CreateAdd(
1264 ShadowBase, ConstantInt::get(IntptrTy,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001265 (Pos >> Mapping.Scale) - ShadowRZSize));
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001266 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001267 uint32_t Poison = 0;
1268 if (DoPoison) {
1269 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001270 RedzoneSize(),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001271 1ULL << Mapping.Scale,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001272 kAsanStackPartialRedzoneMagic);
1273 }
1274 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1275 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1276 }
1277
1278 // Poison the full redzone at right.
1279 Ptr = IRB.CreateAdd(ShadowBase,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001280 ConstantInt::get(IntptrTy, Pos >> Mapping.Scale));
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001281 bool LastAlloca = (i == AllocaVec.size() - 1);
1282 Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001283 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1284
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001285 Pos += RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001286 }
1287}
1288
Alexey Samsonov59cca132012-12-25 12:04:36 +00001289void FunctionStackPoisoner::poisonStack() {
Alexey Samsonov59cca132012-12-25 12:04:36 +00001290 uint64_t LocalStackSize = TotalStackSize +
1291 (AllocaVec.size() + 1) * RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001292
Alexey Samsonov59cca132012-12-25 12:04:36 +00001293 bool DoStackMalloc = ASan.CheckUseAfterReturn
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001294 && LocalStackSize <= kMaxStackMallocSize;
1295
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001296 assert(AllocaVec.size() > 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001297 Instruction *InsBefore = AllocaVec[0];
1298 IRBuilder<> IRB(InsBefore);
1299
1300
1301 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1302 AllocaInst *MyAlloca =
1303 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Alexey Samsonov59cca132012-12-25 12:04:36 +00001304 if (ClRealignStack && StackAlignment < RedzoneSize())
1305 StackAlignment = RedzoneSize();
1306 MyAlloca->setAlignment(StackAlignment);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001307 assert(MyAlloca->isStaticAlloca());
1308 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1309 Value *LocalStackBase = OrigStackBase;
1310
1311 if (DoStackMalloc) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001312 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1313 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1314 }
1315
Kostya Serebryany30160562013-03-22 10:37:20 +00001316 // This string will be parsed by the run-time (DescribeAddressIfStack).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001317 SmallString<2048> StackDescriptionStorage;
1318 raw_svector_ostream StackDescription(StackDescriptionStorage);
Kostya Serebryany30160562013-03-22 10:37:20 +00001319 StackDescription << AllocaVec.size() << " ";
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001320
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001321 // Insert poison calls for lifetime intrinsics for alloca.
1322 bool HavePoisonedAllocas = false;
1323 for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1324 const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1325 IntrinsicInst *II = APC.InsBefore;
1326 AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
1327 assert(AI);
1328 IRBuilder<> IRB(II);
1329 poisonAlloca(AI, APC.Size, IRB, APC.DoPoison);
1330 HavePoisonedAllocas |= APC.DoPoison;
1331 }
1332
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001333 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001334 // Replace Alloca instructions with base+offset.
1335 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1336 AllocaInst *AI = AllocaVec[i];
1337 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1338 StringRef Name = AI->getName();
1339 StackDescription << Pos << " " << SizeInBytes << " "
1340 << Name.size() << " " << Name << " ";
1341 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001342 assert((AlignedSize % RedzoneSize()) == 0);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001343 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001344 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
Alexey Samsonovf985f442012-12-04 01:34:23 +00001345 AI->getType());
Alexey Samsonov1afbb512012-12-12 14:31:53 +00001346 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001347 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001348 Pos += AlignedSize + RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001349 }
1350 assert(Pos == LocalStackSize);
1351
Kostya Serebryany30160562013-03-22 10:37:20 +00001352 // The left-most redzone has enough space for at least 4 pointers.
1353 // Write the Magic value to redzone[0].
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001354 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1355 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1356 BasePlus0);
Kostya Serebryany30160562013-03-22 10:37:20 +00001357 // Write the frame description constant to redzone[1].
1358 Value *BasePlus1 = IRB.CreateIntToPtr(
1359 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1360 IntptrPtrTy);
Alexey Samsonov9ce84c12012-11-02 12:20:34 +00001361 GlobalVariable *StackDescriptionGlobal =
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001362 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
Alexey Samsonov59cca132012-12-25 12:04:36 +00001363 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1364 IntptrTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001365 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryany30160562013-03-22 10:37:20 +00001366 // Write the PC to redzone[2].
1367 Value *BasePlus2 = IRB.CreateIntToPtr(
1368 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1369 2 * ASan.LongSize/8)),
1370 IntptrPtrTy);
1371 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001372
1373 // Poison the stack redzones at the entry.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001374 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1375 poisonRedZones(AllocaVec, IRB, ShadowBase, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001376
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001377 // Unpoison the stack before all ret instructions.
1378 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1379 Instruction *Ret = RetVec[i];
1380 IRBuilder<> IRBRet(Ret);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001381 // Mark the current frame as retired.
1382 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1383 BasePlus0);
1384 // Unpoison the stack.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001385 poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001386 if (DoStackMalloc) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001387 // In use-after-return mode, mark the whole stack frame unaddressable.
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001388 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1389 ConstantInt::get(IntptrTy, LocalStackSize),
1390 OrigStackBase);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001391 } else if (HavePoisonedAllocas) {
1392 // If we poisoned some allocas in llvm.lifetime analysis,
1393 // unpoison whole stack frame now.
1394 assert(LocalStackBase == OrigStackBase);
1395 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001396 }
1397 }
1398
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001399 // We are done. Remove the old unused alloca instructions.
1400 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1401 AllocaVec[i]->eraseFromParent();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001402}
Alexey Samsonovf985f442012-12-04 01:34:23 +00001403
Alexey Samsonov59cca132012-12-25 12:04:36 +00001404void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1405 IRBuilder<> IRB, bool DoPoison) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001406 // For now just insert the call to ASan runtime.
1407 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1408 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1409 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1410 : AsanUnpoisonStackMemoryFunc,
1411 AddrArg, SizeArg);
1412}
Alexey Samsonov59cca132012-12-25 12:04:36 +00001413
1414// Handling llvm.lifetime intrinsics for a given %alloca:
1415// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1416// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1417// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1418// could be poisoned by previous llvm.lifetime.end instruction, as the
1419// variable may go in and out of scope several times, e.g. in loops).
1420// (3) if we poisoned at least one %alloca in a function,
1421// unpoison the whole stack frame at function exit.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001422
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001423AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1424 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1425 // We're intested only in allocas we can handle.
1426 return isInterestingAlloca(*AI) ? AI : 0;
1427 // See if we've already calculated (or started to calculate) alloca for a
1428 // given value.
1429 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1430 if (I != AllocaForValue.end())
1431 return I->second;
1432 // Store 0 while we're calculating alloca for value V to avoid
1433 // infinite recursion if the value references itself.
1434 AllocaForValue[V] = 0;
1435 AllocaInst *Res = 0;
1436 if (CastInst *CI = dyn_cast<CastInst>(V))
1437 Res = findAllocaForValue(CI->getOperand(0));
1438 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1439 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1440 Value *IncValue = PN->getIncomingValue(i);
1441 // Allow self-referencing phi-nodes.
1442 if (IncValue == PN) continue;
1443 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1444 // AI for incoming values should exist and should all be equal.
1445 if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1446 return 0;
1447 Res = IncValueAI;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001448 }
Alexey Samsonov59cca132012-12-25 12:04:36 +00001449 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001450 if (Res != 0)
1451 AllocaForValue[V] = Res;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001452 return Res;
1453}