blob: 9bfd7212f769317c15f2d916608a216ba2140328 [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"
Kuba Brecka8ec94ea2015-07-22 10:25:38 +000021#include "llvm/ADT/SetVector.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000022#include "llvm/ADT/SmallSet.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/SmallVector.h"
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +000025#include "llvm/ADT/Statistic.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000026#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov617232f2012-05-23 11:52:12 +000027#include "llvm/ADT/Triple.h"
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000028#include "llvm/Analysis/MemoryBuiltins.h"
29#include "llvm/Analysis/TargetLibraryInfo.h"
30#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000031#include "llvm/IR/CallSite.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000032#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/DataLayout.h"
Yury Gribov3ae427d2014-12-01 08:47:58 +000034#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Function.h"
36#include "llvm/IR/IRBuilder.h"
37#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000038#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/IntrinsicInst.h"
40#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000041#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000042#include "llvm/IR/Module.h"
43#include "llvm/IR/Type.h"
Kuba Brecka1001bb52014-12-05 22:19:18 +000044#include "llvm/MC/MCSectionMachO.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000045#include "llvm/Support/CommandLine.h"
46#include "llvm/Support/DataTypes.h"
47#include "llvm/Support/Debug.h"
Kostya Serebryany9e62b302013-06-03 14:46:56 +000048#include "llvm/Support/Endian.h"
Yury Gribov55441bb2014-11-21 10:29:50 +000049#include "llvm/Support/SwapByteOrder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000050#include "llvm/Support/raw_ostream.h"
Kostya Serebryany351b0782014-09-03 22:37:37 +000051#include "llvm/Transforms/Scalar.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000052#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000053#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany9f5213f2013-06-26 09:18:17 +000054#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000055#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000056#include "llvm/Transforms/Utils/ModuleUtils.h"
Anna Zaks8ed1d812015-02-27 03:12:36 +000057#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000058#include <algorithm>
Chandler Carruthed0881b2012-12-03 16:50:05 +000059#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000060#include <system_error>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000061
62using namespace llvm;
63
Chandler Carruth964daaa2014-04-22 02:55:47 +000064#define DEBUG_TYPE "asan"
65
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000066static const uint64_t kDefaultShadowScale = 3;
67static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +000068static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000069static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000070static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +000071static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
Kostya Serebryany4766fe62013-01-23 12:54:55 +000072static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +000073static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +000074static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +000075static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000076static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
77static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +000078static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000079
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000080static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000081static const size_t kMaxStackMallocSize = 1 << 16; // 64K
82static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
83static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
84
Craig Topperd3a34f82013-07-16 01:17:10 +000085static const char *const kAsanModuleCtorName = "asan.module_ctor";
86static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000087static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000088static const char *const kAsanReportErrorTemplate = "__asan_report_";
Craig Topperd3a34f82013-07-16 01:17:10 +000089static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000090static const char *const kAsanUnregisterGlobalsName =
91 "__asan_unregister_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +000092static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
93static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kuba Brecka45dbffd2015-07-23 10:54:06 +000094static const char *const kAsanInitName = "__asan_init";
95static const char *const kAsanVersionCheckName =
96 "__asan_version_mismatch_check_v6";
Kostya Serebryany796f6552014-02-27 12:45:36 +000097static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
98static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +000099static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000100static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +0000101static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
102static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000103static const char *const kAsanGenPrefix = "__asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000104static const char *const kSanCovGenPrefix = "__sancov_gen_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000105static const char *const kAsanPoisonStackMemoryName =
106 "__asan_poison_stack_memory";
107static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000108 "__asan_unpoison_stack_memory";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000109
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000110static const char *const kAsanOptionDetectUAR =
111 "__asan_option_detect_stack_use_after_return";
112
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000113static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
114static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
Yury Gribov98b18592015-05-28 07:51:49 +0000115
Kostya Serebryany874dae62012-07-16 16:15:40 +0000116// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
117static const size_t kNumberOfAccessSizes = 5;
118
Yury Gribov55441bb2014-11-21 10:29:50 +0000119static const unsigned kAllocaRzSize = 32;
Yury Gribov55441bb2014-11-21 10:29:50 +0000120
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000121// Command-line flags.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000122static cl::opt<bool> ClEnableKasan(
123 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
124 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000125
126// This flag may need to be replaced with -f[no-]asan-reads.
127static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000128 cl::desc("instrument read instructions"),
129 cl::Hidden, cl::init(true));
130static cl::opt<bool> ClInstrumentWrites(
131 "asan-instrument-writes", cl::desc("instrument write instructions"),
132 cl::Hidden, cl::init(true));
133static cl::opt<bool> ClInstrumentAtomics(
134 "asan-instrument-atomics",
135 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
136 cl::init(true));
137static cl::opt<bool> ClAlwaysSlowPath(
138 "asan-always-slow-path",
139 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
140 cl::init(false));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000141// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000142// in any given BB. Normally, this should be set to unlimited (INT_MAX),
143// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
144// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000145static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
146 "asan-max-ins-per-bb", cl::init(10000),
147 cl::desc("maximal number of instructions to instrument in any given BB"),
148 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000149// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000150static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
151 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000152static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000153 cl::desc("Check return-after-free"),
154 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000155// This flag may need to be replaced with -f[no]asan-globals.
156static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000157 cl::desc("Handle global objects"), cl::Hidden,
158 cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000159static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000160 cl::desc("Handle C++ initializer order"),
161 cl::Hidden, cl::init(true));
162static cl::opt<bool> ClInvalidPointerPairs(
163 "asan-detect-invalid-pointer-pair",
164 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
165 cl::init(false));
166static cl::opt<unsigned> ClRealignStack(
167 "asan-realign-stack",
168 cl::desc("Realign stack to the value of this flag (power of two)"),
169 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000170static cl::opt<int> ClInstrumentationWithCallsThreshold(
171 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000172 cl::desc(
173 "If the function being instrumented contains more than "
174 "this number of memory accesses, use callbacks instead of "
175 "inline checks (-1 means never use callbacks)."),
176 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000177static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000178 "asan-memory-access-callback-prefix",
179 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
180 cl::init("__asan_"));
Yury Gribov55441bb2014-11-21 10:29:50 +0000181static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000182 cl::desc("instrument dynamic allocas"),
Alexey Samsonovf4fb5f52015-10-22 20:07:28 +0000183 cl::Hidden, cl::init(true));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000184static cl::opt<bool> ClSkipPromotableAllocas(
185 "asan-skip-promotable-allocas",
186 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
187 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000188
189// These flags allow to change the shadow mapping.
190// The shadow mapping looks like
191// Shadow = (Mem >> scale) + (1 << offset_log)
192static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000193 cl::desc("scale of asan shadow mapping"),
194 cl::Hidden, cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000195
196// Optimization flags. Not user visible, used mostly for testing
197// and benchmarking the tool.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000198static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
199 cl::Hidden, cl::init(true));
200static cl::opt<bool> ClOptSameTemp(
201 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
202 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000203static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000204 cl::desc("Don't instrument scalar globals"),
205 cl::Hidden, cl::init(true));
206static cl::opt<bool> ClOptStack(
207 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
208 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000209
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000210static cl::opt<bool> ClCheckLifetime(
211 "asan-check-lifetime",
212 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"), cl::Hidden,
213 cl::init(false));
Alexey Samsonovdf624522012-11-29 18:14:24 +0000214
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000215static cl::opt<bool> ClDynamicAllocaStack(
216 "asan-stack-dynamic-alloca",
217 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000218 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000219
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000220static cl::opt<uint32_t> ClForceExperiment(
221 "asan-force-experiment",
222 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
223 cl::init(0));
224
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000225// Debug flags.
226static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
227 cl::init(0));
228static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
229 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000230static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
231 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000232static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
233 cl::Hidden, cl::init(-1));
234static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
235 cl::Hidden, cl::init(-1));
236
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000237STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
238STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000239STATISTIC(NumOptimizedAccessesToGlobalVar,
240 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000241STATISTIC(NumOptimizedAccessesToStackVar,
242 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000243
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000244namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000245/// Frontend-provided metadata for source location.
246struct LocationMetadata {
247 StringRef Filename;
248 int LineNo;
249 int ColumnNo;
250
251 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
252
253 bool empty() const { return Filename.empty(); }
254
255 void parse(MDNode *MDN) {
256 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000257 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
258 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000259 LineNo =
260 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
261 ColumnNo =
262 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000263 }
264};
265
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000266/// Frontend-provided metadata for global variables.
267class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000268 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000269 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000270 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000271 LocationMetadata SourceLoc;
272 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000273 bool IsDynInit;
274 bool IsBlacklisted;
275 };
276
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000277 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000278
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000279 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000280 assert(!inited_);
281 inited_ = true;
282 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000283 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000284 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000285 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000286 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000287 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000288 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000289 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000290 // We can already have an entry for GV if it was merged with another
291 // global.
292 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000293 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
294 E.SourceLoc.parse(Loc);
295 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
296 E.Name = Name->getString();
297 ConstantInt *IsDynInit =
298 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000299 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000300 ConstantInt *IsBlacklisted =
301 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000302 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000303 }
304 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000305
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000306 /// Returns metadata entry for a given global.
307 Entry get(GlobalVariable *G) const {
308 auto Pos = Entries.find(G);
309 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000310 }
311
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000312 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000313 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000314 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000315};
316
Alexey Samsonov1345d352013-01-16 13:23:28 +0000317/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000318/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000319struct ShadowMapping {
320 int Scale;
321 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000322 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000323};
324
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000325static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
326 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000327 bool IsAndroid = TargetTriple.isAndroid();
Bob Wilson9868d712014-10-09 05:43:30 +0000328 bool IsIOS = TargetTriple.isiOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000329 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
330 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000331 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
332 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000333 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000334 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
335 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000336 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
337 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000338 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000339 bool IsWindows = TargetTriple.isOSWindows();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000340
341 ShadowMapping Mapping;
342
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000343 if (LongSize == 32) {
Evgeniy Stepanov9cb08f82015-07-17 23:51:18 +0000344 // Android is always PIE, which means that the beginning of the address
345 // space is always available.
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000346 if (IsAndroid)
347 Mapping.Offset = 0;
348 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000349 Mapping.Offset = kMIPS32_ShadowOffset32;
350 else if (IsFreeBSD)
351 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000352 else if (IsIOS)
353 Mapping.Offset = kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000354 else if (IsWindows)
355 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000356 else
357 Mapping.Offset = kDefaultShadowOffset32;
358 } else { // LongSize == 64
359 if (IsPPC64)
360 Mapping.Offset = kPPC64_ShadowOffset64;
361 else if (IsFreeBSD)
362 Mapping.Offset = kFreeBSD_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000363 else if (IsLinux && IsX86_64) {
364 if (IsKasan)
365 Mapping.Offset = kLinuxKasan_ShadowOffset64;
366 else
367 Mapping.Offset = kSmallX86_64ShadowOffset;
368 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000369 Mapping.Offset = kMIPS64_ShadowOffset64;
Renato Golinaf213722015-02-03 11:20:45 +0000370 else if (IsAArch64)
371 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000372 else
373 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000374 }
375
376 Mapping.Scale = kDefaultShadowScale;
377 if (ClMappingScale) {
378 Mapping.Scale = ClMappingScale;
379 }
380
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000381 // OR-ing shadow offset if more efficient (at least on x86) if the offset
382 // is a power of two, but on ppc64 we have to use add since the shadow
383 // offset is not necessary 1/8-th of the address space.
Adhemerval Zanella35891fe2015-11-09 18:03:48 +0000384 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64
385 && !(Mapping.Offset & (Mapping.Offset - 1));
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000386
Alexey Samsonov1345d352013-01-16 13:23:28 +0000387 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000388}
389
Alexey Samsonov1345d352013-01-16 13:23:28 +0000390static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000391 // Redzone used for stack and globals is at least 32 bytes.
392 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000393 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000394}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000395
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000396/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000397struct AddressSanitizer : public FunctionPass {
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000398 explicit AddressSanitizer(bool CompileKernel = false)
399 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000400 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
401 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000402 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000403 return "AddressSanitizerFunctionPass";
404 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000405 void getAnalysisUsage(AnalysisUsage &AU) const override {
406 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000407 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000408 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000409 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
410 Type *Ty = AI->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000411 uint64_t SizeInBytes =
412 AI->getModule()->getDataLayout().getTypeAllocSize(Ty);
Anna Zaks8ed1d812015-02-27 03:12:36 +0000413 return SizeInBytes;
414 }
415 /// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000416 bool isInterestingAlloca(AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000417
418 // Check if we have dynamic alloca.
419 bool isDynamicAlloca(AllocaInst &AI) const {
420 return AI.isArrayAllocation() || !AI.isStaticAlloca();
421 }
422
Anna Zaks8ed1d812015-02-27 03:12:36 +0000423 /// If it is an interesting memory access, return the PointerOperand
424 /// and set IsWrite/Alignment. Otherwise return nullptr.
425 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000426 uint64_t *TypeSize, unsigned *Alignment);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000427 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000428 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000429 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000430 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
431 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000432 Value *SizeArgument, bool UseCalls, uint32_t Exp);
433 void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
434 uint32_t TypeSize, bool IsWrite,
435 Value *SizeArgument, bool UseCalls,
436 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000437 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
438 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000439 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000440 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000441 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000442 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000443 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000444 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000445 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000446 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000447 bool doInitialization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000448 static char ID; // Pass identification, replacement for typeid
449
Yury Gribov3ae427d2014-12-01 08:47:58 +0000450 DominatorTree &getDominatorTree() const { return *DT; }
451
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000452 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000453 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000454
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000455 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000456 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000457 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
458 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000459
Reid Kleckner2f907552015-07-21 17:40:14 +0000460 /// Helper to cleanup per-function state.
461 struct FunctionStateRAII {
462 AddressSanitizer *Pass;
463 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
464 assert(Pass->ProcessedAllocas.empty() &&
465 "last pass forgot to clear cache");
466 }
467 ~FunctionStateRAII() { Pass->ProcessedAllocas.clear(); }
468 };
469
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000470 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000471 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000472 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000473 bool CompileKernel;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000474 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000475 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000476 DominatorTree *DT;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000477 Function *AsanCtorFunction = nullptr;
478 Function *AsanInitFunction = nullptr;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000479 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000480 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000481 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
482 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
483 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
484 // This array is indexed by AccessIsWrite and Experiment.
485 Function *AsanErrorCallbackSized[2][2];
486 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000487 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000488 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000489 GlobalsMetadata GlobalsMD;
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000490 DenseMap<AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000491
492 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000493};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000494
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000495class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000496 public:
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000497 explicit AddressSanitizerModule(bool CompileKernel = false)
498 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000499 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000500 static char ID; // Pass identification, replacement for typeid
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000501 const char *getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000502
Kostya Serebryany20a79972012-11-22 03:18:50 +0000503 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000504 void initializeCallbacks(Module &M);
505
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000506 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000507 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000508 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000509 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000510 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000511 return RedzoneSizeForScale(Mapping.Scale);
512 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000513
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000514 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000515 bool CompileKernel;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000516 Type *IntptrTy;
517 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000518 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000519 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000520 Function *AsanPoisonGlobals;
521 Function *AsanUnpoisonGlobals;
522 Function *AsanRegisterGlobals;
523 Function *AsanUnregisterGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000524};
525
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000526// Stack poisoning does not play well with exception handling.
527// When an exception is thrown, we essentially bypass the code
528// that unpoisones the stack. This is why the run-time library has
529// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
530// stack in the interceptor. This however does not work inside the
531// actual function which catches the exception. Most likely because the
532// compiler hoists the load of the shadow value somewhere too high.
533// This causes asan to report a non-existing bug on 453.povray.
534// It sounds like an LLVM bug.
535struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
536 Function &F;
537 AddressSanitizer &ASan;
538 DIBuilder DIB;
539 LLVMContext *C;
540 Type *IntptrTy;
541 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000542 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000543
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000544 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000545 SmallSetVector<AllocaInst *, 16> NonInstrumentedStaticAllocaVec;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000546 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000547 unsigned StackAlignment;
548
Kostya Serebryany6805de52013-09-10 13:16:56 +0000549 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000550 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000551 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000552 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000553
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000554 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
555 struct AllocaPoisonCall {
556 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000557 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000558 uint64_t Size;
559 bool DoPoison;
560 };
561 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
562
Yury Gribov98b18592015-05-28 07:51:49 +0000563 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
564 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
565 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000566 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000567
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000568 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000569 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000570 AllocaForValueMapTy AllocaForValue;
571
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000572 bool HasNonEmptyInlineAsm = false;
573 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000574 std::unique_ptr<CallInst> EmptyInlineAsm;
575
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000576 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000577 : F(F),
578 ASan(ASan),
579 DIB(*F.getParent(), /*AllowUnresolved*/ false),
580 C(ASan.C),
581 IntptrTy(ASan.IntptrTy),
582 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
583 Mapping(ASan.Mapping),
584 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000585 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000586
587 bool runOnFunction() {
588 if (!ClStack) return false;
589 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000590 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000591
Yury Gribov55441bb2014-11-21 10:29:50 +0000592 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000593
594 initializeCallbacks(*F.getParent());
595
596 poisonStack();
597
598 if (ClDebugStack) {
599 DEBUG(dbgs() << F);
600 }
601 return true;
602 }
603
Yury Gribov55441bb2014-11-21 10:29:50 +0000604 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000605 // poisoned red zones around all of them.
606 // Then unpoison everything back before the function returns.
607 void poisonStack();
608
Yury Gribov98b18592015-05-28 07:51:49 +0000609 void createDynamicAllocasInitStorage();
610
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000611 // ----------------------- Visitors.
612 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000613 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000614
Yury Gribov98b18592015-05-28 07:51:49 +0000615 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
616 Value *SavedStack) {
617 IRBuilder<> IRB(InstBefore);
Yury Gribov781bce22015-05-28 08:03:28 +0000618 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000619 {IRB.CreateLoad(DynamicAllocaLayout),
Yury Gribov781bce22015-05-28 08:03:28 +0000620 IRB.CreatePtrToInt(SavedStack, IntptrTy)});
Yury Gribov98b18592015-05-28 07:51:49 +0000621 }
622
Yury Gribov55441bb2014-11-21 10:29:50 +0000623 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000624 void unpoisonDynamicAllocas() {
625 for (auto &Ret : RetVec)
626 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000627
Yury Gribov98b18592015-05-28 07:51:49 +0000628 for (auto &StackRestoreInst : StackRestoreVec)
629 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
630 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000631 }
632
Yury Gribov55441bb2014-11-21 10:29:50 +0000633 // Deploy and poison redzones around dynamic alloca call. To do this, we
634 // should replace this call with another one with changed parameters and
635 // replace all its uses with new address, so
636 // addr = alloca type, old_size, align
637 // is replaced by
638 // new_size = (old_size + additional_size) * sizeof(type)
639 // tmp = alloca i8, new_size, max(align, 32)
640 // addr = tmp + 32 (first 32 bytes are for the left redzone).
641 // Additional_size is added to make new memory allocation contain not only
642 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000643 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000644
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000645 /// \brief Collect Alloca instructions we want (and can) handle.
646 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000647 if (!ASan.isInterestingAlloca(AI)) {
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000648 if (AI.isStaticAlloca()) NonInstrumentedStaticAllocaVec.insert(&AI);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000649 return;
650 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000651
652 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Yury Gribov98b18592015-05-28 07:51:49 +0000653 if (ASan.isDynamicAlloca(AI))
654 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000655 else
656 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000657 }
658
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000659 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
660 /// errors.
661 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000662 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000663 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000664 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Yury Gribov98b18592015-05-28 07:51:49 +0000665 if (!ClCheckLifetime) return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000666 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000667 return;
668 // Found lifetime intrinsic, add ASan instrumentation if necessary.
669 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
670 // If size argument is undefined, don't do anything.
671 if (Size->isMinusOne()) return;
672 // Check that size doesn't saturate uint64_t and can
673 // be stored in IntptrTy.
674 const uint64_t SizeValue = Size->getValue().getLimitedValue();
675 if (SizeValue == ~0ULL ||
676 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
677 return;
678 // Find alloca instruction that corresponds to llvm.lifetime argument.
679 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
680 if (!AI) return;
681 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000682 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000683 AllocaPoisonCallVec.push_back(APC);
684 }
685
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000686 void visitCallSite(CallSite CS) {
687 Instruction *I = CS.getInstruction();
688 if (CallInst *CI = dyn_cast<CallInst>(I)) {
689 HasNonEmptyInlineAsm |=
690 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
691 HasReturnsTwiceCall |= CI->canReturnTwice();
692 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000693 }
694
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000695 // ---------------------- Helpers.
696 void initializeCallbacks(Module &M);
697
Yury Gribov3ae427d2014-12-01 08:47:58 +0000698 bool doesDominateAllExits(const Instruction *I) const {
699 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000700 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000701 }
702 return true;
703 }
704
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000705 /// Finds alloca where the value comes from.
706 AllocaInst *findAllocaForValue(Value *V);
Craig Topper3af97222014-08-27 05:25:00 +0000707 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000708 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000709 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000710
711 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
712 int Size);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000713 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
714 bool Dynamic);
715 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
716 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000717};
718
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000719} // anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000720
721char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000722INITIALIZE_PASS_BEGIN(
723 AddressSanitizer, "asan",
724 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
725 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000726INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +0000727INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000728INITIALIZE_PASS_END(
729 AddressSanitizer, "asan",
730 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
731 false)
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000732FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel) {
733 return new AddressSanitizer(CompileKernel);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000734}
735
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000736char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000737INITIALIZE_PASS(
738 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000739 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000740 "ModulePass",
741 false, false)
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000742ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel) {
743 return new AddressSanitizerModule(CompileKernel);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000744}
745
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000746static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000747 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000748 assert(Res < kNumberOfAccessSizes);
749 return Res;
750}
751
Bill Wendling58f8cef2013-08-06 22:52:42 +0000752// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000753static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
754 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000755 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000756 // We use private linkage for module-local strings. If they can be merged
757 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000758 GlobalVariable *GV =
759 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000760 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000761 if (AllowMerging) GV->setUnnamedAddr(true);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000762 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
763 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000764}
765
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000766/// \brief Create a global describing a source location.
767static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
768 LocationMetadata MD) {
769 Constant *LocData[] = {
770 createPrivateGlobalForString(M, MD.Filename, true),
771 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
772 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
773 };
774 auto LocStruct = ConstantStruct::getAnon(LocData);
775 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
776 GlobalValue::PrivateLinkage, LocStruct,
777 kAsanGenPrefix);
778 GV->setUnnamedAddr(true);
779 return GV;
780}
781
Kostya Serebryany139a9372012-11-20 14:16:08 +0000782static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000783 return G->getName().find(kAsanGenPrefix) == 0 ||
784 G->getName().find(kSanCovGenPrefix) == 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000785}
786
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000787Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
788 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000789 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000790 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000791 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000792 if (Mapping.OrShadowOffset)
793 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
794 else
795 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000796}
797
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000798// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000799void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
800 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000801 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000802 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000803 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +0000804 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
805 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
806 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000807 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000808 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000809 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +0000810 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
811 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
812 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000813 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000814 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000815}
816
Anna Zaks8ed1d812015-02-27 03:12:36 +0000817/// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000818bool AddressSanitizer::isInterestingAlloca(AllocaInst &AI) {
819 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
820
821 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
822 return PreviouslySeenAllocaInfo->getSecond();
823
Yury Gribov98b18592015-05-28 07:51:49 +0000824 bool IsInteresting =
825 (AI.getAllocatedType()->isSized() &&
826 // alloca() may be called with 0 size, ignore it.
827 getAllocaSizeInBytes(&AI) > 0 &&
828 // We are only interested in allocas not promotable to registers.
829 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +0000830 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
831 // inalloca allocas are not treated as static, and we don't want
832 // dynamic alloca instrumentation for them as well.
833 !AI.isUsedWithInAlloca());
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000834
835 ProcessedAllocas[&AI] = IsInteresting;
836 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000837}
838
839/// If I is an interesting memory access, return the PointerOperand
840/// and set IsWrite/Alignment. Otherwise return nullptr.
841Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
842 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000843 uint64_t *TypeSize,
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000844 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000845 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000846 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000847
848 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000849 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000850 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000851 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000852 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000853 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000854 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000855 PtrOperand = LI->getPointerOperand();
856 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000857 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000858 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000859 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000860 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000861 PtrOperand = SI->getPointerOperand();
862 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000863 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000864 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000865 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000866 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000867 PtrOperand = RMW->getPointerOperand();
868 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000869 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000870 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000871 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000872 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000873 PtrOperand = XCHG->getPointerOperand();
Kostya Serebryany90241602012-05-30 09:04:06 +0000874 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000875
876 // Treat memory accesses to promotable allocas as non-interesting since they
877 // will not cause memory violations. This greatly speeds up the instrumented
878 // executable at -O0.
879 if (ClSkipPromotableAllocas)
880 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
881 return isInterestingAlloca(*AI) ? AI : nullptr;
882
883 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000884}
885
Kostya Serebryany796f6552014-02-27 12:45:36 +0000886static bool isPointerOperand(Value *V) {
887 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
888}
889
890// This is a rough heuristic; it may cause both false positives and
891// false negatives. The proper implementation requires cooperation with
892// the frontend.
893static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
894 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000895 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000896 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000897 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000898 } else {
899 return false;
900 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +0000901 return isPointerOperand(I->getOperand(0)) &&
902 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +0000903}
904
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000905bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
906 // If a global variable does not have dynamic initialization we don't
907 // have to instrument it. However, if a global does not have initializer
908 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000909 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000910}
911
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000912void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
913 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +0000914 IRBuilder<> IRB(I);
915 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
916 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
917 for (int i = 0; i < 2; i++) {
918 if (Param[i]->getType()->isPointerTy())
919 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
920 }
David Blaikieff6409d2015-05-18 22:13:54 +0000921 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000922}
923
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000924void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000925 Instruction *I, bool UseCalls,
926 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +0000927 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000928 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000929 uint64_t TypeSize = 0;
930 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +0000931 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000932
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000933 // Optimization experiments.
934 // The experiments can be used to evaluate potential optimizations that remove
935 // instrumentation (assess false negatives). Instead of completely removing
936 // some instrumentation, you set Exp to a non-zero value (mask of optimization
937 // experiments that want to remove instrumentation of this instruction).
938 // If Exp is non-zero, this pass will emit special calls into runtime
939 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
940 // make runtime terminate the program in a special way (with a different
941 // exit status). Then you run the new compiler on a buggy corpus, collect
942 // the special terminations (ideally, you don't see them at all -- no false
943 // negatives) and make the decision on the optimization.
944 uint32_t Exp = ClForceExperiment;
945
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000946 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000947 // If initialization order checking is disabled, a simple access to a
948 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000949 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000950 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000951 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
952 NumOptimizedAccessesToGlobalVar++;
953 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000954 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000955 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000956
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000957 if (ClOpt && ClOptStack) {
958 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000959 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000960 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
961 NumOptimizedAccessesToStackVar++;
962 return;
963 }
964 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000965
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000966 if (IsWrite)
967 NumInstrumentedWrites++;
968 else
969 NumInstrumentedReads++;
970
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000971 unsigned Granularity = 1 << Mapping.Scale;
972 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
973 // if the data is properly aligned.
974 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
975 TypeSize == 128) &&
976 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000977 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
978 Exp);
979 instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
980 UseCalls, Exp);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000981}
982
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000983Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
984 Value *Addr, bool IsWrite,
985 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000986 Value *SizeArgument,
987 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000988 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000989 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
990 CallInst *Call = nullptr;
991 if (SizeArgument) {
992 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +0000993 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
994 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000995 else
David Blaikieff6409d2015-05-18 22:13:54 +0000996 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
997 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000998 } else {
999 if (Exp == 0)
1000 Call =
1001 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1002 else
David Blaikieff6409d2015-05-18 22:13:54 +00001003 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1004 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001005 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001006
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001007 // We don't do Call->setDoesNotReturn() because the BB already has
1008 // UnreachableInst at the end.
1009 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001010 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001011 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001012}
1013
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001014Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001015 Value *ShadowValue,
1016 uint32_t TypeSize) {
Alexey Samsonov1345d352013-01-16 13:23:28 +00001017 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001018 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001019 Value *LastAccessedByte =
1020 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001021 // (Addr & (Granularity - 1)) + size - 1
1022 if (TypeSize / 8 > 1)
1023 LastAccessedByte = IRB.CreateAdd(
1024 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1025 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001026 LastAccessedByte =
1027 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001028 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1029 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1030}
1031
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001032void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001033 Instruction *InsertBefore, Value *Addr,
1034 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001035 Value *SizeArgument, bool UseCalls,
1036 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001037 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001038 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001039 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1040
1041 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001042 if (Exp == 0)
1043 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1044 AddrLong);
1045 else
David Blaikieff6409d2015-05-18 22:13:54 +00001046 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1047 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001048 return;
1049 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001050
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001051 Type *ShadowTy =
1052 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001053 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1054 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1055 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001056 Value *ShadowValue =
1057 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001058
1059 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Alexey Samsonov1345d352013-01-16 13:23:28 +00001060 size_t Granularity = 1 << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001061 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001062
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001063 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001064 // We use branch weights for the slow path check, to indicate that the slow
1065 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001066 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1067 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001068 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001069 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001070 IRB.SetInsertPoint(CheckTerm);
1071 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001072 BasicBlock *CrashBlock =
1073 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001074 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001075 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1076 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001077 } else {
Evgeniy Stepanova9164e92013-12-19 13:29:56 +00001078 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001079 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001080
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001081 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001082 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001083 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001084}
1085
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001086// Instrument unusual size or unusual alignment.
1087// We can not do it with a single check, so we do 1-byte check for the first
1088// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1089// to report the actual access size.
1090void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1091 Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1092 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1093 IRBuilder<> IRB(I);
1094 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1095 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1096 if (UseCalls) {
1097 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001098 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1099 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001100 else
David Blaikieff6409d2015-05-18 22:13:54 +00001101 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1102 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001103 } else {
1104 Value *LastByte = IRB.CreateIntToPtr(
1105 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1106 Addr->getType());
1107 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1108 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1109 }
1110}
1111
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001112void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1113 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001114 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001115 IRBuilder<> IRB(&GlobalInit.front(),
1116 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001117
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001118 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001119 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1120 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001121
1122 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001123 for (auto &BB : GlobalInit.getBasicBlockList())
1124 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001125 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001126}
1127
1128void AddressSanitizerModule::createInitializerPoisonCalls(
1129 Module &M, GlobalValue *ModuleName) {
1130 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1131
1132 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1133 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001134 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001135 ConstantStruct *CS = cast<ConstantStruct>(OP);
1136
1137 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001138 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001139 if (F->getName() == kAsanModuleCtorName) continue;
1140 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1141 // Don't instrument CTORs that will run before asan.module_ctor.
1142 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1143 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001144 }
1145 }
1146}
1147
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001148bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001149 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001150 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001151
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001152 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001153 if (!Ty->isSized()) return false;
1154 if (!G->hasInitializer()) return false;
Kostya Serebryany139a9372012-11-20 14:16:08 +00001155 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001156 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001157 // Don't handle ODR linkage types and COMDATs since other modules may be built
1158 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001159 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1160 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1161 G->getLinkage() != GlobalVariable::InternalLinkage)
1162 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001163 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001164 // Two problems with thread-locals:
1165 // - The address of the main thread's copy can't be computed at link-time.
1166 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001167 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001168 // For now, just ignore this Global if the alignment is large.
1169 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001170
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001171 if (G->hasSection()) {
1172 StringRef Section(G->getSection());
Kuba Brecka086e34b2014-12-05 21:32:46 +00001173
Anna Zaks11904602015-06-09 00:58:08 +00001174 // Globals from llvm.metadata aren't emitted, do not instrument them.
1175 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001176 // Do not instrument globals from special LLVM sections.
1177 if (Section.find("__llvm") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001178
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001179 // Do not instrument function pointers to initialization and termination
1180 // routines: dynamic linker will not properly handle redzones.
1181 if (Section.startswith(".preinit_array") ||
1182 Section.startswith(".init_array") ||
1183 Section.startswith(".fini_array")) {
1184 return false;
1185 }
1186
Anna Zaks11904602015-06-09 00:58:08 +00001187 // Callbacks put into the CRT initializer/terminator sections
1188 // should not be instrumented.
1189 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1190 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1191 if (Section.startswith(".CRT")) {
1192 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1193 return false;
1194 }
1195
Kuba Brecka1001bb52014-12-05 22:19:18 +00001196 if (TargetTriple.isOSBinFormatMachO()) {
1197 StringRef ParsedSegment, ParsedSection;
1198 unsigned TAA = 0, StubSize = 0;
1199 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001200 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1201 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001202 if (!ErrorCode.empty()) {
Anna Zaks11904602015-06-09 00:58:08 +00001203 assert(false && "Invalid section specifier.");
1204 return false;
Kuba Brecka1001bb52014-12-05 22:19:18 +00001205 }
1206
1207 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1208 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1209 // them.
1210 if (ParsedSegment == "__OBJC" ||
1211 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1212 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1213 return false;
1214 }
1215 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1216 // Constant CFString instances are compiled in the following way:
1217 // -- the string buffer is emitted into
1218 // __TEXT,__cstring,cstring_literals
1219 // -- the constant NSConstantString structure referencing that buffer
1220 // is placed into __DATA,__cfstring
1221 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1222 // Moreover, it causes the linker to crash on OS X 10.7
1223 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1224 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1225 return false;
1226 }
1227 // The linker merges the contents of cstring_literals and removes the
1228 // trailing zeroes.
1229 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1230 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1231 return false;
1232 }
1233 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001234 }
1235
1236 return true;
1237}
1238
Alexey Samsonov788381b2012-12-25 12:28:20 +00001239void AddressSanitizerModule::initializeCallbacks(Module &M) {
1240 IRBuilder<> IRB(*C);
1241 // Declare our poisoning and unpoisoning functions.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001242 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001243 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001244 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001245 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001246 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001247 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1248 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001249 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001250 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001251 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001252 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001253 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1254 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001255 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1256}
1257
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001258// This function replaces all global variables with new variables that have
1259// trailing redzones. It also creates a function that poisons
1260// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001261bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001262 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001263
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001264 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1265
Alexey Samsonova02e6642014-05-29 18:40:48 +00001266 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001267 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001268 }
1269
1270 size_t n = GlobalsToChange.size();
1271 if (n == 0) return false;
1272
1273 // A global is described by a structure
1274 // size_t beg;
1275 // size_t size;
1276 // size_t size_with_redzone;
1277 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001278 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001279 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001280 // void *source_location;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001281 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001282 StructType *GlobalStructTy =
1283 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001284 IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001285 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001286
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001287 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001288
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001289 // We shouldn't merge same module names, as this string serves as unique
1290 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001291 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001292 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001293
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001294 auto &DL = M.getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001295 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001296 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001297 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001298
1299 auto MD = GlobalsMD.get(G);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001300 // Create string holding the global name (use global name from metadata
1301 // if it's available, otherwise just write the name of global variable).
1302 GlobalVariable *Name = createPrivateGlobalForString(
1303 M, MD.Name.empty() ? G->getName() : MD.Name,
1304 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001305
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001306 PointerType *PtrTy = cast<PointerType>(G->getType());
1307 Type *Ty = PtrTy->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001308 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001309 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001310 // MinRZ <= RZ <= kMaxGlobalRedzone
1311 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001312 uint64_t RZ = std::max(
1313 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001314 uint64_t RightRedzoneSize = RZ;
1315 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001316 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001317 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001318 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1319
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001320 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001321 Constant *NewInitializer =
1322 ConstantStruct::get(NewTy, G->getInitializer(),
1323 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001324
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001325 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001326 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1327 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1328 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001329 GlobalVariable *NewGlobal =
1330 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1331 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001332 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001333 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001334
1335 Value *Indices2[2];
1336 Indices2[0] = IRB.getInt32(0);
1337 Indices2[1] = IRB.getInt32(0);
1338
1339 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001340 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001341 NewGlobal->takeName(G);
1342 G->eraseFromParent();
1343
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001344 Constant *SourceLoc;
1345 if (!MD.SourceLoc.empty()) {
1346 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1347 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1348 } else {
1349 SourceLoc = ConstantInt::get(IntptrTy, 0);
1350 }
1351
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001352 Initializers[i] = ConstantStruct::get(
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001353 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001354 ConstantInt::get(IntptrTy, SizeInBytes),
1355 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1356 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001357 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001358 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001359
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001360 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001361
Kostya Serebryany20343352012-10-17 13:40:06 +00001362 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001363 }
1364
1365 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1366 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001367 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001368 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1369
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001370 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001371 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001372 createInitializerPoisonCalls(M, ModuleName);
David Blaikieff6409d2015-05-18 22:13:54 +00001373 IRB.CreateCall(AsanRegisterGlobals,
1374 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1375 ConstantInt::get(IntptrTy, n)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001376
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001377 // We also need to unregister globals at the end, e.g. when a shared library
1378 // gets closed.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001379 Function *AsanDtorFunction =
1380 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1381 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001382 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1383 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
David Blaikieff6409d2015-05-18 22:13:54 +00001384 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1385 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1386 ConstantInt::get(IntptrTy, n)});
Alexey Samsonov1f647502014-05-29 01:10:14 +00001387 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001388
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001389 DEBUG(dbgs() << M);
1390 return true;
1391}
1392
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001393bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001394 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001395 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001396 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001397 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001398 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001399 initializeCallbacks(M);
1400
1401 bool Changed = false;
1402
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001403 // TODO(glider): temporarily disabled globals instrumentation for KASan.
1404 if (ClGlobals && !CompileKernel) {
1405 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1406 assert(CtorFunc);
1407 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1408 Changed |= InstrumentGlobals(IRB, M);
1409 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001410
1411 return Changed;
1412}
1413
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001414void AddressSanitizer::initializeCallbacks(Module &M) {
1415 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001416 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001417 // IsWrite, TypeSize and Exp are encoded in the function name.
1418 for (int Exp = 0; Exp < 2; Exp++) {
1419 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1420 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1421 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001422 const std::string SuffixStr = CompileKernel ? "N" : "_n";
1423 const std::string EndingStr = CompileKernel ? "_noabort" : "";
Craig Toppere3dcce92015-08-01 22:20:21 +00001424 Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001425 // TODO(glider): for KASan builds add _noabort to error reporting
1426 // functions and make them actually noabort (remove the UnreachableInst).
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001427 AsanErrorCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001428 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001429 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001430 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1431 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001432 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001433 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001434 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1435 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1436 AccessSizeIndex++) {
1437 const std::string Suffix = TypeStr + itostr(1 << AccessSizeIndex);
1438 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001439 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001440 kAsanReportErrorTemplate + ExpStr + Suffix,
1441 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001442 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001443 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001444 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1445 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001446 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001447 }
1448 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00001449
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001450 const std::string MemIntrinCallbackPrefix =
1451 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001452 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001453 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001454 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001455 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001456 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001457 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001458 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001459 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001460 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001461
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001462 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001463 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001464
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001465 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001466 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001467 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001468 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001469 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1470 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1471 StringRef(""), StringRef(""),
1472 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001473}
1474
1475// virtual
1476bool AddressSanitizer::doInitialization(Module &M) {
1477 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001478
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001479 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001480
1481 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001482 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001483 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001484 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001485
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001486 if (!CompileKernel) {
1487 std::tie(AsanCtorFunction, AsanInitFunction) =
Kuba Brecka45dbffd2015-07-23 10:54:06 +00001488 createSanitizerCtorAndInitFunctions(
1489 M, kAsanModuleCtorName, kAsanInitName,
1490 /*InitArgTypes=*/{}, /*InitArgs=*/{}, kAsanVersionCheckName);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001491 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1492 }
1493 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001494 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001495}
1496
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001497bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1498 // For each NSObject descendant having a +load method, this method is invoked
1499 // by the ObjC runtime before any of the static constructors is called.
1500 // Therefore we need to instrument such methods with a call to __asan_init
1501 // at the beginning in order to initialize our runtime before any access to
1502 // the shadow memory.
1503 // We cannot just ignore these methods, because they may call other
1504 // instrumented functions.
1505 if (F.getName().find(" load]") != std::string::npos) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001506 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00001507 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001508 return true;
1509 }
1510 return false;
1511}
1512
Reid Kleckner2f907552015-07-21 17:40:14 +00001513void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
1514 // Find the one possible call to llvm.localescape and pre-mark allocas passed
1515 // to it as uninteresting. This assumes we haven't started processing allocas
1516 // yet. This check is done up front because iterating the use list in
1517 // isInterestingAlloca would be algorithmically slower.
1518 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
1519
1520 // Try to get the declaration of llvm.localescape. If it's not in the module,
1521 // we can exit early.
1522 if (!F.getParent()->getFunction("llvm.localescape")) return;
1523
1524 // Look for a call to llvm.localescape call in the entry block. It can't be in
1525 // any other block.
1526 for (Instruction &I : F.getEntryBlock()) {
1527 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
1528 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
1529 // We found a call. Mark all the allocas passed in as uninteresting.
1530 for (Value *Arg : II->arg_operands()) {
1531 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
1532 assert(AI && AI->isStaticAlloca() &&
1533 "non-static alloca arg to localescape");
1534 ProcessedAllocas[AI] = false;
1535 }
1536 break;
1537 }
1538 }
1539}
1540
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001541bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001542 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001543 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001544 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001545 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001546
Yury Gribov3ae427d2014-12-01 08:47:58 +00001547 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1548
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001549 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001550 maybeInsertAsanInitAtFunctionEntry(F);
1551
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001552 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001553
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001554 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001555
Reid Kleckner2f907552015-07-21 17:40:14 +00001556 FunctionStateRAII CleanupObj(this);
1557
1558 // We can't instrument allocas used with llvm.localescape. Only static allocas
1559 // can be passed to that intrinsic.
1560 markEscapedLocalAllocas(F);
1561
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001562 // We want to instrument every address only once per basic block (unless there
1563 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001564 SmallSet<Value *, 16> TempsToInstrument;
1565 SmallVector<Instruction *, 16> ToInstrument;
1566 SmallVector<Instruction *, 8> NoReturnCalls;
1567 SmallVector<BasicBlock *, 16> AllBlocks;
1568 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001569 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001570 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001571 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001572 uint64_t TypeSize;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001573
1574 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001575 for (auto &BB : F) {
1576 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001577 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001578 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001579 for (auto &Inst : BB) {
1580 if (LooksLikeCodeInBug11395(&Inst)) return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001581 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1582 &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001583 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001584 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001585 continue; // We've seen this temp in the current BB.
1586 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001587 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001588 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1589 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001590 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001591 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001592 // ok, take it.
1593 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001594 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001595 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001596 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001597 // A call inside BB.
1598 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001599 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001600 }
1601 continue;
1602 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001603 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001604 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001605 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001606 }
1607 }
1608
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001609 bool UseCalls =
1610 CompileKernel ||
1611 (ClInstrumentationWithCallsThreshold >= 0 &&
1612 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001613 const TargetLibraryInfo *TLI =
1614 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001615 const DataLayout &DL = F.getParent()->getDataLayout();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001616 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1617 /*RoundToAlign=*/true);
1618
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001619 // Instrument.
1620 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001621 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001622 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1623 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001624 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001625 instrumentMop(ObjSizeVis, Inst, UseCalls,
1626 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001627 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001628 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001629 }
1630 NumInstrumented++;
1631 }
1632
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001633 FunctionStackPoisoner FSP(F, *this);
1634 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001635
1636 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1637 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001638 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001639 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00001640 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001641 }
1642
Alexey Samsonova02e6642014-05-29 18:40:48 +00001643 for (auto Inst : PointerComparisonsOrSubtracts) {
1644 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001645 NumInstrumented++;
1646 }
1647
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001648 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001649
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001650 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1651
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001652 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001653}
1654
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001655// Workaround for bug 11395: we don't want to instrument stack in functions
1656// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1657// FIXME: remove once the bug 11395 is fixed.
1658bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1659 if (LongSize != 32) return false;
1660 CallInst *CI = dyn_cast<CallInst>(I);
1661 if (!CI || !CI->isInlineAsm()) return false;
1662 if (CI->getNumArgOperands() <= 5) return false;
1663 // We have inline assembly with quite a few arguments.
1664 return true;
1665}
1666
1667void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1668 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001669 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1670 std::string Suffix = itostr(i);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001671 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1672 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1673 IntptrTy, nullptr));
1674 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001675 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1676 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001677 }
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001678 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
David Blaikiea92765c2014-11-14 00:41:42 +00001679 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1680 IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001681 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
David Blaikiea92765c2014-11-14 00:41:42 +00001682 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1683 IntptrTy, IntptrTy, nullptr));
Yury Gribov98b18592015-05-28 07:51:49 +00001684 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1685 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1686 AsanAllocasUnpoisonFunc =
1687 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1688 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001689}
1690
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001691void FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1692 IRBuilder<> &IRB, Value *ShadowBase,
1693 bool DoPoison) {
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001694 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001695 size_t i = 0;
1696 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1697 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1698 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1699 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1700 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1701 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1702 uint64_t Val = 0;
1703 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001704 if (F.getParent()->getDataLayout().isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001705 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1706 else
1707 Val = (Val << 8) | ShadowBytes[i + j];
1708 }
1709 if (!Val) continue;
1710 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1711 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1712 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1713 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001714 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001715 }
1716}
1717
Kostya Serebryany6805de52013-09-10 13:16:56 +00001718// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1719// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1720static int StackMallocSizeClass(uint64_t LocalStackSize) {
1721 assert(LocalStackSize <= kMaxStackMallocSize);
1722 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001723 for (int i = 0;; i++, MaxSize *= 2)
1724 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00001725 llvm_unreachable("impossible LocalStackSize");
1726}
1727
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001728// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1729// We can not use MemSet intrinsic because it may end up calling the actual
1730// memset. Size is a multiple of 8.
1731// Currently this generates 8-byte stores on x86_64; it may be better to
1732// generate wider stores.
1733void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1734 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1735 assert(!(Size % 8));
Gabor Horvathfee04342015-03-16 09:53:42 +00001736
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001737 // kAsanStackAfterReturnMagic is 0xf5.
1738 const uint64_t kAsanStackAfterReturnMagic64 = 0xf5f5f5f5f5f5f5f5ULL;
Gabor Horvathfee04342015-03-16 09:53:42 +00001739
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001740 for (int i = 0; i < Size; i += 8) {
1741 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001742 IRB.CreateStore(
1743 ConstantInt::get(IRB.getInt64Ty(), kAsanStackAfterReturnMagic64),
1744 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001745 }
1746}
1747
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001748PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1749 Value *ValueIfTrue,
1750 Instruction *ThenTerm,
1751 Value *ValueIfFalse) {
1752 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1753 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1754 PHI->addIncoming(ValueIfFalse, CondBlock);
1755 BasicBlock *ThenBlock = ThenTerm->getParent();
1756 PHI->addIncoming(ValueIfTrue, ThenBlock);
1757 return PHI;
1758}
1759
1760Value *FunctionStackPoisoner::createAllocaForLayout(
1761 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
1762 AllocaInst *Alloca;
1763 if (Dynamic) {
1764 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
1765 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
1766 "MyAlloca");
1767 } else {
1768 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
1769 nullptr, "MyAlloca");
1770 assert(Alloca->isStaticAlloca());
1771 }
1772 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1773 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1774 Alloca->setAlignment(FrameAlignment);
1775 return IRB.CreatePointerCast(Alloca, IntptrTy);
1776}
1777
Yury Gribov98b18592015-05-28 07:51:49 +00001778void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
1779 BasicBlock &FirstBB = *F.begin();
1780 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
1781 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
1782 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
1783 DynamicAllocaLayout->setAlignment(32);
1784}
1785
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001786void FunctionStackPoisoner::poisonStack() {
Yury Gribov55441bb2014-11-21 10:29:50 +00001787 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1788
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00001789 // Insert poison calls for lifetime intrinsics for alloca.
1790 bool HavePoisonedAllocas = false;
1791 for (const auto &APC : AllocaPoisonCallVec) {
1792 assert(APC.InsBefore);
1793 assert(APC.AI);
1794 IRBuilder<> IRB(APC.InsBefore);
1795 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1796 HavePoisonedAllocas |= APC.DoPoison;
1797 }
1798
Yury Gribov98b18592015-05-28 07:51:49 +00001799 if (ClInstrumentAllocas && DynamicAllocaVec.size() > 0) {
Yury Gribov55441bb2014-11-21 10:29:50 +00001800 // Handle dynamic allocas.
Yury Gribov98b18592015-05-28 07:51:49 +00001801 createDynamicAllocasInitStorage();
Alexander Potapenkof90556e2015-06-12 11:27:06 +00001802 for (auto &AI : DynamicAllocaVec) handleDynamicAllocaCall(AI);
Yury Gribov98b18592015-05-28 07:51:49 +00001803
1804 unpoisonDynamicAllocas();
Kuba Breckaf5875d32015-02-24 09:47:05 +00001805 }
Yury Gribov55441bb2014-11-21 10:29:50 +00001806
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001807 if (AllocaVec.empty()) return;
Yury Gribov55441bb2014-11-21 10:29:50 +00001808
Kostya Serebryany6805de52013-09-10 13:16:56 +00001809 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00001810 DebugLoc EntryDebugLocation;
1811 if (auto SP = getDISubprogram(&F))
1812 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001813
1814 Instruction *InsBefore = AllocaVec[0];
1815 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001816 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001817
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00001818 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
1819 // debug info is broken, because only entry-block allocas are treated as
1820 // regular stack slots.
1821 auto InsBeforeB = InsBefore->getParent();
1822 assert(InsBeforeB == &F.getEntryBlock());
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001823 for (BasicBlock::iterator I(InsBefore); I != InsBeforeB->end(); ++I)
1824 if (auto *AI = dyn_cast<AllocaInst>(I))
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00001825 if (NonInstrumentedStaticAllocaVec.count(AI) > 0)
1826 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00001827
Reid Kleckner2f907552015-07-21 17:40:14 +00001828 // If we have a call to llvm.localescape, keep it in the entry block.
1829 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
1830
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001831 SmallVector<ASanStackVariableDescription, 16> SVD;
1832 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00001833 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001834 ASanStackVariableDescription D = {AI->getName().data(),
1835 ASan.getAllocaSizeInBytes(AI),
1836 AI->getAlignment(), AI, 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001837 SVD.push_back(D);
1838 }
1839 // Minimal header size (left redzone) is 4 pointers,
1840 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1841 size_t MinHeaderSize = ASan.LongSize / 2;
1842 ASanStackFrameLayout L;
1843 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1844 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1845 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001846 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
1847 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00001848 bool DoDynamicAlloca = ClDynamicAllocaStack;
1849 // Don't do dynamic alloca or stack malloc if:
1850 // 1) There is inline asm: too often it makes assumptions on which registers
1851 // are available.
1852 // 2) There is a returns_twice call (typically setjmp), which is
1853 // optimization-hostile, and doesn't play well with introduced indirect
1854 // register-relative calculation of local variable addresses.
1855 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
1856 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001857
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001858 Value *StaticAlloca =
1859 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
1860
1861 Value *FakeStack;
1862 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001863
1864 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001865 // void *FakeStack = __asan_option_detect_stack_use_after_return
1866 // ? __asan_stack_malloc_N(LocalStackSize)
1867 // : nullptr;
1868 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001869 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1870 kAsanOptionDetectUAR, IRB.getInt32Ty());
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001871 Value *UARIsEnabled =
1872 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1873 Constant::getNullValue(IRB.getInt32Ty()));
1874 Instruction *Term =
1875 SplitBlockAndInsertIfThen(UARIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001876 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001877 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001878 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1879 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1880 Value *FakeStackValue =
1881 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
1882 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001883 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001884 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001885 FakeStack = createPHI(IRB, UARIsEnabled, FakeStackValue, Term,
1886 ConstantInt::get(IntptrTy, 0));
1887
1888 Value *NoFakeStack =
1889 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
1890 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
1891 IRBIf.SetInsertPoint(Term);
1892 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1893 Value *AllocaValue =
1894 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
1895 IRB.SetInsertPoint(InsBefore);
1896 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1897 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
1898 } else {
1899 // void *FakeStack = nullptr;
1900 // void *LocalStackBase = alloca(LocalStackSize);
1901 FakeStack = ConstantInt::get(IntptrTy, 0);
1902 LocalStackBase =
1903 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001904 }
1905
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001906 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001907 for (const auto &Desc : SVD) {
1908 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00001909 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00001910 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001911 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00001912 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001913 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001914 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001915
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001916 // The left-most redzone has enough space for at least 4 pointers.
1917 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001918 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1919 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1920 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001921 // Write the frame description constant to redzone[1].
1922 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001923 IRB.CreateAdd(LocalStackBase,
1924 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
1925 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00001926 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001927 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001928 /*AllowMerging*/ true);
1929 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001930 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001931 // Write the PC to redzone[2].
1932 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001933 IRB.CreateAdd(LocalStackBase,
1934 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
1935 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001936 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001937
1938 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001939 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001940 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001941
Kostya Serebryany530e2072013-12-23 14:15:08 +00001942 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001943 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001944 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001945 // Mark the current frame as retired.
1946 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1947 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001948 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001949 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001950 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00001951 // // In use-after-return mode, poison the whole stack frame.
1952 // if StackMallocIdx <= 4
1953 // // For small sizes inline the whole thing:
1954 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001955 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00001956 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001957 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00001958 // else
1959 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001960 Value *Cmp =
1961 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00001962 TerminatorInst *ThenTerm, *ElseTerm;
1963 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1964
1965 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001966 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001967 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1968 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1969 ClassSize >> Mapping.Scale);
1970 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001971 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001972 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1973 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1974 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1975 IRBPoison.CreateStore(
1976 Constant::getNullValue(IRBPoison.getInt8Ty()),
1977 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1978 } else {
1979 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00001980 IRBPoison.CreateCall(
1981 AsanStackFreeFunc[StackMallocIdx],
1982 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001983 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00001984
1985 IRBuilder<> IRBElse(ElseTerm);
1986 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001987 } else if (HavePoisonedAllocas) {
1988 // If we poisoned some allocas in llvm.lifetime analysis,
1989 // unpoison whole stack frame now.
Alexey Samsonov261177a2012-12-04 01:34:23 +00001990 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001991 } else {
1992 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001993 }
1994 }
1995
Kostya Serebryany09959942012-10-19 06:20:53 +00001996 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001997 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001998}
Alexey Samsonov261177a2012-12-04 01:34:23 +00001999
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002000void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00002001 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00002002 // For now just insert the call to ASan runtime.
2003 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2004 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002005 IRB.CreateCall(
2006 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2007 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00002008}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002009
2010// Handling llvm.lifetime intrinsics for a given %alloca:
2011// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2012// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2013// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2014// could be poisoned by previous llvm.lifetime.end instruction, as the
2015// variable may go in and out of scope several times, e.g. in loops).
2016// (3) if we poisoned at least one %alloca in a function,
2017// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002018
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002019AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2020 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
2021 // We're intested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00002022 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002023 // See if we've already calculated (or started to calculate) alloca for a
2024 // given value.
2025 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002026 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002027 // Store 0 while we're calculating alloca for value V to avoid
2028 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00002029 AllocaForValue[V] = nullptr;
2030 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002031 if (CastInst *CI = dyn_cast<CastInst>(V))
2032 Res = findAllocaForValue(CI->getOperand(0));
2033 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00002034 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002035 // Allow self-referencing phi-nodes.
2036 if (IncValue == PN) continue;
2037 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2038 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00002039 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2040 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002041 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002042 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002043 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002044 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002045 return Res;
2046}
Yury Gribov55441bb2014-11-21 10:29:50 +00002047
Yury Gribov98b18592015-05-28 07:51:49 +00002048void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00002049 IRBuilder<> IRB(AI);
2050
Yury Gribov55441bb2014-11-21 10:29:50 +00002051 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2052 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2053
2054 Value *Zero = Constant::getNullValue(IntptrTy);
2055 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2056 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00002057
2058 // Since we need to extend alloca with additional memory to locate
2059 // redzones, and OldSize is number of allocated blocks with
2060 // ElementSize size, get allocated memory size in bytes by
2061 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00002062 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002063 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00002064 Value *OldSize =
2065 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2066 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00002067
2068 // PartialSize = OldSize % 32
2069 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2070
2071 // Misalign = kAllocaRzSize - PartialSize;
2072 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2073
2074 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2075 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2076 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2077
2078 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2079 // Align is added to locate left redzone, PartialPadding for possible
2080 // partial redzone and kAllocaRzSize for right redzone respectively.
2081 Value *AdditionalChunkSize = IRB.CreateAdd(
2082 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2083
2084 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2085
2086 // Insert new alloca with new NewSize and Align params.
2087 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2088 NewAlloca->setAlignment(Align);
2089
2090 // NewAddress = Address + Align
2091 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2092 ConstantInt::get(IntptrTy, Align));
2093
Yury Gribov98b18592015-05-28 07:51:49 +00002094 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00002095 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00002096
2097 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2098 // for unpoisoning stuff.
2099 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2100
Yury Gribov55441bb2014-11-21 10:29:50 +00002101 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2102
Yury Gribov98b18592015-05-28 07:51:49 +00002103 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00002104 AI->replaceAllUsesWith(NewAddressPtr);
2105
Yury Gribov98b18592015-05-28 07:51:49 +00002106 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00002107 AI->eraseFromParent();
2108}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002109
2110// isSafeAccess returns true if Addr is always inbounds with respect to its
2111// base object. For example, it is a field access or an array access with
2112// constant inbounds index.
2113bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2114 Value *Addr, uint64_t TypeSize) const {
2115 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2116 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00002117 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002118 int64_t Offset = SizeOffset.second.getSExtValue();
2119 // Three checks are required to ensure safety:
2120 // . Offset >= 0 (since the offset is given from the base ptr)
2121 // . Size >= Offset (unsigned)
2122 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00002123 return Offset >= 0 && Size >= uint64_t(Offset) &&
2124 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002125}