blob: 75ecc94affbc160b06662734e29d41c23af57127 [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 Serebryany3e1d45b2013-06-03 14:46:56 +000042#include "llvm/Support/Endian.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000043#include "llvm/Support/raw_ostream.h"
44#include "llvm/Support/system_error.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany20985712013-06-26 09:18:17 +000046#include "llvm/Transforms/Utils/Cloning.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"
Peter Collingbourne405515d2013-07-09 22:02:49 +000049#include "llvm/Transforms/Utils/SpecialCaseList.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000050#include <algorithm>
Chandler Carruthd04a8d42012-12-03 16:50:05 +000051#include <string>
Kostya Serebryany800e03f2011-11-16 01:35:23 +000052
53using namespace llvm;
54
55static const uint64_t kDefaultShadowScale = 3;
56static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
57static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Kostya Serebryany117de482013-02-11 14:36:01 +000058static const uint64_t kDefaultShort64bitShadowOffset = 0x7FFF8000; // < 2G.
Kostya Serebryany48a615f2013-01-23 12:54:55 +000059static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +000060static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa8000;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000061
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +000062static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany800e03f2011-11-16 01:35:23 +000063static const size_t kMaxStackMallocSize = 1 << 16; // 64K
64static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
65static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
66
Craig Topper4172a8a2013-07-16 01:17:10 +000067static const char *const kAsanModuleCtorName = "asan.module_ctor";
68static const char *const kAsanModuleDtorName = "asan.module_dtor";
69static const int kAsanCtorAndCtorPriority = 1;
70static const char *const kAsanReportErrorTemplate = "__asan_report_";
71static const char *const kAsanReportLoadN = "__asan_report_load_n";
72static const char *const kAsanReportStoreN = "__asan_report_store_n";
73static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonov48d7d1d2013-08-05 13:19:49 +000074static const char *const kAsanUnregisterGlobalsName =
75 "__asan_unregister_globals";
Craig Topper4172a8a2013-07-16 01:17:10 +000076static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
77static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
78static const char *const kAsanInitName = "__asan_init_v3";
79static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
80static const char *const kAsanMappingOffsetName = "__asan_mapping_offset";
81static const char *const kAsanMappingScaleName = "__asan_mapping_scale";
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +000082static const int kMaxAsanStackMallocSizeClass = 10;
83static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
84static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topper4172a8a2013-07-16 01:17:10 +000085static const char *const kAsanGenPrefix = "__asan_gen_";
86static const char *const kAsanPoisonStackMemoryName =
87 "__asan_poison_stack_memory";
88static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonovf985f442012-12-04 01:34:23 +000089 "__asan_unpoison_stack_memory";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000090
Kostya Serebryany671c3ba2013-09-17 12:14:50 +000091// These constants must match the definitions in the run-time library.
Kostya Serebryany800e03f2011-11-16 01:35:23 +000092static const int kAsanStackLeftRedzoneMagic = 0xf1;
93static const int kAsanStackMidRedzoneMagic = 0xf2;
94static const int kAsanStackRightRedzoneMagic = 0xf3;
95static const int kAsanStackPartialRedzoneMagic = 0xf4;
Kostya Serebryany671c3ba2013-09-17 12:14:50 +000096static const int kAsanStackAfterReturnMagic = 0xf5;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000097
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000098// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
99static const size_t kNumberOfAccessSizes = 5;
100
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000101// Command-line flags.
102
103// This flag may need to be replaced with -f[no-]asan-reads.
104static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
105 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
106static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
107 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000108static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
109 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
110 cl::Hidden, cl::init(true));
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000111static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
112 cl::desc("use instrumentation with slow path for all accesses"),
113 cl::Hidden, cl::init(false));
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000114// This flag limits the number of instructions to be instrumented
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000115// in any given BB. Normally, this should be set to unlimited (INT_MAX),
116// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
117// set it to 10000.
118static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
119 cl::init(10000),
120 cl::desc("maximal number of instructions to instrument in any given BB"),
121 cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000122// This flag may need to be replaced with -f[no]asan-stack.
123static cl::opt<bool> ClStack("asan-stack",
124 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
125// This flag may need to be replaced with -f[no]asan-use-after-return.
126static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
127 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
128// This flag may need to be replaced with -f[no]asan-globals.
129static cl::opt<bool> ClGlobals("asan-globals",
130 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000131static cl::opt<bool> ClInitializers("asan-initialization-order",
132 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000133static cl::opt<bool> ClMemIntrin("asan-memintrin",
134 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
Kostya Serebryany6c554122012-12-04 06:14:01 +0000135static cl::opt<bool> ClRealignStack("asan-realign-stack",
136 cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true));
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000137static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
138 cl::desc("File containing the list of objects to ignore "
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000139 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000140
Kostya Serebryany20985712013-06-26 09:18:17 +0000141// This is an experimental feature that will allow to choose between
142// instrumented and non-instrumented code at link-time.
143// If this option is on, just before instrumenting a function we create its
144// clone; if the function is not changed by asan the clone is deleted.
145// If we end up with a clone, we put the instrumented function into a section
146// called "ASAN" and the uninstrumented function into a section called "NOASAN".
147//
148// This is still a prototype, we need to figure out a way to keep two copies of
149// a function so that the linker can easily choose one of them.
150static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
151 cl::desc("Keep uninstrumented copies of functions"),
152 cl::Hidden, cl::init(false));
153
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000154// These flags allow to change the shadow mapping.
155// The shadow mapping looks like
156// Shadow = (Mem >> scale) + (1 << offset_log)
157static cl::opt<int> ClMappingScale("asan-mapping-scale",
158 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
159static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
160 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
Kostya Serebryany117de482013-02-11 14:36:01 +0000161static cl::opt<bool> ClShort64BitOffset("asan-short-64bit-mapping-offset",
162 cl::desc("Use short immediate constant as the mapping offset for 64bit"),
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000163 cl::Hidden, cl::init(true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000164
165// Optimization flags. Not user visible, used mostly for testing
166// and benchmarking the tool.
167static cl::opt<bool> ClOpt("asan-opt",
168 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
169static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
170 cl::desc("Instrument the same temp just once"), cl::Hidden,
171 cl::init(true));
172static cl::opt<bool> ClOptGlobals("asan-opt-globals",
173 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
174
Alexey Samsonovee548272012-11-29 18:14:24 +0000175static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
176 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
177 cl::Hidden, cl::init(false));
178
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000179// Debug flags.
180static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
181 cl::init(0));
182static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
183 cl::Hidden, cl::init(0));
184static cl::opt<std::string> ClDebugFunc("asan-debug-func",
185 cl::Hidden, cl::desc("Debug func"));
186static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
187 cl::Hidden, cl::init(-1));
188static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
189 cl::Hidden, cl::init(-1));
190
191namespace {
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000192/// A set of dynamically initialized globals extracted from metadata.
193class SetOfDynamicallyInitializedGlobals {
194 public:
195 void Init(Module& M) {
196 // Clang generates metadata identifying all dynamically initialized globals.
197 NamedMDNode *DynamicGlobals =
198 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
199 if (!DynamicGlobals)
200 return;
201 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
202 MDNode *MDN = DynamicGlobals->getOperand(i);
203 assert(MDN->getNumOperands() == 1);
204 Value *VG = MDN->getOperand(0);
205 // The optimizer may optimize away a global entirely, in which case we
206 // cannot instrument access to it.
207 if (!VG)
208 continue;
209 DynInitGlobals.insert(cast<GlobalVariable>(VG));
210 }
211 }
212 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
213 private:
214 SmallSet<GlobalValue*, 32> DynInitGlobals;
215};
216
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000217/// This struct defines the shadow mapping using the rule:
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000218/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000219struct ShadowMapping {
220 int Scale;
221 uint64_t Offset;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000222 bool OrShadowOffset;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000223};
224
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000225static ShadowMapping getShadowMapping(const Module &M, int LongSize,
226 bool ZeroBaseShadow) {
227 llvm::Triple TargetTriple(M.getTargetTriple());
228 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Alexander Potapenkoc8a196a2013-02-12 12:41:12 +0000229 bool IsMacOSX = TargetTriple.getOS() == llvm::Triple::MacOSX;
Bill Schmidtf38cc382013-07-26 01:35:43 +0000230 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
231 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000232 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +0000233 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
234 TargetTriple.getArch() == llvm::Triple::mipsel;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000235
236 ShadowMapping Mapping;
237
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000238 // OR-ing shadow offset if more efficient (at least on x86),
239 // but on ppc64 we have to use add since the shadow offset is not neccesary
240 // 1/8-th of the address space.
Kostya Serebryany117de482013-02-11 14:36:01 +0000241 Mapping.OrShadowOffset = !IsPPC64 && !ClShort64BitOffset;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000242
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000243 Mapping.Offset = (IsAndroid || ZeroBaseShadow) ? 0 :
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +0000244 (LongSize == 32 ?
245 (IsMIPS32 ? kMIPS32_ShadowOffset32 : kDefaultShadowOffset32) :
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000246 IsPPC64 ? kPPC64_ShadowOffset64 : kDefaultShadowOffset64);
Alexander Potapenkoc8a196a2013-02-12 12:41:12 +0000247 if (!ZeroBaseShadow && ClShort64BitOffset && IsX86_64 && !IsMacOSX) {
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000248 assert(LongSize == 64);
Kostya Serebryany117de482013-02-11 14:36:01 +0000249 Mapping.Offset = kDefaultShort64bitShadowOffset;
Kostya Serebryany39f02942013-02-13 05:14:12 +0000250 }
251 if (!ZeroBaseShadow && ClMappingOffsetLog >= 0) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000252 // Zero offset log is the special case.
253 Mapping.Offset = (ClMappingOffsetLog == 0) ? 0 : 1ULL << ClMappingOffsetLog;
254 }
255
256 Mapping.Scale = kDefaultShadowScale;
257 if (ClMappingScale) {
258 Mapping.Scale = ClMappingScale;
259 }
260
261 return Mapping;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000262}
263
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000264static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000265 // Redzone used for stack and globals is at least 32 bytes.
266 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000267 return std::max(32U, 1U << MappingScale);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000268}
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000269
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000270/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000271struct AddressSanitizer : public FunctionPass {
Alexey Samsonovb4ba5e62013-03-14 12:38:58 +0000272 AddressSanitizer(bool CheckInitOrder = true,
Alexey Samsonovee548272012-11-29 18:14:24 +0000273 bool CheckUseAfterReturn = false,
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000274 bool CheckLifetime = false,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000275 StringRef BlacklistFile = StringRef(),
276 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000277 : FunctionPass(ID),
278 CheckInitOrder(CheckInitOrder || ClInitializers),
279 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000280 CheckLifetime(CheckLifetime || ClCheckLifetime),
281 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000282 : BlacklistFile),
283 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000284 virtual const char *getPassName() const {
285 return "AddressSanitizerFunctionPass";
286 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000287 void instrumentMop(Instruction *I);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000288 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
289 Value *Addr, uint32_t TypeSize, bool IsWrite,
290 Value *SizeArgument);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000291 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
292 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000293 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000294 bool IsWrite, size_t AccessSizeIndex,
295 Value *SizeArgument);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000296 bool instrumentMemIntrinsic(MemIntrinsic *MI);
297 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000298 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000299 Instruction *InsertBefore, bool IsWrite);
300 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000301 bool runOnFunction(Function &F);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000302 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000303 void emitShadowMapping(Module &M, IRBuilder<> &IRB) const;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000304 virtual bool doInitialization(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000305 static char ID; // Pass identification, replacement for typeid
306
307 private:
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000308 void initializeCallbacks(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000309
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000310 bool ShouldInstrumentGlobal(GlobalVariable *G);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000311 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000312 void FindDynamicInitializers(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000313
Alexey Samsonovee548272012-11-29 18:14:24 +0000314 bool CheckInitOrder;
315 bool CheckUseAfterReturn;
316 bool CheckLifetime;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000317 SmallString<64> BlacklistFile;
318 bool ZeroBaseShadow;
319
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000320 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +0000321 DataLayout *TD;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000322 int LongSize;
323 Type *IntptrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000324 ShadowMapping Mapping;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000325 Function *AsanCtorFunction;
326 Function *AsanInitFunction;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000327 Function *AsanHandleNoReturnFunc;
Peter Collingbourne405515d2013-07-09 22:02:49 +0000328 OwningPtr<SpecialCaseList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000329 // This array is indexed by AccessIsWrite and log2(AccessSize).
330 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000331 // This array is indexed by AccessIsWrite.
332 Function *AsanErrorCallbackSized[2];
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000333 InlineAsm *EmptyAsm;
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000334 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000335
336 friend struct FunctionStackPoisoner;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000337};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000338
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000339class AddressSanitizerModule : public ModulePass {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000340 public:
Alexey Samsonovb4ba5e62013-03-14 12:38:58 +0000341 AddressSanitizerModule(bool CheckInitOrder = true,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000342 StringRef BlacklistFile = StringRef(),
343 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000344 : ModulePass(ID),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000345 CheckInitOrder(CheckInitOrder || ClInitializers),
346 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000347 : BlacklistFile),
348 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000349 bool runOnModule(Module &M);
350 static char ID; // Pass identification, replacement for typeid
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000351 virtual const char *getPassName() const {
352 return "AddressSanitizerModule";
353 }
Alexey Samsonovf985f442012-12-04 01:34:23 +0000354
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000355 private:
Alexey Samsonov46848582012-12-25 12:28:20 +0000356 void initializeCallbacks(Module &M);
357
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000358 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000359 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000360 size_t RedzoneSize() const {
361 return RedzoneSizeForScale(Mapping.Scale);
362 }
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000363
Alexey Samsonovee548272012-11-29 18:14:24 +0000364 bool CheckInitOrder;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000365 SmallString<64> BlacklistFile;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000366 bool ZeroBaseShadow;
367
Peter Collingbourne405515d2013-07-09 22:02:49 +0000368 OwningPtr<SpecialCaseList> BL;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000369 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
370 Type *IntptrTy;
371 LLVMContext *C;
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000372 DataLayout *TD;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000373 ShadowMapping Mapping;
Alexey Samsonov46848582012-12-25 12:28:20 +0000374 Function *AsanPoisonGlobals;
375 Function *AsanUnpoisonGlobals;
376 Function *AsanRegisterGlobals;
377 Function *AsanUnregisterGlobals;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000378};
379
Alexey Samsonov59cca132012-12-25 12:04:36 +0000380// Stack poisoning does not play well with exception handling.
381// When an exception is thrown, we essentially bypass the code
382// that unpoisones the stack. This is why the run-time library has
383// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
384// stack in the interceptor. This however does not work inside the
385// actual function which catches the exception. Most likely because the
386// compiler hoists the load of the shadow value somewhere too high.
387// This causes asan to report a non-existing bug on 453.povray.
388// It sounds like an LLVM bug.
389struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
390 Function &F;
391 AddressSanitizer &ASan;
392 DIBuilder DIB;
393 LLVMContext *C;
394 Type *IntptrTy;
395 Type *IntptrPtrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000396 ShadowMapping Mapping;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000397
398 SmallVector<AllocaInst*, 16> AllocaVec;
399 SmallVector<Instruction*, 8> RetVec;
400 uint64_t TotalStackSize;
401 unsigned StackAlignment;
402
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +0000403 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
404 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov59cca132012-12-25 12:04:36 +0000405 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
406
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000407 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
408 struct AllocaPoisonCall {
409 IntrinsicInst *InsBefore;
410 uint64_t Size;
411 bool DoPoison;
412 };
413 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
414
415 // Maps Value to an AllocaInst from which the Value is originated.
416 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
417 AllocaForValueMapTy AllocaForValue;
418
Alexey Samsonov59cca132012-12-25 12:04:36 +0000419 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
420 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
421 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000422 Mapping(ASan.Mapping),
423 TotalStackSize(0), StackAlignment(1 << Mapping.Scale) {}
Alexey Samsonov59cca132012-12-25 12:04:36 +0000424
425 bool runOnFunction() {
426 if (!ClStack) return false;
427 // Collect alloca, ret, lifetime instructions etc.
428 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
429 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
430 BasicBlock *BB = *DI;
431 visit(*BB);
432 }
433 if (AllocaVec.empty()) return false;
434
435 initializeCallbacks(*F.getParent());
436
437 poisonStack();
438
439 if (ClDebugStack) {
440 DEBUG(dbgs() << F);
441 }
442 return true;
443 }
444
445 // Finds all static Alloca instructions and puts
446 // poisoned red zones around all of them.
447 // Then unpoison everything back before the function returns.
448 void poisonStack();
449
450 // ----------------------- Visitors.
451 /// \brief Collect all Ret instructions.
452 void visitReturnInst(ReturnInst &RI) {
453 RetVec.push_back(&RI);
454 }
455
456 /// \brief Collect Alloca instructions we want (and can) handle.
457 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000458 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000459
460 StackAlignment = std::max(StackAlignment, AI.getAlignment());
461 AllocaVec.push_back(&AI);
Kostya Serebryanyd4429212013-06-26 09:49:52 +0000462 uint64_t AlignedSize = getAlignedAllocaSize(&AI);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000463 TotalStackSize += AlignedSize;
464 }
465
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000466 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
467 /// errors.
468 void visitIntrinsicInst(IntrinsicInst &II) {
469 if (!ASan.CheckLifetime) return;
470 Intrinsic::ID ID = II.getIntrinsicID();
471 if (ID != Intrinsic::lifetime_start &&
472 ID != Intrinsic::lifetime_end)
473 return;
474 // Found lifetime intrinsic, add ASan instrumentation if necessary.
475 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
476 // If size argument is undefined, don't do anything.
477 if (Size->isMinusOne()) return;
478 // Check that size doesn't saturate uint64_t and can
479 // be stored in IntptrTy.
480 const uint64_t SizeValue = Size->getValue().getLimitedValue();
481 if (SizeValue == ~0ULL ||
482 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
483 return;
484 // Find alloca instruction that corresponds to llvm.lifetime argument.
485 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
486 if (!AI) return;
487 bool DoPoison = (ID == Intrinsic::lifetime_end);
488 AllocaPoisonCall APC = {&II, SizeValue, DoPoison};
489 AllocaPoisonCallVec.push_back(APC);
490 }
491
Alexey Samsonov59cca132012-12-25 12:04:36 +0000492 // ---------------------- Helpers.
493 void initializeCallbacks(Module &M);
494
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000495 // Check if we want (and can) handle this alloca.
Jakub Staszak4c710642013-08-09 20:53:48 +0000496 bool isInterestingAlloca(AllocaInst &AI) const {
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000497 return (!AI.isArrayAllocation() &&
498 AI.isStaticAlloca() &&
Kostya Serebryanyd4429212013-06-26 09:49:52 +0000499 AI.getAlignment() <= RedzoneSize() &&
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000500 AI.getAllocatedType()->isSized());
501 }
502
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000503 size_t RedzoneSize() const {
504 return RedzoneSizeForScale(Mapping.Scale);
505 }
Jakub Staszak4c710642013-08-09 20:53:48 +0000506 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
Alexey Samsonov59cca132012-12-25 12:04:36 +0000507 Type *Ty = AI->getAllocatedType();
508 uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty);
509 return SizeInBytes;
510 }
Jakub Staszak4c710642013-08-09 20:53:48 +0000511 uint64_t getAlignedSize(uint64_t SizeInBytes) const {
Alexey Samsonov59cca132012-12-25 12:04:36 +0000512 size_t RZ = RedzoneSize();
513 return ((SizeInBytes + RZ - 1) / RZ) * RZ;
514 }
Jakub Staszak4c710642013-08-09 20:53:48 +0000515 uint64_t getAlignedAllocaSize(AllocaInst *AI) const {
Alexey Samsonov59cca132012-12-25 12:04:36 +0000516 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
517 return getAlignedSize(SizeInBytes);
518 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000519 /// Finds alloca where the value comes from.
520 AllocaInst *findAllocaForValue(Value *V);
Jakub Staszak4c710642013-08-09 20:53:48 +0000521 void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> &IRB,
Alexey Samsonov59cca132012-12-25 12:04:36 +0000522 Value *ShadowBase, bool DoPoison);
Jakub Staszak4c710642013-08-09 20:53:48 +0000523 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryany671c3ba2013-09-17 12:14:50 +0000524
525 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
526 int Size);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000527};
528
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000529} // namespace
530
531char AddressSanitizer::ID = 0;
532INITIALIZE_PASS(AddressSanitizer, "asan",
533 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
534 false, false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000535FunctionPass *llvm::createAddressSanitizerFunctionPass(
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000536 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000537 StringRef BlacklistFile, bool ZeroBaseShadow) {
Alexey Samsonovee548272012-11-29 18:14:24 +0000538 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000539 CheckLifetime, BlacklistFile, ZeroBaseShadow);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000540}
541
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000542char AddressSanitizerModule::ID = 0;
543INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
544 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
545 "ModulePass", false, false)
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000546ModulePass *llvm::createAddressSanitizerModulePass(
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000547 bool CheckInitOrder, StringRef BlacklistFile, bool ZeroBaseShadow) {
548 return new AddressSanitizerModule(CheckInitOrder, BlacklistFile,
549 ZeroBaseShadow);
Alexander Potapenko25878042012-01-23 11:22:43 +0000550}
551
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000552static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerc6af2432013-05-24 22:23:49 +0000553 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000554 assert(Res < kNumberOfAccessSizes);
555 return Res;
556}
557
Bill Wendling55a1a592013-08-06 22:52:42 +0000558// \brief Create a constant for Str so that we can pass it to the run-time lib.
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000559static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000560 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany51116272013-03-18 09:38:39 +0000561 GlobalVariable *GV = new GlobalVariable(M, StrConst->getType(), true,
Bill Wendling55a1a592013-08-06 22:52:42 +0000562 GlobalValue::InternalLinkage, StrConst,
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000563 kAsanGenPrefix);
Kostya Serebryany51116272013-03-18 09:38:39 +0000564 GV->setUnnamedAddr(true); // Ok to merge these.
565 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
566 return GV;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000567}
568
569static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
570 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000571}
572
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000573Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
574 // Shadow >> scale
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000575 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
576 if (Mapping.Offset == 0)
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000577 return Shadow;
578 // (Shadow >> scale) | offset
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000579 if (Mapping.OrShadowOffset)
580 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
581 else
582 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000583}
584
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000585void AddressSanitizer::instrumentMemIntrinsicParam(
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000586 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000587 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000588 IRBuilder<> IRB(InsertBefore);
589 if (Size->getType() != IntptrTy)
590 Size = IRB.CreateIntCast(Size, IntptrTy, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000591 // Check the first byte.
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000592 instrumentAddress(OrigIns, InsertBefore, Addr, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000593 // Check the last byte.
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000594 IRB.SetInsertPoint(InsertBefore);
595 Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));
596 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
597 Value *AddrLast = IRB.CreateAdd(AddrLong, SizeMinusOne);
598 instrumentAddress(OrigIns, InsertBefore, AddrLast, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000599}
600
601// Instrument memset/memmove/memcpy
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000602bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000603 Value *Dst = MI->getDest();
604 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000605 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000606 Value *Length = MI->getLength();
607
608 Constant *ConstLength = dyn_cast<Constant>(Length);
609 Instruction *InsertBefore = MI;
610 if (ConstLength) {
611 if (ConstLength->isNullValue()) return false;
612 } else {
613 // The size is not a constant so it could be zero -- check at run-time.
614 IRBuilder<> IRB(InsertBefore);
615
616 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000617 Constant::getNullValue(Length->getType()));
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000618 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000619 }
620
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000621 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000622 if (Src)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000623 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000624 return true;
625}
626
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000627// If I is an interesting memory access, return the PointerOperand
628// and set IsWrite. Otherwise return NULL.
629static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000630 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000631 if (!ClInstrumentReads) return NULL;
632 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000633 return LI->getPointerOperand();
634 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000635 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
636 if (!ClInstrumentWrites) return NULL;
637 *IsWrite = true;
638 return SI->getPointerOperand();
639 }
640 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
641 if (!ClInstrumentAtomics) return NULL;
642 *IsWrite = true;
643 return RMW->getPointerOperand();
644 }
645 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
646 if (!ClInstrumentAtomics) return NULL;
647 *IsWrite = true;
648 return XCHG->getPointerOperand();
649 }
650 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000651}
652
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000653void AddressSanitizer::instrumentMop(Instruction *I) {
Axel Naumann3780ad82012-09-17 14:20:57 +0000654 bool IsWrite = false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000655 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
656 assert(Addr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000657 if (ClOpt && ClOptGlobals) {
658 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
659 // If initialization order checking is disabled, a simple access to a
660 // dynamically initialized global is always valid.
Alexey Samsonovee548272012-11-29 18:14:24 +0000661 if (!CheckInitOrder)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000662 return;
663 // If a global variable does not have dynamic initialization we don't
Kostya Serebryany40779062012-11-20 13:11:32 +0000664 // have to instrument it. However, if a global does not have initailizer
665 // at all, we assume it has dynamic initializer (in other TU).
666 if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000667 return;
668 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000669 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000670
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000671 Type *OrigPtrTy = Addr->getType();
672 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
673
674 assert(OrigTy->isSized());
Kostya Serebryany605ff662013-02-18 13:47:02 +0000675 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000676
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000677 assert((TypeSize % 8) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000678
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000679 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check.
680 if (TypeSize == 8 || TypeSize == 16 ||
681 TypeSize == 32 || TypeSize == 64 || TypeSize == 128)
682 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, 0);
683 // Instrument unusual size (but still multiple of 8).
684 // We can not do it with a single check, so we do 1-byte check for the first
685 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
686 // to report the actual access size.
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000687 IRBuilder<> IRB(I);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000688 Value *LastByte = IRB.CreateIntToPtr(
689 IRB.CreateAdd(IRB.CreatePointerCast(Addr, IntptrTy),
690 ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
691 OrigPtrTy);
692 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
693 instrumentAddress(I, I, Addr, 8, IsWrite, Size);
694 instrumentAddress(I, I, LastByte, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000695}
696
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000697// Validate the result of Module::getOrInsertFunction called for an interface
698// function of AddressSanitizer. If the instrumented module defines a function
699// with the same name, their prototypes must match, otherwise
700// getOrInsertFunction returns a bitcast.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000701static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000702 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
703 FuncOrBitcast->dump();
704 report_fatal_error("trying to redefine an AddressSanitizer "
705 "interface function");
706}
707
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000708Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000709 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000710 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000711 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000712 CallInst *Call = SizeArgument
713 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
714 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
715
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000716 // We don't do Call->setDoesNotReturn() because the BB already has
717 // UnreachableInst at the end.
718 // This EmptyAsm is required to avoid callback merge.
719 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000720 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000721}
722
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000723Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000724 Value *ShadowValue,
725 uint32_t TypeSize) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000726 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000727 // Addr & (Granularity - 1)
728 Value *LastAccessedByte = IRB.CreateAnd(
729 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
730 // (Addr & (Granularity - 1)) + size - 1
731 if (TypeSize / 8 > 1)
732 LastAccessedByte = IRB.CreateAdd(
733 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
734 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
735 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000736 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000737 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
738 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
739}
740
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000741void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000742 Instruction *InsertBefore,
743 Value *Addr, uint32_t TypeSize,
744 bool IsWrite, Value *SizeArgument) {
745 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000746 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
747
748 Type *ShadowTy = IntegerType::get(
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000749 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000750 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
751 Value *ShadowPtr = memToShadow(AddrLong, IRB);
752 Value *CmpVal = Constant::getNullValue(ShadowTy);
753 Value *ShadowValue = IRB.CreateLoad(
754 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
755
756 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000757 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000758 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000759 TerminatorInst *CrashTerm = 0;
760
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000761 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000762 TerminatorInst *CheckTerm =
763 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000764 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000765 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000766 IRB.SetInsertPoint(CheckTerm);
767 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000768 BasicBlock *CrashBlock =
769 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000770 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000771 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
772 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000773 } else {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000774 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000775 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000776
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000777 Instruction *Crash = generateCrashCode(
778 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000779 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000780}
781
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000782void AddressSanitizerModule::createInitializerPoisonCalls(
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000783 Module &M, GlobalValue *ModuleName) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000784 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
785 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
786 // If that function is not present, this TU contains no globals, or they have
787 // all been optimized away
788 if (!GlobalInit)
789 return;
790
791 // Set up the arguments to our poison/unpoison functions.
792 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
793
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000794 // Add a call to poison all external globals before the given function starts.
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000795 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
796 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000797
798 // Add calls to unpoison all globals before each return instruction.
799 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
800 I != E; ++I) {
801 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
802 CallInst::Create(AsanUnpoisonGlobals, "", RI);
803 }
804 }
805}
806
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000807bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000808 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000809 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000810
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000811 if (BL->isIn(*G)) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000812 if (!Ty->isSized()) return false;
813 if (!G->hasInitializer()) return false;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000814 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000815 // Touch only those globals that will not be defined in other modules.
816 // Don't handle ODR type linkages since other modules may be built w/o asan.
817 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
818 G->getLinkage() != GlobalVariable::PrivateLinkage &&
819 G->getLinkage() != GlobalVariable::InternalLinkage)
820 return false;
821 // Two problems with thread-locals:
822 // - The address of the main thread's copy can't be computed at link-time.
823 // - Need to poison all copies, not just the main thread's one.
824 if (G->isThreadLocal())
825 return false;
826 // For now, just ignore this Alloca if the alignment is large.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000827 if (G->getAlignment() > RedzoneSize()) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000828
829 // Ignore all the globals with the names starting with "\01L_OBJC_".
830 // Many of those are put into the .cstring section. The linker compresses
831 // that section by removing the spare \0s after the string terminator, so
832 // our redzones get broken.
833 if ((G->getName().find("\01L_OBJC_") == 0) ||
834 (G->getName().find("\01l_OBJC_") == 0)) {
835 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
836 return false;
837 }
838
839 if (G->hasSection()) {
840 StringRef Section(G->getSection());
841 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
842 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
843 // them.
844 if ((Section.find("__OBJC,") == 0) ||
845 (Section.find("__DATA, __objc_") == 0)) {
846 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
847 return false;
848 }
849 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
850 // Constant CFString instances are compiled in the following way:
851 // -- the string buffer is emitted into
852 // __TEXT,__cstring,cstring_literals
853 // -- the constant NSConstantString structure referencing that buffer
854 // is placed into __DATA,__cfstring
855 // Therefore there's no point in placing redzones into __DATA,__cfstring.
856 // Moreover, it causes the linker to crash on OS X 10.7
857 if (Section.find("__DATA,__cfstring") == 0) {
858 DEBUG(dbgs() << "Ignoring CFString: " << *G);
859 return false;
860 }
861 }
862
863 return true;
864}
865
Alexey Samsonov46848582012-12-25 12:28:20 +0000866void AddressSanitizerModule::initializeCallbacks(Module &M) {
867 IRBuilder<> IRB(*C);
868 // Declare our poisoning and unpoisoning functions.
869 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000870 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
Alexey Samsonov46848582012-12-25 12:28:20 +0000871 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
872 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
873 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
874 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
875 // Declare functions that register/unregister globals.
876 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
877 kAsanRegisterGlobalsName, IRB.getVoidTy(),
878 IntptrTy, IntptrTy, NULL));
879 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
880 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
881 kAsanUnregisterGlobalsName,
882 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
883 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
884}
885
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000886// This function replaces all global variables with new variables that have
887// trailing redzones. It also creates a function that poisons
888// redzones and inserts this function into llvm.global_ctors.
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000889bool AddressSanitizerModule::runOnModule(Module &M) {
890 if (!ClGlobals) return false;
891 TD = getAnalysisIfAvailable<DataLayout>();
892 if (!TD)
893 return false;
Alexey Samsonove39e1312013-08-12 11:46:09 +0000894 BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
Alexey Samsonovd6f62c82012-11-29 18:27:01 +0000895 if (BL->isIn(M)) return false;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000896 C = &(M.getContext());
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000897 int LongSize = TD->getPointerSizeInBits();
898 IntptrTy = Type::getIntNTy(*C, LongSize);
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000899 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov46848582012-12-25 12:28:20 +0000900 initializeCallbacks(M);
901 DynamicallyInitializedGlobals.Init(M);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000902
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000903 SmallVector<GlobalVariable *, 16> GlobalsToChange;
904
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000905 for (Module::GlobalListType::iterator G = M.global_begin(),
906 E = M.global_end(); G != E; ++G) {
907 if (ShouldInstrumentGlobal(G))
908 GlobalsToChange.push_back(G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000909 }
910
911 size_t n = GlobalsToChange.size();
912 if (n == 0) return false;
913
914 // A global is described by a structure
915 // size_t beg;
916 // size_t size;
917 // size_t size_with_redzone;
918 // const char *name;
Kostya Serebryany086a4722013-03-18 08:05:29 +0000919 // const char *module_name;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000920 // size_t has_dynamic_init;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000921 // We initialize an array of such structures and pass it to a run-time call.
922 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000923 IntptrTy, IntptrTy,
Kostya Serebryany086a4722013-03-18 08:05:29 +0000924 IntptrTy, IntptrTy, NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000925 SmallVector<Constant *, 16> Initializers(n), DynamicInit;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000926
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000927
928 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
929 assert(CtorFunc);
930 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000931
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000932 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000933
Kostya Serebryany086a4722013-03-18 08:05:29 +0000934 GlobalVariable *ModuleName = createPrivateGlobalForString(
935 M, M.getModuleIdentifier());
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000936 // We shouldn't merge same module names, as this string serves as unique
937 // module ID in runtime.
938 ModuleName->setUnnamedAddr(false);
Kostya Serebryany086a4722013-03-18 08:05:29 +0000939
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000940 for (size_t i = 0; i < n; i++) {
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000941 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000942 GlobalVariable *G = GlobalsToChange[i];
943 PointerType *PtrTy = cast<PointerType>(G->getType());
944 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000945 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000946 uint64_t MinRZ = RedzoneSize();
Kostya Serebryany63f08462013-01-24 10:35:40 +0000947 // MinRZ <= RZ <= kMaxGlobalRedzone
948 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000949 uint64_t RZ = std::max(MinRZ,
Kostya Serebryany63f08462013-01-24 10:35:40 +0000950 std::min(kMaxGlobalRedzone,
951 (SizeInBytes / MinRZ / 4) * MinRZ));
952 uint64_t RightRedzoneSize = RZ;
953 // Round up to MinRZ
954 if (SizeInBytes % MinRZ)
955 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
956 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000957 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000958 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000959 bool GlobalHasDynamicInitializer =
960 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000961 // Don't check initialization order if this global is blacklisted.
Peter Collingbourne46e11c42013-07-09 22:03:17 +0000962 GlobalHasDynamicInitializer &= !BL->isIn(*G, "init");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000963
964 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
965 Constant *NewInitializer = ConstantStruct::get(
966 NewTy, G->getInitializer(),
967 Constant::getNullValue(RightRedZoneTy), NULL);
968
Kostya Serebryany086a4722013-03-18 08:05:29 +0000969 GlobalVariable *Name = createPrivateGlobalForString(M, G->getName());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000970
971 // Create a new global variable with enough space for a redzone.
Bill Wendling55a1a592013-08-06 22:52:42 +0000972 GlobalValue::LinkageTypes Linkage = G->getLinkage();
973 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
974 Linkage = GlobalValue::InternalLinkage;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000975 GlobalVariable *NewGlobal = new GlobalVariable(
Bill Wendling55a1a592013-08-06 22:52:42 +0000976 M, NewTy, G->isConstant(), Linkage,
Hans Wennborgce718ff2012-06-23 11:37:03 +0000977 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000978 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany63f08462013-01-24 10:35:40 +0000979 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000980
981 Value *Indices2[2];
982 Indices2[0] = IRB.getInt32(0);
983 Indices2[1] = IRB.getInt32(0);
984
985 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000986 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000987 NewGlobal->takeName(G);
988 G->eraseFromParent();
989
990 Initializers[i] = ConstantStruct::get(
991 GlobalStructTy,
992 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
993 ConstantInt::get(IntptrTy, SizeInBytes),
994 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
995 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany086a4722013-03-18 08:05:29 +0000996 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000997 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000998 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000999
1000 // Populate the first and last globals declared in this TU.
Alexey Samsonovca825ea2013-03-26 13:05:41 +00001001 if (CheckInitOrder && GlobalHasDynamicInitializer)
1002 HasDynamicallyInitializedGlobals = true;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001003
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001004 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001005 }
1006
1007 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1008 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling55a1a592013-08-06 22:52:42 +00001009 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001010 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1011
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001012 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonovca825ea2013-03-26 13:05:41 +00001013 if (CheckInitOrder && HasDynamicallyInitializedGlobals)
1014 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001015 IRB.CreateCall2(AsanRegisterGlobals,
1016 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1017 ConstantInt::get(IntptrTy, n));
1018
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001019 // We also need to unregister globals at the end, e.g. when a shared library
1020 // gets closed.
1021 Function *AsanDtorFunction = Function::Create(
1022 FunctionType::get(Type::getVoidTy(*C), false),
1023 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1024 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1025 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001026 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1027 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1028 ConstantInt::get(IntptrTy, n));
1029 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
1030
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001031 DEBUG(dbgs() << M);
1032 return true;
1033}
1034
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001035void AddressSanitizer::initializeCallbacks(Module &M) {
1036 IRBuilder<> IRB(*C);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001037 // Create __asan_report* callbacks.
1038 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1039 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1040 AccessSizeIndex++) {
1041 // IsWrite and TypeSize are encoded in the function name.
1042 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
1043 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +00001044 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany7846c1c2012-11-07 12:42:18 +00001045 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1046 checkInterfaceFunction(M.getOrInsertFunction(
1047 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001048 }
1049 }
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +00001050 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1051 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1052 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1053 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001054
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001055 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
1056 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
Kostya Serebryanyf7b08222012-07-20 09:54:50 +00001057 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1058 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1059 StringRef(""), StringRef(""),
1060 /*hasSideEffects=*/true);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001061}
1062
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001063void AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const {
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001064 // Tell the values of mapping offset and scale to the run-time.
1065 GlobalValue *asan_mapping_offset =
1066 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1067 ConstantInt::get(IntptrTy, Mapping.Offset),
1068 kAsanMappingOffsetName);
1069 // Read the global, otherwise it may be optimized away.
1070 IRB.CreateLoad(asan_mapping_offset, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001071
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001072 GlobalValue *asan_mapping_scale =
1073 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1074 ConstantInt::get(IntptrTy, Mapping.Scale),
1075 kAsanMappingScaleName);
1076 // Read the global, otherwise it may be optimized away.
1077 IRB.CreateLoad(asan_mapping_scale, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001078}
1079
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001080// virtual
1081bool AddressSanitizer::doInitialization(Module &M) {
1082 // Initialize the private fields. No one has accessed them before.
1083 TD = getAnalysisIfAvailable<DataLayout>();
1084
1085 if (!TD)
1086 return false;
Alexey Samsonove39e1312013-08-12 11:46:09 +00001087 BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001088 DynamicallyInitializedGlobals.Init(M);
1089
1090 C = &(M.getContext());
1091 LongSize = TD->getPointerSizeInBits();
1092 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001093
1094 AsanCtorFunction = Function::Create(
1095 FunctionType::get(Type::getVoidTy(*C), false),
1096 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1097 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1098 // call __asan_init in the module ctor.
1099 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1100 AsanInitFunction = checkInterfaceFunction(
1101 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1102 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1103 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001104
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001105 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001106 emitShadowMapping(M, IRB);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001107
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001108 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001109 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001110}
1111
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001112bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1113 // For each NSObject descendant having a +load method, this method is invoked
1114 // by the ObjC runtime before any of the static constructors is called.
1115 // Therefore we need to instrument such methods with a call to __asan_init
1116 // at the beginning in order to initialize our runtime before any access to
1117 // the shadow memory.
1118 // We cannot just ignore these methods, because they may call other
1119 // instrumented functions.
1120 if (F.getName().find(" load]") != std::string::npos) {
1121 IRBuilder<> IRB(F.begin()->begin());
1122 IRB.CreateCall(AsanInitFunction);
1123 return true;
1124 }
1125 return false;
1126}
1127
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001128bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001129 if (BL->isIn(F)) return false;
1130 if (&F == AsanCtorFunction) return false;
Kostya Serebryany3797adb2013-03-18 07:33:49 +00001131 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001132 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001133 initializeCallbacks(*F.getParent());
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001134
Kostya Serebryany8eec41f2013-02-26 06:58:09 +00001135 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001136 maybeInsertAsanInitAtFunctionEntry(F);
1137
Kostya Serebryany20985712013-06-26 09:18:17 +00001138 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
Bill Wendling67658342012-10-09 07:45:08 +00001139 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001140
1141 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1142 return false;
Bill Wendling67658342012-10-09 07:45:08 +00001143
1144 // We want to instrument every address only once per basic block (unless there
1145 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001146 SmallSet<Value*, 16> TempsToInstrument;
1147 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001148 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryany20985712013-06-26 09:18:17 +00001149 int NumAllocas = 0;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001150 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001151
1152 // Fill the set of memory operations to instrument.
1153 for (Function::iterator FI = F.begin(), FE = F.end();
1154 FI != FE; ++FI) {
1155 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001156 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001157 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1158 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +00001159 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001160 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001161 if (ClOpt && ClOptSameTemp) {
1162 if (!TempsToInstrument.insert(Addr))
1163 continue; // We've seen this temp in the current BB.
1164 }
1165 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1166 // ok, take it.
1167 } else {
Kostya Serebryany20985712013-06-26 09:18:17 +00001168 if (isa<AllocaInst>(BI))
1169 NumAllocas++;
Kostya Serebryany1479c9b2013-02-20 12:35:15 +00001170 CallSite CS(BI);
1171 if (CS) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001172 // A call inside BB.
1173 TempsToInstrument.clear();
Kostya Serebryany1479c9b2013-02-20 12:35:15 +00001174 if (CS.doesNotReturn())
1175 NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001176 }
1177 continue;
1178 }
1179 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001180 NumInsnsPerBB++;
1181 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1182 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001183 }
1184 }
1185
Kostya Serebryany20985712013-06-26 09:18:17 +00001186 Function *UninstrumentedDuplicate = 0;
1187 bool LikelyToInstrument =
1188 !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1189 if (ClKeepUninstrumented && LikelyToInstrument) {
1190 ValueToValueMapTy VMap;
1191 UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1192 UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1193 UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1194 F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1195 }
1196
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001197 // Instrument.
1198 int NumInstrumented = 0;
1199 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1200 Instruction *Inst = ToInstrument[i];
1201 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1202 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001203 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001204 instrumentMop(Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001205 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001206 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001207 }
1208 NumInstrumented++;
1209 }
1210
Alexey Samsonov59cca132012-12-25 12:04:36 +00001211 FunctionStackPoisoner FSP(F, *this);
1212 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001213
1214 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1215 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1216 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1217 Instruction *CI = NoReturnCalls[i];
1218 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001219 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001220 }
1221
Kostya Serebryany20985712013-06-26 09:18:17 +00001222 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1223 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1224
1225 if (ClKeepUninstrumented) {
1226 if (!res) {
1227 // No instrumentation is done, no need for the duplicate.
1228 if (UninstrumentedDuplicate)
1229 UninstrumentedDuplicate->eraseFromParent();
1230 } else {
1231 // The function was instrumented. We must have the duplicate.
1232 assert(UninstrumentedDuplicate);
1233 UninstrumentedDuplicate->setSection("NOASAN");
1234 assert(!F.hasSection());
1235 F.setSection("ASAN");
1236 }
1237 }
1238
1239 return res;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001240}
1241
1242static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1243 if (ShadowRedzoneSize == 1) return PoisonByte;
1244 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1245 if (ShadowRedzoneSize == 4)
1246 return (PoisonByte << 24) + (PoisonByte << 16) +
1247 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +00001248 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001249}
1250
1251static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1252 size_t Size,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001253 size_t RZSize,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001254 size_t ShadowGranularity,
1255 uint8_t Magic) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001256 for (size_t i = 0; i < RZSize;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001257 i+= ShadowGranularity, Shadow++) {
1258 if (i + ShadowGranularity <= Size) {
1259 *Shadow = 0; // fully addressable
1260 } else if (i >= Size) {
1261 *Shadow = Magic; // unaddressable
1262 } else {
1263 *Shadow = Size - i; // first Size-i bytes are addressable
1264 }
1265 }
1266}
1267
Alexey Samsonov59cca132012-12-25 12:04:36 +00001268// Workaround for bug 11395: we don't want to instrument stack in functions
1269// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1270// FIXME: remove once the bug 11395 is fixed.
1271bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1272 if (LongSize != 32) return false;
1273 CallInst *CI = dyn_cast<CallInst>(I);
1274 if (!CI || !CI->isInlineAsm()) return false;
1275 if (CI->getNumArgOperands() <= 5) return false;
1276 // We have inline assembly with quite a few arguments.
1277 return true;
1278}
1279
1280void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1281 IRBuilder<> IRB(*C);
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001282 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1283 std::string Suffix = itostr(i);
1284 AsanStackMallocFunc[i] = checkInterfaceFunction(
1285 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1286 IntptrTy, IntptrTy, NULL));
1287 AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1288 kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1289 IntptrTy, IntptrTy, NULL));
1290 }
Alexey Samsonov59cca132012-12-25 12:04:36 +00001291 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1292 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1293 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1294 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1295}
1296
1297void FunctionStackPoisoner::poisonRedZones(
Jakub Staszak4c710642013-08-09 20:53:48 +00001298 const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> &IRB, Value *ShadowBase,
Alexey Samsonov59cca132012-12-25 12:04:36 +00001299 bool DoPoison) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001300 size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001301 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1302 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1303 Type *RZPtrTy = PointerType::get(RZTy, 0);
1304
1305 Value *PoisonLeft = ConstantInt::get(RZTy,
1306 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1307 Value *PoisonMid = ConstantInt::get(RZTy,
1308 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1309 Value *PoisonRight = ConstantInt::get(RZTy,
1310 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1311
1312 // poison the first red zone.
1313 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1314
1315 // poison all other red zones.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001316 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001317 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1318 AllocaInst *AI = AllocaVec[i];
1319 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1320 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001321 assert(AlignedSize - SizeInBytes < RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001322 Value *Ptr = NULL;
1323
1324 Pos += AlignedSize;
1325
1326 assert(ShadowBase->getType() == IntptrTy);
1327 if (SizeInBytes < AlignedSize) {
1328 // Poison the partial redzone at right
1329 Ptr = IRB.CreateAdd(
1330 ShadowBase, ConstantInt::get(IntptrTy,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001331 (Pos >> Mapping.Scale) - ShadowRZSize));
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001332 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001333 uint32_t Poison = 0;
1334 if (DoPoison) {
1335 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001336 RedzoneSize(),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001337 1ULL << Mapping.Scale,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001338 kAsanStackPartialRedzoneMagic);
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +00001339 Poison =
1340 ASan.TD->isLittleEndian()
1341 ? support::endian::byte_swap<uint32_t, support::little>(Poison)
1342 : support::endian::byte_swap<uint32_t, support::big>(Poison);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001343 }
1344 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1345 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1346 }
1347
1348 // Poison the full redzone at right.
1349 Ptr = IRB.CreateAdd(ShadowBase,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001350 ConstantInt::get(IntptrTy, Pos >> Mapping.Scale));
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001351 bool LastAlloca = (i == AllocaVec.size() - 1);
1352 Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001353 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1354
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001355 Pos += RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001356 }
1357}
1358
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001359// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1360// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1361static int StackMallocSizeClass(uint64_t LocalStackSize) {
1362 assert(LocalStackSize <= kMaxStackMallocSize);
1363 uint64_t MaxSize = kMinStackMallocSize;
1364 for (int i = 0; ; i++, MaxSize *= 2)
1365 if (LocalStackSize <= MaxSize)
1366 return i;
1367 llvm_unreachable("impossible LocalStackSize");
1368}
1369
Kostya Serebryany671c3ba2013-09-17 12:14:50 +00001370// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1371// We can not use MemSet intrinsic because it may end up calling the actual
1372// memset. Size is a multiple of 8.
1373// Currently this generates 8-byte stores on x86_64; it may be better to
1374// generate wider stores.
1375void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1376 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1377 assert(!(Size % 8));
1378 assert(kAsanStackAfterReturnMagic == 0xf5);
1379 for (int i = 0; i < Size; i += 8) {
1380 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1381 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1382 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1383 }
1384}
1385
Alexey Samsonov59cca132012-12-25 12:04:36 +00001386void FunctionStackPoisoner::poisonStack() {
Alexey Samsonov59cca132012-12-25 12:04:36 +00001387 uint64_t LocalStackSize = TotalStackSize +
1388 (AllocaVec.size() + 1) * RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001389
Alexey Samsonov59cca132012-12-25 12:04:36 +00001390 bool DoStackMalloc = ASan.CheckUseAfterReturn
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001391 && LocalStackSize <= kMaxStackMallocSize;
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001392 int StackMallocIdx = -1;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001393
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001394 assert(AllocaVec.size() > 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001395 Instruction *InsBefore = AllocaVec[0];
1396 IRBuilder<> IRB(InsBefore);
1397
1398
1399 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1400 AllocaInst *MyAlloca =
1401 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Alexey Samsonov59cca132012-12-25 12:04:36 +00001402 if (ClRealignStack && StackAlignment < RedzoneSize())
1403 StackAlignment = RedzoneSize();
1404 MyAlloca->setAlignment(StackAlignment);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001405 assert(MyAlloca->isStaticAlloca());
1406 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1407 Value *LocalStackBase = OrigStackBase;
1408
1409 if (DoStackMalloc) {
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001410 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1411 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1412 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc[StackMallocIdx],
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001413 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1414 }
1415
Kostya Serebryany30160562013-03-22 10:37:20 +00001416 // This string will be parsed by the run-time (DescribeAddressIfStack).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001417 SmallString<2048> StackDescriptionStorage;
1418 raw_svector_ostream StackDescription(StackDescriptionStorage);
Kostya Serebryany30160562013-03-22 10:37:20 +00001419 StackDescription << AllocaVec.size() << " ";
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001420
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001421 // Insert poison calls for lifetime intrinsics for alloca.
1422 bool HavePoisonedAllocas = false;
1423 for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1424 const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1425 IntrinsicInst *II = APC.InsBefore;
1426 AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
1427 assert(AI);
1428 IRBuilder<> IRB(II);
1429 poisonAlloca(AI, APC.Size, IRB, APC.DoPoison);
1430 HavePoisonedAllocas |= APC.DoPoison;
1431 }
1432
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001433 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001434 // Replace Alloca instructions with base+offset.
1435 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1436 AllocaInst *AI = AllocaVec[i];
1437 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1438 StringRef Name = AI->getName();
1439 StackDescription << Pos << " " << SizeInBytes << " "
1440 << Name.size() << " " << Name << " ";
1441 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001442 assert((AlignedSize % RedzoneSize()) == 0);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001443 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001444 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
Alexey Samsonovf985f442012-12-04 01:34:23 +00001445 AI->getType());
Alexey Samsonov1afbb512012-12-12 14:31:53 +00001446 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001447 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001448 Pos += AlignedSize + RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001449 }
1450 assert(Pos == LocalStackSize);
1451
Kostya Serebryany30160562013-03-22 10:37:20 +00001452 // The left-most redzone has enough space for at least 4 pointers.
1453 // Write the Magic value to redzone[0].
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001454 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1455 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1456 BasePlus0);
Kostya Serebryany30160562013-03-22 10:37:20 +00001457 // Write the frame description constant to redzone[1].
1458 Value *BasePlus1 = IRB.CreateIntToPtr(
1459 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1460 IntptrPtrTy);
Alexey Samsonov9ce84c12012-11-02 12:20:34 +00001461 GlobalVariable *StackDescriptionGlobal =
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001462 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
Alexey Samsonov59cca132012-12-25 12:04:36 +00001463 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1464 IntptrTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001465 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryany30160562013-03-22 10:37:20 +00001466 // Write the PC to redzone[2].
1467 Value *BasePlus2 = IRB.CreateIntToPtr(
1468 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1469 2 * ASan.LongSize/8)),
1470 IntptrPtrTy);
1471 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001472
1473 // Poison the stack redzones at the entry.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001474 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1475 poisonRedZones(AllocaVec, IRB, ShadowBase, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001476
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001477 // Unpoison the stack before all ret instructions.
1478 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1479 Instruction *Ret = RetVec[i];
1480 IRBuilder<> IRBRet(Ret);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001481 // Mark the current frame as retired.
1482 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1483 BasePlus0);
1484 // Unpoison the stack.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001485 poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001486 if (DoStackMalloc) {
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001487 assert(StackMallocIdx >= 0);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001488 // In use-after-return mode, mark the whole stack frame unaddressable.
Kostya Serebryany671c3ba2013-09-17 12:14:50 +00001489 if (StackMallocIdx <= 4) {
1490 // For small sizes inline the whole thing:
1491 // if LocalStackBase != OrigStackBase:
1492 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1493 // **SavedFlagPtr(LocalStackBase) = 0
1494 // FIXME: if LocalStackBase != OrigStackBase don't call poisonRedZones.
1495 Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1496 TerminatorInst *PoisonTerm =
1497 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
1498 IRBuilder<> IRBPoison(PoisonTerm);
1499 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1500 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1501 ClassSize >> Mapping.Scale);
1502 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1503 LocalStackBase,
1504 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1505 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1506 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1507 IRBPoison.CreateStore(
1508 Constant::getNullValue(IRBPoison.getInt8Ty()),
1509 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1510 } else {
1511 // For larger frames call __asan_stack_free_*.
1512 IRBRet.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1513 ConstantInt::get(IntptrTy, LocalStackSize),
1514 OrigStackBase);
1515 }
Alexey Samsonovf985f442012-12-04 01:34:23 +00001516 } else if (HavePoisonedAllocas) {
1517 // If we poisoned some allocas in llvm.lifetime analysis,
1518 // unpoison whole stack frame now.
1519 assert(LocalStackBase == OrigStackBase);
1520 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001521 }
1522 }
1523
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001524 // We are done. Remove the old unused alloca instructions.
1525 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1526 AllocaVec[i]->eraseFromParent();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001527}
Alexey Samsonovf985f442012-12-04 01:34:23 +00001528
Alexey Samsonov59cca132012-12-25 12:04:36 +00001529void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak4c710642013-08-09 20:53:48 +00001530 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001531 // For now just insert the call to ASan runtime.
1532 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1533 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1534 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1535 : AsanUnpoisonStackMemoryFunc,
1536 AddrArg, SizeArg);
1537}
Alexey Samsonov59cca132012-12-25 12:04:36 +00001538
1539// Handling llvm.lifetime intrinsics for a given %alloca:
1540// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1541// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1542// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1543// could be poisoned by previous llvm.lifetime.end instruction, as the
1544// variable may go in and out of scope several times, e.g. in loops).
1545// (3) if we poisoned at least one %alloca in a function,
1546// unpoison the whole stack frame at function exit.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001547
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001548AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1549 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1550 // We're intested only in allocas we can handle.
1551 return isInterestingAlloca(*AI) ? AI : 0;
1552 // See if we've already calculated (or started to calculate) alloca for a
1553 // given value.
1554 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1555 if (I != AllocaForValue.end())
1556 return I->second;
1557 // Store 0 while we're calculating alloca for value V to avoid
1558 // infinite recursion if the value references itself.
1559 AllocaForValue[V] = 0;
1560 AllocaInst *Res = 0;
1561 if (CastInst *CI = dyn_cast<CastInst>(V))
1562 Res = findAllocaForValue(CI->getOperand(0));
1563 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1564 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1565 Value *IncValue = PN->getIncomingValue(i);
1566 // Allow self-referencing phi-nodes.
1567 if (IncValue == PN) continue;
1568 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1569 // AI for incoming values should exist and should all be equal.
1570 if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1571 return 0;
1572 Res = IncValueAI;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001573 }
Alexey Samsonov59cca132012-12-25 12:04:36 +00001574 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001575 if (Res != 0)
1576 AllocaForValue[V] = Res;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001577 return Res;
1578}