blob: 779ef66069eaaa8e349f2c5f0d6474e5e7576689 [file] [log] [blame]
Kostya Serebryany6e6b03e2011-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
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000017#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov29dd7f22012-12-27 08:50:58 +000018#include "llvm/ADT/DenseMap.h"
Alexey Samsonov4f319cc2014-07-02 16:54:41 +000019#include "llvm/ADT/DenseSet.h"
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +000020#include "llvm/ADT/DepthFirstIterator.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000021#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/SmallString.h"
23#include "llvm/ADT/SmallVector.h"
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +000024#include "llvm/ADT/Statistic.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000025#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov617232f2012-05-23 11:52:12 +000026#include "llvm/ADT/Triple.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000027#include "llvm/IR/CallSite.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000028#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/Function.h"
31#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000033#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000036#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/Module.h"
38#include "llvm/IR/Type.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000039#include "llvm/Support/CommandLine.h"
40#include "llvm/Support/DataTypes.h"
41#include "llvm/Support/Debug.h"
Kostya Serebryany9e62b302013-06-03 14:46:56 +000042#include "llvm/Support/Endian.h"
Kostya Serebryany351b0782014-09-03 22:37:37 +000043#include "llvm/Transforms/Scalar.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000044#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany9f5213f2013-06-26 09:18:17 +000046#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000047#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000048#include "llvm/Transforms/Utils/ModuleUtils.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000049#include <algorithm>
Chandler Carruthed0881b2012-12-03 16:50:05 +000050#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000051#include <system_error>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000052
53using namespace llvm;
54
Chandler Carruth964daaa2014-04-22 02:55:47 +000055#define DEBUG_TYPE "asan"
56
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000057static const uint64_t kDefaultShadowScale = 3;
58static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +000059static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000060static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000061static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Kostya Serebryany4766fe62013-01-23 12:54:55 +000062static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +000063static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kostya Serebryany231bd082014-11-11 23:02:57 +000064static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000065static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
66static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000067
Kostya Serebryany6805de52013-09-10 13:16:56 +000068static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000069static const size_t kMaxStackMallocSize = 1 << 16; // 64K
70static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
71static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
72
Craig Topperd3a34f82013-07-16 01:17:10 +000073static const char *const kAsanModuleCtorName = "asan.module_ctor";
74static const char *const kAsanModuleDtorName = "asan.module_dtor";
Kostya Serebryany34ddf872014-09-24 22:41:55 +000075static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000076static const char *const kAsanReportErrorTemplate = "__asan_report_";
77static const char *const kAsanReportLoadN = "__asan_report_load_n";
78static const char *const kAsanReportStoreN = "__asan_report_store_n";
79static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000080static const char *const kAsanUnregisterGlobalsName =
81 "__asan_unregister_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +000082static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
83static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Alexey Samsonov4f319cc2014-07-02 16:54:41 +000084static const char *const kAsanInitName = "__asan_init_v4";
Kostya Serebryany796f6552014-02-27 12:45:36 +000085static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
86static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +000087static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany6805de52013-09-10 13:16:56 +000088static const int kMaxAsanStackMallocSizeClass = 10;
89static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
90static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +000091static const char *const kAsanGenPrefix = "__asan_gen_";
92static const char *const kAsanPoisonStackMemoryName =
93 "__asan_poison_stack_memory";
94static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +000095 "__asan_unpoison_stack_memory";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000096
Kostya Serebryanyf3223822013-09-18 14:07:14 +000097static const char *const kAsanOptionDetectUAR =
98 "__asan_option_detect_stack_use_after_return";
99
David Blaikieeacc2872013-09-18 00:11:27 +0000100#ifndef NDEBUG
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000101static const int kAsanStackAfterReturnMagic = 0xf5;
David Blaikieeacc2872013-09-18 00:11:27 +0000102#endif
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000103
Kostya Serebryany874dae62012-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 Serebryany6e6b03e2011-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 Serebryany90241602012-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 Serebryany1e575ab2012-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 Serebryany874dae62012-07-16 16:15:40 +0000120// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-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 Serebryany6e6b03e2011-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));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000131static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000132 cl::desc("Check return-after-free"), cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000133// This flag may need to be replaced with -f[no]asan-globals.
134static cl::opt<bool> ClGlobals("asan-globals",
135 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000136static cl::opt<bool> ClInitializers("asan-initialization-order",
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000137 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(true));
Kostya Serebryany796f6552014-02-27 12:45:36 +0000138static cl::opt<bool> ClInvalidPointerPairs("asan-detect-invalid-pointer-pair",
139 cl::desc("Instrument <, <=, >, >=, - with pointer operands"),
Kostya Serebryanyec346652014-02-27 12:56:20 +0000140 cl::Hidden, cl::init(false));
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000141static cl::opt<unsigned> ClRealignStack("asan-realign-stack",
142 cl::desc("Realign stack to the value of this flag (power of two)"),
143 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000144static cl::opt<int> ClInstrumentationWithCallsThreshold(
145 "asan-instrumentation-with-call-threshold",
146 cl::desc("If the function being instrumented contains more than "
147 "this number of memory accesses, use callbacks instead of "
148 "inline checks (-1 means never use callbacks)."),
Kostya Serebryany4d237a82014-05-26 11:57:16 +0000149 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000150static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
151 "asan-memory-access-callback-prefix",
152 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
153 cl::init("__asan_"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000154
Kostya Serebryany9f5213f2013-06-26 09:18:17 +0000155// This is an experimental feature that will allow to choose between
156// instrumented and non-instrumented code at link-time.
157// If this option is on, just before instrumenting a function we create its
158// clone; if the function is not changed by asan the clone is deleted.
159// If we end up with a clone, we put the instrumented function into a section
160// called "ASAN" and the uninstrumented function into a section called "NOASAN".
161//
162// This is still a prototype, we need to figure out a way to keep two copies of
163// a function so that the linker can easily choose one of them.
164static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
165 cl::desc("Keep uninstrumented copies of functions"),
166 cl::Hidden, cl::init(false));
167
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000168// These flags allow to change the shadow mapping.
169// The shadow mapping looks like
170// Shadow = (Mem >> scale) + (1 << offset_log)
171static cl::opt<int> ClMappingScale("asan-mapping-scale",
172 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000173
174// Optimization flags. Not user visible, used mostly for testing
175// and benchmarking the tool.
176static cl::opt<bool> ClOpt("asan-opt",
177 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
178static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
179 cl::desc("Instrument the same temp just once"), cl::Hidden,
180 cl::init(true));
181static cl::opt<bool> ClOptGlobals("asan-opt-globals",
182 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
183
Alexey Samsonovdf624522012-11-29 18:14:24 +0000184static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
185 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
186 cl::Hidden, cl::init(false));
187
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000188// Debug flags.
189static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
190 cl::init(0));
191static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
192 cl::Hidden, cl::init(0));
193static cl::opt<std::string> ClDebugFunc("asan-debug-func",
194 cl::Hidden, cl::desc("Debug func"));
195static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
196 cl::Hidden, cl::init(-1));
197static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
198 cl::Hidden, cl::init(-1));
199
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000200STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
201STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
202STATISTIC(NumOptimizedAccessesToGlobalArray,
203 "Number of optimized accesses to global arrays");
204STATISTIC(NumOptimizedAccessesToGlobalVar,
205 "Number of optimized accesses to global vars");
206
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000207namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000208/// Frontend-provided metadata for source location.
209struct LocationMetadata {
210 StringRef Filename;
211 int LineNo;
212 int ColumnNo;
213
214 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
215
216 bool empty() const { return Filename.empty(); }
217
218 void parse(MDNode *MDN) {
219 assert(MDN->getNumOperands() == 3);
220 MDString *MDFilename = cast<MDString>(MDN->getOperand(0));
221 Filename = MDFilename->getString();
222 LineNo = cast<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
223 ColumnNo = cast<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
224 }
225};
226
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000227/// Frontend-provided metadata for global variables.
228class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000229 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000230 struct Entry {
Alexey Samsonov15c96692014-07-12 00:42:52 +0000231 Entry()
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000232 : SourceLoc(), Name(), IsDynInit(false),
Alexey Samsonov15c96692014-07-12 00:42:52 +0000233 IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000234 LocationMetadata SourceLoc;
235 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000236 bool IsDynInit;
237 bool IsBlacklisted;
238 };
239
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000240 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000241
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000242 void init(Module& M) {
243 assert(!inited_);
244 inited_ = true;
245 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
246 if (!Globals)
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000247 return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000248 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000249 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000250 assert(MDN->getNumOperands() == 5);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000251 Value *V = MDN->getOperand(0);
252 // The optimizer may optimize away a global entirely.
253 if (!V)
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000254 continue;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000255 GlobalVariable *GV = cast<GlobalVariable>(V);
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000256 // We can already have an entry for GV if it was merged with another
257 // global.
258 Entry &E = Entries[GV];
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000259 if (Value *Loc = MDN->getOperand(1))
260 E.SourceLoc.parse(cast<MDNode>(Loc));
Alexey Samsonov15c96692014-07-12 00:42:52 +0000261 if (Value *Name = MDN->getOperand(2)) {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000262 MDString *MDName = cast<MDString>(Name);
263 E.Name = MDName->getString();
Alexey Samsonov15c96692014-07-12 00:42:52 +0000264 }
265 ConstantInt *IsDynInit = cast<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000266 E.IsDynInit |= IsDynInit->isOne();
Alexey Samsonov15c96692014-07-12 00:42:52 +0000267 ConstantInt *IsBlacklisted = cast<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000268 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000269 }
270 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000271
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000272 /// Returns metadata entry for a given global.
273 Entry get(GlobalVariable *G) const {
274 auto Pos = Entries.find(G);
275 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000276 }
277
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000278 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000279 bool inited_;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000280 DenseMap<GlobalVariable*, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000281};
282
Alexey Samsonov1345d352013-01-16 13:23:28 +0000283/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000284/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000285struct ShadowMapping {
286 int Scale;
287 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000288 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000289};
290
Evgeniy Stepanov13665362014-01-16 10:19:12 +0000291static ShadowMapping getShadowMapping(const Module &M, int LongSize) {
Alexey Samsonov347bcd32013-01-17 11:12:32 +0000292 llvm::Triple TargetTriple(M.getTargetTriple());
293 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Bob Wilson9868d712014-10-09 05:43:30 +0000294 bool IsIOS = TargetTriple.isiOS();
Kostya Serebryany8baa3862014-02-10 07:37:04 +0000295 bool IsFreeBSD = TargetTriple.getOS() == llvm::Triple::FreeBSD;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000296 bool IsLinux = TargetTriple.getOS() == llvm::Triple::Linux;
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000297 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
298 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000299 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000300 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
301 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000302 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
303 TargetTriple.getArch() == llvm::Triple::mips64el;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000304
305 ShadowMapping Mapping;
306
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000307 if (LongSize == 32) {
308 if (IsAndroid)
309 Mapping.Offset = 0;
310 else if (IsMIPS32)
311 Mapping.Offset = kMIPS32_ShadowOffset32;
312 else if (IsFreeBSD)
313 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000314 else if (IsIOS)
315 Mapping.Offset = kIOSShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000316 else
317 Mapping.Offset = kDefaultShadowOffset32;
318 } else { // LongSize == 64
319 if (IsPPC64)
320 Mapping.Offset = kPPC64_ShadowOffset64;
321 else if (IsFreeBSD)
322 Mapping.Offset = kFreeBSD_ShadowOffset64;
323 else if (IsLinux && IsX86_64)
324 Mapping.Offset = kSmallX86_64ShadowOffset;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000325 else if (IsMIPS64)
326 Mapping.Offset = kMIPS64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000327 else
328 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000329 }
330
331 Mapping.Scale = kDefaultShadowScale;
332 if (ClMappingScale) {
333 Mapping.Scale = ClMappingScale;
334 }
335
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000336 // OR-ing shadow offset if more efficient (at least on x86) if the offset
337 // is a power of two, but on ppc64 we have to use add since the shadow
338 // offset is not necessary 1/8-th of the address space.
339 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
340
Alexey Samsonov1345d352013-01-16 13:23:28 +0000341 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000342}
343
Alexey Samsonov1345d352013-01-16 13:23:28 +0000344static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000345 // Redzone used for stack and globals is at least 32 bytes.
346 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000347 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000348}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000349
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000350/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000351struct AddressSanitizer : public FunctionPass {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000352 AddressSanitizer() : FunctionPass(ID) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000353 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000354 return "AddressSanitizerFunctionPass";
355 }
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000356 void instrumentMop(Instruction *I, bool UseCalls);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000357 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000358 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
359 Value *Addr, uint32_t TypeSize, bool IsWrite,
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000360 Value *SizeArgument, bool UseCalls);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000361 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
362 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000363 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000364 bool IsWrite, size_t AccessSizeIndex,
365 Value *SizeArgument);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000366 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000367 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000368 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000369 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000370 bool doInitialization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000371 static char ID; // Pass identification, replacement for typeid
372
373 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000374 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000375
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000376 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000377 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000378
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000379 LLVMContext *C;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000380 const DataLayout *DL;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000381 int LongSize;
382 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000383 ShadowMapping Mapping;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000384 Function *AsanCtorFunction;
385 Function *AsanInitFunction;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000386 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000387 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Kostya Serebryany4273bb02012-07-16 14:09:42 +0000388 // This array is indexed by AccessIsWrite and log2(AccessSize).
389 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000390 Function *AsanMemoryAccessCallback[2][kNumberOfAccessSizes];
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000391 // This array is indexed by AccessIsWrite.
Kostya Serebryany86332c02014-04-21 07:10:43 +0000392 Function *AsanErrorCallbackSized[2],
393 *AsanMemoryAccessCallbackSized[2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000394 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000395 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000396 GlobalsMetadata GlobalsMD;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000397
398 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000399};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000400
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000401class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000402 public:
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000403 AddressSanitizerModule() : ModulePass(ID) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000404 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000405 static char ID; // Pass identification, replacement for typeid
Craig Topper3e4c6972014-03-05 09:10:37 +0000406 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000407 return "AddressSanitizerModule";
408 }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000409
Kostya Serebryany20a79972012-11-22 03:18:50 +0000410 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000411 void initializeCallbacks(Module &M);
412
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000413 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000414 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000415 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000416 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000417 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000418 return RedzoneSizeForScale(Mapping.Scale);
419 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000420
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000421 GlobalsMetadata GlobalsMD;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000422 Type *IntptrTy;
423 LLVMContext *C;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000424 const DataLayout *DL;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000425 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000426 Function *AsanPoisonGlobals;
427 Function *AsanUnpoisonGlobals;
428 Function *AsanRegisterGlobals;
429 Function *AsanUnregisterGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000430};
431
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000432// Stack poisoning does not play well with exception handling.
433// When an exception is thrown, we essentially bypass the code
434// that unpoisones the stack. This is why the run-time library has
435// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
436// stack in the interceptor. This however does not work inside the
437// actual function which catches the exception. Most likely because the
438// compiler hoists the load of the shadow value somewhere too high.
439// This causes asan to report a non-existing bug on 453.povray.
440// It sounds like an LLVM bug.
441struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
442 Function &F;
443 AddressSanitizer &ASan;
444 DIBuilder DIB;
445 LLVMContext *C;
446 Type *IntptrTy;
447 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000448 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000449
450 SmallVector<AllocaInst*, 16> AllocaVec;
451 SmallVector<Instruction*, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000452 unsigned StackAlignment;
453
Kostya Serebryany6805de52013-09-10 13:16:56 +0000454 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
455 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000456 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
457
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000458 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
459 struct AllocaPoisonCall {
460 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000461 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000462 uint64_t Size;
463 bool DoPoison;
464 };
465 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
466
467 // Maps Value to an AllocaInst from which the Value is originated.
468 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
469 AllocaForValueMapTy AllocaForValue;
470
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000471 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
472 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
473 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Alexey Samsonov1345d352013-01-16 13:23:28 +0000474 Mapping(ASan.Mapping),
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000475 StackAlignment(1 << Mapping.Scale) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000476
477 bool runOnFunction() {
478 if (!ClStack) return false;
479 // Collect alloca, ret, lifetime instructions etc.
David Blaikieceec2bd2014-04-11 01:50:01 +0000480 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000481 visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000482
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000483 if (AllocaVec.empty()) return false;
484
485 initializeCallbacks(*F.getParent());
486
487 poisonStack();
488
489 if (ClDebugStack) {
490 DEBUG(dbgs() << F);
491 }
492 return true;
493 }
494
495 // Finds all static Alloca instructions and puts
496 // poisoned red zones around all of them.
497 // Then unpoison everything back before the function returns.
498 void poisonStack();
499
500 // ----------------------- Visitors.
501 /// \brief Collect all Ret instructions.
502 void visitReturnInst(ReturnInst &RI) {
503 RetVec.push_back(&RI);
504 }
505
506 /// \brief Collect Alloca instructions we want (and can) handle.
507 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000508 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000509
510 StackAlignment = std::max(StackAlignment, AI.getAlignment());
511 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000512 }
513
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000514 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
515 /// errors.
516 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000517 if (!ClCheckLifetime) return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000518 Intrinsic::ID ID = II.getIntrinsicID();
519 if (ID != Intrinsic::lifetime_start &&
520 ID != Intrinsic::lifetime_end)
521 return;
522 // Found lifetime intrinsic, add ASan instrumentation if necessary.
523 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
524 // If size argument is undefined, don't do anything.
525 if (Size->isMinusOne()) return;
526 // Check that size doesn't saturate uint64_t and can
527 // be stored in IntptrTy.
528 const uint64_t SizeValue = Size->getValue().getLimitedValue();
529 if (SizeValue == ~0ULL ||
530 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
531 return;
532 // Find alloca instruction that corresponds to llvm.lifetime argument.
533 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
534 if (!AI) return;
535 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000536 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000537 AllocaPoisonCallVec.push_back(APC);
538 }
539
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000540 // ---------------------- Helpers.
541 void initializeCallbacks(Module &M);
542
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000543 // Check if we want (and can) handle this alloca.
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000544 bool isInterestingAlloca(AllocaInst &AI) const {
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000545 return (!AI.isArrayAllocation() && AI.isStaticAlloca() &&
546 AI.getAllocatedType()->isSized() &&
547 // alloca() may be called with 0 size, ignore it.
548 getAllocaSizeInBytes(&AI) > 0);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000549 }
550
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000551 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000552 Type *Ty = AI->getAllocatedType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000553 uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000554 return SizeInBytes;
555 }
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000556 /// Finds alloca where the value comes from.
557 AllocaInst *findAllocaForValue(Value *V);
Craig Topper3af97222014-08-27 05:25:00 +0000558 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000559 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000560 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000561
562 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
563 int Size);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000564};
565
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000566} // namespace
567
568char AddressSanitizer::ID = 0;
569INITIALIZE_PASS(AddressSanitizer, "asan",
570 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
571 false, false)
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000572FunctionPass *llvm::createAddressSanitizerFunctionPass() {
573 return new AddressSanitizer();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000574}
575
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000576char AddressSanitizerModule::ID = 0;
577INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
578 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
579 "ModulePass", false, false)
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000580ModulePass *llvm::createAddressSanitizerModulePass() {
581 return new AddressSanitizerModule();
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000582}
583
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000584static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000585 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000586 assert(Res < kNumberOfAccessSizes);
587 return Res;
588}
589
Bill Wendling58f8cef2013-08-06 22:52:42 +0000590// \brief Create a constant for Str so that we can pass it to the run-time lib.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000591static GlobalVariable *createPrivateGlobalForString(
592 Module &M, StringRef Str, bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000593 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000594 // We use private linkage for module-local strings. If they can be merged
595 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000596 GlobalVariable *GV =
597 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000598 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
599 if (AllowMerging)
600 GV->setUnnamedAddr(true);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000601 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
602 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000603}
604
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000605/// \brief Create a global describing a source location.
606static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
607 LocationMetadata MD) {
608 Constant *LocData[] = {
609 createPrivateGlobalForString(M, MD.Filename, true),
610 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
611 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
612 };
613 auto LocStruct = ConstantStruct::getAnon(LocData);
614 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
615 GlobalValue::PrivateLinkage, LocStruct,
616 kAsanGenPrefix);
617 GV->setUnnamedAddr(true);
618 return GV;
619}
620
Kostya Serebryany139a9372012-11-20 14:16:08 +0000621static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
622 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000623}
624
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000625Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
626 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000627 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
628 if (Mapping.Offset == 0)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000629 return Shadow;
630 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000631 if (Mapping.OrShadowOffset)
632 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
633 else
634 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000635}
636
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000637// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000638void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
639 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000640 if (isa<MemTransferInst>(MI)) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000641 IRB.CreateCall3(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000642 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
643 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
644 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
645 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
646 } else if (isa<MemSetInst>(MI)) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000647 IRB.CreateCall3(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000648 AsanMemset,
649 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
650 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
651 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000652 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000653 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000654}
655
Kostya Serebryany90241602012-05-30 09:04:06 +0000656// If I is an interesting memory access, return the PointerOperand
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000657// and set IsWrite/Alignment. Otherwise return NULL.
658static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
659 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000660 // Skip memory accesses inserted by another instrumentation.
661 if (I->getMetadata("nosanitize"))
662 return nullptr;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000663 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000664 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000665 *IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000666 *Alignment = LI->getAlignment();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000667 return LI->getPointerOperand();
668 }
Kostya Serebryany90241602012-05-30 09:04:06 +0000669 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000670 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000671 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000672 *Alignment = SI->getAlignment();
Kostya Serebryany90241602012-05-30 09:04:06 +0000673 return SI->getPointerOperand();
674 }
675 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000676 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000677 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000678 *Alignment = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +0000679 return RMW->getPointerOperand();
680 }
681 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000682 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000683 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000684 *Alignment = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +0000685 return XCHG->getPointerOperand();
686 }
Craig Topperf40110f2014-04-25 05:29:35 +0000687 return nullptr;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000688}
689
Kostya Serebryany796f6552014-02-27 12:45:36 +0000690static bool isPointerOperand(Value *V) {
691 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
692}
693
694// This is a rough heuristic; it may cause both false positives and
695// false negatives. The proper implementation requires cooperation with
696// the frontend.
697static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
698 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
699 if (!Cmp->isRelational())
700 return false;
701 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +0000702 if (BO->getOpcode() != Instruction::Sub)
Kostya Serebryany796f6552014-02-27 12:45:36 +0000703 return false;
704 } else {
705 return false;
706 }
707 if (!isPointerOperand(I->getOperand(0)) ||
708 !isPointerOperand(I->getOperand(1)))
709 return false;
710 return true;
711}
712
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000713bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
714 // If a global variable does not have dynamic initialization we don't
715 // have to instrument it. However, if a global does not have initializer
716 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000717 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000718}
719
Kostya Serebryany796f6552014-02-27 12:45:36 +0000720void
721AddressSanitizer::instrumentPointerComparisonOrSubtraction(Instruction *I) {
722 IRBuilder<> IRB(I);
723 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
724 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
725 for (int i = 0; i < 2; i++) {
726 if (Param[i]->getType()->isPointerTy())
727 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
728 }
729 IRB.CreateCall2(F, Param[0], Param[1]);
730}
731
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000732void AddressSanitizer::instrumentMop(Instruction *I, bool UseCalls) {
Axel Naumann4a127062012-09-17 14:20:57 +0000733 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000734 unsigned Alignment = 0;
735 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +0000736 assert(Addr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000737 if (ClOpt && ClOptGlobals) {
738 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
739 // If initialization order checking is disabled, a simple access to a
740 // dynamically initialized global is always valid.
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000741 if (!ClInitializers || GlobalIsLinkerInitialized(G)) {
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000742 NumOptimizedAccessesToGlobalVar++;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000743 return;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000744 }
745 }
746 ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
747 if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
748 if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
749 if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
750 NumOptimizedAccessesToGlobalArray++;
751 return;
752 }
753 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000754 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000755 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000756
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000757 Type *OrigPtrTy = Addr->getType();
758 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
759
760 assert(OrigTy->isSized());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000761 uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000762
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000763 assert((TypeSize % 8) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000764
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000765 if (IsWrite)
766 NumInstrumentedWrites++;
767 else
768 NumInstrumentedReads++;
769
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000770 unsigned Granularity = 1 << Mapping.Scale;
771 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
772 // if the data is properly aligned.
773 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
774 TypeSize == 128) &&
775 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Craig Topperf40110f2014-04-25 05:29:35 +0000776 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls);
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000777 // Instrument unusual size or unusual alignment.
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000778 // We can not do it with a single check, so we do 1-byte check for the first
779 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
780 // to report the actual access size.
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000781 IRBuilder<> IRB(I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000782 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
Kostya Serebryanyc9a2c172014-04-22 11:19:45 +0000783 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
784 if (UseCalls) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000785 IRB.CreateCall2(AsanMemoryAccessCallbackSized[IsWrite], AddrLong, Size);
Kostya Serebryanyc9a2c172014-04-22 11:19:45 +0000786 } else {
787 Value *LastByte = IRB.CreateIntToPtr(
788 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
789 OrigPtrTy);
790 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false);
791 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false);
792 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000793}
794
Alexander Potapenko056e27e2012-04-23 10:47:31 +0000795// Validate the result of Module::getOrInsertFunction called for an interface
796// function of AddressSanitizer. If the instrumented module defines a function
797// with the same name, their prototypes must match, otherwise
798// getOrInsertFunction returns a bitcast.
Kostya Serebryany20a79972012-11-22 03:18:50 +0000799static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko056e27e2012-04-23 10:47:31 +0000800 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
801 FuncOrBitcast->dump();
802 report_fatal_error("trying to redefine an AddressSanitizer "
803 "interface function");
804}
805
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000806Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000807 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000808 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000809 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000810 CallInst *Call = SizeArgument
811 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
812 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
813
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000814 // We don't do Call->setDoesNotReturn() because the BB already has
815 // UnreachableInst at the end.
816 // This EmptyAsm is required to avoid callback merge.
817 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3411f2e2012-01-06 18:09:21 +0000818 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000819}
820
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000821Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryany874dae62012-07-16 16:15:40 +0000822 Value *ShadowValue,
823 uint32_t TypeSize) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000824 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +0000825 // Addr & (Granularity - 1)
826 Value *LastAccessedByte = IRB.CreateAnd(
827 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
828 // (Addr & (Granularity - 1)) + size - 1
829 if (TypeSize / 8 > 1)
830 LastAccessedByte = IRB.CreateAdd(
831 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
832 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
833 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000834 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000835 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
836 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
837}
838
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000839void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000840 Instruction *InsertBefore, Value *Addr,
841 uint32_t TypeSize, bool IsWrite,
842 Value *SizeArgument, bool UseCalls) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000843 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000844 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000845 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
846
847 if (UseCalls) {
Kostya Serebryany94f57d192014-04-21 10:28:13 +0000848 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][AccessSizeIndex],
849 AddrLong);
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000850 return;
851 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000852
853 Type *ShadowTy = IntegerType::get(
Alexey Samsonov1345d352013-01-16 13:23:28 +0000854 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000855 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
856 Value *ShadowPtr = memToShadow(AddrLong, IRB);
857 Value *CmpVal = Constant::getNullValue(ShadowTy);
858 Value *ShadowValue = IRB.CreateLoad(
859 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
860
861 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Alexey Samsonov1345d352013-01-16 13:23:28 +0000862 size_t Granularity = 1 << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +0000863 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000864
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000865 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +0000866 // We use branch weights for the slow path check, to indicate that the slow
867 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000868 TerminatorInst *CheckTerm =
Kostya Serebryanyad238522014-09-02 21:46:51 +0000869 SplitBlockAndInsertIfThen(Cmp, InsertBefore, false,
870 MDBuilder(*C).createBranchWeights(1, 100000));
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000871 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000872 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000873 IRB.SetInsertPoint(CheckTerm);
874 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000875 BasicBlock *CrashBlock =
876 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000877 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000878 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
879 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000880 } else {
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000881 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000882 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000883
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000884 Instruction *Crash = generateCrashCode(
885 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000886 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000887}
888
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000889void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
890 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000891 // Set up the arguments to our poison/unpoison functions.
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000892 IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000893
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000894 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000895 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
896 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000897
898 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000899 for (auto &BB : GlobalInit.getBasicBlockList())
900 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000901 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000902}
903
904void AddressSanitizerModule::createInitializerPoisonCalls(
905 Module &M, GlobalValue *ModuleName) {
906 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
907
908 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
909 for (Use &OP : CA->operands()) {
910 if (isa<ConstantAggregateZero>(OP))
911 continue;
912 ConstantStruct *CS = cast<ConstantStruct>(OP);
913
914 // Must have a function or null ptr.
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000915 if (Function* F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +0000916 if (F->getName() == kAsanModuleCtorName) continue;
917 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
918 // Don't instrument CTORs that will run before asan.module_ctor.
919 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
920 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000921 }
922 }
923}
924
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000925bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000926 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany20343352012-10-17 13:40:06 +0000927 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000928
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000929 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000930 if (!Ty->isSized()) return false;
931 if (!G->hasInitializer()) return false;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000932 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000933 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +0000934 // Don't handle ODR linkage types and COMDATs since other modules may be built
935 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000936 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
937 G->getLinkage() != GlobalVariable::PrivateLinkage &&
938 G->getLinkage() != GlobalVariable::InternalLinkage)
939 return false;
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +0000940 if (G->hasComdat())
941 return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000942 // Two problems with thread-locals:
943 // - The address of the main thread's copy can't be computed at link-time.
944 // - Need to poison all copies, not just the main thread's one.
945 if (G->isThreadLocal())
946 return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000947 // For now, just ignore this Global if the alignment is large.
948 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000949
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000950 if (G->hasSection()) {
951 StringRef Section(G->getSection());
952 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
953 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
954 // them.
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +0000955 if (Section.startswith("__OBJC,") ||
956 Section.startswith("__DATA, __objc_")) {
Alexander Potapenkob76ea322014-03-14 10:41:49 +0000957 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000958 return false;
959 }
960 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
961 // Constant CFString instances are compiled in the following way:
962 // -- the string buffer is emitted into
963 // __TEXT,__cstring,cstring_literals
964 // -- the constant NSConstantString structure referencing that buffer
965 // is placed into __DATA,__cfstring
966 // Therefore there's no point in placing redzones into __DATA,__cfstring.
967 // Moreover, it causes the linker to crash on OS X 10.7
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +0000968 if (Section.startswith("__DATA,__cfstring")) {
Alexander Potapenkob76ea322014-03-14 10:41:49 +0000969 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
970 return false;
971 }
972 // The linker merges the contents of cstring_literals and removes the
973 // trailing zeroes.
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +0000974 if (Section.startswith("__TEXT,__cstring,cstring_literals")) {
Alexander Potapenkob76ea322014-03-14 10:41:49 +0000975 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000976 return false;
977 }
Rafael Espindolab7a45052014-11-06 20:01:34 +0000978 if (Section.startswith("__TEXT,__objc_methname,cstring_literals")) {
979 DEBUG(dbgs() << "Ignoring objc_methname cstring global: " << *G << "\n");
980 return false;
981 }
982
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +0000983
984 // Callbacks put into the CRT initializer/terminator sections
985 // should not be instrumented.
986 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
987 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
988 if (Section.startswith(".CRT")) {
989 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
990 return false;
991 }
992
Alexander Potapenko04969e82014-03-20 10:48:34 +0000993 // Globals from llvm.metadata aren't emitted, do not instrument them.
994 if (Section == "llvm.metadata") return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000995 }
996
997 return true;
998}
999
Alexey Samsonov788381b2012-12-25 12:28:20 +00001000void AddressSanitizerModule::initializeCallbacks(Module &M) {
1001 IRBuilder<> IRB(*C);
1002 // Declare our poisoning and unpoisoning functions.
1003 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001004 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001005 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1006 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1007 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
1008 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1009 // Declare functions that register/unregister globals.
1010 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1011 kAsanRegisterGlobalsName, IRB.getVoidTy(),
1012 IntptrTy, IntptrTy, NULL));
1013 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1014 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1015 kAsanUnregisterGlobalsName,
1016 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1017 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1018}
1019
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001020// This function replaces all global variables with new variables that have
1021// trailing redzones. It also creates a function that poisons
1022// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001023bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001024 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001025
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001026 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1027
Alexey Samsonova02e6642014-05-29 18:40:48 +00001028 for (auto &G : M.globals()) {
1029 if (ShouldInstrumentGlobal(&G))
1030 GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001031 }
1032
1033 size_t n = GlobalsToChange.size();
1034 if (n == 0) return false;
1035
1036 // A global is described by a structure
1037 // size_t beg;
1038 // size_t size;
1039 // size_t size_with_redzone;
1040 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001041 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001042 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001043 // void *source_location;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001044 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001045 StructType *GlobalStructTy =
1046 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
1047 IntptrTy, IntptrTy, NULL);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001048 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001049
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001050 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001051
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001052 // We shouldn't merge same module names, as this string serves as unique
1053 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001054 GlobalVariable *ModuleName = createPrivateGlobalForString(
1055 M, M.getModuleIdentifier(), /*AllowMerging*/false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001056
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001057 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001058 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001059 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001060
1061 auto MD = GlobalsMD.get(G);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001062 // Create string holding the global name (use global name from metadata
1063 // if it's available, otherwise just write the name of global variable).
1064 GlobalVariable *Name = createPrivateGlobalForString(
1065 M, MD.Name.empty() ? G->getName() : MD.Name,
1066 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001067
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001068 PointerType *PtrTy = cast<PointerType>(G->getType());
1069 Type *Ty = PtrTy->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001070 uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001071 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001072 // MinRZ <= RZ <= kMaxGlobalRedzone
1073 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001074 uint64_t RZ = std::max(MinRZ,
Kostya Serebryany87191f62013-01-24 10:35:40 +00001075 std::min(kMaxGlobalRedzone,
1076 (SizeInBytes / MinRZ / 4) * MinRZ));
1077 uint64_t RightRedzoneSize = RZ;
1078 // Round up to MinRZ
1079 if (SizeInBytes % MinRZ)
1080 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1081 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001082 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1083
1084 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
1085 Constant *NewInitializer = ConstantStruct::get(
1086 NewTy, G->getInitializer(),
1087 Constant::getNullValue(RightRedZoneTy), NULL);
1088
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001089 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001090 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1091 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1092 Linkage = GlobalValue::InternalLinkage;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001093 GlobalVariable *NewGlobal = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001094 M, NewTy, G->isConstant(), Linkage,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001095 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001096 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001097 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001098
1099 Value *Indices2[2];
1100 Indices2[0] = IRB.getInt32(0);
1101 Indices2[1] = IRB.getInt32(0);
1102
1103 G->replaceAllUsesWith(
Kostya Serebryany7471d132012-01-28 04:27:16 +00001104 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001105 NewGlobal->takeName(G);
1106 G->eraseFromParent();
1107
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001108 Constant *SourceLoc;
1109 if (!MD.SourceLoc.empty()) {
1110 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1111 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1112 } else {
1113 SourceLoc = ConstantInt::get(IntptrTy, 0);
1114 }
1115
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001116 Initializers[i] = ConstantStruct::get(
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001117 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001118 ConstantInt::get(IntptrTy, SizeInBytes),
1119 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1120 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001121 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001122 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, NULL);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001123
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001124 if (ClInitializers && MD.IsDynInit)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001125 HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001126
Kostya Serebryany20343352012-10-17 13:40:06 +00001127 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001128 }
1129
1130 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1131 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001132 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001133 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1134
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001135 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001136 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001137 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001138 IRB.CreateCall2(AsanRegisterGlobals,
1139 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1140 ConstantInt::get(IntptrTy, n));
1141
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001142 // We also need to unregister globals at the end, e.g. when a shared library
1143 // gets closed.
1144 Function *AsanDtorFunction = Function::Create(
1145 FunctionType::get(Type::getVoidTy(*C), false),
1146 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1147 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1148 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001149 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1150 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1151 ConstantInt::get(IntptrTy, n));
Alexey Samsonov1f647502014-05-29 01:10:14 +00001152 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001153
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001154 DEBUG(dbgs() << M);
1155 return true;
1156}
1157
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001158bool AddressSanitizerModule::runOnModule(Module &M) {
1159 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1160 if (!DLP)
1161 return false;
1162 DL = &DLP->getDataLayout();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001163 C = &(M.getContext());
1164 int LongSize = DL->getPointerSizeInBits();
1165 IntptrTy = Type::getIntNTy(*C, LongSize);
1166 Mapping = getShadowMapping(M, LongSize);
1167 initializeCallbacks(M);
1168
1169 bool Changed = false;
1170
1171 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1172 assert(CtorFunc);
1173 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1174
Alexey Samsonovc94285a2014-07-08 00:50:49 +00001175 if (ClGlobals)
1176 Changed |= InstrumentGlobals(IRB, M);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001177
1178 return Changed;
1179}
1180
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001181void AddressSanitizer::initializeCallbacks(Module &M) {
1182 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001183 // Create __asan_report* callbacks.
1184 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1185 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1186 AccessSizeIndex++) {
1187 // IsWrite and TypeSize are encoded in the function name.
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001188 std::string Suffix =
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001189 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany157a5152012-11-07 12:42:18 +00001190 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001191 checkInterfaceFunction(
1192 M.getOrInsertFunction(kAsanReportErrorTemplate + Suffix,
1193 IRB.getVoidTy(), IntptrTy, NULL));
1194 AsanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
1195 checkInterfaceFunction(
1196 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + Suffix,
1197 IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001198 }
1199 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001200 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1201 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1202 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1203 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001204
Kostya Serebryany86332c02014-04-21 07:10:43 +00001205 AsanMemoryAccessCallbackSized[0] = checkInterfaceFunction(
1206 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "loadN",
1207 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1208 AsanMemoryAccessCallbackSized[1] = checkInterfaceFunction(
1209 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "storeN",
1210 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1211
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001212 AsanMemmove = checkInterfaceFunction(M.getOrInsertFunction(
1213 ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
1214 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
1215 AsanMemcpy = checkInterfaceFunction(M.getOrInsertFunction(
1216 ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
1217 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
1218 AsanMemset = checkInterfaceFunction(M.getOrInsertFunction(
1219 ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
1220 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, NULL));
1221
1222 AsanHandleNoReturnFunc = checkInterfaceFunction(
1223 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001224
Kostya Serebryany796f6552014-02-27 12:45:36 +00001225 AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
1226 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1227 AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
1228 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001229 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1230 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1231 StringRef(""), StringRef(""),
1232 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001233}
1234
1235// virtual
1236bool AddressSanitizer::doInitialization(Module &M) {
1237 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001238 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1239 if (!DLP)
Evgeniy Stepanov119cb2e2014-04-23 12:51:32 +00001240 report_fatal_error("data layout missing");
Rafael Espindola93512512014-02-25 17:30:31 +00001241 DL = &DLP->getDataLayout();
1242
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001243 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001244
1245 C = &(M.getContext());
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001246 LongSize = DL->getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001247 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001248
1249 AsanCtorFunction = Function::Create(
1250 FunctionType::get(Type::getVoidTy(*C), false),
1251 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1252 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1253 // call __asan_init in the module ctor.
1254 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1255 AsanInitFunction = checkInterfaceFunction(
1256 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1257 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1258 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001259
Evgeniy Stepanov13665362014-01-16 10:19:12 +00001260 Mapping = getShadowMapping(M, LongSize);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001261
Alexey Samsonov1f647502014-05-29 01:10:14 +00001262 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001263 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001264}
1265
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001266bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1267 // For each NSObject descendant having a +load method, this method is invoked
1268 // by the ObjC runtime before any of the static constructors is called.
1269 // Therefore we need to instrument such methods with a call to __asan_init
1270 // at the beginning in order to initialize our runtime before any access to
1271 // the shadow memory.
1272 // We cannot just ignore these methods, because they may call other
1273 // instrumented functions.
1274 if (F.getName().find(" load]") != std::string::npos) {
1275 IRBuilder<> IRB(F.begin()->begin());
1276 IRB.CreateCall(AsanInitFunction);
1277 return true;
1278 }
1279 return false;
1280}
1281
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001282bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001283 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001284 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001285 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001286 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001287
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001288 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001289 maybeInsertAsanInitAtFunctionEntry(F);
1290
Alexey Samsonov6d8bab82014-06-02 18:08:27 +00001291 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001292 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001293
1294 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1295 return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001296
1297 // We want to instrument every address only once per basic block (unless there
1298 // are calls between uses).
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001299 SmallSet<Value*, 16> TempsToInstrument;
1300 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001301 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001302 SmallVector<BasicBlock*, 16> AllBlocks;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001303 SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001304 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001305 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001306 unsigned Alignment;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001307
1308 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001309 for (auto &BB : F) {
1310 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001311 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001312 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001313 for (auto &Inst : BB) {
1314 if (LooksLikeCodeInBug11395(&Inst)) return false;
1315 if (Value *Addr =
1316 isInterestingMemoryAccess(&Inst, &IsWrite, &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001317 if (ClOpt && ClOptSameTemp) {
1318 if (!TempsToInstrument.insert(Addr))
1319 continue; // We've seen this temp in the current BB.
1320 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001321 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001322 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1323 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001324 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001325 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001326 // ok, take it.
1327 } else {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001328 if (isa<AllocaInst>(Inst))
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001329 NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001330 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001331 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001332 // A call inside BB.
1333 TempsToInstrument.clear();
Kostya Serebryany699ac282013-02-20 12:35:15 +00001334 if (CS.doesNotReturn())
1335 NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001336 }
1337 continue;
1338 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001339 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001340 NumInsnsPerBB++;
1341 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1342 break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001343 }
1344 }
1345
Craig Topperf40110f2014-04-25 05:29:35 +00001346 Function *UninstrumentedDuplicate = nullptr;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001347 bool LikelyToInstrument =
1348 !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1349 if (ClKeepUninstrumented && LikelyToInstrument) {
1350 ValueToValueMapTy VMap;
1351 UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1352 UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1353 UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1354 F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1355 }
1356
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001357 bool UseCalls = false;
1358 if (ClInstrumentationWithCallsThreshold >= 0 &&
1359 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1360 UseCalls = true;
1361
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001362 // Instrument.
1363 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001364 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001365 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1366 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001367 if (isInterestingMemoryAccess(Inst, &IsWrite, &Alignment))
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001368 instrumentMop(Inst, UseCalls);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001369 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001370 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001371 }
1372 NumInstrumented++;
1373 }
1374
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001375 FunctionStackPoisoner FSP(F, *this);
1376 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001377
1378 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1379 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001380 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001381 IRBuilder<> IRB(CI);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001382 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001383 }
1384
Alexey Samsonova02e6642014-05-29 18:40:48 +00001385 for (auto Inst : PointerComparisonsOrSubtracts) {
1386 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001387 NumInstrumented++;
1388 }
1389
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001390 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001391
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001392 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1393
1394 if (ClKeepUninstrumented) {
1395 if (!res) {
1396 // No instrumentation is done, no need for the duplicate.
1397 if (UninstrumentedDuplicate)
1398 UninstrumentedDuplicate->eraseFromParent();
1399 } else {
1400 // The function was instrumented. We must have the duplicate.
1401 assert(UninstrumentedDuplicate);
1402 UninstrumentedDuplicate->setSection("NOASAN");
1403 assert(!F.hasSection());
1404 F.setSection("ASAN");
1405 }
1406 }
1407
1408 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001409}
1410
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001411// Workaround for bug 11395: we don't want to instrument stack in functions
1412// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1413// FIXME: remove once the bug 11395 is fixed.
1414bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1415 if (LongSize != 32) return false;
1416 CallInst *CI = dyn_cast<CallInst>(I);
1417 if (!CI || !CI->isInlineAsm()) return false;
1418 if (CI->getNumArgOperands() <= 5) return false;
1419 // We have inline assembly with quite a few arguments.
1420 return true;
1421}
1422
1423void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1424 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001425 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1426 std::string Suffix = itostr(i);
1427 AsanStackMallocFunc[i] = checkInterfaceFunction(
1428 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1429 IntptrTy, IntptrTy, NULL));
1430 AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1431 kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1432 IntptrTy, IntptrTy, NULL));
1433 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001434 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1435 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1436 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1437 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1438}
1439
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001440void
Craig Topper3af97222014-08-27 05:25:00 +00001441FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001442 IRBuilder<> &IRB, Value *ShadowBase,
1443 bool DoPoison) {
1444 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001445 size_t i = 0;
1446 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1447 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1448 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1449 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1450 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1451 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1452 uint64_t Val = 0;
1453 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001454 if (ASan.DL->isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001455 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1456 else
1457 Val = (Val << 8) | ShadowBytes[i + j];
1458 }
1459 if (!Val) continue;
1460 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1461 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1462 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1463 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001464 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001465 }
1466}
1467
Kostya Serebryany6805de52013-09-10 13:16:56 +00001468// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1469// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1470static int StackMallocSizeClass(uint64_t LocalStackSize) {
1471 assert(LocalStackSize <= kMaxStackMallocSize);
1472 uint64_t MaxSize = kMinStackMallocSize;
1473 for (int i = 0; ; i++, MaxSize *= 2)
1474 if (LocalStackSize <= MaxSize)
1475 return i;
1476 llvm_unreachable("impossible LocalStackSize");
1477}
1478
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001479// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1480// We can not use MemSet intrinsic because it may end up calling the actual
1481// memset. Size is a multiple of 8.
1482// Currently this generates 8-byte stores on x86_64; it may be better to
1483// generate wider stores.
1484void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1485 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1486 assert(!(Size % 8));
1487 assert(kAsanStackAfterReturnMagic == 0xf5);
1488 for (int i = 0; i < Size; i += 8) {
1489 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1490 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1491 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1492 }
1493}
1494
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001495static DebugLoc getFunctionEntryDebugLocation(Function &F) {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001496 for (const auto &Inst : F.getEntryBlock())
1497 if (!isa<AllocaInst>(Inst))
1498 return Inst.getDebugLoc();
1499 return DebugLoc();
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001500}
1501
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001502void FunctionStackPoisoner::poisonStack() {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001503 int StackMallocIdx = -1;
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001504 DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001505
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001506 assert(AllocaVec.size() > 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001507 Instruction *InsBefore = AllocaVec[0];
1508 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001509 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001510
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001511 SmallVector<ASanStackVariableDescription, 16> SVD;
1512 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00001513 for (AllocaInst *AI : AllocaVec) {
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001514 ASanStackVariableDescription D = { AI->getName().data(),
1515 getAllocaSizeInBytes(AI),
1516 AI->getAlignment(), AI, 0};
1517 SVD.push_back(D);
1518 }
1519 // Minimal header size (left redzone) is 4 pointers,
1520 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1521 size_t MinHeaderSize = ASan.LongSize / 2;
1522 ASanStackFrameLayout L;
1523 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1524 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1525 uint64_t LocalStackSize = L.FrameSize;
1526 bool DoStackMalloc =
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001527 ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001528
1529 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1530 AllocaInst *MyAlloca =
1531 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001532 MyAlloca->setDebugLoc(EntryDebugLocation);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001533 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1534 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1535 MyAlloca->setAlignment(FrameAlignment);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001536 assert(MyAlloca->isStaticAlloca());
1537 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1538 Value *LocalStackBase = OrigStackBase;
1539
1540 if (DoStackMalloc) {
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001541 // LocalStackBase = OrigStackBase
1542 // if (__asan_option_detect_stack_use_after_return)
1543 // LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001544 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1545 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001546 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1547 kAsanOptionDetectUAR, IRB.getInt32Ty());
1548 Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1549 Constant::getNullValue(IRB.getInt32Ty()));
Evgeniy Stepanova9164e92013-12-19 13:29:56 +00001550 Instruction *Term = SplitBlockAndInsertIfThen(Cmp, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001551 BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1552 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001553 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001554 LocalStackBase = IRBIf.CreateCall2(
1555 AsanStackMallocFunc[StackMallocIdx],
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001556 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001557 BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1558 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001559 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001560 PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1561 Phi->addIncoming(OrigStackBase, CmpBlock);
1562 Phi->addIncoming(LocalStackBase, SetBlock);
1563 LocalStackBase = Phi;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001564 }
1565
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001566 // Insert poison calls for lifetime intrinsics for alloca.
1567 bool HavePoisonedAllocas = false;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001568 for (const auto &APC : AllocaPoisonCallVec) {
Alexey Samsonova788b942013-11-18 14:53:55 +00001569 assert(APC.InsBefore);
1570 assert(APC.AI);
1571 IRBuilder<> IRB(APC.InsBefore);
1572 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001573 HavePoisonedAllocas |= APC.DoPoison;
1574 }
1575
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001576 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001577 for (const auto &Desc : SVD) {
1578 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00001579 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00001580 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001581 AI->getType());
Alexey Samsonov3d43b632012-12-12 14:31:53 +00001582 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001583 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001584 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001585
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001586 // The left-most redzone has enough space for at least 4 pointers.
1587 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001588 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1589 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1590 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001591 // Write the frame description constant to redzone[1].
1592 Value *BasePlus1 = IRB.CreateIntToPtr(
1593 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1594 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00001595 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001596 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1597 /*AllowMerging*/true);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001598 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1599 IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001600 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001601 // Write the PC to redzone[2].
1602 Value *BasePlus2 = IRB.CreateIntToPtr(
1603 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1604 2 * ASan.LongSize/8)),
1605 IntptrPtrTy);
1606 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001607
1608 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001609 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001610 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001611
Kostya Serebryany530e2072013-12-23 14:15:08 +00001612 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001613 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001614 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001615 // Mark the current frame as retired.
1616 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1617 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001618 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001619 assert(StackMallocIdx >= 0);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001620 // if LocalStackBase != OrigStackBase:
1621 // // In use-after-return mode, poison the whole stack frame.
1622 // if StackMallocIdx <= 4
1623 // // For small sizes inline the whole thing:
1624 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1625 // **SavedFlagPtr(LocalStackBase) = 0
1626 // else
1627 // __asan_stack_free_N(LocalStackBase, OrigStackBase)
1628 // else
1629 // <This is not a fake stack; unpoison the redzones>
1630 Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1631 TerminatorInst *ThenTerm, *ElseTerm;
1632 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1633
1634 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001635 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001636 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1637 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1638 ClassSize >> Mapping.Scale);
1639 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1640 LocalStackBase,
1641 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1642 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1643 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1644 IRBPoison.CreateStore(
1645 Constant::getNullValue(IRBPoison.getInt8Ty()),
1646 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1647 } else {
1648 // For larger frames call __asan_stack_free_*.
Kostya Serebryany530e2072013-12-23 14:15:08 +00001649 IRBPoison.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1650 ConstantInt::get(IntptrTy, LocalStackSize),
1651 OrigStackBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001652 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00001653
1654 IRBuilder<> IRBElse(ElseTerm);
1655 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001656 } else if (HavePoisonedAllocas) {
1657 // If we poisoned some allocas in llvm.lifetime analysis,
1658 // unpoison whole stack frame now.
1659 assert(LocalStackBase == OrigStackBase);
1660 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001661 } else {
1662 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001663 }
1664 }
1665
Kostya Serebryany09959942012-10-19 06:20:53 +00001666 // We are done. Remove the old unused alloca instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001667 for (auto AI : AllocaVec)
1668 AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001669}
Alexey Samsonov261177a2012-12-04 01:34:23 +00001670
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001671void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00001672 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00001673 // For now just insert the call to ASan runtime.
1674 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1675 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1676 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1677 : AsanUnpoisonStackMemoryFunc,
1678 AddrArg, SizeArg);
1679}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001680
1681// Handling llvm.lifetime intrinsics for a given %alloca:
1682// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1683// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1684// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1685// could be poisoned by previous llvm.lifetime.end instruction, as the
1686// variable may go in and out of scope several times, e.g. in loops).
1687// (3) if we poisoned at least one %alloca in a function,
1688// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001689
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001690AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1691 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1692 // We're intested only in allocas we can handle.
Craig Topperf40110f2014-04-25 05:29:35 +00001693 return isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001694 // See if we've already calculated (or started to calculate) alloca for a
1695 // given value.
1696 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1697 if (I != AllocaForValue.end())
1698 return I->second;
1699 // Store 0 while we're calculating alloca for value V to avoid
1700 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00001701 AllocaForValue[V] = nullptr;
1702 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001703 if (CastInst *CI = dyn_cast<CastInst>(V))
1704 Res = findAllocaForValue(CI->getOperand(0));
1705 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1706 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1707 Value *IncValue = PN->getIncomingValue(i);
1708 // Allow self-referencing phi-nodes.
1709 if (IncValue == PN) continue;
1710 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1711 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00001712 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1713 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001714 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001715 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001716 }
Craig Topperf40110f2014-04-25 05:29:35 +00001717 if (Res)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001718 AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001719 return Res;
1720}