blob: 33693eb5417db8407317a05df927ced404e91cfa [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
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000248// Debug flags.
249static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
250 cl::init(0));
251static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
252 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000253static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
254 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000255static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
256 cl::Hidden, cl::init(-1));
257static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
258 cl::Hidden, cl::init(-1));
259
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000260STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
261STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000262STATISTIC(NumOptimizedAccessesToGlobalVar,
263 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000264STATISTIC(NumOptimizedAccessesToStackVar,
265 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000266
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000267namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000268/// Frontend-provided metadata for source location.
269struct LocationMetadata {
270 StringRef Filename;
271 int LineNo;
272 int ColumnNo;
273
274 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
275
276 bool empty() const { return Filename.empty(); }
277
278 void parse(MDNode *MDN) {
279 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000280 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
281 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000282 LineNo =
283 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
284 ColumnNo =
285 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000286 }
287};
288
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000289/// Frontend-provided metadata for global variables.
290class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000291 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000292 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000293 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000294 LocationMetadata SourceLoc;
295 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000296 bool IsDynInit;
297 bool IsBlacklisted;
298 };
299
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000300 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000301
Keno Fischere03fae42015-12-05 14:42:34 +0000302 void reset() {
303 inited_ = false;
304 Entries.clear();
305 }
306
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000307 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000308 assert(!inited_);
309 inited_ = true;
310 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000311 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000312 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000313 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000314 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000315 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000316 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000317 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000318 // We can already have an entry for GV if it was merged with another
319 // global.
320 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000321 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
322 E.SourceLoc.parse(Loc);
323 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
324 E.Name = Name->getString();
325 ConstantInt *IsDynInit =
326 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000327 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000328 ConstantInt *IsBlacklisted =
329 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000330 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000331 }
332 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000333
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000334 /// Returns metadata entry for a given global.
335 Entry get(GlobalVariable *G) const {
336 auto Pos = Entries.find(G);
337 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000338 }
339
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000340 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000341 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000342 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000343};
344
Alexey Samsonov1345d352013-01-16 13:23:28 +0000345/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000346/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000347struct ShadowMapping {
348 int Scale;
349 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000350 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000351};
352
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000353static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
354 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000355 bool IsAndroid = TargetTriple.isAndroid();
Anna Zaks3b50e702016-02-02 22:05:07 +0000356 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000357 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
358 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000359 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
360 TargetTriple.getArch() == llvm::Triple::ppc64le;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000361 bool IsSystemZ = TargetTriple.getArch() == llvm::Triple::systemz;
Anna Zaks3b50e702016-02-02 22:05:07 +0000362 bool IsX86 = TargetTriple.getArch() == llvm::Triple::x86;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000363 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000364 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
365 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000366 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
367 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000368 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000369 bool IsWindows = TargetTriple.isOSWindows();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000370
371 ShadowMapping Mapping;
372
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000373 if (LongSize == 32) {
Evgeniy Stepanov9cb08f82015-07-17 23:51:18 +0000374 // Android is always PIE, which means that the beginning of the address
375 // space is always available.
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000376 if (IsAndroid)
377 Mapping.Offset = 0;
378 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000379 Mapping.Offset = kMIPS32_ShadowOffset32;
380 else if (IsFreeBSD)
381 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000382 else if (IsIOS)
Anna Zaks3b50e702016-02-02 22:05:07 +0000383 // If we're targeting iOS and x86, the binary is built for iOS simulator.
384 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000385 else if (IsWindows)
386 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000387 else
388 Mapping.Offset = kDefaultShadowOffset32;
389 } else { // LongSize == 64
390 if (IsPPC64)
391 Mapping.Offset = kPPC64_ShadowOffset64;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000392 else if (IsSystemZ)
393 Mapping.Offset = kSystemZ_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000394 else if (IsFreeBSD)
395 Mapping.Offset = kFreeBSD_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000396 else if (IsLinux && IsX86_64) {
397 if (IsKasan)
398 Mapping.Offset = kLinuxKasan_ShadowOffset64;
399 else
400 Mapping.Offset = kSmallX86_64ShadowOffset;
Etienne Bergeron70684f92016-06-21 15:07:29 +0000401 } else if (IsWindows && IsX86_64) {
402 Mapping.Offset = kWindowsShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000403 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000404 Mapping.Offset = kMIPS64_ShadowOffset64;
Anna Zaks3b50e702016-02-02 22:05:07 +0000405 else if (IsIOS)
406 // If we're targeting iOS and x86, the binary is built for iOS simulator.
407 Mapping.Offset = IsX86_64 ? kIOSSimShadowOffset64 : kIOSShadowOffset64;
Renato Golinaf213722015-02-03 11:20:45 +0000408 else if (IsAArch64)
409 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000410 else
411 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000412 }
413
414 Mapping.Scale = kDefaultShadowScale;
Ryan Govostes3f37df02016-05-06 10:25:22 +0000415 if (ClMappingScale.getNumOccurrences() > 0) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000416 Mapping.Scale = ClMappingScale;
417 }
418
Ryan Govostes3f37df02016-05-06 10:25:22 +0000419 if (ClMappingOffset.getNumOccurrences() > 0) {
420 Mapping.Offset = ClMappingOffset;
421 }
422
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000423 // OR-ing shadow offset if more efficient (at least on x86) if the offset
424 // is a power of two, but on ppc64 we have to use add since the shadow
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000425 // offset is not necessary 1/8-th of the address space. On SystemZ,
426 // we could OR the constant in a single instruction, but it's more
427 // efficient to load it once and use indexed addressing.
428 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ
Adhemerval Zanella35891fe2015-11-09 18:03:48 +0000429 && !(Mapping.Offset & (Mapping.Offset - 1));
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000430
Alexey Samsonov1345d352013-01-16 13:23:28 +0000431 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000432}
433
Alexey Samsonov1345d352013-01-16 13:23:28 +0000434static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000435 // Redzone used for stack and globals is at least 32 bytes.
436 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000437 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000438}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000439
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000440/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000441struct AddressSanitizer : public FunctionPass {
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000442 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
443 bool UseAfterScope = false)
Yury Gribovd7731982015-11-11 10:36:49 +0000444 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000445 Recover(Recover || ClRecover),
446 UseAfterScope(UseAfterScope || ClUseAfterScope) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000447 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
448 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000449 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000450 return "AddressSanitizerFunctionPass";
451 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000452 void getAnalysisUsage(AnalysisUsage &AU) const override {
453 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000454 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000455 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000456 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
457 Type *Ty = AI->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000458 uint64_t SizeInBytes =
459 AI->getModule()->getDataLayout().getTypeAllocSize(Ty);
Anna Zaks8ed1d812015-02-27 03:12:36 +0000460 return SizeInBytes;
461 }
462 /// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000463 bool isInterestingAlloca(AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000464
465 // Check if we have dynamic alloca.
466 bool isDynamicAlloca(AllocaInst &AI) const {
467 return AI.isArrayAllocation() || !AI.isStaticAlloca();
468 }
469
Anna Zaks8ed1d812015-02-27 03:12:36 +0000470 /// If it is an interesting memory access, return the PointerOperand
471 /// and set IsWrite/Alignment. Otherwise return nullptr.
472 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000473 uint64_t *TypeSize, unsigned *Alignment);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000474 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000475 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000476 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000477 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
478 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000479 Value *SizeArgument, bool UseCalls, uint32_t Exp);
480 void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
481 uint32_t TypeSize, bool IsWrite,
482 Value *SizeArgument, bool UseCalls,
483 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000484 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
485 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000486 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000487 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000488 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000489 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000490 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000491 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000492 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000493 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000494 bool doInitialization(Module &M) override;
Keno Fischere03fae42015-12-05 14:42:34 +0000495 bool doFinalization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000496 static char ID; // Pass identification, replacement for typeid
497
Yury Gribov3ae427d2014-12-01 08:47:58 +0000498 DominatorTree &getDominatorTree() const { return *DT; }
499
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000500 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000501 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000502
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000503 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000504 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000505 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
506 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000507
Reid Kleckner2f907552015-07-21 17:40:14 +0000508 /// Helper to cleanup per-function state.
509 struct FunctionStateRAII {
510 AddressSanitizer *Pass;
511 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
512 assert(Pass->ProcessedAllocas.empty() &&
513 "last pass forgot to clear cache");
514 }
515 ~FunctionStateRAII() { Pass->ProcessedAllocas.clear(); }
516 };
517
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000518 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000519 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000520 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000521 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000522 bool Recover;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000523 bool UseAfterScope;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000524 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000525 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000526 DominatorTree *DT;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000527 Function *AsanCtorFunction = nullptr;
528 Function *AsanInitFunction = nullptr;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000529 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000530 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000531 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
532 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
533 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
534 // This array is indexed by AccessIsWrite and Experiment.
535 Function *AsanErrorCallbackSized[2][2];
536 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000537 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000538 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000539 GlobalsMetadata GlobalsMD;
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000540 DenseMap<AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000541
542 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000543};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000544
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000545class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000546 public:
Yury Gribovd7731982015-11-11 10:36:49 +0000547 explicit AddressSanitizerModule(bool CompileKernel = false,
548 bool Recover = false)
549 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
550 Recover(Recover || ClRecover) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000551 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000552 static char ID; // Pass identification, replacement for typeid
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000553 const char *getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000554
Kostya Serebryany20a79972012-11-22 03:18:50 +0000555 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000556 void initializeCallbacks(Module &M);
557
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000558 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000559 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000560 bool ShouldUseMachOGlobalsSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000561 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000562 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000563 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000564 return RedzoneSizeForScale(Mapping.Scale);
565 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000566
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000567 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000568 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000569 bool Recover;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000570 Type *IntptrTy;
571 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000572 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000573 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000574 Function *AsanPoisonGlobals;
575 Function *AsanUnpoisonGlobals;
576 Function *AsanRegisterGlobals;
577 Function *AsanUnregisterGlobals;
Ryan Govostes653f9d02016-03-28 20:28:57 +0000578 Function *AsanRegisterImageGlobals;
579 Function *AsanUnregisterImageGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000580};
581
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000582// Stack poisoning does not play well with exception handling.
583// When an exception is thrown, we essentially bypass the code
584// that unpoisones the stack. This is why the run-time library has
585// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
586// stack in the interceptor. This however does not work inside the
587// actual function which catches the exception. Most likely because the
588// compiler hoists the load of the shadow value somewhere too high.
589// This causes asan to report a non-existing bug on 453.povray.
590// It sounds like an LLVM bug.
591struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
592 Function &F;
593 AddressSanitizer &ASan;
594 DIBuilder DIB;
595 LLVMContext *C;
596 Type *IntptrTy;
597 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000598 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000599
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000600 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000601 SmallSetVector<AllocaInst *, 16> NonInstrumentedStaticAllocaVec;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000602 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000603 unsigned StackAlignment;
604
Kostya Serebryany6805de52013-09-10 13:16:56 +0000605 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000606 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000607 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000608 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000609
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000610 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
611 struct AllocaPoisonCall {
612 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000613 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000614 uint64_t Size;
615 bool DoPoison;
616 };
617 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
618
Yury Gribov98b18592015-05-28 07:51:49 +0000619 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
620 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
621 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000622 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000623
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000624 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000625 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000626 AllocaForValueMapTy AllocaForValue;
627
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000628 bool HasNonEmptyInlineAsm = false;
629 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000630 std::unique_ptr<CallInst> EmptyInlineAsm;
631
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000632 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000633 : F(F),
634 ASan(ASan),
635 DIB(*F.getParent(), /*AllowUnresolved*/ false),
636 C(ASan.C),
637 IntptrTy(ASan.IntptrTy),
638 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
639 Mapping(ASan.Mapping),
640 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000641 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000642
643 bool runOnFunction() {
644 if (!ClStack) return false;
645 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000646 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000647
Yury Gribov55441bb2014-11-21 10:29:50 +0000648 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000649
650 initializeCallbacks(*F.getParent());
651
652 poisonStack();
653
654 if (ClDebugStack) {
655 DEBUG(dbgs() << F);
656 }
657 return true;
658 }
659
Yury Gribov55441bb2014-11-21 10:29:50 +0000660 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000661 // poisoned red zones around all of them.
662 // Then unpoison everything back before the function returns.
663 void poisonStack();
664
Yury Gribov98b18592015-05-28 07:51:49 +0000665 void createDynamicAllocasInitStorage();
666
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000667 // ----------------------- Visitors.
668 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000669 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000670
Yury Gribov98b18592015-05-28 07:51:49 +0000671 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
672 Value *SavedStack) {
673 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000674 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
675 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
676 // need to adjust extracted SP to compute the address of the most recent
677 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
678 // this purpose.
679 if (!isa<ReturnInst>(InstBefore)) {
680 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
681 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
682 {IntptrTy});
683
684 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
685
686 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
687 DynamicAreaOffset);
688 }
689
Yury Gribov781bce22015-05-28 08:03:28 +0000690 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000691 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000692 }
693
Yury Gribov55441bb2014-11-21 10:29:50 +0000694 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000695 void unpoisonDynamicAllocas() {
696 for (auto &Ret : RetVec)
697 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000698
Yury Gribov98b18592015-05-28 07:51:49 +0000699 for (auto &StackRestoreInst : StackRestoreVec)
700 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
701 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000702 }
703
Yury Gribov55441bb2014-11-21 10:29:50 +0000704 // Deploy and poison redzones around dynamic alloca call. To do this, we
705 // should replace this call with another one with changed parameters and
706 // replace all its uses with new address, so
707 // addr = alloca type, old_size, align
708 // is replaced by
709 // new_size = (old_size + additional_size) * sizeof(type)
710 // tmp = alloca i8, new_size, max(align, 32)
711 // addr = tmp + 32 (first 32 bytes are for the left redzone).
712 // Additional_size is added to make new memory allocation contain not only
713 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000714 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000715
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000716 /// \brief Collect Alloca instructions we want (and can) handle.
717 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000718 if (!ASan.isInterestingAlloca(AI)) {
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000719 if (AI.isStaticAlloca()) NonInstrumentedStaticAllocaVec.insert(&AI);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000720 return;
721 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000722
723 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Yury Gribov98b18592015-05-28 07:51:49 +0000724 if (ASan.isDynamicAlloca(AI))
725 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000726 else
727 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000728 }
729
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000730 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
731 /// errors.
732 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000733 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000734 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000735 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000736 if (!ASan.UseAfterScope)
737 return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000738 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000739 return;
740 // Found lifetime intrinsic, add ASan instrumentation if necessary.
741 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
742 // If size argument is undefined, don't do anything.
743 if (Size->isMinusOne()) return;
744 // Check that size doesn't saturate uint64_t and can
745 // be stored in IntptrTy.
746 const uint64_t SizeValue = Size->getValue().getLimitedValue();
747 if (SizeValue == ~0ULL ||
748 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
749 return;
750 // Find alloca instruction that corresponds to llvm.lifetime argument.
751 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
Vitaly Bukab451f1b2016-06-09 23:31:59 +0000752 if (!AI || !ASan.isInterestingAlloca(*AI))
753 return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000754 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000755 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000756 AllocaPoisonCallVec.push_back(APC);
757 }
758
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000759 void visitCallSite(CallSite CS) {
760 Instruction *I = CS.getInstruction();
761 if (CallInst *CI = dyn_cast<CallInst>(I)) {
762 HasNonEmptyInlineAsm |=
763 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
764 HasReturnsTwiceCall |= CI->canReturnTwice();
765 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000766 }
767
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000768 // ---------------------- Helpers.
769 void initializeCallbacks(Module &M);
770
Yury Gribov3ae427d2014-12-01 08:47:58 +0000771 bool doesDominateAllExits(const Instruction *I) const {
772 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000773 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000774 }
775 return true;
776 }
777
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000778 /// Finds alloca where the value comes from.
779 AllocaInst *findAllocaForValue(Value *V);
Craig Topper3af97222014-08-27 05:25:00 +0000780 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000781 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000782 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000783
784 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
785 int Size);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000786 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
787 bool Dynamic);
788 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
789 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000790};
791
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000792} // anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000793
794char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000795INITIALIZE_PASS_BEGIN(
796 AddressSanitizer, "asan",
797 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
798 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000799INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +0000800INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000801INITIALIZE_PASS_END(
802 AddressSanitizer, "asan",
803 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
804 false)
Yury Gribovd7731982015-11-11 10:36:49 +0000805FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000806 bool Recover,
807 bool UseAfterScope) {
Yury Gribovd7731982015-11-11 10:36:49 +0000808 assert(!CompileKernel || Recover);
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000809 return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000810}
811
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000812char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000813INITIALIZE_PASS(
814 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000815 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000816 "ModulePass",
817 false, false)
Yury Gribovd7731982015-11-11 10:36:49 +0000818ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
819 bool Recover) {
820 assert(!CompileKernel || Recover);
821 return new AddressSanitizerModule(CompileKernel, Recover);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000822}
823
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000824static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000825 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000826 assert(Res < kNumberOfAccessSizes);
827 return Res;
828}
829
Bill Wendling58f8cef2013-08-06 22:52:42 +0000830// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000831static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
832 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000833 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000834 // We use private linkage for module-local strings. If they can be merged
835 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000836 GlobalVariable *GV =
837 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000838 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000839 if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000840 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
841 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000842}
843
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000844/// \brief Create a global describing a source location.
845static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
846 LocationMetadata MD) {
847 Constant *LocData[] = {
848 createPrivateGlobalForString(M, MD.Filename, true),
849 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
850 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
851 };
852 auto LocStruct = ConstantStruct::getAnon(LocData);
853 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
854 GlobalValue::PrivateLinkage, LocStruct,
855 kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000856 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000857 return GV;
858}
859
Vedant Kumarf5ac6d42016-06-22 17:30:58 +0000860/// \brief Check if \p G has been created by a trusted compiler pass.
861static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
862 // Do not instrument asan globals.
863 if (G->getName().startswith(kAsanGenPrefix) ||
864 G->getName().startswith(kSanCovGenPrefix) ||
865 G->getName().startswith(kODRGenPrefix))
866 return true;
867
868 // Do not instrument gcov counter arrays.
869 if (G->getName() == "__llvm_gcov_ctr")
870 return true;
871
872 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000873}
874
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000875Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
876 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000877 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000878 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000879 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000880 if (Mapping.OrShadowOffset)
881 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
882 else
883 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000884}
885
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000886// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000887void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
888 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000889 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000890 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000891 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +0000892 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
893 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
894 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000895 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000896 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000897 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +0000898 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
899 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
900 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000901 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000902 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000903}
904
Anna Zaks8ed1d812015-02-27 03:12:36 +0000905/// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000906bool AddressSanitizer::isInterestingAlloca(AllocaInst &AI) {
907 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
908
909 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
910 return PreviouslySeenAllocaInfo->getSecond();
911
Yury Gribov98b18592015-05-28 07:51:49 +0000912 bool IsInteresting =
913 (AI.getAllocatedType()->isSized() &&
914 // alloca() may be called with 0 size, ignore it.
915 getAllocaSizeInBytes(&AI) > 0 &&
916 // We are only interested in allocas not promotable to registers.
917 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +0000918 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
919 // inalloca allocas are not treated as static, and we don't want
920 // dynamic alloca instrumentation for them as well.
921 !AI.isUsedWithInAlloca());
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000922
923 ProcessedAllocas[&AI] = IsInteresting;
924 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000925}
926
927/// If I is an interesting memory access, return the PointerOperand
928/// and set IsWrite/Alignment. Otherwise return nullptr.
929Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
930 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000931 uint64_t *TypeSize,
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000932 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000933 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000934 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000935
936 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000937 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000938 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000939 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000940 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000941 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000942 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000943 PtrOperand = LI->getPointerOperand();
944 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000945 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000946 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000947 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000948 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000949 PtrOperand = SI->getPointerOperand();
950 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000951 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000952 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000953 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000954 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000955 PtrOperand = RMW->getPointerOperand();
956 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000957 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000958 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000959 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000960 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000961 PtrOperand = XCHG->getPointerOperand();
Kostya Serebryany90241602012-05-30 09:04:06 +0000962 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000963
Anna Zaks644d9d32016-06-22 00:15:52 +0000964 // Do not instrument acesses from different address spaces; we cannot deal
965 // with them.
966 if (PtrOperand) {
967 Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
968 if (PtrTy->getPointerAddressSpace() != 0)
969 return nullptr;
970 }
971
Anna Zaks8ed1d812015-02-27 03:12:36 +0000972 // Treat memory accesses to promotable allocas as non-interesting since they
973 // will not cause memory violations. This greatly speeds up the instrumented
974 // executable at -O0.
975 if (ClSkipPromotableAllocas)
976 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
977 return isInterestingAlloca(*AI) ? AI : nullptr;
978
979 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000980}
981
Kostya Serebryany796f6552014-02-27 12:45:36 +0000982static bool isPointerOperand(Value *V) {
983 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
984}
985
986// This is a rough heuristic; it may cause both false positives and
987// false negatives. The proper implementation requires cooperation with
988// the frontend.
989static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
990 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000991 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000992 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000993 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000994 } else {
995 return false;
996 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +0000997 return isPointerOperand(I->getOperand(0)) &&
998 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +0000999}
1000
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001001bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1002 // If a global variable does not have dynamic initialization we don't
1003 // have to instrument it. However, if a global does not have initializer
1004 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001005 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001006}
1007
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001008void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1009 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +00001010 IRBuilder<> IRB(I);
1011 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1012 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
1013 for (int i = 0; i < 2; i++) {
1014 if (Param[i]->getType()->isPointerTy())
1015 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
1016 }
David Blaikieff6409d2015-05-18 22:13:54 +00001017 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001018}
1019
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001020void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001021 Instruction *I, bool UseCalls,
1022 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +00001023 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001024 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001025 uint64_t TypeSize = 0;
1026 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +00001027 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001028
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001029 // Optimization experiments.
1030 // The experiments can be used to evaluate potential optimizations that remove
1031 // instrumentation (assess false negatives). Instead of completely removing
1032 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1033 // experiments that want to remove instrumentation of this instruction).
1034 // If Exp is non-zero, this pass will emit special calls into runtime
1035 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1036 // make runtime terminate the program in a special way (with a different
1037 // exit status). Then you run the new compiler on a buggy corpus, collect
1038 // the special terminations (ideally, you don't see them at all -- no false
1039 // negatives) and make the decision on the optimization.
1040 uint32_t Exp = ClForceExperiment;
1041
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001042 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001043 // If initialization order checking is disabled, a simple access to a
1044 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001045 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001046 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001047 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1048 NumOptimizedAccessesToGlobalVar++;
1049 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001050 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001051 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001052
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001053 if (ClOpt && ClOptStack) {
1054 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001055 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001056 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1057 NumOptimizedAccessesToStackVar++;
1058 return;
1059 }
1060 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001061
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001062 if (IsWrite)
1063 NumInstrumentedWrites++;
1064 else
1065 NumInstrumentedReads++;
1066
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001067 unsigned Granularity = 1 << Mapping.Scale;
1068 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1069 // if the data is properly aligned.
1070 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1071 TypeSize == 128) &&
1072 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001073 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
1074 Exp);
1075 instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
1076 UseCalls, Exp);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001077}
1078
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001079Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1080 Value *Addr, bool IsWrite,
1081 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001082 Value *SizeArgument,
1083 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001084 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001085 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1086 CallInst *Call = nullptr;
1087 if (SizeArgument) {
1088 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001089 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1090 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001091 else
David Blaikieff6409d2015-05-18 22:13:54 +00001092 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1093 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001094 } else {
1095 if (Exp == 0)
1096 Call =
1097 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1098 else
David Blaikieff6409d2015-05-18 22:13:54 +00001099 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1100 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001101 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001102
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001103 // We don't do Call->setDoesNotReturn() because the BB already has
1104 // UnreachableInst at the end.
1105 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001106 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001107 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001108}
1109
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001110Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001111 Value *ShadowValue,
1112 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001113 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001114 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001115 Value *LastAccessedByte =
1116 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001117 // (Addr & (Granularity - 1)) + size - 1
1118 if (TypeSize / 8 > 1)
1119 LastAccessedByte = IRB.CreateAdd(
1120 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1121 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001122 LastAccessedByte =
1123 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001124 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1125 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1126}
1127
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001128void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001129 Instruction *InsertBefore, Value *Addr,
1130 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001131 Value *SizeArgument, bool UseCalls,
1132 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001133 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001134 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001135 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1136
1137 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001138 if (Exp == 0)
1139 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1140 AddrLong);
1141 else
David Blaikieff6409d2015-05-18 22:13:54 +00001142 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1143 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001144 return;
1145 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001146
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001147 Type *ShadowTy =
1148 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001149 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1150 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1151 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001152 Value *ShadowValue =
1153 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001154
1155 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001156 size_t Granularity = 1ULL << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001157 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001158
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001159 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001160 // We use branch weights for the slow path check, to indicate that the slow
1161 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001162 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1163 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001164 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001165 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001166 IRB.SetInsertPoint(CheckTerm);
1167 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001168 if (Recover) {
1169 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1170 } else {
1171 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001172 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001173 CrashTerm = new UnreachableInst(*C, CrashBlock);
1174 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1175 ReplaceInstWithInst(CheckTerm, NewTerm);
1176 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001177 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001178 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001179 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001180
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001181 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001182 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001183 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001184}
1185
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001186// Instrument unusual size or unusual alignment.
1187// We can not do it with a single check, so we do 1-byte check for the first
1188// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1189// to report the actual access size.
1190void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1191 Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1192 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1193 IRBuilder<> IRB(I);
1194 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1195 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1196 if (UseCalls) {
1197 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001198 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1199 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001200 else
David Blaikieff6409d2015-05-18 22:13:54 +00001201 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1202 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001203 } else {
1204 Value *LastByte = IRB.CreateIntToPtr(
1205 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1206 Addr->getType());
1207 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1208 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1209 }
1210}
1211
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001212void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1213 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001214 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001215 IRBuilder<> IRB(&GlobalInit.front(),
1216 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001217
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001218 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001219 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1220 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001221
1222 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001223 for (auto &BB : GlobalInit.getBasicBlockList())
1224 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001225 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001226}
1227
1228void AddressSanitizerModule::createInitializerPoisonCalls(
1229 Module &M, GlobalValue *ModuleName) {
1230 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1231
1232 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1233 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001234 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001235 ConstantStruct *CS = cast<ConstantStruct>(OP);
1236
1237 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001238 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001239 if (F->getName() == kAsanModuleCtorName) continue;
1240 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1241 // Don't instrument CTORs that will run before asan.module_ctor.
1242 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1243 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001244 }
1245 }
1246}
1247
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001248bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001249 Type *Ty = G->getValueType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001250 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001251
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001252 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001253 if (!Ty->isSized()) return false;
1254 if (!G->hasInitializer()) return false;
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001255 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001256 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001257 // Don't handle ODR linkage types and COMDATs since other modules may be built
1258 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001259 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1260 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1261 G->getLinkage() != GlobalVariable::InternalLinkage)
1262 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001263 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001264 // Two problems with thread-locals:
1265 // - The address of the main thread's copy can't be computed at link-time.
1266 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001267 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001268 // For now, just ignore this Global if the alignment is large.
1269 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001270
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001271 if (G->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001272 StringRef Section = G->getSection();
Kuba Brecka086e34b2014-12-05 21:32:46 +00001273
Anna Zaks11904602015-06-09 00:58:08 +00001274 // Globals from llvm.metadata aren't emitted, do not instrument them.
1275 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001276 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001277 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001278
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001279 // Do not instrument function pointers to initialization and termination
1280 // routines: dynamic linker will not properly handle redzones.
1281 if (Section.startswith(".preinit_array") ||
1282 Section.startswith(".init_array") ||
1283 Section.startswith(".fini_array")) {
1284 return false;
1285 }
1286
Anna Zaks11904602015-06-09 00:58:08 +00001287 // Callbacks put into the CRT initializer/terminator sections
1288 // should not be instrumented.
1289 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1290 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1291 if (Section.startswith(".CRT")) {
1292 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1293 return false;
1294 }
1295
Kuba Brecka1001bb52014-12-05 22:19:18 +00001296 if (TargetTriple.isOSBinFormatMachO()) {
1297 StringRef ParsedSegment, ParsedSection;
1298 unsigned TAA = 0, StubSize = 0;
1299 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001300 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1301 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001302 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001303
1304 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1305 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1306 // them.
1307 if (ParsedSegment == "__OBJC" ||
1308 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1309 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1310 return false;
1311 }
1312 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1313 // Constant CFString instances are compiled in the following way:
1314 // -- the string buffer is emitted into
1315 // __TEXT,__cstring,cstring_literals
1316 // -- the constant NSConstantString structure referencing that buffer
1317 // is placed into __DATA,__cfstring
1318 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1319 // Moreover, it causes the linker to crash on OS X 10.7
1320 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1321 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1322 return false;
1323 }
1324 // The linker merges the contents of cstring_literals and removes the
1325 // trailing zeroes.
1326 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1327 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1328 return false;
1329 }
1330 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001331 }
1332
1333 return true;
1334}
1335
Ryan Govostes653f9d02016-03-28 20:28:57 +00001336// On Mach-O platforms, we emit global metadata in a separate section of the
1337// binary in order to allow the linker to properly dead strip. This is only
1338// supported on recent versions of ld64.
1339bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
1340 if (!TargetTriple.isOSBinFormatMachO())
1341 return false;
1342
1343 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1344 return true;
1345 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001346 return true;
Ryan Govostes653f9d02016-03-28 20:28:57 +00001347 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1348 return true;
1349
1350 return false;
1351}
1352
Alexey Samsonov788381b2012-12-25 12:28:20 +00001353void AddressSanitizerModule::initializeCallbacks(Module &M) {
1354 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001355
Alexey Samsonov788381b2012-12-25 12:28:20 +00001356 // Declare our poisoning and unpoisoning functions.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001357 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001358 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001359 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001360 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001361 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001362 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001363
Alexey Samsonov788381b2012-12-25 12:28:20 +00001364 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001365 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001366 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001367 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001368 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001369 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1370 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001371 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001372
1373 // Declare the functions that find globals in a shared object and then invoke
1374 // the (un)register function on them.
1375 AsanRegisterImageGlobals = checkSanitizerInterfaceFunction(
1376 M.getOrInsertFunction(kAsanRegisterImageGlobalsName,
1377 IRB.getVoidTy(), IntptrTy, nullptr));
1378 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001379
Ryan Govostes653f9d02016-03-28 20:28:57 +00001380 AsanUnregisterImageGlobals = checkSanitizerInterfaceFunction(
1381 M.getOrInsertFunction(kAsanUnregisterImageGlobalsName,
1382 IRB.getVoidTy(), IntptrTy, nullptr));
1383 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001384}
1385
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001386// This function replaces all global variables with new variables that have
1387// trailing redzones. It also creates a function that poisons
1388// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001389bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001390 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001391
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001392 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1393
Alexey Samsonova02e6642014-05-29 18:40:48 +00001394 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001395 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001396 }
1397
1398 size_t n = GlobalsToChange.size();
1399 if (n == 0) return false;
1400
1401 // A global is described by a structure
1402 // size_t beg;
1403 // size_t size;
1404 // size_t size_with_redzone;
1405 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001406 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001407 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001408 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001409 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001410 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001411 StructType *GlobalStructTy =
1412 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001413 IntptrTy, IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001414 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001415
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001416 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001417
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001418 // We shouldn't merge same module names, as this string serves as unique
1419 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001420 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001421 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001422
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001423 auto &DL = M.getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001424 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001425 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001426 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001427
1428 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001429 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001430 // Create string holding the global name (use global name from metadata
1431 // if it's available, otherwise just write the name of global variable).
1432 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001433 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001434 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001435
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001436 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001437 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001438 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001439 // MinRZ <= RZ <= kMaxGlobalRedzone
1440 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001441 uint64_t RZ = std::max(
1442 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001443 uint64_t RightRedzoneSize = RZ;
1444 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001445 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001446 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001447 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1448
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001449 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001450 Constant *NewInitializer =
1451 ConstantStruct::get(NewTy, G->getInitializer(),
1452 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001453
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001454 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001455 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1456 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1457 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001458 GlobalVariable *NewGlobal =
1459 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1460 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001461 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001462 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001463
1464 Value *Indices2[2];
1465 Indices2[0] = IRB.getInt32(0);
1466 Indices2[1] = IRB.getInt32(0);
1467
1468 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001469 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001470 NewGlobal->takeName(G);
1471 G->eraseFromParent();
1472
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001473 Constant *SourceLoc;
1474 if (!MD.SourceLoc.empty()) {
1475 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1476 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1477 } else {
1478 SourceLoc = ConstantInt::get(IntptrTy, 0);
1479 }
1480
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001481 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
1482 GlobalValue *InstrumentedGlobal = NewGlobal;
1483
1484 bool CanUsePrivateAliases = TargetTriple.isOSBinFormatELF();
1485 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
1486 // Create local alias for NewGlobal to avoid crash on ODR between
1487 // instrumented and non-instrumented libraries.
1488 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
1489 NameForGlobal + M.getName(), NewGlobal);
1490
1491 // With local aliases, we need to provide another externally visible
1492 // symbol __odr_asan_XXX to detect ODR violation.
1493 auto *ODRIndicatorSym =
1494 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
1495 Constant::getNullValue(IRB.getInt8Ty()),
1496 kODRGenPrefix + NameForGlobal, nullptr,
1497 NewGlobal->getThreadLocalMode());
1498
1499 // Set meaningful attributes for indicator symbol.
1500 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
1501 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
1502 ODRIndicatorSym->setAlignment(1);
1503 ODRIndicator = ODRIndicatorSym;
1504 InstrumentedGlobal = GA;
1505 }
1506
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001507 Initializers[i] = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001508 GlobalStructTy,
1509 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001510 ConstantInt::get(IntptrTy, SizeInBytes),
1511 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1512 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001513 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001514 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
1515 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy), nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001516
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001517 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001518
Kostya Serebryany20343352012-10-17 13:40:06 +00001519 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001520 }
1521
Ryan Govostes653f9d02016-03-28 20:28:57 +00001522
1523 GlobalVariable *AllGlobals = nullptr;
1524 GlobalVariable *RegisteredFlag = nullptr;
1525
1526 // On recent Mach-O platforms, we emit the global metadata in a way that
1527 // allows the linker to properly strip dead globals.
1528 if (ShouldUseMachOGlobalsSection()) {
1529 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1530 // to look up the loaded image that contains it. Second, we can store in it
1531 // whether registration has already occurred, to prevent duplicate
1532 // registration.
1533 //
1534 // Common linkage allows us to coalesce needles defined in each object
1535 // file so that there's only one per shared library.
1536 RegisteredFlag = new GlobalVariable(
1537 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1538 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1539
1540 // We also emit a structure which binds the liveness of the global
1541 // variable to the metadata struct.
1542 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy, nullptr);
1543
1544 for (size_t i = 0; i < n; i++) {
1545 GlobalVariable *Metadata = new GlobalVariable(
1546 M, GlobalStructTy, false, GlobalVariable::InternalLinkage,
1547 Initializers[i], "");
1548 Metadata->setSection("__DATA,__asan_globals,regular");
1549 Metadata->setAlignment(1); // don't leave padding in between
1550
1551 auto LivenessBinder = ConstantStruct::get(LivenessTy,
1552 Initializers[i]->getAggregateElement(0u),
1553 ConstantExpr::getPointerCast(Metadata, IntptrTy),
1554 nullptr);
1555 GlobalVariable *Liveness = new GlobalVariable(
1556 M, LivenessTy, false, GlobalVariable::InternalLinkage,
1557 LivenessBinder, "");
1558 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1559 }
1560 } else {
1561 // On all other platfoms, we just emit an array of global metadata
1562 // structures.
1563 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1564 AllGlobals = new GlobalVariable(
1565 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1566 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1567 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001568
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001569 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001570 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001571 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001572
Ryan Govostes653f9d02016-03-28 20:28:57 +00001573 // Create a call to register the globals with the runtime.
1574 if (ShouldUseMachOGlobalsSection()) {
1575 IRB.CreateCall(AsanRegisterImageGlobals,
1576 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1577 } else {
1578 IRB.CreateCall(AsanRegisterGlobals,
1579 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1580 ConstantInt::get(IntptrTy, n)});
1581 }
1582
1583 // We also need to unregister globals at the end, e.g., when a shared library
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001584 // gets closed.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001585 Function *AsanDtorFunction =
1586 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1587 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001588 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1589 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001590
1591 if (ShouldUseMachOGlobalsSection()) {
1592 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1593 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1594 } else {
1595 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1596 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1597 ConstantInt::get(IntptrTy, n)});
1598 }
1599
Alexey Samsonov1f647502014-05-29 01:10:14 +00001600 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001601
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001602 DEBUG(dbgs() << M);
1603 return true;
1604}
1605
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001606bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001607 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001608 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001609 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001610 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001611 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001612 initializeCallbacks(M);
1613
1614 bool Changed = false;
1615
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001616 // TODO(glider): temporarily disabled globals instrumentation for KASan.
1617 if (ClGlobals && !CompileKernel) {
1618 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1619 assert(CtorFunc);
1620 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1621 Changed |= InstrumentGlobals(IRB, M);
1622 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001623
1624 return Changed;
1625}
1626
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001627void AddressSanitizer::initializeCallbacks(Module &M) {
1628 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001629 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001630 // IsWrite, TypeSize and Exp are encoded in the function name.
1631 for (int Exp = 0; Exp < 2; Exp++) {
1632 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1633 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1634 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001635 const std::string SuffixStr = CompileKernel ? "N" : "_n";
Yury Gribovd7731982015-11-11 10:36:49 +00001636 const std::string EndingStr = Recover ? "_noabort" : "";
Craig Toppere3dcce92015-08-01 22:20:21 +00001637 Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001638 AsanErrorCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001639 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001640 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001641 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1642 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001643 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001644 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001645 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1646 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1647 AccessSizeIndex++) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001648 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001649 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001650 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001651 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001652 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001653 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001654 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001655 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1656 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001657 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001658 }
1659 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00001660
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001661 const std::string MemIntrinCallbackPrefix =
1662 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001663 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001664 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001665 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001666 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001667 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001668 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001669 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001670 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001671 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001672
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001673 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001674 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001675
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001676 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001677 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001678 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001679 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001680 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1681 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1682 StringRef(""), StringRef(""),
1683 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001684}
1685
1686// virtual
1687bool AddressSanitizer::doInitialization(Module &M) {
1688 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001689
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001690 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001691
1692 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001693 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001694 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001695 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001696
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001697 if (!CompileKernel) {
1698 std::tie(AsanCtorFunction, AsanInitFunction) =
Kuba Brecka45dbffd2015-07-23 10:54:06 +00001699 createSanitizerCtorAndInitFunctions(
1700 M, kAsanModuleCtorName, kAsanInitName,
1701 /*InitArgTypes=*/{}, /*InitArgs=*/{}, kAsanVersionCheckName);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001702 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1703 }
1704 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001705 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001706}
1707
Keno Fischere03fae42015-12-05 14:42:34 +00001708bool AddressSanitizer::doFinalization(Module &M) {
1709 GlobalsMD.reset();
1710 return false;
1711}
1712
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001713bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1714 // For each NSObject descendant having a +load method, this method is invoked
1715 // by the ObjC runtime before any of the static constructors is called.
1716 // Therefore we need to instrument such methods with a call to __asan_init
1717 // at the beginning in order to initialize our runtime before any access to
1718 // the shadow memory.
1719 // We cannot just ignore these methods, because they may call other
1720 // instrumented functions.
1721 if (F.getName().find(" load]") != std::string::npos) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001722 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00001723 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001724 return true;
1725 }
1726 return false;
1727}
1728
Reid Kleckner2f907552015-07-21 17:40:14 +00001729void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
1730 // Find the one possible call to llvm.localescape and pre-mark allocas passed
1731 // to it as uninteresting. This assumes we haven't started processing allocas
1732 // yet. This check is done up front because iterating the use list in
1733 // isInterestingAlloca would be algorithmically slower.
1734 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
1735
1736 // Try to get the declaration of llvm.localescape. If it's not in the module,
1737 // we can exit early.
1738 if (!F.getParent()->getFunction("llvm.localescape")) return;
1739
1740 // Look for a call to llvm.localescape call in the entry block. It can't be in
1741 // any other block.
1742 for (Instruction &I : F.getEntryBlock()) {
1743 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
1744 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
1745 // We found a call. Mark all the allocas passed in as uninteresting.
1746 for (Value *Arg : II->arg_operands()) {
1747 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
1748 assert(AI && AI->isStaticAlloca() &&
1749 "non-static alloca arg to localescape");
1750 ProcessedAllocas[AI] = false;
1751 }
1752 break;
1753 }
1754 }
1755}
1756
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001757bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001758 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001759 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001760 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001761 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001762
Yury Gribov3ae427d2014-12-01 08:47:58 +00001763 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1764
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001765 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001766 maybeInsertAsanInitAtFunctionEntry(F);
1767
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001768 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001769
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001770 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001771
Reid Kleckner2f907552015-07-21 17:40:14 +00001772 FunctionStateRAII CleanupObj(this);
1773
1774 // We can't instrument allocas used with llvm.localescape. Only static allocas
1775 // can be passed to that intrinsic.
1776 markEscapedLocalAllocas(F);
1777
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001778 // We want to instrument every address only once per basic block (unless there
1779 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001780 SmallSet<Value *, 16> TempsToInstrument;
1781 SmallVector<Instruction *, 16> ToInstrument;
1782 SmallVector<Instruction *, 8> NoReturnCalls;
1783 SmallVector<BasicBlock *, 16> AllBlocks;
1784 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001785 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001786 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001787 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001788 uint64_t TypeSize;
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00001789 const TargetLibraryInfo *TLI =
1790 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001791
1792 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001793 for (auto &BB : F) {
1794 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001795 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001796 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001797 for (auto &Inst : BB) {
1798 if (LooksLikeCodeInBug11395(&Inst)) return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001799 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1800 &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001801 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001802 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001803 continue; // We've seen this temp in the current BB.
1804 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001805 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001806 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1807 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001808 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001809 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001810 // ok, take it.
1811 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001812 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001813 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001814 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001815 // A call inside BB.
1816 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001817 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001818 }
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00001819 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
1820 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001821 continue;
1822 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001823 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001824 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001825 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001826 }
1827 }
1828
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001829 bool UseCalls =
1830 CompileKernel ||
1831 (ClInstrumentationWithCallsThreshold >= 0 &&
1832 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001833 const DataLayout &DL = F.getParent()->getDataLayout();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001834 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1835 /*RoundToAlign=*/true);
1836
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001837 // Instrument.
1838 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001839 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001840 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1841 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001842 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001843 instrumentMop(ObjSizeVis, Inst, UseCalls,
1844 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001845 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001846 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001847 }
1848 NumInstrumented++;
1849 }
1850
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001851 FunctionStackPoisoner FSP(F, *this);
1852 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001853
1854 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1855 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001856 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001857 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00001858 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001859 }
1860
Alexey Samsonova02e6642014-05-29 18:40:48 +00001861 for (auto Inst : PointerComparisonsOrSubtracts) {
1862 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001863 NumInstrumented++;
1864 }
1865
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001866 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001867
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001868 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1869
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001870 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001871}
1872
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001873// Workaround for bug 11395: we don't want to instrument stack in functions
1874// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1875// FIXME: remove once the bug 11395 is fixed.
1876bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1877 if (LongSize != 32) return false;
1878 CallInst *CI = dyn_cast<CallInst>(I);
1879 if (!CI || !CI->isInlineAsm()) return false;
1880 if (CI->getNumArgOperands() <= 5) return false;
1881 // We have inline assembly with quite a few arguments.
1882 return true;
1883}
1884
1885void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1886 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001887 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1888 std::string Suffix = itostr(i);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001889 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1890 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1891 IntptrTy, nullptr));
1892 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001893 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1894 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001895 }
Vitaly Buka79b75d32016-06-09 23:05:35 +00001896 if (ASan.UseAfterScope) {
1897 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
1898 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1899 IntptrTy, IntptrTy, nullptr));
1900 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
1901 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1902 IntptrTy, IntptrTy, nullptr));
1903 }
1904
Yury Gribov98b18592015-05-28 07:51:49 +00001905 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1906 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1907 AsanAllocasUnpoisonFunc =
1908 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1909 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001910}
1911
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001912void FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1913 IRBuilder<> &IRB, Value *ShadowBase,
1914 bool DoPoison) {
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001915 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001916 size_t i = 0;
1917 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1918 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1919 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1920 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1921 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1922 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1923 uint64_t Val = 0;
1924 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001925 if (F.getParent()->getDataLayout().isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001926 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1927 else
1928 Val = (Val << 8) | ShadowBytes[i + j];
1929 }
1930 if (!Val) continue;
1931 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1932 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1933 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1934 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001935 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001936 }
1937}
1938
Kostya Serebryany6805de52013-09-10 13:16:56 +00001939// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1940// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1941static int StackMallocSizeClass(uint64_t LocalStackSize) {
1942 assert(LocalStackSize <= kMaxStackMallocSize);
1943 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001944 for (int i = 0;; i++, MaxSize *= 2)
1945 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00001946 llvm_unreachable("impossible LocalStackSize");
1947}
1948
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001949// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1950// We can not use MemSet intrinsic because it may end up calling the actual
1951// memset. Size is a multiple of 8.
1952// Currently this generates 8-byte stores on x86_64; it may be better to
1953// generate wider stores.
1954void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1955 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1956 assert(!(Size % 8));
Gabor Horvathfee04342015-03-16 09:53:42 +00001957
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001958 // kAsanStackAfterReturnMagic is 0xf5.
1959 const uint64_t kAsanStackAfterReturnMagic64 = 0xf5f5f5f5f5f5f5f5ULL;
Gabor Horvathfee04342015-03-16 09:53:42 +00001960
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001961 for (int i = 0; i < Size; i += 8) {
1962 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001963 IRB.CreateStore(
1964 ConstantInt::get(IRB.getInt64Ty(), kAsanStackAfterReturnMagic64),
1965 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001966 }
1967}
1968
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001969PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1970 Value *ValueIfTrue,
1971 Instruction *ThenTerm,
1972 Value *ValueIfFalse) {
1973 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1974 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1975 PHI->addIncoming(ValueIfFalse, CondBlock);
1976 BasicBlock *ThenBlock = ThenTerm->getParent();
1977 PHI->addIncoming(ValueIfTrue, ThenBlock);
1978 return PHI;
1979}
1980
1981Value *FunctionStackPoisoner::createAllocaForLayout(
1982 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
1983 AllocaInst *Alloca;
1984 if (Dynamic) {
1985 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
1986 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
1987 "MyAlloca");
1988 } else {
1989 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
1990 nullptr, "MyAlloca");
1991 assert(Alloca->isStaticAlloca());
1992 }
1993 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1994 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1995 Alloca->setAlignment(FrameAlignment);
1996 return IRB.CreatePointerCast(Alloca, IntptrTy);
1997}
1998
Yury Gribov98b18592015-05-28 07:51:49 +00001999void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2000 BasicBlock &FirstBB = *F.begin();
2001 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2002 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2003 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2004 DynamicAllocaLayout->setAlignment(32);
2005}
2006
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002007void FunctionStackPoisoner::poisonStack() {
Yury Gribov55441bb2014-11-21 10:29:50 +00002008 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
2009
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002010 // Insert poison calls for lifetime intrinsics for alloca.
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002011 bool HavePoisonedStaticAllocas = false;
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002012 for (const auto &APC : AllocaPoisonCallVec) {
2013 assert(APC.InsBefore);
2014 assert(APC.AI);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002015 assert(ASan.isInterestingAlloca(*APC.AI));
2016 bool IsDynamicAlloca = ASan.isDynamicAlloca(*APC.AI);
2017 if (!ClInstrumentAllocas && IsDynamicAlloca)
2018 continue;
2019
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002020 IRBuilder<> IRB(APC.InsBefore);
2021 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002022 // Dynamic allocas will be unpoisoned unconditionally below in
2023 // unpoisonDynamicAllocas.
2024 // Flag that we need unpoison static allocas.
2025 HavePoisonedStaticAllocas |= (APC.DoPoison && !IsDynamicAlloca);
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002026 }
2027
Yury Gribov98b18592015-05-28 07:51:49 +00002028 if (ClInstrumentAllocas && DynamicAllocaVec.size() > 0) {
Yury Gribov55441bb2014-11-21 10:29:50 +00002029 // Handle dynamic allocas.
Yury Gribov98b18592015-05-28 07:51:49 +00002030 createDynamicAllocasInitStorage();
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002031 for (auto &AI : DynamicAllocaVec) handleDynamicAllocaCall(AI);
Yury Gribov98b18592015-05-28 07:51:49 +00002032
2033 unpoisonDynamicAllocas();
Kuba Breckaf5875d32015-02-24 09:47:05 +00002034 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002035
Hans Wennborg083ca9b2015-10-06 23:24:35 +00002036 if (AllocaVec.empty()) return;
Yury Gribov55441bb2014-11-21 10:29:50 +00002037
Kostya Serebryany6805de52013-09-10 13:16:56 +00002038 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002039 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00002040 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002041 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002042
2043 Instruction *InsBefore = AllocaVec[0];
2044 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002045 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002046
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002047 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2048 // debug info is broken, because only entry-block allocas are treated as
2049 // regular stack slots.
2050 auto InsBeforeB = InsBefore->getParent();
2051 assert(InsBeforeB == &F.getEntryBlock());
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002052 for (BasicBlock::iterator I(InsBefore); I != InsBeforeB->end(); ++I)
2053 if (auto *AI = dyn_cast<AllocaInst>(I))
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002054 if (NonInstrumentedStaticAllocaVec.count(AI) > 0)
2055 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00002056
Reid Kleckner2f907552015-07-21 17:40:14 +00002057 // If we have a call to llvm.localescape, keep it in the entry block.
2058 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2059
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002060 SmallVector<ASanStackVariableDescription, 16> SVD;
2061 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00002062 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002063 ASanStackVariableDescription D = {AI->getName().data(),
2064 ASan.getAllocaSizeInBytes(AI),
2065 AI->getAlignment(), AI, 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002066 SVD.push_back(D);
2067 }
2068 // Minimal header size (left redzone) is 4 pointers,
2069 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2070 size_t MinHeaderSize = ASan.LongSize / 2;
2071 ASanStackFrameLayout L;
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00002072 ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize, &L);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002073 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
2074 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002075 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2076 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00002077 bool DoDynamicAlloca = ClDynamicAllocaStack;
2078 // Don't do dynamic alloca or stack malloc if:
2079 // 1) There is inline asm: too often it makes assumptions on which registers
2080 // are available.
2081 // 2) There is a returns_twice call (typically setjmp), which is
2082 // optimization-hostile, and doesn't play well with introduced indirect
2083 // register-relative calculation of local variable addresses.
2084 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2085 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002086
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002087 Value *StaticAlloca =
2088 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2089
2090 Value *FakeStack;
2091 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002092
2093 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002094 // void *FakeStack = __asan_option_detect_stack_use_after_return
2095 // ? __asan_stack_malloc_N(LocalStackSize)
2096 // : nullptr;
2097 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002098 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2099 kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2100 Value *UseAfterReturnIsEnabled =
2101 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002102 Constant::getNullValue(IRB.getInt32Ty()));
2103 Instruction *Term =
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002104 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002105 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002106 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002107 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2108 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2109 Value *FakeStackValue =
2110 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2111 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002112 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002113 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002114 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002115 ConstantInt::get(IntptrTy, 0));
2116
2117 Value *NoFakeStack =
2118 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2119 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2120 IRBIf.SetInsertPoint(Term);
2121 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2122 Value *AllocaValue =
2123 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2124 IRB.SetInsertPoint(InsBefore);
2125 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2126 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2127 } else {
2128 // void *FakeStack = nullptr;
2129 // void *LocalStackBase = alloca(LocalStackSize);
2130 FakeStack = ConstantInt::get(IntptrTy, 0);
2131 LocalStackBase =
2132 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002133 }
2134
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002135 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002136 for (const auto &Desc : SVD) {
2137 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00002138 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00002139 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002140 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00002141 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002142 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002143 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002144
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002145 // The left-most redzone has enough space for at least 4 pointers.
2146 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002147 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2148 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2149 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002150 // Write the frame description constant to redzone[1].
2151 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002152 IRB.CreateAdd(LocalStackBase,
2153 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2154 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00002155 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00002156 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002157 /*AllowMerging*/ true);
2158 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002159 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002160 // Write the PC to redzone[2].
2161 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002162 IRB.CreateAdd(LocalStackBase,
2163 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2164 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002165 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002166
2167 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002168 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002169 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002170
Vitaly Buka79b75d32016-06-09 23:05:35 +00002171 auto UnpoisonStack = [&](IRBuilder<> &IRB) {
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002172 if (HavePoisonedStaticAllocas) {
Vitaly Buka79b75d32016-06-09 23:05:35 +00002173 // If we poisoned some allocas in llvm.lifetime analysis,
2174 // unpoison whole stack frame now.
2175 poisonAlloca(LocalStackBase, LocalStackSize, IRB, false);
2176 } else {
2177 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, false);
2178 }
2179 };
2180
Kostya Serebryany530e2072013-12-23 14:15:08 +00002181 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002182 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002183 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002184 // Mark the current frame as retired.
2185 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2186 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002187 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00002188 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002189 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00002190 // // In use-after-return mode, poison the whole stack frame.
2191 // if StackMallocIdx <= 4
2192 // // For small sizes inline the whole thing:
2193 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002194 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00002195 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002196 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00002197 // else
2198 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002199 Value *Cmp =
2200 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00002201 TerminatorInst *ThenTerm, *ElseTerm;
2202 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2203
2204 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002205 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002206 int ClassSize = kMinStackMallocSize << StackMallocIdx;
2207 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
2208 ClassSize >> Mapping.Scale);
2209 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002210 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002211 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2212 Value *SavedFlagPtr = IRBPoison.CreateLoad(
2213 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2214 IRBPoison.CreateStore(
2215 Constant::getNullValue(IRBPoison.getInt8Ty()),
2216 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2217 } else {
2218 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00002219 IRBPoison.CreateCall(
2220 AsanStackFreeFunc[StackMallocIdx],
2221 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002222 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00002223
2224 IRBuilder<> IRBElse(ElseTerm);
Vitaly Buka79b75d32016-06-09 23:05:35 +00002225 UnpoisonStack(IRBElse);
Kostya Serebryany530e2072013-12-23 14:15:08 +00002226 } else {
Vitaly Buka79b75d32016-06-09 23:05:35 +00002227 UnpoisonStack(IRBRet);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002228 }
2229 }
2230
Kostya Serebryany09959942012-10-19 06:20:53 +00002231 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002232 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002233}
Alexey Samsonov261177a2012-12-04 01:34:23 +00002234
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002235void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00002236 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00002237 // For now just insert the call to ASan runtime.
2238 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2239 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002240 IRB.CreateCall(
2241 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2242 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00002243}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002244
2245// Handling llvm.lifetime intrinsics for a given %alloca:
2246// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2247// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2248// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2249// could be poisoned by previous llvm.lifetime.end instruction, as the
2250// variable may go in and out of scope several times, e.g. in loops).
2251// (3) if we poisoned at least one %alloca in a function,
2252// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002253
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002254AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2255 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
2256 // We're intested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00002257 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002258 // See if we've already calculated (or started to calculate) alloca for a
2259 // given value.
2260 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002261 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002262 // Store 0 while we're calculating alloca for value V to avoid
2263 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00002264 AllocaForValue[V] = nullptr;
2265 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002266 if (CastInst *CI = dyn_cast<CastInst>(V))
2267 Res = findAllocaForValue(CI->getOperand(0));
2268 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00002269 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002270 // Allow self-referencing phi-nodes.
2271 if (IncValue == PN) continue;
2272 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2273 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00002274 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2275 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002276 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002277 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002278 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002279 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002280 return Res;
2281}
Yury Gribov55441bb2014-11-21 10:29:50 +00002282
Yury Gribov98b18592015-05-28 07:51:49 +00002283void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00002284 IRBuilder<> IRB(AI);
2285
Yury Gribov55441bb2014-11-21 10:29:50 +00002286 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2287 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2288
2289 Value *Zero = Constant::getNullValue(IntptrTy);
2290 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2291 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00002292
2293 // Since we need to extend alloca with additional memory to locate
2294 // redzones, and OldSize is number of allocated blocks with
2295 // ElementSize size, get allocated memory size in bytes by
2296 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00002297 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002298 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00002299 Value *OldSize =
2300 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2301 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00002302
2303 // PartialSize = OldSize % 32
2304 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2305
2306 // Misalign = kAllocaRzSize - PartialSize;
2307 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2308
2309 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2310 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2311 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2312
2313 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2314 // Align is added to locate left redzone, PartialPadding for possible
2315 // partial redzone and kAllocaRzSize for right redzone respectively.
2316 Value *AdditionalChunkSize = IRB.CreateAdd(
2317 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2318
2319 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2320
2321 // Insert new alloca with new NewSize and Align params.
2322 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2323 NewAlloca->setAlignment(Align);
2324
2325 // NewAddress = Address + Align
2326 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2327 ConstantInt::get(IntptrTy, Align));
2328
Yury Gribov98b18592015-05-28 07:51:49 +00002329 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00002330 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00002331
2332 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2333 // for unpoisoning stuff.
2334 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2335
Yury Gribov55441bb2014-11-21 10:29:50 +00002336 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2337
Yury Gribov98b18592015-05-28 07:51:49 +00002338 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00002339 AI->replaceAllUsesWith(NewAddressPtr);
2340
Yury Gribov98b18592015-05-28 07:51:49 +00002341 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00002342 AI->eraseFromParent();
2343}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002344
2345// isSafeAccess returns true if Addr is always inbounds with respect to its
2346// base object. For example, it is a field access or an array access with
2347// constant inbounds index.
2348bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2349 Value *Addr, uint64_t TypeSize) const {
2350 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2351 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00002352 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002353 int64_t Offset = SizeOffset.second.getSExtValue();
2354 // Three checks are required to ensure safety:
2355 // . Offset >= 0 (since the offset is given from the base ptr)
2356 // . Size >= Offset (unsigned)
2357 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00002358 return Offset >= 0 && Size >= uint64_t(Offset) &&
2359 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002360}