blob: 599b2cc5b36dd663428012ade3e294eb55c122df [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;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000081
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000082static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000083static const size_t kMaxStackMallocSize = 1 << 16; // 64K
84static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
85static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
86
Craig Topperd3a34f82013-07-16 01:17:10 +000087static const char *const kAsanModuleCtorName = "asan.module_ctor";
88static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000089static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000090static const char *const kAsanReportErrorTemplate = "__asan_report_";
Craig Topperd3a34f82013-07-16 01:17:10 +000091static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000092static const char *const kAsanUnregisterGlobalsName =
93 "__asan_unregister_globals";
Ryan Govostes653f9d02016-03-28 20:28:57 +000094static const char *const kAsanRegisterImageGlobalsName =
95 "__asan_register_image_globals";
96static const char *const kAsanUnregisterImageGlobalsName =
97 "__asan_unregister_image_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +000098static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
99static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kuba Brecka45dbffd2015-07-23 10:54:06 +0000100static const char *const kAsanInitName = "__asan_init";
101static const char *const kAsanVersionCheckName =
Ryan Govostes653f9d02016-03-28 20:28:57 +0000102 "__asan_version_mismatch_check_v8";
Kostya Serebryany796f6552014-02-27 12:45:36 +0000103static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
104static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +0000105static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000106static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +0000107static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
108static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000109static const char *const kAsanGenPrefix = "__asan_gen_";
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000110static const char *const kODRGenPrefix = "__odr_asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000111static const char *const kSanCovGenPrefix = "__sancov_gen_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000112static const char *const kAsanPoisonStackMemoryName =
113 "__asan_poison_stack_memory";
114static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000115 "__asan_unpoison_stack_memory";
Ryan Govostes653f9d02016-03-28 20:28:57 +0000116static const char *const kAsanGlobalsRegisteredFlagName =
117 "__asan_globals_registered";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000118
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +0000119static const char *const kAsanOptionDetectUseAfterReturn =
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000120 "__asan_option_detect_stack_use_after_return";
121
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000122static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
123static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
Yury Gribov98b18592015-05-28 07:51:49 +0000124
Kostya Serebryany874dae62012-07-16 16:15:40 +0000125// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
126static const size_t kNumberOfAccessSizes = 5;
127
Yury Gribov55441bb2014-11-21 10:29:50 +0000128static const unsigned kAllocaRzSize = 32;
Yury Gribov55441bb2014-11-21 10:29:50 +0000129
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000130// Command-line flags.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000131static cl::opt<bool> ClEnableKasan(
132 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
133 cl::Hidden, cl::init(false));
Yury Gribovd7731982015-11-11 10:36:49 +0000134static cl::opt<bool> ClRecover(
135 "asan-recover",
136 cl::desc("Enable recovery mode (continue-after-error)."),
137 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000138
139// This flag may need to be replaced with -f[no-]asan-reads.
140static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000141 cl::desc("instrument read instructions"),
142 cl::Hidden, cl::init(true));
143static cl::opt<bool> ClInstrumentWrites(
144 "asan-instrument-writes", cl::desc("instrument write instructions"),
145 cl::Hidden, cl::init(true));
146static cl::opt<bool> ClInstrumentAtomics(
147 "asan-instrument-atomics",
148 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
149 cl::init(true));
150static cl::opt<bool> ClAlwaysSlowPath(
151 "asan-always-slow-path",
152 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
153 cl::init(false));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000154// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000155// in any given BB. Normally, this should be set to unlimited (INT_MAX),
156// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
157// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000158static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
159 "asan-max-ins-per-bb", cl::init(10000),
160 cl::desc("maximal number of instructions to instrument in any given BB"),
161 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000162// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000163static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
164 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000165static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Mike Aizatsky243b71f2016-04-21 22:00:13 +0000166 cl::desc("Check stack-use-after-return"),
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000167 cl::Hidden, cl::init(true));
Kostya Serebryanya83bfea2016-04-20 20:02:58 +0000168static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
169 cl::desc("Check stack-use-after-scope"),
170 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000171// This flag may need to be replaced with -f[no]asan-globals.
172static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000173 cl::desc("Handle global objects"), cl::Hidden,
174 cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000175static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000176 cl::desc("Handle C++ initializer order"),
177 cl::Hidden, cl::init(true));
178static cl::opt<bool> ClInvalidPointerPairs(
179 "asan-detect-invalid-pointer-pair",
180 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
181 cl::init(false));
182static cl::opt<unsigned> ClRealignStack(
183 "asan-realign-stack",
184 cl::desc("Realign stack to the value of this flag (power of two)"),
185 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000186static cl::opt<int> ClInstrumentationWithCallsThreshold(
187 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000188 cl::desc(
189 "If the function being instrumented contains more than "
190 "this number of memory accesses, use callbacks instead of "
191 "inline checks (-1 means never use callbacks)."),
192 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000193static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000194 "asan-memory-access-callback-prefix",
195 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
196 cl::init("__asan_"));
Yury Gribov55441bb2014-11-21 10:29:50 +0000197static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000198 cl::desc("instrument dynamic allocas"),
Alexey Samsonovf4fb5f52015-10-22 20:07:28 +0000199 cl::Hidden, cl::init(true));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000200static cl::opt<bool> ClSkipPromotableAllocas(
201 "asan-skip-promotable-allocas",
202 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
203 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000204
205// These flags allow to change the shadow mapping.
206// The shadow mapping looks like
Ryan Govostes3f37df02016-05-06 10:25:22 +0000207// Shadow = (Mem >> scale) + offset
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000208static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000209 cl::desc("scale of asan shadow mapping"),
210 cl::Hidden, cl::init(0));
Ryan Govostes6194ae62016-05-06 11:22:11 +0000211static cl::opt<unsigned long long> ClMappingOffset(
212 "asan-mapping-offset",
213 cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden,
214 cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000215
216// Optimization flags. Not user visible, used mostly for testing
217// and benchmarking the tool.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000218static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
219 cl::Hidden, cl::init(true));
220static cl::opt<bool> ClOptSameTemp(
221 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
222 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000223static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000224 cl::desc("Don't instrument scalar globals"),
225 cl::Hidden, cl::init(true));
226static cl::opt<bool> ClOptStack(
227 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
228 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000229
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000230static cl::opt<bool> ClDynamicAllocaStack(
231 "asan-stack-dynamic-alloca",
232 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000233 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000234
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000235static cl::opt<uint32_t> ClForceExperiment(
236 "asan-force-experiment",
237 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
238 cl::init(0));
239
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000240static cl::opt<bool>
241 ClUsePrivateAliasForGlobals("asan-use-private-alias",
242 cl::desc("Use private aliases for global"
243 " variables"),
244 cl::Hidden, cl::init(false));
245
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000246// Debug flags.
247static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
248 cl::init(0));
249static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
250 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000251static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
252 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000253static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
254 cl::Hidden, cl::init(-1));
255static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
256 cl::Hidden, cl::init(-1));
257
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000258STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
259STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000260STATISTIC(NumOptimizedAccessesToGlobalVar,
261 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000262STATISTIC(NumOptimizedAccessesToStackVar,
263 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000264
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000265namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000266/// Frontend-provided metadata for source location.
267struct LocationMetadata {
268 StringRef Filename;
269 int LineNo;
270 int ColumnNo;
271
272 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
273
274 bool empty() const { return Filename.empty(); }
275
276 void parse(MDNode *MDN) {
277 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000278 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
279 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000280 LineNo =
281 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
282 ColumnNo =
283 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000284 }
285};
286
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000287/// Frontend-provided metadata for global variables.
288class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000289 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000290 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000291 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000292 LocationMetadata SourceLoc;
293 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000294 bool IsDynInit;
295 bool IsBlacklisted;
296 };
297
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000298 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000299
Keno Fischere03fae42015-12-05 14:42:34 +0000300 void reset() {
301 inited_ = false;
302 Entries.clear();
303 }
304
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000305 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000306 assert(!inited_);
307 inited_ = true;
308 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000309 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000310 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000311 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000312 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000313 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000314 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000315 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000316 // We can already have an entry for GV if it was merged with another
317 // global.
318 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000319 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
320 E.SourceLoc.parse(Loc);
321 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
322 E.Name = Name->getString();
323 ConstantInt *IsDynInit =
324 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000325 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000326 ConstantInt *IsBlacklisted =
327 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000328 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000329 }
330 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000331
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000332 /// Returns metadata entry for a given global.
333 Entry get(GlobalVariable *G) const {
334 auto Pos = Entries.find(G);
335 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000336 }
337
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000338 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000339 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000340 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000341};
342
Alexey Samsonov1345d352013-01-16 13:23:28 +0000343/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000344/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000345struct ShadowMapping {
346 int Scale;
347 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000348 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000349};
350
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000351static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
352 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000353 bool IsAndroid = TargetTriple.isAndroid();
Anna Zaks3b50e702016-02-02 22:05:07 +0000354 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000355 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
356 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000357 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
358 TargetTriple.getArch() == llvm::Triple::ppc64le;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000359 bool IsSystemZ = TargetTriple.getArch() == llvm::Triple::systemz;
Anna Zaks3b50e702016-02-02 22:05:07 +0000360 bool IsX86 = TargetTriple.getArch() == llvm::Triple::x86;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000361 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000362 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
363 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000364 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
365 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000366 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000367 bool IsWindows = TargetTriple.isOSWindows();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000368
369 ShadowMapping Mapping;
370
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000371 if (LongSize == 32) {
Evgeniy Stepanov9cb08f82015-07-17 23:51:18 +0000372 // Android is always PIE, which means that the beginning of the address
373 // space is always available.
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000374 if (IsAndroid)
375 Mapping.Offset = 0;
376 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000377 Mapping.Offset = kMIPS32_ShadowOffset32;
378 else if (IsFreeBSD)
379 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000380 else if (IsIOS)
Anna Zaks3b50e702016-02-02 22:05:07 +0000381 // If we're targeting iOS and x86, the binary is built for iOS simulator.
382 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000383 else if (IsWindows)
384 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000385 else
386 Mapping.Offset = kDefaultShadowOffset32;
387 } else { // LongSize == 64
388 if (IsPPC64)
389 Mapping.Offset = kPPC64_ShadowOffset64;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000390 else if (IsSystemZ)
391 Mapping.Offset = kSystemZ_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000392 else if (IsFreeBSD)
393 Mapping.Offset = kFreeBSD_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000394 else if (IsLinux && IsX86_64) {
395 if (IsKasan)
396 Mapping.Offset = kLinuxKasan_ShadowOffset64;
397 else
398 Mapping.Offset = kSmallX86_64ShadowOffset;
399 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000400 Mapping.Offset = kMIPS64_ShadowOffset64;
Anna Zaks3b50e702016-02-02 22:05:07 +0000401 else if (IsIOS)
402 // If we're targeting iOS and x86, the binary is built for iOS simulator.
403 Mapping.Offset = IsX86_64 ? kIOSSimShadowOffset64 : kIOSShadowOffset64;
Renato Golinaf213722015-02-03 11:20:45 +0000404 else if (IsAArch64)
405 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000406 else
407 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000408 }
409
410 Mapping.Scale = kDefaultShadowScale;
Ryan Govostes3f37df02016-05-06 10:25:22 +0000411 if (ClMappingScale.getNumOccurrences() > 0) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000412 Mapping.Scale = ClMappingScale;
413 }
414
Ryan Govostes3f37df02016-05-06 10:25:22 +0000415 if (ClMappingOffset.getNumOccurrences() > 0) {
416 Mapping.Offset = ClMappingOffset;
417 }
418
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000419 // OR-ing shadow offset if more efficient (at least on x86) if the offset
420 // is a power of two, but on ppc64 we have to use add since the shadow
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000421 // offset is not necessary 1/8-th of the address space. On SystemZ,
422 // we could OR the constant in a single instruction, but it's more
423 // efficient to load it once and use indexed addressing.
424 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ
Adhemerval Zanella35891fe2015-11-09 18:03:48 +0000425 && !(Mapping.Offset & (Mapping.Offset - 1));
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000426
Alexey Samsonov1345d352013-01-16 13:23:28 +0000427 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000428}
429
Alexey Samsonov1345d352013-01-16 13:23:28 +0000430static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000431 // Redzone used for stack and globals is at least 32 bytes.
432 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000433 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000434}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000435
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000436/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000437struct AddressSanitizer : public FunctionPass {
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000438 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
439 bool UseAfterScope = false)
Yury Gribovd7731982015-11-11 10:36:49 +0000440 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000441 Recover(Recover || ClRecover),
442 UseAfterScope(UseAfterScope || ClUseAfterScope) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000443 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
444 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000445 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000446 return "AddressSanitizerFunctionPass";
447 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000448 void getAnalysisUsage(AnalysisUsage &AU) const override {
449 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000450 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000451 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000452 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
453 Type *Ty = AI->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000454 uint64_t SizeInBytes =
455 AI->getModule()->getDataLayout().getTypeAllocSize(Ty);
Anna Zaks8ed1d812015-02-27 03:12:36 +0000456 return SizeInBytes;
457 }
458 /// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000459 bool isInterestingAlloca(AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000460
461 // Check if we have dynamic alloca.
462 bool isDynamicAlloca(AllocaInst &AI) const {
463 return AI.isArrayAllocation() || !AI.isStaticAlloca();
464 }
465
Anna Zaks8ed1d812015-02-27 03:12:36 +0000466 /// If it is an interesting memory access, return the PointerOperand
467 /// and set IsWrite/Alignment. Otherwise return nullptr.
468 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000469 uint64_t *TypeSize, unsigned *Alignment);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000470 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000471 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000472 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000473 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
474 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000475 Value *SizeArgument, bool UseCalls, uint32_t Exp);
476 void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
477 uint32_t TypeSize, bool IsWrite,
478 Value *SizeArgument, bool UseCalls,
479 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000480 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
481 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000482 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000483 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000484 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000485 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000486 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000487 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000488 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000489 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000490 bool doInitialization(Module &M) override;
Keno Fischere03fae42015-12-05 14:42:34 +0000491 bool doFinalization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000492 static char ID; // Pass identification, replacement for typeid
493
Yury Gribov3ae427d2014-12-01 08:47:58 +0000494 DominatorTree &getDominatorTree() const { return *DT; }
495
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000496 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000497 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000498
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000499 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000500 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000501 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
502 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000503
Reid Kleckner2f907552015-07-21 17:40:14 +0000504 /// Helper to cleanup per-function state.
505 struct FunctionStateRAII {
506 AddressSanitizer *Pass;
507 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
508 assert(Pass->ProcessedAllocas.empty() &&
509 "last pass forgot to clear cache");
510 }
511 ~FunctionStateRAII() { Pass->ProcessedAllocas.clear(); }
512 };
513
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000514 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000515 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000516 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000517 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000518 bool Recover;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000519 bool UseAfterScope;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000520 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000521 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000522 DominatorTree *DT;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000523 Function *AsanCtorFunction = nullptr;
524 Function *AsanInitFunction = nullptr;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000525 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000526 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000527 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
528 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
529 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
530 // This array is indexed by AccessIsWrite and Experiment.
531 Function *AsanErrorCallbackSized[2][2];
532 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000533 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000534 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000535 GlobalsMetadata GlobalsMD;
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000536 DenseMap<AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000537
538 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000539};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000540
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000541class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000542 public:
Yury Gribovd7731982015-11-11 10:36:49 +0000543 explicit AddressSanitizerModule(bool CompileKernel = false,
544 bool Recover = false)
545 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
546 Recover(Recover || ClRecover) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000547 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000548 static char ID; // Pass identification, replacement for typeid
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000549 const char *getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000550
Kostya Serebryany20a79972012-11-22 03:18:50 +0000551 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000552 void initializeCallbacks(Module &M);
553
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000554 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000555 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000556 bool ShouldUseMachOGlobalsSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000557 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000558 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000559 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000560 return RedzoneSizeForScale(Mapping.Scale);
561 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000562
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000563 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000564 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000565 bool Recover;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000566 Type *IntptrTy;
567 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000568 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000569 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000570 Function *AsanPoisonGlobals;
571 Function *AsanUnpoisonGlobals;
572 Function *AsanRegisterGlobals;
573 Function *AsanUnregisterGlobals;
Ryan Govostes653f9d02016-03-28 20:28:57 +0000574 Function *AsanRegisterImageGlobals;
575 Function *AsanUnregisterImageGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000576};
577
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000578// Stack poisoning does not play well with exception handling.
579// When an exception is thrown, we essentially bypass the code
580// that unpoisones the stack. This is why the run-time library has
581// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
582// stack in the interceptor. This however does not work inside the
583// actual function which catches the exception. Most likely because the
584// compiler hoists the load of the shadow value somewhere too high.
585// This causes asan to report a non-existing bug on 453.povray.
586// It sounds like an LLVM bug.
587struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
588 Function &F;
589 AddressSanitizer &ASan;
590 DIBuilder DIB;
591 LLVMContext *C;
592 Type *IntptrTy;
593 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000594 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000595
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000596 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000597 SmallSetVector<AllocaInst *, 16> NonInstrumentedStaticAllocaVec;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000598 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000599 unsigned StackAlignment;
600
Kostya Serebryany6805de52013-09-10 13:16:56 +0000601 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000602 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000603 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000604 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000605
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000606 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
607 struct AllocaPoisonCall {
608 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000609 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000610 uint64_t Size;
611 bool DoPoison;
612 };
613 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
614
Yury Gribov98b18592015-05-28 07:51:49 +0000615 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
616 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
617 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000618 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000619
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000620 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000621 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000622 AllocaForValueMapTy AllocaForValue;
623
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000624 bool HasNonEmptyInlineAsm = false;
625 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000626 std::unique_ptr<CallInst> EmptyInlineAsm;
627
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000628 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000629 : F(F),
630 ASan(ASan),
631 DIB(*F.getParent(), /*AllowUnresolved*/ false),
632 C(ASan.C),
633 IntptrTy(ASan.IntptrTy),
634 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
635 Mapping(ASan.Mapping),
636 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000637 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000638
639 bool runOnFunction() {
640 if (!ClStack) return false;
641 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000642 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000643
Yury Gribov55441bb2014-11-21 10:29:50 +0000644 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000645
646 initializeCallbacks(*F.getParent());
647
648 poisonStack();
649
650 if (ClDebugStack) {
651 DEBUG(dbgs() << F);
652 }
653 return true;
654 }
655
Yury Gribov55441bb2014-11-21 10:29:50 +0000656 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000657 // poisoned red zones around all of them.
658 // Then unpoison everything back before the function returns.
659 void poisonStack();
660
Yury Gribov98b18592015-05-28 07:51:49 +0000661 void createDynamicAllocasInitStorage();
662
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000663 // ----------------------- Visitors.
664 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000665 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000666
Yury Gribov98b18592015-05-28 07:51:49 +0000667 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
668 Value *SavedStack) {
669 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000670 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
671 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
672 // need to adjust extracted SP to compute the address of the most recent
673 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
674 // this purpose.
675 if (!isa<ReturnInst>(InstBefore)) {
676 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
677 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
678 {IntptrTy});
679
680 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
681
682 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
683 DynamicAreaOffset);
684 }
685
Yury Gribov781bce22015-05-28 08:03:28 +0000686 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000687 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000688 }
689
Yury Gribov55441bb2014-11-21 10:29:50 +0000690 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000691 void unpoisonDynamicAllocas() {
692 for (auto &Ret : RetVec)
693 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000694
Yury Gribov98b18592015-05-28 07:51:49 +0000695 for (auto &StackRestoreInst : StackRestoreVec)
696 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
697 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000698 }
699
Yury Gribov55441bb2014-11-21 10:29:50 +0000700 // Deploy and poison redzones around dynamic alloca call. To do this, we
701 // should replace this call with another one with changed parameters and
702 // replace all its uses with new address, so
703 // addr = alloca type, old_size, align
704 // is replaced by
705 // new_size = (old_size + additional_size) * sizeof(type)
706 // tmp = alloca i8, new_size, max(align, 32)
707 // addr = tmp + 32 (first 32 bytes are for the left redzone).
708 // Additional_size is added to make new memory allocation contain not only
709 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000710 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000711
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000712 /// \brief Collect Alloca instructions we want (and can) handle.
713 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000714 if (!ASan.isInterestingAlloca(AI)) {
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000715 if (AI.isStaticAlloca()) NonInstrumentedStaticAllocaVec.insert(&AI);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000716 return;
717 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000718
719 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Yury Gribov98b18592015-05-28 07:51:49 +0000720 if (ASan.isDynamicAlloca(AI))
721 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000722 else
723 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000724 }
725
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000726 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
727 /// errors.
728 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000729 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000730 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000731 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000732 if (!ASan.UseAfterScope)
733 return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000734 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000735 return;
736 // Found lifetime intrinsic, add ASan instrumentation if necessary.
737 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
738 // If size argument is undefined, don't do anything.
739 if (Size->isMinusOne()) return;
740 // Check that size doesn't saturate uint64_t and can
741 // be stored in IntptrTy.
742 const uint64_t SizeValue = Size->getValue().getLimitedValue();
743 if (SizeValue == ~0ULL ||
744 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
745 return;
746 // Find alloca instruction that corresponds to llvm.lifetime argument.
747 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
Vitaly Bukab451f1b2016-06-09 23:31:59 +0000748 if (!AI || !ASan.isInterestingAlloca(*AI))
749 return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000750 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000751 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000752 AllocaPoisonCallVec.push_back(APC);
753 }
754
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000755 void visitCallSite(CallSite CS) {
756 Instruction *I = CS.getInstruction();
757 if (CallInst *CI = dyn_cast<CallInst>(I)) {
758 HasNonEmptyInlineAsm |=
759 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
760 HasReturnsTwiceCall |= CI->canReturnTwice();
761 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000762 }
763
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000764 // ---------------------- Helpers.
765 void initializeCallbacks(Module &M);
766
Yury Gribov3ae427d2014-12-01 08:47:58 +0000767 bool doesDominateAllExits(const Instruction *I) const {
768 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000769 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000770 }
771 return true;
772 }
773
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000774 /// Finds alloca where the value comes from.
775 AllocaInst *findAllocaForValue(Value *V);
Craig Topper3af97222014-08-27 05:25:00 +0000776 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000777 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000778 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000779
780 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
781 int Size);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000782 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
783 bool Dynamic);
784 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
785 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000786};
787
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000788} // anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000789
790char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000791INITIALIZE_PASS_BEGIN(
792 AddressSanitizer, "asan",
793 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
794 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000795INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +0000796INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000797INITIALIZE_PASS_END(
798 AddressSanitizer, "asan",
799 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
800 false)
Yury Gribovd7731982015-11-11 10:36:49 +0000801FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000802 bool Recover,
803 bool UseAfterScope) {
Yury Gribovd7731982015-11-11 10:36:49 +0000804 assert(!CompileKernel || Recover);
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000805 return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000806}
807
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000808char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000809INITIALIZE_PASS(
810 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000811 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000812 "ModulePass",
813 false, false)
Yury Gribovd7731982015-11-11 10:36:49 +0000814ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
815 bool Recover) {
816 assert(!CompileKernel || Recover);
817 return new AddressSanitizerModule(CompileKernel, Recover);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000818}
819
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000820static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000821 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000822 assert(Res < kNumberOfAccessSizes);
823 return Res;
824}
825
Bill Wendling58f8cef2013-08-06 22:52:42 +0000826// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000827static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
828 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000829 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000830 // We use private linkage for module-local strings. If they can be merged
831 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000832 GlobalVariable *GV =
833 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000834 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000835 if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000836 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
837 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000838}
839
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000840/// \brief Create a global describing a source location.
841static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
842 LocationMetadata MD) {
843 Constant *LocData[] = {
844 createPrivateGlobalForString(M, MD.Filename, true),
845 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
846 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
847 };
848 auto LocStruct = ConstantStruct::getAnon(LocData);
849 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
850 GlobalValue::PrivateLinkage, LocStruct,
851 kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000852 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000853 return GV;
854}
855
Kostya Serebryany139a9372012-11-20 14:16:08 +0000856static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
Benjamin Kramerf6f815b2016-05-27 16:54:57 +0000857 return G->getName().startswith(kAsanGenPrefix) ||
858 G->getName().startswith(kSanCovGenPrefix) ||
859 G->getName().startswith(kODRGenPrefix);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000860}
861
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000862Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
863 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000864 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000865 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000866 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000867 if (Mapping.OrShadowOffset)
868 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
869 else
870 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000871}
872
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000873// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000874void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
875 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000876 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000877 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000878 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +0000879 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
880 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
881 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000882 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000883 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000884 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +0000885 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
886 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
887 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000888 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000889 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000890}
891
Anna Zaks8ed1d812015-02-27 03:12:36 +0000892/// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000893bool AddressSanitizer::isInterestingAlloca(AllocaInst &AI) {
894 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
895
896 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
897 return PreviouslySeenAllocaInfo->getSecond();
898
Yury Gribov98b18592015-05-28 07:51:49 +0000899 bool IsInteresting =
900 (AI.getAllocatedType()->isSized() &&
901 // alloca() may be called with 0 size, ignore it.
902 getAllocaSizeInBytes(&AI) > 0 &&
903 // We are only interested in allocas not promotable to registers.
904 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +0000905 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
906 // inalloca allocas are not treated as static, and we don't want
907 // dynamic alloca instrumentation for them as well.
908 !AI.isUsedWithInAlloca());
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000909
910 ProcessedAllocas[&AI] = IsInteresting;
911 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000912}
913
914/// If I is an interesting memory access, return the PointerOperand
915/// and set IsWrite/Alignment. Otherwise return nullptr.
916Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
917 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000918 uint64_t *TypeSize,
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000919 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000920 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000921 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000922
923 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000924 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000925 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000926 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000927 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000928 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000929 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000930 PtrOperand = LI->getPointerOperand();
931 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000932 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000933 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000934 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000935 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000936 PtrOperand = SI->getPointerOperand();
937 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000938 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000939 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000940 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000941 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000942 PtrOperand = RMW->getPointerOperand();
943 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000944 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000945 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000946 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000947 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000948 PtrOperand = XCHG->getPointerOperand();
Kostya Serebryany90241602012-05-30 09:04:06 +0000949 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000950
951 // Treat memory accesses to promotable allocas as non-interesting since they
952 // will not cause memory violations. This greatly speeds up the instrumented
953 // executable at -O0.
954 if (ClSkipPromotableAllocas)
955 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
956 return isInterestingAlloca(*AI) ? AI : nullptr;
957
958 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000959}
960
Kostya Serebryany796f6552014-02-27 12:45:36 +0000961static bool isPointerOperand(Value *V) {
962 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
963}
964
965// This is a rough heuristic; it may cause both false positives and
966// false negatives. The proper implementation requires cooperation with
967// the frontend.
968static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
969 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000970 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000971 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000972 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000973 } else {
974 return false;
975 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +0000976 return isPointerOperand(I->getOperand(0)) &&
977 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +0000978}
979
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000980bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
981 // If a global variable does not have dynamic initialization we don't
982 // have to instrument it. However, if a global does not have initializer
983 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000984 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000985}
986
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000987void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
988 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +0000989 IRBuilder<> IRB(I);
990 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
991 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
992 for (int i = 0; i < 2; i++) {
993 if (Param[i]->getType()->isPointerTy())
994 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
995 }
David Blaikieff6409d2015-05-18 22:13:54 +0000996 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000997}
998
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000999void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001000 Instruction *I, bool UseCalls,
1001 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +00001002 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001003 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001004 uint64_t TypeSize = 0;
1005 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +00001006 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001007
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001008 // Optimization experiments.
1009 // The experiments can be used to evaluate potential optimizations that remove
1010 // instrumentation (assess false negatives). Instead of completely removing
1011 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1012 // experiments that want to remove instrumentation of this instruction).
1013 // If Exp is non-zero, this pass will emit special calls into runtime
1014 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1015 // make runtime terminate the program in a special way (with a different
1016 // exit status). Then you run the new compiler on a buggy corpus, collect
1017 // the special terminations (ideally, you don't see them at all -- no false
1018 // negatives) and make the decision on the optimization.
1019 uint32_t Exp = ClForceExperiment;
1020
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001021 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001022 // If initialization order checking is disabled, a simple access to a
1023 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001024 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001025 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001026 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1027 NumOptimizedAccessesToGlobalVar++;
1028 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001029 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001030 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001031
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001032 if (ClOpt && ClOptStack) {
1033 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001034 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001035 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1036 NumOptimizedAccessesToStackVar++;
1037 return;
1038 }
1039 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001040
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001041 if (IsWrite)
1042 NumInstrumentedWrites++;
1043 else
1044 NumInstrumentedReads++;
1045
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001046 unsigned Granularity = 1 << Mapping.Scale;
1047 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1048 // if the data is properly aligned.
1049 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1050 TypeSize == 128) &&
1051 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001052 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
1053 Exp);
1054 instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
1055 UseCalls, Exp);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001056}
1057
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001058Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1059 Value *Addr, bool IsWrite,
1060 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001061 Value *SizeArgument,
1062 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001063 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001064 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1065 CallInst *Call = nullptr;
1066 if (SizeArgument) {
1067 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001068 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1069 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001070 else
David Blaikieff6409d2015-05-18 22:13:54 +00001071 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1072 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001073 } else {
1074 if (Exp == 0)
1075 Call =
1076 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1077 else
David Blaikieff6409d2015-05-18 22:13:54 +00001078 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1079 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001080 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001081
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001082 // We don't do Call->setDoesNotReturn() because the BB already has
1083 // UnreachableInst at the end.
1084 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001085 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001086 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001087}
1088
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001089Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001090 Value *ShadowValue,
1091 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001092 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001093 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001094 Value *LastAccessedByte =
1095 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001096 // (Addr & (Granularity - 1)) + size - 1
1097 if (TypeSize / 8 > 1)
1098 LastAccessedByte = IRB.CreateAdd(
1099 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1100 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001101 LastAccessedByte =
1102 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001103 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1104 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1105}
1106
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001107void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001108 Instruction *InsertBefore, Value *Addr,
1109 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001110 Value *SizeArgument, bool UseCalls,
1111 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001112 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001113 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001114 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1115
1116 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001117 if (Exp == 0)
1118 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1119 AddrLong);
1120 else
David Blaikieff6409d2015-05-18 22:13:54 +00001121 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1122 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001123 return;
1124 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001125
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001126 Type *ShadowTy =
1127 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001128 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1129 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1130 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001131 Value *ShadowValue =
1132 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001133
1134 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001135 size_t Granularity = 1ULL << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001136 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001137
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001138 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001139 // We use branch weights for the slow path check, to indicate that the slow
1140 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001141 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1142 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001143 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001144 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001145 IRB.SetInsertPoint(CheckTerm);
1146 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001147 if (Recover) {
1148 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1149 } else {
1150 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001151 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001152 CrashTerm = new UnreachableInst(*C, CrashBlock);
1153 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1154 ReplaceInstWithInst(CheckTerm, NewTerm);
1155 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001156 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001157 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001158 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001159
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001160 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001161 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001162 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001163}
1164
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001165// Instrument unusual size or unusual alignment.
1166// We can not do it with a single check, so we do 1-byte check for the first
1167// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1168// to report the actual access size.
1169void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1170 Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1171 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1172 IRBuilder<> IRB(I);
1173 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1174 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1175 if (UseCalls) {
1176 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001177 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1178 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001179 else
David Blaikieff6409d2015-05-18 22:13:54 +00001180 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1181 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001182 } else {
1183 Value *LastByte = IRB.CreateIntToPtr(
1184 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1185 Addr->getType());
1186 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1187 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1188 }
1189}
1190
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001191void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1192 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001193 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001194 IRBuilder<> IRB(&GlobalInit.front(),
1195 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001196
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001197 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001198 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1199 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001200
1201 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001202 for (auto &BB : GlobalInit.getBasicBlockList())
1203 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001204 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001205}
1206
1207void AddressSanitizerModule::createInitializerPoisonCalls(
1208 Module &M, GlobalValue *ModuleName) {
1209 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1210
1211 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1212 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001213 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001214 ConstantStruct *CS = cast<ConstantStruct>(OP);
1215
1216 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001217 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001218 if (F->getName() == kAsanModuleCtorName) continue;
1219 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1220 // Don't instrument CTORs that will run before asan.module_ctor.
1221 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1222 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001223 }
1224 }
1225}
1226
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001227bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001228 Type *Ty = G->getValueType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001229 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001230
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001231 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001232 if (!Ty->isSized()) return false;
1233 if (!G->hasInitializer()) return false;
Kostya Serebryany139a9372012-11-20 14:16:08 +00001234 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001235 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001236 // Don't handle ODR linkage types and COMDATs since other modules may be built
1237 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001238 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1239 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1240 G->getLinkage() != GlobalVariable::InternalLinkage)
1241 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001242 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001243 // Two problems with thread-locals:
1244 // - The address of the main thread's copy can't be computed at link-time.
1245 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001246 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001247 // For now, just ignore this Global if the alignment is large.
1248 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001249
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001250 if (G->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001251 StringRef Section = G->getSection();
Kuba Brecka086e34b2014-12-05 21:32:46 +00001252
Anna Zaks11904602015-06-09 00:58:08 +00001253 // Globals from llvm.metadata aren't emitted, do not instrument them.
1254 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001255 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001256 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001257
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001258 // Do not instrument function pointers to initialization and termination
1259 // routines: dynamic linker will not properly handle redzones.
1260 if (Section.startswith(".preinit_array") ||
1261 Section.startswith(".init_array") ||
1262 Section.startswith(".fini_array")) {
1263 return false;
1264 }
1265
Anna Zaks11904602015-06-09 00:58:08 +00001266 // Callbacks put into the CRT initializer/terminator sections
1267 // should not be instrumented.
1268 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1269 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1270 if (Section.startswith(".CRT")) {
1271 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1272 return false;
1273 }
1274
Kuba Brecka1001bb52014-12-05 22:19:18 +00001275 if (TargetTriple.isOSBinFormatMachO()) {
1276 StringRef ParsedSegment, ParsedSection;
1277 unsigned TAA = 0, StubSize = 0;
1278 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001279 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1280 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001281 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001282
1283 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1284 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1285 // them.
1286 if (ParsedSegment == "__OBJC" ||
1287 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1288 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1289 return false;
1290 }
1291 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1292 // Constant CFString instances are compiled in the following way:
1293 // -- the string buffer is emitted into
1294 // __TEXT,__cstring,cstring_literals
1295 // -- the constant NSConstantString structure referencing that buffer
1296 // is placed into __DATA,__cfstring
1297 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1298 // Moreover, it causes the linker to crash on OS X 10.7
1299 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1300 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1301 return false;
1302 }
1303 // The linker merges the contents of cstring_literals and removes the
1304 // trailing zeroes.
1305 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1306 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1307 return false;
1308 }
1309 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001310 }
1311
1312 return true;
1313}
1314
Ryan Govostes653f9d02016-03-28 20:28:57 +00001315// On Mach-O platforms, we emit global metadata in a separate section of the
1316// binary in order to allow the linker to properly dead strip. This is only
1317// supported on recent versions of ld64.
1318bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
1319 if (!TargetTriple.isOSBinFormatMachO())
1320 return false;
1321
1322 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1323 return true;
1324 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001325 return true;
Ryan Govostes653f9d02016-03-28 20:28:57 +00001326 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1327 return true;
1328
1329 return false;
1330}
1331
Alexey Samsonov788381b2012-12-25 12:28:20 +00001332void AddressSanitizerModule::initializeCallbacks(Module &M) {
1333 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001334
Alexey Samsonov788381b2012-12-25 12:28:20 +00001335 // Declare our poisoning and unpoisoning functions.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001336 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001337 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001338 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001339 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001340 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001341 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001342
Alexey Samsonov788381b2012-12-25 12:28:20 +00001343 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001344 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001345 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001346 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001347 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001348 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1349 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001350 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001351
1352 // Declare the functions that find globals in a shared object and then invoke
1353 // the (un)register function on them.
1354 AsanRegisterImageGlobals = checkSanitizerInterfaceFunction(
1355 M.getOrInsertFunction(kAsanRegisterImageGlobalsName,
1356 IRB.getVoidTy(), IntptrTy, nullptr));
1357 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001358
Ryan Govostes653f9d02016-03-28 20:28:57 +00001359 AsanUnregisterImageGlobals = checkSanitizerInterfaceFunction(
1360 M.getOrInsertFunction(kAsanUnregisterImageGlobalsName,
1361 IRB.getVoidTy(), IntptrTy, nullptr));
1362 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001363}
1364
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001365// This function replaces all global variables with new variables that have
1366// trailing redzones. It also creates a function that poisons
1367// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001368bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001369 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001370
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001371 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1372
Alexey Samsonova02e6642014-05-29 18:40:48 +00001373 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001374 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001375 }
1376
1377 size_t n = GlobalsToChange.size();
1378 if (n == 0) return false;
1379
1380 // A global is described by a structure
1381 // size_t beg;
1382 // size_t size;
1383 // size_t size_with_redzone;
1384 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001385 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001386 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001387 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001388 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001389 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001390 StructType *GlobalStructTy =
1391 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001392 IntptrTy, IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001393 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001394
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001395 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001396
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001397 // We shouldn't merge same module names, as this string serves as unique
1398 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001399 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001400 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001401
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001402 auto &DL = M.getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001403 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001404 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001405 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001406
1407 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001408 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001409 // Create string holding the global name (use global name from metadata
1410 // if it's available, otherwise just write the name of global variable).
1411 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001412 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001413 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001414
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001415 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001416 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001417 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001418 // MinRZ <= RZ <= kMaxGlobalRedzone
1419 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001420 uint64_t RZ = std::max(
1421 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001422 uint64_t RightRedzoneSize = RZ;
1423 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001424 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001425 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001426 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1427
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001428 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001429 Constant *NewInitializer =
1430 ConstantStruct::get(NewTy, G->getInitializer(),
1431 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001432
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001433 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001434 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1435 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1436 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001437 GlobalVariable *NewGlobal =
1438 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1439 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001440 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001441 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001442
1443 Value *Indices2[2];
1444 Indices2[0] = IRB.getInt32(0);
1445 Indices2[1] = IRB.getInt32(0);
1446
1447 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001448 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001449 NewGlobal->takeName(G);
1450 G->eraseFromParent();
1451
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001452 Constant *SourceLoc;
1453 if (!MD.SourceLoc.empty()) {
1454 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1455 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1456 } else {
1457 SourceLoc = ConstantInt::get(IntptrTy, 0);
1458 }
1459
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001460 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
1461 GlobalValue *InstrumentedGlobal = NewGlobal;
1462
1463 bool CanUsePrivateAliases = TargetTriple.isOSBinFormatELF();
1464 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
1465 // Create local alias for NewGlobal to avoid crash on ODR between
1466 // instrumented and non-instrumented libraries.
1467 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
1468 NameForGlobal + M.getName(), NewGlobal);
1469
1470 // With local aliases, we need to provide another externally visible
1471 // symbol __odr_asan_XXX to detect ODR violation.
1472 auto *ODRIndicatorSym =
1473 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
1474 Constant::getNullValue(IRB.getInt8Ty()),
1475 kODRGenPrefix + NameForGlobal, nullptr,
1476 NewGlobal->getThreadLocalMode());
1477
1478 // Set meaningful attributes for indicator symbol.
1479 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
1480 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
1481 ODRIndicatorSym->setAlignment(1);
1482 ODRIndicator = ODRIndicatorSym;
1483 InstrumentedGlobal = GA;
1484 }
1485
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001486 Initializers[i] = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001487 GlobalStructTy,
1488 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001489 ConstantInt::get(IntptrTy, SizeInBytes),
1490 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1491 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001492 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001493 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
1494 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy), nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001495
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001496 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001497
Kostya Serebryany20343352012-10-17 13:40:06 +00001498 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001499 }
1500
Ryan Govostes653f9d02016-03-28 20:28:57 +00001501
1502 GlobalVariable *AllGlobals = nullptr;
1503 GlobalVariable *RegisteredFlag = nullptr;
1504
1505 // On recent Mach-O platforms, we emit the global metadata in a way that
1506 // allows the linker to properly strip dead globals.
1507 if (ShouldUseMachOGlobalsSection()) {
1508 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1509 // to look up the loaded image that contains it. Second, we can store in it
1510 // whether registration has already occurred, to prevent duplicate
1511 // registration.
1512 //
1513 // Common linkage allows us to coalesce needles defined in each object
1514 // file so that there's only one per shared library.
1515 RegisteredFlag = new GlobalVariable(
1516 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1517 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1518
1519 // We also emit a structure which binds the liveness of the global
1520 // variable to the metadata struct.
1521 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy, nullptr);
1522
1523 for (size_t i = 0; i < n; i++) {
1524 GlobalVariable *Metadata = new GlobalVariable(
1525 M, GlobalStructTy, false, GlobalVariable::InternalLinkage,
1526 Initializers[i], "");
1527 Metadata->setSection("__DATA,__asan_globals,regular");
1528 Metadata->setAlignment(1); // don't leave padding in between
1529
1530 auto LivenessBinder = ConstantStruct::get(LivenessTy,
1531 Initializers[i]->getAggregateElement(0u),
1532 ConstantExpr::getPointerCast(Metadata, IntptrTy),
1533 nullptr);
1534 GlobalVariable *Liveness = new GlobalVariable(
1535 M, LivenessTy, false, GlobalVariable::InternalLinkage,
1536 LivenessBinder, "");
1537 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1538 }
1539 } else {
1540 // On all other platfoms, we just emit an array of global metadata
1541 // structures.
1542 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1543 AllGlobals = new GlobalVariable(
1544 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1545 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1546 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001547
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001548 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001549 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001550 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001551
Ryan Govostes653f9d02016-03-28 20:28:57 +00001552 // Create a call to register the globals with the runtime.
1553 if (ShouldUseMachOGlobalsSection()) {
1554 IRB.CreateCall(AsanRegisterImageGlobals,
1555 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1556 } else {
1557 IRB.CreateCall(AsanRegisterGlobals,
1558 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1559 ConstantInt::get(IntptrTy, n)});
1560 }
1561
1562 // We also need to unregister globals at the end, e.g., when a shared library
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001563 // gets closed.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001564 Function *AsanDtorFunction =
1565 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1566 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001567 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1568 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001569
1570 if (ShouldUseMachOGlobalsSection()) {
1571 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1572 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1573 } else {
1574 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1575 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1576 ConstantInt::get(IntptrTy, n)});
1577 }
1578
Alexey Samsonov1f647502014-05-29 01:10:14 +00001579 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001580
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001581 DEBUG(dbgs() << M);
1582 return true;
1583}
1584
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001585bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001586 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001587 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001588 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001589 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001590 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001591 initializeCallbacks(M);
1592
1593 bool Changed = false;
1594
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001595 // TODO(glider): temporarily disabled globals instrumentation for KASan.
1596 if (ClGlobals && !CompileKernel) {
1597 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1598 assert(CtorFunc);
1599 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1600 Changed |= InstrumentGlobals(IRB, M);
1601 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001602
1603 return Changed;
1604}
1605
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001606void AddressSanitizer::initializeCallbacks(Module &M) {
1607 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001608 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001609 // IsWrite, TypeSize and Exp are encoded in the function name.
1610 for (int Exp = 0; Exp < 2; Exp++) {
1611 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1612 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1613 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001614 const std::string SuffixStr = CompileKernel ? "N" : "_n";
Yury Gribovd7731982015-11-11 10:36:49 +00001615 const std::string EndingStr = Recover ? "_noabort" : "";
Craig Toppere3dcce92015-08-01 22:20:21 +00001616 Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001617 AsanErrorCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001618 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001619 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001620 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1621 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001622 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001623 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001624 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1625 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1626 AccessSizeIndex++) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001627 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001628 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001629 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001630 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001631 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001632 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001633 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001634 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1635 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001636 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001637 }
1638 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00001639
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001640 const std::string MemIntrinCallbackPrefix =
1641 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001642 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001643 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001644 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001645 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001646 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001647 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001648 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001649 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001650 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001651
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001652 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001653 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001654
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001655 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001656 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001657 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001658 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001659 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1660 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1661 StringRef(""), StringRef(""),
1662 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001663}
1664
1665// virtual
1666bool AddressSanitizer::doInitialization(Module &M) {
1667 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001668
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001669 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001670
1671 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001672 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001673 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001674 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001675
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001676 if (!CompileKernel) {
1677 std::tie(AsanCtorFunction, AsanInitFunction) =
Kuba Brecka45dbffd2015-07-23 10:54:06 +00001678 createSanitizerCtorAndInitFunctions(
1679 M, kAsanModuleCtorName, kAsanInitName,
1680 /*InitArgTypes=*/{}, /*InitArgs=*/{}, kAsanVersionCheckName);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001681 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1682 }
1683 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001684 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001685}
1686
Keno Fischere03fae42015-12-05 14:42:34 +00001687bool AddressSanitizer::doFinalization(Module &M) {
1688 GlobalsMD.reset();
1689 return false;
1690}
1691
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001692bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1693 // For each NSObject descendant having a +load method, this method is invoked
1694 // by the ObjC runtime before any of the static constructors is called.
1695 // Therefore we need to instrument such methods with a call to __asan_init
1696 // at the beginning in order to initialize our runtime before any access to
1697 // the shadow memory.
1698 // We cannot just ignore these methods, because they may call other
1699 // instrumented functions.
1700 if (F.getName().find(" load]") != std::string::npos) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001701 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00001702 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001703 return true;
1704 }
1705 return false;
1706}
1707
Reid Kleckner2f907552015-07-21 17:40:14 +00001708void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
1709 // Find the one possible call to llvm.localescape and pre-mark allocas passed
1710 // to it as uninteresting. This assumes we haven't started processing allocas
1711 // yet. This check is done up front because iterating the use list in
1712 // isInterestingAlloca would be algorithmically slower.
1713 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
1714
1715 // Try to get the declaration of llvm.localescape. If it's not in the module,
1716 // we can exit early.
1717 if (!F.getParent()->getFunction("llvm.localescape")) return;
1718
1719 // Look for a call to llvm.localescape call in the entry block. It can't be in
1720 // any other block.
1721 for (Instruction &I : F.getEntryBlock()) {
1722 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
1723 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
1724 // We found a call. Mark all the allocas passed in as uninteresting.
1725 for (Value *Arg : II->arg_operands()) {
1726 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
1727 assert(AI && AI->isStaticAlloca() &&
1728 "non-static alloca arg to localescape");
1729 ProcessedAllocas[AI] = false;
1730 }
1731 break;
1732 }
1733 }
1734}
1735
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001736bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001737 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001738 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001739 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001740 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001741
Yury Gribov3ae427d2014-12-01 08:47:58 +00001742 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1743
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001744 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001745 maybeInsertAsanInitAtFunctionEntry(F);
1746
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001747 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001748
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001749 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001750
Reid Kleckner2f907552015-07-21 17:40:14 +00001751 FunctionStateRAII CleanupObj(this);
1752
1753 // We can't instrument allocas used with llvm.localescape. Only static allocas
1754 // can be passed to that intrinsic.
1755 markEscapedLocalAllocas(F);
1756
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001757 // We want to instrument every address only once per basic block (unless there
1758 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001759 SmallSet<Value *, 16> TempsToInstrument;
1760 SmallVector<Instruction *, 16> ToInstrument;
1761 SmallVector<Instruction *, 8> NoReturnCalls;
1762 SmallVector<BasicBlock *, 16> AllBlocks;
1763 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001764 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001765 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001766 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001767 uint64_t TypeSize;
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00001768 const TargetLibraryInfo *TLI =
1769 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001770
1771 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001772 for (auto &BB : F) {
1773 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001774 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001775 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001776 for (auto &Inst : BB) {
1777 if (LooksLikeCodeInBug11395(&Inst)) return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001778 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1779 &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001780 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001781 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001782 continue; // We've seen this temp in the current BB.
1783 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001784 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001785 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1786 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001787 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001788 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001789 // ok, take it.
1790 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001791 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001792 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001793 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001794 // A call inside BB.
1795 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001796 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001797 }
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00001798 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
1799 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001800 continue;
1801 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001802 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001803 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001804 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001805 }
1806 }
1807
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001808 bool UseCalls =
1809 CompileKernel ||
1810 (ClInstrumentationWithCallsThreshold >= 0 &&
1811 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001812 const DataLayout &DL = F.getParent()->getDataLayout();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001813 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1814 /*RoundToAlign=*/true);
1815
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001816 // Instrument.
1817 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001818 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001819 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1820 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001821 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001822 instrumentMop(ObjSizeVis, Inst, UseCalls,
1823 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001824 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001825 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001826 }
1827 NumInstrumented++;
1828 }
1829
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001830 FunctionStackPoisoner FSP(F, *this);
1831 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001832
1833 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1834 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001835 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001836 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00001837 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001838 }
1839
Alexey Samsonova02e6642014-05-29 18:40:48 +00001840 for (auto Inst : PointerComparisonsOrSubtracts) {
1841 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001842 NumInstrumented++;
1843 }
1844
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001845 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001846
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001847 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1848
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001849 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001850}
1851
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001852// Workaround for bug 11395: we don't want to instrument stack in functions
1853// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1854// FIXME: remove once the bug 11395 is fixed.
1855bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1856 if (LongSize != 32) return false;
1857 CallInst *CI = dyn_cast<CallInst>(I);
1858 if (!CI || !CI->isInlineAsm()) return false;
1859 if (CI->getNumArgOperands() <= 5) return false;
1860 // We have inline assembly with quite a few arguments.
1861 return true;
1862}
1863
1864void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1865 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001866 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1867 std::string Suffix = itostr(i);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001868 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1869 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1870 IntptrTy, nullptr));
1871 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001872 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1873 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001874 }
Vitaly Buka79b75d32016-06-09 23:05:35 +00001875 if (ASan.UseAfterScope) {
1876 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
1877 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1878 IntptrTy, IntptrTy, nullptr));
1879 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
1880 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1881 IntptrTy, IntptrTy, nullptr));
1882 }
1883
Yury Gribov98b18592015-05-28 07:51:49 +00001884 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1885 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1886 AsanAllocasUnpoisonFunc =
1887 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1888 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001889}
1890
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001891void FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1892 IRBuilder<> &IRB, Value *ShadowBase,
1893 bool DoPoison) {
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001894 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001895 size_t i = 0;
1896 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1897 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1898 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1899 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1900 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1901 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1902 uint64_t Val = 0;
1903 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001904 if (F.getParent()->getDataLayout().isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001905 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1906 else
1907 Val = (Val << 8) | ShadowBytes[i + j];
1908 }
1909 if (!Val) continue;
1910 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1911 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1912 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1913 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001914 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001915 }
1916}
1917
Kostya Serebryany6805de52013-09-10 13:16:56 +00001918// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1919// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1920static int StackMallocSizeClass(uint64_t LocalStackSize) {
1921 assert(LocalStackSize <= kMaxStackMallocSize);
1922 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001923 for (int i = 0;; i++, MaxSize *= 2)
1924 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00001925 llvm_unreachable("impossible LocalStackSize");
1926}
1927
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001928// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1929// We can not use MemSet intrinsic because it may end up calling the actual
1930// memset. Size is a multiple of 8.
1931// Currently this generates 8-byte stores on x86_64; it may be better to
1932// generate wider stores.
1933void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1934 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1935 assert(!(Size % 8));
Gabor Horvathfee04342015-03-16 09:53:42 +00001936
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001937 // kAsanStackAfterReturnMagic is 0xf5.
1938 const uint64_t kAsanStackAfterReturnMagic64 = 0xf5f5f5f5f5f5f5f5ULL;
Gabor Horvathfee04342015-03-16 09:53:42 +00001939
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001940 for (int i = 0; i < Size; i += 8) {
1941 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001942 IRB.CreateStore(
1943 ConstantInt::get(IRB.getInt64Ty(), kAsanStackAfterReturnMagic64),
1944 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001945 }
1946}
1947
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001948PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1949 Value *ValueIfTrue,
1950 Instruction *ThenTerm,
1951 Value *ValueIfFalse) {
1952 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1953 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1954 PHI->addIncoming(ValueIfFalse, CondBlock);
1955 BasicBlock *ThenBlock = ThenTerm->getParent();
1956 PHI->addIncoming(ValueIfTrue, ThenBlock);
1957 return PHI;
1958}
1959
1960Value *FunctionStackPoisoner::createAllocaForLayout(
1961 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
1962 AllocaInst *Alloca;
1963 if (Dynamic) {
1964 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
1965 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
1966 "MyAlloca");
1967 } else {
1968 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
1969 nullptr, "MyAlloca");
1970 assert(Alloca->isStaticAlloca());
1971 }
1972 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1973 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1974 Alloca->setAlignment(FrameAlignment);
1975 return IRB.CreatePointerCast(Alloca, IntptrTy);
1976}
1977
Yury Gribov98b18592015-05-28 07:51:49 +00001978void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
1979 BasicBlock &FirstBB = *F.begin();
1980 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
1981 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
1982 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
1983 DynamicAllocaLayout->setAlignment(32);
1984}
1985
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001986void FunctionStackPoisoner::poisonStack() {
Yury Gribov55441bb2014-11-21 10:29:50 +00001987 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1988
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00001989 // Insert poison calls for lifetime intrinsics for alloca.
Vitaly Bukab451f1b2016-06-09 23:31:59 +00001990 bool HavePoisonedStaticAllocas = false;
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00001991 for (const auto &APC : AllocaPoisonCallVec) {
1992 assert(APC.InsBefore);
1993 assert(APC.AI);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00001994 assert(ASan.isInterestingAlloca(*APC.AI));
1995 bool IsDynamicAlloca = ASan.isDynamicAlloca(*APC.AI);
1996 if (!ClInstrumentAllocas && IsDynamicAlloca)
1997 continue;
1998
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00001999 IRBuilder<> IRB(APC.InsBefore);
2000 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002001 // Dynamic allocas will be unpoisoned unconditionally below in
2002 // unpoisonDynamicAllocas.
2003 // Flag that we need unpoison static allocas.
2004 HavePoisonedStaticAllocas |= (APC.DoPoison && !IsDynamicAlloca);
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002005 }
2006
Yury Gribov98b18592015-05-28 07:51:49 +00002007 if (ClInstrumentAllocas && DynamicAllocaVec.size() > 0) {
Yury Gribov55441bb2014-11-21 10:29:50 +00002008 // Handle dynamic allocas.
Yury Gribov98b18592015-05-28 07:51:49 +00002009 createDynamicAllocasInitStorage();
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002010 for (auto &AI : DynamicAllocaVec) handleDynamicAllocaCall(AI);
Yury Gribov98b18592015-05-28 07:51:49 +00002011
2012 unpoisonDynamicAllocas();
Kuba Breckaf5875d32015-02-24 09:47:05 +00002013 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002014
Hans Wennborg083ca9b2015-10-06 23:24:35 +00002015 if (AllocaVec.empty()) return;
Yury Gribov55441bb2014-11-21 10:29:50 +00002016
Kostya Serebryany6805de52013-09-10 13:16:56 +00002017 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002018 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00002019 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002020 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002021
2022 Instruction *InsBefore = AllocaVec[0];
2023 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002024 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002025
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002026 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2027 // debug info is broken, because only entry-block allocas are treated as
2028 // regular stack slots.
2029 auto InsBeforeB = InsBefore->getParent();
2030 assert(InsBeforeB == &F.getEntryBlock());
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002031 for (BasicBlock::iterator I(InsBefore); I != InsBeforeB->end(); ++I)
2032 if (auto *AI = dyn_cast<AllocaInst>(I))
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002033 if (NonInstrumentedStaticAllocaVec.count(AI) > 0)
2034 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00002035
Reid Kleckner2f907552015-07-21 17:40:14 +00002036 // If we have a call to llvm.localescape, keep it in the entry block.
2037 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2038
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002039 SmallVector<ASanStackVariableDescription, 16> SVD;
2040 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00002041 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002042 ASanStackVariableDescription D = {AI->getName().data(),
2043 ASan.getAllocaSizeInBytes(AI),
2044 AI->getAlignment(), AI, 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002045 SVD.push_back(D);
2046 }
2047 // Minimal header size (left redzone) is 4 pointers,
2048 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2049 size_t MinHeaderSize = ASan.LongSize / 2;
2050 ASanStackFrameLayout L;
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00002051 ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize, &L);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002052 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
2053 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002054 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2055 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00002056 bool DoDynamicAlloca = ClDynamicAllocaStack;
2057 // Don't do dynamic alloca or stack malloc if:
2058 // 1) There is inline asm: too often it makes assumptions on which registers
2059 // are available.
2060 // 2) There is a returns_twice call (typically setjmp), which is
2061 // optimization-hostile, and doesn't play well with introduced indirect
2062 // register-relative calculation of local variable addresses.
2063 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2064 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002065
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002066 Value *StaticAlloca =
2067 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2068
2069 Value *FakeStack;
2070 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002071
2072 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002073 // void *FakeStack = __asan_option_detect_stack_use_after_return
2074 // ? __asan_stack_malloc_N(LocalStackSize)
2075 // : nullptr;
2076 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002077 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2078 kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2079 Value *UseAfterReturnIsEnabled =
2080 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002081 Constant::getNullValue(IRB.getInt32Ty()));
2082 Instruction *Term =
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002083 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002084 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002085 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002086 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2087 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2088 Value *FakeStackValue =
2089 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2090 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002091 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002092 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002093 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002094 ConstantInt::get(IntptrTy, 0));
2095
2096 Value *NoFakeStack =
2097 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2098 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2099 IRBIf.SetInsertPoint(Term);
2100 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2101 Value *AllocaValue =
2102 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2103 IRB.SetInsertPoint(InsBefore);
2104 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2105 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2106 } else {
2107 // void *FakeStack = nullptr;
2108 // void *LocalStackBase = alloca(LocalStackSize);
2109 FakeStack = ConstantInt::get(IntptrTy, 0);
2110 LocalStackBase =
2111 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002112 }
2113
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002114 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002115 for (const auto &Desc : SVD) {
2116 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00002117 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00002118 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002119 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00002120 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002121 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002122 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002123
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002124 // The left-most redzone has enough space for at least 4 pointers.
2125 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002126 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2127 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2128 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002129 // Write the frame description constant to redzone[1].
2130 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002131 IRB.CreateAdd(LocalStackBase,
2132 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2133 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00002134 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00002135 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002136 /*AllowMerging*/ true);
2137 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002138 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002139 // Write the PC to redzone[2].
2140 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002141 IRB.CreateAdd(LocalStackBase,
2142 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2143 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002144 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002145
2146 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002147 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002148 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002149
Vitaly Buka79b75d32016-06-09 23:05:35 +00002150 auto UnpoisonStack = [&](IRBuilder<> &IRB) {
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002151 if (HavePoisonedStaticAllocas) {
Vitaly Buka79b75d32016-06-09 23:05:35 +00002152 // If we poisoned some allocas in llvm.lifetime analysis,
2153 // unpoison whole stack frame now.
2154 poisonAlloca(LocalStackBase, LocalStackSize, IRB, false);
2155 } else {
2156 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, false);
2157 }
2158 };
2159
Kostya Serebryany530e2072013-12-23 14:15:08 +00002160 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002161 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002162 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002163 // Mark the current frame as retired.
2164 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2165 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002166 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00002167 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002168 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00002169 // // In use-after-return mode, poison the whole stack frame.
2170 // if StackMallocIdx <= 4
2171 // // For small sizes inline the whole thing:
2172 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002173 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00002174 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002175 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00002176 // else
2177 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002178 Value *Cmp =
2179 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00002180 TerminatorInst *ThenTerm, *ElseTerm;
2181 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2182
2183 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002184 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002185 int ClassSize = kMinStackMallocSize << StackMallocIdx;
2186 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
2187 ClassSize >> Mapping.Scale);
2188 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002189 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002190 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2191 Value *SavedFlagPtr = IRBPoison.CreateLoad(
2192 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2193 IRBPoison.CreateStore(
2194 Constant::getNullValue(IRBPoison.getInt8Ty()),
2195 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2196 } else {
2197 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00002198 IRBPoison.CreateCall(
2199 AsanStackFreeFunc[StackMallocIdx],
2200 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002201 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00002202
2203 IRBuilder<> IRBElse(ElseTerm);
Vitaly Buka79b75d32016-06-09 23:05:35 +00002204 UnpoisonStack(IRBElse);
Kostya Serebryany530e2072013-12-23 14:15:08 +00002205 } else {
Vitaly Buka79b75d32016-06-09 23:05:35 +00002206 UnpoisonStack(IRBRet);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002207 }
2208 }
2209
Kostya Serebryany09959942012-10-19 06:20:53 +00002210 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002211 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002212}
Alexey Samsonov261177a2012-12-04 01:34:23 +00002213
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002214void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00002215 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00002216 // For now just insert the call to ASan runtime.
2217 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2218 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002219 IRB.CreateCall(
2220 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2221 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00002222}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002223
2224// Handling llvm.lifetime intrinsics for a given %alloca:
2225// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2226// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2227// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2228// could be poisoned by previous llvm.lifetime.end instruction, as the
2229// variable may go in and out of scope several times, e.g. in loops).
2230// (3) if we poisoned at least one %alloca in a function,
2231// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002232
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002233AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2234 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
2235 // We're intested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00002236 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002237 // See if we've already calculated (or started to calculate) alloca for a
2238 // given value.
2239 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002240 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002241 // Store 0 while we're calculating alloca for value V to avoid
2242 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00002243 AllocaForValue[V] = nullptr;
2244 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002245 if (CastInst *CI = dyn_cast<CastInst>(V))
2246 Res = findAllocaForValue(CI->getOperand(0));
2247 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00002248 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002249 // Allow self-referencing phi-nodes.
2250 if (IncValue == PN) continue;
2251 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2252 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00002253 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2254 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002255 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002256 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002257 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002258 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002259 return Res;
2260}
Yury Gribov55441bb2014-11-21 10:29:50 +00002261
Yury Gribov98b18592015-05-28 07:51:49 +00002262void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00002263 IRBuilder<> IRB(AI);
2264
Yury Gribov55441bb2014-11-21 10:29:50 +00002265 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2266 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2267
2268 Value *Zero = Constant::getNullValue(IntptrTy);
2269 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2270 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00002271
2272 // Since we need to extend alloca with additional memory to locate
2273 // redzones, and OldSize is number of allocated blocks with
2274 // ElementSize size, get allocated memory size in bytes by
2275 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00002276 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002277 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00002278 Value *OldSize =
2279 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2280 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00002281
2282 // PartialSize = OldSize % 32
2283 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2284
2285 // Misalign = kAllocaRzSize - PartialSize;
2286 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2287
2288 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2289 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2290 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2291
2292 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2293 // Align is added to locate left redzone, PartialPadding for possible
2294 // partial redzone and kAllocaRzSize for right redzone respectively.
2295 Value *AdditionalChunkSize = IRB.CreateAdd(
2296 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2297
2298 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2299
2300 // Insert new alloca with new NewSize and Align params.
2301 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2302 NewAlloca->setAlignment(Align);
2303
2304 // NewAddress = Address + Align
2305 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2306 ConstantInt::get(IntptrTy, Align));
2307
Yury Gribov98b18592015-05-28 07:51:49 +00002308 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00002309 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00002310
2311 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2312 // for unpoisoning stuff.
2313 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2314
Yury Gribov55441bb2014-11-21 10:29:50 +00002315 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2316
Yury Gribov98b18592015-05-28 07:51:49 +00002317 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00002318 AI->replaceAllUsesWith(NewAddressPtr);
2319
Yury Gribov98b18592015-05-28 07:51:49 +00002320 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00002321 AI->eraseFromParent();
2322}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002323
2324// isSafeAccess returns true if Addr is always inbounds with respect to its
2325// base object. For example, it is a field access or an array access with
2326// constant inbounds index.
2327bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2328 Value *Addr, uint64_t TypeSize) const {
2329 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2330 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00002331 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002332 int64_t Offset = SizeOffset.second.getSExtValue();
2333 // Three checks are required to ensure safety:
2334 // . Offset >= 0 (since the offset is given from the base ptr)
2335 // . Size >= Offset (unsigned)
2336 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00002337 return Offset >= 0 && Size >= uint64_t(Offset) &&
2338 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002339}