blob: de0a43bfd949fa4211568d6c2f7c6c12451918d5 [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"
Kostya Serebryany3386d252013-10-16 14:06:14 +000026#include "llvm/ADT/Statistic.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000027#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000028#include "llvm/ADT/Triple.h"
Alexey Samsonov1afbb512012-12-12 14:31:53 +000029#include "llvm/DIBuilder.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000030#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/InlineAsm.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/LLVMContext.h"
36#include "llvm/IR/Module.h"
37#include "llvm/IR/Type.h"
Alexey Samsonov59cca132012-12-25 12:04:36 +000038#include "llvm/InstVisitor.h"
Kostya Serebryany1479c9b2013-02-20 12:35:15 +000039#include "llvm/Support/CallSite.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000040#include "llvm/Support/CommandLine.h"
41#include "llvm/Support/DataTypes.h"
42#include "llvm/Support/Debug.h"
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +000043#include "llvm/Support/Endian.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000044#include "llvm/Support/raw_ostream.h"
45#include "llvm/Support/system_error.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000046#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany20985712013-06-26 09:18:17 +000047#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov1afbb512012-12-12 14:31:53 +000048#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000049#include "llvm/Transforms/Utils/ModuleUtils.h"
Peter Collingbourne405515d2013-07-09 22:02:49 +000050#include "llvm/Transforms/Utils/SpecialCaseList.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000051#include <algorithm>
Chandler Carruthd04a8d42012-12-03 16:50:05 +000052#include <string>
Kostya Serebryany800e03f2011-11-16 01:35:23 +000053
54using namespace llvm;
55
56static const uint64_t kDefaultShadowScale = 3;
57static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
58static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Kostya Serebryany117de482013-02-11 14:36:01 +000059static const uint64_t kDefaultShort64bitShadowOffset = 0x7FFF8000; // < 2G.
Kostya Serebryany48a615f2013-01-23 12:54:55 +000060static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +000061static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa8000;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000062
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +000063static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany800e03f2011-11-16 01:35:23 +000064static const size_t kMaxStackMallocSize = 1 << 16; // 64K
65static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
66static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
67
Craig Topper4172a8a2013-07-16 01:17:10 +000068static const char *const kAsanModuleCtorName = "asan.module_ctor";
69static const char *const kAsanModuleDtorName = "asan.module_dtor";
70static const int kAsanCtorAndCtorPriority = 1;
71static const char *const kAsanReportErrorTemplate = "__asan_report_";
72static const char *const kAsanReportLoadN = "__asan_report_load_n";
73static const char *const kAsanReportStoreN = "__asan_report_store_n";
74static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonov48d7d1d2013-08-05 13:19:49 +000075static const char *const kAsanUnregisterGlobalsName =
76 "__asan_unregister_globals";
Craig Topper4172a8a2013-07-16 01:17:10 +000077static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
78static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
79static const char *const kAsanInitName = "__asan_init_v3";
80static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
81static const char *const kAsanMappingOffsetName = "__asan_mapping_offset";
82static const char *const kAsanMappingScaleName = "__asan_mapping_scale";
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +000083static const int kMaxAsanStackMallocSizeClass = 10;
84static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
85static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topper4172a8a2013-07-16 01:17:10 +000086static const char *const kAsanGenPrefix = "__asan_gen_";
87static const char *const kAsanPoisonStackMemoryName =
88 "__asan_poison_stack_memory";
89static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonovf985f442012-12-04 01:34:23 +000090 "__asan_unpoison_stack_memory";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000091
Kostya Serebryanyac04aba2013-09-18 14:07:14 +000092static const char *const kAsanOptionDetectUAR =
93 "__asan_option_detect_stack_use_after_return";
94
Kostya Serebryany671c3ba2013-09-17 12:14:50 +000095// These constants must match the definitions in the run-time library.
Kostya Serebryany800e03f2011-11-16 01:35:23 +000096static const int kAsanStackLeftRedzoneMagic = 0xf1;
97static const int kAsanStackMidRedzoneMagic = 0xf2;
98static const int kAsanStackRightRedzoneMagic = 0xf3;
99static const int kAsanStackPartialRedzoneMagic = 0xf4;
David Blaikie0b956502013-09-18 00:11:27 +0000100#ifndef NDEBUG
Kostya Serebryany671c3ba2013-09-17 12:14:50 +0000101static const int kAsanStackAfterReturnMagic = 0xf5;
David Blaikie0b956502013-09-18 00:11:27 +0000102#endif
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000103
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000104// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
105static const size_t kNumberOfAccessSizes = 5;
106
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000107// Command-line flags.
108
109// This flag may need to be replaced with -f[no-]asan-reads.
110static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
111 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
112static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
113 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000114static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
115 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
116 cl::Hidden, cl::init(true));
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000117static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
118 cl::desc("use instrumentation with slow path for all accesses"),
119 cl::Hidden, cl::init(false));
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000120// This flag limits the number of instructions to be instrumented
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000121// in any given BB. Normally, this should be set to unlimited (INT_MAX),
122// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
123// set it to 10000.
124static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
125 cl::init(10000),
126 cl::desc("maximal number of instructions to instrument in any given BB"),
127 cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000128// This flag may need to be replaced with -f[no]asan-stack.
129static cl::opt<bool> ClStack("asan-stack",
130 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
131// This flag may need to be replaced with -f[no]asan-use-after-return.
132static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
133 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
134// This flag may need to be replaced with -f[no]asan-globals.
135static cl::opt<bool> ClGlobals("asan-globals",
136 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000137static cl::opt<bool> ClInitializers("asan-initialization-order",
138 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000139static cl::opt<bool> ClMemIntrin("asan-memintrin",
140 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
Kostya Serebryany6c554122012-12-04 06:14:01 +0000141static cl::opt<bool> ClRealignStack("asan-realign-stack",
142 cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true));
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000143static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
144 cl::desc("File containing the list of objects to ignore "
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000145 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000146
Kostya Serebryany20985712013-06-26 09:18:17 +0000147// This is an experimental feature that will allow to choose between
148// instrumented and non-instrumented code at link-time.
149// If this option is on, just before instrumenting a function we create its
150// clone; if the function is not changed by asan the clone is deleted.
151// If we end up with a clone, we put the instrumented function into a section
152// called "ASAN" and the uninstrumented function into a section called "NOASAN".
153//
154// This is still a prototype, we need to figure out a way to keep two copies of
155// a function so that the linker can easily choose one of them.
156static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
157 cl::desc("Keep uninstrumented copies of functions"),
158 cl::Hidden, cl::init(false));
159
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000160// These flags allow to change the shadow mapping.
161// The shadow mapping looks like
162// Shadow = (Mem >> scale) + (1 << offset_log)
163static cl::opt<int> ClMappingScale("asan-mapping-scale",
164 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
165static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
166 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
Kostya Serebryany117de482013-02-11 14:36:01 +0000167static cl::opt<bool> ClShort64BitOffset("asan-short-64bit-mapping-offset",
168 cl::desc("Use short immediate constant as the mapping offset for 64bit"),
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000169 cl::Hidden, cl::init(true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000170
171// Optimization flags. Not user visible, used mostly for testing
172// and benchmarking the tool.
173static cl::opt<bool> ClOpt("asan-opt",
174 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
175static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
176 cl::desc("Instrument the same temp just once"), cl::Hidden,
177 cl::init(true));
178static cl::opt<bool> ClOptGlobals("asan-opt-globals",
179 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
180
Alexey Samsonovee548272012-11-29 18:14:24 +0000181static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
182 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
183 cl::Hidden, cl::init(false));
184
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000185// Debug flags.
186static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
187 cl::init(0));
188static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
189 cl::Hidden, cl::init(0));
190static cl::opt<std::string> ClDebugFunc("asan-debug-func",
191 cl::Hidden, cl::desc("Debug func"));
192static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
193 cl::Hidden, cl::init(-1));
194static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
195 cl::Hidden, cl::init(-1));
196
Kostya Serebryany3386d252013-10-16 14:06:14 +0000197STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
198STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
199STATISTIC(NumOptimizedAccessesToGlobalArray,
200 "Number of optimized accesses to global arrays");
201STATISTIC(NumOptimizedAccessesToGlobalVar,
202 "Number of optimized accesses to global vars");
203
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000204namespace {
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000205/// A set of dynamically initialized globals extracted from metadata.
206class SetOfDynamicallyInitializedGlobals {
207 public:
208 void Init(Module& M) {
209 // Clang generates metadata identifying all dynamically initialized globals.
210 NamedMDNode *DynamicGlobals =
211 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
212 if (!DynamicGlobals)
213 return;
214 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
215 MDNode *MDN = DynamicGlobals->getOperand(i);
216 assert(MDN->getNumOperands() == 1);
217 Value *VG = MDN->getOperand(0);
218 // The optimizer may optimize away a global entirely, in which case we
219 // cannot instrument access to it.
220 if (!VG)
221 continue;
222 DynInitGlobals.insert(cast<GlobalVariable>(VG));
223 }
224 }
225 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
226 private:
227 SmallSet<GlobalValue*, 32> DynInitGlobals;
228};
229
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000230/// This struct defines the shadow mapping using the rule:
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000231/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000232struct ShadowMapping {
233 int Scale;
234 uint64_t Offset;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000235 bool OrShadowOffset;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000236};
237
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000238static ShadowMapping getShadowMapping(const Module &M, int LongSize,
239 bool ZeroBaseShadow) {
240 llvm::Triple TargetTriple(M.getTargetTriple());
241 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Alexander Potapenkoc8a196a2013-02-12 12:41:12 +0000242 bool IsMacOSX = TargetTriple.getOS() == llvm::Triple::MacOSX;
Bill Schmidtf38cc382013-07-26 01:35:43 +0000243 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
244 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000245 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +0000246 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
247 TargetTriple.getArch() == llvm::Triple::mipsel;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000248
249 ShadowMapping Mapping;
250
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000251 // OR-ing shadow offset if more efficient (at least on x86),
252 // but on ppc64 we have to use add since the shadow offset is not neccesary
253 // 1/8-th of the address space.
Kostya Serebryany117de482013-02-11 14:36:01 +0000254 Mapping.OrShadowOffset = !IsPPC64 && !ClShort64BitOffset;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000255
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000256 Mapping.Offset = (IsAndroid || ZeroBaseShadow) ? 0 :
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +0000257 (LongSize == 32 ?
258 (IsMIPS32 ? kMIPS32_ShadowOffset32 : kDefaultShadowOffset32) :
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000259 IsPPC64 ? kPPC64_ShadowOffset64 : kDefaultShadowOffset64);
Alexander Potapenkoc8a196a2013-02-12 12:41:12 +0000260 if (!ZeroBaseShadow && ClShort64BitOffset && IsX86_64 && !IsMacOSX) {
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000261 assert(LongSize == 64);
Kostya Serebryany117de482013-02-11 14:36:01 +0000262 Mapping.Offset = kDefaultShort64bitShadowOffset;
Kostya Serebryany39f02942013-02-13 05:14:12 +0000263 }
264 if (!ZeroBaseShadow && ClMappingOffsetLog >= 0) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000265 // Zero offset log is the special case.
266 Mapping.Offset = (ClMappingOffsetLog == 0) ? 0 : 1ULL << ClMappingOffsetLog;
267 }
268
269 Mapping.Scale = kDefaultShadowScale;
270 if (ClMappingScale) {
271 Mapping.Scale = ClMappingScale;
272 }
273
274 return Mapping;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000275}
276
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000277static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000278 // Redzone used for stack and globals is at least 32 bytes.
279 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000280 return std::max(32U, 1U << MappingScale);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000281}
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000282
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000283/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000284struct AddressSanitizer : public FunctionPass {
Alexey Samsonovb4ba5e62013-03-14 12:38:58 +0000285 AddressSanitizer(bool CheckInitOrder = true,
Alexey Samsonovee548272012-11-29 18:14:24 +0000286 bool CheckUseAfterReturn = false,
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000287 bool CheckLifetime = false,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000288 StringRef BlacklistFile = StringRef(),
289 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000290 : FunctionPass(ID),
291 CheckInitOrder(CheckInitOrder || ClInitializers),
292 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000293 CheckLifetime(CheckLifetime || ClCheckLifetime),
294 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000295 : BlacklistFile),
296 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000297 virtual const char *getPassName() const {
298 return "AddressSanitizerFunctionPass";
299 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000300 void instrumentMop(Instruction *I);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000301 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
302 Value *Addr, uint32_t TypeSize, bool IsWrite,
303 Value *SizeArgument);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000304 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
305 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000306 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000307 bool IsWrite, size_t AccessSizeIndex,
308 Value *SizeArgument);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000309 bool instrumentMemIntrinsic(MemIntrinsic *MI);
310 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000311 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000312 Instruction *InsertBefore, bool IsWrite);
313 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000314 bool runOnFunction(Function &F);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000315 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000316 void emitShadowMapping(Module &M, IRBuilder<> &IRB) const;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000317 virtual bool doInitialization(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000318 static char ID; // Pass identification, replacement for typeid
319
320 private:
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000321 void initializeCallbacks(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000322
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000323 bool ShouldInstrumentGlobal(GlobalVariable *G);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000324 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000325 void FindDynamicInitializers(Module &M);
Kostya Serebryany3386d252013-10-16 14:06:14 +0000326 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000327
Alexey Samsonovee548272012-11-29 18:14:24 +0000328 bool CheckInitOrder;
329 bool CheckUseAfterReturn;
330 bool CheckLifetime;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000331 SmallString<64> BlacklistFile;
332 bool ZeroBaseShadow;
333
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000334 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +0000335 DataLayout *TD;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000336 int LongSize;
337 Type *IntptrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000338 ShadowMapping Mapping;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000339 Function *AsanCtorFunction;
340 Function *AsanInitFunction;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000341 Function *AsanHandleNoReturnFunc;
Peter Collingbourne405515d2013-07-09 22:02:49 +0000342 OwningPtr<SpecialCaseList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000343 // This array is indexed by AccessIsWrite and log2(AccessSize).
344 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000345 // This array is indexed by AccessIsWrite.
346 Function *AsanErrorCallbackSized[2];
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000347 InlineAsm *EmptyAsm;
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000348 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000349
350 friend struct FunctionStackPoisoner;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000351};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000352
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000353class AddressSanitizerModule : public ModulePass {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000354 public:
Alexey Samsonovb4ba5e62013-03-14 12:38:58 +0000355 AddressSanitizerModule(bool CheckInitOrder = true,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000356 StringRef BlacklistFile = StringRef(),
357 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000358 : ModulePass(ID),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000359 CheckInitOrder(CheckInitOrder || ClInitializers),
360 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000361 : BlacklistFile),
362 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000363 bool runOnModule(Module &M);
364 static char ID; // Pass identification, replacement for typeid
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000365 virtual const char *getPassName() const {
366 return "AddressSanitizerModule";
367 }
Alexey Samsonovf985f442012-12-04 01:34:23 +0000368
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000369 private:
Alexey Samsonov46848582012-12-25 12:28:20 +0000370 void initializeCallbacks(Module &M);
371
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000372 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000373 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000374 size_t RedzoneSize() const {
375 return RedzoneSizeForScale(Mapping.Scale);
376 }
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000377
Alexey Samsonovee548272012-11-29 18:14:24 +0000378 bool CheckInitOrder;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000379 SmallString<64> BlacklistFile;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000380 bool ZeroBaseShadow;
381
Peter Collingbourne405515d2013-07-09 22:02:49 +0000382 OwningPtr<SpecialCaseList> BL;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000383 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
384 Type *IntptrTy;
385 LLVMContext *C;
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000386 DataLayout *TD;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000387 ShadowMapping Mapping;
Alexey Samsonov46848582012-12-25 12:28:20 +0000388 Function *AsanPoisonGlobals;
389 Function *AsanUnpoisonGlobals;
390 Function *AsanRegisterGlobals;
391 Function *AsanUnregisterGlobals;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000392};
393
Alexey Samsonov59cca132012-12-25 12:04:36 +0000394// Stack poisoning does not play well with exception handling.
395// When an exception is thrown, we essentially bypass the code
396// that unpoisones the stack. This is why the run-time library has
397// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
398// stack in the interceptor. This however does not work inside the
399// actual function which catches the exception. Most likely because the
400// compiler hoists the load of the shadow value somewhere too high.
401// This causes asan to report a non-existing bug on 453.povray.
402// It sounds like an LLVM bug.
403struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
404 Function &F;
405 AddressSanitizer &ASan;
406 DIBuilder DIB;
407 LLVMContext *C;
408 Type *IntptrTy;
409 Type *IntptrPtrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000410 ShadowMapping Mapping;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000411
412 SmallVector<AllocaInst*, 16> AllocaVec;
413 SmallVector<Instruction*, 8> RetVec;
414 uint64_t TotalStackSize;
415 unsigned StackAlignment;
416
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +0000417 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
418 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov59cca132012-12-25 12:04:36 +0000419 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
420
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000421 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
422 struct AllocaPoisonCall {
423 IntrinsicInst *InsBefore;
424 uint64_t Size;
425 bool DoPoison;
426 };
427 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
428
429 // Maps Value to an AllocaInst from which the Value is originated.
430 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
431 AllocaForValueMapTy AllocaForValue;
432
Alexey Samsonov59cca132012-12-25 12:04:36 +0000433 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
434 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
435 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000436 Mapping(ASan.Mapping),
437 TotalStackSize(0), StackAlignment(1 << Mapping.Scale) {}
Alexey Samsonov59cca132012-12-25 12:04:36 +0000438
439 bool runOnFunction() {
440 if (!ClStack) return false;
441 // Collect alloca, ret, lifetime instructions etc.
442 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
443 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
444 BasicBlock *BB = *DI;
445 visit(*BB);
446 }
447 if (AllocaVec.empty()) return false;
448
449 initializeCallbacks(*F.getParent());
450
451 poisonStack();
452
453 if (ClDebugStack) {
454 DEBUG(dbgs() << F);
455 }
456 return true;
457 }
458
459 // Finds all static Alloca instructions and puts
460 // poisoned red zones around all of them.
461 // Then unpoison everything back before the function returns.
462 void poisonStack();
463
464 // ----------------------- Visitors.
465 /// \brief Collect all Ret instructions.
466 void visitReturnInst(ReturnInst &RI) {
467 RetVec.push_back(&RI);
468 }
469
470 /// \brief Collect Alloca instructions we want (and can) handle.
471 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000472 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000473
474 StackAlignment = std::max(StackAlignment, AI.getAlignment());
475 AllocaVec.push_back(&AI);
Kostya Serebryanyd4429212013-06-26 09:49:52 +0000476 uint64_t AlignedSize = getAlignedAllocaSize(&AI);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000477 TotalStackSize += AlignedSize;
478 }
479
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000480 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
481 /// errors.
482 void visitIntrinsicInst(IntrinsicInst &II) {
483 if (!ASan.CheckLifetime) return;
484 Intrinsic::ID ID = II.getIntrinsicID();
485 if (ID != Intrinsic::lifetime_start &&
486 ID != Intrinsic::lifetime_end)
487 return;
488 // Found lifetime intrinsic, add ASan instrumentation if necessary.
489 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
490 // If size argument is undefined, don't do anything.
491 if (Size->isMinusOne()) return;
492 // Check that size doesn't saturate uint64_t and can
493 // be stored in IntptrTy.
494 const uint64_t SizeValue = Size->getValue().getLimitedValue();
495 if (SizeValue == ~0ULL ||
496 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
497 return;
498 // Find alloca instruction that corresponds to llvm.lifetime argument.
499 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
500 if (!AI) return;
501 bool DoPoison = (ID == Intrinsic::lifetime_end);
502 AllocaPoisonCall APC = {&II, SizeValue, DoPoison};
503 AllocaPoisonCallVec.push_back(APC);
504 }
505
Alexey Samsonov59cca132012-12-25 12:04:36 +0000506 // ---------------------- Helpers.
507 void initializeCallbacks(Module &M);
508
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000509 // Check if we want (and can) handle this alloca.
Jakub Staszak4c710642013-08-09 20:53:48 +0000510 bool isInterestingAlloca(AllocaInst &AI) const {
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000511 return (!AI.isArrayAllocation() &&
512 AI.isStaticAlloca() &&
Kostya Serebryanyd4429212013-06-26 09:49:52 +0000513 AI.getAlignment() <= RedzoneSize() &&
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000514 AI.getAllocatedType()->isSized());
515 }
516
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000517 size_t RedzoneSize() const {
518 return RedzoneSizeForScale(Mapping.Scale);
519 }
Jakub Staszak4c710642013-08-09 20:53:48 +0000520 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
Alexey Samsonov59cca132012-12-25 12:04:36 +0000521 Type *Ty = AI->getAllocatedType();
522 uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty);
523 return SizeInBytes;
524 }
Jakub Staszak4c710642013-08-09 20:53:48 +0000525 uint64_t getAlignedSize(uint64_t SizeInBytes) const {
Alexey Samsonov59cca132012-12-25 12:04:36 +0000526 size_t RZ = RedzoneSize();
527 return ((SizeInBytes + RZ - 1) / RZ) * RZ;
528 }
Jakub Staszak4c710642013-08-09 20:53:48 +0000529 uint64_t getAlignedAllocaSize(AllocaInst *AI) const {
Alexey Samsonov59cca132012-12-25 12:04:36 +0000530 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
531 return getAlignedSize(SizeInBytes);
532 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000533 /// Finds alloca where the value comes from.
534 AllocaInst *findAllocaForValue(Value *V);
Jakub Staszak4c710642013-08-09 20:53:48 +0000535 void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> &IRB,
Alexey Samsonov59cca132012-12-25 12:04:36 +0000536 Value *ShadowBase, bool DoPoison);
Jakub Staszak4c710642013-08-09 20:53:48 +0000537 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryany671c3ba2013-09-17 12:14:50 +0000538
539 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
540 int Size);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000541};
542
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000543} // namespace
544
545char AddressSanitizer::ID = 0;
546INITIALIZE_PASS(AddressSanitizer, "asan",
547 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
548 false, false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000549FunctionPass *llvm::createAddressSanitizerFunctionPass(
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000550 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000551 StringRef BlacklistFile, bool ZeroBaseShadow) {
Alexey Samsonovee548272012-11-29 18:14:24 +0000552 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000553 CheckLifetime, BlacklistFile, ZeroBaseShadow);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000554}
555
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000556char AddressSanitizerModule::ID = 0;
557INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
558 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
559 "ModulePass", false, false)
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000560ModulePass *llvm::createAddressSanitizerModulePass(
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000561 bool CheckInitOrder, StringRef BlacklistFile, bool ZeroBaseShadow) {
562 return new AddressSanitizerModule(CheckInitOrder, BlacklistFile,
563 ZeroBaseShadow);
Alexander Potapenko25878042012-01-23 11:22:43 +0000564}
565
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000566static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerc6af2432013-05-24 22:23:49 +0000567 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000568 assert(Res < kNumberOfAccessSizes);
569 return Res;
570}
571
Bill Wendling55a1a592013-08-06 22:52:42 +0000572// \brief Create a constant for Str so that we can pass it to the run-time lib.
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000573static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000574 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany51116272013-03-18 09:38:39 +0000575 GlobalVariable *GV = new GlobalVariable(M, StrConst->getType(), true,
Bill Wendling55a1a592013-08-06 22:52:42 +0000576 GlobalValue::InternalLinkage, StrConst,
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000577 kAsanGenPrefix);
Kostya Serebryany51116272013-03-18 09:38:39 +0000578 GV->setUnnamedAddr(true); // Ok to merge these.
579 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
580 return GV;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000581}
582
583static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
584 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000585}
586
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000587Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
588 // Shadow >> scale
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000589 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
590 if (Mapping.Offset == 0)
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000591 return Shadow;
592 // (Shadow >> scale) | offset
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000593 if (Mapping.OrShadowOffset)
594 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
595 else
596 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000597}
598
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000599void AddressSanitizer::instrumentMemIntrinsicParam(
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000600 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000601 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000602 IRBuilder<> IRB(InsertBefore);
603 if (Size->getType() != IntptrTy)
604 Size = IRB.CreateIntCast(Size, IntptrTy, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000605 // Check the first byte.
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000606 instrumentAddress(OrigIns, InsertBefore, Addr, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000607 // Check the last byte.
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000608 IRB.SetInsertPoint(InsertBefore);
609 Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));
610 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
611 Value *AddrLast = IRB.CreateAdd(AddrLong, SizeMinusOne);
612 instrumentAddress(OrigIns, InsertBefore, AddrLast, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000613}
614
615// Instrument memset/memmove/memcpy
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000616bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000617 Value *Dst = MI->getDest();
618 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000619 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000620 Value *Length = MI->getLength();
621
622 Constant *ConstLength = dyn_cast<Constant>(Length);
623 Instruction *InsertBefore = MI;
624 if (ConstLength) {
625 if (ConstLength->isNullValue()) return false;
626 } else {
627 // The size is not a constant so it could be zero -- check at run-time.
628 IRBuilder<> IRB(InsertBefore);
629
630 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000631 Constant::getNullValue(Length->getType()));
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000632 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000633 }
634
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000635 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000636 if (Src)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000637 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000638 return true;
639}
640
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000641// If I is an interesting memory access, return the PointerOperand
642// and set IsWrite. Otherwise return NULL.
643static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000644 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000645 if (!ClInstrumentReads) return NULL;
646 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000647 return LI->getPointerOperand();
648 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000649 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
650 if (!ClInstrumentWrites) return NULL;
651 *IsWrite = true;
652 return SI->getPointerOperand();
653 }
654 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
655 if (!ClInstrumentAtomics) return NULL;
656 *IsWrite = true;
657 return RMW->getPointerOperand();
658 }
659 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
660 if (!ClInstrumentAtomics) return NULL;
661 *IsWrite = true;
662 return XCHG->getPointerOperand();
663 }
664 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000665}
666
Kostya Serebryany3386d252013-10-16 14:06:14 +0000667bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
668 // If a global variable does not have dynamic initialization we don't
669 // have to instrument it. However, if a global does not have initializer
670 // at all, we assume it has dynamic initializer (in other TU).
671 return G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G);
672}
673
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000674void AddressSanitizer::instrumentMop(Instruction *I) {
Axel Naumann3780ad82012-09-17 14:20:57 +0000675 bool IsWrite = false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000676 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
677 assert(Addr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000678 if (ClOpt && ClOptGlobals) {
679 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
680 // If initialization order checking is disabled, a simple access to a
681 // dynamically initialized global is always valid.
Kostya Serebryany3386d252013-10-16 14:06:14 +0000682 if (!CheckInitOrder || GlobalIsLinkerInitialized(G)) {
683 NumOptimizedAccessesToGlobalVar++;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000684 return;
Kostya Serebryany3386d252013-10-16 14:06:14 +0000685 }
686 }
687 ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
688 if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
689 if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
690 if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
691 NumOptimizedAccessesToGlobalArray++;
692 return;
693 }
694 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000695 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000696 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000697
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000698 Type *OrigPtrTy = Addr->getType();
699 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
700
701 assert(OrigTy->isSized());
Kostya Serebryany605ff662013-02-18 13:47:02 +0000702 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000703
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000704 assert((TypeSize % 8) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000705
Kostya Serebryany3386d252013-10-16 14:06:14 +0000706 if (IsWrite)
707 NumInstrumentedWrites++;
708 else
709 NumInstrumentedReads++;
710
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000711 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check.
712 if (TypeSize == 8 || TypeSize == 16 ||
713 TypeSize == 32 || TypeSize == 64 || TypeSize == 128)
714 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, 0);
715 // Instrument unusual size (but still multiple of 8).
716 // We can not do it with a single check, so we do 1-byte check for the first
717 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
718 // to report the actual access size.
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000719 IRBuilder<> IRB(I);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000720 Value *LastByte = IRB.CreateIntToPtr(
721 IRB.CreateAdd(IRB.CreatePointerCast(Addr, IntptrTy),
722 ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
723 OrigPtrTy);
724 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
725 instrumentAddress(I, I, Addr, 8, IsWrite, Size);
726 instrumentAddress(I, I, LastByte, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000727}
728
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000729// Validate the result of Module::getOrInsertFunction called for an interface
730// function of AddressSanitizer. If the instrumented module defines a function
731// with the same name, their prototypes must match, otherwise
732// getOrInsertFunction returns a bitcast.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000733static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000734 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
735 FuncOrBitcast->dump();
736 report_fatal_error("trying to redefine an AddressSanitizer "
737 "interface function");
738}
739
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000740Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000741 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000742 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000743 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000744 CallInst *Call = SizeArgument
745 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
746 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
747
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000748 // We don't do Call->setDoesNotReturn() because the BB already has
749 // UnreachableInst at the end.
750 // This EmptyAsm is required to avoid callback merge.
751 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000752 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000753}
754
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000755Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000756 Value *ShadowValue,
757 uint32_t TypeSize) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000758 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000759 // Addr & (Granularity - 1)
760 Value *LastAccessedByte = IRB.CreateAnd(
761 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
762 // (Addr & (Granularity - 1)) + size - 1
763 if (TypeSize / 8 > 1)
764 LastAccessedByte = IRB.CreateAdd(
765 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
766 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
767 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000768 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000769 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
770 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
771}
772
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000773void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000774 Instruction *InsertBefore,
775 Value *Addr, uint32_t TypeSize,
776 bool IsWrite, Value *SizeArgument) {
777 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000778 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
779
780 Type *ShadowTy = IntegerType::get(
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000781 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000782 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
783 Value *ShadowPtr = memToShadow(AddrLong, IRB);
784 Value *CmpVal = Constant::getNullValue(ShadowTy);
785 Value *ShadowValue = IRB.CreateLoad(
786 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
787
788 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000789 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000790 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000791 TerminatorInst *CrashTerm = 0;
792
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000793 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000794 TerminatorInst *CheckTerm =
795 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000796 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000797 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000798 IRB.SetInsertPoint(CheckTerm);
799 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000800 BasicBlock *CrashBlock =
801 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000802 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000803 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
804 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000805 } else {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000806 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000807 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000808
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000809 Instruction *Crash = generateCrashCode(
810 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000811 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000812}
813
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000814void AddressSanitizerModule::createInitializerPoisonCalls(
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000815 Module &M, GlobalValue *ModuleName) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000816 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
817 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
818 // If that function is not present, this TU contains no globals, or they have
819 // all been optimized away
820 if (!GlobalInit)
821 return;
822
823 // Set up the arguments to our poison/unpoison functions.
824 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
825
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000826 // Add a call to poison all external globals before the given function starts.
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000827 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
828 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000829
830 // Add calls to unpoison all globals before each return instruction.
831 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
832 I != E; ++I) {
833 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
834 CallInst::Create(AsanUnpoisonGlobals, "", RI);
835 }
836 }
837}
838
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000839bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000840 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000841 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000842
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000843 if (BL->isIn(*G)) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000844 if (!Ty->isSized()) return false;
845 if (!G->hasInitializer()) return false;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000846 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000847 // Touch only those globals that will not be defined in other modules.
848 // Don't handle ODR type linkages since other modules may be built w/o asan.
849 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
850 G->getLinkage() != GlobalVariable::PrivateLinkage &&
851 G->getLinkage() != GlobalVariable::InternalLinkage)
852 return false;
853 // Two problems with thread-locals:
854 // - The address of the main thread's copy can't be computed at link-time.
855 // - Need to poison all copies, not just the main thread's one.
856 if (G->isThreadLocal())
857 return false;
858 // For now, just ignore this Alloca if the alignment is large.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000859 if (G->getAlignment() > RedzoneSize()) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000860
861 // Ignore all the globals with the names starting with "\01L_OBJC_".
862 // Many of those are put into the .cstring section. The linker compresses
863 // that section by removing the spare \0s after the string terminator, so
864 // our redzones get broken.
865 if ((G->getName().find("\01L_OBJC_") == 0) ||
866 (G->getName().find("\01l_OBJC_") == 0)) {
867 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
868 return false;
869 }
870
871 if (G->hasSection()) {
872 StringRef Section(G->getSection());
873 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
874 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
875 // them.
876 if ((Section.find("__OBJC,") == 0) ||
877 (Section.find("__DATA, __objc_") == 0)) {
878 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
879 return false;
880 }
881 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
882 // Constant CFString instances are compiled in the following way:
883 // -- the string buffer is emitted into
884 // __TEXT,__cstring,cstring_literals
885 // -- the constant NSConstantString structure referencing that buffer
886 // is placed into __DATA,__cfstring
887 // Therefore there's no point in placing redzones into __DATA,__cfstring.
888 // Moreover, it causes the linker to crash on OS X 10.7
889 if (Section.find("__DATA,__cfstring") == 0) {
890 DEBUG(dbgs() << "Ignoring CFString: " << *G);
891 return false;
892 }
893 }
894
895 return true;
896}
897
Alexey Samsonov46848582012-12-25 12:28:20 +0000898void AddressSanitizerModule::initializeCallbacks(Module &M) {
899 IRBuilder<> IRB(*C);
900 // Declare our poisoning and unpoisoning functions.
901 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000902 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
Alexey Samsonov46848582012-12-25 12:28:20 +0000903 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
904 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
905 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
906 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
907 // Declare functions that register/unregister globals.
908 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
909 kAsanRegisterGlobalsName, IRB.getVoidTy(),
910 IntptrTy, IntptrTy, NULL));
911 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
912 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
913 kAsanUnregisterGlobalsName,
914 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
915 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
916}
917
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000918// This function replaces all global variables with new variables that have
919// trailing redzones. It also creates a function that poisons
920// redzones and inserts this function into llvm.global_ctors.
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000921bool AddressSanitizerModule::runOnModule(Module &M) {
922 if (!ClGlobals) return false;
923 TD = getAnalysisIfAvailable<DataLayout>();
924 if (!TD)
925 return false;
Alexey Samsonove39e1312013-08-12 11:46:09 +0000926 BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
Alexey Samsonovd6f62c82012-11-29 18:27:01 +0000927 if (BL->isIn(M)) return false;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000928 C = &(M.getContext());
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000929 int LongSize = TD->getPointerSizeInBits();
930 IntptrTy = Type::getIntNTy(*C, LongSize);
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000931 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov46848582012-12-25 12:28:20 +0000932 initializeCallbacks(M);
933 DynamicallyInitializedGlobals.Init(M);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000934
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000935 SmallVector<GlobalVariable *, 16> GlobalsToChange;
936
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000937 for (Module::GlobalListType::iterator G = M.global_begin(),
938 E = M.global_end(); G != E; ++G) {
939 if (ShouldInstrumentGlobal(G))
940 GlobalsToChange.push_back(G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000941 }
942
943 size_t n = GlobalsToChange.size();
944 if (n == 0) return false;
945
946 // A global is described by a structure
947 // size_t beg;
948 // size_t size;
949 // size_t size_with_redzone;
950 // const char *name;
Kostya Serebryany086a4722013-03-18 08:05:29 +0000951 // const char *module_name;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000952 // size_t has_dynamic_init;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000953 // We initialize an array of such structures and pass it to a run-time call.
954 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000955 IntptrTy, IntptrTy,
Kostya Serebryany086a4722013-03-18 08:05:29 +0000956 IntptrTy, IntptrTy, NULL);
Rafael Espindola8819c842013-10-01 13:32:03 +0000957 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000958
959 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
960 assert(CtorFunc);
961 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000962
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000963 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000964
Kostya Serebryany086a4722013-03-18 08:05:29 +0000965 GlobalVariable *ModuleName = createPrivateGlobalForString(
966 M, M.getModuleIdentifier());
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000967 // We shouldn't merge same module names, as this string serves as unique
968 // module ID in runtime.
969 ModuleName->setUnnamedAddr(false);
Kostya Serebryany086a4722013-03-18 08:05:29 +0000970
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000971 for (size_t i = 0; i < n; i++) {
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000972 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000973 GlobalVariable *G = GlobalsToChange[i];
974 PointerType *PtrTy = cast<PointerType>(G->getType());
975 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000976 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000977 uint64_t MinRZ = RedzoneSize();
Kostya Serebryany63f08462013-01-24 10:35:40 +0000978 // MinRZ <= RZ <= kMaxGlobalRedzone
979 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000980 uint64_t RZ = std::max(MinRZ,
Kostya Serebryany63f08462013-01-24 10:35:40 +0000981 std::min(kMaxGlobalRedzone,
982 (SizeInBytes / MinRZ / 4) * MinRZ));
983 uint64_t RightRedzoneSize = RZ;
984 // Round up to MinRZ
985 if (SizeInBytes % MinRZ)
986 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
987 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000988 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000989 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000990 bool GlobalHasDynamicInitializer =
991 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000992 // Don't check initialization order if this global is blacklisted.
Peter Collingbourne46e11c42013-07-09 22:03:17 +0000993 GlobalHasDynamicInitializer &= !BL->isIn(*G, "init");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000994
995 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
996 Constant *NewInitializer = ConstantStruct::get(
997 NewTy, G->getInitializer(),
998 Constant::getNullValue(RightRedZoneTy), NULL);
999
Kostya Serebryany086a4722013-03-18 08:05:29 +00001000 GlobalVariable *Name = createPrivateGlobalForString(M, G->getName());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001001
1002 // Create a new global variable with enough space for a redzone.
Bill Wendling55a1a592013-08-06 22:52:42 +00001003 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1004 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1005 Linkage = GlobalValue::InternalLinkage;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001006 GlobalVariable *NewGlobal = new GlobalVariable(
Bill Wendling55a1a592013-08-06 22:52:42 +00001007 M, NewTy, G->isConstant(), Linkage,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001008 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001009 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany63f08462013-01-24 10:35:40 +00001010 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001011
1012 Value *Indices2[2];
1013 Indices2[0] = IRB.getInt32(0);
1014 Indices2[1] = IRB.getInt32(0);
1015
1016 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +00001017 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001018 NewGlobal->takeName(G);
1019 G->eraseFromParent();
1020
1021 Initializers[i] = ConstantStruct::get(
1022 GlobalStructTy,
1023 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
1024 ConstantInt::get(IntptrTy, SizeInBytes),
1025 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1026 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany086a4722013-03-18 08:05:29 +00001027 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001028 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001029 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001030
1031 // Populate the first and last globals declared in this TU.
Alexey Samsonovca825ea2013-03-26 13:05:41 +00001032 if (CheckInitOrder && GlobalHasDynamicInitializer)
1033 HasDynamicallyInitializedGlobals = true;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001034
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001035 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001036 }
1037
1038 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1039 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling55a1a592013-08-06 22:52:42 +00001040 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001041 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1042
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001043 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonovca825ea2013-03-26 13:05:41 +00001044 if (CheckInitOrder && HasDynamicallyInitializedGlobals)
1045 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001046 IRB.CreateCall2(AsanRegisterGlobals,
1047 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1048 ConstantInt::get(IntptrTy, n));
1049
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001050 // We also need to unregister globals at the end, e.g. when a shared library
1051 // gets closed.
1052 Function *AsanDtorFunction = Function::Create(
1053 FunctionType::get(Type::getVoidTy(*C), false),
1054 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1055 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1056 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001057 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1058 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1059 ConstantInt::get(IntptrTy, n));
1060 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
1061
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001062 DEBUG(dbgs() << M);
1063 return true;
1064}
1065
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001066void AddressSanitizer::initializeCallbacks(Module &M) {
1067 IRBuilder<> IRB(*C);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001068 // Create __asan_report* callbacks.
1069 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1070 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1071 AccessSizeIndex++) {
1072 // IsWrite and TypeSize are encoded in the function name.
1073 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
1074 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +00001075 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany7846c1c2012-11-07 12:42:18 +00001076 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1077 checkInterfaceFunction(M.getOrInsertFunction(
1078 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001079 }
1080 }
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +00001081 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1082 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1083 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1084 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001085
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001086 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
1087 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
Kostya Serebryanyf7b08222012-07-20 09:54:50 +00001088 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1089 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1090 StringRef(""), StringRef(""),
1091 /*hasSideEffects=*/true);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001092}
1093
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001094void AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const {
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001095 // Tell the values of mapping offset and scale to the run-time.
1096 GlobalValue *asan_mapping_offset =
1097 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1098 ConstantInt::get(IntptrTy, Mapping.Offset),
1099 kAsanMappingOffsetName);
1100 // Read the global, otherwise it may be optimized away.
1101 IRB.CreateLoad(asan_mapping_offset, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001102
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001103 GlobalValue *asan_mapping_scale =
1104 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1105 ConstantInt::get(IntptrTy, Mapping.Scale),
1106 kAsanMappingScaleName);
1107 // Read the global, otherwise it may be optimized away.
1108 IRB.CreateLoad(asan_mapping_scale, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001109}
1110
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001111// virtual
1112bool AddressSanitizer::doInitialization(Module &M) {
1113 // Initialize the private fields. No one has accessed them before.
1114 TD = getAnalysisIfAvailable<DataLayout>();
1115
1116 if (!TD)
1117 return false;
Alexey Samsonove39e1312013-08-12 11:46:09 +00001118 BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001119 DynamicallyInitializedGlobals.Init(M);
1120
1121 C = &(M.getContext());
1122 LongSize = TD->getPointerSizeInBits();
1123 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001124
1125 AsanCtorFunction = Function::Create(
1126 FunctionType::get(Type::getVoidTy(*C), false),
1127 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1128 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1129 // call __asan_init in the module ctor.
1130 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1131 AsanInitFunction = checkInterfaceFunction(
1132 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1133 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1134 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001135
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001136 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001137 emitShadowMapping(M, IRB);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001138
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001139 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001140 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001141}
1142
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001143bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1144 // For each NSObject descendant having a +load method, this method is invoked
1145 // by the ObjC runtime before any of the static constructors is called.
1146 // Therefore we need to instrument such methods with a call to __asan_init
1147 // at the beginning in order to initialize our runtime before any access to
1148 // the shadow memory.
1149 // We cannot just ignore these methods, because they may call other
1150 // instrumented functions.
1151 if (F.getName().find(" load]") != std::string::npos) {
1152 IRBuilder<> IRB(F.begin()->begin());
1153 IRB.CreateCall(AsanInitFunction);
1154 return true;
1155 }
1156 return false;
1157}
1158
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001159bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001160 if (BL->isIn(F)) return false;
1161 if (&F == AsanCtorFunction) return false;
Kostya Serebryany3797adb2013-03-18 07:33:49 +00001162 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001163 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001164 initializeCallbacks(*F.getParent());
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001165
Kostya Serebryany8eec41f2013-02-26 06:58:09 +00001166 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001167 maybeInsertAsanInitAtFunctionEntry(F);
1168
Kostya Serebryany20985712013-06-26 09:18:17 +00001169 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
Bill Wendling67658342012-10-09 07:45:08 +00001170 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001171
1172 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1173 return false;
Bill Wendling67658342012-10-09 07:45:08 +00001174
1175 // We want to instrument every address only once per basic block (unless there
1176 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001177 SmallSet<Value*, 16> TempsToInstrument;
1178 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001179 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryany20985712013-06-26 09:18:17 +00001180 int NumAllocas = 0;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001181 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001182
1183 // Fill the set of memory operations to instrument.
1184 for (Function::iterator FI = F.begin(), FE = F.end();
1185 FI != FE; ++FI) {
1186 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001187 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001188 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1189 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +00001190 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001191 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001192 if (ClOpt && ClOptSameTemp) {
1193 if (!TempsToInstrument.insert(Addr))
1194 continue; // We've seen this temp in the current BB.
1195 }
1196 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1197 // ok, take it.
1198 } else {
Kostya Serebryany20985712013-06-26 09:18:17 +00001199 if (isa<AllocaInst>(BI))
1200 NumAllocas++;
Kostya Serebryany1479c9b2013-02-20 12:35:15 +00001201 CallSite CS(BI);
1202 if (CS) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001203 // A call inside BB.
1204 TempsToInstrument.clear();
Kostya Serebryany1479c9b2013-02-20 12:35:15 +00001205 if (CS.doesNotReturn())
1206 NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001207 }
1208 continue;
1209 }
1210 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001211 NumInsnsPerBB++;
1212 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1213 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001214 }
1215 }
1216
Kostya Serebryany20985712013-06-26 09:18:17 +00001217 Function *UninstrumentedDuplicate = 0;
1218 bool LikelyToInstrument =
1219 !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1220 if (ClKeepUninstrumented && LikelyToInstrument) {
1221 ValueToValueMapTy VMap;
1222 UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1223 UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1224 UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1225 F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1226 }
1227
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001228 // Instrument.
1229 int NumInstrumented = 0;
1230 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1231 Instruction *Inst = ToInstrument[i];
1232 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1233 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001234 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001235 instrumentMop(Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001236 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001237 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001238 }
1239 NumInstrumented++;
1240 }
1241
Alexey Samsonov59cca132012-12-25 12:04:36 +00001242 FunctionStackPoisoner FSP(F, *this);
1243 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001244
1245 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1246 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1247 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1248 Instruction *CI = NoReturnCalls[i];
1249 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001250 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001251 }
1252
Kostya Serebryany20985712013-06-26 09:18:17 +00001253 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1254 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1255
1256 if (ClKeepUninstrumented) {
1257 if (!res) {
1258 // No instrumentation is done, no need for the duplicate.
1259 if (UninstrumentedDuplicate)
1260 UninstrumentedDuplicate->eraseFromParent();
1261 } else {
1262 // The function was instrumented. We must have the duplicate.
1263 assert(UninstrumentedDuplicate);
1264 UninstrumentedDuplicate->setSection("NOASAN");
1265 assert(!F.hasSection());
1266 F.setSection("ASAN");
1267 }
1268 }
1269
1270 return res;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001271}
1272
1273static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1274 if (ShadowRedzoneSize == 1) return PoisonByte;
1275 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1276 if (ShadowRedzoneSize == 4)
1277 return (PoisonByte << 24) + (PoisonByte << 16) +
1278 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +00001279 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001280}
1281
1282static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1283 size_t Size,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001284 size_t RZSize,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001285 size_t ShadowGranularity,
1286 uint8_t Magic) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001287 for (size_t i = 0; i < RZSize;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001288 i+= ShadowGranularity, Shadow++) {
1289 if (i + ShadowGranularity <= Size) {
1290 *Shadow = 0; // fully addressable
1291 } else if (i >= Size) {
1292 *Shadow = Magic; // unaddressable
1293 } else {
1294 *Shadow = Size - i; // first Size-i bytes are addressable
1295 }
1296 }
1297}
1298
Alexey Samsonov59cca132012-12-25 12:04:36 +00001299// Workaround for bug 11395: we don't want to instrument stack in functions
1300// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1301// FIXME: remove once the bug 11395 is fixed.
1302bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1303 if (LongSize != 32) return false;
1304 CallInst *CI = dyn_cast<CallInst>(I);
1305 if (!CI || !CI->isInlineAsm()) return false;
1306 if (CI->getNumArgOperands() <= 5) return false;
1307 // We have inline assembly with quite a few arguments.
1308 return true;
1309}
1310
1311void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1312 IRBuilder<> IRB(*C);
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001313 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1314 std::string Suffix = itostr(i);
1315 AsanStackMallocFunc[i] = checkInterfaceFunction(
1316 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1317 IntptrTy, IntptrTy, NULL));
1318 AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1319 kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1320 IntptrTy, IntptrTy, NULL));
1321 }
Alexey Samsonov59cca132012-12-25 12:04:36 +00001322 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1323 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1324 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1325 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1326}
1327
1328void FunctionStackPoisoner::poisonRedZones(
Jakub Staszak4c710642013-08-09 20:53:48 +00001329 const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> &IRB, Value *ShadowBase,
Alexey Samsonov59cca132012-12-25 12:04:36 +00001330 bool DoPoison) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001331 size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001332 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1333 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1334 Type *RZPtrTy = PointerType::get(RZTy, 0);
1335
1336 Value *PoisonLeft = ConstantInt::get(RZTy,
1337 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1338 Value *PoisonMid = ConstantInt::get(RZTy,
1339 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1340 Value *PoisonRight = ConstantInt::get(RZTy,
1341 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1342
1343 // poison the first red zone.
1344 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1345
1346 // poison all other red zones.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001347 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001348 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1349 AllocaInst *AI = AllocaVec[i];
1350 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1351 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001352 assert(AlignedSize - SizeInBytes < RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001353 Value *Ptr = NULL;
1354
1355 Pos += AlignedSize;
1356
1357 assert(ShadowBase->getType() == IntptrTy);
1358 if (SizeInBytes < AlignedSize) {
1359 // Poison the partial redzone at right
1360 Ptr = IRB.CreateAdd(
1361 ShadowBase, ConstantInt::get(IntptrTy,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001362 (Pos >> Mapping.Scale) - ShadowRZSize));
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001363 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001364 uint32_t Poison = 0;
1365 if (DoPoison) {
1366 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001367 RedzoneSize(),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001368 1ULL << Mapping.Scale,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001369 kAsanStackPartialRedzoneMagic);
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +00001370 Poison =
1371 ASan.TD->isLittleEndian()
1372 ? support::endian::byte_swap<uint32_t, support::little>(Poison)
1373 : support::endian::byte_swap<uint32_t, support::big>(Poison);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001374 }
1375 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1376 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1377 }
1378
1379 // Poison the full redzone at right.
1380 Ptr = IRB.CreateAdd(ShadowBase,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001381 ConstantInt::get(IntptrTy, Pos >> Mapping.Scale));
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001382 bool LastAlloca = (i == AllocaVec.size() - 1);
1383 Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001384 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1385
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001386 Pos += RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001387 }
1388}
1389
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001390// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1391// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1392static int StackMallocSizeClass(uint64_t LocalStackSize) {
1393 assert(LocalStackSize <= kMaxStackMallocSize);
1394 uint64_t MaxSize = kMinStackMallocSize;
1395 for (int i = 0; ; i++, MaxSize *= 2)
1396 if (LocalStackSize <= MaxSize)
1397 return i;
1398 llvm_unreachable("impossible LocalStackSize");
1399}
1400
Kostya Serebryany671c3ba2013-09-17 12:14:50 +00001401// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1402// We can not use MemSet intrinsic because it may end up calling the actual
1403// memset. Size is a multiple of 8.
1404// Currently this generates 8-byte stores on x86_64; it may be better to
1405// generate wider stores.
1406void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1407 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1408 assert(!(Size % 8));
1409 assert(kAsanStackAfterReturnMagic == 0xf5);
1410 for (int i = 0; i < Size; i += 8) {
1411 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1412 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1413 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1414 }
1415}
1416
Alexey Samsonov59cca132012-12-25 12:04:36 +00001417void FunctionStackPoisoner::poisonStack() {
Alexey Samsonov59cca132012-12-25 12:04:36 +00001418 uint64_t LocalStackSize = TotalStackSize +
1419 (AllocaVec.size() + 1) * RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001420
Alexey Samsonov59cca132012-12-25 12:04:36 +00001421 bool DoStackMalloc = ASan.CheckUseAfterReturn
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001422 && LocalStackSize <= kMaxStackMallocSize;
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001423 int StackMallocIdx = -1;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001424
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001425 assert(AllocaVec.size() > 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001426 Instruction *InsBefore = AllocaVec[0];
1427 IRBuilder<> IRB(InsBefore);
1428
1429
1430 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1431 AllocaInst *MyAlloca =
1432 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Alexey Samsonov59cca132012-12-25 12:04:36 +00001433 if (ClRealignStack && StackAlignment < RedzoneSize())
1434 StackAlignment = RedzoneSize();
1435 MyAlloca->setAlignment(StackAlignment);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001436 assert(MyAlloca->isStaticAlloca());
1437 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1438 Value *LocalStackBase = OrigStackBase;
1439
1440 if (DoStackMalloc) {
Kostya Serebryanyac04aba2013-09-18 14:07:14 +00001441 // LocalStackBase = OrigStackBase
1442 // if (__asan_option_detect_stack_use_after_return)
1443 // LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001444 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1445 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
Kostya Serebryanyac04aba2013-09-18 14:07:14 +00001446 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1447 kAsanOptionDetectUAR, IRB.getInt32Ty());
1448 Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1449 Constant::getNullValue(IRB.getInt32Ty()));
1450 Instruction *Term =
1451 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
1452 BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1453 IRBuilder<> IRBIf(Term);
1454 LocalStackBase = IRBIf.CreateCall2(
1455 AsanStackMallocFunc[StackMallocIdx],
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001456 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
Kostya Serebryanyac04aba2013-09-18 14:07:14 +00001457 BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1458 IRB.SetInsertPoint(InsBefore);
1459 PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1460 Phi->addIncoming(OrigStackBase, CmpBlock);
1461 Phi->addIncoming(LocalStackBase, SetBlock);
1462 LocalStackBase = Phi;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001463 }
1464
Kostya Serebryany30160562013-03-22 10:37:20 +00001465 // This string will be parsed by the run-time (DescribeAddressIfStack).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001466 SmallString<2048> StackDescriptionStorage;
1467 raw_svector_ostream StackDescription(StackDescriptionStorage);
Kostya Serebryany30160562013-03-22 10:37:20 +00001468 StackDescription << AllocaVec.size() << " ";
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001469
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001470 // Insert poison calls for lifetime intrinsics for alloca.
1471 bool HavePoisonedAllocas = false;
1472 for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1473 const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1474 IntrinsicInst *II = APC.InsBefore;
1475 AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
1476 assert(AI);
1477 IRBuilder<> IRB(II);
1478 poisonAlloca(AI, APC.Size, IRB, APC.DoPoison);
1479 HavePoisonedAllocas |= APC.DoPoison;
1480 }
1481
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001482 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001483 // Replace Alloca instructions with base+offset.
1484 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1485 AllocaInst *AI = AllocaVec[i];
1486 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1487 StringRef Name = AI->getName();
1488 StackDescription << Pos << " " << SizeInBytes << " "
1489 << Name.size() << " " << Name << " ";
1490 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001491 assert((AlignedSize % RedzoneSize()) == 0);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001492 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001493 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
Alexey Samsonovf985f442012-12-04 01:34:23 +00001494 AI->getType());
Alexey Samsonov1afbb512012-12-12 14:31:53 +00001495 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001496 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001497 Pos += AlignedSize + RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001498 }
1499 assert(Pos == LocalStackSize);
1500
Kostya Serebryany30160562013-03-22 10:37:20 +00001501 // The left-most redzone has enough space for at least 4 pointers.
1502 // Write the Magic value to redzone[0].
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001503 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1504 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1505 BasePlus0);
Kostya Serebryany30160562013-03-22 10:37:20 +00001506 // Write the frame description constant to redzone[1].
1507 Value *BasePlus1 = IRB.CreateIntToPtr(
1508 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1509 IntptrPtrTy);
Alexey Samsonov9ce84c12012-11-02 12:20:34 +00001510 GlobalVariable *StackDescriptionGlobal =
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001511 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
Alexey Samsonov59cca132012-12-25 12:04:36 +00001512 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1513 IntptrTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001514 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryany30160562013-03-22 10:37:20 +00001515 // Write the PC to redzone[2].
1516 Value *BasePlus2 = IRB.CreateIntToPtr(
1517 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1518 2 * ASan.LongSize/8)),
1519 IntptrPtrTy);
1520 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001521
1522 // Poison the stack redzones at the entry.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001523 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1524 poisonRedZones(AllocaVec, IRB, ShadowBase, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001525
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001526 // Unpoison the stack before all ret instructions.
1527 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1528 Instruction *Ret = RetVec[i];
1529 IRBuilder<> IRBRet(Ret);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001530 // Mark the current frame as retired.
1531 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1532 BasePlus0);
1533 // Unpoison the stack.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001534 poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001535 if (DoStackMalloc) {
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001536 assert(StackMallocIdx >= 0);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001537 // In use-after-return mode, mark the whole stack frame unaddressable.
Kostya Serebryany671c3ba2013-09-17 12:14:50 +00001538 if (StackMallocIdx <= 4) {
1539 // For small sizes inline the whole thing:
1540 // if LocalStackBase != OrigStackBase:
1541 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1542 // **SavedFlagPtr(LocalStackBase) = 0
1543 // FIXME: if LocalStackBase != OrigStackBase don't call poisonRedZones.
1544 Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1545 TerminatorInst *PoisonTerm =
1546 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
1547 IRBuilder<> IRBPoison(PoisonTerm);
1548 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1549 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1550 ClassSize >> Mapping.Scale);
1551 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1552 LocalStackBase,
1553 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1554 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1555 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1556 IRBPoison.CreateStore(
1557 Constant::getNullValue(IRBPoison.getInt8Ty()),
1558 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1559 } else {
1560 // For larger frames call __asan_stack_free_*.
1561 IRBRet.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1562 ConstantInt::get(IntptrTy, LocalStackSize),
1563 OrigStackBase);
1564 }
Alexey Samsonovf985f442012-12-04 01:34:23 +00001565 } else if (HavePoisonedAllocas) {
1566 // If we poisoned some allocas in llvm.lifetime analysis,
1567 // unpoison whole stack frame now.
1568 assert(LocalStackBase == OrigStackBase);
1569 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001570 }
1571 }
1572
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001573 // We are done. Remove the old unused alloca instructions.
1574 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1575 AllocaVec[i]->eraseFromParent();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001576}
Alexey Samsonovf985f442012-12-04 01:34:23 +00001577
Alexey Samsonov59cca132012-12-25 12:04:36 +00001578void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak4c710642013-08-09 20:53:48 +00001579 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001580 // For now just insert the call to ASan runtime.
1581 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1582 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1583 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1584 : AsanUnpoisonStackMemoryFunc,
1585 AddrArg, SizeArg);
1586}
Alexey Samsonov59cca132012-12-25 12:04:36 +00001587
1588// Handling llvm.lifetime intrinsics for a given %alloca:
1589// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1590// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1591// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1592// could be poisoned by previous llvm.lifetime.end instruction, as the
1593// variable may go in and out of scope several times, e.g. in loops).
1594// (3) if we poisoned at least one %alloca in a function,
1595// unpoison the whole stack frame at function exit.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001596
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001597AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1598 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1599 // We're intested only in allocas we can handle.
1600 return isInterestingAlloca(*AI) ? AI : 0;
1601 // See if we've already calculated (or started to calculate) alloca for a
1602 // given value.
1603 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1604 if (I != AllocaForValue.end())
1605 return I->second;
1606 // Store 0 while we're calculating alloca for value V to avoid
1607 // infinite recursion if the value references itself.
1608 AllocaForValue[V] = 0;
1609 AllocaInst *Res = 0;
1610 if (CastInst *CI = dyn_cast<CastInst>(V))
1611 Res = findAllocaForValue(CI->getOperand(0));
1612 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1613 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1614 Value *IncValue = PN->getIncomingValue(i);
1615 // Allow self-referencing phi-nodes.
1616 if (IncValue == PN) continue;
1617 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1618 // AI for incoming values should exist and should all be equal.
1619 if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1620 return 0;
1621 Res = IncValueAI;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001622 }
Alexey Samsonov59cca132012-12-25 12:04:36 +00001623 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001624 if (Res != 0)
1625 AllocaForValue[V] = Res;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001626 return Res;
1627}