blob: 1a2cc55c60ee9108400805bf6e745dc6218fb604 [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"
Yury Gribov3ae427d2014-12-01 08:47:58 +000030#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/Function.h"
32#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000034#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/IntrinsicInst.h"
36#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000037#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Module.h"
39#include "llvm/IR/Type.h"
Kuba Brecka1001bb52014-12-05 22:19:18 +000040#include "llvm/MC/MCSectionMachO.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000041#include "llvm/Support/CommandLine.h"
42#include "llvm/Support/DataTypes.h"
43#include "llvm/Support/Debug.h"
Kostya Serebryany9e62b302013-06-03 14:46:56 +000044#include "llvm/Support/Endian.h"
Yury Gribov55441bb2014-11-21 10:29:50 +000045#include "llvm/Support/SwapByteOrder.h"
Kostya Serebryany351b0782014-09-03 22:37:37 +000046#include "llvm/Transforms/Scalar.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000047#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000048#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany9f5213f2013-06-26 09:18:17 +000049#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000050#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000051#include "llvm/Transforms/Utils/ModuleUtils.h"
Anna Zaks8ed1d812015-02-27 03:12:36 +000052#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000053#include <algorithm>
Chandler Carruthed0881b2012-12-03 16:50:05 +000054#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000055#include <system_error>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000056
57using namespace llvm;
58
Chandler Carruth964daaa2014-04-22 02:55:47 +000059#define DEBUG_TYPE "asan"
60
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000061static const uint64_t kDefaultShadowScale = 3;
62static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +000063static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000064static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000065static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Kostya Serebryany4766fe62013-01-23 12:54:55 +000066static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +000067static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +000068static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +000069static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000070static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
71static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +000072static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000073
Kostya Serebryany6805de52013-09-10 13:16:56 +000074static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000075static const size_t kMaxStackMallocSize = 1 << 16; // 64K
76static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
77static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
78
Craig Topperd3a34f82013-07-16 01:17:10 +000079static const char *const kAsanModuleCtorName = "asan.module_ctor";
80static const char *const kAsanModuleDtorName = "asan.module_dtor";
Kostya Serebryany34ddf872014-09-24 22:41:55 +000081static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000082static const char *const kAsanReportErrorTemplate = "__asan_report_";
83static const char *const kAsanReportLoadN = "__asan_report_load_n";
84static const char *const kAsanReportStoreN = "__asan_report_store_n";
85static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000086static const char *const kAsanUnregisterGlobalsName =
87 "__asan_unregister_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +000088static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
89static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Alexey Samsonov4b7f4132014-12-11 21:53:03 +000090static const char *const kAsanInitName = "__asan_init_v5";
Kostya Serebryany796f6552014-02-27 12:45:36 +000091static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
92static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +000093static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany6805de52013-09-10 13:16:56 +000094static const int kMaxAsanStackMallocSizeClass = 10;
95static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
96static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +000097static const char *const kAsanGenPrefix = "__asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +000098static const char *const kSanCovGenPrefix = "__sancov_gen_";
Craig Topperd3a34f82013-07-16 01:17:10 +000099static const char *const kAsanPoisonStackMemoryName =
100 "__asan_poison_stack_memory";
101static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000102 "__asan_unpoison_stack_memory";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000103
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000104static const char *const kAsanOptionDetectUAR =
105 "__asan_option_detect_stack_use_after_return";
106
David Blaikieeacc2872013-09-18 00:11:27 +0000107#ifndef NDEBUG
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000108static const int kAsanStackAfterReturnMagic = 0xf5;
David Blaikieeacc2872013-09-18 00:11:27 +0000109#endif
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000110
Kostya Serebryany874dae62012-07-16 16:15:40 +0000111// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
112static const size_t kNumberOfAccessSizes = 5;
113
Yury Gribov55441bb2014-11-21 10:29:50 +0000114static const unsigned kAllocaRzSize = 32;
115static const unsigned kAsanAllocaLeftMagic = 0xcacacacaU;
116static const unsigned kAsanAllocaRightMagic = 0xcbcbcbcbU;
117static const unsigned kAsanAllocaPartialVal1 = 0xcbcbcb00U;
118static const unsigned kAsanAllocaPartialVal2 = 0x000000cbU;
119
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000120// Command-line flags.
121
122// This flag may need to be replaced with -f[no-]asan-reads.
123static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
124 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
125static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
126 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryany90241602012-05-30 09:04:06 +0000127static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
128 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
129 cl::Hidden, cl::init(true));
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000130static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
131 cl::desc("use instrumentation with slow path for all accesses"),
132 cl::Hidden, cl::init(false));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000133// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000134// in any given BB. Normally, this should be set to unlimited (INT_MAX),
135// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
136// set it to 10000.
137static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
138 cl::init(10000),
139 cl::desc("maximal number of instructions to instrument in any given BB"),
140 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000141// This flag may need to be replaced with -f[no]asan-stack.
142static cl::opt<bool> ClStack("asan-stack",
143 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000144static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000145 cl::desc("Check return-after-free"), cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000146// This flag may need to be replaced with -f[no]asan-globals.
147static cl::opt<bool> ClGlobals("asan-globals",
148 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000149static cl::opt<bool> ClInitializers("asan-initialization-order",
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000150 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(true));
Kostya Serebryany796f6552014-02-27 12:45:36 +0000151static cl::opt<bool> ClInvalidPointerPairs("asan-detect-invalid-pointer-pair",
152 cl::desc("Instrument <, <=, >, >=, - with pointer operands"),
Kostya Serebryanyec346652014-02-27 12:56:20 +0000153 cl::Hidden, cl::init(false));
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000154static cl::opt<unsigned> ClRealignStack("asan-realign-stack",
155 cl::desc("Realign stack to the value of this flag (power of two)"),
156 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000157static cl::opt<int> ClInstrumentationWithCallsThreshold(
158 "asan-instrumentation-with-call-threshold",
159 cl::desc("If the function being instrumented contains more than "
160 "this number of memory accesses, use callbacks instead of "
161 "inline checks (-1 means never use callbacks)."),
Kostya Serebryany4d237a82014-05-26 11:57:16 +0000162 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000163static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
164 "asan-memory-access-callback-prefix",
165 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
166 cl::init("__asan_"));
Yury Gribov55441bb2014-11-21 10:29:50 +0000167static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
168 cl::desc("instrument dynamic allocas"), cl::Hidden, cl::init(false));
Anna Zaks8ed1d812015-02-27 03:12:36 +0000169static cl::opt<bool> ClSkipPromotableAllocas("asan-skip-promotable-allocas",
170 cl::desc("Do not instrument promotable allocas"),
171 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000172
173// These flags allow to change the shadow mapping.
174// The shadow mapping looks like
175// Shadow = (Mem >> scale) + (1 << offset_log)
176static cl::opt<int> ClMappingScale("asan-mapping-scale",
177 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000178
179// Optimization flags. Not user visible, used mostly for testing
180// and benchmarking the tool.
181static cl::opt<bool> ClOpt("asan-opt",
182 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
183static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
184 cl::desc("Instrument the same temp just once"), cl::Hidden,
185 cl::init(true));
186static cl::opt<bool> ClOptGlobals("asan-opt-globals",
187 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
188
Alexey Samsonovdf624522012-11-29 18:14:24 +0000189static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
190 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
191 cl::Hidden, cl::init(false));
192
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000193static cl::opt<bool> ClDynamicAllocaStack(
194 "asan-stack-dynamic-alloca",
195 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000196 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000197
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000198// Debug flags.
199static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
200 cl::init(0));
201static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
202 cl::Hidden, cl::init(0));
203static cl::opt<std::string> ClDebugFunc("asan-debug-func",
204 cl::Hidden, cl::desc("Debug func"));
205static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
206 cl::Hidden, cl::init(-1));
207static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
208 cl::Hidden, cl::init(-1));
209
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000210STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
211STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyea2cb6f2014-11-21 21:25:18 +0000212STATISTIC(NumInstrumentedDynamicAllocas,
213 "Number of instrumented dynamic allocas");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000214STATISTIC(NumOptimizedAccessesToGlobalArray,
215 "Number of optimized accesses to global arrays");
216STATISTIC(NumOptimizedAccessesToGlobalVar,
217 "Number of optimized accesses to global vars");
218
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000219namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000220/// Frontend-provided metadata for source location.
221struct LocationMetadata {
222 StringRef Filename;
223 int LineNo;
224 int ColumnNo;
225
226 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
227
228 bool empty() const { return Filename.empty(); }
229
230 void parse(MDNode *MDN) {
231 assert(MDN->getNumOperands() == 3);
232 MDString *MDFilename = cast<MDString>(MDN->getOperand(0));
233 Filename = MDFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000234 LineNo =
235 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
236 ColumnNo =
237 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000238 }
239};
240
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000241/// Frontend-provided metadata for global variables.
242class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000243 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000244 struct Entry {
Alexey Samsonov15c96692014-07-12 00:42:52 +0000245 Entry()
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000246 : SourceLoc(), Name(), IsDynInit(false),
Alexey Samsonov15c96692014-07-12 00:42:52 +0000247 IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000248 LocationMetadata SourceLoc;
249 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000250 bool IsDynInit;
251 bool IsBlacklisted;
252 };
253
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000254 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000255
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000256 void init(Module& M) {
257 assert(!inited_);
258 inited_ = true;
259 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
260 if (!Globals)
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000261 return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000262 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000263 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000264 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000265 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000266 // The optimizer may optimize away a global entirely.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000267 if (!GV)
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000268 continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000269 // We can already have an entry for GV if it was merged with another
270 // global.
271 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000272 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
273 E.SourceLoc.parse(Loc);
274 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
275 E.Name = Name->getString();
276 ConstantInt *IsDynInit =
277 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000278 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000279 ConstantInt *IsBlacklisted =
280 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000281 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000282 }
283 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000284
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000285 /// Returns metadata entry for a given global.
286 Entry get(GlobalVariable *G) const {
287 auto Pos = Entries.find(G);
288 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000289 }
290
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000291 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000292 bool inited_;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000293 DenseMap<GlobalVariable*, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000294};
295
Alexey Samsonov1345d352013-01-16 13:23:28 +0000296/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000297/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000298struct ShadowMapping {
299 int Scale;
300 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000301 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000302};
303
Kuba Brecka1001bb52014-12-05 22:19:18 +0000304static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize) {
Alexey Samsonov347bcd32013-01-17 11:12:32 +0000305 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Bob Wilson9868d712014-10-09 05:43:30 +0000306 bool IsIOS = TargetTriple.isiOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000307 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
308 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000309 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
310 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000311 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000312 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
313 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000314 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
315 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000316 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000317 bool IsWindows = TargetTriple.isOSWindows();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000318
319 ShadowMapping Mapping;
320
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000321 if (LongSize == 32) {
322 if (IsAndroid)
323 Mapping.Offset = 0;
324 else if (IsMIPS32)
325 Mapping.Offset = kMIPS32_ShadowOffset32;
326 else if (IsFreeBSD)
327 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000328 else if (IsIOS)
329 Mapping.Offset = kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000330 else if (IsWindows)
331 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000332 else
333 Mapping.Offset = kDefaultShadowOffset32;
334 } else { // LongSize == 64
335 if (IsPPC64)
336 Mapping.Offset = kPPC64_ShadowOffset64;
337 else if (IsFreeBSD)
338 Mapping.Offset = kFreeBSD_ShadowOffset64;
339 else if (IsLinux && IsX86_64)
340 Mapping.Offset = kSmallX86_64ShadowOffset;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000341 else if (IsMIPS64)
342 Mapping.Offset = kMIPS64_ShadowOffset64;
Renato Golinaf213722015-02-03 11:20:45 +0000343 else if (IsAArch64)
344 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000345 else
346 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000347 }
348
349 Mapping.Scale = kDefaultShadowScale;
350 if (ClMappingScale) {
351 Mapping.Scale = ClMappingScale;
352 }
353
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000354 // OR-ing shadow offset if more efficient (at least on x86) if the offset
355 // is a power of two, but on ppc64 we have to use add since the shadow
356 // offset is not necessary 1/8-th of the address space.
357 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
358
Alexey Samsonov1345d352013-01-16 13:23:28 +0000359 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000360}
361
Alexey Samsonov1345d352013-01-16 13:23:28 +0000362static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000363 // Redzone used for stack and globals is at least 32 bytes.
364 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000365 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000366}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000367
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000368/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000369struct AddressSanitizer : public FunctionPass {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000370 AddressSanitizer() : FunctionPass(ID) {
371 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
372 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000373 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000374 return "AddressSanitizerFunctionPass";
375 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000376 void getAnalysisUsage(AnalysisUsage &AU) const override {
377 AU.addRequired<DominatorTreeWrapperPass>();
378 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000379 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
380 Type *Ty = AI->getAllocatedType();
381 uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
382 return SizeInBytes;
383 }
384 /// Check if we want (and can) handle this alloca.
385 bool isInterestingAlloca(AllocaInst &AI) const;
386 /// If it is an interesting memory access, return the PointerOperand
387 /// and set IsWrite/Alignment. Otherwise return nullptr.
388 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
389 unsigned *Alignment) const;
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000390 void instrumentMop(Instruction *I, bool UseCalls);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000391 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000392 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
393 Value *Addr, uint32_t TypeSize, bool IsWrite,
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000394 Value *SizeArgument, bool UseCalls);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000395 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
396 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000397 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000398 bool IsWrite, size_t AccessSizeIndex,
399 Value *SizeArgument);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000400 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000401 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000402 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000403 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000404 bool doInitialization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000405 static char ID; // Pass identification, replacement for typeid
406
Yury Gribov3ae427d2014-12-01 08:47:58 +0000407 DominatorTree &getDominatorTree() const { return *DT; }
408
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000409 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000410 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000411
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000412 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000413 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000414
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000415 LLVMContext *C;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000416 const DataLayout *DL;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000417 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000418 int LongSize;
419 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000420 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000421 DominatorTree *DT;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000422 Function *AsanCtorFunction;
423 Function *AsanInitFunction;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000424 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000425 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Kostya Serebryany4273bb02012-07-16 14:09:42 +0000426 // This array is indexed by AccessIsWrite and log2(AccessSize).
427 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000428 Function *AsanMemoryAccessCallback[2][kNumberOfAccessSizes];
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000429 // This array is indexed by AccessIsWrite.
Kostya Serebryany86332c02014-04-21 07:10:43 +0000430 Function *AsanErrorCallbackSized[2],
431 *AsanMemoryAccessCallbackSized[2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000432 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000433 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000434 GlobalsMetadata GlobalsMD;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000435
436 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000437};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000438
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000439class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000440 public:
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000441 AddressSanitizerModule() : ModulePass(ID) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000442 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000443 static char ID; // Pass identification, replacement for typeid
Craig Topper3e4c6972014-03-05 09:10:37 +0000444 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000445 return "AddressSanitizerModule";
446 }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000447
Kostya Serebryany20a79972012-11-22 03:18:50 +0000448 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000449 void initializeCallbacks(Module &M);
450
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000451 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000452 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000453 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000454 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000455 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000456 return RedzoneSizeForScale(Mapping.Scale);
457 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000458
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000459 GlobalsMetadata GlobalsMD;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000460 Type *IntptrTy;
461 LLVMContext *C;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000462 const DataLayout *DL;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000463 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000464 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000465 Function *AsanPoisonGlobals;
466 Function *AsanUnpoisonGlobals;
467 Function *AsanRegisterGlobals;
468 Function *AsanUnregisterGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000469};
470
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000471// Stack poisoning does not play well with exception handling.
472// When an exception is thrown, we essentially bypass the code
473// that unpoisones the stack. This is why the run-time library has
474// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
475// stack in the interceptor. This however does not work inside the
476// actual function which catches the exception. Most likely because the
477// compiler hoists the load of the shadow value somewhere too high.
478// This causes asan to report a non-existing bug on 453.povray.
479// It sounds like an LLVM bug.
480struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
481 Function &F;
482 AddressSanitizer &ASan;
483 DIBuilder DIB;
484 LLVMContext *C;
485 Type *IntptrTy;
486 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000487 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000488
489 SmallVector<AllocaInst*, 16> AllocaVec;
490 SmallVector<Instruction*, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000491 unsigned StackAlignment;
492
Kostya Serebryany6805de52013-09-10 13:16:56 +0000493 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
494 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000495 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
496
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000497 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
498 struct AllocaPoisonCall {
499 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000500 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000501 uint64_t Size;
502 bool DoPoison;
503 };
504 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
505
Yury Gribov55441bb2014-11-21 10:29:50 +0000506 // Stores left and right redzone shadow addresses for dynamic alloca
507 // and pointer to alloca instruction itself.
508 // LeftRzAddr is a shadow address for alloca left redzone.
509 // RightRzAddr is a shadow address for alloca right redzone.
510 struct DynamicAllocaCall {
511 AllocaInst *AI;
512 Value *LeftRzAddr;
513 Value *RightRzAddr;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000514 bool Poison;
Yury Gribov55441bb2014-11-21 10:29:50 +0000515 explicit DynamicAllocaCall(AllocaInst *AI,
516 Value *LeftRzAddr = nullptr,
517 Value *RightRzAddr = nullptr)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000518 : AI(AI), LeftRzAddr(LeftRzAddr), RightRzAddr(RightRzAddr), Poison(true)
Yury Gribov55441bb2014-11-21 10:29:50 +0000519 {}
520 };
521 SmallVector<DynamicAllocaCall, 1> DynamicAllocaVec;
522
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000523 // Maps Value to an AllocaInst from which the Value is originated.
524 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
525 AllocaForValueMapTy AllocaForValue;
526
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000527 bool HasNonEmptyInlineAsm;
528 std::unique_ptr<CallInst> EmptyInlineAsm;
529
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000530 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000531 : F(F), ASan(ASan), DIB(*F.getParent(), /*AllowUnresolved*/ false),
532 C(ASan.C), IntptrTy(ASan.IntptrTy),
533 IntptrPtrTy(PointerType::get(IntptrTy, 0)), Mapping(ASan.Mapping),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000534 StackAlignment(1 << Mapping.Scale), HasNonEmptyInlineAsm(false),
535 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000536
537 bool runOnFunction() {
538 if (!ClStack) return false;
539 // Collect alloca, ret, lifetime instructions etc.
David Blaikieceec2bd2014-04-11 01:50:01 +0000540 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000541 visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000542
Yury Gribov55441bb2014-11-21 10:29:50 +0000543 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000544
545 initializeCallbacks(*F.getParent());
546
547 poisonStack();
548
549 if (ClDebugStack) {
550 DEBUG(dbgs() << F);
551 }
552 return true;
553 }
554
Yury Gribov55441bb2014-11-21 10:29:50 +0000555 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000556 // poisoned red zones around all of them.
557 // Then unpoison everything back before the function returns.
558 void poisonStack();
559
560 // ----------------------- Visitors.
561 /// \brief Collect all Ret instructions.
562 void visitReturnInst(ReturnInst &RI) {
563 RetVec.push_back(&RI);
564 }
565
Yury Gribov55441bb2014-11-21 10:29:50 +0000566 // Unpoison dynamic allocas redzones.
567 void unpoisonDynamicAlloca(DynamicAllocaCall &AllocaCall) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000568 if (!AllocaCall.Poison)
569 return;
Yury Gribov55441bb2014-11-21 10:29:50 +0000570 for (auto Ret : RetVec) {
571 IRBuilder<> IRBRet(Ret);
572 PointerType *Int32PtrTy = PointerType::getUnqual(IRBRet.getInt32Ty());
573 Value *Zero = Constant::getNullValue(IRBRet.getInt32Ty());
574 Value *PartialRzAddr = IRBRet.CreateSub(AllocaCall.RightRzAddr,
575 ConstantInt::get(IntptrTy, 4));
576 IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(AllocaCall.LeftRzAddr,
577 Int32PtrTy));
578 IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(PartialRzAddr,
579 Int32PtrTy));
580 IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(AllocaCall.RightRzAddr,
581 Int32PtrTy));
582 }
583 }
584
585 // Right shift for BigEndian and left shift for LittleEndian.
586 Value *shiftAllocaMagic(Value *Val, IRBuilder<> &IRB, Value *Shift) {
587 return ASan.DL->isLittleEndian() ? IRB.CreateShl(Val, Shift)
588 : IRB.CreateLShr(Val, Shift);
589 }
590
591 // Compute PartialRzMagic for dynamic alloca call. Since we don't know the
592 // size of requested memory until runtime, we should compute it dynamically.
593 // If PartialSize is 0, PartialRzMagic would contain kAsanAllocaRightMagic,
594 // otherwise it would contain the value that we will use to poison the
595 // partial redzone for alloca call.
596 Value *computePartialRzMagic(Value *PartialSize, IRBuilder<> &IRB);
597
598 // Deploy and poison redzones around dynamic alloca call. To do this, we
599 // should replace this call with another one with changed parameters and
600 // replace all its uses with new address, so
601 // addr = alloca type, old_size, align
602 // is replaced by
603 // new_size = (old_size + additional_size) * sizeof(type)
604 // tmp = alloca i8, new_size, max(align, 32)
605 // addr = tmp + 32 (first 32 bytes are for the left redzone).
606 // Additional_size is added to make new memory allocation contain not only
607 // requested memory, but also left, partial and right redzones.
608 // After that, we should poison redzones:
609 // (1) Left redzone with kAsanAllocaLeftMagic.
610 // (2) Partial redzone with the value, computed in runtime by
611 // computePartialRzMagic function.
612 // (3) Right redzone with kAsanAllocaRightMagic.
613 void handleDynamicAllocaCall(DynamicAllocaCall &AllocaCall);
614
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000615 /// \brief Collect Alloca instructions we want (and can) handle.
616 void visitAllocaInst(AllocaInst &AI) {
Anna Zaks8ed1d812015-02-27 03:12:36 +0000617 if (!ASan.isInterestingAlloca(AI)) return;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000618
619 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Yury Gribov55441bb2014-11-21 10:29:50 +0000620 if (isDynamicAlloca(AI))
621 DynamicAllocaVec.push_back(DynamicAllocaCall(&AI));
622 else
623 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000624 }
625
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000626 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
627 /// errors.
628 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000629 if (!ClCheckLifetime) return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000630 Intrinsic::ID ID = II.getIntrinsicID();
631 if (ID != Intrinsic::lifetime_start &&
632 ID != Intrinsic::lifetime_end)
633 return;
634 // Found lifetime intrinsic, add ASan instrumentation if necessary.
635 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
636 // If size argument is undefined, don't do anything.
637 if (Size->isMinusOne()) return;
638 // Check that size doesn't saturate uint64_t and can
639 // be stored in IntptrTy.
640 const uint64_t SizeValue = Size->getValue().getLimitedValue();
641 if (SizeValue == ~0ULL ||
642 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
643 return;
644 // Find alloca instruction that corresponds to llvm.lifetime argument.
645 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
646 if (!AI) return;
647 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000648 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000649 AllocaPoisonCallVec.push_back(APC);
650 }
651
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000652 void visitCallInst(CallInst &CI) {
653 HasNonEmptyInlineAsm |=
654 CI.isInlineAsm() && !CI.isIdenticalTo(EmptyInlineAsm.get());
655 }
656
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000657 // ---------------------- Helpers.
658 void initializeCallbacks(Module &M);
659
Yury Gribov3ae427d2014-12-01 08:47:58 +0000660 bool doesDominateAllExits(const Instruction *I) const {
661 for (auto Ret : RetVec) {
662 if (!ASan.getDominatorTree().dominates(I, Ret))
663 return false;
664 }
665 return true;
666 }
667
Yury Gribov55441bb2014-11-21 10:29:50 +0000668 bool isDynamicAlloca(AllocaInst &AI) const {
669 return AI.isArrayAllocation() || !AI.isStaticAlloca();
670 }
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000671 /// Finds alloca where the value comes from.
672 AllocaInst *findAllocaForValue(Value *V);
Craig Topper3af97222014-08-27 05:25:00 +0000673 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000674 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000675 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000676
677 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
678 int Size);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000679 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
680 bool Dynamic);
681 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
682 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000683};
684
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000685} // namespace
686
687char AddressSanitizer::ID = 0;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000688INITIALIZE_PASS_BEGIN(AddressSanitizer, "asan",
689 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
690 false, false)
691INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
692INITIALIZE_PASS_END(AddressSanitizer, "asan",
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000693 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
694 false, false)
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000695FunctionPass *llvm::createAddressSanitizerFunctionPass() {
696 return new AddressSanitizer();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000697}
698
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000699char AddressSanitizerModule::ID = 0;
700INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
701 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
702 "ModulePass", false, false)
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000703ModulePass *llvm::createAddressSanitizerModulePass() {
704 return new AddressSanitizerModule();
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000705}
706
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000707static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000708 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000709 assert(Res < kNumberOfAccessSizes);
710 return Res;
711}
712
Bill Wendling58f8cef2013-08-06 22:52:42 +0000713// \brief Create a constant for Str so that we can pass it to the run-time lib.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000714static GlobalVariable *createPrivateGlobalForString(
715 Module &M, StringRef Str, bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000716 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000717 // We use private linkage for module-local strings. If they can be merged
718 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000719 GlobalVariable *GV =
720 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000721 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
722 if (AllowMerging)
723 GV->setUnnamedAddr(true);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000724 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
725 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000726}
727
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000728/// \brief Create a global describing a source location.
729static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
730 LocationMetadata MD) {
731 Constant *LocData[] = {
732 createPrivateGlobalForString(M, MD.Filename, true),
733 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
734 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
735 };
736 auto LocStruct = ConstantStruct::getAnon(LocData);
737 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
738 GlobalValue::PrivateLinkage, LocStruct,
739 kAsanGenPrefix);
740 GV->setUnnamedAddr(true);
741 return GV;
742}
743
Kostya Serebryany139a9372012-11-20 14:16:08 +0000744static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000745 return G->getName().find(kAsanGenPrefix) == 0 ||
746 G->getName().find(kSanCovGenPrefix) == 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000747}
748
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000749Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
750 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000751 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
752 if (Mapping.Offset == 0)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000753 return Shadow;
754 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000755 if (Mapping.OrShadowOffset)
756 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
757 else
758 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000759}
760
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000761// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000762void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
763 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000764 if (isa<MemTransferInst>(MI)) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000765 IRB.CreateCall3(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000766 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
767 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
768 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
769 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
770 } else if (isa<MemSetInst>(MI)) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000771 IRB.CreateCall3(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000772 AsanMemset,
773 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
774 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
775 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000776 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000777 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000778}
779
Anna Zaks8ed1d812015-02-27 03:12:36 +0000780/// Check if we want (and can) handle this alloca.
781bool AddressSanitizer::isInterestingAlloca(AllocaInst &AI) const {
782 return (AI.getAllocatedType()->isSized() &&
783 // alloca() may be called with 0 size, ignore it.
784 getAllocaSizeInBytes(&AI) > 0 &&
785 // We are only interested in allocas not promotable to registers.
786 // Promotable allocas are common under -O0.
787 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)));
788}
789
790/// If I is an interesting memory access, return the PointerOperand
791/// and set IsWrite/Alignment. Otherwise return nullptr.
792Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
793 bool *IsWrite,
794 unsigned *Alignment) const {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000795 // Skip memory accesses inserted by another instrumentation.
796 if (I->getMetadata("nosanitize"))
797 return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000798
799 Value *PtrOperand = nullptr;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000800 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000801 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000802 *IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000803 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000804 PtrOperand = LI->getPointerOperand();
805 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000806 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000807 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000808 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000809 PtrOperand = SI->getPointerOperand();
810 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000811 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000812 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000813 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000814 PtrOperand = RMW->getPointerOperand();
815 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000816 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000817 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000818 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000819 PtrOperand = XCHG->getPointerOperand();
Kostya Serebryany90241602012-05-30 09:04:06 +0000820 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000821
822 // Treat memory accesses to promotable allocas as non-interesting since they
823 // will not cause memory violations. This greatly speeds up the instrumented
824 // executable at -O0.
825 if (ClSkipPromotableAllocas)
826 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
827 return isInterestingAlloca(*AI) ? AI : nullptr;
828
829 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000830}
831
Kostya Serebryany796f6552014-02-27 12:45:36 +0000832static bool isPointerOperand(Value *V) {
833 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
834}
835
836// This is a rough heuristic; it may cause both false positives and
837// false negatives. The proper implementation requires cooperation with
838// the frontend.
839static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
840 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
841 if (!Cmp->isRelational())
842 return false;
843 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +0000844 if (BO->getOpcode() != Instruction::Sub)
Kostya Serebryany796f6552014-02-27 12:45:36 +0000845 return false;
846 } else {
847 return false;
848 }
849 if (!isPointerOperand(I->getOperand(0)) ||
850 !isPointerOperand(I->getOperand(1)))
851 return false;
852 return true;
853}
854
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000855bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
856 // If a global variable does not have dynamic initialization we don't
857 // have to instrument it. However, if a global does not have initializer
858 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000859 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000860}
861
Kostya Serebryany796f6552014-02-27 12:45:36 +0000862void
863AddressSanitizer::instrumentPointerComparisonOrSubtraction(Instruction *I) {
864 IRBuilder<> IRB(I);
865 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
866 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
867 for (int i = 0; i < 2; i++) {
868 if (Param[i]->getType()->isPointerTy())
869 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
870 }
871 IRB.CreateCall2(F, Param[0], Param[1]);
872}
873
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000874void AddressSanitizer::instrumentMop(Instruction *I, bool UseCalls) {
Axel Naumann4a127062012-09-17 14:20:57 +0000875 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000876 unsigned Alignment = 0;
877 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +0000878 assert(Addr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000879 if (ClOpt && ClOptGlobals) {
880 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
881 // If initialization order checking is disabled, a simple access to a
882 // dynamically initialized global is always valid.
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000883 if (!ClInitializers || GlobalIsLinkerInitialized(G)) {
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000884 NumOptimizedAccessesToGlobalVar++;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000885 return;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000886 }
887 }
888 ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
889 if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
890 if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
891 if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
892 NumOptimizedAccessesToGlobalArray++;
893 return;
894 }
895 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000896 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000897 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000898
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000899 Type *OrigPtrTy = Addr->getType();
900 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
901
902 assert(OrigTy->isSized());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000903 uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000904
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000905 assert((TypeSize % 8) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000906
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000907 if (IsWrite)
908 NumInstrumentedWrites++;
909 else
910 NumInstrumentedReads++;
911
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000912 unsigned Granularity = 1 << Mapping.Scale;
913 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
914 // if the data is properly aligned.
915 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
916 TypeSize == 128) &&
917 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Craig Topperf40110f2014-04-25 05:29:35 +0000918 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls);
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000919 // Instrument unusual size or unusual alignment.
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000920 // We can not do it with a single check, so we do 1-byte check for the first
921 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
922 // to report the actual access size.
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000923 IRBuilder<> IRB(I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000924 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
Kostya Serebryanyc9a2c172014-04-22 11:19:45 +0000925 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
926 if (UseCalls) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000927 IRB.CreateCall2(AsanMemoryAccessCallbackSized[IsWrite], AddrLong, Size);
Kostya Serebryanyc9a2c172014-04-22 11:19:45 +0000928 } else {
929 Value *LastByte = IRB.CreateIntToPtr(
930 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
931 OrigPtrTy);
932 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false);
933 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false);
934 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000935}
936
Alexander Potapenko056e27e2012-04-23 10:47:31 +0000937// Validate the result of Module::getOrInsertFunction called for an interface
938// function of AddressSanitizer. If the instrumented module defines a function
939// with the same name, their prototypes must match, otherwise
940// getOrInsertFunction returns a bitcast.
Kostya Serebryany20a79972012-11-22 03:18:50 +0000941static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko056e27e2012-04-23 10:47:31 +0000942 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
943 FuncOrBitcast->dump();
944 report_fatal_error("trying to redefine an AddressSanitizer "
945 "interface function");
946}
947
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000948Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000949 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000950 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000951 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000952 CallInst *Call = SizeArgument
953 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
954 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
955
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000956 // We don't do Call->setDoesNotReturn() because the BB already has
957 // UnreachableInst at the end.
958 // This EmptyAsm is required to avoid callback merge.
959 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3411f2e2012-01-06 18:09:21 +0000960 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000961}
962
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000963Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryany874dae62012-07-16 16:15:40 +0000964 Value *ShadowValue,
965 uint32_t TypeSize) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000966 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +0000967 // Addr & (Granularity - 1)
968 Value *LastAccessedByte = IRB.CreateAnd(
969 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
970 // (Addr & (Granularity - 1)) + size - 1
971 if (TypeSize / 8 > 1)
972 LastAccessedByte = IRB.CreateAdd(
973 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
974 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
975 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000976 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000977 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
978 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
979}
980
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000981void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000982 Instruction *InsertBefore, Value *Addr,
983 uint32_t TypeSize, bool IsWrite,
984 Value *SizeArgument, bool UseCalls) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000985 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000986 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000987 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
988
989 if (UseCalls) {
Kostya Serebryany94f57d192014-04-21 10:28:13 +0000990 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][AccessSizeIndex],
991 AddrLong);
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000992 return;
993 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000994
995 Type *ShadowTy = IntegerType::get(
Alexey Samsonov1345d352013-01-16 13:23:28 +0000996 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000997 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
998 Value *ShadowPtr = memToShadow(AddrLong, IRB);
999 Value *CmpVal = Constant::getNullValue(ShadowTy);
1000 Value *ShadowValue = IRB.CreateLoad(
1001 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
1002
1003 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Alexey Samsonov1345d352013-01-16 13:23:28 +00001004 size_t Granularity = 1 << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001005 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001006
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001007 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001008 // We use branch weights for the slow path check, to indicate that the slow
1009 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +00001010 TerminatorInst *CheckTerm =
Kostya Serebryanyad238522014-09-02 21:46:51 +00001011 SplitBlockAndInsertIfThen(Cmp, InsertBefore, false,
1012 MDBuilder(*C).createBranchWeights(1, 100000));
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001013 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001014 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001015 IRB.SetInsertPoint(CheckTerm);
1016 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001017 BasicBlock *CrashBlock =
1018 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001019 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001020 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1021 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001022 } else {
Evgeniy Stepanova9164e92013-12-19 13:29:56 +00001023 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001024 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001025
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001026 Instruction *Crash = generateCrashCode(
1027 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001028 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001029}
1030
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001031void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1032 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001033 // Set up the arguments to our poison/unpoison functions.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001034 IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001035
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001036 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001037 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1038 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001039
1040 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001041 for (auto &BB : GlobalInit.getBasicBlockList())
1042 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001043 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001044}
1045
1046void AddressSanitizerModule::createInitializerPoisonCalls(
1047 Module &M, GlobalValue *ModuleName) {
1048 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1049
1050 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1051 for (Use &OP : CA->operands()) {
1052 if (isa<ConstantAggregateZero>(OP))
1053 continue;
1054 ConstantStruct *CS = cast<ConstantStruct>(OP);
1055
1056 // Must have a function or null ptr.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001057 if (Function* F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001058 if (F->getName() == kAsanModuleCtorName) continue;
1059 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1060 // Don't instrument CTORs that will run before asan.module_ctor.
1061 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1062 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001063 }
1064 }
1065}
1066
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001067bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001068 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001069 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001070
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001071 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001072 if (!Ty->isSized()) return false;
1073 if (!G->hasInitializer()) return false;
Kostya Serebryany139a9372012-11-20 14:16:08 +00001074 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001075 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001076 // Don't handle ODR linkage types and COMDATs since other modules may be built
1077 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001078 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1079 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1080 G->getLinkage() != GlobalVariable::InternalLinkage)
1081 return false;
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001082 if (G->hasComdat())
1083 return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001084 // Two problems with thread-locals:
1085 // - The address of the main thread's copy can't be computed at link-time.
1086 // - Need to poison all copies, not just the main thread's one.
1087 if (G->isThreadLocal())
1088 return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001089 // For now, just ignore this Global if the alignment is large.
1090 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001091
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001092 if (G->hasSection()) {
1093 StringRef Section(G->getSection());
Kuba Brecka086e34b2014-12-05 21:32:46 +00001094
Kuba Brecka1001bb52014-12-05 22:19:18 +00001095 if (TargetTriple.isOSBinFormatMachO()) {
1096 StringRef ParsedSegment, ParsedSection;
1097 unsigned TAA = 0, StubSize = 0;
1098 bool TAAParsed;
1099 std::string ErrorCode =
1100 MCSectionMachO::ParseSectionSpecifier(Section, ParsedSegment,
1101 ParsedSection, TAA, TAAParsed,
1102 StubSize);
1103 if (!ErrorCode.empty()) {
1104 report_fatal_error("Invalid section specifier '" + ParsedSection +
1105 "': " + ErrorCode + ".");
1106 }
1107
1108 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1109 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1110 // them.
1111 if (ParsedSegment == "__OBJC" ||
1112 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1113 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1114 return false;
1115 }
1116 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1117 // Constant CFString instances are compiled in the following way:
1118 // -- the string buffer is emitted into
1119 // __TEXT,__cstring,cstring_literals
1120 // -- the constant NSConstantString structure referencing that buffer
1121 // is placed into __DATA,__cfstring
1122 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1123 // Moreover, it causes the linker to crash on OS X 10.7
1124 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1125 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1126 return false;
1127 }
1128 // The linker merges the contents of cstring_literals and removes the
1129 // trailing zeroes.
1130 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1131 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1132 return false;
1133 }
1134 }
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +00001135
1136 // Callbacks put into the CRT initializer/terminator sections
1137 // should not be instrumented.
1138 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1139 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1140 if (Section.startswith(".CRT")) {
1141 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1142 return false;
1143 }
1144
Alexander Potapenko04969e82014-03-20 10:48:34 +00001145 // Globals from llvm.metadata aren't emitted, do not instrument them.
1146 if (Section == "llvm.metadata") return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001147 }
1148
1149 return true;
1150}
1151
Alexey Samsonov788381b2012-12-25 12:28:20 +00001152void AddressSanitizerModule::initializeCallbacks(Module &M) {
1153 IRBuilder<> IRB(*C);
1154 // Declare our poisoning and unpoisoning functions.
1155 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001156 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001157 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1158 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001159 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001160 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1161 // Declare functions that register/unregister globals.
1162 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1163 kAsanRegisterGlobalsName, IRB.getVoidTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001164 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001165 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1166 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1167 kAsanUnregisterGlobalsName,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001168 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001169 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1170}
1171
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001172// This function replaces all global variables with new variables that have
1173// trailing redzones. It also creates a function that poisons
1174// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001175bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001176 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001177
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001178 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1179
Alexey Samsonova02e6642014-05-29 18:40:48 +00001180 for (auto &G : M.globals()) {
1181 if (ShouldInstrumentGlobal(&G))
1182 GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001183 }
1184
1185 size_t n = GlobalsToChange.size();
1186 if (n == 0) return false;
1187
1188 // A global is described by a structure
1189 // size_t beg;
1190 // size_t size;
1191 // size_t size_with_redzone;
1192 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001193 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001194 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001195 // void *source_location;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001196 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001197 StructType *GlobalStructTy =
1198 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001199 IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001200 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001201
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001202 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001203
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001204 // We shouldn't merge same module names, as this string serves as unique
1205 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001206 GlobalVariable *ModuleName = createPrivateGlobalForString(
1207 M, M.getModuleIdentifier(), /*AllowMerging*/false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001208
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001209 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001210 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001211 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001212
1213 auto MD = GlobalsMD.get(G);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001214 // Create string holding the global name (use global name from metadata
1215 // if it's available, otherwise just write the name of global variable).
1216 GlobalVariable *Name = createPrivateGlobalForString(
1217 M, MD.Name.empty() ? G->getName() : MD.Name,
1218 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001219
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001220 PointerType *PtrTy = cast<PointerType>(G->getType());
1221 Type *Ty = PtrTy->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001222 uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001223 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001224 // MinRZ <= RZ <= kMaxGlobalRedzone
1225 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001226 uint64_t RZ = std::max(MinRZ,
Kostya Serebryany87191f62013-01-24 10:35:40 +00001227 std::min(kMaxGlobalRedzone,
1228 (SizeInBytes / MinRZ / 4) * MinRZ));
1229 uint64_t RightRedzoneSize = RZ;
1230 // Round up to MinRZ
1231 if (SizeInBytes % MinRZ)
1232 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1233 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001234 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1235
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001236 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001237 Constant *NewInitializer = ConstantStruct::get(
1238 NewTy, G->getInitializer(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001239 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001240
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001241 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001242 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1243 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1244 Linkage = GlobalValue::InternalLinkage;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001245 GlobalVariable *NewGlobal = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001246 M, NewTy, G->isConstant(), Linkage,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001247 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001248 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001249 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001250
1251 Value *Indices2[2];
1252 Indices2[0] = IRB.getInt32(0);
1253 Indices2[1] = IRB.getInt32(0);
1254
1255 G->replaceAllUsesWith(
Kostya Serebryany7471d132012-01-28 04:27:16 +00001256 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001257 NewGlobal->takeName(G);
1258 G->eraseFromParent();
1259
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001260 Constant *SourceLoc;
1261 if (!MD.SourceLoc.empty()) {
1262 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1263 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1264 } else {
1265 SourceLoc = ConstantInt::get(IntptrTy, 0);
1266 }
1267
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001268 Initializers[i] = ConstantStruct::get(
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001269 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001270 ConstantInt::get(IntptrTy, SizeInBytes),
1271 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1272 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001273 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001274 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001275
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001276 if (ClInitializers && MD.IsDynInit)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001277 HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001278
Kostya Serebryany20343352012-10-17 13:40:06 +00001279 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001280 }
1281
1282 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1283 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001284 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001285 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1286
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001287 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001288 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001289 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001290 IRB.CreateCall2(AsanRegisterGlobals,
1291 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1292 ConstantInt::get(IntptrTy, n));
1293
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001294 // We also need to unregister globals at the end, e.g. when a shared library
1295 // gets closed.
1296 Function *AsanDtorFunction = Function::Create(
1297 FunctionType::get(Type::getVoidTy(*C), false),
1298 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1299 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1300 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001301 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1302 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1303 ConstantInt::get(IntptrTy, n));
Alexey Samsonov1f647502014-05-29 01:10:14 +00001304 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001305
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001306 DEBUG(dbgs() << M);
1307 return true;
1308}
1309
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001310bool AddressSanitizerModule::runOnModule(Module &M) {
1311 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1312 if (!DLP)
1313 return false;
1314 DL = &DLP->getDataLayout();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001315 C = &(M.getContext());
1316 int LongSize = DL->getPointerSizeInBits();
1317 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001318 TargetTriple = Triple(M.getTargetTriple());
1319 Mapping = getShadowMapping(TargetTriple, LongSize);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001320 initializeCallbacks(M);
1321
1322 bool Changed = false;
1323
1324 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1325 assert(CtorFunc);
1326 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1327
Alexey Samsonovc94285a2014-07-08 00:50:49 +00001328 if (ClGlobals)
1329 Changed |= InstrumentGlobals(IRB, M);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001330
1331 return Changed;
1332}
1333
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001334void AddressSanitizer::initializeCallbacks(Module &M) {
1335 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001336 // Create __asan_report* callbacks.
1337 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1338 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1339 AccessSizeIndex++) {
1340 // IsWrite and TypeSize are encoded in the function name.
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001341 std::string Suffix =
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001342 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany157a5152012-11-07 12:42:18 +00001343 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001344 checkInterfaceFunction(
1345 M.getOrInsertFunction(kAsanReportErrorTemplate + Suffix,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001346 IRB.getVoidTy(), IntptrTy, nullptr));
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001347 AsanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
1348 checkInterfaceFunction(
1349 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + Suffix,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001350 IRB.getVoidTy(), IntptrTy, nullptr));
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001351 }
1352 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001353 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001354 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001355 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001356 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001357
Kostya Serebryany86332c02014-04-21 07:10:43 +00001358 AsanMemoryAccessCallbackSized[0] = checkInterfaceFunction(
1359 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "loadN",
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001360 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany86332c02014-04-21 07:10:43 +00001361 AsanMemoryAccessCallbackSized[1] = checkInterfaceFunction(
1362 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "storeN",
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001363 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany86332c02014-04-21 07:10:43 +00001364
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001365 AsanMemmove = checkInterfaceFunction(M.getOrInsertFunction(
1366 ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001367 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001368 AsanMemcpy = checkInterfaceFunction(M.getOrInsertFunction(
1369 ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001370 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001371 AsanMemset = checkInterfaceFunction(M.getOrInsertFunction(
1372 ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001373 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001374
1375 AsanHandleNoReturnFunc = checkInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001376 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001377
Kostya Serebryany796f6552014-02-27 12:45:36 +00001378 AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001379 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001380 AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001381 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001382 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1383 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1384 StringRef(""), StringRef(""),
1385 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001386}
1387
1388// virtual
1389bool AddressSanitizer::doInitialization(Module &M) {
1390 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001391 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1392 if (!DLP)
Evgeniy Stepanov119cb2e2014-04-23 12:51:32 +00001393 report_fatal_error("data layout missing");
Rafael Espindola93512512014-02-25 17:30:31 +00001394 DL = &DLP->getDataLayout();
1395
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001396 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001397
1398 C = &(M.getContext());
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001399 LongSize = DL->getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001400 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001401 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001402
1403 AsanCtorFunction = Function::Create(
1404 FunctionType::get(Type::getVoidTy(*C), false),
1405 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1406 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1407 // call __asan_init in the module ctor.
1408 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1409 AsanInitFunction = checkInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001410 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001411 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1412 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001413
Kuba Brecka1001bb52014-12-05 22:19:18 +00001414 Mapping = getShadowMapping(TargetTriple, LongSize);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001415
Alexey Samsonov1f647502014-05-29 01:10:14 +00001416 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001417 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001418}
1419
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001420bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1421 // For each NSObject descendant having a +load method, this method is invoked
1422 // by the ObjC runtime before any of the static constructors is called.
1423 // Therefore we need to instrument such methods with a call to __asan_init
1424 // at the beginning in order to initialize our runtime before any access to
1425 // the shadow memory.
1426 // We cannot just ignore these methods, because they may call other
1427 // instrumented functions.
1428 if (F.getName().find(" load]") != std::string::npos) {
1429 IRBuilder<> IRB(F.begin()->begin());
1430 IRB.CreateCall(AsanInitFunction);
1431 return true;
1432 }
1433 return false;
1434}
1435
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001436bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001437 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001438 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001439 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001440 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001441
Yury Gribov3ae427d2014-12-01 08:47:58 +00001442 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1443
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001444 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001445 maybeInsertAsanInitAtFunctionEntry(F);
1446
Alexey Samsonov6d8bab82014-06-02 18:08:27 +00001447 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001448 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001449
1450 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1451 return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001452
1453 // We want to instrument every address only once per basic block (unless there
1454 // are calls between uses).
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001455 SmallSet<Value*, 16> TempsToInstrument;
1456 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001457 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001458 SmallVector<BasicBlock*, 16> AllBlocks;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001459 SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001460 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001461 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001462 unsigned Alignment;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001463
1464 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001465 for (auto &BB : F) {
1466 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001467 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001468 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001469 for (auto &Inst : BB) {
1470 if (LooksLikeCodeInBug11395(&Inst)) return false;
1471 if (Value *Addr =
1472 isInterestingMemoryAccess(&Inst, &IsWrite, &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001473 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001474 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001475 continue; // We've seen this temp in the current BB.
1476 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001477 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001478 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1479 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001480 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001481 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001482 // ok, take it.
1483 } else {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001484 if (isa<AllocaInst>(Inst))
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001485 NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001486 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001487 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001488 // A call inside BB.
1489 TempsToInstrument.clear();
Kostya Serebryany699ac282013-02-20 12:35:15 +00001490 if (CS.doesNotReturn())
1491 NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001492 }
1493 continue;
1494 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001495 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001496 NumInsnsPerBB++;
1497 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1498 break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001499 }
1500 }
1501
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001502 bool UseCalls = false;
1503 if (ClInstrumentationWithCallsThreshold >= 0 &&
1504 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1505 UseCalls = true;
1506
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001507 // Instrument.
1508 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001509 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001510 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1511 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001512 if (isInterestingMemoryAccess(Inst, &IsWrite, &Alignment))
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001513 instrumentMop(Inst, UseCalls);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001514 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001515 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001516 }
1517 NumInstrumented++;
1518 }
1519
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001520 FunctionStackPoisoner FSP(F, *this);
1521 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001522
1523 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1524 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001525 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001526 IRBuilder<> IRB(CI);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001527 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001528 }
1529
Alexey Samsonova02e6642014-05-29 18:40:48 +00001530 for (auto Inst : PointerComparisonsOrSubtracts) {
1531 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001532 NumInstrumented++;
1533 }
1534
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001535 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001536
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001537 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1538
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001539 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001540}
1541
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001542// Workaround for bug 11395: we don't want to instrument stack in functions
1543// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1544// FIXME: remove once the bug 11395 is fixed.
1545bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1546 if (LongSize != 32) return false;
1547 CallInst *CI = dyn_cast<CallInst>(I);
1548 if (!CI || !CI->isInlineAsm()) return false;
1549 if (CI->getNumArgOperands() <= 5) return false;
1550 // We have inline assembly with quite a few arguments.
1551 return true;
1552}
1553
1554void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1555 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001556 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1557 std::string Suffix = itostr(i);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001558 AsanStackMallocFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1559 kAsanStackMallocNameTemplate + Suffix, IntptrTy, IntptrTy, nullptr));
1560 AsanStackFreeFunc[i] = checkInterfaceFunction(
1561 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1562 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001563 }
David Blaikiea92765c2014-11-14 00:41:42 +00001564 AsanPoisonStackMemoryFunc = checkInterfaceFunction(
1565 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1566 IntptrTy, IntptrTy, nullptr));
1567 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(
1568 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1569 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001570}
1571
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001572void
Craig Topper3af97222014-08-27 05:25:00 +00001573FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001574 IRBuilder<> &IRB, Value *ShadowBase,
1575 bool DoPoison) {
1576 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001577 size_t i = 0;
1578 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1579 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1580 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1581 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1582 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1583 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1584 uint64_t Val = 0;
1585 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001586 if (ASan.DL->isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001587 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1588 else
1589 Val = (Val << 8) | ShadowBytes[i + j];
1590 }
1591 if (!Val) continue;
1592 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1593 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1594 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1595 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001596 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001597 }
1598}
1599
Kostya Serebryany6805de52013-09-10 13:16:56 +00001600// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1601// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1602static int StackMallocSizeClass(uint64_t LocalStackSize) {
1603 assert(LocalStackSize <= kMaxStackMallocSize);
1604 uint64_t MaxSize = kMinStackMallocSize;
1605 for (int i = 0; ; i++, MaxSize *= 2)
1606 if (LocalStackSize <= MaxSize)
1607 return i;
1608 llvm_unreachable("impossible LocalStackSize");
1609}
1610
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001611// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1612// We can not use MemSet intrinsic because it may end up calling the actual
1613// memset. Size is a multiple of 8.
1614// Currently this generates 8-byte stores on x86_64; it may be better to
1615// generate wider stores.
1616void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1617 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1618 assert(!(Size % 8));
1619 assert(kAsanStackAfterReturnMagic == 0xf5);
1620 for (int i = 0; i < Size; i += 8) {
1621 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1622 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1623 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1624 }
1625}
1626
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001627static DebugLoc getFunctionEntryDebugLocation(Function &F) {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001628 for (const auto &Inst : F.getEntryBlock())
1629 if (!isa<AllocaInst>(Inst))
1630 return Inst.getDebugLoc();
1631 return DebugLoc();
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001632}
1633
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001634PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1635 Value *ValueIfTrue,
1636 Instruction *ThenTerm,
1637 Value *ValueIfFalse) {
1638 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1639 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1640 PHI->addIncoming(ValueIfFalse, CondBlock);
1641 BasicBlock *ThenBlock = ThenTerm->getParent();
1642 PHI->addIncoming(ValueIfTrue, ThenBlock);
1643 return PHI;
1644}
1645
1646Value *FunctionStackPoisoner::createAllocaForLayout(
1647 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
1648 AllocaInst *Alloca;
1649 if (Dynamic) {
1650 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
1651 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
1652 "MyAlloca");
1653 } else {
1654 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
1655 nullptr, "MyAlloca");
1656 assert(Alloca->isStaticAlloca());
1657 }
1658 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1659 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1660 Alloca->setAlignment(FrameAlignment);
1661 return IRB.CreatePointerCast(Alloca, IntptrTy);
1662}
1663
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001664void FunctionStackPoisoner::poisonStack() {
Yury Gribov55441bb2014-11-21 10:29:50 +00001665 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1666
Kuba Breckaf5875d32015-02-24 09:47:05 +00001667 if (ClInstrumentAllocas) {
Yury Gribov55441bb2014-11-21 10:29:50 +00001668 // Handle dynamic allocas.
Kuba Breckaf5875d32015-02-24 09:47:05 +00001669 for (auto &AllocaCall : DynamicAllocaVec) {
Yury Gribov55441bb2014-11-21 10:29:50 +00001670 handleDynamicAllocaCall(AllocaCall);
Kuba Breckaf5875d32015-02-24 09:47:05 +00001671 unpoisonDynamicAlloca(AllocaCall);
1672 }
1673 }
Yury Gribov55441bb2014-11-21 10:29:50 +00001674
1675 if (AllocaVec.size() == 0) return;
1676
Kostya Serebryany6805de52013-09-10 13:16:56 +00001677 int StackMallocIdx = -1;
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001678 DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001679
1680 Instruction *InsBefore = AllocaVec[0];
1681 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001682 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001683
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001684 SmallVector<ASanStackVariableDescription, 16> SVD;
1685 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00001686 for (AllocaInst *AI : AllocaVec) {
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001687 ASanStackVariableDescription D = { AI->getName().data(),
Anna Zaks8ed1d812015-02-27 03:12:36 +00001688 ASan.getAllocaSizeInBytes(AI),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001689 AI->getAlignment(), AI, 0};
1690 SVD.push_back(D);
1691 }
1692 // Minimal header size (left redzone) is 4 pointers,
1693 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1694 size_t MinHeaderSize = ASan.LongSize / 2;
1695 ASanStackFrameLayout L;
1696 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1697 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1698 uint64_t LocalStackSize = L.FrameSize;
1699 bool DoStackMalloc =
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001700 ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001701 // Don't do dynamic alloca in presence of inline asm: too often it
1702 // makes assumptions on which registers are available.
1703 bool DoDynamicAlloca = ClDynamicAllocaStack && !HasNonEmptyInlineAsm;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001704
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001705 Value *StaticAlloca =
1706 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
1707
1708 Value *FakeStack;
1709 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001710
1711 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001712 // void *FakeStack = __asan_option_detect_stack_use_after_return
1713 // ? __asan_stack_malloc_N(LocalStackSize)
1714 // : nullptr;
1715 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001716 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1717 kAsanOptionDetectUAR, IRB.getInt32Ty());
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001718 Value *UARIsEnabled =
1719 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1720 Constant::getNullValue(IRB.getInt32Ty()));
1721 Instruction *Term =
1722 SplitBlockAndInsertIfThen(UARIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001723 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001724 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001725 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1726 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1727 Value *FakeStackValue =
1728 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
1729 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001730 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001731 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001732 FakeStack = createPHI(IRB, UARIsEnabled, FakeStackValue, Term,
1733 ConstantInt::get(IntptrTy, 0));
1734
1735 Value *NoFakeStack =
1736 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
1737 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
1738 IRBIf.SetInsertPoint(Term);
1739 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1740 Value *AllocaValue =
1741 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
1742 IRB.SetInsertPoint(InsBefore);
1743 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1744 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
1745 } else {
1746 // void *FakeStack = nullptr;
1747 // void *LocalStackBase = alloca(LocalStackSize);
1748 FakeStack = ConstantInt::get(IntptrTy, 0);
1749 LocalStackBase =
1750 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001751 }
1752
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001753 // Insert poison calls for lifetime intrinsics for alloca.
1754 bool HavePoisonedAllocas = false;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001755 for (const auto &APC : AllocaPoisonCallVec) {
Alexey Samsonova788b942013-11-18 14:53:55 +00001756 assert(APC.InsBefore);
1757 assert(APC.AI);
1758 IRBuilder<> IRB(APC.InsBefore);
1759 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001760 HavePoisonedAllocas |= APC.DoPoison;
1761 }
1762
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001763 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001764 for (const auto &Desc : SVD) {
1765 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00001766 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00001767 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001768 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00001769 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001770 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001771 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001772
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001773 // The left-most redzone has enough space for at least 4 pointers.
1774 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001775 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1776 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1777 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001778 // Write the frame description constant to redzone[1].
1779 Value *BasePlus1 = IRB.CreateIntToPtr(
1780 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1781 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00001782 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001783 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1784 /*AllowMerging*/true);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001785 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1786 IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001787 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001788 // Write the PC to redzone[2].
1789 Value *BasePlus2 = IRB.CreateIntToPtr(
1790 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1791 2 * ASan.LongSize/8)),
1792 IntptrPtrTy);
1793 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001794
1795 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001796 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001797 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001798
Kostya Serebryany530e2072013-12-23 14:15:08 +00001799 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001800 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001801 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001802 // Mark the current frame as retired.
1803 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1804 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001805 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001806 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001807 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00001808 // // In use-after-return mode, poison the whole stack frame.
1809 // if StackMallocIdx <= 4
1810 // // For small sizes inline the whole thing:
1811 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001812 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00001813 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001814 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00001815 // else
1816 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001817 Value *Cmp =
1818 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00001819 TerminatorInst *ThenTerm, *ElseTerm;
1820 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1821
1822 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001823 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001824 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1825 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1826 ClassSize >> Mapping.Scale);
1827 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001828 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001829 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1830 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1831 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1832 IRBPoison.CreateStore(
1833 Constant::getNullValue(IRBPoison.getInt8Ty()),
1834 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1835 } else {
1836 // For larger frames call __asan_stack_free_*.
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001837 IRBPoison.CreateCall2(AsanStackFreeFunc[StackMallocIdx], FakeStack,
1838 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001839 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00001840
1841 IRBuilder<> IRBElse(ElseTerm);
1842 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001843 } else if (HavePoisonedAllocas) {
1844 // If we poisoned some allocas in llvm.lifetime analysis,
1845 // unpoison whole stack frame now.
Alexey Samsonov261177a2012-12-04 01:34:23 +00001846 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001847 } else {
1848 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001849 }
1850 }
1851
Kostya Serebryany09959942012-10-19 06:20:53 +00001852 // We are done. Remove the old unused alloca instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001853 for (auto AI : AllocaVec)
1854 AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001855}
Alexey Samsonov261177a2012-12-04 01:34:23 +00001856
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001857void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00001858 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00001859 // For now just insert the call to ASan runtime.
1860 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1861 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1862 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1863 : AsanUnpoisonStackMemoryFunc,
1864 AddrArg, SizeArg);
1865}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001866
1867// Handling llvm.lifetime intrinsics for a given %alloca:
1868// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1869// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1870// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1871// could be poisoned by previous llvm.lifetime.end instruction, as the
1872// variable may go in and out of scope several times, e.g. in loops).
1873// (3) if we poisoned at least one %alloca in a function,
1874// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001875
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001876AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1877 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1878 // We're intested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00001879 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001880 // See if we've already calculated (or started to calculate) alloca for a
1881 // given value.
1882 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1883 if (I != AllocaForValue.end())
1884 return I->second;
1885 // Store 0 while we're calculating alloca for value V to avoid
1886 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00001887 AllocaForValue[V] = nullptr;
1888 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001889 if (CastInst *CI = dyn_cast<CastInst>(V))
1890 Res = findAllocaForValue(CI->getOperand(0));
1891 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1892 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1893 Value *IncValue = PN->getIncomingValue(i);
1894 // Allow self-referencing phi-nodes.
1895 if (IncValue == PN) continue;
1896 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1897 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00001898 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1899 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001900 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001901 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001902 }
Craig Topperf40110f2014-04-25 05:29:35 +00001903 if (Res)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001904 AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001905 return Res;
1906}
Yury Gribov55441bb2014-11-21 10:29:50 +00001907
1908// Compute PartialRzMagic for dynamic alloca call. PartialRzMagic is
1909// constructed from two separate 32-bit numbers: PartialRzMagic = Val1 | Val2.
1910// (1) Val1 is resposible for forming base value for PartialRzMagic, containing
1911// only 00 for fully addressable and 0xcb for fully poisoned bytes for each
1912// 8-byte chunk of user memory respectively.
1913// (2) Val2 forms the value for marking first poisoned byte in shadow memory
1914// with appropriate value (0x01 - 0x07 or 0xcb if Padding % 8 == 0).
1915
1916// Shift = Padding & ~7; // the number of bits we need to shift to access first
1917// chunk in shadow memory, containing nonzero bytes.
1918// Example:
1919// Padding = 21 Padding = 16
1920// Shadow: |00|00|05|cb| Shadow: |00|00|cb|cb|
1921// ^ ^
1922// | |
1923// Shift = 21 & ~7 = 16 Shift = 16 & ~7 = 16
1924//
1925// Val1 = 0xcbcbcbcb << Shift;
1926// PartialBits = Padding ? Padding & 7 : 0xcb;
1927// Val2 = PartialBits << Shift;
1928// Result = Val1 | Val2;
1929Value *FunctionStackPoisoner::computePartialRzMagic(Value *PartialSize,
1930 IRBuilder<> &IRB) {
1931 PartialSize = IRB.CreateIntCast(PartialSize, IRB.getInt32Ty(), false);
1932 Value *Shift = IRB.CreateAnd(PartialSize, IRB.getInt32(~7));
1933 unsigned Val1Int = kAsanAllocaPartialVal1;
1934 unsigned Val2Int = kAsanAllocaPartialVal2;
1935 if (!ASan.DL->isLittleEndian()) {
1936 Val1Int = sys::getSwappedBytes(Val1Int);
1937 Val2Int = sys::getSwappedBytes(Val2Int);
1938 }
1939 Value *Val1 = shiftAllocaMagic(IRB.getInt32(Val1Int), IRB, Shift);
1940 Value *PartialBits = IRB.CreateAnd(PartialSize, IRB.getInt32(7));
1941 // For BigEndian get 0x000000YZ -> 0xYZ000000.
1942 if (ASan.DL->isBigEndian())
1943 PartialBits = IRB.CreateShl(PartialBits, IRB.getInt32(24));
1944 Value *Val2 = IRB.getInt32(Val2Int);
1945 Value *Cond =
1946 IRB.CreateICmpNE(PartialBits, Constant::getNullValue(IRB.getInt32Ty()));
1947 Val2 = IRB.CreateSelect(Cond, shiftAllocaMagic(PartialBits, IRB, Shift),
1948 shiftAllocaMagic(Val2, IRB, Shift));
1949 return IRB.CreateOr(Val1, Val2);
1950}
1951
1952void FunctionStackPoisoner::handleDynamicAllocaCall(
1953 DynamicAllocaCall &AllocaCall) {
1954 AllocaInst *AI = AllocaCall.AI;
Yury Gribov3ae427d2014-12-01 08:47:58 +00001955 if (!doesDominateAllExits(AI)) {
1956 // We do not yet handle complex allocas
1957 AllocaCall.Poison = false;
1958 return;
1959 }
1960
Yury Gribov55441bb2014-11-21 10:29:50 +00001961 IRBuilder<> IRB(AI);
1962
1963 PointerType *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
1964 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
1965 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
1966
1967 Value *Zero = Constant::getNullValue(IntptrTy);
1968 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
1969 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
1970 Value *NotAllocaRzMask = ConstantInt::get(IntptrTy, ~AllocaRedzoneMask);
1971
1972 // Since we need to extend alloca with additional memory to locate
1973 // redzones, and OldSize is number of allocated blocks with
1974 // ElementSize size, get allocated memory size in bytes by
1975 // OldSize * ElementSize.
1976 unsigned ElementSize = ASan.DL->getTypeAllocSize(AI->getAllocatedType());
1977 Value *OldSize = IRB.CreateMul(AI->getArraySize(),
1978 ConstantInt::get(IntptrTy, ElementSize));
1979
1980 // PartialSize = OldSize % 32
1981 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
1982
1983 // Misalign = kAllocaRzSize - PartialSize;
1984 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
1985
1986 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
1987 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
1988 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
1989
1990 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
1991 // Align is added to locate left redzone, PartialPadding for possible
1992 // partial redzone and kAllocaRzSize for right redzone respectively.
1993 Value *AdditionalChunkSize = IRB.CreateAdd(
1994 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
1995
1996 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
1997
1998 // Insert new alloca with new NewSize and Align params.
1999 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2000 NewAlloca->setAlignment(Align);
2001
2002 // NewAddress = Address + Align
2003 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2004 ConstantInt::get(IntptrTy, Align));
2005
2006 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2007
2008 // LeftRzAddress = NewAddress - kAllocaRzSize
2009 Value *LeftRzAddress = IRB.CreateSub(NewAddress, AllocaRzSize);
2010
2011 // Poisoning left redzone.
2012 AllocaCall.LeftRzAddr = ASan.memToShadow(LeftRzAddress, IRB);
2013 IRB.CreateStore(ConstantInt::get(IRB.getInt32Ty(), kAsanAllocaLeftMagic),
2014 IRB.CreateIntToPtr(AllocaCall.LeftRzAddr, Int32PtrTy));
2015
2016 // PartialRzAligned = PartialRzAddr & ~AllocaRzMask
2017 Value *PartialRzAddr = IRB.CreateAdd(NewAddress, OldSize);
2018 Value *PartialRzAligned = IRB.CreateAnd(PartialRzAddr, NotAllocaRzMask);
2019
2020 // Poisoning partial redzone.
2021 Value *PartialRzMagic = computePartialRzMagic(PartialSize, IRB);
2022 Value *PartialRzShadowAddr = ASan.memToShadow(PartialRzAligned, IRB);
2023 IRB.CreateStore(PartialRzMagic,
2024 IRB.CreateIntToPtr(PartialRzShadowAddr, Int32PtrTy));
2025
2026 // RightRzAddress
2027 // = (PartialRzAddr + AllocaRzMask) & ~AllocaRzMask
2028 Value *RightRzAddress = IRB.CreateAnd(
2029 IRB.CreateAdd(PartialRzAddr, AllocaRzMask), NotAllocaRzMask);
2030
2031 // Poisoning right redzone.
2032 AllocaCall.RightRzAddr = ASan.memToShadow(RightRzAddress, IRB);
2033 IRB.CreateStore(ConstantInt::get(IRB.getInt32Ty(), kAsanAllocaRightMagic),
2034 IRB.CreateIntToPtr(AllocaCall.RightRzAddr, Int32PtrTy));
2035
2036 // Replace all uses of AddessReturnedByAlloca with NewAddress.
2037 AI->replaceAllUsesWith(NewAddressPtr);
2038
2039 // We are done. Erase old alloca and store left, partial and right redzones
2040 // shadow addresses for future unpoisoning.
2041 AI->eraseFromParent();
Kostya Serebryanyea2cb6f2014-11-21 21:25:18 +00002042 NumInstrumentedDynamicAllocas++;
Yury Gribov55441bb2014-11-21 10:29:50 +00002043}