blob: dea94a514fe8ffcf6450914c93626f4f7cbac72a [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));
Yury Gribovd7731982015-11-11 10:36:49 +0000125static cl::opt<bool> ClRecover(
126 "asan-recover",
127 cl::desc("Enable recovery mode (continue-after-error)."),
128 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000129
130// This flag may need to be replaced with -f[no-]asan-reads.
131static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000132 cl::desc("instrument read instructions"),
133 cl::Hidden, cl::init(true));
134static cl::opt<bool> ClInstrumentWrites(
135 "asan-instrument-writes", cl::desc("instrument write instructions"),
136 cl::Hidden, cl::init(true));
137static cl::opt<bool> ClInstrumentAtomics(
138 "asan-instrument-atomics",
139 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
140 cl::init(true));
141static cl::opt<bool> ClAlwaysSlowPath(
142 "asan-always-slow-path",
143 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
144 cl::init(false));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000145// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000146// in any given BB. Normally, this should be set to unlimited (INT_MAX),
147// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
148// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000149static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
150 "asan-max-ins-per-bb", cl::init(10000),
151 cl::desc("maximal number of instructions to instrument in any given BB"),
152 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000153// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000154static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
155 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000156static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000157 cl::desc("Check return-after-free"),
158 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000159// This flag may need to be replaced with -f[no]asan-globals.
160static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000161 cl::desc("Handle global objects"), cl::Hidden,
162 cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000163static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000164 cl::desc("Handle C++ initializer order"),
165 cl::Hidden, cl::init(true));
166static cl::opt<bool> ClInvalidPointerPairs(
167 "asan-detect-invalid-pointer-pair",
168 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
169 cl::init(false));
170static cl::opt<unsigned> ClRealignStack(
171 "asan-realign-stack",
172 cl::desc("Realign stack to the value of this flag (power of two)"),
173 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000174static cl::opt<int> ClInstrumentationWithCallsThreshold(
175 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000176 cl::desc(
177 "If the function being instrumented contains more than "
178 "this number of memory accesses, use callbacks instead of "
179 "inline checks (-1 means never use callbacks)."),
180 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000181static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000182 "asan-memory-access-callback-prefix",
183 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
184 cl::init("__asan_"));
Yury Gribov55441bb2014-11-21 10:29:50 +0000185static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000186 cl::desc("instrument dynamic allocas"),
Alexey Samsonovf4fb5f52015-10-22 20:07:28 +0000187 cl::Hidden, cl::init(true));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000188static cl::opt<bool> ClSkipPromotableAllocas(
189 "asan-skip-promotable-allocas",
190 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
191 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000192
193// These flags allow to change the shadow mapping.
194// The shadow mapping looks like
195// Shadow = (Mem >> scale) + (1 << offset_log)
196static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000197 cl::desc("scale of asan shadow mapping"),
198 cl::Hidden, cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000199
200// Optimization flags. Not user visible, used mostly for testing
201// and benchmarking the tool.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000202static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
203 cl::Hidden, cl::init(true));
204static cl::opt<bool> ClOptSameTemp(
205 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
206 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000207static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000208 cl::desc("Don't instrument scalar globals"),
209 cl::Hidden, cl::init(true));
210static cl::opt<bool> ClOptStack(
211 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
212 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000213
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000214static cl::opt<bool> ClCheckLifetime(
215 "asan-check-lifetime",
216 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"), cl::Hidden,
217 cl::init(false));
Alexey Samsonovdf624522012-11-29 18:14:24 +0000218
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000219static cl::opt<bool> ClDynamicAllocaStack(
220 "asan-stack-dynamic-alloca",
221 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000222 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000223
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000224static cl::opt<uint32_t> ClForceExperiment(
225 "asan-force-experiment",
226 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
227 cl::init(0));
228
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000229// Debug flags.
230static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
231 cl::init(0));
232static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
233 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000234static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
235 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000236static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
237 cl::Hidden, cl::init(-1));
238static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
239 cl::Hidden, cl::init(-1));
240
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000241STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
242STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000243STATISTIC(NumOptimizedAccessesToGlobalVar,
244 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000245STATISTIC(NumOptimizedAccessesToStackVar,
246 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000247
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000248namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000249/// Frontend-provided metadata for source location.
250struct LocationMetadata {
251 StringRef Filename;
252 int LineNo;
253 int ColumnNo;
254
255 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
256
257 bool empty() const { return Filename.empty(); }
258
259 void parse(MDNode *MDN) {
260 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000261 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
262 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000263 LineNo =
264 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
265 ColumnNo =
266 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000267 }
268};
269
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000270/// Frontend-provided metadata for global variables.
271class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000272 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000273 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000274 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000275 LocationMetadata SourceLoc;
276 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000277 bool IsDynInit;
278 bool IsBlacklisted;
279 };
280
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000281 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000282
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000283 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000284 assert(!inited_);
285 inited_ = true;
286 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000287 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000288 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000289 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000290 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000291 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000292 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000293 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000294 // We can already have an entry for GV if it was merged with another
295 // global.
296 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000297 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
298 E.SourceLoc.parse(Loc);
299 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
300 E.Name = Name->getString();
301 ConstantInt *IsDynInit =
302 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000303 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000304 ConstantInt *IsBlacklisted =
305 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000306 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000307 }
308 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000309
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000310 /// Returns metadata entry for a given global.
311 Entry get(GlobalVariable *G) const {
312 auto Pos = Entries.find(G);
313 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000314 }
315
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000316 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000317 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000318 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000319};
320
Alexey Samsonov1345d352013-01-16 13:23:28 +0000321/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000322/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000323struct ShadowMapping {
324 int Scale;
325 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000326 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000327};
328
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000329static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
330 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000331 bool IsAndroid = TargetTriple.isAndroid();
Bob Wilson9868d712014-10-09 05:43:30 +0000332 bool IsIOS = TargetTriple.isiOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000333 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
334 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000335 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
336 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000337 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000338 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
339 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000340 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
341 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000342 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000343 bool IsWindows = TargetTriple.isOSWindows();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000344
345 ShadowMapping Mapping;
346
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000347 if (LongSize == 32) {
Evgeniy Stepanov9cb08f82015-07-17 23:51:18 +0000348 // Android is always PIE, which means that the beginning of the address
349 // space is always available.
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000350 if (IsAndroid)
351 Mapping.Offset = 0;
352 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000353 Mapping.Offset = kMIPS32_ShadowOffset32;
354 else if (IsFreeBSD)
355 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000356 else if (IsIOS)
357 Mapping.Offset = kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000358 else if (IsWindows)
359 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000360 else
361 Mapping.Offset = kDefaultShadowOffset32;
362 } else { // LongSize == 64
363 if (IsPPC64)
364 Mapping.Offset = kPPC64_ShadowOffset64;
365 else if (IsFreeBSD)
366 Mapping.Offset = kFreeBSD_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000367 else if (IsLinux && IsX86_64) {
368 if (IsKasan)
369 Mapping.Offset = kLinuxKasan_ShadowOffset64;
370 else
371 Mapping.Offset = kSmallX86_64ShadowOffset;
372 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000373 Mapping.Offset = kMIPS64_ShadowOffset64;
Renato Golinaf213722015-02-03 11:20:45 +0000374 else if (IsAArch64)
375 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000376 else
377 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000378 }
379
380 Mapping.Scale = kDefaultShadowScale;
381 if (ClMappingScale) {
382 Mapping.Scale = ClMappingScale;
383 }
384
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000385 // OR-ing shadow offset if more efficient (at least on x86) if the offset
386 // is a power of two, but on ppc64 we have to use add since the shadow
387 // offset is not necessary 1/8-th of the address space.
Adhemerval Zanella35891fe2015-11-09 18:03:48 +0000388 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64
389 && !(Mapping.Offset & (Mapping.Offset - 1));
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000390
Alexey Samsonov1345d352013-01-16 13:23:28 +0000391 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000392}
393
Alexey Samsonov1345d352013-01-16 13:23:28 +0000394static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000395 // Redzone used for stack and globals is at least 32 bytes.
396 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000397 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000398}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000399
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000400/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000401struct AddressSanitizer : public FunctionPass {
Yury Gribovd7731982015-11-11 10:36:49 +0000402 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false)
403 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
404 Recover(Recover || ClRecover) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000405 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
406 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000407 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000408 return "AddressSanitizerFunctionPass";
409 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000410 void getAnalysisUsage(AnalysisUsage &AU) const override {
411 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000412 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000413 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000414 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
415 Type *Ty = AI->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000416 uint64_t SizeInBytes =
417 AI->getModule()->getDataLayout().getTypeAllocSize(Ty);
Anna Zaks8ed1d812015-02-27 03:12:36 +0000418 return SizeInBytes;
419 }
420 /// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000421 bool isInterestingAlloca(AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000422
423 // Check if we have dynamic alloca.
424 bool isDynamicAlloca(AllocaInst &AI) const {
425 return AI.isArrayAllocation() || !AI.isStaticAlloca();
426 }
427
Anna Zaks8ed1d812015-02-27 03:12:36 +0000428 /// If it is an interesting memory access, return the PointerOperand
429 /// and set IsWrite/Alignment. Otherwise return nullptr.
430 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000431 uint64_t *TypeSize, unsigned *Alignment);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000432 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000433 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000434 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000435 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
436 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000437 Value *SizeArgument, bool UseCalls, uint32_t Exp);
438 void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
439 uint32_t TypeSize, bool IsWrite,
440 Value *SizeArgument, bool UseCalls,
441 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000442 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
443 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000444 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000445 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000446 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000447 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000448 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000449 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000450 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000451 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000452 bool doInitialization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000453 static char ID; // Pass identification, replacement for typeid
454
Yury Gribov3ae427d2014-12-01 08:47:58 +0000455 DominatorTree &getDominatorTree() const { return *DT; }
456
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000457 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000458 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000459
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000460 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000461 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000462 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
463 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000464
Reid Kleckner2f907552015-07-21 17:40:14 +0000465 /// Helper to cleanup per-function state.
466 struct FunctionStateRAII {
467 AddressSanitizer *Pass;
468 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
469 assert(Pass->ProcessedAllocas.empty() &&
470 "last pass forgot to clear cache");
471 }
472 ~FunctionStateRAII() { Pass->ProcessedAllocas.clear(); }
473 };
474
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000475 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000476 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000477 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000478 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000479 bool Recover;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000480 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000481 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000482 DominatorTree *DT;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000483 Function *AsanCtorFunction = nullptr;
484 Function *AsanInitFunction = nullptr;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000485 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000486 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000487 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
488 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
489 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
490 // This array is indexed by AccessIsWrite and Experiment.
491 Function *AsanErrorCallbackSized[2][2];
492 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000493 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000494 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000495 GlobalsMetadata GlobalsMD;
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000496 DenseMap<AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000497
498 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000499};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000500
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000501class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000502 public:
Yury Gribovd7731982015-11-11 10:36:49 +0000503 explicit AddressSanitizerModule(bool CompileKernel = false,
504 bool Recover = false)
505 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
506 Recover(Recover || ClRecover) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000507 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000508 static char ID; // Pass identification, replacement for typeid
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000509 const char *getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000510
Kostya Serebryany20a79972012-11-22 03:18:50 +0000511 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000512 void initializeCallbacks(Module &M);
513
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000514 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000515 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000516 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000517 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000518 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000519 return RedzoneSizeForScale(Mapping.Scale);
520 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000521
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000522 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000523 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000524 bool Recover;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000525 Type *IntptrTy;
526 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000527 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000528 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000529 Function *AsanPoisonGlobals;
530 Function *AsanUnpoisonGlobals;
531 Function *AsanRegisterGlobals;
532 Function *AsanUnregisterGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000533};
534
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000535// Stack poisoning does not play well with exception handling.
536// When an exception is thrown, we essentially bypass the code
537// that unpoisones the stack. This is why the run-time library has
538// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
539// stack in the interceptor. This however does not work inside the
540// actual function which catches the exception. Most likely because the
541// compiler hoists the load of the shadow value somewhere too high.
542// This causes asan to report a non-existing bug on 453.povray.
543// It sounds like an LLVM bug.
544struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
545 Function &F;
546 AddressSanitizer &ASan;
547 DIBuilder DIB;
548 LLVMContext *C;
549 Type *IntptrTy;
550 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000551 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000552
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000553 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000554 SmallSetVector<AllocaInst *, 16> NonInstrumentedStaticAllocaVec;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000555 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000556 unsigned StackAlignment;
557
Kostya Serebryany6805de52013-09-10 13:16:56 +0000558 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000559 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000560 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000561 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000562
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000563 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
564 struct AllocaPoisonCall {
565 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000566 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000567 uint64_t Size;
568 bool DoPoison;
569 };
570 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
571
Yury Gribov98b18592015-05-28 07:51:49 +0000572 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
573 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
574 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000575 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000576
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000577 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000578 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000579 AllocaForValueMapTy AllocaForValue;
580
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000581 bool HasNonEmptyInlineAsm = false;
582 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000583 std::unique_ptr<CallInst> EmptyInlineAsm;
584
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000585 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000586 : F(F),
587 ASan(ASan),
588 DIB(*F.getParent(), /*AllowUnresolved*/ false),
589 C(ASan.C),
590 IntptrTy(ASan.IntptrTy),
591 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
592 Mapping(ASan.Mapping),
593 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000594 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000595
596 bool runOnFunction() {
597 if (!ClStack) return false;
598 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000599 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000600
Yury Gribov55441bb2014-11-21 10:29:50 +0000601 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000602
603 initializeCallbacks(*F.getParent());
604
605 poisonStack();
606
607 if (ClDebugStack) {
608 DEBUG(dbgs() << F);
609 }
610 return true;
611 }
612
Yury Gribov55441bb2014-11-21 10:29:50 +0000613 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000614 // poisoned red zones around all of them.
615 // Then unpoison everything back before the function returns.
616 void poisonStack();
617
Yury Gribov98b18592015-05-28 07:51:49 +0000618 void createDynamicAllocasInitStorage();
619
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000620 // ----------------------- Visitors.
621 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000622 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000623
Yury Gribov98b18592015-05-28 07:51:49 +0000624 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
625 Value *SavedStack) {
626 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000627 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
628 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
629 // need to adjust extracted SP to compute the address of the most recent
630 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
631 // this purpose.
632 if (!isa<ReturnInst>(InstBefore)) {
633 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
634 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
635 {IntptrTy});
636
637 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
638
639 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
640 DynamicAreaOffset);
641 }
642
Yury Gribov781bce22015-05-28 08:03:28 +0000643 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000644 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000645 }
646
Yury Gribov55441bb2014-11-21 10:29:50 +0000647 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000648 void unpoisonDynamicAllocas() {
649 for (auto &Ret : RetVec)
650 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000651
Yury Gribov98b18592015-05-28 07:51:49 +0000652 for (auto &StackRestoreInst : StackRestoreVec)
653 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
654 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000655 }
656
Yury Gribov55441bb2014-11-21 10:29:50 +0000657 // Deploy and poison redzones around dynamic alloca call. To do this, we
658 // should replace this call with another one with changed parameters and
659 // replace all its uses with new address, so
660 // addr = alloca type, old_size, align
661 // is replaced by
662 // new_size = (old_size + additional_size) * sizeof(type)
663 // tmp = alloca i8, new_size, max(align, 32)
664 // addr = tmp + 32 (first 32 bytes are for the left redzone).
665 // Additional_size is added to make new memory allocation contain not only
666 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000667 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000668
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000669 /// \brief Collect Alloca instructions we want (and can) handle.
670 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000671 if (!ASan.isInterestingAlloca(AI)) {
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000672 if (AI.isStaticAlloca()) NonInstrumentedStaticAllocaVec.insert(&AI);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000673 return;
674 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000675
676 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Yury Gribov98b18592015-05-28 07:51:49 +0000677 if (ASan.isDynamicAlloca(AI))
678 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000679 else
680 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000681 }
682
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000683 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
684 /// errors.
685 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000686 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000687 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000688 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Yury Gribov98b18592015-05-28 07:51:49 +0000689 if (!ClCheckLifetime) return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000690 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000691 return;
692 // Found lifetime intrinsic, add ASan instrumentation if necessary.
693 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
694 // If size argument is undefined, don't do anything.
695 if (Size->isMinusOne()) return;
696 // Check that size doesn't saturate uint64_t and can
697 // be stored in IntptrTy.
698 const uint64_t SizeValue = Size->getValue().getLimitedValue();
699 if (SizeValue == ~0ULL ||
700 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
701 return;
702 // Find alloca instruction that corresponds to llvm.lifetime argument.
703 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
704 if (!AI) return;
705 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000706 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000707 AllocaPoisonCallVec.push_back(APC);
708 }
709
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000710 void visitCallSite(CallSite CS) {
711 Instruction *I = CS.getInstruction();
712 if (CallInst *CI = dyn_cast<CallInst>(I)) {
713 HasNonEmptyInlineAsm |=
714 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
715 HasReturnsTwiceCall |= CI->canReturnTwice();
716 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000717 }
718
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000719 // ---------------------- Helpers.
720 void initializeCallbacks(Module &M);
721
Yury Gribov3ae427d2014-12-01 08:47:58 +0000722 bool doesDominateAllExits(const Instruction *I) const {
723 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000724 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000725 }
726 return true;
727 }
728
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000729 /// Finds alloca where the value comes from.
730 AllocaInst *findAllocaForValue(Value *V);
Craig Topper3af97222014-08-27 05:25:00 +0000731 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000732 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000733 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000734
735 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
736 int Size);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000737 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
738 bool Dynamic);
739 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
740 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000741};
742
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000743} // anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000744
745char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000746INITIALIZE_PASS_BEGIN(
747 AddressSanitizer, "asan",
748 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
749 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000750INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +0000751INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000752INITIALIZE_PASS_END(
753 AddressSanitizer, "asan",
754 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
755 false)
Yury Gribovd7731982015-11-11 10:36:49 +0000756FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
757 bool Recover) {
758 assert(!CompileKernel || Recover);
759 return new AddressSanitizer(CompileKernel, Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000760}
761
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000762char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000763INITIALIZE_PASS(
764 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000765 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000766 "ModulePass",
767 false, false)
Yury Gribovd7731982015-11-11 10:36:49 +0000768ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
769 bool Recover) {
770 assert(!CompileKernel || Recover);
771 return new AddressSanitizerModule(CompileKernel, Recover);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000772}
773
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000774static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000775 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000776 assert(Res < kNumberOfAccessSizes);
777 return Res;
778}
779
Bill Wendling58f8cef2013-08-06 22:52:42 +0000780// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000781static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
782 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000783 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000784 // We use private linkage for module-local strings. If they can be merged
785 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000786 GlobalVariable *GV =
787 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000788 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000789 if (AllowMerging) GV->setUnnamedAddr(true);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000790 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
791 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000792}
793
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000794/// \brief Create a global describing a source location.
795static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
796 LocationMetadata MD) {
797 Constant *LocData[] = {
798 createPrivateGlobalForString(M, MD.Filename, true),
799 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
800 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
801 };
802 auto LocStruct = ConstantStruct::getAnon(LocData);
803 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
804 GlobalValue::PrivateLinkage, LocStruct,
805 kAsanGenPrefix);
806 GV->setUnnamedAddr(true);
807 return GV;
808}
809
Kostya Serebryany139a9372012-11-20 14:16:08 +0000810static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000811 return G->getName().find(kAsanGenPrefix) == 0 ||
812 G->getName().find(kSanCovGenPrefix) == 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000813}
814
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000815Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
816 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000817 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000818 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000819 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000820 if (Mapping.OrShadowOffset)
821 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
822 else
823 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000824}
825
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000826// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000827void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
828 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000829 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000830 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000831 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +0000832 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
833 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
834 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000835 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000836 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000837 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +0000838 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
839 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
840 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000841 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000842 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000843}
844
Anna Zaks8ed1d812015-02-27 03:12:36 +0000845/// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000846bool AddressSanitizer::isInterestingAlloca(AllocaInst &AI) {
847 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
848
849 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
850 return PreviouslySeenAllocaInfo->getSecond();
851
Yury Gribov98b18592015-05-28 07:51:49 +0000852 bool IsInteresting =
853 (AI.getAllocatedType()->isSized() &&
854 // alloca() may be called with 0 size, ignore it.
855 getAllocaSizeInBytes(&AI) > 0 &&
856 // We are only interested in allocas not promotable to registers.
857 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +0000858 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
859 // inalloca allocas are not treated as static, and we don't want
860 // dynamic alloca instrumentation for them as well.
861 !AI.isUsedWithInAlloca());
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000862
863 ProcessedAllocas[&AI] = IsInteresting;
864 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000865}
866
867/// If I is an interesting memory access, return the PointerOperand
868/// and set IsWrite/Alignment. Otherwise return nullptr.
869Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
870 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000871 uint64_t *TypeSize,
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000872 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000873 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000874 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000875
876 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000877 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000878 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000879 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000880 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000881 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000882 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000883 PtrOperand = LI->getPointerOperand();
884 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000885 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000886 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000887 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000888 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000889 PtrOperand = SI->getPointerOperand();
890 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000891 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000892 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000893 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000894 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000895 PtrOperand = RMW->getPointerOperand();
896 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000897 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000898 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000899 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000900 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000901 PtrOperand = XCHG->getPointerOperand();
Kostya Serebryany90241602012-05-30 09:04:06 +0000902 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000903
904 // Treat memory accesses to promotable allocas as non-interesting since they
905 // will not cause memory violations. This greatly speeds up the instrumented
906 // executable at -O0.
907 if (ClSkipPromotableAllocas)
908 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
909 return isInterestingAlloca(*AI) ? AI : nullptr;
910
911 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000912}
913
Kostya Serebryany796f6552014-02-27 12:45:36 +0000914static bool isPointerOperand(Value *V) {
915 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
916}
917
918// This is a rough heuristic; it may cause both false positives and
919// false negatives. The proper implementation requires cooperation with
920// the frontend.
921static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
922 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000923 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000924 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000925 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000926 } else {
927 return false;
928 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +0000929 return isPointerOperand(I->getOperand(0)) &&
930 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +0000931}
932
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000933bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
934 // If a global variable does not have dynamic initialization we don't
935 // have to instrument it. However, if a global does not have initializer
936 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000937 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000938}
939
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000940void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
941 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +0000942 IRBuilder<> IRB(I);
943 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
944 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
945 for (int i = 0; i < 2; i++) {
946 if (Param[i]->getType()->isPointerTy())
947 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
948 }
David Blaikieff6409d2015-05-18 22:13:54 +0000949 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000950}
951
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000952void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000953 Instruction *I, bool UseCalls,
954 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +0000955 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000956 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000957 uint64_t TypeSize = 0;
958 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +0000959 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000960
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000961 // Optimization experiments.
962 // The experiments can be used to evaluate potential optimizations that remove
963 // instrumentation (assess false negatives). Instead of completely removing
964 // some instrumentation, you set Exp to a non-zero value (mask of optimization
965 // experiments that want to remove instrumentation of this instruction).
966 // If Exp is non-zero, this pass will emit special calls into runtime
967 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
968 // make runtime terminate the program in a special way (with a different
969 // exit status). Then you run the new compiler on a buggy corpus, collect
970 // the special terminations (ideally, you don't see them at all -- no false
971 // negatives) and make the decision on the optimization.
972 uint32_t Exp = ClForceExperiment;
973
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000974 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000975 // If initialization order checking is disabled, a simple access to a
976 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000977 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000978 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000979 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
980 NumOptimizedAccessesToGlobalVar++;
981 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000982 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000983 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000984
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000985 if (ClOpt && ClOptStack) {
986 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000987 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000988 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
989 NumOptimizedAccessesToStackVar++;
990 return;
991 }
992 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000993
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000994 if (IsWrite)
995 NumInstrumentedWrites++;
996 else
997 NumInstrumentedReads++;
998
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000999 unsigned Granularity = 1 << Mapping.Scale;
1000 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1001 // if the data is properly aligned.
1002 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1003 TypeSize == 128) &&
1004 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001005 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
1006 Exp);
1007 instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
1008 UseCalls, Exp);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001009}
1010
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001011Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1012 Value *Addr, bool IsWrite,
1013 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001014 Value *SizeArgument,
1015 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001016 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001017 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1018 CallInst *Call = nullptr;
1019 if (SizeArgument) {
1020 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001021 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1022 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001023 else
David Blaikieff6409d2015-05-18 22:13:54 +00001024 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1025 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001026 } else {
1027 if (Exp == 0)
1028 Call =
1029 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1030 else
David Blaikieff6409d2015-05-18 22:13:54 +00001031 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1032 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001033 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001034
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001035 // We don't do Call->setDoesNotReturn() because the BB already has
1036 // UnreachableInst at the end.
1037 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001038 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001039 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001040}
1041
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001042Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001043 Value *ShadowValue,
1044 uint32_t TypeSize) {
Alexey Samsonov1345d352013-01-16 13:23:28 +00001045 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001046 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001047 Value *LastAccessedByte =
1048 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001049 // (Addr & (Granularity - 1)) + size - 1
1050 if (TypeSize / 8 > 1)
1051 LastAccessedByte = IRB.CreateAdd(
1052 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1053 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001054 LastAccessedByte =
1055 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001056 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1057 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1058}
1059
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001060void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001061 Instruction *InsertBefore, Value *Addr,
1062 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001063 Value *SizeArgument, bool UseCalls,
1064 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001065 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001066 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001067 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1068
1069 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001070 if (Exp == 0)
1071 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1072 AddrLong);
1073 else
David Blaikieff6409d2015-05-18 22:13:54 +00001074 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1075 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001076 return;
1077 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001078
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001079 Type *ShadowTy =
1080 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001081 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1082 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1083 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001084 Value *ShadowValue =
1085 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001086
1087 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Alexey Samsonov1345d352013-01-16 13:23:28 +00001088 size_t Granularity = 1 << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001089 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001090
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001091 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001092 // We use branch weights for the slow path check, to indicate that the slow
1093 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001094 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1095 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001096 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001097 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001098 IRB.SetInsertPoint(CheckTerm);
1099 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001100 if (Recover) {
1101 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1102 } else {
1103 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001104 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001105 CrashTerm = new UnreachableInst(*C, CrashBlock);
1106 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1107 ReplaceInstWithInst(CheckTerm, NewTerm);
1108 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001109 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001110 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001111 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001112
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001113 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001114 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001115 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001116}
1117
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001118// Instrument unusual size or unusual alignment.
1119// We can not do it with a single check, so we do 1-byte check for the first
1120// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1121// to report the actual access size.
1122void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1123 Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1124 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1125 IRBuilder<> IRB(I);
1126 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1127 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1128 if (UseCalls) {
1129 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001130 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1131 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001132 else
David Blaikieff6409d2015-05-18 22:13:54 +00001133 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1134 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001135 } else {
1136 Value *LastByte = IRB.CreateIntToPtr(
1137 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1138 Addr->getType());
1139 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1140 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1141 }
1142}
1143
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001144void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1145 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001146 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001147 IRBuilder<> IRB(&GlobalInit.front(),
1148 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001149
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001150 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001151 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1152 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001153
1154 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001155 for (auto &BB : GlobalInit.getBasicBlockList())
1156 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001157 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001158}
1159
1160void AddressSanitizerModule::createInitializerPoisonCalls(
1161 Module &M, GlobalValue *ModuleName) {
1162 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1163
1164 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1165 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001166 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001167 ConstantStruct *CS = cast<ConstantStruct>(OP);
1168
1169 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001170 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001171 if (F->getName() == kAsanModuleCtorName) continue;
1172 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1173 // Don't instrument CTORs that will run before asan.module_ctor.
1174 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1175 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001176 }
1177 }
1178}
1179
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001180bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001181 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001182 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001183
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001184 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001185 if (!Ty->isSized()) return false;
1186 if (!G->hasInitializer()) return false;
Kostya Serebryany139a9372012-11-20 14:16:08 +00001187 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001188 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001189 // Don't handle ODR linkage types and COMDATs since other modules may be built
1190 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001191 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1192 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1193 G->getLinkage() != GlobalVariable::InternalLinkage)
1194 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001195 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001196 // Two problems with thread-locals:
1197 // - The address of the main thread's copy can't be computed at link-time.
1198 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001199 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001200 // For now, just ignore this Global if the alignment is large.
1201 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001202
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001203 if (G->hasSection()) {
1204 StringRef Section(G->getSection());
Kuba Brecka086e34b2014-12-05 21:32:46 +00001205
Anna Zaks11904602015-06-09 00:58:08 +00001206 // Globals from llvm.metadata aren't emitted, do not instrument them.
1207 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001208 // Do not instrument globals from special LLVM sections.
1209 if (Section.find("__llvm") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001210
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001211 // Do not instrument function pointers to initialization and termination
1212 // routines: dynamic linker will not properly handle redzones.
1213 if (Section.startswith(".preinit_array") ||
1214 Section.startswith(".init_array") ||
1215 Section.startswith(".fini_array")) {
1216 return false;
1217 }
1218
Anna Zaks11904602015-06-09 00:58:08 +00001219 // Callbacks put into the CRT initializer/terminator sections
1220 // should not be instrumented.
1221 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1222 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1223 if (Section.startswith(".CRT")) {
1224 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1225 return false;
1226 }
1227
Kuba Brecka1001bb52014-12-05 22:19:18 +00001228 if (TargetTriple.isOSBinFormatMachO()) {
1229 StringRef ParsedSegment, ParsedSection;
1230 unsigned TAA = 0, StubSize = 0;
1231 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001232 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1233 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001234 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001235
1236 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1237 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1238 // them.
1239 if (ParsedSegment == "__OBJC" ||
1240 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1241 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1242 return false;
1243 }
1244 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1245 // Constant CFString instances are compiled in the following way:
1246 // -- the string buffer is emitted into
1247 // __TEXT,__cstring,cstring_literals
1248 // -- the constant NSConstantString structure referencing that buffer
1249 // is placed into __DATA,__cfstring
1250 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1251 // Moreover, it causes the linker to crash on OS X 10.7
1252 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1253 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1254 return false;
1255 }
1256 // The linker merges the contents of cstring_literals and removes the
1257 // trailing zeroes.
1258 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1259 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1260 return false;
1261 }
1262 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001263 }
1264
1265 return true;
1266}
1267
Alexey Samsonov788381b2012-12-25 12:28:20 +00001268void AddressSanitizerModule::initializeCallbacks(Module &M) {
1269 IRBuilder<> IRB(*C);
1270 // Declare our poisoning and unpoisoning functions.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001271 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001272 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001273 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001274 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001275 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001276 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1277 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001278 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001279 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001280 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001281 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001282 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1283 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001284 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1285}
1286
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001287// This function replaces all global variables with new variables that have
1288// trailing redzones. It also creates a function that poisons
1289// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001290bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001291 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001292
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001293 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1294
Alexey Samsonova02e6642014-05-29 18:40:48 +00001295 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001296 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001297 }
1298
1299 size_t n = GlobalsToChange.size();
1300 if (n == 0) return false;
1301
1302 // A global is described by a structure
1303 // size_t beg;
1304 // size_t size;
1305 // size_t size_with_redzone;
1306 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001307 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001308 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001309 // void *source_location;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001310 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001311 StructType *GlobalStructTy =
1312 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001313 IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001314 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001315
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001316 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001317
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001318 // We shouldn't merge same module names, as this string serves as unique
1319 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001320 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001321 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001322
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001323 auto &DL = M.getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001324 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001325 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001326 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001327
1328 auto MD = GlobalsMD.get(G);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001329 // Create string holding the global name (use global name from metadata
1330 // if it's available, otherwise just write the name of global variable).
1331 GlobalVariable *Name = createPrivateGlobalForString(
1332 M, MD.Name.empty() ? G->getName() : MD.Name,
1333 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001334
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001335 PointerType *PtrTy = cast<PointerType>(G->getType());
1336 Type *Ty = PtrTy->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001337 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001338 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001339 // MinRZ <= RZ <= kMaxGlobalRedzone
1340 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001341 uint64_t RZ = std::max(
1342 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001343 uint64_t RightRedzoneSize = RZ;
1344 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001345 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001346 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001347 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1348
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001349 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001350 Constant *NewInitializer =
1351 ConstantStruct::get(NewTy, G->getInitializer(),
1352 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001353
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001354 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001355 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1356 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1357 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001358 GlobalVariable *NewGlobal =
1359 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1360 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001361 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001362 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001363
1364 Value *Indices2[2];
1365 Indices2[0] = IRB.getInt32(0);
1366 Indices2[1] = IRB.getInt32(0);
1367
1368 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001369 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001370 NewGlobal->takeName(G);
1371 G->eraseFromParent();
1372
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001373 Constant *SourceLoc;
1374 if (!MD.SourceLoc.empty()) {
1375 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1376 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1377 } else {
1378 SourceLoc = ConstantInt::get(IntptrTy, 0);
1379 }
1380
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001381 Initializers[i] = ConstantStruct::get(
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001382 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001383 ConstantInt::get(IntptrTy, SizeInBytes),
1384 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1385 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001386 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001387 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001388
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001389 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001390
Kostya Serebryany20343352012-10-17 13:40:06 +00001391 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001392 }
1393
1394 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1395 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001396 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001397 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1398
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001399 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001400 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001401 createInitializerPoisonCalls(M, ModuleName);
David Blaikieff6409d2015-05-18 22:13:54 +00001402 IRB.CreateCall(AsanRegisterGlobals,
1403 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1404 ConstantInt::get(IntptrTy, n)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001405
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001406 // We also need to unregister globals at the end, e.g. when a shared library
1407 // gets closed.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001408 Function *AsanDtorFunction =
1409 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1410 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001411 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1412 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
David Blaikieff6409d2015-05-18 22:13:54 +00001413 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1414 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1415 ConstantInt::get(IntptrTy, n)});
Alexey Samsonov1f647502014-05-29 01:10:14 +00001416 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001417
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001418 DEBUG(dbgs() << M);
1419 return true;
1420}
1421
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001422bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001423 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001424 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001425 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001426 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001427 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001428 initializeCallbacks(M);
1429
1430 bool Changed = false;
1431
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001432 // TODO(glider): temporarily disabled globals instrumentation for KASan.
1433 if (ClGlobals && !CompileKernel) {
1434 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1435 assert(CtorFunc);
1436 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1437 Changed |= InstrumentGlobals(IRB, M);
1438 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001439
1440 return Changed;
1441}
1442
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001443void AddressSanitizer::initializeCallbacks(Module &M) {
1444 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001445 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001446 // IsWrite, TypeSize and Exp are encoded in the function name.
1447 for (int Exp = 0; Exp < 2; Exp++) {
1448 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1449 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1450 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001451 const std::string SuffixStr = CompileKernel ? "N" : "_n";
Yury Gribovd7731982015-11-11 10:36:49 +00001452 const std::string EndingStr = Recover ? "_noabort" : "";
Craig Toppere3dcce92015-08-01 22:20:21 +00001453 Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001454 AsanErrorCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001455 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001456 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001457 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1458 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001459 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001460 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001461 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1462 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1463 AccessSizeIndex++) {
1464 const std::string Suffix = TypeStr + itostr(1 << AccessSizeIndex);
1465 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001466 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001467 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001468 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001469 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001470 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001471 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1472 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001473 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001474 }
1475 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00001476
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001477 const std::string MemIntrinCallbackPrefix =
1478 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001479 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001480 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001481 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001482 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001483 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001484 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001485 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001486 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001487 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001488
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001489 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001490 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001491
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001492 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001493 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001494 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001495 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001496 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1497 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1498 StringRef(""), StringRef(""),
1499 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001500}
1501
1502// virtual
1503bool AddressSanitizer::doInitialization(Module &M) {
1504 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001505
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001506 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001507
1508 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001509 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001510 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001511 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001512
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001513 if (!CompileKernel) {
1514 std::tie(AsanCtorFunction, AsanInitFunction) =
Kuba Brecka45dbffd2015-07-23 10:54:06 +00001515 createSanitizerCtorAndInitFunctions(
1516 M, kAsanModuleCtorName, kAsanInitName,
1517 /*InitArgTypes=*/{}, /*InitArgs=*/{}, kAsanVersionCheckName);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001518 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1519 }
1520 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001521 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001522}
1523
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001524bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1525 // For each NSObject descendant having a +load method, this method is invoked
1526 // by the ObjC runtime before any of the static constructors is called.
1527 // Therefore we need to instrument such methods with a call to __asan_init
1528 // at the beginning in order to initialize our runtime before any access to
1529 // the shadow memory.
1530 // We cannot just ignore these methods, because they may call other
1531 // instrumented functions.
1532 if (F.getName().find(" load]") != std::string::npos) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001533 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00001534 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001535 return true;
1536 }
1537 return false;
1538}
1539
Reid Kleckner2f907552015-07-21 17:40:14 +00001540void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
1541 // Find the one possible call to llvm.localescape and pre-mark allocas passed
1542 // to it as uninteresting. This assumes we haven't started processing allocas
1543 // yet. This check is done up front because iterating the use list in
1544 // isInterestingAlloca would be algorithmically slower.
1545 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
1546
1547 // Try to get the declaration of llvm.localescape. If it's not in the module,
1548 // we can exit early.
1549 if (!F.getParent()->getFunction("llvm.localescape")) return;
1550
1551 // Look for a call to llvm.localescape call in the entry block. It can't be in
1552 // any other block.
1553 for (Instruction &I : F.getEntryBlock()) {
1554 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
1555 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
1556 // We found a call. Mark all the allocas passed in as uninteresting.
1557 for (Value *Arg : II->arg_operands()) {
1558 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
1559 assert(AI && AI->isStaticAlloca() &&
1560 "non-static alloca arg to localescape");
1561 ProcessedAllocas[AI] = false;
1562 }
1563 break;
1564 }
1565 }
1566}
1567
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001568bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001569 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001570 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001571 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001572 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001573
Yury Gribov3ae427d2014-12-01 08:47:58 +00001574 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1575
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001576 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001577 maybeInsertAsanInitAtFunctionEntry(F);
1578
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001579 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001580
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001581 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001582
Reid Kleckner2f907552015-07-21 17:40:14 +00001583 FunctionStateRAII CleanupObj(this);
1584
1585 // We can't instrument allocas used with llvm.localescape. Only static allocas
1586 // can be passed to that intrinsic.
1587 markEscapedLocalAllocas(F);
1588
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001589 // We want to instrument every address only once per basic block (unless there
1590 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001591 SmallSet<Value *, 16> TempsToInstrument;
1592 SmallVector<Instruction *, 16> ToInstrument;
1593 SmallVector<Instruction *, 8> NoReturnCalls;
1594 SmallVector<BasicBlock *, 16> AllBlocks;
1595 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001596 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001597 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001598 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001599 uint64_t TypeSize;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001600
1601 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001602 for (auto &BB : F) {
1603 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001604 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001605 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001606 for (auto &Inst : BB) {
1607 if (LooksLikeCodeInBug11395(&Inst)) return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001608 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1609 &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001610 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001611 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001612 continue; // We've seen this temp in the current BB.
1613 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001614 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001615 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1616 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001617 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001618 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001619 // ok, take it.
1620 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001621 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001622 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001623 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001624 // A call inside BB.
1625 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001626 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001627 }
1628 continue;
1629 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001630 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001631 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001632 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001633 }
1634 }
1635
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001636 bool UseCalls =
1637 CompileKernel ||
1638 (ClInstrumentationWithCallsThreshold >= 0 &&
1639 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001640 const TargetLibraryInfo *TLI =
1641 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001642 const DataLayout &DL = F.getParent()->getDataLayout();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001643 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1644 /*RoundToAlign=*/true);
1645
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001646 // Instrument.
1647 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001648 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001649 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1650 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001651 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001652 instrumentMop(ObjSizeVis, Inst, UseCalls,
1653 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001654 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001655 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001656 }
1657 NumInstrumented++;
1658 }
1659
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001660 FunctionStackPoisoner FSP(F, *this);
1661 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001662
1663 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1664 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001665 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001666 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00001667 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001668 }
1669
Alexey Samsonova02e6642014-05-29 18:40:48 +00001670 for (auto Inst : PointerComparisonsOrSubtracts) {
1671 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001672 NumInstrumented++;
1673 }
1674
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001675 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001676
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001677 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1678
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001679 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001680}
1681
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001682// Workaround for bug 11395: we don't want to instrument stack in functions
1683// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1684// FIXME: remove once the bug 11395 is fixed.
1685bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1686 if (LongSize != 32) return false;
1687 CallInst *CI = dyn_cast<CallInst>(I);
1688 if (!CI || !CI->isInlineAsm()) return false;
1689 if (CI->getNumArgOperands() <= 5) return false;
1690 // We have inline assembly with quite a few arguments.
1691 return true;
1692}
1693
1694void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1695 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001696 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1697 std::string Suffix = itostr(i);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001698 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1699 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1700 IntptrTy, nullptr));
1701 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001702 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1703 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001704 }
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001705 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
David Blaikiea92765c2014-11-14 00:41:42 +00001706 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1707 IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001708 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
David Blaikiea92765c2014-11-14 00:41:42 +00001709 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1710 IntptrTy, IntptrTy, nullptr));
Yury Gribov98b18592015-05-28 07:51:49 +00001711 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1712 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1713 AsanAllocasUnpoisonFunc =
1714 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1715 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001716}
1717
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001718void FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1719 IRBuilder<> &IRB, Value *ShadowBase,
1720 bool DoPoison) {
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001721 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001722 size_t i = 0;
1723 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1724 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1725 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1726 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1727 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1728 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1729 uint64_t Val = 0;
1730 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001731 if (F.getParent()->getDataLayout().isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001732 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1733 else
1734 Val = (Val << 8) | ShadowBytes[i + j];
1735 }
1736 if (!Val) continue;
1737 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1738 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1739 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1740 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001741 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001742 }
1743}
1744
Kostya Serebryany6805de52013-09-10 13:16:56 +00001745// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1746// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1747static int StackMallocSizeClass(uint64_t LocalStackSize) {
1748 assert(LocalStackSize <= kMaxStackMallocSize);
1749 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001750 for (int i = 0;; i++, MaxSize *= 2)
1751 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00001752 llvm_unreachable("impossible LocalStackSize");
1753}
1754
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001755// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1756// We can not use MemSet intrinsic because it may end up calling the actual
1757// memset. Size is a multiple of 8.
1758// Currently this generates 8-byte stores on x86_64; it may be better to
1759// generate wider stores.
1760void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1761 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1762 assert(!(Size % 8));
Gabor Horvathfee04342015-03-16 09:53:42 +00001763
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001764 // kAsanStackAfterReturnMagic is 0xf5.
1765 const uint64_t kAsanStackAfterReturnMagic64 = 0xf5f5f5f5f5f5f5f5ULL;
Gabor Horvathfee04342015-03-16 09:53:42 +00001766
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001767 for (int i = 0; i < Size; i += 8) {
1768 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001769 IRB.CreateStore(
1770 ConstantInt::get(IRB.getInt64Ty(), kAsanStackAfterReturnMagic64),
1771 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001772 }
1773}
1774
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001775PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1776 Value *ValueIfTrue,
1777 Instruction *ThenTerm,
1778 Value *ValueIfFalse) {
1779 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1780 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1781 PHI->addIncoming(ValueIfFalse, CondBlock);
1782 BasicBlock *ThenBlock = ThenTerm->getParent();
1783 PHI->addIncoming(ValueIfTrue, ThenBlock);
1784 return PHI;
1785}
1786
1787Value *FunctionStackPoisoner::createAllocaForLayout(
1788 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
1789 AllocaInst *Alloca;
1790 if (Dynamic) {
1791 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
1792 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
1793 "MyAlloca");
1794 } else {
1795 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
1796 nullptr, "MyAlloca");
1797 assert(Alloca->isStaticAlloca());
1798 }
1799 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1800 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1801 Alloca->setAlignment(FrameAlignment);
1802 return IRB.CreatePointerCast(Alloca, IntptrTy);
1803}
1804
Yury Gribov98b18592015-05-28 07:51:49 +00001805void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
1806 BasicBlock &FirstBB = *F.begin();
1807 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
1808 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
1809 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
1810 DynamicAllocaLayout->setAlignment(32);
1811}
1812
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001813void FunctionStackPoisoner::poisonStack() {
Yury Gribov55441bb2014-11-21 10:29:50 +00001814 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1815
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00001816 // Insert poison calls for lifetime intrinsics for alloca.
1817 bool HavePoisonedAllocas = false;
1818 for (const auto &APC : AllocaPoisonCallVec) {
1819 assert(APC.InsBefore);
1820 assert(APC.AI);
1821 IRBuilder<> IRB(APC.InsBefore);
1822 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1823 HavePoisonedAllocas |= APC.DoPoison;
1824 }
1825
Yury Gribov98b18592015-05-28 07:51:49 +00001826 if (ClInstrumentAllocas && DynamicAllocaVec.size() > 0) {
Yury Gribov55441bb2014-11-21 10:29:50 +00001827 // Handle dynamic allocas.
Yury Gribov98b18592015-05-28 07:51:49 +00001828 createDynamicAllocasInitStorage();
Alexander Potapenkof90556e2015-06-12 11:27:06 +00001829 for (auto &AI : DynamicAllocaVec) handleDynamicAllocaCall(AI);
Yury Gribov98b18592015-05-28 07:51:49 +00001830
1831 unpoisonDynamicAllocas();
Kuba Breckaf5875d32015-02-24 09:47:05 +00001832 }
Yury Gribov55441bb2014-11-21 10:29:50 +00001833
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001834 if (AllocaVec.empty()) return;
Yury Gribov55441bb2014-11-21 10:29:50 +00001835
Kostya Serebryany6805de52013-09-10 13:16:56 +00001836 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00001837 DebugLoc EntryDebugLocation;
1838 if (auto SP = getDISubprogram(&F))
1839 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001840
1841 Instruction *InsBefore = AllocaVec[0];
1842 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001843 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001844
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00001845 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
1846 // debug info is broken, because only entry-block allocas are treated as
1847 // regular stack slots.
1848 auto InsBeforeB = InsBefore->getParent();
1849 assert(InsBeforeB == &F.getEntryBlock());
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001850 for (BasicBlock::iterator I(InsBefore); I != InsBeforeB->end(); ++I)
1851 if (auto *AI = dyn_cast<AllocaInst>(I))
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00001852 if (NonInstrumentedStaticAllocaVec.count(AI) > 0)
1853 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00001854
Reid Kleckner2f907552015-07-21 17:40:14 +00001855 // If we have a call to llvm.localescape, keep it in the entry block.
1856 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
1857
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001858 SmallVector<ASanStackVariableDescription, 16> SVD;
1859 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00001860 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001861 ASanStackVariableDescription D = {AI->getName().data(),
1862 ASan.getAllocaSizeInBytes(AI),
1863 AI->getAlignment(), AI, 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001864 SVD.push_back(D);
1865 }
1866 // Minimal header size (left redzone) is 4 pointers,
1867 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1868 size_t MinHeaderSize = ASan.LongSize / 2;
1869 ASanStackFrameLayout L;
1870 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1871 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1872 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001873 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
1874 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00001875 bool DoDynamicAlloca = ClDynamicAllocaStack;
1876 // Don't do dynamic alloca or stack malloc if:
1877 // 1) There is inline asm: too often it makes assumptions on which registers
1878 // are available.
1879 // 2) There is a returns_twice call (typically setjmp), which is
1880 // optimization-hostile, and doesn't play well with introduced indirect
1881 // register-relative calculation of local variable addresses.
1882 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
1883 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001884
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001885 Value *StaticAlloca =
1886 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
1887
1888 Value *FakeStack;
1889 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001890
1891 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001892 // void *FakeStack = __asan_option_detect_stack_use_after_return
1893 // ? __asan_stack_malloc_N(LocalStackSize)
1894 // : nullptr;
1895 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001896 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1897 kAsanOptionDetectUAR, IRB.getInt32Ty());
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001898 Value *UARIsEnabled =
1899 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1900 Constant::getNullValue(IRB.getInt32Ty()));
1901 Instruction *Term =
1902 SplitBlockAndInsertIfThen(UARIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001903 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001904 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001905 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1906 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1907 Value *FakeStackValue =
1908 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
1909 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001910 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001911 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001912 FakeStack = createPHI(IRB, UARIsEnabled, FakeStackValue, Term,
1913 ConstantInt::get(IntptrTy, 0));
1914
1915 Value *NoFakeStack =
1916 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
1917 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
1918 IRBIf.SetInsertPoint(Term);
1919 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1920 Value *AllocaValue =
1921 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
1922 IRB.SetInsertPoint(InsBefore);
1923 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1924 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
1925 } else {
1926 // void *FakeStack = nullptr;
1927 // void *LocalStackBase = alloca(LocalStackSize);
1928 FakeStack = ConstantInt::get(IntptrTy, 0);
1929 LocalStackBase =
1930 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001931 }
1932
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001933 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001934 for (const auto &Desc : SVD) {
1935 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00001936 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00001937 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001938 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00001939 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001940 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001941 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001942
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001943 // The left-most redzone has enough space for at least 4 pointers.
1944 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001945 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1946 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1947 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001948 // Write the frame description constant to redzone[1].
1949 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001950 IRB.CreateAdd(LocalStackBase,
1951 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
1952 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00001953 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001954 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001955 /*AllowMerging*/ true);
1956 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001957 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001958 // Write the PC to redzone[2].
1959 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001960 IRB.CreateAdd(LocalStackBase,
1961 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
1962 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001963 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001964
1965 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001966 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001967 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001968
Kostya Serebryany530e2072013-12-23 14:15:08 +00001969 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001970 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001971 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001972 // Mark the current frame as retired.
1973 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1974 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001975 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001976 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001977 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00001978 // // In use-after-return mode, poison the whole stack frame.
1979 // if StackMallocIdx <= 4
1980 // // For small sizes inline the whole thing:
1981 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001982 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00001983 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001984 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00001985 // else
1986 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001987 Value *Cmp =
1988 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00001989 TerminatorInst *ThenTerm, *ElseTerm;
1990 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1991
1992 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001993 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001994 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1995 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1996 ClassSize >> Mapping.Scale);
1997 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001998 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001999 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2000 Value *SavedFlagPtr = IRBPoison.CreateLoad(
2001 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2002 IRBPoison.CreateStore(
2003 Constant::getNullValue(IRBPoison.getInt8Ty()),
2004 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2005 } else {
2006 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00002007 IRBPoison.CreateCall(
2008 AsanStackFreeFunc[StackMallocIdx],
2009 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002010 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00002011
2012 IRBuilder<> IRBElse(ElseTerm);
2013 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002014 } else if (HavePoisonedAllocas) {
2015 // If we poisoned some allocas in llvm.lifetime analysis,
2016 // unpoison whole stack frame now.
Alexey Samsonov261177a2012-12-04 01:34:23 +00002017 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany530e2072013-12-23 14:15:08 +00002018 } else {
2019 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002020 }
2021 }
2022
Kostya Serebryany09959942012-10-19 06:20:53 +00002023 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002024 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002025}
Alexey Samsonov261177a2012-12-04 01:34:23 +00002026
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002027void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00002028 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00002029 // For now just insert the call to ASan runtime.
2030 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2031 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002032 IRB.CreateCall(
2033 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2034 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00002035}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002036
2037// Handling llvm.lifetime intrinsics for a given %alloca:
2038// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2039// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2040// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2041// could be poisoned by previous llvm.lifetime.end instruction, as the
2042// variable may go in and out of scope several times, e.g. in loops).
2043// (3) if we poisoned at least one %alloca in a function,
2044// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002045
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002046AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2047 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
2048 // We're intested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00002049 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002050 // See if we've already calculated (or started to calculate) alloca for a
2051 // given value.
2052 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002053 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002054 // Store 0 while we're calculating alloca for value V to avoid
2055 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00002056 AllocaForValue[V] = nullptr;
2057 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002058 if (CastInst *CI = dyn_cast<CastInst>(V))
2059 Res = findAllocaForValue(CI->getOperand(0));
2060 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00002061 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002062 // Allow self-referencing phi-nodes.
2063 if (IncValue == PN) continue;
2064 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2065 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00002066 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2067 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002068 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002069 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002070 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002071 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002072 return Res;
2073}
Yury Gribov55441bb2014-11-21 10:29:50 +00002074
Yury Gribov98b18592015-05-28 07:51:49 +00002075void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00002076 IRBuilder<> IRB(AI);
2077
Yury Gribov55441bb2014-11-21 10:29:50 +00002078 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2079 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2080
2081 Value *Zero = Constant::getNullValue(IntptrTy);
2082 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2083 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00002084
2085 // Since we need to extend alloca with additional memory to locate
2086 // redzones, and OldSize is number of allocated blocks with
2087 // ElementSize size, get allocated memory size in bytes by
2088 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00002089 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002090 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00002091 Value *OldSize =
2092 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2093 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00002094
2095 // PartialSize = OldSize % 32
2096 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2097
2098 // Misalign = kAllocaRzSize - PartialSize;
2099 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2100
2101 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2102 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2103 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2104
2105 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2106 // Align is added to locate left redzone, PartialPadding for possible
2107 // partial redzone and kAllocaRzSize for right redzone respectively.
2108 Value *AdditionalChunkSize = IRB.CreateAdd(
2109 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2110
2111 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2112
2113 // Insert new alloca with new NewSize and Align params.
2114 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2115 NewAlloca->setAlignment(Align);
2116
2117 // NewAddress = Address + Align
2118 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2119 ConstantInt::get(IntptrTy, Align));
2120
Yury Gribov98b18592015-05-28 07:51:49 +00002121 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00002122 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00002123
2124 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2125 // for unpoisoning stuff.
2126 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2127
Yury Gribov55441bb2014-11-21 10:29:50 +00002128 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2129
Yury Gribov98b18592015-05-28 07:51:49 +00002130 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00002131 AI->replaceAllUsesWith(NewAddressPtr);
2132
Yury Gribov98b18592015-05-28 07:51:49 +00002133 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00002134 AI->eraseFromParent();
2135}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002136
2137// isSafeAccess returns true if Addr is always inbounds with respect to its
2138// base object. For example, it is a field access or an array access with
2139// constant inbounds index.
2140bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2141 Value *Addr, uint64_t TypeSize) const {
2142 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2143 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00002144 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002145 int64_t Offset = SizeOffset.second.getSExtValue();
2146 // Three checks are required to ensure safety:
2147 // . Offset >= 0 (since the offset is given from the base ptr)
2148 // . Size >= Offset (unsigned)
2149 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00002150 return Offset >= 0 && Size >= uint64_t(Offset) &&
2151 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002152}