blob: 538cc850295a78bb44802a22babe7361f7115309 [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
Adhemerval Zanellae00b4972015-08-20 18:30:40 +000066// VMA size definition for architecture that support multiple sizes.
67// AArch64 has 3 VMA sizes: 39, 42 and 48.
68#ifndef SANITIZER_AARCH64_VMA
69# define SANITIZER_AARCH64_VMA 39
70#else
71# if SANITIZER_AARCH64_VMA != 39 && SANITIZER_AARCH64_VMA != 42
72# error "invalid SANITIZER_AARCH64_VMA size"
73# endif
74#endif
75
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000076static const uint64_t kDefaultShadowScale = 3;
77static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +000078static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000079static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000080static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +000081static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
Kostya Serebryany4766fe62013-01-23 12:54:55 +000082static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +000083static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +000084static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Adhemerval Zanellae00b4972015-08-20 18:30:40 +000085#if SANITIZER_AARCH64_VMA == 39
Renato Golinaf213722015-02-03 11:20:45 +000086static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Adhemerval Zanellae00b4972015-08-20 18:30:40 +000087#elif SANITIZER_AARCH64_VMA == 42
88static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 39;
89#endif
Kostya Serebryany8baa3862014-02-10 07:37:04 +000090static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
91static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +000092static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000093
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000094static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000095static const size_t kMaxStackMallocSize = 1 << 16; // 64K
96static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
97static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
98
Craig Topperd3a34f82013-07-16 01:17:10 +000099static const char *const kAsanModuleCtorName = "asan.module_ctor";
100static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000101static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +0000102static const char *const kAsanReportErrorTemplate = "__asan_report_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000103static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +0000104static const char *const kAsanUnregisterGlobalsName =
105 "__asan_unregister_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +0000106static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
107static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kuba Brecka45dbffd2015-07-23 10:54:06 +0000108static const char *const kAsanInitName = "__asan_init";
109static const char *const kAsanVersionCheckName =
110 "__asan_version_mismatch_check_v6";
Kostya Serebryany796f6552014-02-27 12:45:36 +0000111static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
112static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +0000113static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000114static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +0000115static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
116static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000117static const char *const kAsanGenPrefix = "__asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000118static const char *const kSanCovGenPrefix = "__sancov_gen_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000119static const char *const kAsanPoisonStackMemoryName =
120 "__asan_poison_stack_memory";
121static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000122 "__asan_unpoison_stack_memory";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000123
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000124static const char *const kAsanOptionDetectUAR =
125 "__asan_option_detect_stack_use_after_return";
126
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000127static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
128static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
Yury Gribov98b18592015-05-28 07:51:49 +0000129
Kostya Serebryany874dae62012-07-16 16:15:40 +0000130// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
131static const size_t kNumberOfAccessSizes = 5;
132
Yury Gribov55441bb2014-11-21 10:29:50 +0000133static const unsigned kAllocaRzSize = 32;
Yury Gribov55441bb2014-11-21 10:29:50 +0000134
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000135// Command-line flags.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000136static cl::opt<bool> ClEnableKasan(
137 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
138 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000139
140// This flag may need to be replaced with -f[no-]asan-reads.
141static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000142 cl::desc("instrument read instructions"),
143 cl::Hidden, cl::init(true));
144static cl::opt<bool> ClInstrumentWrites(
145 "asan-instrument-writes", cl::desc("instrument write instructions"),
146 cl::Hidden, cl::init(true));
147static cl::opt<bool> ClInstrumentAtomics(
148 "asan-instrument-atomics",
149 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
150 cl::init(true));
151static cl::opt<bool> ClAlwaysSlowPath(
152 "asan-always-slow-path",
153 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
154 cl::init(false));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000155// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000156// in any given BB. Normally, this should be set to unlimited (INT_MAX),
157// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
158// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000159static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
160 "asan-max-ins-per-bb", cl::init(10000),
161 cl::desc("maximal number of instructions to instrument in any given BB"),
162 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000163// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000164static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
165 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000166static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000167 cl::desc("Check return-after-free"),
168 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000169// This flag may need to be replaced with -f[no]asan-globals.
170static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000171 cl::desc("Handle global objects"), cl::Hidden,
172 cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000173static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000174 cl::desc("Handle C++ initializer order"),
175 cl::Hidden, cl::init(true));
176static cl::opt<bool> ClInvalidPointerPairs(
177 "asan-detect-invalid-pointer-pair",
178 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
179 cl::init(false));
180static cl::opt<unsigned> ClRealignStack(
181 "asan-realign-stack",
182 cl::desc("Realign stack to the value of this flag (power of two)"),
183 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000184static cl::opt<int> ClInstrumentationWithCallsThreshold(
185 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000186 cl::desc(
187 "If the function being instrumented contains more than "
188 "this number of memory accesses, use callbacks instead of "
189 "inline checks (-1 means never use callbacks)."),
190 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000191static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000192 "asan-memory-access-callback-prefix",
193 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
194 cl::init("__asan_"));
Yury Gribov55441bb2014-11-21 10:29:50 +0000195static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000196 cl::desc("instrument dynamic allocas"),
Alexey Samsonovf4fb5f52015-10-22 20:07:28 +0000197 cl::Hidden, cl::init(true));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000198static cl::opt<bool> ClSkipPromotableAllocas(
199 "asan-skip-promotable-allocas",
200 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
201 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000202
203// These flags allow to change the shadow mapping.
204// The shadow mapping looks like
205// Shadow = (Mem >> scale) + (1 << offset_log)
206static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000207 cl::desc("scale of asan shadow mapping"),
208 cl::Hidden, cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000209
210// Optimization flags. Not user visible, used mostly for testing
211// and benchmarking the tool.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000212static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
213 cl::Hidden, cl::init(true));
214static cl::opt<bool> ClOptSameTemp(
215 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
216 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000217static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000218 cl::desc("Don't instrument scalar globals"),
219 cl::Hidden, cl::init(true));
220static cl::opt<bool> ClOptStack(
221 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
222 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000223
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000224static cl::opt<bool> ClCheckLifetime(
225 "asan-check-lifetime",
226 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"), cl::Hidden,
227 cl::init(false));
Alexey Samsonovdf624522012-11-29 18:14:24 +0000228
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000229static cl::opt<bool> ClDynamicAllocaStack(
230 "asan-stack-dynamic-alloca",
231 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000232 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000233
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000234static cl::opt<uint32_t> ClForceExperiment(
235 "asan-force-experiment",
236 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
237 cl::init(0));
238
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000239// Debug flags.
240static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
241 cl::init(0));
242static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
243 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000244static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
245 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000246static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
247 cl::Hidden, cl::init(-1));
248static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
249 cl::Hidden, cl::init(-1));
250
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000251STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
252STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000253STATISTIC(NumOptimizedAccessesToGlobalVar,
254 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000255STATISTIC(NumOptimizedAccessesToStackVar,
256 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000257
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000258namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000259/// Frontend-provided metadata for source location.
260struct LocationMetadata {
261 StringRef Filename;
262 int LineNo;
263 int ColumnNo;
264
265 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
266
267 bool empty() const { return Filename.empty(); }
268
269 void parse(MDNode *MDN) {
270 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000271 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
272 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000273 LineNo =
274 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
275 ColumnNo =
276 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000277 }
278};
279
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000280/// Frontend-provided metadata for global variables.
281class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000282 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000283 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000284 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000285 LocationMetadata SourceLoc;
286 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000287 bool IsDynInit;
288 bool IsBlacklisted;
289 };
290
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000291 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000292
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000293 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000294 assert(!inited_);
295 inited_ = true;
296 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000297 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000298 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000299 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000300 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000301 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000302 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000303 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000304 // We can already have an entry for GV if it was merged with another
305 // global.
306 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000307 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
308 E.SourceLoc.parse(Loc);
309 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
310 E.Name = Name->getString();
311 ConstantInt *IsDynInit =
312 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000313 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000314 ConstantInt *IsBlacklisted =
315 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000316 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000317 }
318 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000319
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000320 /// Returns metadata entry for a given global.
321 Entry get(GlobalVariable *G) const {
322 auto Pos = Entries.find(G);
323 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000324 }
325
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000326 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000327 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000328 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000329};
330
Alexey Samsonov1345d352013-01-16 13:23:28 +0000331/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000332/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000333struct ShadowMapping {
334 int Scale;
335 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000336 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000337};
338
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000339static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
340 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000341 bool IsAndroid = TargetTriple.isAndroid();
Bob Wilson9868d712014-10-09 05:43:30 +0000342 bool IsIOS = TargetTriple.isiOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000343 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
344 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000345 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
346 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000347 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000348 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
349 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000350 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
351 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000352 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000353 bool IsWindows = TargetTriple.isOSWindows();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000354
355 ShadowMapping Mapping;
356
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000357 if (LongSize == 32) {
Evgeniy Stepanov9cb08f82015-07-17 23:51:18 +0000358 // Android is always PIE, which means that the beginning of the address
359 // space is always available.
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000360 if (IsAndroid)
361 Mapping.Offset = 0;
362 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000363 Mapping.Offset = kMIPS32_ShadowOffset32;
364 else if (IsFreeBSD)
365 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000366 else if (IsIOS)
367 Mapping.Offset = kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000368 else if (IsWindows)
369 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000370 else
371 Mapping.Offset = kDefaultShadowOffset32;
372 } else { // LongSize == 64
373 if (IsPPC64)
374 Mapping.Offset = kPPC64_ShadowOffset64;
375 else if (IsFreeBSD)
376 Mapping.Offset = kFreeBSD_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000377 else if (IsLinux && IsX86_64) {
378 if (IsKasan)
379 Mapping.Offset = kLinuxKasan_ShadowOffset64;
380 else
381 Mapping.Offset = kSmallX86_64ShadowOffset;
382 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000383 Mapping.Offset = kMIPS64_ShadowOffset64;
Renato Golinaf213722015-02-03 11:20:45 +0000384 else if (IsAArch64)
385 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000386 else
387 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000388 }
389
390 Mapping.Scale = kDefaultShadowScale;
391 if (ClMappingScale) {
392 Mapping.Scale = ClMappingScale;
393 }
394
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000395 // OR-ing shadow offset if more efficient (at least on x86) if the offset
396 // is a power of two, but on ppc64 we have to use add since the shadow
397 // offset is not necessary 1/8-th of the address space.
398 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
399
Alexey Samsonov1345d352013-01-16 13:23:28 +0000400 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000401}
402
Alexey Samsonov1345d352013-01-16 13:23:28 +0000403static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000404 // Redzone used for stack and globals is at least 32 bytes.
405 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000406 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000407}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000408
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000409/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000410struct AddressSanitizer : public FunctionPass {
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000411 explicit AddressSanitizer(bool CompileKernel = false)
412 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000413 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
414 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000415 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000416 return "AddressSanitizerFunctionPass";
417 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000418 void getAnalysisUsage(AnalysisUsage &AU) const override {
419 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000420 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000421 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000422 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
423 Type *Ty = AI->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000424 uint64_t SizeInBytes =
425 AI->getModule()->getDataLayout().getTypeAllocSize(Ty);
Anna Zaks8ed1d812015-02-27 03:12:36 +0000426 return SizeInBytes;
427 }
428 /// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000429 bool isInterestingAlloca(AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000430
431 // Check if we have dynamic alloca.
432 bool isDynamicAlloca(AllocaInst &AI) const {
433 return AI.isArrayAllocation() || !AI.isStaticAlloca();
434 }
435
Anna Zaks8ed1d812015-02-27 03:12:36 +0000436 /// If it is an interesting memory access, return the PointerOperand
437 /// and set IsWrite/Alignment. Otherwise return nullptr.
438 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000439 uint64_t *TypeSize, unsigned *Alignment);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000440 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000441 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000442 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000443 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
444 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000445 Value *SizeArgument, bool UseCalls, uint32_t Exp);
446 void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
447 uint32_t TypeSize, bool IsWrite,
448 Value *SizeArgument, bool UseCalls,
449 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000450 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
451 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000452 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000453 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000454 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000455 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000456 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000457 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000458 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000459 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000460 bool doInitialization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000461 static char ID; // Pass identification, replacement for typeid
462
Yury Gribov3ae427d2014-12-01 08:47:58 +0000463 DominatorTree &getDominatorTree() const { return *DT; }
464
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000465 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000466 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000467
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000468 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000469 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000470 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
471 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000472
Reid Kleckner2f907552015-07-21 17:40:14 +0000473 /// Helper to cleanup per-function state.
474 struct FunctionStateRAII {
475 AddressSanitizer *Pass;
476 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
477 assert(Pass->ProcessedAllocas.empty() &&
478 "last pass forgot to clear cache");
479 }
480 ~FunctionStateRAII() { Pass->ProcessedAllocas.clear(); }
481 };
482
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000483 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000484 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000485 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000486 bool CompileKernel;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000487 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000488 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000489 DominatorTree *DT;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000490 Function *AsanCtorFunction = nullptr;
491 Function *AsanInitFunction = nullptr;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000492 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000493 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000494 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
495 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
496 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
497 // This array is indexed by AccessIsWrite and Experiment.
498 Function *AsanErrorCallbackSized[2][2];
499 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000500 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000501 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000502 GlobalsMetadata GlobalsMD;
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000503 DenseMap<AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000504
505 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000506};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000507
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000508class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000509 public:
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000510 explicit AddressSanitizerModule(bool CompileKernel = false)
511 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000512 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000513 static char ID; // Pass identification, replacement for typeid
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000514 const char *getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000515
Kostya Serebryany20a79972012-11-22 03:18:50 +0000516 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000517 void initializeCallbacks(Module &M);
518
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000519 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000520 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000521 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000522 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000523 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000524 return RedzoneSizeForScale(Mapping.Scale);
525 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000526
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000527 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000528 bool CompileKernel;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000529 Type *IntptrTy;
530 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000531 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000532 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000533 Function *AsanPoisonGlobals;
534 Function *AsanUnpoisonGlobals;
535 Function *AsanRegisterGlobals;
536 Function *AsanUnregisterGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000537};
538
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000539// Stack poisoning does not play well with exception handling.
540// When an exception is thrown, we essentially bypass the code
541// that unpoisones the stack. This is why the run-time library has
542// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
543// stack in the interceptor. This however does not work inside the
544// actual function which catches the exception. Most likely because the
545// compiler hoists the load of the shadow value somewhere too high.
546// This causes asan to report a non-existing bug on 453.povray.
547// It sounds like an LLVM bug.
548struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
549 Function &F;
550 AddressSanitizer &ASan;
551 DIBuilder DIB;
552 LLVMContext *C;
553 Type *IntptrTy;
554 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000555 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000556
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000557 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000558 SmallSetVector<AllocaInst *, 16> NonInstrumentedStaticAllocaVec;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000559 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000560 unsigned StackAlignment;
561
Kostya Serebryany6805de52013-09-10 13:16:56 +0000562 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000563 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000564 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000565 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000566
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000567 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
568 struct AllocaPoisonCall {
569 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000570 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000571 uint64_t Size;
572 bool DoPoison;
573 };
574 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
575
Yury Gribov98b18592015-05-28 07:51:49 +0000576 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
577 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
578 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000579 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000580
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000581 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000582 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000583 AllocaForValueMapTy AllocaForValue;
584
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000585 bool HasNonEmptyInlineAsm = false;
586 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000587 std::unique_ptr<CallInst> EmptyInlineAsm;
588
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000589 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000590 : F(F),
591 ASan(ASan),
592 DIB(*F.getParent(), /*AllowUnresolved*/ false),
593 C(ASan.C),
594 IntptrTy(ASan.IntptrTy),
595 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
596 Mapping(ASan.Mapping),
597 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000598 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000599
600 bool runOnFunction() {
601 if (!ClStack) return false;
602 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000603 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000604
Yury Gribov55441bb2014-11-21 10:29:50 +0000605 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000606
607 initializeCallbacks(*F.getParent());
608
609 poisonStack();
610
611 if (ClDebugStack) {
612 DEBUG(dbgs() << F);
613 }
614 return true;
615 }
616
Yury Gribov55441bb2014-11-21 10:29:50 +0000617 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000618 // poisoned red zones around all of them.
619 // Then unpoison everything back before the function returns.
620 void poisonStack();
621
Yury Gribov98b18592015-05-28 07:51:49 +0000622 void createDynamicAllocasInitStorage();
623
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000624 // ----------------------- Visitors.
625 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000626 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000627
Yury Gribov98b18592015-05-28 07:51:49 +0000628 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
629 Value *SavedStack) {
630 IRBuilder<> IRB(InstBefore);
Yury Gribov781bce22015-05-28 08:03:28 +0000631 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000632 {IRB.CreateLoad(DynamicAllocaLayout),
Yury Gribov781bce22015-05-28 08:03:28 +0000633 IRB.CreatePtrToInt(SavedStack, IntptrTy)});
Yury Gribov98b18592015-05-28 07:51:49 +0000634 }
635
Yury Gribov55441bb2014-11-21 10:29:50 +0000636 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000637 void unpoisonDynamicAllocas() {
638 for (auto &Ret : RetVec)
639 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000640
Yury Gribov98b18592015-05-28 07:51:49 +0000641 for (auto &StackRestoreInst : StackRestoreVec)
642 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
643 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000644 }
645
Yury Gribov55441bb2014-11-21 10:29:50 +0000646 // Deploy and poison redzones around dynamic alloca call. To do this, we
647 // should replace this call with another one with changed parameters and
648 // replace all its uses with new address, so
649 // addr = alloca type, old_size, align
650 // is replaced by
651 // new_size = (old_size + additional_size) * sizeof(type)
652 // tmp = alloca i8, new_size, max(align, 32)
653 // addr = tmp + 32 (first 32 bytes are for the left redzone).
654 // Additional_size is added to make new memory allocation contain not only
655 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000656 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000657
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000658 /// \brief Collect Alloca instructions we want (and can) handle.
659 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000660 if (!ASan.isInterestingAlloca(AI)) {
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000661 if (AI.isStaticAlloca()) NonInstrumentedStaticAllocaVec.insert(&AI);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000662 return;
663 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000664
665 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Yury Gribov98b18592015-05-28 07:51:49 +0000666 if (ASan.isDynamicAlloca(AI))
667 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000668 else
669 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000670 }
671
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000672 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
673 /// errors.
674 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000675 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000676 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000677 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Yury Gribov98b18592015-05-28 07:51:49 +0000678 if (!ClCheckLifetime) return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000679 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000680 return;
681 // Found lifetime intrinsic, add ASan instrumentation if necessary.
682 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
683 // If size argument is undefined, don't do anything.
684 if (Size->isMinusOne()) return;
685 // Check that size doesn't saturate uint64_t and can
686 // be stored in IntptrTy.
687 const uint64_t SizeValue = Size->getValue().getLimitedValue();
688 if (SizeValue == ~0ULL ||
689 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
690 return;
691 // Find alloca instruction that corresponds to llvm.lifetime argument.
692 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
693 if (!AI) return;
694 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000695 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000696 AllocaPoisonCallVec.push_back(APC);
697 }
698
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000699 void visitCallSite(CallSite CS) {
700 Instruction *I = CS.getInstruction();
701 if (CallInst *CI = dyn_cast<CallInst>(I)) {
702 HasNonEmptyInlineAsm |=
703 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
704 HasReturnsTwiceCall |= CI->canReturnTwice();
705 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000706 }
707
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000708 // ---------------------- Helpers.
709 void initializeCallbacks(Module &M);
710
Yury Gribov3ae427d2014-12-01 08:47:58 +0000711 bool doesDominateAllExits(const Instruction *I) const {
712 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000713 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000714 }
715 return true;
716 }
717
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000718 /// Finds alloca where the value comes from.
719 AllocaInst *findAllocaForValue(Value *V);
Craig Topper3af97222014-08-27 05:25:00 +0000720 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000721 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000722 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000723
724 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
725 int Size);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000726 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
727 bool Dynamic);
728 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
729 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000730};
731
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000732} // anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000733
734char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000735INITIALIZE_PASS_BEGIN(
736 AddressSanitizer, "asan",
737 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
738 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000739INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +0000740INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000741INITIALIZE_PASS_END(
742 AddressSanitizer, "asan",
743 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
744 false)
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000745FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel) {
746 return new AddressSanitizer(CompileKernel);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000747}
748
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000749char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000750INITIALIZE_PASS(
751 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000752 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000753 "ModulePass",
754 false, false)
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000755ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel) {
756 return new AddressSanitizerModule(CompileKernel);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000757}
758
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000759static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000760 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000761 assert(Res < kNumberOfAccessSizes);
762 return Res;
763}
764
Bill Wendling58f8cef2013-08-06 22:52:42 +0000765// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000766static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
767 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000768 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000769 // We use private linkage for module-local strings. If they can be merged
770 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000771 GlobalVariable *GV =
772 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000773 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000774 if (AllowMerging) GV->setUnnamedAddr(true);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000775 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
776 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000777}
778
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000779/// \brief Create a global describing a source location.
780static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
781 LocationMetadata MD) {
782 Constant *LocData[] = {
783 createPrivateGlobalForString(M, MD.Filename, true),
784 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
785 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
786 };
787 auto LocStruct = ConstantStruct::getAnon(LocData);
788 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
789 GlobalValue::PrivateLinkage, LocStruct,
790 kAsanGenPrefix);
791 GV->setUnnamedAddr(true);
792 return GV;
793}
794
Kostya Serebryany139a9372012-11-20 14:16:08 +0000795static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000796 return G->getName().find(kAsanGenPrefix) == 0 ||
797 G->getName().find(kSanCovGenPrefix) == 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000798}
799
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000800Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
801 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000802 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000803 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000804 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000805 if (Mapping.OrShadowOffset)
806 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
807 else
808 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000809}
810
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000811// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000812void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
813 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000814 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000815 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000816 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +0000817 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
818 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
819 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000820 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000821 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000822 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +0000823 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
824 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
825 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000826 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000827 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000828}
829
Anna Zaks8ed1d812015-02-27 03:12:36 +0000830/// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000831bool AddressSanitizer::isInterestingAlloca(AllocaInst &AI) {
832 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
833
834 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
835 return PreviouslySeenAllocaInfo->getSecond();
836
Yury Gribov98b18592015-05-28 07:51:49 +0000837 bool IsInteresting =
838 (AI.getAllocatedType()->isSized() &&
839 // alloca() may be called with 0 size, ignore it.
840 getAllocaSizeInBytes(&AI) > 0 &&
841 // We are only interested in allocas not promotable to registers.
842 // Promotable allocas are common under -O0.
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +0000843 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)));
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000844
845 ProcessedAllocas[&AI] = IsInteresting;
846 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000847}
848
849/// If I is an interesting memory access, return the PointerOperand
850/// and set IsWrite/Alignment. Otherwise return nullptr.
851Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
852 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000853 uint64_t *TypeSize,
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000854 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000855 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000856 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000857
858 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000859 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000860 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000861 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000862 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000863 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000864 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000865 PtrOperand = LI->getPointerOperand();
866 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000867 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000868 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000869 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000870 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000871 PtrOperand = SI->getPointerOperand();
872 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000873 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000874 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000875 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000876 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000877 PtrOperand = RMW->getPointerOperand();
878 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000879 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000880 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000881 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000882 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000883 PtrOperand = XCHG->getPointerOperand();
Kostya Serebryany90241602012-05-30 09:04:06 +0000884 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000885
886 // Treat memory accesses to promotable allocas as non-interesting since they
887 // will not cause memory violations. This greatly speeds up the instrumented
888 // executable at -O0.
889 if (ClSkipPromotableAllocas)
890 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
891 return isInterestingAlloca(*AI) ? AI : nullptr;
892
893 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000894}
895
Kostya Serebryany796f6552014-02-27 12:45:36 +0000896static bool isPointerOperand(Value *V) {
897 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
898}
899
900// This is a rough heuristic; it may cause both false positives and
901// false negatives. The proper implementation requires cooperation with
902// the frontend.
903static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
904 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000905 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000906 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000907 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000908 } else {
909 return false;
910 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +0000911 return isPointerOperand(I->getOperand(0)) &&
912 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +0000913}
914
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000915bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
916 // If a global variable does not have dynamic initialization we don't
917 // have to instrument it. However, if a global does not have initializer
918 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000919 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000920}
921
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000922void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
923 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +0000924 IRBuilder<> IRB(I);
925 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
926 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
927 for (int i = 0; i < 2; i++) {
928 if (Param[i]->getType()->isPointerTy())
929 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
930 }
David Blaikieff6409d2015-05-18 22:13:54 +0000931 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000932}
933
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000934void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000935 Instruction *I, bool UseCalls,
936 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +0000937 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000938 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000939 uint64_t TypeSize = 0;
940 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +0000941 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000942
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000943 // Optimization experiments.
944 // The experiments can be used to evaluate potential optimizations that remove
945 // instrumentation (assess false negatives). Instead of completely removing
946 // some instrumentation, you set Exp to a non-zero value (mask of optimization
947 // experiments that want to remove instrumentation of this instruction).
948 // If Exp is non-zero, this pass will emit special calls into runtime
949 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
950 // make runtime terminate the program in a special way (with a different
951 // exit status). Then you run the new compiler on a buggy corpus, collect
952 // the special terminations (ideally, you don't see them at all -- no false
953 // negatives) and make the decision on the optimization.
954 uint32_t Exp = ClForceExperiment;
955
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000956 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000957 // If initialization order checking is disabled, a simple access to a
958 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000959 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000960 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000961 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
962 NumOptimizedAccessesToGlobalVar++;
963 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000964 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000965 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000966
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000967 if (ClOpt && ClOptStack) {
968 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000969 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000970 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
971 NumOptimizedAccessesToStackVar++;
972 return;
973 }
974 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000975
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000976 if (IsWrite)
977 NumInstrumentedWrites++;
978 else
979 NumInstrumentedReads++;
980
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000981 unsigned Granularity = 1 << Mapping.Scale;
982 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
983 // if the data is properly aligned.
984 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
985 TypeSize == 128) &&
986 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000987 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
988 Exp);
989 instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
990 UseCalls, Exp);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000991}
992
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000993Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
994 Value *Addr, bool IsWrite,
995 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000996 Value *SizeArgument,
997 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000998 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000999 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1000 CallInst *Call = nullptr;
1001 if (SizeArgument) {
1002 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001003 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1004 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001005 else
David Blaikieff6409d2015-05-18 22:13:54 +00001006 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1007 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001008 } else {
1009 if (Exp == 0)
1010 Call =
1011 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1012 else
David Blaikieff6409d2015-05-18 22:13:54 +00001013 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1014 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001015 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001016
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001017 // We don't do Call->setDoesNotReturn() because the BB already has
1018 // UnreachableInst at the end.
1019 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001020 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001021 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001022}
1023
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001024Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001025 Value *ShadowValue,
1026 uint32_t TypeSize) {
Alexey Samsonov1345d352013-01-16 13:23:28 +00001027 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001028 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001029 Value *LastAccessedByte =
1030 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001031 // (Addr & (Granularity - 1)) + size - 1
1032 if (TypeSize / 8 > 1)
1033 LastAccessedByte = IRB.CreateAdd(
1034 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1035 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001036 LastAccessedByte =
1037 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001038 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1039 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1040}
1041
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001042void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001043 Instruction *InsertBefore, Value *Addr,
1044 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001045 Value *SizeArgument, bool UseCalls,
1046 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001047 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001048 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001049 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1050
1051 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001052 if (Exp == 0)
1053 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1054 AddrLong);
1055 else
David Blaikieff6409d2015-05-18 22:13:54 +00001056 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1057 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001058 return;
1059 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001060
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001061 Type *ShadowTy =
1062 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001063 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1064 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1065 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001066 Value *ShadowValue =
1067 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001068
1069 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Alexey Samsonov1345d352013-01-16 13:23:28 +00001070 size_t Granularity = 1 << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001071 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001072
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001073 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001074 // We use branch weights for the slow path check, to indicate that the slow
1075 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001076 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1077 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001078 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001079 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001080 IRB.SetInsertPoint(CheckTerm);
1081 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001082 BasicBlock *CrashBlock =
1083 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001084 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001085 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1086 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001087 } else {
Evgeniy Stepanova9164e92013-12-19 13:29:56 +00001088 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001089 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001090
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001091 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001092 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001093 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001094}
1095
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001096// Instrument unusual size or unusual alignment.
1097// We can not do it with a single check, so we do 1-byte check for the first
1098// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1099// to report the actual access size.
1100void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1101 Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1102 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1103 IRBuilder<> IRB(I);
1104 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1105 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1106 if (UseCalls) {
1107 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001108 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1109 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001110 else
David Blaikieff6409d2015-05-18 22:13:54 +00001111 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1112 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001113 } else {
1114 Value *LastByte = IRB.CreateIntToPtr(
1115 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1116 Addr->getType());
1117 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1118 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1119 }
1120}
1121
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001122void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1123 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001124 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001125 IRBuilder<> IRB(&GlobalInit.front(),
1126 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001127
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001128 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001129 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1130 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001131
1132 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001133 for (auto &BB : GlobalInit.getBasicBlockList())
1134 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001135 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001136}
1137
1138void AddressSanitizerModule::createInitializerPoisonCalls(
1139 Module &M, GlobalValue *ModuleName) {
1140 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1141
1142 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1143 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001144 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001145 ConstantStruct *CS = cast<ConstantStruct>(OP);
1146
1147 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001148 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001149 if (F->getName() == kAsanModuleCtorName) continue;
1150 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1151 // Don't instrument CTORs that will run before asan.module_ctor.
1152 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1153 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001154 }
1155 }
1156}
1157
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001158bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001159 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001160 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001161
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001162 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001163 if (!Ty->isSized()) return false;
1164 if (!G->hasInitializer()) return false;
Kostya Serebryany139a9372012-11-20 14:16:08 +00001165 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001166 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001167 // Don't handle ODR linkage types and COMDATs since other modules may be built
1168 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001169 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1170 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1171 G->getLinkage() != GlobalVariable::InternalLinkage)
1172 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001173 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001174 // Two problems with thread-locals:
1175 // - The address of the main thread's copy can't be computed at link-time.
1176 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001177 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001178 // For now, just ignore this Global if the alignment is large.
1179 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001180
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001181 if (G->hasSection()) {
1182 StringRef Section(G->getSection());
Kuba Brecka086e34b2014-12-05 21:32:46 +00001183
Anna Zaks11904602015-06-09 00:58:08 +00001184 // Globals from llvm.metadata aren't emitted, do not instrument them.
1185 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001186 // Do not instrument globals from special LLVM sections.
1187 if (Section.find("__llvm") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001188
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001189 // Do not instrument function pointers to initialization and termination
1190 // routines: dynamic linker will not properly handle redzones.
1191 if (Section.startswith(".preinit_array") ||
1192 Section.startswith(".init_array") ||
1193 Section.startswith(".fini_array")) {
1194 return false;
1195 }
1196
Anna Zaks11904602015-06-09 00:58:08 +00001197 // Callbacks put into the CRT initializer/terminator sections
1198 // should not be instrumented.
1199 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1200 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1201 if (Section.startswith(".CRT")) {
1202 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1203 return false;
1204 }
1205
Kuba Brecka1001bb52014-12-05 22:19:18 +00001206 if (TargetTriple.isOSBinFormatMachO()) {
1207 StringRef ParsedSegment, ParsedSection;
1208 unsigned TAA = 0, StubSize = 0;
1209 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001210 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1211 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001212 if (!ErrorCode.empty()) {
Anna Zaks11904602015-06-09 00:58:08 +00001213 assert(false && "Invalid section specifier.");
1214 return false;
Kuba Brecka1001bb52014-12-05 22:19:18 +00001215 }
1216
1217 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1218 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1219 // them.
1220 if (ParsedSegment == "__OBJC" ||
1221 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1222 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1223 return false;
1224 }
1225 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1226 // Constant CFString instances are compiled in the following way:
1227 // -- the string buffer is emitted into
1228 // __TEXT,__cstring,cstring_literals
1229 // -- the constant NSConstantString structure referencing that buffer
1230 // is placed into __DATA,__cfstring
1231 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1232 // Moreover, it causes the linker to crash on OS X 10.7
1233 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1234 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1235 return false;
1236 }
1237 // The linker merges the contents of cstring_literals and removes the
1238 // trailing zeroes.
1239 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1240 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1241 return false;
1242 }
1243 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001244 }
1245
1246 return true;
1247}
1248
Alexey Samsonov788381b2012-12-25 12:28:20 +00001249void AddressSanitizerModule::initializeCallbacks(Module &M) {
1250 IRBuilder<> IRB(*C);
1251 // Declare our poisoning and unpoisoning functions.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001252 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001253 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001254 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001255 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001256 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001257 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1258 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001259 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001260 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001261 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001262 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001263 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1264 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001265 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1266}
1267
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001268// This function replaces all global variables with new variables that have
1269// trailing redzones. It also creates a function that poisons
1270// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001271bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001272 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001273
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001274 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1275
Alexey Samsonova02e6642014-05-29 18:40:48 +00001276 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001277 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001278 }
1279
1280 size_t n = GlobalsToChange.size();
1281 if (n == 0) return false;
1282
1283 // A global is described by a structure
1284 // size_t beg;
1285 // size_t size;
1286 // size_t size_with_redzone;
1287 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001288 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001289 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001290 // void *source_location;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001291 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001292 StructType *GlobalStructTy =
1293 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001294 IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001295 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001296
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001297 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001298
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001299 // We shouldn't merge same module names, as this string serves as unique
1300 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001301 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001302 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001303
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001304 auto &DL = M.getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001305 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001306 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001307 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001308
1309 auto MD = GlobalsMD.get(G);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001310 // Create string holding the global name (use global name from metadata
1311 // if it's available, otherwise just write the name of global variable).
1312 GlobalVariable *Name = createPrivateGlobalForString(
1313 M, MD.Name.empty() ? G->getName() : MD.Name,
1314 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001315
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001316 PointerType *PtrTy = cast<PointerType>(G->getType());
1317 Type *Ty = PtrTy->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001318 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001319 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001320 // MinRZ <= RZ <= kMaxGlobalRedzone
1321 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001322 uint64_t RZ = std::max(
1323 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001324 uint64_t RightRedzoneSize = RZ;
1325 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001326 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001327 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001328 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1329
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001330 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001331 Constant *NewInitializer =
1332 ConstantStruct::get(NewTy, G->getInitializer(),
1333 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001334
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001335 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001336 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1337 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1338 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001339 GlobalVariable *NewGlobal =
1340 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1341 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001342 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001343 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001344
1345 Value *Indices2[2];
1346 Indices2[0] = IRB.getInt32(0);
1347 Indices2[1] = IRB.getInt32(0);
1348
1349 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001350 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001351 NewGlobal->takeName(G);
1352 G->eraseFromParent();
1353
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001354 Constant *SourceLoc;
1355 if (!MD.SourceLoc.empty()) {
1356 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1357 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1358 } else {
1359 SourceLoc = ConstantInt::get(IntptrTy, 0);
1360 }
1361
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001362 Initializers[i] = ConstantStruct::get(
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001363 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001364 ConstantInt::get(IntptrTy, SizeInBytes),
1365 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1366 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001367 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001368 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001369
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001370 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001371
Kostya Serebryany20343352012-10-17 13:40:06 +00001372 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001373 }
1374
1375 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1376 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001377 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001378 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1379
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001380 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001381 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001382 createInitializerPoisonCalls(M, ModuleName);
David Blaikieff6409d2015-05-18 22:13:54 +00001383 IRB.CreateCall(AsanRegisterGlobals,
1384 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1385 ConstantInt::get(IntptrTy, n)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001386
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001387 // We also need to unregister globals at the end, e.g. when a shared library
1388 // gets closed.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001389 Function *AsanDtorFunction =
1390 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1391 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001392 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1393 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
David Blaikieff6409d2015-05-18 22:13:54 +00001394 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1395 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1396 ConstantInt::get(IntptrTy, n)});
Alexey Samsonov1f647502014-05-29 01:10:14 +00001397 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001398
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001399 DEBUG(dbgs() << M);
1400 return true;
1401}
1402
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001403bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001404 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001405 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001406 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001407 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001408 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001409 initializeCallbacks(M);
1410
1411 bool Changed = false;
1412
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001413 // TODO(glider): temporarily disabled globals instrumentation for KASan.
1414 if (ClGlobals && !CompileKernel) {
1415 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1416 assert(CtorFunc);
1417 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1418 Changed |= InstrumentGlobals(IRB, M);
1419 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001420
1421 return Changed;
1422}
1423
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001424void AddressSanitizer::initializeCallbacks(Module &M) {
1425 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001426 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001427 // IsWrite, TypeSize and Exp are encoded in the function name.
1428 for (int Exp = 0; Exp < 2; Exp++) {
1429 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1430 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1431 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001432 const std::string SuffixStr = CompileKernel ? "N" : "_n";
1433 const std::string EndingStr = CompileKernel ? "_noabort" : "";
Craig Toppere3dcce92015-08-01 22:20:21 +00001434 Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001435 // TODO(glider): for KASan builds add _noabort to error reporting
1436 // functions and make them actually noabort (remove the UnreachableInst).
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001437 AsanErrorCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001438 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001439 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001440 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1441 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001442 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001443 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001444 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1445 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1446 AccessSizeIndex++) {
1447 const std::string Suffix = TypeStr + itostr(1 << AccessSizeIndex);
1448 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001449 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001450 kAsanReportErrorTemplate + ExpStr + Suffix,
1451 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001452 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001453 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001454 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1455 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001456 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001457 }
1458 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00001459
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001460 const std::string MemIntrinCallbackPrefix =
1461 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001462 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001463 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001464 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001465 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001466 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001467 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001468 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001469 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001470 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001471
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001472 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001473 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001474
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001475 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001476 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001477 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001478 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001479 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1480 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1481 StringRef(""), StringRef(""),
1482 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001483}
1484
1485// virtual
1486bool AddressSanitizer::doInitialization(Module &M) {
1487 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001488
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001489 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001490
1491 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001492 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001493 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001494 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001495
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001496 if (!CompileKernel) {
1497 std::tie(AsanCtorFunction, AsanInitFunction) =
Kuba Brecka45dbffd2015-07-23 10:54:06 +00001498 createSanitizerCtorAndInitFunctions(
1499 M, kAsanModuleCtorName, kAsanInitName,
1500 /*InitArgTypes=*/{}, /*InitArgs=*/{}, kAsanVersionCheckName);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001501 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1502 }
1503 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001504 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001505}
1506
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001507bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1508 // For each NSObject descendant having a +load method, this method is invoked
1509 // by the ObjC runtime before any of the static constructors is called.
1510 // Therefore we need to instrument such methods with a call to __asan_init
1511 // at the beginning in order to initialize our runtime before any access to
1512 // the shadow memory.
1513 // We cannot just ignore these methods, because they may call other
1514 // instrumented functions.
1515 if (F.getName().find(" load]") != std::string::npos) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001516 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00001517 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001518 return true;
1519 }
1520 return false;
1521}
1522
Reid Kleckner2f907552015-07-21 17:40:14 +00001523void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
1524 // Find the one possible call to llvm.localescape and pre-mark allocas passed
1525 // to it as uninteresting. This assumes we haven't started processing allocas
1526 // yet. This check is done up front because iterating the use list in
1527 // isInterestingAlloca would be algorithmically slower.
1528 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
1529
1530 // Try to get the declaration of llvm.localescape. If it's not in the module,
1531 // we can exit early.
1532 if (!F.getParent()->getFunction("llvm.localescape")) return;
1533
1534 // Look for a call to llvm.localescape call in the entry block. It can't be in
1535 // any other block.
1536 for (Instruction &I : F.getEntryBlock()) {
1537 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
1538 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
1539 // We found a call. Mark all the allocas passed in as uninteresting.
1540 for (Value *Arg : II->arg_operands()) {
1541 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
1542 assert(AI && AI->isStaticAlloca() &&
1543 "non-static alloca arg to localescape");
1544 ProcessedAllocas[AI] = false;
1545 }
1546 break;
1547 }
1548 }
1549}
1550
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001551bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001552 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001553 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001554 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001555 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001556
Yury Gribov3ae427d2014-12-01 08:47:58 +00001557 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1558
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001559 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001560 maybeInsertAsanInitAtFunctionEntry(F);
1561
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001562 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001563
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001564 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001565
Reid Kleckner2f907552015-07-21 17:40:14 +00001566 FunctionStateRAII CleanupObj(this);
1567
1568 // We can't instrument allocas used with llvm.localescape. Only static allocas
1569 // can be passed to that intrinsic.
1570 markEscapedLocalAllocas(F);
1571
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001572 // We want to instrument every address only once per basic block (unless there
1573 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001574 SmallSet<Value *, 16> TempsToInstrument;
1575 SmallVector<Instruction *, 16> ToInstrument;
1576 SmallVector<Instruction *, 8> NoReturnCalls;
1577 SmallVector<BasicBlock *, 16> AllBlocks;
1578 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001579 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001580 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001581 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001582 uint64_t TypeSize;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001583
1584 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001585 for (auto &BB : F) {
1586 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001587 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001588 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001589 for (auto &Inst : BB) {
1590 if (LooksLikeCodeInBug11395(&Inst)) return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001591 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1592 &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001593 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001594 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001595 continue; // We've seen this temp in the current BB.
1596 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001597 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001598 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1599 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001600 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001601 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001602 // ok, take it.
1603 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001604 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001605 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001606 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001607 // A call inside BB.
1608 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001609 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001610 }
1611 continue;
1612 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001613 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001614 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001615 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001616 }
1617 }
1618
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001619 bool UseCalls =
1620 CompileKernel ||
1621 (ClInstrumentationWithCallsThreshold >= 0 &&
1622 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001623 const TargetLibraryInfo *TLI =
1624 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001625 const DataLayout &DL = F.getParent()->getDataLayout();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001626 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1627 /*RoundToAlign=*/true);
1628
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001629 // Instrument.
1630 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001631 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001632 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1633 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001634 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001635 instrumentMop(ObjSizeVis, Inst, UseCalls,
1636 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001637 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001638 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001639 }
1640 NumInstrumented++;
1641 }
1642
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001643 FunctionStackPoisoner FSP(F, *this);
1644 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001645
1646 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1647 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001648 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001649 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00001650 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001651 }
1652
Alexey Samsonova02e6642014-05-29 18:40:48 +00001653 for (auto Inst : PointerComparisonsOrSubtracts) {
1654 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001655 NumInstrumented++;
1656 }
1657
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001658 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001659
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001660 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1661
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001662 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001663}
1664
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001665// Workaround for bug 11395: we don't want to instrument stack in functions
1666// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1667// FIXME: remove once the bug 11395 is fixed.
1668bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1669 if (LongSize != 32) return false;
1670 CallInst *CI = dyn_cast<CallInst>(I);
1671 if (!CI || !CI->isInlineAsm()) return false;
1672 if (CI->getNumArgOperands() <= 5) return false;
1673 // We have inline assembly with quite a few arguments.
1674 return true;
1675}
1676
1677void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1678 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001679 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1680 std::string Suffix = itostr(i);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001681 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1682 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1683 IntptrTy, nullptr));
1684 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001685 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1686 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001687 }
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001688 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
David Blaikiea92765c2014-11-14 00:41:42 +00001689 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1690 IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001691 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
David Blaikiea92765c2014-11-14 00:41:42 +00001692 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1693 IntptrTy, IntptrTy, nullptr));
Yury Gribov98b18592015-05-28 07:51:49 +00001694 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1695 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1696 AsanAllocasUnpoisonFunc =
1697 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1698 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001699}
1700
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001701void FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1702 IRBuilder<> &IRB, Value *ShadowBase,
1703 bool DoPoison) {
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001704 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001705 size_t i = 0;
1706 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1707 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1708 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1709 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1710 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1711 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1712 uint64_t Val = 0;
1713 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001714 if (F.getParent()->getDataLayout().isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001715 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1716 else
1717 Val = (Val << 8) | ShadowBytes[i + j];
1718 }
1719 if (!Val) continue;
1720 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1721 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1722 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1723 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001724 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001725 }
1726}
1727
Kostya Serebryany6805de52013-09-10 13:16:56 +00001728// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1729// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1730static int StackMallocSizeClass(uint64_t LocalStackSize) {
1731 assert(LocalStackSize <= kMaxStackMallocSize);
1732 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001733 for (int i = 0;; i++, MaxSize *= 2)
1734 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00001735 llvm_unreachable("impossible LocalStackSize");
1736}
1737
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001738// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1739// We can not use MemSet intrinsic because it may end up calling the actual
1740// memset. Size is a multiple of 8.
1741// Currently this generates 8-byte stores on x86_64; it may be better to
1742// generate wider stores.
1743void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1744 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1745 assert(!(Size % 8));
Gabor Horvathfee04342015-03-16 09:53:42 +00001746
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001747 // kAsanStackAfterReturnMagic is 0xf5.
1748 const uint64_t kAsanStackAfterReturnMagic64 = 0xf5f5f5f5f5f5f5f5ULL;
Gabor Horvathfee04342015-03-16 09:53:42 +00001749
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001750 for (int i = 0; i < Size; i += 8) {
1751 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001752 IRB.CreateStore(
1753 ConstantInt::get(IRB.getInt64Ty(), kAsanStackAfterReturnMagic64),
1754 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001755 }
1756}
1757
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001758PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1759 Value *ValueIfTrue,
1760 Instruction *ThenTerm,
1761 Value *ValueIfFalse) {
1762 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1763 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1764 PHI->addIncoming(ValueIfFalse, CondBlock);
1765 BasicBlock *ThenBlock = ThenTerm->getParent();
1766 PHI->addIncoming(ValueIfTrue, ThenBlock);
1767 return PHI;
1768}
1769
1770Value *FunctionStackPoisoner::createAllocaForLayout(
1771 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
1772 AllocaInst *Alloca;
1773 if (Dynamic) {
1774 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
1775 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
1776 "MyAlloca");
1777 } else {
1778 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
1779 nullptr, "MyAlloca");
1780 assert(Alloca->isStaticAlloca());
1781 }
1782 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1783 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1784 Alloca->setAlignment(FrameAlignment);
1785 return IRB.CreatePointerCast(Alloca, IntptrTy);
1786}
1787
Yury Gribov98b18592015-05-28 07:51:49 +00001788void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
1789 BasicBlock &FirstBB = *F.begin();
1790 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
1791 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
1792 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
1793 DynamicAllocaLayout->setAlignment(32);
1794}
1795
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001796void FunctionStackPoisoner::poisonStack() {
Yury Gribov55441bb2014-11-21 10:29:50 +00001797 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1798
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00001799 // Insert poison calls for lifetime intrinsics for alloca.
1800 bool HavePoisonedAllocas = false;
1801 for (const auto &APC : AllocaPoisonCallVec) {
1802 assert(APC.InsBefore);
1803 assert(APC.AI);
1804 IRBuilder<> IRB(APC.InsBefore);
1805 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1806 HavePoisonedAllocas |= APC.DoPoison;
1807 }
1808
Yury Gribov98b18592015-05-28 07:51:49 +00001809 if (ClInstrumentAllocas && DynamicAllocaVec.size() > 0) {
Yury Gribov55441bb2014-11-21 10:29:50 +00001810 // Handle dynamic allocas.
Yury Gribov98b18592015-05-28 07:51:49 +00001811 createDynamicAllocasInitStorage();
Alexander Potapenkof90556e2015-06-12 11:27:06 +00001812 for (auto &AI : DynamicAllocaVec) handleDynamicAllocaCall(AI);
Yury Gribov98b18592015-05-28 07:51:49 +00001813
1814 unpoisonDynamicAllocas();
Kuba Breckaf5875d32015-02-24 09:47:05 +00001815 }
Yury Gribov55441bb2014-11-21 10:29:50 +00001816
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001817 if (AllocaVec.empty()) return;
Yury Gribov55441bb2014-11-21 10:29:50 +00001818
Kostya Serebryany6805de52013-09-10 13:16:56 +00001819 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00001820 DebugLoc EntryDebugLocation;
1821 if (auto SP = getDISubprogram(&F))
1822 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001823
1824 Instruction *InsBefore = AllocaVec[0];
1825 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001826 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001827
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00001828 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
1829 // debug info is broken, because only entry-block allocas are treated as
1830 // regular stack slots.
1831 auto InsBeforeB = InsBefore->getParent();
1832 assert(InsBeforeB == &F.getEntryBlock());
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001833 for (BasicBlock::iterator I(InsBefore); I != InsBeforeB->end(); ++I)
1834 if (auto *AI = dyn_cast<AllocaInst>(I))
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00001835 if (NonInstrumentedStaticAllocaVec.count(AI) > 0)
1836 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00001837
Reid Kleckner2f907552015-07-21 17:40:14 +00001838 // If we have a call to llvm.localescape, keep it in the entry block.
1839 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
1840
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001841 SmallVector<ASanStackVariableDescription, 16> SVD;
1842 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00001843 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001844 ASanStackVariableDescription D = {AI->getName().data(),
1845 ASan.getAllocaSizeInBytes(AI),
1846 AI->getAlignment(), AI, 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001847 SVD.push_back(D);
1848 }
1849 // Minimal header size (left redzone) is 4 pointers,
1850 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1851 size_t MinHeaderSize = ASan.LongSize / 2;
1852 ASanStackFrameLayout L;
1853 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1854 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1855 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001856 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
1857 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00001858 bool DoDynamicAlloca = ClDynamicAllocaStack;
1859 // Don't do dynamic alloca or stack malloc if:
1860 // 1) There is inline asm: too often it makes assumptions on which registers
1861 // are available.
1862 // 2) There is a returns_twice call (typically setjmp), which is
1863 // optimization-hostile, and doesn't play well with introduced indirect
1864 // register-relative calculation of local variable addresses.
1865 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
1866 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001867
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001868 Value *StaticAlloca =
1869 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
1870
1871 Value *FakeStack;
1872 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001873
1874 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001875 // void *FakeStack = __asan_option_detect_stack_use_after_return
1876 // ? __asan_stack_malloc_N(LocalStackSize)
1877 // : nullptr;
1878 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001879 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1880 kAsanOptionDetectUAR, IRB.getInt32Ty());
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001881 Value *UARIsEnabled =
1882 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1883 Constant::getNullValue(IRB.getInt32Ty()));
1884 Instruction *Term =
1885 SplitBlockAndInsertIfThen(UARIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001886 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001887 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001888 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1889 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1890 Value *FakeStackValue =
1891 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
1892 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001893 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001894 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001895 FakeStack = createPHI(IRB, UARIsEnabled, FakeStackValue, Term,
1896 ConstantInt::get(IntptrTy, 0));
1897
1898 Value *NoFakeStack =
1899 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
1900 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
1901 IRBIf.SetInsertPoint(Term);
1902 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1903 Value *AllocaValue =
1904 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
1905 IRB.SetInsertPoint(InsBefore);
1906 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1907 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
1908 } else {
1909 // void *FakeStack = nullptr;
1910 // void *LocalStackBase = alloca(LocalStackSize);
1911 FakeStack = ConstantInt::get(IntptrTy, 0);
1912 LocalStackBase =
1913 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001914 }
1915
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001916 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001917 for (const auto &Desc : SVD) {
1918 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00001919 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00001920 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001921 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00001922 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001923 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001924 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001925
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001926 // The left-most redzone has enough space for at least 4 pointers.
1927 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001928 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1929 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1930 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001931 // Write the frame description constant to redzone[1].
1932 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001933 IRB.CreateAdd(LocalStackBase,
1934 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
1935 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00001936 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001937 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001938 /*AllowMerging*/ true);
1939 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001940 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001941 // Write the PC to redzone[2].
1942 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001943 IRB.CreateAdd(LocalStackBase,
1944 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
1945 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001946 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001947
1948 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001949 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001950 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001951
Kostya Serebryany530e2072013-12-23 14:15:08 +00001952 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001953 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001954 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001955 // Mark the current frame as retired.
1956 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1957 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001958 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001959 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001960 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00001961 // // In use-after-return mode, poison the whole stack frame.
1962 // if StackMallocIdx <= 4
1963 // // For small sizes inline the whole thing:
1964 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001965 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00001966 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001967 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00001968 // else
1969 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001970 Value *Cmp =
1971 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00001972 TerminatorInst *ThenTerm, *ElseTerm;
1973 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1974
1975 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001976 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001977 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1978 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1979 ClassSize >> Mapping.Scale);
1980 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001981 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001982 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1983 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1984 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1985 IRBPoison.CreateStore(
1986 Constant::getNullValue(IRBPoison.getInt8Ty()),
1987 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1988 } else {
1989 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00001990 IRBPoison.CreateCall(
1991 AsanStackFreeFunc[StackMallocIdx],
1992 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001993 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00001994
1995 IRBuilder<> IRBElse(ElseTerm);
1996 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001997 } else if (HavePoisonedAllocas) {
1998 // If we poisoned some allocas in llvm.lifetime analysis,
1999 // unpoison whole stack frame now.
Alexey Samsonov261177a2012-12-04 01:34:23 +00002000 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany530e2072013-12-23 14:15:08 +00002001 } else {
2002 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002003 }
2004 }
2005
Kostya Serebryany09959942012-10-19 06:20:53 +00002006 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002007 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002008}
Alexey Samsonov261177a2012-12-04 01:34:23 +00002009
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002010void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00002011 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00002012 // For now just insert the call to ASan runtime.
2013 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2014 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002015 IRB.CreateCall(
2016 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2017 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00002018}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002019
2020// Handling llvm.lifetime intrinsics for a given %alloca:
2021// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2022// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2023// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2024// could be poisoned by previous llvm.lifetime.end instruction, as the
2025// variable may go in and out of scope several times, e.g. in loops).
2026// (3) if we poisoned at least one %alloca in a function,
2027// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002028
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002029AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2030 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
2031 // We're intested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00002032 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002033 // See if we've already calculated (or started to calculate) alloca for a
2034 // given value.
2035 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002036 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002037 // Store 0 while we're calculating alloca for value V to avoid
2038 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00002039 AllocaForValue[V] = nullptr;
2040 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002041 if (CastInst *CI = dyn_cast<CastInst>(V))
2042 Res = findAllocaForValue(CI->getOperand(0));
2043 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00002044 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002045 // Allow self-referencing phi-nodes.
2046 if (IncValue == PN) continue;
2047 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2048 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00002049 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2050 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002051 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002052 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002053 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002054 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002055 return Res;
2056}
Yury Gribov55441bb2014-11-21 10:29:50 +00002057
Yury Gribov98b18592015-05-28 07:51:49 +00002058void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00002059 IRBuilder<> IRB(AI);
2060
Yury Gribov55441bb2014-11-21 10:29:50 +00002061 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2062 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2063
2064 Value *Zero = Constant::getNullValue(IntptrTy);
2065 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2066 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00002067
2068 // Since we need to extend alloca with additional memory to locate
2069 // redzones, and OldSize is number of allocated blocks with
2070 // ElementSize size, get allocated memory size in bytes by
2071 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00002072 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002073 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00002074 Value *OldSize =
2075 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2076 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00002077
2078 // PartialSize = OldSize % 32
2079 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2080
2081 // Misalign = kAllocaRzSize - PartialSize;
2082 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2083
2084 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2085 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2086 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2087
2088 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2089 // Align is added to locate left redzone, PartialPadding for possible
2090 // partial redzone and kAllocaRzSize for right redzone respectively.
2091 Value *AdditionalChunkSize = IRB.CreateAdd(
2092 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2093
2094 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2095
2096 // Insert new alloca with new NewSize and Align params.
2097 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2098 NewAlloca->setAlignment(Align);
2099
2100 // NewAddress = Address + Align
2101 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2102 ConstantInt::get(IntptrTy, Align));
2103
Yury Gribov98b18592015-05-28 07:51:49 +00002104 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00002105 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00002106
2107 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2108 // for unpoisoning stuff.
2109 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2110
Yury Gribov55441bb2014-11-21 10:29:50 +00002111 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2112
Yury Gribov98b18592015-05-28 07:51:49 +00002113 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00002114 AI->replaceAllUsesWith(NewAddressPtr);
2115
Yury Gribov98b18592015-05-28 07:51:49 +00002116 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00002117 AI->eraseFromParent();
2118}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002119
2120// isSafeAccess returns true if Addr is always inbounds with respect to its
2121// base object. For example, it is a field access or an array access with
2122// constant inbounds index.
2123bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2124 Value *Addr, uint64_t TypeSize) const {
2125 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2126 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00002127 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002128 int64_t Offset = SizeOffset.second.getSExtValue();
2129 // Three checks are required to ensure safety:
2130 // . Offset >= 0 (since the offset is given from the base ptr)
2131 // . Size >= Offset (unsigned)
2132 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00002133 return Offset >= 0 && Size >= uint64_t(Offset) &&
2134 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002135}