blob: 2e088ccb29bb7dd4f683111da6169f4a17de25b2 [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"
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000027#include "llvm/Analysis/MemoryBuiltins.h"
28#include "llvm/Analysis/TargetLibraryInfo.h"
29#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000030#include "llvm/IR/CallSite.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000031#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/DataLayout.h"
Yury Gribov3ae427d2014-12-01 08:47:58 +000033#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Function.h"
35#include "llvm/IR/IRBuilder.h"
36#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000037#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/IntrinsicInst.h"
39#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000040#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Module.h"
42#include "llvm/IR/Type.h"
Kuba Brecka1001bb52014-12-05 22:19:18 +000043#include "llvm/MC/MCSectionMachO.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000044#include "llvm/Support/CommandLine.h"
45#include "llvm/Support/DataTypes.h"
46#include "llvm/Support/Debug.h"
Kostya Serebryany9e62b302013-06-03 14:46:56 +000047#include "llvm/Support/Endian.h"
Yury Gribov55441bb2014-11-21 10:29:50 +000048#include "llvm/Support/SwapByteOrder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000049#include "llvm/Support/raw_ostream.h"
Kostya Serebryany351b0782014-09-03 22:37:37 +000050#include "llvm/Transforms/Scalar.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000051#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000052#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany9f5213f2013-06-26 09:18:17 +000053#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000054#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000055#include "llvm/Transforms/Utils/ModuleUtils.h"
Anna Zaks8ed1d812015-02-27 03:12:36 +000056#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000057#include <algorithm>
Chandler Carruthed0881b2012-12-03 16:50:05 +000058#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000059#include <system_error>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000060
61using namespace llvm;
62
Chandler Carruth964daaa2014-04-22 02:55:47 +000063#define DEBUG_TYPE "asan"
64
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000065static const uint64_t kDefaultShadowScale = 3;
66static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +000067static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000068static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000069static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Kostya Serebryany4766fe62013-01-23 12:54:55 +000070static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +000071static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +000072static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +000073static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000074static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
75static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +000076static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000077
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000078static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000079static const size_t kMaxStackMallocSize = 1 << 16; // 64K
80static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
81static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
82
Craig Topperd3a34f82013-07-16 01:17:10 +000083static const char *const kAsanModuleCtorName = "asan.module_ctor";
84static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000085static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000086static const char *const kAsanReportErrorTemplate = "__asan_report_";
Craig Topperd3a34f82013-07-16 01:17:10 +000087static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000088static const char *const kAsanUnregisterGlobalsName =
89 "__asan_unregister_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +000090static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
91static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Alexey Samsonov4b7f4132014-12-11 21:53:03 +000092static const char *const kAsanInitName = "__asan_init_v5";
Kostya Serebryany796f6552014-02-27 12:45:36 +000093static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
94static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +000095static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000096static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +000097static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
98static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +000099static const char *const kAsanGenPrefix = "__asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000100static const char *const kSanCovGenPrefix = "__sancov_gen_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000101static const char *const kAsanPoisonStackMemoryName =
102 "__asan_poison_stack_memory";
103static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000104 "__asan_unpoison_stack_memory";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000105
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000106static const char *const kAsanOptionDetectUAR =
107 "__asan_option_detect_stack_use_after_return";
108
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000109static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
110static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
Yury Gribov98b18592015-05-28 07:51:49 +0000111
Kostya Serebryany874dae62012-07-16 16:15:40 +0000112// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
113static const size_t kNumberOfAccessSizes = 5;
114
Yury Gribov55441bb2014-11-21 10:29:50 +0000115static const unsigned kAllocaRzSize = 32;
Yury Gribov55441bb2014-11-21 10:29:50 +0000116
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000117// Command-line flags.
118
119// This flag may need to be replaced with -f[no-]asan-reads.
120static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000121 cl::desc("instrument read instructions"),
122 cl::Hidden, cl::init(true));
123static cl::opt<bool> ClInstrumentWrites(
124 "asan-instrument-writes", cl::desc("instrument write instructions"),
125 cl::Hidden, cl::init(true));
126static cl::opt<bool> ClInstrumentAtomics(
127 "asan-instrument-atomics",
128 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
129 cl::init(true));
130static cl::opt<bool> ClAlwaysSlowPath(
131 "asan-always-slow-path",
132 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
133 cl::init(false));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000134// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000135// in any given BB. Normally, this should be set to unlimited (INT_MAX),
136// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
137// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000138static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
139 "asan-max-ins-per-bb", cl::init(10000),
140 cl::desc("maximal number of instructions to instrument in any given BB"),
141 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000142// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000143static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
144 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000145static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000146 cl::desc("Check return-after-free"),
147 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000148// This flag may need to be replaced with -f[no]asan-globals.
149static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000150 cl::desc("Handle global objects"), cl::Hidden,
151 cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000152static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000153 cl::desc("Handle C++ initializer order"),
154 cl::Hidden, cl::init(true));
155static cl::opt<bool> ClInvalidPointerPairs(
156 "asan-detect-invalid-pointer-pair",
157 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
158 cl::init(false));
159static cl::opt<unsigned> ClRealignStack(
160 "asan-realign-stack",
161 cl::desc("Realign stack to the value of this flag (power of two)"),
162 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000163static cl::opt<int> ClInstrumentationWithCallsThreshold(
164 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000165 cl::desc(
166 "If the function being instrumented contains more than "
167 "this number of memory accesses, use callbacks instead of "
168 "inline checks (-1 means never use callbacks)."),
169 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000170static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000171 "asan-memory-access-callback-prefix",
172 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
173 cl::init("__asan_"));
Yury Gribov55441bb2014-11-21 10:29:50 +0000174static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000175 cl::desc("instrument dynamic allocas"),
176 cl::Hidden, cl::init(false));
177static cl::opt<bool> ClSkipPromotableAllocas(
178 "asan-skip-promotable-allocas",
179 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
180 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000181
182// These flags allow to change the shadow mapping.
183// The shadow mapping looks like
184// Shadow = (Mem >> scale) + (1 << offset_log)
185static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000186 cl::desc("scale of asan shadow mapping"),
187 cl::Hidden, cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000188
189// Optimization flags. Not user visible, used mostly for testing
190// and benchmarking the tool.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000191static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
192 cl::Hidden, cl::init(true));
193static cl::opt<bool> ClOptSameTemp(
194 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
195 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000196static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000197 cl::desc("Don't instrument scalar globals"),
198 cl::Hidden, cl::init(true));
199static cl::opt<bool> ClOptStack(
200 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
201 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000202
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000203static cl::opt<bool> ClCheckLifetime(
204 "asan-check-lifetime",
205 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"), cl::Hidden,
206 cl::init(false));
Alexey Samsonovdf624522012-11-29 18:14:24 +0000207
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000208static cl::opt<bool> ClDynamicAllocaStack(
209 "asan-stack-dynamic-alloca",
210 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000211 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000212
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000213static cl::opt<uint32_t> ClForceExperiment(
214 "asan-force-experiment",
215 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
216 cl::init(0));
217
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000218// Debug flags.
219static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
220 cl::init(0));
221static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
222 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000223static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
224 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000225static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
226 cl::Hidden, cl::init(-1));
227static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
228 cl::Hidden, cl::init(-1));
229
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000230STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
231STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000232STATISTIC(NumOptimizedAccessesToGlobalVar,
233 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000234STATISTIC(NumOptimizedAccessesToStackVar,
235 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000236
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000237namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000238/// Frontend-provided metadata for source location.
239struct LocationMetadata {
240 StringRef Filename;
241 int LineNo;
242 int ColumnNo;
243
244 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
245
246 bool empty() const { return Filename.empty(); }
247
248 void parse(MDNode *MDN) {
249 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000250 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
251 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000252 LineNo =
253 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
254 ColumnNo =
255 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000256 }
257};
258
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000259/// Frontend-provided metadata for global variables.
260class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000261 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000262 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000263 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000264 LocationMetadata SourceLoc;
265 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000266 bool IsDynInit;
267 bool IsBlacklisted;
268 };
269
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000270 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000271
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000272 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000273 assert(!inited_);
274 inited_ = true;
275 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000276 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000277 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000278 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000279 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000280 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000281 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000282 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000283 // We can already have an entry for GV if it was merged with another
284 // global.
285 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000286 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
287 E.SourceLoc.parse(Loc);
288 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
289 E.Name = Name->getString();
290 ConstantInt *IsDynInit =
291 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000292 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000293 ConstantInt *IsBlacklisted =
294 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000295 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000296 }
297 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000298
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000299 /// Returns metadata entry for a given global.
300 Entry get(GlobalVariable *G) const {
301 auto Pos = Entries.find(G);
302 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000303 }
304
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000305 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000306 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000307 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000308};
309
Alexey Samsonov1345d352013-01-16 13:23:28 +0000310/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000311/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000312struct ShadowMapping {
313 int Scale;
314 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000315 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000316};
317
Kuba Brecka1001bb52014-12-05 22:19:18 +0000318static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize) {
Alexey Samsonov347bcd32013-01-17 11:12:32 +0000319 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Bob Wilson9868d712014-10-09 05:43:30 +0000320 bool IsIOS = TargetTriple.isiOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000321 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
322 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000323 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
324 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000325 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000326 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
327 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000328 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
329 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000330 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000331 bool IsWindows = TargetTriple.isOSWindows();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000332
333 ShadowMapping Mapping;
334
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000335 if (LongSize == 32) {
336 if (IsAndroid)
337 Mapping.Offset = 0;
338 else if (IsMIPS32)
339 Mapping.Offset = kMIPS32_ShadowOffset32;
340 else if (IsFreeBSD)
341 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000342 else if (IsIOS)
343 Mapping.Offset = kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000344 else if (IsWindows)
345 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000346 else
347 Mapping.Offset = kDefaultShadowOffset32;
348 } else { // LongSize == 64
349 if (IsPPC64)
350 Mapping.Offset = kPPC64_ShadowOffset64;
351 else if (IsFreeBSD)
352 Mapping.Offset = kFreeBSD_ShadowOffset64;
353 else if (IsLinux && IsX86_64)
354 Mapping.Offset = kSmallX86_64ShadowOffset;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000355 else if (IsMIPS64)
356 Mapping.Offset = kMIPS64_ShadowOffset64;
Renato Golinaf213722015-02-03 11:20:45 +0000357 else if (IsAArch64)
358 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000359 else
360 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000361 }
362
363 Mapping.Scale = kDefaultShadowScale;
364 if (ClMappingScale) {
365 Mapping.Scale = ClMappingScale;
366 }
367
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000368 // OR-ing shadow offset if more efficient (at least on x86) if the offset
369 // is a power of two, but on ppc64 we have to use add since the shadow
370 // offset is not necessary 1/8-th of the address space.
371 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
372
Alexey Samsonov1345d352013-01-16 13:23:28 +0000373 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000374}
375
Alexey Samsonov1345d352013-01-16 13:23:28 +0000376static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000377 // Redzone used for stack and globals is at least 32 bytes.
378 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000379 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000380}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000381
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000382/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000383struct AddressSanitizer : public FunctionPass {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000384 AddressSanitizer() : FunctionPass(ID) {
385 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
386 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000387 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000388 return "AddressSanitizerFunctionPass";
389 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000390 void getAnalysisUsage(AnalysisUsage &AU) const override {
391 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000392 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000393 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000394 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
395 Type *Ty = AI->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000396 uint64_t SizeInBytes =
397 AI->getModule()->getDataLayout().getTypeAllocSize(Ty);
Anna Zaks8ed1d812015-02-27 03:12:36 +0000398 return SizeInBytes;
399 }
400 /// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000401 bool isInterestingAlloca(AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000402
403 // Check if we have dynamic alloca.
404 bool isDynamicAlloca(AllocaInst &AI) const {
405 return AI.isArrayAllocation() || !AI.isStaticAlloca();
406 }
407
Anna Zaks8ed1d812015-02-27 03:12:36 +0000408 /// If it is an interesting memory access, return the PointerOperand
409 /// and set IsWrite/Alignment. Otherwise return nullptr.
410 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000411 uint64_t *TypeSize, unsigned *Alignment);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000412 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000413 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000414 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000415 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
416 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000417 Value *SizeArgument, bool UseCalls, uint32_t Exp);
418 void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
419 uint32_t TypeSize, bool IsWrite,
420 Value *SizeArgument, bool UseCalls,
421 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000422 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
423 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000424 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000425 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000426 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000427 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000428 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000429 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000430 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000431 bool doInitialization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000432 static char ID; // Pass identification, replacement for typeid
433
Yury Gribov3ae427d2014-12-01 08:47:58 +0000434 DominatorTree &getDominatorTree() const { return *DT; }
435
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000436 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000437 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000438
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000439 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000440 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000441 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
442 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000443
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000444 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000445 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000446 int LongSize;
447 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000448 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000449 DominatorTree *DT;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000450 Function *AsanCtorFunction;
451 Function *AsanInitFunction;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000452 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000453 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000454 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
455 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
456 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
457 // This array is indexed by AccessIsWrite and Experiment.
458 Function *AsanErrorCallbackSized[2][2];
459 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000460 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000461 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000462 GlobalsMetadata GlobalsMD;
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000463 DenseMap<AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000464
465 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000466};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000467
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000468class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000469 public:
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000470 AddressSanitizerModule() : ModulePass(ID) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000471 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000472 static char ID; // Pass identification, replacement for typeid
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000473 const char *getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000474
Kostya Serebryany20a79972012-11-22 03:18:50 +0000475 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000476 void initializeCallbacks(Module &M);
477
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000478 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000479 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000480 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000481 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000482 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000483 return RedzoneSizeForScale(Mapping.Scale);
484 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000485
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000486 GlobalsMetadata GlobalsMD;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000487 Type *IntptrTy;
488 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000489 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000490 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000491 Function *AsanPoisonGlobals;
492 Function *AsanUnpoisonGlobals;
493 Function *AsanRegisterGlobals;
494 Function *AsanUnregisterGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000495};
496
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000497// Stack poisoning does not play well with exception handling.
498// When an exception is thrown, we essentially bypass the code
499// that unpoisones the stack. This is why the run-time library has
500// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
501// stack in the interceptor. This however does not work inside the
502// actual function which catches the exception. Most likely because the
503// compiler hoists the load of the shadow value somewhere too high.
504// This causes asan to report a non-existing bug on 453.povray.
505// It sounds like an LLVM bug.
506struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
507 Function &F;
508 AddressSanitizer &ASan;
509 DIBuilder DIB;
510 LLVMContext *C;
511 Type *IntptrTy;
512 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000513 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000514
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000515 SmallVector<AllocaInst *, 16> AllocaVec;
516 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000517 unsigned StackAlignment;
518
Kostya Serebryany6805de52013-09-10 13:16:56 +0000519 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000520 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000521 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000522 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000523
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000524 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
525 struct AllocaPoisonCall {
526 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000527 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000528 uint64_t Size;
529 bool DoPoison;
530 };
531 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
532
Yury Gribov98b18592015-05-28 07:51:49 +0000533 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
534 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
535 AllocaInst *DynamicAllocaLayout = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000536
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000537 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000538 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000539 AllocaForValueMapTy AllocaForValue;
540
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000541 bool HasNonEmptyInlineAsm;
542 std::unique_ptr<CallInst> EmptyInlineAsm;
543
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000544 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000545 : F(F),
546 ASan(ASan),
547 DIB(*F.getParent(), /*AllowUnresolved*/ false),
548 C(ASan.C),
549 IntptrTy(ASan.IntptrTy),
550 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
551 Mapping(ASan.Mapping),
552 StackAlignment(1 << Mapping.Scale),
553 HasNonEmptyInlineAsm(false),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000554 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000555
556 bool runOnFunction() {
557 if (!ClStack) return false;
558 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000559 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000560
Yury Gribov55441bb2014-11-21 10:29:50 +0000561 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000562
563 initializeCallbacks(*F.getParent());
564
565 poisonStack();
566
567 if (ClDebugStack) {
568 DEBUG(dbgs() << F);
569 }
570 return true;
571 }
572
Yury Gribov55441bb2014-11-21 10:29:50 +0000573 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000574 // poisoned red zones around all of them.
575 // Then unpoison everything back before the function returns.
576 void poisonStack();
577
Yury Gribov98b18592015-05-28 07:51:49 +0000578 void createDynamicAllocasInitStorage();
579
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000580 // ----------------------- Visitors.
581 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000582 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000583
Yury Gribov98b18592015-05-28 07:51:49 +0000584 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
585 Value *SavedStack) {
586 IRBuilder<> IRB(InstBefore);
Yury Gribov781bce22015-05-28 08:03:28 +0000587 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000588 {IRB.CreateLoad(DynamicAllocaLayout),
Yury Gribov781bce22015-05-28 08:03:28 +0000589 IRB.CreatePtrToInt(SavedStack, IntptrTy)});
Yury Gribov98b18592015-05-28 07:51:49 +0000590 }
591
Yury Gribov55441bb2014-11-21 10:29:50 +0000592 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000593 void unpoisonDynamicAllocas() {
594 for (auto &Ret : RetVec)
595 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000596
Yury Gribov98b18592015-05-28 07:51:49 +0000597 for (auto &StackRestoreInst : StackRestoreVec)
598 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
599 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000600 }
601
Yury Gribov55441bb2014-11-21 10:29:50 +0000602 // Deploy and poison redzones around dynamic alloca call. To do this, we
603 // should replace this call with another one with changed parameters and
604 // replace all its uses with new address, so
605 // addr = alloca type, old_size, align
606 // is replaced by
607 // new_size = (old_size + additional_size) * sizeof(type)
608 // tmp = alloca i8, new_size, max(align, 32)
609 // addr = tmp + 32 (first 32 bytes are for the left redzone).
610 // Additional_size is added to make new memory allocation contain not only
611 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000612 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000613
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000614 /// \brief Collect Alloca instructions we want (and can) handle.
615 void visitAllocaInst(AllocaInst &AI) {
Anna Zaks8ed1d812015-02-27 03:12:36 +0000616 if (!ASan.isInterestingAlloca(AI)) return;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000617
618 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Yury Gribov98b18592015-05-28 07:51:49 +0000619 if (ASan.isDynamicAlloca(AI))
620 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000621 else
622 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000623 }
624
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000625 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
626 /// errors.
627 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000628 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000629 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
630 if (!ClCheckLifetime) return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000631 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000632 return;
633 // Found lifetime intrinsic, add ASan instrumentation if necessary.
634 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
635 // If size argument is undefined, don't do anything.
636 if (Size->isMinusOne()) return;
637 // Check that size doesn't saturate uint64_t and can
638 // be stored in IntptrTy.
639 const uint64_t SizeValue = Size->getValue().getLimitedValue();
640 if (SizeValue == ~0ULL ||
641 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
642 return;
643 // Find alloca instruction that corresponds to llvm.lifetime argument.
644 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
645 if (!AI) return;
646 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000647 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000648 AllocaPoisonCallVec.push_back(APC);
649 }
650
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000651 void visitCallInst(CallInst &CI) {
652 HasNonEmptyInlineAsm |=
653 CI.isInlineAsm() && !CI.isIdenticalTo(EmptyInlineAsm.get());
654 }
655
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000656 // ---------------------- Helpers.
657 void initializeCallbacks(Module &M);
658
Yury Gribov3ae427d2014-12-01 08:47:58 +0000659 bool doesDominateAllExits(const Instruction *I) const {
660 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000661 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000662 }
663 return true;
664 }
665
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000666 /// Finds alloca where the value comes from.
667 AllocaInst *findAllocaForValue(Value *V);
Craig Topper3af97222014-08-27 05:25:00 +0000668 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000669 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000670 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000671
672 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
673 int Size);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000674 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
675 bool Dynamic);
676 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
677 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000678};
679
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000680} // namespace
681
682char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000683INITIALIZE_PASS_BEGIN(
684 AddressSanitizer, "asan",
685 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
686 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000687INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000688INITIALIZE_PASS_END(
689 AddressSanitizer, "asan",
690 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
691 false)
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000692FunctionPass *llvm::createAddressSanitizerFunctionPass() {
693 return new AddressSanitizer();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000694}
695
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000696char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000697INITIALIZE_PASS(
698 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000699 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000700 "ModulePass",
701 false, false)
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000702ModulePass *llvm::createAddressSanitizerModulePass() {
703 return new AddressSanitizerModule();
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000704}
705
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000706static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000707 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000708 assert(Res < kNumberOfAccessSizes);
709 return Res;
710}
711
Bill Wendling58f8cef2013-08-06 22:52:42 +0000712// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000713static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
714 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000715 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000716 // We use private linkage for module-local strings. If they can be merged
717 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000718 GlobalVariable *GV =
719 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000720 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000721 if (AllowMerging) GV->setUnnamedAddr(true);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000722 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
723 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000724}
725
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000726/// \brief Create a global describing a source location.
727static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
728 LocationMetadata MD) {
729 Constant *LocData[] = {
730 createPrivateGlobalForString(M, MD.Filename, true),
731 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
732 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
733 };
734 auto LocStruct = ConstantStruct::getAnon(LocData);
735 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
736 GlobalValue::PrivateLinkage, LocStruct,
737 kAsanGenPrefix);
738 GV->setUnnamedAddr(true);
739 return GV;
740}
741
Kostya Serebryany139a9372012-11-20 14:16:08 +0000742static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000743 return G->getName().find(kAsanGenPrefix) == 0 ||
744 G->getName().find(kSanCovGenPrefix) == 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000745}
746
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000747Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
748 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000749 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000750 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000751 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000752 if (Mapping.OrShadowOffset)
753 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
754 else
755 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000756}
757
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000758// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000759void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
760 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000761 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000762 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000763 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +0000764 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
765 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
766 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000767 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000768 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000769 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +0000770 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
771 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
772 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000773 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000774 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000775}
776
Anna Zaks8ed1d812015-02-27 03:12:36 +0000777/// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000778bool AddressSanitizer::isInterestingAlloca(AllocaInst &AI) {
779 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
780
781 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
782 return PreviouslySeenAllocaInfo->getSecond();
783
Yury Gribov98b18592015-05-28 07:51:49 +0000784 bool IsInteresting =
785 (AI.getAllocatedType()->isSized() &&
786 // alloca() may be called with 0 size, ignore it.
787 getAllocaSizeInBytes(&AI) > 0 &&
788 // We are only interested in allocas not promotable to registers.
789 // Promotable allocas are common under -O0.
790 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI) ||
791 isDynamicAlloca(AI)));
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000792
793 ProcessedAllocas[&AI] = IsInteresting;
794 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000795}
796
797/// If I is an interesting memory access, return the PointerOperand
798/// and set IsWrite/Alignment. Otherwise return nullptr.
799Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
800 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000801 uint64_t *TypeSize,
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000802 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000803 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000804 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000805
806 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000807 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000808 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000809 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000810 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000811 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000812 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000813 PtrOperand = LI->getPointerOperand();
814 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000815 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000816 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000817 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000818 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000819 PtrOperand = SI->getPointerOperand();
820 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000821 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000822 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000823 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000824 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000825 PtrOperand = RMW->getPointerOperand();
826 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000827 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000828 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000829 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000830 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000831 PtrOperand = XCHG->getPointerOperand();
Kostya Serebryany90241602012-05-30 09:04:06 +0000832 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000833
834 // Treat memory accesses to promotable allocas as non-interesting since they
835 // will not cause memory violations. This greatly speeds up the instrumented
836 // executable at -O0.
837 if (ClSkipPromotableAllocas)
838 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
839 return isInterestingAlloca(*AI) ? AI : nullptr;
840
841 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000842}
843
Kostya Serebryany796f6552014-02-27 12:45:36 +0000844static bool isPointerOperand(Value *V) {
845 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
846}
847
848// This is a rough heuristic; it may cause both false positives and
849// false negatives. The proper implementation requires cooperation with
850// the frontend.
851static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
852 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000853 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000854 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000855 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000856 } else {
857 return false;
858 }
859 if (!isPointerOperand(I->getOperand(0)) ||
860 !isPointerOperand(I->getOperand(1)))
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000861 return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000862 return true;
863}
864
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000865bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
866 // If a global variable does not have dynamic initialization we don't
867 // have to instrument it. However, if a global does not have initializer
868 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000869 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000870}
871
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000872void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
873 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +0000874 IRBuilder<> IRB(I);
875 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
876 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
877 for (int i = 0; i < 2; i++) {
878 if (Param[i]->getType()->isPointerTy())
879 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
880 }
David Blaikieff6409d2015-05-18 22:13:54 +0000881 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000882}
883
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000884void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000885 Instruction *I, bool UseCalls,
886 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +0000887 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000888 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000889 uint64_t TypeSize = 0;
890 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +0000891 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000892
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000893 // Optimization experiments.
894 // The experiments can be used to evaluate potential optimizations that remove
895 // instrumentation (assess false negatives). Instead of completely removing
896 // some instrumentation, you set Exp to a non-zero value (mask of optimization
897 // experiments that want to remove instrumentation of this instruction).
898 // If Exp is non-zero, this pass will emit special calls into runtime
899 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
900 // make runtime terminate the program in a special way (with a different
901 // exit status). Then you run the new compiler on a buggy corpus, collect
902 // the special terminations (ideally, you don't see them at all -- no false
903 // negatives) and make the decision on the optimization.
904 uint32_t Exp = ClForceExperiment;
905
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000906 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000907 // If initialization order checking is disabled, a simple access to a
908 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000909 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000910 if (G != NULL && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
911 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
912 NumOptimizedAccessesToGlobalVar++;
913 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000914 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000915 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000916
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000917 if (ClOpt && ClOptStack) {
918 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000919 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000920 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
921 NumOptimizedAccessesToStackVar++;
922 return;
923 }
924 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000925
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000926 if (IsWrite)
927 NumInstrumentedWrites++;
928 else
929 NumInstrumentedReads++;
930
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000931 unsigned Granularity = 1 << Mapping.Scale;
932 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
933 // if the data is properly aligned.
934 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
935 TypeSize == 128) &&
936 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000937 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
938 Exp);
939 instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
940 UseCalls, Exp);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000941}
942
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000943Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
944 Value *Addr, bool IsWrite,
945 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000946 Value *SizeArgument,
947 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000948 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000949 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
950 CallInst *Call = nullptr;
951 if (SizeArgument) {
952 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +0000953 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
954 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000955 else
David Blaikieff6409d2015-05-18 22:13:54 +0000956 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
957 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000958 } else {
959 if (Exp == 0)
960 Call =
961 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
962 else
David Blaikieff6409d2015-05-18 22:13:54 +0000963 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
964 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000965 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000966
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000967 // We don't do Call->setDoesNotReturn() because the BB already has
968 // UnreachableInst at the end.
969 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +0000970 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +0000971 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000972}
973
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000974Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000975 Value *ShadowValue,
976 uint32_t TypeSize) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000977 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +0000978 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000979 Value *LastAccessedByte =
980 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000981 // (Addr & (Granularity - 1)) + size - 1
982 if (TypeSize / 8 > 1)
983 LastAccessedByte = IRB.CreateAdd(
984 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
985 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000986 LastAccessedByte =
987 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000988 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
989 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
990}
991
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000992void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000993 Instruction *InsertBefore, Value *Addr,
994 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000995 Value *SizeArgument, bool UseCalls,
996 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000997 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000998 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000999 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1000
1001 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001002 if (Exp == 0)
1003 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1004 AddrLong);
1005 else
David Blaikieff6409d2015-05-18 22:13:54 +00001006 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1007 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001008 return;
1009 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001010
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001011 Type *ShadowTy =
1012 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001013 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1014 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1015 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001016 Value *ShadowValue =
1017 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001018
1019 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Alexey Samsonov1345d352013-01-16 13:23:28 +00001020 size_t Granularity = 1 << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001021 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001022
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001023 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001024 // We use branch weights for the slow path check, to indicate that the slow
1025 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001026 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1027 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001028 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001029 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001030 IRB.SetInsertPoint(CheckTerm);
1031 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001032 BasicBlock *CrashBlock =
1033 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001034 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001035 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1036 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001037 } else {
Evgeniy Stepanova9164e92013-12-19 13:29:56 +00001038 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001039 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001040
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001041 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001042 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001043 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001044}
1045
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001046// Instrument unusual size or unusual alignment.
1047// We can not do it with a single check, so we do 1-byte check for the first
1048// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1049// to report the actual access size.
1050void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1051 Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1052 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1053 IRBuilder<> IRB(I);
1054 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1055 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1056 if (UseCalls) {
1057 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001058 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1059 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001060 else
David Blaikieff6409d2015-05-18 22:13:54 +00001061 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1062 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001063 } else {
1064 Value *LastByte = IRB.CreateIntToPtr(
1065 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1066 Addr->getType());
1067 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1068 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1069 }
1070}
1071
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001072void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1073 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001074 // Set up the arguments to our poison/unpoison functions.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001075 IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001076
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001077 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001078 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1079 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001080
1081 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001082 for (auto &BB : GlobalInit.getBasicBlockList())
1083 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001084 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001085}
1086
1087void AddressSanitizerModule::createInitializerPoisonCalls(
1088 Module &M, GlobalValue *ModuleName) {
1089 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1090
1091 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1092 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001093 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001094 ConstantStruct *CS = cast<ConstantStruct>(OP);
1095
1096 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001097 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001098 if (F->getName() == kAsanModuleCtorName) continue;
1099 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1100 // Don't instrument CTORs that will run before asan.module_ctor.
1101 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1102 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001103 }
1104 }
1105}
1106
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001107bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001108 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001109 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001110
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001111 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001112 if (!Ty->isSized()) return false;
1113 if (!G->hasInitializer()) return false;
Kostya Serebryany139a9372012-11-20 14:16:08 +00001114 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001115 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001116 // Don't handle ODR linkage types and COMDATs since other modules may be built
1117 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001118 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1119 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1120 G->getLinkage() != GlobalVariable::InternalLinkage)
1121 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001122 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001123 // Two problems with thread-locals:
1124 // - The address of the main thread's copy can't be computed at link-time.
1125 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001126 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001127 // For now, just ignore this Global if the alignment is large.
1128 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001129
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001130 if (G->hasSection()) {
1131 StringRef Section(G->getSection());
Kuba Brecka086e34b2014-12-05 21:32:46 +00001132
Anna Zaks11904602015-06-09 00:58:08 +00001133 // Globals from llvm.metadata aren't emitted, do not instrument them.
1134 if (Section == "llvm.metadata") return false;
1135
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
Kuba Brecka1001bb52014-12-05 22:19:18 +00001145 if (TargetTriple.isOSBinFormatMachO()) {
1146 StringRef ParsedSegment, ParsedSection;
1147 unsigned TAA = 0, StubSize = 0;
1148 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001149 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1150 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001151 if (!ErrorCode.empty()) {
Anna Zaks11904602015-06-09 00:58:08 +00001152 assert(false && "Invalid section specifier.");
1153 return false;
Kuba Brecka1001bb52014-12-05 22:19:18 +00001154 }
1155
1156 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1157 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1158 // them.
1159 if (ParsedSegment == "__OBJC" ||
1160 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1161 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1162 return false;
1163 }
1164 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1165 // Constant CFString instances are compiled in the following way:
1166 // -- the string buffer is emitted into
1167 // __TEXT,__cstring,cstring_literals
1168 // -- the constant NSConstantString structure referencing that buffer
1169 // is placed into __DATA,__cfstring
1170 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1171 // Moreover, it causes the linker to crash on OS X 10.7
1172 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1173 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1174 return false;
1175 }
1176 // The linker merges the contents of cstring_literals and removes the
1177 // trailing zeroes.
1178 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1179 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1180 return false;
1181 }
1182 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001183 }
1184
1185 return true;
1186}
1187
Alexey Samsonov788381b2012-12-25 12:28:20 +00001188void AddressSanitizerModule::initializeCallbacks(Module &M) {
1189 IRBuilder<> IRB(*C);
1190 // Declare our poisoning and unpoisoning functions.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001191 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001192 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001193 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001194 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001195 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001196 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1197 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001198 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001199 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001200 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001201 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001202 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1203 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001204 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1205}
1206
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001207// This function replaces all global variables with new variables that have
1208// trailing redzones. It also creates a function that poisons
1209// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001210bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001211 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001212
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001213 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1214
Alexey Samsonova02e6642014-05-29 18:40:48 +00001215 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001216 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001217 }
1218
1219 size_t n = GlobalsToChange.size();
1220 if (n == 0) return false;
1221
1222 // A global is described by a structure
1223 // size_t beg;
1224 // size_t size;
1225 // size_t size_with_redzone;
1226 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001227 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001228 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001229 // void *source_location;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001230 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001231 StructType *GlobalStructTy =
1232 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001233 IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001234 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001235
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001236 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001237
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001238 // We shouldn't merge same module names, as this string serves as unique
1239 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001240 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001241 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001242
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001243 auto &DL = M.getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001244 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001245 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001246 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001247
1248 auto MD = GlobalsMD.get(G);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001249 // Create string holding the global name (use global name from metadata
1250 // if it's available, otherwise just write the name of global variable).
1251 GlobalVariable *Name = createPrivateGlobalForString(
1252 M, MD.Name.empty() ? G->getName() : MD.Name,
1253 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001254
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001255 PointerType *PtrTy = cast<PointerType>(G->getType());
1256 Type *Ty = PtrTy->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001257 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001258 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001259 // MinRZ <= RZ <= kMaxGlobalRedzone
1260 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001261 uint64_t RZ = std::max(
1262 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001263 uint64_t RightRedzoneSize = RZ;
1264 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001265 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001266 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001267 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1268
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001269 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001270 Constant *NewInitializer =
1271 ConstantStruct::get(NewTy, G->getInitializer(),
1272 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001273
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001274 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001275 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1276 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1277 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001278 GlobalVariable *NewGlobal =
1279 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1280 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001281 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001282 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001283
1284 Value *Indices2[2];
1285 Indices2[0] = IRB.getInt32(0);
1286 Indices2[1] = IRB.getInt32(0);
1287
1288 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001289 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001290 NewGlobal->takeName(G);
1291 G->eraseFromParent();
1292
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001293 Constant *SourceLoc;
1294 if (!MD.SourceLoc.empty()) {
1295 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1296 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1297 } else {
1298 SourceLoc = ConstantInt::get(IntptrTy, 0);
1299 }
1300
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001301 Initializers[i] = ConstantStruct::get(
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001302 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001303 ConstantInt::get(IntptrTy, SizeInBytes),
1304 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1305 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001306 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001307 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001308
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001309 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001310
Kostya Serebryany20343352012-10-17 13:40:06 +00001311 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001312 }
1313
1314 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1315 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001316 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001317 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1318
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001319 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001320 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001321 createInitializerPoisonCalls(M, ModuleName);
David Blaikieff6409d2015-05-18 22:13:54 +00001322 IRB.CreateCall(AsanRegisterGlobals,
1323 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1324 ConstantInt::get(IntptrTy, n)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001325
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001326 // We also need to unregister globals at the end, e.g. when a shared library
1327 // gets closed.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001328 Function *AsanDtorFunction =
1329 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1330 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001331 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1332 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
David Blaikieff6409d2015-05-18 22:13:54 +00001333 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1334 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1335 ConstantInt::get(IntptrTy, n)});
Alexey Samsonov1f647502014-05-29 01:10:14 +00001336 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001337
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001338 DEBUG(dbgs() << M);
1339 return true;
1340}
1341
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001342bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001343 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001344 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001345 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001346 TargetTriple = Triple(M.getTargetTriple());
1347 Mapping = getShadowMapping(TargetTriple, LongSize);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001348 initializeCallbacks(M);
1349
1350 bool Changed = false;
1351
1352 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1353 assert(CtorFunc);
1354 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1355
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001356 if (ClGlobals) Changed |= InstrumentGlobals(IRB, M);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001357
1358 return Changed;
1359}
1360
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001361void AddressSanitizer::initializeCallbacks(Module &M) {
1362 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001363 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001364 // IsWrite, TypeSize and Exp are encoded in the function name.
1365 for (int Exp = 0; Exp < 2; Exp++) {
1366 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1367 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1368 const std::string ExpStr = Exp ? "exp_" : "";
1369 const Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
1370 AsanErrorCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001371 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001372 kAsanReportErrorTemplate + ExpStr + TypeStr + "_n",
1373 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1374 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001375 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001376 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N",
1377 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1378 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1379 AccessSizeIndex++) {
1380 const std::string Suffix = TypeStr + itostr(1 << AccessSizeIndex);
1381 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001382 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001383 kAsanReportErrorTemplate + ExpStr + Suffix, IRB.getVoidTy(),
1384 IntptrTy, ExpType, nullptr));
1385 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001386 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001387 ClMemoryAccessCallbackPrefix + ExpStr + Suffix, IRB.getVoidTy(),
1388 IntptrTy, ExpType, nullptr));
1389 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001390 }
1391 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00001392
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001393 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001394 ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001395 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001396 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001397 ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001398 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001399 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001400 ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001401 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001402
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001403 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001404 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001405
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001406 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001407 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001408 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001409 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001410 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1411 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1412 StringRef(""), StringRef(""),
1413 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001414}
1415
1416// virtual
1417bool AddressSanitizer::doInitialization(Module &M) {
1418 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001419
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001420 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001421
1422 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001423 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001424 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001425 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001426
Ismail Pazarbasi09c37092015-05-07 21:40:46 +00001427 std::tie(AsanCtorFunction, AsanInitFunction) =
1428 createSanitizerCtorAndInitFunctions(M, kAsanModuleCtorName, kAsanInitName,
1429 /*InitArgTypes=*/{},
1430 /*InitArgs=*/{});
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001431
Kuba Brecka1001bb52014-12-05 22:19:18 +00001432 Mapping = getShadowMapping(TargetTriple, LongSize);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001433
Alexey Samsonov1f647502014-05-29 01:10:14 +00001434 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001435 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001436}
1437
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001438bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1439 // For each NSObject descendant having a +load method, this method is invoked
1440 // by the ObjC runtime before any of the static constructors is called.
1441 // Therefore we need to instrument such methods with a call to __asan_init
1442 // at the beginning in order to initialize our runtime before any access to
1443 // the shadow memory.
1444 // We cannot just ignore these methods, because they may call other
1445 // instrumented functions.
1446 if (F.getName().find(" load]") != std::string::npos) {
1447 IRBuilder<> IRB(F.begin()->begin());
David Blaikieff6409d2015-05-18 22:13:54 +00001448 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001449 return true;
1450 }
1451 return false;
1452}
1453
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001454bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001455 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001456 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001457 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001458 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001459
Yury Gribov3ae427d2014-12-01 08:47:58 +00001460 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1461
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001462 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001463 maybeInsertAsanInitAtFunctionEntry(F);
1464
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001465 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001466
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001467 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001468
1469 // We want to instrument every address only once per basic block (unless there
1470 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001471 SmallSet<Value *, 16> TempsToInstrument;
1472 SmallVector<Instruction *, 16> ToInstrument;
1473 SmallVector<Instruction *, 8> NoReturnCalls;
1474 SmallVector<BasicBlock *, 16> AllBlocks;
1475 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001476 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001477 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001478 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001479 uint64_t TypeSize;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001480
1481 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001482 for (auto &BB : F) {
1483 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001484 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001485 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001486 for (auto &Inst : BB) {
1487 if (LooksLikeCodeInBug11395(&Inst)) return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001488 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1489 &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001490 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001491 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001492 continue; // We've seen this temp in the current BB.
1493 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001494 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001495 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1496 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001497 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001498 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001499 // ok, take it.
1500 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001501 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001502 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001503 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001504 // A call inside BB.
1505 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001506 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001507 }
1508 continue;
1509 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001510 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001511 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001512 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001513 }
1514 }
1515
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001516 bool UseCalls = false;
1517 if (ClInstrumentationWithCallsThreshold >= 0 &&
1518 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1519 UseCalls = true;
1520
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001521 const TargetLibraryInfo *TLI =
1522 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001523 const DataLayout &DL = F.getParent()->getDataLayout();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001524 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1525 /*RoundToAlign=*/true);
1526
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001527 // Instrument.
1528 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001529 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001530 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1531 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001532 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001533 instrumentMop(ObjSizeVis, Inst, UseCalls,
1534 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001535 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001536 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001537 }
1538 NumInstrumented++;
1539 }
1540
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001541 FunctionStackPoisoner FSP(F, *this);
1542 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001543
1544 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1545 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001546 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001547 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00001548 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001549 }
1550
Alexey Samsonova02e6642014-05-29 18:40:48 +00001551 for (auto Inst : PointerComparisonsOrSubtracts) {
1552 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001553 NumInstrumented++;
1554 }
1555
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001556 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001557
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001558 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1559
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001560 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001561}
1562
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001563// Workaround for bug 11395: we don't want to instrument stack in functions
1564// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1565// FIXME: remove once the bug 11395 is fixed.
1566bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1567 if (LongSize != 32) return false;
1568 CallInst *CI = dyn_cast<CallInst>(I);
1569 if (!CI || !CI->isInlineAsm()) return false;
1570 if (CI->getNumArgOperands() <= 5) return false;
1571 // We have inline assembly with quite a few arguments.
1572 return true;
1573}
1574
1575void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1576 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001577 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1578 std::string Suffix = itostr(i);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001579 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1580 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1581 IntptrTy, nullptr));
1582 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001583 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1584 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001585 }
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001586 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
David Blaikiea92765c2014-11-14 00:41:42 +00001587 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1588 IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001589 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
David Blaikiea92765c2014-11-14 00:41:42 +00001590 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1591 IntptrTy, IntptrTy, nullptr));
Yury Gribov98b18592015-05-28 07:51:49 +00001592 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1593 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1594 AsanAllocasUnpoisonFunc =
1595 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1596 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001597}
1598
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001599void FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1600 IRBuilder<> &IRB, Value *ShadowBase,
1601 bool DoPoison) {
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001602 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001603 size_t i = 0;
1604 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1605 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1606 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1607 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1608 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1609 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1610 uint64_t Val = 0;
1611 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001612 if (F.getParent()->getDataLayout().isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001613 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1614 else
1615 Val = (Val << 8) | ShadowBytes[i + j];
1616 }
1617 if (!Val) continue;
1618 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1619 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1620 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1621 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001622 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001623 }
1624}
1625
Kostya Serebryany6805de52013-09-10 13:16:56 +00001626// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1627// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1628static int StackMallocSizeClass(uint64_t LocalStackSize) {
1629 assert(LocalStackSize <= kMaxStackMallocSize);
1630 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001631 for (int i = 0;; i++, MaxSize *= 2)
1632 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00001633 llvm_unreachable("impossible LocalStackSize");
1634}
1635
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001636// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1637// We can not use MemSet intrinsic because it may end up calling the actual
1638// memset. Size is a multiple of 8.
1639// Currently this generates 8-byte stores on x86_64; it may be better to
1640// generate wider stores.
1641void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1642 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1643 assert(!(Size % 8));
Gabor Horvathfee04342015-03-16 09:53:42 +00001644
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001645 // kAsanStackAfterReturnMagic is 0xf5.
1646 const uint64_t kAsanStackAfterReturnMagic64 = 0xf5f5f5f5f5f5f5f5ULL;
Gabor Horvathfee04342015-03-16 09:53:42 +00001647
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001648 for (int i = 0; i < Size; i += 8) {
1649 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001650 IRB.CreateStore(
1651 ConstantInt::get(IRB.getInt64Ty(), kAsanStackAfterReturnMagic64),
1652 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001653 }
1654}
1655
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001656static DebugLoc getFunctionEntryDebugLocation(Function &F) {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001657 for (const auto &Inst : F.getEntryBlock())
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001658 if (!isa<AllocaInst>(Inst)) return Inst.getDebugLoc();
Alexey Samsonova02e6642014-05-29 18:40:48 +00001659 return DebugLoc();
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001660}
1661
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001662PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1663 Value *ValueIfTrue,
1664 Instruction *ThenTerm,
1665 Value *ValueIfFalse) {
1666 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1667 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1668 PHI->addIncoming(ValueIfFalse, CondBlock);
1669 BasicBlock *ThenBlock = ThenTerm->getParent();
1670 PHI->addIncoming(ValueIfTrue, ThenBlock);
1671 return PHI;
1672}
1673
1674Value *FunctionStackPoisoner::createAllocaForLayout(
1675 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
1676 AllocaInst *Alloca;
1677 if (Dynamic) {
1678 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
1679 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
1680 "MyAlloca");
1681 } else {
1682 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
1683 nullptr, "MyAlloca");
1684 assert(Alloca->isStaticAlloca());
1685 }
1686 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1687 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1688 Alloca->setAlignment(FrameAlignment);
1689 return IRB.CreatePointerCast(Alloca, IntptrTy);
1690}
1691
Yury Gribov98b18592015-05-28 07:51:49 +00001692void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
1693 BasicBlock &FirstBB = *F.begin();
1694 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
1695 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
1696 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
1697 DynamicAllocaLayout->setAlignment(32);
1698}
1699
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001700void FunctionStackPoisoner::poisonStack() {
Yury Gribov55441bb2014-11-21 10:29:50 +00001701 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1702
Yury Gribov98b18592015-05-28 07:51:49 +00001703 if (ClInstrumentAllocas && DynamicAllocaVec.size() > 0) {
Yury Gribov55441bb2014-11-21 10:29:50 +00001704 // Handle dynamic allocas.
Yury Gribov98b18592015-05-28 07:51:49 +00001705 createDynamicAllocasInitStorage();
Alexander Potapenkof90556e2015-06-12 11:27:06 +00001706 for (auto &AI : DynamicAllocaVec) handleDynamicAllocaCall(AI);
Yury Gribov98b18592015-05-28 07:51:49 +00001707
1708 unpoisonDynamicAllocas();
Kuba Breckaf5875d32015-02-24 09:47:05 +00001709 }
Yury Gribov55441bb2014-11-21 10:29:50 +00001710
1711 if (AllocaVec.size() == 0) return;
1712
Kostya Serebryany6805de52013-09-10 13:16:56 +00001713 int StackMallocIdx = -1;
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001714 DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001715
1716 Instruction *InsBefore = AllocaVec[0];
1717 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001718 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001719
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001720 SmallVector<ASanStackVariableDescription, 16> SVD;
1721 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00001722 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001723 ASanStackVariableDescription D = {AI->getName().data(),
1724 ASan.getAllocaSizeInBytes(AI),
1725 AI->getAlignment(), AI, 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001726 SVD.push_back(D);
1727 }
1728 // Minimal header size (left redzone) is 4 pointers,
1729 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1730 size_t MinHeaderSize = ASan.LongSize / 2;
1731 ASanStackFrameLayout L;
1732 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1733 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1734 uint64_t LocalStackSize = L.FrameSize;
1735 bool DoStackMalloc =
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001736 ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
Reid Kleckner92b9c6e2015-04-02 21:44:55 +00001737 // Don't do dynamic alloca in presence of inline asm: too often it makes
1738 // assumptions on which registers are available. Don't do stack malloc in the
1739 // presence of inline asm on 32-bit platforms for the same reason.
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001740 bool DoDynamicAlloca = ClDynamicAllocaStack && !HasNonEmptyInlineAsm;
Reid Kleckner92b9c6e2015-04-02 21:44:55 +00001741 DoStackMalloc &= !HasNonEmptyInlineAsm || ASan.LongSize != 32;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001742
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001743 Value *StaticAlloca =
1744 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
1745
1746 Value *FakeStack;
1747 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001748
1749 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001750 // void *FakeStack = __asan_option_detect_stack_use_after_return
1751 // ? __asan_stack_malloc_N(LocalStackSize)
1752 // : nullptr;
1753 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001754 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1755 kAsanOptionDetectUAR, IRB.getInt32Ty());
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001756 Value *UARIsEnabled =
1757 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1758 Constant::getNullValue(IRB.getInt32Ty()));
1759 Instruction *Term =
1760 SplitBlockAndInsertIfThen(UARIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001761 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001762 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001763 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1764 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1765 Value *FakeStackValue =
1766 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
1767 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001768 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001769 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001770 FakeStack = createPHI(IRB, UARIsEnabled, FakeStackValue, Term,
1771 ConstantInt::get(IntptrTy, 0));
1772
1773 Value *NoFakeStack =
1774 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
1775 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
1776 IRBIf.SetInsertPoint(Term);
1777 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1778 Value *AllocaValue =
1779 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
1780 IRB.SetInsertPoint(InsBefore);
1781 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1782 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
1783 } else {
1784 // void *FakeStack = nullptr;
1785 // void *LocalStackBase = alloca(LocalStackSize);
1786 FakeStack = ConstantInt::get(IntptrTy, 0);
1787 LocalStackBase =
1788 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001789 }
1790
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001791 // Insert poison calls for lifetime intrinsics for alloca.
1792 bool HavePoisonedAllocas = false;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001793 for (const auto &APC : AllocaPoisonCallVec) {
Alexey Samsonova788b942013-11-18 14:53:55 +00001794 assert(APC.InsBefore);
1795 assert(APC.AI);
1796 IRBuilder<> IRB(APC.InsBefore);
1797 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001798 HavePoisonedAllocas |= APC.DoPoison;
1799 }
1800
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001801 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001802 for (const auto &Desc : SVD) {
1803 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00001804 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00001805 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001806 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00001807 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001808 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001809 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001810
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001811 // The left-most redzone has enough space for at least 4 pointers.
1812 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001813 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1814 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1815 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001816 // Write the frame description constant to redzone[1].
1817 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001818 IRB.CreateAdd(LocalStackBase,
1819 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
1820 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00001821 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001822 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001823 /*AllowMerging*/ true);
1824 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001825 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001826 // Write the PC to redzone[2].
1827 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001828 IRB.CreateAdd(LocalStackBase,
1829 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
1830 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001831 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001832
1833 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001834 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001835 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001836
Kostya Serebryany530e2072013-12-23 14:15:08 +00001837 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001838 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001839 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001840 // Mark the current frame as retired.
1841 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1842 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001843 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001844 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001845 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00001846 // // In use-after-return mode, poison the whole stack frame.
1847 // if StackMallocIdx <= 4
1848 // // For small sizes inline the whole thing:
1849 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001850 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00001851 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001852 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00001853 // else
1854 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001855 Value *Cmp =
1856 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00001857 TerminatorInst *ThenTerm, *ElseTerm;
1858 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1859
1860 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001861 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001862 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1863 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1864 ClassSize >> Mapping.Scale);
1865 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001866 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001867 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1868 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1869 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1870 IRBPoison.CreateStore(
1871 Constant::getNullValue(IRBPoison.getInt8Ty()),
1872 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1873 } else {
1874 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00001875 IRBPoison.CreateCall(
1876 AsanStackFreeFunc[StackMallocIdx],
1877 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001878 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00001879
1880 IRBuilder<> IRBElse(ElseTerm);
1881 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001882 } else if (HavePoisonedAllocas) {
1883 // If we poisoned some allocas in llvm.lifetime analysis,
1884 // unpoison whole stack frame now.
Alexey Samsonov261177a2012-12-04 01:34:23 +00001885 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001886 } else {
1887 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001888 }
1889 }
1890
Kostya Serebryany09959942012-10-19 06:20:53 +00001891 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001892 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001893}
Alexey Samsonov261177a2012-12-04 01:34:23 +00001894
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001895void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00001896 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00001897 // For now just insert the call to ASan runtime.
1898 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1899 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00001900 IRB.CreateCall(
1901 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
1902 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00001903}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001904
1905// Handling llvm.lifetime intrinsics for a given %alloca:
1906// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1907// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1908// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1909// could be poisoned by previous llvm.lifetime.end instruction, as the
1910// variable may go in and out of scope several times, e.g. in loops).
1911// (3) if we poisoned at least one %alloca in a function,
1912// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001913
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001914AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1915 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1916 // We're intested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00001917 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001918 // See if we've already calculated (or started to calculate) alloca for a
1919 // given value.
1920 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001921 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001922 // Store 0 while we're calculating alloca for value V to avoid
1923 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00001924 AllocaForValue[V] = nullptr;
1925 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001926 if (CastInst *CI = dyn_cast<CastInst>(V))
1927 Res = findAllocaForValue(CI->getOperand(0));
1928 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00001929 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001930 // Allow self-referencing phi-nodes.
1931 if (IncValue == PN) continue;
1932 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1933 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00001934 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1935 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001936 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001937 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001938 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001939 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001940 return Res;
1941}
Yury Gribov55441bb2014-11-21 10:29:50 +00001942
Yury Gribov98b18592015-05-28 07:51:49 +00001943void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00001944 IRBuilder<> IRB(AI);
1945
Yury Gribov55441bb2014-11-21 10:29:50 +00001946 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
1947 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
1948
1949 Value *Zero = Constant::getNullValue(IntptrTy);
1950 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
1951 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00001952
1953 // Since we need to extend alloca with additional memory to locate
1954 // redzones, and OldSize is number of allocated blocks with
1955 // ElementSize size, get allocated memory size in bytes by
1956 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00001957 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001958 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00001959 Value *OldSize =
1960 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
1961 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00001962
1963 // PartialSize = OldSize % 32
1964 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
1965
1966 // Misalign = kAllocaRzSize - PartialSize;
1967 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
1968
1969 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
1970 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
1971 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
1972
1973 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
1974 // Align is added to locate left redzone, PartialPadding for possible
1975 // partial redzone and kAllocaRzSize for right redzone respectively.
1976 Value *AdditionalChunkSize = IRB.CreateAdd(
1977 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
1978
1979 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
1980
1981 // Insert new alloca with new NewSize and Align params.
1982 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
1983 NewAlloca->setAlignment(Align);
1984
1985 // NewAddress = Address + Align
1986 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
1987 ConstantInt::get(IntptrTy, Align));
1988
Yury Gribov98b18592015-05-28 07:51:49 +00001989 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00001990 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00001991
1992 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
1993 // for unpoisoning stuff.
1994 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
1995
Yury Gribov55441bb2014-11-21 10:29:50 +00001996 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
1997
Yury Gribov98b18592015-05-28 07:51:49 +00001998 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00001999 AI->replaceAllUsesWith(NewAddressPtr);
2000
Yury Gribov98b18592015-05-28 07:51:49 +00002001 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00002002 AI->eraseFromParent();
2003}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002004
2005// isSafeAccess returns true if Addr is always inbounds with respect to its
2006// base object. For example, it is a field access or an array access with
2007// constant inbounds index.
2008bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2009 Value *Addr, uint64_t TypeSize) const {
2010 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2011 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00002012 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002013 int64_t Offset = SizeOffset.second.getSExtValue();
2014 // Three checks are required to ensure safety:
2015 // . Offset >= 0 (since the offset is given from the base ptr)
2016 // . Size >= Offset (unsigned)
2017 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00002018 return Offset >= 0 && Size >= uint64_t(Offset) &&
2019 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002020}