blob: 3ad8e145815fcba064fb2c3a0058a47ff4cc9d57 [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
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000016#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov29dd7f22012-12-27 08:50:58 +000017#include "llvm/ADT/DenseMap.h"
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +000018#include "llvm/ADT/DepthFirstIterator.h"
Kuba Brecka8ec94ea2015-07-22 10:25:38 +000019#include "llvm/ADT/SetVector.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000020#include "llvm/ADT/SmallSet.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000021#include "llvm/ADT/SmallVector.h"
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +000022#include "llvm/ADT/Statistic.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000023#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov617232f2012-05-23 11:52:12 +000024#include "llvm/ADT/Triple.h"
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000025#include "llvm/Analysis/MemoryBuiltins.h"
26#include "llvm/Analysis/TargetLibraryInfo.h"
27#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000028#include "llvm/IR/CallSite.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000029#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/DataLayout.h"
Yury Gribov3ae427d2014-12-01 08:47:58 +000031#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Function.h"
33#include "llvm/IR/IRBuilder.h"
34#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000035#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/IntrinsicInst.h"
37#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000038#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Module.h"
40#include "llvm/IR/Type.h"
Kuba Brecka1001bb52014-12-05 22:19:18 +000041#include "llvm/MC/MCSectionMachO.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000042#include "llvm/Support/CommandLine.h"
43#include "llvm/Support/DataTypes.h"
44#include "llvm/Support/Debug.h"
Kostya Serebryany9e62b302013-06-03 14:46:56 +000045#include "llvm/Support/Endian.h"
Yury Gribov55441bb2014-11-21 10:29:50 +000046#include "llvm/Support/SwapByteOrder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000047#include "llvm/Support/raw_ostream.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000048#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany351b0782014-09-03 22:37:37 +000049#include "llvm/Transforms/Scalar.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000050#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000051#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany9f5213f2013-06-26 09:18:17 +000052#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000053#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000054#include "llvm/Transforms/Utils/ModuleUtils.h"
Anna Zaks8ed1d812015-02-27 03:12:36 +000055#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000056#include <algorithm>
Chandler Carruthed0881b2012-12-03 16:50:05 +000057#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000058#include <system_error>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000059
60using namespace llvm;
61
Chandler Carruth964daaa2014-04-22 02:55:47 +000062#define DEBUG_TYPE "asan"
63
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000064static const uint64_t kDefaultShadowScale = 3;
65static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
66static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Anna Zaks3b50e702016-02-02 22:05:07 +000067static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
68static const uint64_t kIOSShadowOffset64 = 0x120200000;
69static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
70static const uint64_t kIOSSimShadowOffset64 = kDefaultShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000071static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +000072static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
Kostya Serebryany4766fe62013-01-23 12:54:55 +000073static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +000074static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +000075static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +000076static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +000077static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000078static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
79static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +000080static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Etienne Bergeron70684f92016-06-21 15:07:29 +000081// TODO(wwchrome): Experimental for asan Win64, may change.
82static const uint64_t kWindowsShadowOffset64 = 0x1ULL << 45; // 32TB.
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000083
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000084static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000085static const size_t kMaxStackMallocSize = 1 << 16; // 64K
86static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
87static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
88
Craig Topperd3a34f82013-07-16 01:17:10 +000089static const char *const kAsanModuleCtorName = "asan.module_ctor";
90static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000091static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000092static const char *const kAsanReportErrorTemplate = "__asan_report_";
Craig Topperd3a34f82013-07-16 01:17:10 +000093static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000094static const char *const kAsanUnregisterGlobalsName =
95 "__asan_unregister_globals";
Ryan Govostes653f9d02016-03-28 20:28:57 +000096static const char *const kAsanRegisterImageGlobalsName =
97 "__asan_register_image_globals";
98static const char *const kAsanUnregisterImageGlobalsName =
99 "__asan_unregister_image_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +0000100static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
101static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kuba Brecka45dbffd2015-07-23 10:54:06 +0000102static const char *const kAsanInitName = "__asan_init";
103static const char *const kAsanVersionCheckName =
Ryan Govostes653f9d02016-03-28 20:28:57 +0000104 "__asan_version_mismatch_check_v8";
Kostya Serebryany796f6552014-02-27 12:45:36 +0000105static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
106static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +0000107static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000108static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +0000109static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
110static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000111static const char *const kAsanGenPrefix = "__asan_gen_";
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000112static const char *const kODRGenPrefix = "__odr_asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000113static const char *const kSanCovGenPrefix = "__sancov_gen_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000114static const char *const kAsanPoisonStackMemoryName =
115 "__asan_poison_stack_memory";
116static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000117 "__asan_unpoison_stack_memory";
Ryan Govostes653f9d02016-03-28 20:28:57 +0000118static const char *const kAsanGlobalsRegisteredFlagName =
119 "__asan_globals_registered";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000120
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +0000121static const char *const kAsanOptionDetectUseAfterReturn =
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000122 "__asan_option_detect_stack_use_after_return";
123
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000124static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
125static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
Yury Gribov98b18592015-05-28 07:51:49 +0000126
Kostya Serebryany874dae62012-07-16 16:15:40 +0000127// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
128static const size_t kNumberOfAccessSizes = 5;
129
Yury Gribov55441bb2014-11-21 10:29:50 +0000130static const unsigned kAllocaRzSize = 32;
Yury Gribov55441bb2014-11-21 10:29:50 +0000131
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000132// Command-line flags.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000133static cl::opt<bool> ClEnableKasan(
134 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
135 cl::Hidden, cl::init(false));
Yury Gribovd7731982015-11-11 10:36:49 +0000136static cl::opt<bool> ClRecover(
137 "asan-recover",
138 cl::desc("Enable recovery mode (continue-after-error)."),
139 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000140
141// This flag may need to be replaced with -f[no-]asan-reads.
142static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000143 cl::desc("instrument read instructions"),
144 cl::Hidden, cl::init(true));
145static cl::opt<bool> ClInstrumentWrites(
146 "asan-instrument-writes", cl::desc("instrument write instructions"),
147 cl::Hidden, cl::init(true));
148static cl::opt<bool> ClInstrumentAtomics(
149 "asan-instrument-atomics",
150 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
151 cl::init(true));
152static cl::opt<bool> ClAlwaysSlowPath(
153 "asan-always-slow-path",
154 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
155 cl::init(false));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000156// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000157// in any given BB. Normally, this should be set to unlimited (INT_MAX),
158// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
159// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000160static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
161 "asan-max-ins-per-bb", cl::init(10000),
162 cl::desc("maximal number of instructions to instrument in any given BB"),
163 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000164// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000165static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
166 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000167static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Mike Aizatsky243b71f2016-04-21 22:00:13 +0000168 cl::desc("Check stack-use-after-return"),
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000169 cl::Hidden, cl::init(true));
Kostya Serebryanya83bfea2016-04-20 20:02:58 +0000170static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
171 cl::desc("Check stack-use-after-scope"),
172 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000173// This flag may need to be replaced with -f[no]asan-globals.
174static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000175 cl::desc("Handle global objects"), cl::Hidden,
176 cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000177static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000178 cl::desc("Handle C++ initializer order"),
179 cl::Hidden, cl::init(true));
180static cl::opt<bool> ClInvalidPointerPairs(
181 "asan-detect-invalid-pointer-pair",
182 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
183 cl::init(false));
184static cl::opt<unsigned> ClRealignStack(
185 "asan-realign-stack",
186 cl::desc("Realign stack to the value of this flag (power of two)"),
187 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000188static cl::opt<int> ClInstrumentationWithCallsThreshold(
189 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000190 cl::desc(
191 "If the function being instrumented contains more than "
192 "this number of memory accesses, use callbacks instead of "
193 "inline checks (-1 means never use callbacks)."),
194 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000195static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000196 "asan-memory-access-callback-prefix",
197 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
198 cl::init("__asan_"));
Yury Gribov55441bb2014-11-21 10:29:50 +0000199static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000200 cl::desc("instrument dynamic allocas"),
Alexey Samsonovf4fb5f52015-10-22 20:07:28 +0000201 cl::Hidden, cl::init(true));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000202static cl::opt<bool> ClSkipPromotableAllocas(
203 "asan-skip-promotable-allocas",
204 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
205 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000206
207// These flags allow to change the shadow mapping.
208// The shadow mapping looks like
Ryan Govostes3f37df02016-05-06 10:25:22 +0000209// Shadow = (Mem >> scale) + offset
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000210static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000211 cl::desc("scale of asan shadow mapping"),
212 cl::Hidden, cl::init(0));
Ryan Govostes6194ae62016-05-06 11:22:11 +0000213static cl::opt<unsigned long long> ClMappingOffset(
214 "asan-mapping-offset",
215 cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden,
216 cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000217
218// Optimization flags. Not user visible, used mostly for testing
219// and benchmarking the tool.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000220static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
221 cl::Hidden, cl::init(true));
222static cl::opt<bool> ClOptSameTemp(
223 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
224 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000225static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000226 cl::desc("Don't instrument scalar globals"),
227 cl::Hidden, cl::init(true));
228static cl::opt<bool> ClOptStack(
229 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
230 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000231
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000232static cl::opt<bool> ClDynamicAllocaStack(
233 "asan-stack-dynamic-alloca",
234 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000235 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000236
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000237static cl::opt<uint32_t> ClForceExperiment(
238 "asan-force-experiment",
239 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
240 cl::init(0));
241
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000242static cl::opt<bool>
243 ClUsePrivateAliasForGlobals("asan-use-private-alias",
244 cl::desc("Use private aliases for global"
245 " variables"),
246 cl::Hidden, cl::init(false));
247
Ryan Govostese51401b2016-07-05 21:53:08 +0000248static cl::opt<bool>
249 ClUseMachOGlobalsSection("asan-globals-live-support",
250 cl::desc("Use linker features to support dead "
251 "code stripping of globals "
252 "(Mach-O only)"),
253 cl::Hidden, cl::init(false));
254
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000255// Debug flags.
256static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
257 cl::init(0));
258static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
259 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000260static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
261 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000262static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
263 cl::Hidden, cl::init(-1));
264static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
265 cl::Hidden, cl::init(-1));
266
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000267STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
268STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000269STATISTIC(NumOptimizedAccessesToGlobalVar,
270 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000271STATISTIC(NumOptimizedAccessesToStackVar,
272 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000273
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000274namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000275/// Frontend-provided metadata for source location.
276struct LocationMetadata {
277 StringRef Filename;
278 int LineNo;
279 int ColumnNo;
280
281 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
282
283 bool empty() const { return Filename.empty(); }
284
285 void parse(MDNode *MDN) {
286 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000287 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
288 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000289 LineNo =
290 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
291 ColumnNo =
292 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000293 }
294};
295
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000296/// Frontend-provided metadata for global variables.
297class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000298 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000299 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000300 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000301 LocationMetadata SourceLoc;
302 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000303 bool IsDynInit;
304 bool IsBlacklisted;
305 };
306
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000307 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000308
Keno Fischere03fae42015-12-05 14:42:34 +0000309 void reset() {
310 inited_ = false;
311 Entries.clear();
312 }
313
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000314 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000315 assert(!inited_);
316 inited_ = true;
317 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000318 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000319 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000320 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000321 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000322 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000323 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000324 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000325 // We can already have an entry for GV if it was merged with another
326 // global.
327 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000328 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
329 E.SourceLoc.parse(Loc);
330 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
331 E.Name = Name->getString();
332 ConstantInt *IsDynInit =
333 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000334 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000335 ConstantInt *IsBlacklisted =
336 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000337 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000338 }
339 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000340
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000341 /// Returns metadata entry for a given global.
342 Entry get(GlobalVariable *G) const {
343 auto Pos = Entries.find(G);
344 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000345 }
346
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000347 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000348 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000349 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000350};
351
Alexey Samsonov1345d352013-01-16 13:23:28 +0000352/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000353/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000354struct ShadowMapping {
355 int Scale;
356 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000357 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000358};
359
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000360static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
361 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000362 bool IsAndroid = TargetTriple.isAndroid();
Anna Zaks3b50e702016-02-02 22:05:07 +0000363 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000364 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
365 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000366 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
367 TargetTriple.getArch() == llvm::Triple::ppc64le;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000368 bool IsSystemZ = TargetTriple.getArch() == llvm::Triple::systemz;
Anna Zaks3b50e702016-02-02 22:05:07 +0000369 bool IsX86 = TargetTriple.getArch() == llvm::Triple::x86;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000370 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000371 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
372 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000373 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
374 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000375 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000376 bool IsWindows = TargetTriple.isOSWindows();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000377
378 ShadowMapping Mapping;
379
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000380 if (LongSize == 32) {
Evgeniy Stepanov9cb08f82015-07-17 23:51:18 +0000381 // Android is always PIE, which means that the beginning of the address
382 // space is always available.
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000383 if (IsAndroid)
384 Mapping.Offset = 0;
385 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000386 Mapping.Offset = kMIPS32_ShadowOffset32;
387 else if (IsFreeBSD)
388 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000389 else if (IsIOS)
Anna Zaks3b50e702016-02-02 22:05:07 +0000390 // If we're targeting iOS and x86, the binary is built for iOS simulator.
391 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000392 else if (IsWindows)
393 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000394 else
395 Mapping.Offset = kDefaultShadowOffset32;
396 } else { // LongSize == 64
397 if (IsPPC64)
398 Mapping.Offset = kPPC64_ShadowOffset64;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000399 else if (IsSystemZ)
400 Mapping.Offset = kSystemZ_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000401 else if (IsFreeBSD)
402 Mapping.Offset = kFreeBSD_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000403 else if (IsLinux && IsX86_64) {
404 if (IsKasan)
405 Mapping.Offset = kLinuxKasan_ShadowOffset64;
406 else
407 Mapping.Offset = kSmallX86_64ShadowOffset;
Etienne Bergeron70684f92016-06-21 15:07:29 +0000408 } else if (IsWindows && IsX86_64) {
409 Mapping.Offset = kWindowsShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000410 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000411 Mapping.Offset = kMIPS64_ShadowOffset64;
Anna Zaks3b50e702016-02-02 22:05:07 +0000412 else if (IsIOS)
413 // If we're targeting iOS and x86, the binary is built for iOS simulator.
414 Mapping.Offset = IsX86_64 ? kIOSSimShadowOffset64 : kIOSShadowOffset64;
Renato Golinaf213722015-02-03 11:20:45 +0000415 else if (IsAArch64)
416 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000417 else
418 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000419 }
420
421 Mapping.Scale = kDefaultShadowScale;
Ryan Govostes3f37df02016-05-06 10:25:22 +0000422 if (ClMappingScale.getNumOccurrences() > 0) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000423 Mapping.Scale = ClMappingScale;
424 }
425
Ryan Govostes3f37df02016-05-06 10:25:22 +0000426 if (ClMappingOffset.getNumOccurrences() > 0) {
427 Mapping.Offset = ClMappingOffset;
428 }
429
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000430 // OR-ing shadow offset if more efficient (at least on x86) if the offset
431 // is a power of two, but on ppc64 we have to use add since the shadow
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000432 // offset is not necessary 1/8-th of the address space. On SystemZ,
433 // we could OR the constant in a single instruction, but it's more
434 // efficient to load it once and use indexed addressing.
435 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ
Adhemerval Zanella35891fe2015-11-09 18:03:48 +0000436 && !(Mapping.Offset & (Mapping.Offset - 1));
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000437
Alexey Samsonov1345d352013-01-16 13:23:28 +0000438 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000439}
440
Alexey Samsonov1345d352013-01-16 13:23:28 +0000441static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000442 // Redzone used for stack and globals is at least 32 bytes.
443 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000444 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000445}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000446
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000447/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000448struct AddressSanitizer : public FunctionPass {
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000449 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
450 bool UseAfterScope = false)
Yury Gribovd7731982015-11-11 10:36:49 +0000451 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000452 Recover(Recover || ClRecover),
453 UseAfterScope(UseAfterScope || ClUseAfterScope) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000454 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
455 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000456 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000457 return "AddressSanitizerFunctionPass";
458 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000459 void getAnalysisUsage(AnalysisUsage &AU) const override {
460 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000461 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000462 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000463 uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000464 uint64_t ArraySize = 1;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000465 if (AI.isArrayAllocation()) {
466 const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000467 assert(CI && "non-constant array size");
468 ArraySize = CI->getZExtValue();
469 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000470 Type *Ty = AI.getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000471 uint64_t SizeInBytes =
Vitaly Buka21a9e572016-07-28 22:50:50 +0000472 AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000473 return SizeInBytes * ArraySize;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000474 }
475 /// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000476 bool isInterestingAlloca(const AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000477
Anna Zaks8ed1d812015-02-27 03:12:36 +0000478 /// If it is an interesting memory access, return the PointerOperand
479 /// and set IsWrite/Alignment. Otherwise return nullptr.
480 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000481 uint64_t *TypeSize, unsigned *Alignment);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000482 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000483 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000484 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000485 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
486 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000487 Value *SizeArgument, bool UseCalls, uint32_t Exp);
488 void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
489 uint32_t TypeSize, bool IsWrite,
490 Value *SizeArgument, bool UseCalls,
491 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000492 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
493 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000494 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000495 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000496 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000497 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000498 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000499 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000500 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000501 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000502 bool doInitialization(Module &M) override;
Keno Fischere03fae42015-12-05 14:42:34 +0000503 bool doFinalization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000504 static char ID; // Pass identification, replacement for typeid
505
Yury Gribov3ae427d2014-12-01 08:47:58 +0000506 DominatorTree &getDominatorTree() const { return *DT; }
507
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000508 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000509 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000510
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000511 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000512 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000513 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
514 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000515
Reid Kleckner2f907552015-07-21 17:40:14 +0000516 /// Helper to cleanup per-function state.
517 struct FunctionStateRAII {
518 AddressSanitizer *Pass;
519 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
520 assert(Pass->ProcessedAllocas.empty() &&
521 "last pass forgot to clear cache");
522 }
523 ~FunctionStateRAII() { Pass->ProcessedAllocas.clear(); }
524 };
525
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000526 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000527 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000528 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000529 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000530 bool Recover;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000531 bool UseAfterScope;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000532 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000533 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000534 DominatorTree *DT;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000535 Function *AsanCtorFunction = nullptr;
536 Function *AsanInitFunction = nullptr;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000537 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000538 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000539 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
540 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
541 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
542 // This array is indexed by AccessIsWrite and Experiment.
543 Function *AsanErrorCallbackSized[2][2];
544 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000545 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000546 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000547 GlobalsMetadata GlobalsMD;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000548 DenseMap<const AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000549
550 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000551};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000552
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000553class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000554 public:
Yury Gribovd7731982015-11-11 10:36:49 +0000555 explicit AddressSanitizerModule(bool CompileKernel = false,
556 bool Recover = false)
557 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
558 Recover(Recover || ClRecover) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000559 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000560 static char ID; // Pass identification, replacement for typeid
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000561 const char *getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000562
Kostya Serebryany20a79972012-11-22 03:18:50 +0000563 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000564 void initializeCallbacks(Module &M);
565
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000566 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000567 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000568 bool ShouldUseMachOGlobalsSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000569 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000570 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000571 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000572 return RedzoneSizeForScale(Mapping.Scale);
573 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000574
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000575 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000576 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000577 bool Recover;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000578 Type *IntptrTy;
579 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000580 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000581 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000582 Function *AsanPoisonGlobals;
583 Function *AsanUnpoisonGlobals;
584 Function *AsanRegisterGlobals;
585 Function *AsanUnregisterGlobals;
Ryan Govostes653f9d02016-03-28 20:28:57 +0000586 Function *AsanRegisterImageGlobals;
587 Function *AsanUnregisterImageGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000588};
589
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000590// Stack poisoning does not play well with exception handling.
591// When an exception is thrown, we essentially bypass the code
592// that unpoisones the stack. This is why the run-time library has
593// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
594// stack in the interceptor. This however does not work inside the
595// actual function which catches the exception. Most likely because the
596// compiler hoists the load of the shadow value somewhere too high.
597// This causes asan to report a non-existing bug on 453.povray.
598// It sounds like an LLVM bug.
599struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
600 Function &F;
601 AddressSanitizer &ASan;
602 DIBuilder DIB;
603 LLVMContext *C;
604 Type *IntptrTy;
605 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000606 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000607
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000608 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000609 SmallSetVector<AllocaInst *, 16> NonInstrumentedStaticAllocaVec;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000610 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000611 unsigned StackAlignment;
612
Kostya Serebryany6805de52013-09-10 13:16:56 +0000613 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000614 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000615 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000616 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000617
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000618 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
619 struct AllocaPoisonCall {
620 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000621 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000622 uint64_t Size;
623 bool DoPoison;
624 };
625 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
626
Yury Gribov98b18592015-05-28 07:51:49 +0000627 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
628 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
629 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000630 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000631
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000632 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000633 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000634 AllocaForValueMapTy AllocaForValue;
635
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000636 bool HasNonEmptyInlineAsm = false;
637 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000638 std::unique_ptr<CallInst> EmptyInlineAsm;
639
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000640 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000641 : F(F),
642 ASan(ASan),
643 DIB(*F.getParent(), /*AllowUnresolved*/ false),
644 C(ASan.C),
645 IntptrTy(ASan.IntptrTy),
646 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
647 Mapping(ASan.Mapping),
648 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000649 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000650
651 bool runOnFunction() {
652 if (!ClStack) return false;
653 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000654 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000655
Yury Gribov55441bb2014-11-21 10:29:50 +0000656 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000657
658 initializeCallbacks(*F.getParent());
659
660 poisonStack();
661
662 if (ClDebugStack) {
663 DEBUG(dbgs() << F);
664 }
665 return true;
666 }
667
Yury Gribov55441bb2014-11-21 10:29:50 +0000668 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000669 // poisoned red zones around all of them.
670 // Then unpoison everything back before the function returns.
671 void poisonStack();
672
Yury Gribov98b18592015-05-28 07:51:49 +0000673 void createDynamicAllocasInitStorage();
674
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000675 // ----------------------- Visitors.
676 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000677 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000678
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000679 /// \brief Collect all Resume instructions.
680 void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
681
682 /// \brief Collect all CatchReturnInst instructions.
683 void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
684
Yury Gribov98b18592015-05-28 07:51:49 +0000685 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
686 Value *SavedStack) {
687 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000688 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
689 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
690 // need to adjust extracted SP to compute the address of the most recent
691 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
692 // this purpose.
693 if (!isa<ReturnInst>(InstBefore)) {
694 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
695 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
696 {IntptrTy});
697
698 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
699
700 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
701 DynamicAreaOffset);
702 }
703
Yury Gribov781bce22015-05-28 08:03:28 +0000704 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000705 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000706 }
707
Yury Gribov55441bb2014-11-21 10:29:50 +0000708 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000709 void unpoisonDynamicAllocas() {
710 for (auto &Ret : RetVec)
711 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000712
Yury Gribov98b18592015-05-28 07:51:49 +0000713 for (auto &StackRestoreInst : StackRestoreVec)
714 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
715 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000716 }
717
Yury Gribov55441bb2014-11-21 10:29:50 +0000718 // Deploy and poison redzones around dynamic alloca call. To do this, we
719 // should replace this call with another one with changed parameters and
720 // replace all its uses with new address, so
721 // addr = alloca type, old_size, align
722 // is replaced by
723 // new_size = (old_size + additional_size) * sizeof(type)
724 // tmp = alloca i8, new_size, max(align, 32)
725 // addr = tmp + 32 (first 32 bytes are for the left redzone).
726 // Additional_size is added to make new memory allocation contain not only
727 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000728 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000729
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000730 /// \brief Collect Alloca instructions we want (and can) handle.
731 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000732 if (!ASan.isInterestingAlloca(AI)) {
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000733 if (AI.isStaticAlloca()) NonInstrumentedStaticAllocaVec.insert(&AI);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000734 return;
735 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000736
737 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000738 if (!AI.isStaticAlloca())
Yury Gribov98b18592015-05-28 07:51:49 +0000739 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000740 else
741 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000742 }
743
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000744 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
745 /// errors.
746 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000747 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000748 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000749 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000750 if (!ASan.UseAfterScope)
751 return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000752 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000753 return;
754 // Found lifetime intrinsic, add ASan instrumentation if necessary.
755 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
756 // If size argument is undefined, don't do anything.
757 if (Size->isMinusOne()) return;
758 // Check that size doesn't saturate uint64_t and can
759 // be stored in IntptrTy.
760 const uint64_t SizeValue = Size->getValue().getLimitedValue();
761 if (SizeValue == ~0ULL ||
762 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
763 return;
764 // Find alloca instruction that corresponds to llvm.lifetime argument.
765 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
Vitaly Bukab451f1b2016-06-09 23:31:59 +0000766 if (!AI || !ASan.isInterestingAlloca(*AI))
767 return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000768 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000769 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000770 AllocaPoisonCallVec.push_back(APC);
771 }
772
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000773 void visitCallSite(CallSite CS) {
774 Instruction *I = CS.getInstruction();
775 if (CallInst *CI = dyn_cast<CallInst>(I)) {
776 HasNonEmptyInlineAsm |=
777 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
778 HasReturnsTwiceCall |= CI->canReturnTwice();
779 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000780 }
781
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000782 // ---------------------- Helpers.
783 void initializeCallbacks(Module &M);
784
Yury Gribov3ae427d2014-12-01 08:47:58 +0000785 bool doesDominateAllExits(const Instruction *I) const {
786 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000787 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000788 }
789 return true;
790 }
791
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000792 /// Finds alloca where the value comes from.
793 AllocaInst *findAllocaForValue(Value *V);
Craig Topper3af97222014-08-27 05:25:00 +0000794 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000795 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000796 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000797
Vitaly Buka170dede2016-08-19 17:15:38 +0000798 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
799 int Size);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000800 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
801 bool Dynamic);
802 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
803 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000804};
805
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000806} // anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000807
808char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000809INITIALIZE_PASS_BEGIN(
810 AddressSanitizer, "asan",
811 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
812 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000813INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +0000814INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000815INITIALIZE_PASS_END(
816 AddressSanitizer, "asan",
817 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
818 false)
Yury Gribovd7731982015-11-11 10:36:49 +0000819FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000820 bool Recover,
821 bool UseAfterScope) {
Yury Gribovd7731982015-11-11 10:36:49 +0000822 assert(!CompileKernel || Recover);
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000823 return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000824}
825
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000826char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000827INITIALIZE_PASS(
828 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000829 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000830 "ModulePass",
831 false, false)
Yury Gribovd7731982015-11-11 10:36:49 +0000832ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
833 bool Recover) {
834 assert(!CompileKernel || Recover);
835 return new AddressSanitizerModule(CompileKernel, Recover);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000836}
837
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000838static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000839 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000840 assert(Res < kNumberOfAccessSizes);
841 return Res;
842}
843
Bill Wendling58f8cef2013-08-06 22:52:42 +0000844// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000845static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
846 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000847 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000848 // We use private linkage for module-local strings. If they can be merged
849 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000850 GlobalVariable *GV =
851 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000852 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000853 if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000854 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
855 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000856}
857
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000858/// \brief Create a global describing a source location.
859static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
860 LocationMetadata MD) {
861 Constant *LocData[] = {
862 createPrivateGlobalForString(M, MD.Filename, true),
863 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
864 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
865 };
866 auto LocStruct = ConstantStruct::getAnon(LocData);
867 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
868 GlobalValue::PrivateLinkage, LocStruct,
869 kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000870 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000871 return GV;
872}
873
Vedant Kumarf5ac6d42016-06-22 17:30:58 +0000874/// \brief Check if \p G has been created by a trusted compiler pass.
875static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
876 // Do not instrument asan globals.
877 if (G->getName().startswith(kAsanGenPrefix) ||
878 G->getName().startswith(kSanCovGenPrefix) ||
879 G->getName().startswith(kODRGenPrefix))
880 return true;
881
882 // Do not instrument gcov counter arrays.
883 if (G->getName() == "__llvm_gcov_ctr")
884 return true;
885
886 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000887}
888
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000889Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
890 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000891 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000892 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000893 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000894 if (Mapping.OrShadowOffset)
895 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
896 else
897 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000898}
899
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000900// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000901void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
902 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000903 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000904 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000905 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +0000906 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
907 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
908 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000909 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000910 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000911 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +0000912 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
913 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
914 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000915 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000916 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000917}
918
Anna Zaks8ed1d812015-02-27 03:12:36 +0000919/// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000920bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000921 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
922
923 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
924 return PreviouslySeenAllocaInfo->getSecond();
925
Yury Gribov98b18592015-05-28 07:51:49 +0000926 bool IsInteresting =
927 (AI.getAllocatedType()->isSized() &&
928 // alloca() may be called with 0 size, ignore it.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000929 ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
Yury Gribov98b18592015-05-28 07:51:49 +0000930 // We are only interested in allocas not promotable to registers.
931 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +0000932 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
933 // inalloca allocas are not treated as static, and we don't want
934 // dynamic alloca instrumentation for them as well.
935 !AI.isUsedWithInAlloca());
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000936
937 ProcessedAllocas[&AI] = IsInteresting;
938 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000939}
940
941/// If I is an interesting memory access, return the PointerOperand
942/// and set IsWrite/Alignment. Otherwise return nullptr.
943Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
944 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000945 uint64_t *TypeSize,
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000946 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000947 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000948 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000949
950 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000951 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000952 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000953 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000954 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000955 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000956 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000957 PtrOperand = LI->getPointerOperand();
958 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000959 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000960 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000961 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000962 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000963 PtrOperand = SI->getPointerOperand();
964 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000965 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000966 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000967 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000968 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000969 PtrOperand = RMW->getPointerOperand();
970 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000971 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000972 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000973 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000974 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000975 PtrOperand = XCHG->getPointerOperand();
Kostya Serebryany90241602012-05-30 09:04:06 +0000976 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000977
Anna Zaks644d9d32016-06-22 00:15:52 +0000978 // Do not instrument acesses from different address spaces; we cannot deal
979 // with them.
980 if (PtrOperand) {
981 Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
982 if (PtrTy->getPointerAddressSpace() != 0)
983 return nullptr;
984 }
985
Anna Zaks8ed1d812015-02-27 03:12:36 +0000986 // Treat memory accesses to promotable allocas as non-interesting since they
987 // will not cause memory violations. This greatly speeds up the instrumented
988 // executable at -O0.
989 if (ClSkipPromotableAllocas)
990 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
991 return isInterestingAlloca(*AI) ? AI : nullptr;
992
993 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000994}
995
Kostya Serebryany796f6552014-02-27 12:45:36 +0000996static bool isPointerOperand(Value *V) {
997 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
998}
999
1000// This is a rough heuristic; it may cause both false positives and
1001// false negatives. The proper implementation requires cooperation with
1002// the frontend.
1003static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1004 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001005 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001006 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001007 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001008 } else {
1009 return false;
1010 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +00001011 return isPointerOperand(I->getOperand(0)) &&
1012 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001013}
1014
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001015bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1016 // If a global variable does not have dynamic initialization we don't
1017 // have to instrument it. However, if a global does not have initializer
1018 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001019 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001020}
1021
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001022void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1023 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +00001024 IRBuilder<> IRB(I);
1025 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1026 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
Benjamin Kramer135f7352016-06-26 12:28:59 +00001027 for (Value *&i : Param) {
1028 if (i->getType()->isPointerTy())
1029 i = IRB.CreatePointerCast(i, IntptrTy);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001030 }
David Blaikieff6409d2015-05-18 22:13:54 +00001031 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001032}
1033
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001034void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001035 Instruction *I, bool UseCalls,
1036 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +00001037 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001038 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001039 uint64_t TypeSize = 0;
1040 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +00001041 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001042
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001043 // Optimization experiments.
1044 // The experiments can be used to evaluate potential optimizations that remove
1045 // instrumentation (assess false negatives). Instead of completely removing
1046 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1047 // experiments that want to remove instrumentation of this instruction).
1048 // If Exp is non-zero, this pass will emit special calls into runtime
1049 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1050 // make runtime terminate the program in a special way (with a different
1051 // exit status). Then you run the new compiler on a buggy corpus, collect
1052 // the special terminations (ideally, you don't see them at all -- no false
1053 // negatives) and make the decision on the optimization.
1054 uint32_t Exp = ClForceExperiment;
1055
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001056 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001057 // If initialization order checking is disabled, a simple access to a
1058 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001059 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001060 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001061 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1062 NumOptimizedAccessesToGlobalVar++;
1063 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001064 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001065 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001066
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001067 if (ClOpt && ClOptStack) {
1068 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001069 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001070 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1071 NumOptimizedAccessesToStackVar++;
1072 return;
1073 }
1074 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001075
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001076 if (IsWrite)
1077 NumInstrumentedWrites++;
1078 else
1079 NumInstrumentedReads++;
1080
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001081 unsigned Granularity = 1 << Mapping.Scale;
1082 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1083 // if the data is properly aligned.
1084 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1085 TypeSize == 128) &&
1086 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001087 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
1088 Exp);
1089 instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
1090 UseCalls, Exp);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001091}
1092
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001093Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1094 Value *Addr, bool IsWrite,
1095 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001096 Value *SizeArgument,
1097 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001098 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001099 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1100 CallInst *Call = nullptr;
1101 if (SizeArgument) {
1102 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001103 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1104 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001105 else
David Blaikieff6409d2015-05-18 22:13:54 +00001106 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1107 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001108 } else {
1109 if (Exp == 0)
1110 Call =
1111 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1112 else
David Blaikieff6409d2015-05-18 22:13:54 +00001113 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1114 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001115 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001116
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001117 // We don't do Call->setDoesNotReturn() because the BB already has
1118 // UnreachableInst at the end.
1119 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001120 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001121 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001122}
1123
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001124Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001125 Value *ShadowValue,
1126 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001127 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001128 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001129 Value *LastAccessedByte =
1130 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001131 // (Addr & (Granularity - 1)) + size - 1
1132 if (TypeSize / 8 > 1)
1133 LastAccessedByte = IRB.CreateAdd(
1134 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1135 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001136 LastAccessedByte =
1137 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001138 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1139 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1140}
1141
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001142void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001143 Instruction *InsertBefore, Value *Addr,
1144 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001145 Value *SizeArgument, bool UseCalls,
1146 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001147 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001148 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001149 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1150
1151 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001152 if (Exp == 0)
1153 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1154 AddrLong);
1155 else
David Blaikieff6409d2015-05-18 22:13:54 +00001156 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1157 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001158 return;
1159 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001160
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001161 Type *ShadowTy =
1162 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001163 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1164 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1165 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001166 Value *ShadowValue =
1167 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001168
1169 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001170 size_t Granularity = 1ULL << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001171 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001172
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001173 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001174 // We use branch weights for the slow path check, to indicate that the slow
1175 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001176 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1177 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001178 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001179 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001180 IRB.SetInsertPoint(CheckTerm);
1181 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001182 if (Recover) {
1183 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1184 } else {
1185 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001186 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001187 CrashTerm = new UnreachableInst(*C, CrashBlock);
1188 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1189 ReplaceInstWithInst(CheckTerm, NewTerm);
1190 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001191 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001192 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001193 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001194
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001195 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001196 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001197 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001198}
1199
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001200// Instrument unusual size or unusual alignment.
1201// We can not do it with a single check, so we do 1-byte check for the first
1202// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1203// to report the actual access size.
1204void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1205 Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1206 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1207 IRBuilder<> IRB(I);
1208 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1209 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1210 if (UseCalls) {
1211 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001212 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1213 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001214 else
David Blaikieff6409d2015-05-18 22:13:54 +00001215 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1216 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001217 } else {
1218 Value *LastByte = IRB.CreateIntToPtr(
1219 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1220 Addr->getType());
1221 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1222 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1223 }
1224}
1225
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001226void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1227 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001228 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001229 IRBuilder<> IRB(&GlobalInit.front(),
1230 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001231
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001232 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001233 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1234 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001235
1236 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001237 for (auto &BB : GlobalInit.getBasicBlockList())
1238 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001239 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001240}
1241
1242void AddressSanitizerModule::createInitializerPoisonCalls(
1243 Module &M, GlobalValue *ModuleName) {
1244 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1245
1246 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1247 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001248 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001249 ConstantStruct *CS = cast<ConstantStruct>(OP);
1250
1251 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001252 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001253 if (F->getName() == kAsanModuleCtorName) continue;
1254 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1255 // Don't instrument CTORs that will run before asan.module_ctor.
1256 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1257 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001258 }
1259 }
1260}
1261
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001262bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001263 Type *Ty = G->getValueType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001264 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001265
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001266 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001267 if (!Ty->isSized()) return false;
1268 if (!G->hasInitializer()) return false;
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001269 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001270 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001271 // Don't handle ODR linkage types and COMDATs since other modules may be built
1272 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001273 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1274 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1275 G->getLinkage() != GlobalVariable::InternalLinkage)
1276 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001277 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001278 // Two problems with thread-locals:
1279 // - The address of the main thread's copy can't be computed at link-time.
1280 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001281 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001282 // For now, just ignore this Global if the alignment is large.
1283 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001284
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001285 if (G->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001286 StringRef Section = G->getSection();
Kuba Brecka086e34b2014-12-05 21:32:46 +00001287
Anna Zaks11904602015-06-09 00:58:08 +00001288 // Globals from llvm.metadata aren't emitted, do not instrument them.
1289 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001290 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001291 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001292
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001293 // Do not instrument function pointers to initialization and termination
1294 // routines: dynamic linker will not properly handle redzones.
1295 if (Section.startswith(".preinit_array") ||
1296 Section.startswith(".init_array") ||
1297 Section.startswith(".fini_array")) {
1298 return false;
1299 }
1300
Anna Zaks11904602015-06-09 00:58:08 +00001301 // Callbacks put into the CRT initializer/terminator sections
1302 // should not be instrumented.
1303 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1304 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1305 if (Section.startswith(".CRT")) {
1306 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1307 return false;
1308 }
1309
Kuba Brecka1001bb52014-12-05 22:19:18 +00001310 if (TargetTriple.isOSBinFormatMachO()) {
1311 StringRef ParsedSegment, ParsedSection;
1312 unsigned TAA = 0, StubSize = 0;
1313 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001314 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1315 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001316 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001317
1318 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1319 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1320 // them.
1321 if (ParsedSegment == "__OBJC" ||
1322 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1323 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1324 return false;
1325 }
1326 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1327 // Constant CFString instances are compiled in the following way:
1328 // -- the string buffer is emitted into
1329 // __TEXT,__cstring,cstring_literals
1330 // -- the constant NSConstantString structure referencing that buffer
1331 // is placed into __DATA,__cfstring
1332 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1333 // Moreover, it causes the linker to crash on OS X 10.7
1334 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1335 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1336 return false;
1337 }
1338 // The linker merges the contents of cstring_literals and removes the
1339 // trailing zeroes.
1340 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1341 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1342 return false;
1343 }
1344 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001345 }
1346
1347 return true;
1348}
1349
Ryan Govostes653f9d02016-03-28 20:28:57 +00001350// On Mach-O platforms, we emit global metadata in a separate section of the
1351// binary in order to allow the linker to properly dead strip. This is only
1352// supported on recent versions of ld64.
1353bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
Ryan Govostese51401b2016-07-05 21:53:08 +00001354 if (!ClUseMachOGlobalsSection)
1355 return false;
1356
Ryan Govostes653f9d02016-03-28 20:28:57 +00001357 if (!TargetTriple.isOSBinFormatMachO())
1358 return false;
1359
1360 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1361 return true;
1362 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001363 return true;
Ryan Govostes653f9d02016-03-28 20:28:57 +00001364 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1365 return true;
1366
1367 return false;
1368}
1369
Alexey Samsonov788381b2012-12-25 12:28:20 +00001370void AddressSanitizerModule::initializeCallbacks(Module &M) {
1371 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001372
Alexey Samsonov788381b2012-12-25 12:28:20 +00001373 // Declare our poisoning and unpoisoning functions.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001374 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001375 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001376 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001377 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001378 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001379 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001380
Alexey Samsonov788381b2012-12-25 12:28:20 +00001381 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001382 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001383 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001384 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001385 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001386 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1387 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001388 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001389
1390 // Declare the functions that find globals in a shared object and then invoke
1391 // the (un)register function on them.
1392 AsanRegisterImageGlobals = checkSanitizerInterfaceFunction(
1393 M.getOrInsertFunction(kAsanRegisterImageGlobalsName,
1394 IRB.getVoidTy(), IntptrTy, nullptr));
1395 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001396
Ryan Govostes653f9d02016-03-28 20:28:57 +00001397 AsanUnregisterImageGlobals = checkSanitizerInterfaceFunction(
1398 M.getOrInsertFunction(kAsanUnregisterImageGlobalsName,
1399 IRB.getVoidTy(), IntptrTy, nullptr));
1400 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001401}
1402
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001403// This function replaces all global variables with new variables that have
1404// trailing redzones. It also creates a function that poisons
1405// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001406bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001407 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001408
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001409 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1410
Alexey Samsonova02e6642014-05-29 18:40:48 +00001411 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001412 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001413 }
1414
1415 size_t n = GlobalsToChange.size();
1416 if (n == 0) return false;
1417
1418 // A global is described by a structure
1419 // size_t beg;
1420 // size_t size;
1421 // size_t size_with_redzone;
1422 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001423 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001424 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001425 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001426 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001427 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001428 StructType *GlobalStructTy =
1429 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001430 IntptrTy, IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001431 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001432
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001433 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001434
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001435 // We shouldn't merge same module names, as this string serves as unique
1436 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001437 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001438 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001439
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001440 auto &DL = M.getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001441 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001442 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001443 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001444
1445 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001446 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001447 // Create string holding the global name (use global name from metadata
1448 // if it's available, otherwise just write the name of global variable).
1449 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001450 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001451 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001452
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001453 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001454 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001455 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001456 // MinRZ <= RZ <= kMaxGlobalRedzone
1457 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001458 uint64_t RZ = std::max(
1459 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001460 uint64_t RightRedzoneSize = RZ;
1461 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001462 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001463 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001464 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1465
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001466 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001467 Constant *NewInitializer =
1468 ConstantStruct::get(NewTy, G->getInitializer(),
1469 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001470
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001471 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001472 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1473 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1474 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001475 GlobalVariable *NewGlobal =
1476 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1477 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001478 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001479 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001480
1481 Value *Indices2[2];
1482 Indices2[0] = IRB.getInt32(0);
1483 Indices2[1] = IRB.getInt32(0);
1484
1485 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001486 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001487 NewGlobal->takeName(G);
1488 G->eraseFromParent();
1489
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001490 Constant *SourceLoc;
1491 if (!MD.SourceLoc.empty()) {
1492 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1493 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1494 } else {
1495 SourceLoc = ConstantInt::get(IntptrTy, 0);
1496 }
1497
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001498 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
1499 GlobalValue *InstrumentedGlobal = NewGlobal;
1500
1501 bool CanUsePrivateAliases = TargetTriple.isOSBinFormatELF();
1502 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
1503 // Create local alias for NewGlobal to avoid crash on ODR between
1504 // instrumented and non-instrumented libraries.
1505 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
1506 NameForGlobal + M.getName(), NewGlobal);
1507
1508 // With local aliases, we need to provide another externally visible
1509 // symbol __odr_asan_XXX to detect ODR violation.
1510 auto *ODRIndicatorSym =
1511 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
1512 Constant::getNullValue(IRB.getInt8Ty()),
1513 kODRGenPrefix + NameForGlobal, nullptr,
1514 NewGlobal->getThreadLocalMode());
1515
1516 // Set meaningful attributes for indicator symbol.
1517 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
1518 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
1519 ODRIndicatorSym->setAlignment(1);
1520 ODRIndicator = ODRIndicatorSym;
1521 InstrumentedGlobal = GA;
1522 }
1523
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001524 Initializers[i] = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001525 GlobalStructTy,
1526 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001527 ConstantInt::get(IntptrTy, SizeInBytes),
1528 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1529 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001530 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001531 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
1532 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy), nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001533
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001534 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001535
Kostya Serebryany20343352012-10-17 13:40:06 +00001536 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001537 }
1538
Ryan Govostes653f9d02016-03-28 20:28:57 +00001539
1540 GlobalVariable *AllGlobals = nullptr;
1541 GlobalVariable *RegisteredFlag = nullptr;
1542
1543 // On recent Mach-O platforms, we emit the global metadata in a way that
1544 // allows the linker to properly strip dead globals.
1545 if (ShouldUseMachOGlobalsSection()) {
1546 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1547 // to look up the loaded image that contains it. Second, we can store in it
1548 // whether registration has already occurred, to prevent duplicate
1549 // registration.
1550 //
1551 // Common linkage allows us to coalesce needles defined in each object
1552 // file so that there's only one per shared library.
1553 RegisteredFlag = new GlobalVariable(
1554 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1555 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1556
1557 // We also emit a structure which binds the liveness of the global
1558 // variable to the metadata struct.
1559 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy, nullptr);
1560
1561 for (size_t i = 0; i < n; i++) {
1562 GlobalVariable *Metadata = new GlobalVariable(
1563 M, GlobalStructTy, false, GlobalVariable::InternalLinkage,
1564 Initializers[i], "");
1565 Metadata->setSection("__DATA,__asan_globals,regular");
1566 Metadata->setAlignment(1); // don't leave padding in between
1567
1568 auto LivenessBinder = ConstantStruct::get(LivenessTy,
1569 Initializers[i]->getAggregateElement(0u),
1570 ConstantExpr::getPointerCast(Metadata, IntptrTy),
1571 nullptr);
1572 GlobalVariable *Liveness = new GlobalVariable(
1573 M, LivenessTy, false, GlobalVariable::InternalLinkage,
1574 LivenessBinder, "");
1575 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1576 }
1577 } else {
1578 // On all other platfoms, we just emit an array of global metadata
1579 // structures.
1580 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1581 AllGlobals = new GlobalVariable(
1582 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1583 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1584 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001585
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001586 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001587 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001588 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001589
Ryan Govostes653f9d02016-03-28 20:28:57 +00001590 // Create a call to register the globals with the runtime.
1591 if (ShouldUseMachOGlobalsSection()) {
1592 IRB.CreateCall(AsanRegisterImageGlobals,
1593 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1594 } else {
1595 IRB.CreateCall(AsanRegisterGlobals,
1596 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1597 ConstantInt::get(IntptrTy, n)});
1598 }
1599
1600 // We also need to unregister globals at the end, e.g., when a shared library
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001601 // gets closed.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001602 Function *AsanDtorFunction =
1603 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1604 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001605 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1606 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001607
1608 if (ShouldUseMachOGlobalsSection()) {
1609 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1610 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1611 } else {
1612 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1613 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1614 ConstantInt::get(IntptrTy, n)});
1615 }
1616
Alexey Samsonov1f647502014-05-29 01:10:14 +00001617 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001618
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001619 DEBUG(dbgs() << M);
1620 return true;
1621}
1622
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001623bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001624 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001625 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001626 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001627 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001628 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001629 initializeCallbacks(M);
1630
1631 bool Changed = false;
1632
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001633 // TODO(glider): temporarily disabled globals instrumentation for KASan.
1634 if (ClGlobals && !CompileKernel) {
1635 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1636 assert(CtorFunc);
1637 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1638 Changed |= InstrumentGlobals(IRB, M);
1639 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001640
1641 return Changed;
1642}
1643
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001644void AddressSanitizer::initializeCallbacks(Module &M) {
1645 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001646 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001647 // IsWrite, TypeSize and Exp are encoded in the function name.
1648 for (int Exp = 0; Exp < 2; Exp++) {
1649 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1650 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1651 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001652 const std::string SuffixStr = CompileKernel ? "N" : "_n";
Yury Gribovd7731982015-11-11 10:36:49 +00001653 const std::string EndingStr = Recover ? "_noabort" : "";
Craig Toppere3dcce92015-08-01 22:20:21 +00001654 Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001655 AsanErrorCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001656 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001657 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001658 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1659 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001660 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001661 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001662 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1663 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1664 AccessSizeIndex++) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001665 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001666 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001667 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001668 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001669 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001670 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001671 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001672 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1673 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001674 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001675 }
1676 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00001677
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001678 const std::string MemIntrinCallbackPrefix =
1679 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001680 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001681 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001682 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001683 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001684 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001685 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001686 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001687 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001688 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001689
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001690 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001691 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001692
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001693 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001694 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001695 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001696 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001697 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1698 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1699 StringRef(""), StringRef(""),
1700 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001701}
1702
1703// virtual
1704bool AddressSanitizer::doInitialization(Module &M) {
1705 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001706
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001707 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001708
1709 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001710 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001711 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001712 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001713
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001714 if (!CompileKernel) {
1715 std::tie(AsanCtorFunction, AsanInitFunction) =
Kuba Brecka45dbffd2015-07-23 10:54:06 +00001716 createSanitizerCtorAndInitFunctions(
1717 M, kAsanModuleCtorName, kAsanInitName,
1718 /*InitArgTypes=*/{}, /*InitArgs=*/{}, kAsanVersionCheckName);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001719 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1720 }
1721 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001722 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001723}
1724
Keno Fischere03fae42015-12-05 14:42:34 +00001725bool AddressSanitizer::doFinalization(Module &M) {
1726 GlobalsMD.reset();
1727 return false;
1728}
1729
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001730bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1731 // For each NSObject descendant having a +load method, this method is invoked
1732 // by the ObjC runtime before any of the static constructors is called.
1733 // Therefore we need to instrument such methods with a call to __asan_init
1734 // at the beginning in order to initialize our runtime before any access to
1735 // the shadow memory.
1736 // We cannot just ignore these methods, because they may call other
1737 // instrumented functions.
1738 if (F.getName().find(" load]") != std::string::npos) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001739 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00001740 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001741 return true;
1742 }
1743 return false;
1744}
1745
Reid Kleckner2f907552015-07-21 17:40:14 +00001746void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
1747 // Find the one possible call to llvm.localescape and pre-mark allocas passed
1748 // to it as uninteresting. This assumes we haven't started processing allocas
1749 // yet. This check is done up front because iterating the use list in
1750 // isInterestingAlloca would be algorithmically slower.
1751 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
1752
1753 // Try to get the declaration of llvm.localescape. If it's not in the module,
1754 // we can exit early.
1755 if (!F.getParent()->getFunction("llvm.localescape")) return;
1756
1757 // Look for a call to llvm.localescape call in the entry block. It can't be in
1758 // any other block.
1759 for (Instruction &I : F.getEntryBlock()) {
1760 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
1761 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
1762 // We found a call. Mark all the allocas passed in as uninteresting.
1763 for (Value *Arg : II->arg_operands()) {
1764 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
1765 assert(AI && AI->isStaticAlloca() &&
1766 "non-static alloca arg to localescape");
1767 ProcessedAllocas[AI] = false;
1768 }
1769 break;
1770 }
1771 }
1772}
1773
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001774bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001775 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001776 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001777 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001778 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001779
Yury Gribov3ae427d2014-12-01 08:47:58 +00001780 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1781
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001782 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001783 maybeInsertAsanInitAtFunctionEntry(F);
1784
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001785 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001786
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001787 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001788
Reid Kleckner2f907552015-07-21 17:40:14 +00001789 FunctionStateRAII CleanupObj(this);
1790
1791 // We can't instrument allocas used with llvm.localescape. Only static allocas
1792 // can be passed to that intrinsic.
1793 markEscapedLocalAllocas(F);
1794
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001795 // We want to instrument every address only once per basic block (unless there
1796 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001797 SmallSet<Value *, 16> TempsToInstrument;
1798 SmallVector<Instruction *, 16> ToInstrument;
1799 SmallVector<Instruction *, 8> NoReturnCalls;
1800 SmallVector<BasicBlock *, 16> AllBlocks;
1801 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001802 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001803 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001804 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001805 uint64_t TypeSize;
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00001806 const TargetLibraryInfo *TLI =
1807 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001808
1809 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001810 for (auto &BB : F) {
1811 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001812 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001813 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001814 for (auto &Inst : BB) {
1815 if (LooksLikeCodeInBug11395(&Inst)) return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001816 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1817 &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001818 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001819 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001820 continue; // We've seen this temp in the current BB.
1821 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001822 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001823 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1824 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001825 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001826 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001827 // ok, take it.
1828 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001829 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001830 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001831 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001832 // A call inside BB.
1833 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001834 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001835 }
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00001836 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
1837 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001838 continue;
1839 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001840 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001841 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001842 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001843 }
1844 }
1845
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001846 bool UseCalls =
1847 CompileKernel ||
1848 (ClInstrumentationWithCallsThreshold >= 0 &&
1849 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001850 const DataLayout &DL = F.getParent()->getDataLayout();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001851 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1852 /*RoundToAlign=*/true);
1853
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001854 // Instrument.
1855 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001856 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001857 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1858 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001859 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001860 instrumentMop(ObjSizeVis, Inst, UseCalls,
1861 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001862 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001863 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001864 }
1865 NumInstrumented++;
1866 }
1867
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001868 FunctionStackPoisoner FSP(F, *this);
1869 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001870
1871 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1872 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001873 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001874 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00001875 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001876 }
1877
Alexey Samsonova02e6642014-05-29 18:40:48 +00001878 for (auto Inst : PointerComparisonsOrSubtracts) {
1879 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001880 NumInstrumented++;
1881 }
1882
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001883 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001884
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001885 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1886
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001887 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001888}
1889
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001890// Workaround for bug 11395: we don't want to instrument stack in functions
1891// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1892// FIXME: remove once the bug 11395 is fixed.
1893bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1894 if (LongSize != 32) return false;
1895 CallInst *CI = dyn_cast<CallInst>(I);
1896 if (!CI || !CI->isInlineAsm()) return false;
1897 if (CI->getNumArgOperands() <= 5) return false;
1898 // We have inline assembly with quite a few arguments.
1899 return true;
1900}
1901
1902void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1903 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001904 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1905 std::string Suffix = itostr(i);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001906 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1907 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1908 IntptrTy, nullptr));
1909 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001910 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1911 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001912 }
Vitaly Buka79b75d32016-06-09 23:05:35 +00001913 if (ASan.UseAfterScope) {
1914 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
1915 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1916 IntptrTy, IntptrTy, nullptr));
1917 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
1918 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1919 IntptrTy, IntptrTy, nullptr));
1920 }
1921
Yury Gribov98b18592015-05-28 07:51:49 +00001922 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1923 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1924 AsanAllocasUnpoisonFunc =
1925 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1926 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001927}
1928
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001929void FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1930 IRBuilder<> &IRB, Value *ShadowBase,
1931 bool DoPoison) {
Vitaly Buka170dede2016-08-19 17:15:38 +00001932 size_t n = ShadowBytes.size();
1933 size_t i = 0;
1934 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1935 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1936 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1937 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1938 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1939 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1940 uint64_t Val = 0;
1941 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
1942 if (F.getParent()->getDataLayout().isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001943 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1944 else
1945 Val = (Val << 8) | ShadowBytes[i + j];
1946 }
Vitaly Buka170dede2016-08-19 17:15:38 +00001947 if (!Val) continue;
1948 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1949 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1950 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1951 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001952 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001953 }
1954}
1955
Kostya Serebryany6805de52013-09-10 13:16:56 +00001956// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1957// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1958static int StackMallocSizeClass(uint64_t LocalStackSize) {
1959 assert(LocalStackSize <= kMaxStackMallocSize);
1960 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001961 for (int i = 0;; i++, MaxSize *= 2)
1962 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00001963 llvm_unreachable("impossible LocalStackSize");
1964}
1965
Vitaly Buka170dede2016-08-19 17:15:38 +00001966// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1967// We can not use MemSet intrinsic because it may end up calling the actual
1968// memset. Size is a multiple of 8.
1969// Currently this generates 8-byte stores on x86_64; it may be better to
1970// generate wider stores.
1971void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1972 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1973 assert(!(Size % 8));
1974
1975 // kAsanStackAfterReturnMagic is 0xf5.
1976 const uint64_t kAsanStackAfterReturnMagic64 = 0xf5f5f5f5f5f5f5f5ULL;
1977
1978 for (int i = 0; i < Size; i += 8) {
1979 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1980 IRB.CreateStore(
1981 ConstantInt::get(IRB.getInt64Ty(), kAsanStackAfterReturnMagic64),
1982 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1983 }
1984}
1985
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001986PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1987 Value *ValueIfTrue,
1988 Instruction *ThenTerm,
1989 Value *ValueIfFalse) {
1990 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1991 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1992 PHI->addIncoming(ValueIfFalse, CondBlock);
1993 BasicBlock *ThenBlock = ThenTerm->getParent();
1994 PHI->addIncoming(ValueIfTrue, ThenBlock);
1995 return PHI;
1996}
1997
1998Value *FunctionStackPoisoner::createAllocaForLayout(
1999 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2000 AllocaInst *Alloca;
2001 if (Dynamic) {
2002 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2003 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2004 "MyAlloca");
2005 } else {
2006 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2007 nullptr, "MyAlloca");
2008 assert(Alloca->isStaticAlloca());
2009 }
2010 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2011 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2012 Alloca->setAlignment(FrameAlignment);
2013 return IRB.CreatePointerCast(Alloca, IntptrTy);
2014}
2015
Yury Gribov98b18592015-05-28 07:51:49 +00002016void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2017 BasicBlock &FirstBB = *F.begin();
2018 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2019 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2020 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2021 DynamicAllocaLayout->setAlignment(32);
2022}
2023
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002024void FunctionStackPoisoner::poisonStack() {
Yury Gribov55441bb2014-11-21 10:29:50 +00002025 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
2026
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002027 // Insert poison calls for lifetime intrinsics for alloca.
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002028 bool HavePoisonedStaticAllocas = false;
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002029 for (const auto &APC : AllocaPoisonCallVec) {
2030 assert(APC.InsBefore);
2031 assert(APC.AI);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002032 assert(ASan.isInterestingAlloca(*APC.AI));
Kuba Brecka7d03ce42016-06-27 15:57:08 +00002033 bool IsDynamicAlloca = !(*APC.AI).isStaticAlloca();
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002034 if (!ClInstrumentAllocas && IsDynamicAlloca)
2035 continue;
2036
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002037 IRBuilder<> IRB(APC.InsBefore);
2038 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002039 // Dynamic allocas will be unpoisoned unconditionally below in
2040 // unpoisonDynamicAllocas.
2041 // Flag that we need unpoison static allocas.
2042 HavePoisonedStaticAllocas |= (APC.DoPoison && !IsDynamicAlloca);
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002043 }
2044
Yury Gribov98b18592015-05-28 07:51:49 +00002045 if (ClInstrumentAllocas && DynamicAllocaVec.size() > 0) {
Yury Gribov55441bb2014-11-21 10:29:50 +00002046 // Handle dynamic allocas.
Yury Gribov98b18592015-05-28 07:51:49 +00002047 createDynamicAllocasInitStorage();
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002048 for (auto &AI : DynamicAllocaVec) handleDynamicAllocaCall(AI);
Yury Gribov98b18592015-05-28 07:51:49 +00002049
2050 unpoisonDynamicAllocas();
Kuba Breckaf5875d32015-02-24 09:47:05 +00002051 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002052
Hans Wennborg083ca9b2015-10-06 23:24:35 +00002053 if (AllocaVec.empty()) return;
Yury Gribov55441bb2014-11-21 10:29:50 +00002054
Kostya Serebryany6805de52013-09-10 13:16:56 +00002055 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002056 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00002057 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002058 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002059
2060 Instruction *InsBefore = AllocaVec[0];
2061 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002062 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002063
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002064 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2065 // debug info is broken, because only entry-block allocas are treated as
2066 // regular stack slots.
2067 auto InsBeforeB = InsBefore->getParent();
2068 assert(InsBeforeB == &F.getEntryBlock());
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002069 for (BasicBlock::iterator I(InsBefore); I != InsBeforeB->end(); ++I)
2070 if (auto *AI = dyn_cast<AllocaInst>(I))
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002071 if (NonInstrumentedStaticAllocaVec.count(AI) > 0)
2072 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00002073
Reid Kleckner2f907552015-07-21 17:40:14 +00002074 // If we have a call to llvm.localescape, keep it in the entry block.
2075 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2076
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002077 SmallVector<ASanStackVariableDescription, 16> SVD;
2078 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00002079 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002080 ASanStackVariableDescription D = {AI->getName().data(),
Vitaly Buka21a9e572016-07-28 22:50:50 +00002081 ASan.getAllocaSizeInBytes(*AI),
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002082 0,
2083 AI->getAlignment(),
2084 AI,
2085 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002086 SVD.push_back(D);
2087 }
2088 // Minimal header size (left redzone) is 4 pointers,
2089 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2090 size_t MinHeaderSize = ASan.LongSize / 2;
2091 ASanStackFrameLayout L;
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00002092 ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize, &L);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002093 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
2094 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002095 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2096 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00002097 bool DoDynamicAlloca = ClDynamicAllocaStack;
2098 // Don't do dynamic alloca or stack malloc if:
2099 // 1) There is inline asm: too often it makes assumptions on which registers
2100 // are available.
2101 // 2) There is a returns_twice call (typically setjmp), which is
2102 // optimization-hostile, and doesn't play well with introduced indirect
2103 // register-relative calculation of local variable addresses.
2104 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2105 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002106
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002107 Value *StaticAlloca =
2108 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2109
2110 Value *FakeStack;
2111 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002112
2113 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002114 // void *FakeStack = __asan_option_detect_stack_use_after_return
2115 // ? __asan_stack_malloc_N(LocalStackSize)
2116 // : nullptr;
2117 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002118 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2119 kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2120 Value *UseAfterReturnIsEnabled =
2121 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002122 Constant::getNullValue(IRB.getInt32Ty()));
2123 Instruction *Term =
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002124 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002125 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002126 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002127 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2128 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2129 Value *FakeStackValue =
2130 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2131 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002132 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002133 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002134 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002135 ConstantInt::get(IntptrTy, 0));
2136
2137 Value *NoFakeStack =
2138 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2139 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2140 IRBIf.SetInsertPoint(Term);
2141 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2142 Value *AllocaValue =
2143 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2144 IRB.SetInsertPoint(InsBefore);
2145 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2146 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2147 } else {
2148 // void *FakeStack = nullptr;
2149 // void *LocalStackBase = alloca(LocalStackSize);
2150 FakeStack = ConstantInt::get(IntptrTy, 0);
2151 LocalStackBase =
2152 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002153 }
2154
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002155 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002156 for (const auto &Desc : SVD) {
2157 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00002158 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00002159 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002160 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00002161 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002162 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002163 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002164
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002165 // The left-most redzone has enough space for at least 4 pointers.
2166 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002167 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2168 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2169 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002170 // Write the frame description constant to redzone[1].
2171 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002172 IRB.CreateAdd(LocalStackBase,
2173 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2174 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00002175 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00002176 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002177 /*AllowMerging*/ true);
2178 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002179 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002180 // Write the PC to redzone[2].
2181 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002182 IRB.CreateAdd(LocalStackBase,
2183 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2184 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002185 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002186
2187 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002188 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002189 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002190
Vitaly Buka79b75d32016-06-09 23:05:35 +00002191 auto UnpoisonStack = [&](IRBuilder<> &IRB) {
Vitaly Buka1ce73ef2016-08-16 16:24:10 +00002192 // Do this always as poisonAlloca can be disabled with
2193 // detect_stack_use_after_scope=0.
2194 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, false);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002195 if (HavePoisonedStaticAllocas) {
Vitaly Buka79b75d32016-06-09 23:05:35 +00002196 // If we poisoned some allocas in llvm.lifetime analysis,
2197 // unpoison whole stack frame now.
2198 poisonAlloca(LocalStackBase, LocalStackSize, IRB, false);
Vitaly Buka79b75d32016-06-09 23:05:35 +00002199 }
2200 };
2201
Kostya Serebryany530e2072013-12-23 14:15:08 +00002202 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002203 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002204 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002205 // Mark the current frame as retired.
2206 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2207 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002208 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00002209 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002210 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00002211 // // In use-after-return mode, poison the whole stack frame.
2212 // if StackMallocIdx <= 4
2213 // // For small sizes inline the whole thing:
2214 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002215 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00002216 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002217 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00002218 // else
2219 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002220 Value *Cmp =
2221 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00002222 TerminatorInst *ThenTerm, *ElseTerm;
2223 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2224
2225 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002226 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002227 int ClassSize = kMinStackMallocSize << StackMallocIdx;
Vitaly Buka170dede2016-08-19 17:15:38 +00002228 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
2229 ClassSize >> Mapping.Scale);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002230 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002231 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002232 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2233 Value *SavedFlagPtr = IRBPoison.CreateLoad(
2234 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2235 IRBPoison.CreateStore(
2236 Constant::getNullValue(IRBPoison.getInt8Ty()),
2237 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2238 } else {
2239 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00002240 IRBPoison.CreateCall(
2241 AsanStackFreeFunc[StackMallocIdx],
2242 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002243 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00002244
2245 IRBuilder<> IRBElse(ElseTerm);
Vitaly Buka79b75d32016-06-09 23:05:35 +00002246 UnpoisonStack(IRBElse);
Kostya Serebryany530e2072013-12-23 14:15:08 +00002247 } else {
Vitaly Buka79b75d32016-06-09 23:05:35 +00002248 UnpoisonStack(IRBRet);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002249 }
2250 }
2251
Kostya Serebryany09959942012-10-19 06:20:53 +00002252 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002253 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002254}
Alexey Samsonov261177a2012-12-04 01:34:23 +00002255
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002256void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00002257 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00002258 // For now just insert the call to ASan runtime.
2259 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2260 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002261 IRB.CreateCall(
2262 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2263 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00002264}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002265
2266// Handling llvm.lifetime intrinsics for a given %alloca:
2267// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2268// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2269// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2270// could be poisoned by previous llvm.lifetime.end instruction, as the
2271// variable may go in and out of scope several times, e.g. in loops).
2272// (3) if we poisoned at least one %alloca in a function,
2273// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002274
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002275AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2276 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
2277 // We're intested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00002278 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002279 // See if we've already calculated (or started to calculate) alloca for a
2280 // given value.
2281 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002282 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002283 // Store 0 while we're calculating alloca for value V to avoid
2284 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00002285 AllocaForValue[V] = nullptr;
2286 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002287 if (CastInst *CI = dyn_cast<CastInst>(V))
2288 Res = findAllocaForValue(CI->getOperand(0));
2289 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00002290 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002291 // Allow self-referencing phi-nodes.
2292 if (IncValue == PN) continue;
2293 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2294 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00002295 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2296 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002297 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002298 }
Vitaly Buka53054a72016-07-22 00:56:17 +00002299 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
2300 Res = findAllocaForValue(EP->getPointerOperand());
2301 } else {
2302 DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V << "\n");
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002303 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002304 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002305 return Res;
2306}
Yury Gribov55441bb2014-11-21 10:29:50 +00002307
Yury Gribov98b18592015-05-28 07:51:49 +00002308void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00002309 IRBuilder<> IRB(AI);
2310
Yury Gribov55441bb2014-11-21 10:29:50 +00002311 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2312 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2313
2314 Value *Zero = Constant::getNullValue(IntptrTy);
2315 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2316 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00002317
2318 // Since we need to extend alloca with additional memory to locate
2319 // redzones, and OldSize is number of allocated blocks with
2320 // ElementSize size, get allocated memory size in bytes by
2321 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00002322 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002323 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00002324 Value *OldSize =
2325 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2326 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00002327
2328 // PartialSize = OldSize % 32
2329 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2330
2331 // Misalign = kAllocaRzSize - PartialSize;
2332 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2333
2334 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2335 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2336 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2337
2338 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2339 // Align is added to locate left redzone, PartialPadding for possible
2340 // partial redzone and kAllocaRzSize for right redzone respectively.
2341 Value *AdditionalChunkSize = IRB.CreateAdd(
2342 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2343
2344 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2345
2346 // Insert new alloca with new NewSize and Align params.
2347 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2348 NewAlloca->setAlignment(Align);
2349
2350 // NewAddress = Address + Align
2351 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2352 ConstantInt::get(IntptrTy, Align));
2353
Yury Gribov98b18592015-05-28 07:51:49 +00002354 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00002355 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00002356
2357 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2358 // for unpoisoning stuff.
2359 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2360
Yury Gribov55441bb2014-11-21 10:29:50 +00002361 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2362
Yury Gribov98b18592015-05-28 07:51:49 +00002363 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00002364 AI->replaceAllUsesWith(NewAddressPtr);
2365
Yury Gribov98b18592015-05-28 07:51:49 +00002366 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00002367 AI->eraseFromParent();
2368}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002369
2370// isSafeAccess returns true if Addr is always inbounds with respect to its
2371// base object. For example, it is a field access or an array access with
2372// constant inbounds index.
2373bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2374 Value *Addr, uint64_t TypeSize) const {
2375 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2376 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00002377 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002378 int64_t Offset = SizeOffset.second.getSExtValue();
2379 // Three checks are required to ensure safety:
2380 // . Offset >= 0 (since the offset is given from the base ptr)
2381 // . Size >= Offset (unsigned)
2382 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00002383 return Offset >= 0 && Size >= uint64_t(Offset) &&
2384 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002385}