blob: 635e0894d940a1e90c5d9d89b2deaffa827271b9 [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
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000119static const char *const kAsanOptionDetectUAR =
120 "__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 Govostes3f37df02016-05-06 10:25:22 +0000211static cl::opt<unsigned long long> ClMappingOffset("asan-mapping-offset",
212 cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"),
213 cl::Hidden, cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000214
215// Optimization flags. Not user visible, used mostly for testing
216// and benchmarking the tool.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000217static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
218 cl::Hidden, cl::init(true));
219static cl::opt<bool> ClOptSameTemp(
220 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
221 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000222static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000223 cl::desc("Don't instrument scalar globals"),
224 cl::Hidden, cl::init(true));
225static cl::opt<bool> ClOptStack(
226 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
227 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000228
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000229static cl::opt<bool> ClDynamicAllocaStack(
230 "asan-stack-dynamic-alloca",
231 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000232 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000233
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000234static cl::opt<uint32_t> ClForceExperiment(
235 "asan-force-experiment",
236 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
237 cl::init(0));
238
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000239static cl::opt<bool>
240 ClUsePrivateAliasForGlobals("asan-use-private-alias",
241 cl::desc("Use private aliases for global"
242 " variables"),
243 cl::Hidden, cl::init(false));
244
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000245// Debug flags.
246static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
247 cl::init(0));
248static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
249 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000250static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
251 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000252static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
253 cl::Hidden, cl::init(-1));
254static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
255 cl::Hidden, cl::init(-1));
256
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000257STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
258STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000259STATISTIC(NumOptimizedAccessesToGlobalVar,
260 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000261STATISTIC(NumOptimizedAccessesToStackVar,
262 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000263
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000264namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000265/// Frontend-provided metadata for source location.
266struct LocationMetadata {
267 StringRef Filename;
268 int LineNo;
269 int ColumnNo;
270
271 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
272
273 bool empty() const { return Filename.empty(); }
274
275 void parse(MDNode *MDN) {
276 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000277 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
278 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000279 LineNo =
280 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
281 ColumnNo =
282 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000283 }
284};
285
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000286/// Frontend-provided metadata for global variables.
287class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000288 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000289 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000290 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000291 LocationMetadata SourceLoc;
292 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000293 bool IsDynInit;
294 bool IsBlacklisted;
295 };
296
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000297 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000298
Keno Fischere03fae42015-12-05 14:42:34 +0000299 void reset() {
300 inited_ = false;
301 Entries.clear();
302 }
303
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000304 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000305 assert(!inited_);
306 inited_ = true;
307 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000308 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000309 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000310 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000311 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000312 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000313 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000314 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000315 // We can already have an entry for GV if it was merged with another
316 // global.
317 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000318 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
319 E.SourceLoc.parse(Loc);
320 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
321 E.Name = Name->getString();
322 ConstantInt *IsDynInit =
323 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000324 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000325 ConstantInt *IsBlacklisted =
326 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000327 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000328 }
329 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000330
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000331 /// Returns metadata entry for a given global.
332 Entry get(GlobalVariable *G) const {
333 auto Pos = Entries.find(G);
334 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000335 }
336
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000337 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000338 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000339 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000340};
341
Alexey Samsonov1345d352013-01-16 13:23:28 +0000342/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000343/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000344struct ShadowMapping {
345 int Scale;
346 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000347 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000348};
349
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000350static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
351 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000352 bool IsAndroid = TargetTriple.isAndroid();
Anna Zaks3b50e702016-02-02 22:05:07 +0000353 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000354 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
355 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000356 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
357 TargetTriple.getArch() == llvm::Triple::ppc64le;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000358 bool IsSystemZ = TargetTriple.getArch() == llvm::Triple::systemz;
Anna Zaks3b50e702016-02-02 22:05:07 +0000359 bool IsX86 = TargetTriple.getArch() == llvm::Triple::x86;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000360 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000361 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
362 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000363 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
364 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000365 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000366 bool IsWindows = TargetTriple.isOSWindows();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000367
368 ShadowMapping Mapping;
369
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000370 if (LongSize == 32) {
Evgeniy Stepanov9cb08f82015-07-17 23:51:18 +0000371 // Android is always PIE, which means that the beginning of the address
372 // space is always available.
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000373 if (IsAndroid)
374 Mapping.Offset = 0;
375 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000376 Mapping.Offset = kMIPS32_ShadowOffset32;
377 else if (IsFreeBSD)
378 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000379 else if (IsIOS)
Anna Zaks3b50e702016-02-02 22:05:07 +0000380 // If we're targeting iOS and x86, the binary is built for iOS simulator.
381 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000382 else if (IsWindows)
383 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000384 else
385 Mapping.Offset = kDefaultShadowOffset32;
386 } else { // LongSize == 64
387 if (IsPPC64)
388 Mapping.Offset = kPPC64_ShadowOffset64;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000389 else if (IsSystemZ)
390 Mapping.Offset = kSystemZ_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000391 else if (IsFreeBSD)
392 Mapping.Offset = kFreeBSD_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000393 else if (IsLinux && IsX86_64) {
394 if (IsKasan)
395 Mapping.Offset = kLinuxKasan_ShadowOffset64;
396 else
397 Mapping.Offset = kSmallX86_64ShadowOffset;
398 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000399 Mapping.Offset = kMIPS64_ShadowOffset64;
Anna Zaks3b50e702016-02-02 22:05:07 +0000400 else if (IsIOS)
401 // If we're targeting iOS and x86, the binary is built for iOS simulator.
402 Mapping.Offset = IsX86_64 ? kIOSSimShadowOffset64 : kIOSShadowOffset64;
Renato Golinaf213722015-02-03 11:20:45 +0000403 else if (IsAArch64)
404 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000405 else
406 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000407 }
408
409 Mapping.Scale = kDefaultShadowScale;
Ryan Govostes3f37df02016-05-06 10:25:22 +0000410 if (ClMappingScale.getNumOccurrences() > 0) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000411 Mapping.Scale = ClMappingScale;
412 }
413
Ryan Govostes3f37df02016-05-06 10:25:22 +0000414 if (ClMappingOffset.getNumOccurrences() > 0) {
415 Mapping.Offset = ClMappingOffset;
416 }
417
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000418 // OR-ing shadow offset if more efficient (at least on x86) if the offset
419 // is a power of two, but on ppc64 we have to use add since the shadow
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000420 // offset is not necessary 1/8-th of the address space. On SystemZ,
421 // we could OR the constant in a single instruction, but it's more
422 // efficient to load it once and use indexed addressing.
423 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ
Adhemerval Zanella35891fe2015-11-09 18:03:48 +0000424 && !(Mapping.Offset & (Mapping.Offset - 1));
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000425
Alexey Samsonov1345d352013-01-16 13:23:28 +0000426 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000427}
428
Alexey Samsonov1345d352013-01-16 13:23:28 +0000429static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000430 // Redzone used for stack and globals is at least 32 bytes.
431 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000432 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000433}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000434
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000435/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000436struct AddressSanitizer : public FunctionPass {
Yury Gribovd7731982015-11-11 10:36:49 +0000437 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false)
438 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
439 Recover(Recover || ClRecover) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000440 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
441 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000442 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000443 return "AddressSanitizerFunctionPass";
444 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000445 void getAnalysisUsage(AnalysisUsage &AU) const override {
446 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000447 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000448 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000449 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
450 Type *Ty = AI->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000451 uint64_t SizeInBytes =
452 AI->getModule()->getDataLayout().getTypeAllocSize(Ty);
Anna Zaks8ed1d812015-02-27 03:12:36 +0000453 return SizeInBytes;
454 }
455 /// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000456 bool isInterestingAlloca(AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000457
458 // Check if we have dynamic alloca.
459 bool isDynamicAlloca(AllocaInst &AI) const {
460 return AI.isArrayAllocation() || !AI.isStaticAlloca();
461 }
462
Anna Zaks8ed1d812015-02-27 03:12:36 +0000463 /// If it is an interesting memory access, return the PointerOperand
464 /// and set IsWrite/Alignment. Otherwise return nullptr.
465 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000466 uint64_t *TypeSize, unsigned *Alignment);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000467 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000468 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000469 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000470 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
471 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000472 Value *SizeArgument, bool UseCalls, uint32_t Exp);
473 void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
474 uint32_t TypeSize, bool IsWrite,
475 Value *SizeArgument, bool UseCalls,
476 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000477 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
478 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000479 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000480 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000481 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000482 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000483 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000484 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000485 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000486 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000487 bool doInitialization(Module &M) override;
Keno Fischere03fae42015-12-05 14:42:34 +0000488 bool doFinalization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000489 static char ID; // Pass identification, replacement for typeid
490
Yury Gribov3ae427d2014-12-01 08:47:58 +0000491 DominatorTree &getDominatorTree() const { return *DT; }
492
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000493 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000494 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000495
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000496 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000497 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000498 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
499 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000500
Reid Kleckner2f907552015-07-21 17:40:14 +0000501 /// Helper to cleanup per-function state.
502 struct FunctionStateRAII {
503 AddressSanitizer *Pass;
504 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
505 assert(Pass->ProcessedAllocas.empty() &&
506 "last pass forgot to clear cache");
507 }
508 ~FunctionStateRAII() { Pass->ProcessedAllocas.clear(); }
509 };
510
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000511 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000512 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000513 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000514 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000515 bool Recover;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000516 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000517 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000518 DominatorTree *DT;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000519 Function *AsanCtorFunction = nullptr;
520 Function *AsanInitFunction = nullptr;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000521 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000522 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000523 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
524 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
525 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
526 // This array is indexed by AccessIsWrite and Experiment.
527 Function *AsanErrorCallbackSized[2][2];
528 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000529 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000530 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000531 GlobalsMetadata GlobalsMD;
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000532 DenseMap<AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000533
534 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000535};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000536
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000537class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000538 public:
Yury Gribovd7731982015-11-11 10:36:49 +0000539 explicit AddressSanitizerModule(bool CompileKernel = false,
540 bool Recover = false)
541 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
542 Recover(Recover || ClRecover) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000543 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000544 static char ID; // Pass identification, replacement for typeid
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000545 const char *getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000546
Kostya Serebryany20a79972012-11-22 03:18:50 +0000547 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000548 void initializeCallbacks(Module &M);
549
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000550 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000551 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000552 bool ShouldUseMachOGlobalsSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000553 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000554 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000555 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000556 return RedzoneSizeForScale(Mapping.Scale);
557 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000558
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000559 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000560 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000561 bool Recover;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000562 Type *IntptrTy;
563 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000564 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000565 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000566 Function *AsanPoisonGlobals;
567 Function *AsanUnpoisonGlobals;
568 Function *AsanRegisterGlobals;
569 Function *AsanUnregisterGlobals;
Ryan Govostes653f9d02016-03-28 20:28:57 +0000570 Function *AsanRegisterImageGlobals;
571 Function *AsanUnregisterImageGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000572};
573
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000574// Stack poisoning does not play well with exception handling.
575// When an exception is thrown, we essentially bypass the code
576// that unpoisones the stack. This is why the run-time library has
577// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
578// stack in the interceptor. This however does not work inside the
579// actual function which catches the exception. Most likely because the
580// compiler hoists the load of the shadow value somewhere too high.
581// This causes asan to report a non-existing bug on 453.povray.
582// It sounds like an LLVM bug.
583struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
584 Function &F;
585 AddressSanitizer &ASan;
586 DIBuilder DIB;
587 LLVMContext *C;
588 Type *IntptrTy;
589 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000590 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000591
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000592 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000593 SmallSetVector<AllocaInst *, 16> NonInstrumentedStaticAllocaVec;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000594 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000595 unsigned StackAlignment;
596
Kostya Serebryany6805de52013-09-10 13:16:56 +0000597 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000598 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000599 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000600 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000601
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000602 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
603 struct AllocaPoisonCall {
604 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000605 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000606 uint64_t Size;
607 bool DoPoison;
608 };
609 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
610
Yury Gribov98b18592015-05-28 07:51:49 +0000611 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
612 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
613 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000614 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000615
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000616 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000617 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000618 AllocaForValueMapTy AllocaForValue;
619
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000620 bool HasNonEmptyInlineAsm = false;
621 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000622 std::unique_ptr<CallInst> EmptyInlineAsm;
623
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000624 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000625 : F(F),
626 ASan(ASan),
627 DIB(*F.getParent(), /*AllowUnresolved*/ false),
628 C(ASan.C),
629 IntptrTy(ASan.IntptrTy),
630 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
631 Mapping(ASan.Mapping),
632 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000633 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000634
635 bool runOnFunction() {
636 if (!ClStack) return false;
637 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000638 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000639
Yury Gribov55441bb2014-11-21 10:29:50 +0000640 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000641
642 initializeCallbacks(*F.getParent());
643
644 poisonStack();
645
646 if (ClDebugStack) {
647 DEBUG(dbgs() << F);
648 }
649 return true;
650 }
651
Yury Gribov55441bb2014-11-21 10:29:50 +0000652 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000653 // poisoned red zones around all of them.
654 // Then unpoison everything back before the function returns.
655 void poisonStack();
656
Yury Gribov98b18592015-05-28 07:51:49 +0000657 void createDynamicAllocasInitStorage();
658
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000659 // ----------------------- Visitors.
660 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000661 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000662
Yury Gribov98b18592015-05-28 07:51:49 +0000663 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
664 Value *SavedStack) {
665 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000666 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
667 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
668 // need to adjust extracted SP to compute the address of the most recent
669 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
670 // this purpose.
671 if (!isa<ReturnInst>(InstBefore)) {
672 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
673 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
674 {IntptrTy});
675
676 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
677
678 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
679 DynamicAreaOffset);
680 }
681
Yury Gribov781bce22015-05-28 08:03:28 +0000682 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000683 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000684 }
685
Yury Gribov55441bb2014-11-21 10:29:50 +0000686 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000687 void unpoisonDynamicAllocas() {
688 for (auto &Ret : RetVec)
689 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000690
Yury Gribov98b18592015-05-28 07:51:49 +0000691 for (auto &StackRestoreInst : StackRestoreVec)
692 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
693 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000694 }
695
Yury Gribov55441bb2014-11-21 10:29:50 +0000696 // Deploy and poison redzones around dynamic alloca call. To do this, we
697 // should replace this call with another one with changed parameters and
698 // replace all its uses with new address, so
699 // addr = alloca type, old_size, align
700 // is replaced by
701 // new_size = (old_size + additional_size) * sizeof(type)
702 // tmp = alloca i8, new_size, max(align, 32)
703 // addr = tmp + 32 (first 32 bytes are for the left redzone).
704 // Additional_size is added to make new memory allocation contain not only
705 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000706 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000707
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000708 /// \brief Collect Alloca instructions we want (and can) handle.
709 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000710 if (!ASan.isInterestingAlloca(AI)) {
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000711 if (AI.isStaticAlloca()) NonInstrumentedStaticAllocaVec.insert(&AI);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000712 return;
713 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000714
715 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Yury Gribov98b18592015-05-28 07:51:49 +0000716 if (ASan.isDynamicAlloca(AI))
717 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000718 else
719 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000720 }
721
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000722 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
723 /// errors.
724 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000725 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000726 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000727 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Kostya Serebryanya83bfea2016-04-20 20:02:58 +0000728 if (!ClUseAfterScope) return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000729 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000730 return;
731 // Found lifetime intrinsic, add ASan instrumentation if necessary.
732 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
733 // If size argument is undefined, don't do anything.
734 if (Size->isMinusOne()) return;
735 // Check that size doesn't saturate uint64_t and can
736 // be stored in IntptrTy.
737 const uint64_t SizeValue = Size->getValue().getLimitedValue();
738 if (SizeValue == ~0ULL ||
739 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
740 return;
741 // Find alloca instruction that corresponds to llvm.lifetime argument.
742 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
743 if (!AI) return;
744 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000745 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000746 AllocaPoisonCallVec.push_back(APC);
747 }
748
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000749 void visitCallSite(CallSite CS) {
750 Instruction *I = CS.getInstruction();
751 if (CallInst *CI = dyn_cast<CallInst>(I)) {
752 HasNonEmptyInlineAsm |=
753 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
754 HasReturnsTwiceCall |= CI->canReturnTwice();
755 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000756 }
757
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000758 // ---------------------- Helpers.
759 void initializeCallbacks(Module &M);
760
Yury Gribov3ae427d2014-12-01 08:47:58 +0000761 bool doesDominateAllExits(const Instruction *I) const {
762 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000763 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000764 }
765 return true;
766 }
767
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000768 /// Finds alloca where the value comes from.
769 AllocaInst *findAllocaForValue(Value *V);
Craig Topper3af97222014-08-27 05:25:00 +0000770 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000771 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000772 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000773
774 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
775 int Size);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000776 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
777 bool Dynamic);
778 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
779 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000780};
781
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000782} // anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000783
784char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000785INITIALIZE_PASS_BEGIN(
786 AddressSanitizer, "asan",
787 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
788 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000789INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +0000790INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000791INITIALIZE_PASS_END(
792 AddressSanitizer, "asan",
793 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
794 false)
Yury Gribovd7731982015-11-11 10:36:49 +0000795FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
796 bool Recover) {
797 assert(!CompileKernel || Recover);
798 return new AddressSanitizer(CompileKernel, Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000799}
800
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000801char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000802INITIALIZE_PASS(
803 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000804 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000805 "ModulePass",
806 false, false)
Yury Gribovd7731982015-11-11 10:36:49 +0000807ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
808 bool Recover) {
809 assert(!CompileKernel || Recover);
810 return new AddressSanitizerModule(CompileKernel, Recover);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000811}
812
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000813static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000814 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000815 assert(Res < kNumberOfAccessSizes);
816 return Res;
817}
818
Bill Wendling58f8cef2013-08-06 22:52:42 +0000819// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000820static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
821 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000822 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000823 // We use private linkage for module-local strings. If they can be merged
824 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000825 GlobalVariable *GV =
826 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000827 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000828 if (AllowMerging) GV->setUnnamedAddr(true);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000829 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
830 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000831}
832
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000833/// \brief Create a global describing a source location.
834static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
835 LocationMetadata MD) {
836 Constant *LocData[] = {
837 createPrivateGlobalForString(M, MD.Filename, true),
838 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
839 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
840 };
841 auto LocStruct = ConstantStruct::getAnon(LocData);
842 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
843 GlobalValue::PrivateLinkage, LocStruct,
844 kAsanGenPrefix);
845 GV->setUnnamedAddr(true);
846 return GV;
847}
848
Kostya Serebryany139a9372012-11-20 14:16:08 +0000849static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000850 return G->getName().find(kAsanGenPrefix) == 0 ||
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000851 G->getName().find(kSanCovGenPrefix) == 0 ||
852 G->getName().find(kODRGenPrefix) == 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000853}
854
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000855Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
856 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000857 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000858 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000859 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000860 if (Mapping.OrShadowOffset)
861 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
862 else
863 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000864}
865
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000866// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000867void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
868 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000869 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000870 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000871 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +0000872 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
873 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
874 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000875 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000876 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000877 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +0000878 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
879 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
880 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000881 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000882 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000883}
884
Anna Zaks8ed1d812015-02-27 03:12:36 +0000885/// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000886bool AddressSanitizer::isInterestingAlloca(AllocaInst &AI) {
887 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
888
889 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
890 return PreviouslySeenAllocaInfo->getSecond();
891
Yury Gribov98b18592015-05-28 07:51:49 +0000892 bool IsInteresting =
893 (AI.getAllocatedType()->isSized() &&
894 // alloca() may be called with 0 size, ignore it.
895 getAllocaSizeInBytes(&AI) > 0 &&
896 // We are only interested in allocas not promotable to registers.
897 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +0000898 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
899 // inalloca allocas are not treated as static, and we don't want
900 // dynamic alloca instrumentation for them as well.
901 !AI.isUsedWithInAlloca());
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000902
903 ProcessedAllocas[&AI] = IsInteresting;
904 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000905}
906
907/// If I is an interesting memory access, return the PointerOperand
908/// and set IsWrite/Alignment. Otherwise return nullptr.
909Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
910 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000911 uint64_t *TypeSize,
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000912 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000913 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000914 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000915
916 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000917 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000918 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000919 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000920 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000921 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000922 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000923 PtrOperand = LI->getPointerOperand();
924 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000925 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000926 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000927 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000928 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000929 PtrOperand = SI->getPointerOperand();
930 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000931 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000932 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000933 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000934 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000935 PtrOperand = RMW->getPointerOperand();
936 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000937 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000938 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000939 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000940 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000941 PtrOperand = XCHG->getPointerOperand();
Kostya Serebryany90241602012-05-30 09:04:06 +0000942 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000943
944 // Treat memory accesses to promotable allocas as non-interesting since they
945 // will not cause memory violations. This greatly speeds up the instrumented
946 // executable at -O0.
947 if (ClSkipPromotableAllocas)
948 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
949 return isInterestingAlloca(*AI) ? AI : nullptr;
950
951 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000952}
953
Kostya Serebryany796f6552014-02-27 12:45:36 +0000954static bool isPointerOperand(Value *V) {
955 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
956}
957
958// This is a rough heuristic; it may cause both false positives and
959// false negatives. The proper implementation requires cooperation with
960// the frontend.
961static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
962 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000963 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000964 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000965 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000966 } else {
967 return false;
968 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +0000969 return isPointerOperand(I->getOperand(0)) &&
970 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +0000971}
972
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000973bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
974 // If a global variable does not have dynamic initialization we don't
975 // have to instrument it. However, if a global does not have initializer
976 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000977 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000978}
979
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000980void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
981 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +0000982 IRBuilder<> IRB(I);
983 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
984 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
985 for (int i = 0; i < 2; i++) {
986 if (Param[i]->getType()->isPointerTy())
987 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
988 }
David Blaikieff6409d2015-05-18 22:13:54 +0000989 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000990}
991
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000992void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000993 Instruction *I, bool UseCalls,
994 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +0000995 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000996 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000997 uint64_t TypeSize = 0;
998 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +0000999 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001000
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001001 // Optimization experiments.
1002 // The experiments can be used to evaluate potential optimizations that remove
1003 // instrumentation (assess false negatives). Instead of completely removing
1004 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1005 // experiments that want to remove instrumentation of this instruction).
1006 // If Exp is non-zero, this pass will emit special calls into runtime
1007 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1008 // make runtime terminate the program in a special way (with a different
1009 // exit status). Then you run the new compiler on a buggy corpus, collect
1010 // the special terminations (ideally, you don't see them at all -- no false
1011 // negatives) and make the decision on the optimization.
1012 uint32_t Exp = ClForceExperiment;
1013
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001014 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001015 // If initialization order checking is disabled, a simple access to a
1016 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001017 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001018 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001019 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1020 NumOptimizedAccessesToGlobalVar++;
1021 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001022 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001023 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001024
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001025 if (ClOpt && ClOptStack) {
1026 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001027 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001028 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1029 NumOptimizedAccessesToStackVar++;
1030 return;
1031 }
1032 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001033
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001034 if (IsWrite)
1035 NumInstrumentedWrites++;
1036 else
1037 NumInstrumentedReads++;
1038
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001039 unsigned Granularity = 1 << Mapping.Scale;
1040 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1041 // if the data is properly aligned.
1042 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1043 TypeSize == 128) &&
1044 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001045 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
1046 Exp);
1047 instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
1048 UseCalls, Exp);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001049}
1050
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001051Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1052 Value *Addr, bool IsWrite,
1053 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001054 Value *SizeArgument,
1055 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001056 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001057 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1058 CallInst *Call = nullptr;
1059 if (SizeArgument) {
1060 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001061 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1062 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001063 else
David Blaikieff6409d2015-05-18 22:13:54 +00001064 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1065 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001066 } else {
1067 if (Exp == 0)
1068 Call =
1069 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1070 else
David Blaikieff6409d2015-05-18 22:13:54 +00001071 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1072 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001073 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001074
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001075 // We don't do Call->setDoesNotReturn() because the BB already has
1076 // UnreachableInst at the end.
1077 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001078 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001079 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001080}
1081
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001082Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001083 Value *ShadowValue,
1084 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001085 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001086 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001087 Value *LastAccessedByte =
1088 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001089 // (Addr & (Granularity - 1)) + size - 1
1090 if (TypeSize / 8 > 1)
1091 LastAccessedByte = IRB.CreateAdd(
1092 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1093 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001094 LastAccessedByte =
1095 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001096 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1097 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1098}
1099
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001100void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001101 Instruction *InsertBefore, Value *Addr,
1102 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001103 Value *SizeArgument, bool UseCalls,
1104 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001105 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001106 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001107 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1108
1109 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001110 if (Exp == 0)
1111 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1112 AddrLong);
1113 else
David Blaikieff6409d2015-05-18 22:13:54 +00001114 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1115 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001116 return;
1117 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001118
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001119 Type *ShadowTy =
1120 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001121 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1122 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1123 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001124 Value *ShadowValue =
1125 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001126
1127 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001128 size_t Granularity = 1ULL << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001129 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001130
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001131 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001132 // We use branch weights for the slow path check, to indicate that the slow
1133 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001134 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1135 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001136 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001137 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001138 IRB.SetInsertPoint(CheckTerm);
1139 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001140 if (Recover) {
1141 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1142 } else {
1143 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001144 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001145 CrashTerm = new UnreachableInst(*C, CrashBlock);
1146 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1147 ReplaceInstWithInst(CheckTerm, NewTerm);
1148 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001149 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001150 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001151 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001152
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001153 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001154 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001155 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001156}
1157
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001158// Instrument unusual size or unusual alignment.
1159// We can not do it with a single check, so we do 1-byte check for the first
1160// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1161// to report the actual access size.
1162void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1163 Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1164 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1165 IRBuilder<> IRB(I);
1166 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1167 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1168 if (UseCalls) {
1169 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001170 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1171 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001172 else
David Blaikieff6409d2015-05-18 22:13:54 +00001173 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1174 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001175 } else {
1176 Value *LastByte = IRB.CreateIntToPtr(
1177 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1178 Addr->getType());
1179 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1180 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1181 }
1182}
1183
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001184void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1185 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001186 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001187 IRBuilder<> IRB(&GlobalInit.front(),
1188 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001189
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001190 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001191 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1192 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001193
1194 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001195 for (auto &BB : GlobalInit.getBasicBlockList())
1196 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001197 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001198}
1199
1200void AddressSanitizerModule::createInitializerPoisonCalls(
1201 Module &M, GlobalValue *ModuleName) {
1202 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1203
1204 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1205 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001206 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001207 ConstantStruct *CS = cast<ConstantStruct>(OP);
1208
1209 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001210 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001211 if (F->getName() == kAsanModuleCtorName) continue;
1212 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1213 // Don't instrument CTORs that will run before asan.module_ctor.
1214 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1215 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001216 }
1217 }
1218}
1219
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001220bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001221 Type *Ty = G->getValueType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001222 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001223
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001224 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001225 if (!Ty->isSized()) return false;
1226 if (!G->hasInitializer()) return false;
Kostya Serebryany139a9372012-11-20 14:16:08 +00001227 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001228 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001229 // Don't handle ODR linkage types and COMDATs since other modules may be built
1230 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001231 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1232 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1233 G->getLinkage() != GlobalVariable::InternalLinkage)
1234 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001235 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001236 // Two problems with thread-locals:
1237 // - The address of the main thread's copy can't be computed at link-time.
1238 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001239 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001240 // For now, just ignore this Global if the alignment is large.
1241 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001242
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001243 if (G->hasSection()) {
1244 StringRef Section(G->getSection());
Kuba Brecka086e34b2014-12-05 21:32:46 +00001245
Anna Zaks11904602015-06-09 00:58:08 +00001246 // Globals from llvm.metadata aren't emitted, do not instrument them.
1247 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001248 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001249 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001250
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001251 // Do not instrument function pointers to initialization and termination
1252 // routines: dynamic linker will not properly handle redzones.
1253 if (Section.startswith(".preinit_array") ||
1254 Section.startswith(".init_array") ||
1255 Section.startswith(".fini_array")) {
1256 return false;
1257 }
1258
Anna Zaks11904602015-06-09 00:58:08 +00001259 // Callbacks put into the CRT initializer/terminator sections
1260 // should not be instrumented.
1261 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1262 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1263 if (Section.startswith(".CRT")) {
1264 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1265 return false;
1266 }
1267
Kuba Brecka1001bb52014-12-05 22:19:18 +00001268 if (TargetTriple.isOSBinFormatMachO()) {
1269 StringRef ParsedSegment, ParsedSection;
1270 unsigned TAA = 0, StubSize = 0;
1271 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001272 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1273 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001274 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001275
1276 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1277 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1278 // them.
1279 if (ParsedSegment == "__OBJC" ||
1280 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1281 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1282 return false;
1283 }
1284 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1285 // Constant CFString instances are compiled in the following way:
1286 // -- the string buffer is emitted into
1287 // __TEXT,__cstring,cstring_literals
1288 // -- the constant NSConstantString structure referencing that buffer
1289 // is placed into __DATA,__cfstring
1290 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1291 // Moreover, it causes the linker to crash on OS X 10.7
1292 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1293 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1294 return false;
1295 }
1296 // The linker merges the contents of cstring_literals and removes the
1297 // trailing zeroes.
1298 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1299 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1300 return false;
1301 }
1302 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001303 }
1304
1305 return true;
1306}
1307
Ryan Govostes653f9d02016-03-28 20:28:57 +00001308// On Mach-O platforms, we emit global metadata in a separate section of the
1309// binary in order to allow the linker to properly dead strip. This is only
1310// supported on recent versions of ld64.
1311bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
1312 if (!TargetTriple.isOSBinFormatMachO())
1313 return false;
1314
1315 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1316 return true;
1317 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001318 return true;
Ryan Govostes653f9d02016-03-28 20:28:57 +00001319 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1320 return true;
1321
1322 return false;
1323}
1324
Alexey Samsonov788381b2012-12-25 12:28:20 +00001325void AddressSanitizerModule::initializeCallbacks(Module &M) {
1326 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001327
Alexey Samsonov788381b2012-12-25 12:28:20 +00001328 // Declare our poisoning and unpoisoning functions.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001329 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001330 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001331 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001332 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001333 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001334 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001335
Alexey Samsonov788381b2012-12-25 12:28:20 +00001336 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001337 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001338 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001339 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001340 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001341 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1342 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001343 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001344
1345 // Declare the functions that find globals in a shared object and then invoke
1346 // the (un)register function on them.
1347 AsanRegisterImageGlobals = checkSanitizerInterfaceFunction(
1348 M.getOrInsertFunction(kAsanRegisterImageGlobalsName,
1349 IRB.getVoidTy(), IntptrTy, nullptr));
1350 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001351
Ryan Govostes653f9d02016-03-28 20:28:57 +00001352 AsanUnregisterImageGlobals = checkSanitizerInterfaceFunction(
1353 M.getOrInsertFunction(kAsanUnregisterImageGlobalsName,
1354 IRB.getVoidTy(), IntptrTy, nullptr));
1355 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001356}
1357
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001358// This function replaces all global variables with new variables that have
1359// trailing redzones. It also creates a function that poisons
1360// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001361bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001362 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001363
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001364 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1365
Alexey Samsonova02e6642014-05-29 18:40:48 +00001366 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001367 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001368 }
1369
1370 size_t n = GlobalsToChange.size();
1371 if (n == 0) return false;
1372
1373 // A global is described by a structure
1374 // size_t beg;
1375 // size_t size;
1376 // size_t size_with_redzone;
1377 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001378 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001379 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001380 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001381 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001382 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001383 StructType *GlobalStructTy =
1384 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001385 IntptrTy, IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001386 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001387
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001388 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001389
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001390 // We shouldn't merge same module names, as this string serves as unique
1391 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001392 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001393 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001394
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001395 auto &DL = M.getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001396 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001397 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001398 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001399
1400 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001401 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001402 // Create string holding the global name (use global name from metadata
1403 // if it's available, otherwise just write the name of global variable).
1404 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001405 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001406 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001407
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001408 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001409 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001410 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001411 // MinRZ <= RZ <= kMaxGlobalRedzone
1412 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001413 uint64_t RZ = std::max(
1414 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001415 uint64_t RightRedzoneSize = RZ;
1416 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001417 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001418 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001419 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1420
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001421 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001422 Constant *NewInitializer =
1423 ConstantStruct::get(NewTy, G->getInitializer(),
1424 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001425
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001426 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001427 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1428 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1429 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001430 GlobalVariable *NewGlobal =
1431 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1432 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001433 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001434 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001435
1436 Value *Indices2[2];
1437 Indices2[0] = IRB.getInt32(0);
1438 Indices2[1] = IRB.getInt32(0);
1439
1440 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001441 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001442 NewGlobal->takeName(G);
1443 G->eraseFromParent();
1444
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001445 Constant *SourceLoc;
1446 if (!MD.SourceLoc.empty()) {
1447 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1448 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1449 } else {
1450 SourceLoc = ConstantInt::get(IntptrTy, 0);
1451 }
1452
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001453 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
1454 GlobalValue *InstrumentedGlobal = NewGlobal;
1455
1456 bool CanUsePrivateAliases = TargetTriple.isOSBinFormatELF();
1457 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
1458 // Create local alias for NewGlobal to avoid crash on ODR between
1459 // instrumented and non-instrumented libraries.
1460 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
1461 NameForGlobal + M.getName(), NewGlobal);
1462
1463 // With local aliases, we need to provide another externally visible
1464 // symbol __odr_asan_XXX to detect ODR violation.
1465 auto *ODRIndicatorSym =
1466 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
1467 Constant::getNullValue(IRB.getInt8Ty()),
1468 kODRGenPrefix + NameForGlobal, nullptr,
1469 NewGlobal->getThreadLocalMode());
1470
1471 // Set meaningful attributes for indicator symbol.
1472 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
1473 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
1474 ODRIndicatorSym->setAlignment(1);
1475 ODRIndicator = ODRIndicatorSym;
1476 InstrumentedGlobal = GA;
1477 }
1478
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001479 Initializers[i] = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001480 GlobalStructTy,
1481 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001482 ConstantInt::get(IntptrTy, SizeInBytes),
1483 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1484 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001485 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001486 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
1487 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy), nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001488
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001489 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001490
Kostya Serebryany20343352012-10-17 13:40:06 +00001491 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001492 }
1493
Ryan Govostes653f9d02016-03-28 20:28:57 +00001494
1495 GlobalVariable *AllGlobals = nullptr;
1496 GlobalVariable *RegisteredFlag = nullptr;
1497
1498 // On recent Mach-O platforms, we emit the global metadata in a way that
1499 // allows the linker to properly strip dead globals.
1500 if (ShouldUseMachOGlobalsSection()) {
1501 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1502 // to look up the loaded image that contains it. Second, we can store in it
1503 // whether registration has already occurred, to prevent duplicate
1504 // registration.
1505 //
1506 // Common linkage allows us to coalesce needles defined in each object
1507 // file so that there's only one per shared library.
1508 RegisteredFlag = new GlobalVariable(
1509 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1510 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1511
1512 // We also emit a structure which binds the liveness of the global
1513 // variable to the metadata struct.
1514 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy, nullptr);
1515
1516 for (size_t i = 0; i < n; i++) {
1517 GlobalVariable *Metadata = new GlobalVariable(
1518 M, GlobalStructTy, false, GlobalVariable::InternalLinkage,
1519 Initializers[i], "");
1520 Metadata->setSection("__DATA,__asan_globals,regular");
1521 Metadata->setAlignment(1); // don't leave padding in between
1522
1523 auto LivenessBinder = ConstantStruct::get(LivenessTy,
1524 Initializers[i]->getAggregateElement(0u),
1525 ConstantExpr::getPointerCast(Metadata, IntptrTy),
1526 nullptr);
1527 GlobalVariable *Liveness = new GlobalVariable(
1528 M, LivenessTy, false, GlobalVariable::InternalLinkage,
1529 LivenessBinder, "");
1530 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1531 }
1532 } else {
1533 // On all other platfoms, we just emit an array of global metadata
1534 // structures.
1535 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1536 AllGlobals = new GlobalVariable(
1537 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1538 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1539 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001540
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001541 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001542 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001543 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001544
Ryan Govostes653f9d02016-03-28 20:28:57 +00001545 // Create a call to register the globals with the runtime.
1546 if (ShouldUseMachOGlobalsSection()) {
1547 IRB.CreateCall(AsanRegisterImageGlobals,
1548 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1549 } else {
1550 IRB.CreateCall(AsanRegisterGlobals,
1551 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1552 ConstantInt::get(IntptrTy, n)});
1553 }
1554
1555 // We also need to unregister globals at the end, e.g., when a shared library
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001556 // gets closed.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001557 Function *AsanDtorFunction =
1558 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1559 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001560 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1561 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001562
1563 if (ShouldUseMachOGlobalsSection()) {
1564 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1565 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1566 } else {
1567 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1568 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1569 ConstantInt::get(IntptrTy, n)});
1570 }
1571
Alexey Samsonov1f647502014-05-29 01:10:14 +00001572 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001573
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001574 DEBUG(dbgs() << M);
1575 return true;
1576}
1577
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001578bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001579 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001580 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001581 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001582 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001583 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001584 initializeCallbacks(M);
1585
1586 bool Changed = false;
1587
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001588 // TODO(glider): temporarily disabled globals instrumentation for KASan.
1589 if (ClGlobals && !CompileKernel) {
1590 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1591 assert(CtorFunc);
1592 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1593 Changed |= InstrumentGlobals(IRB, M);
1594 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001595
1596 return Changed;
1597}
1598
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001599void AddressSanitizer::initializeCallbacks(Module &M) {
1600 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001601 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001602 // IsWrite, TypeSize and Exp are encoded in the function name.
1603 for (int Exp = 0; Exp < 2; Exp++) {
1604 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1605 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1606 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001607 const std::string SuffixStr = CompileKernel ? "N" : "_n";
Yury Gribovd7731982015-11-11 10:36:49 +00001608 const std::string EndingStr = Recover ? "_noabort" : "";
Craig Toppere3dcce92015-08-01 22:20:21 +00001609 Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001610 AsanErrorCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001611 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001612 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001613 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1614 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001615 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001616 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001617 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1618 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1619 AccessSizeIndex++) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001620 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001621 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001622 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001623 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001624 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001625 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001626 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001627 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1628 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001629 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001630 }
1631 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00001632
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001633 const std::string MemIntrinCallbackPrefix =
1634 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001635 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001636 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001637 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001638 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001639 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001640 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001641 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001642 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001643 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001644
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001645 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001646 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001647
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001648 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001649 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001650 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001651 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001652 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1653 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1654 StringRef(""), StringRef(""),
1655 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001656}
1657
1658// virtual
1659bool AddressSanitizer::doInitialization(Module &M) {
1660 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001661
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001662 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001663
1664 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001665 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001666 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001667 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001668
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001669 if (!CompileKernel) {
1670 std::tie(AsanCtorFunction, AsanInitFunction) =
Kuba Brecka45dbffd2015-07-23 10:54:06 +00001671 createSanitizerCtorAndInitFunctions(
1672 M, kAsanModuleCtorName, kAsanInitName,
1673 /*InitArgTypes=*/{}, /*InitArgs=*/{}, kAsanVersionCheckName);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001674 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1675 }
1676 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001677 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001678}
1679
Keno Fischere03fae42015-12-05 14:42:34 +00001680bool AddressSanitizer::doFinalization(Module &M) {
1681 GlobalsMD.reset();
1682 return false;
1683}
1684
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001685bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1686 // For each NSObject descendant having a +load method, this method is invoked
1687 // by the ObjC runtime before any of the static constructors is called.
1688 // Therefore we need to instrument such methods with a call to __asan_init
1689 // at the beginning in order to initialize our runtime before any access to
1690 // the shadow memory.
1691 // We cannot just ignore these methods, because they may call other
1692 // instrumented functions.
1693 if (F.getName().find(" load]") != std::string::npos) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001694 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00001695 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001696 return true;
1697 }
1698 return false;
1699}
1700
Reid Kleckner2f907552015-07-21 17:40:14 +00001701void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
1702 // Find the one possible call to llvm.localescape and pre-mark allocas passed
1703 // to it as uninteresting. This assumes we haven't started processing allocas
1704 // yet. This check is done up front because iterating the use list in
1705 // isInterestingAlloca would be algorithmically slower.
1706 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
1707
1708 // Try to get the declaration of llvm.localescape. If it's not in the module,
1709 // we can exit early.
1710 if (!F.getParent()->getFunction("llvm.localescape")) return;
1711
1712 // Look for a call to llvm.localescape call in the entry block. It can't be in
1713 // any other block.
1714 for (Instruction &I : F.getEntryBlock()) {
1715 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
1716 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
1717 // We found a call. Mark all the allocas passed in as uninteresting.
1718 for (Value *Arg : II->arg_operands()) {
1719 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
1720 assert(AI && AI->isStaticAlloca() &&
1721 "non-static alloca arg to localescape");
1722 ProcessedAllocas[AI] = false;
1723 }
1724 break;
1725 }
1726 }
1727}
1728
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001729bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001730 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001731 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001732 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001733 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001734
Yury Gribov3ae427d2014-12-01 08:47:58 +00001735 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1736
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001737 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001738 maybeInsertAsanInitAtFunctionEntry(F);
1739
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001740 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001741
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001742 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001743
Reid Kleckner2f907552015-07-21 17:40:14 +00001744 FunctionStateRAII CleanupObj(this);
1745
1746 // We can't instrument allocas used with llvm.localescape. Only static allocas
1747 // can be passed to that intrinsic.
1748 markEscapedLocalAllocas(F);
1749
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001750 // We want to instrument every address only once per basic block (unless there
1751 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001752 SmallSet<Value *, 16> TempsToInstrument;
1753 SmallVector<Instruction *, 16> ToInstrument;
1754 SmallVector<Instruction *, 8> NoReturnCalls;
1755 SmallVector<BasicBlock *, 16> AllBlocks;
1756 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001757 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001758 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001759 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001760 uint64_t TypeSize;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001761
1762 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001763 for (auto &BB : F) {
1764 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001765 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001766 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001767 for (auto &Inst : BB) {
1768 if (LooksLikeCodeInBug11395(&Inst)) return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001769 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1770 &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001771 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001772 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001773 continue; // We've seen this temp in the current BB.
1774 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001775 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001776 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1777 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001778 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001779 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001780 // ok, take it.
1781 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001782 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001783 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001784 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001785 // A call inside BB.
1786 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001787 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001788 }
1789 continue;
1790 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001791 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001792 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001793 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001794 }
1795 }
1796
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001797 bool UseCalls =
1798 CompileKernel ||
1799 (ClInstrumentationWithCallsThreshold >= 0 &&
1800 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001801 const TargetLibraryInfo *TLI =
1802 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001803 const DataLayout &DL = F.getParent()->getDataLayout();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001804 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1805 /*RoundToAlign=*/true);
1806
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001807 // Instrument.
1808 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001809 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001810 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1811 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001812 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001813 instrumentMop(ObjSizeVis, Inst, UseCalls,
1814 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001815 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001816 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001817 }
1818 NumInstrumented++;
1819 }
1820
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001821 FunctionStackPoisoner FSP(F, *this);
1822 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001823
1824 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1825 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001826 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001827 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00001828 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001829 }
1830
Alexey Samsonova02e6642014-05-29 18:40:48 +00001831 for (auto Inst : PointerComparisonsOrSubtracts) {
1832 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001833 NumInstrumented++;
1834 }
1835
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001836 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001837
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001838 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1839
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001840 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001841}
1842
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001843// Workaround for bug 11395: we don't want to instrument stack in functions
1844// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1845// FIXME: remove once the bug 11395 is fixed.
1846bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1847 if (LongSize != 32) return false;
1848 CallInst *CI = dyn_cast<CallInst>(I);
1849 if (!CI || !CI->isInlineAsm()) return false;
1850 if (CI->getNumArgOperands() <= 5) return false;
1851 // We have inline assembly with quite a few arguments.
1852 return true;
1853}
1854
1855void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1856 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001857 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1858 std::string Suffix = itostr(i);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001859 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1860 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1861 IntptrTy, nullptr));
1862 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001863 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1864 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001865 }
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001866 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
David Blaikiea92765c2014-11-14 00:41:42 +00001867 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1868 IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001869 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
David Blaikiea92765c2014-11-14 00:41:42 +00001870 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1871 IntptrTy, IntptrTy, nullptr));
Yury Gribov98b18592015-05-28 07:51:49 +00001872 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1873 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1874 AsanAllocasUnpoisonFunc =
1875 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1876 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001877}
1878
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001879void FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1880 IRBuilder<> &IRB, Value *ShadowBase,
1881 bool DoPoison) {
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001882 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001883 size_t i = 0;
1884 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1885 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1886 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1887 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1888 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1889 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1890 uint64_t Val = 0;
1891 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001892 if (F.getParent()->getDataLayout().isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001893 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1894 else
1895 Val = (Val << 8) | ShadowBytes[i + j];
1896 }
1897 if (!Val) continue;
1898 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1899 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1900 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1901 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001902 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001903 }
1904}
1905
Kostya Serebryany6805de52013-09-10 13:16:56 +00001906// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1907// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1908static int StackMallocSizeClass(uint64_t LocalStackSize) {
1909 assert(LocalStackSize <= kMaxStackMallocSize);
1910 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001911 for (int i = 0;; i++, MaxSize *= 2)
1912 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00001913 llvm_unreachable("impossible LocalStackSize");
1914}
1915
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001916// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1917// We can not use MemSet intrinsic because it may end up calling the actual
1918// memset. Size is a multiple of 8.
1919// Currently this generates 8-byte stores on x86_64; it may be better to
1920// generate wider stores.
1921void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1922 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1923 assert(!(Size % 8));
Gabor Horvathfee04342015-03-16 09:53:42 +00001924
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001925 // kAsanStackAfterReturnMagic is 0xf5.
1926 const uint64_t kAsanStackAfterReturnMagic64 = 0xf5f5f5f5f5f5f5f5ULL;
Gabor Horvathfee04342015-03-16 09:53:42 +00001927
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001928 for (int i = 0; i < Size; i += 8) {
1929 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001930 IRB.CreateStore(
1931 ConstantInt::get(IRB.getInt64Ty(), kAsanStackAfterReturnMagic64),
1932 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001933 }
1934}
1935
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001936PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1937 Value *ValueIfTrue,
1938 Instruction *ThenTerm,
1939 Value *ValueIfFalse) {
1940 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1941 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1942 PHI->addIncoming(ValueIfFalse, CondBlock);
1943 BasicBlock *ThenBlock = ThenTerm->getParent();
1944 PHI->addIncoming(ValueIfTrue, ThenBlock);
1945 return PHI;
1946}
1947
1948Value *FunctionStackPoisoner::createAllocaForLayout(
1949 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
1950 AllocaInst *Alloca;
1951 if (Dynamic) {
1952 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
1953 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
1954 "MyAlloca");
1955 } else {
1956 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
1957 nullptr, "MyAlloca");
1958 assert(Alloca->isStaticAlloca());
1959 }
1960 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1961 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1962 Alloca->setAlignment(FrameAlignment);
1963 return IRB.CreatePointerCast(Alloca, IntptrTy);
1964}
1965
Yury Gribov98b18592015-05-28 07:51:49 +00001966void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
1967 BasicBlock &FirstBB = *F.begin();
1968 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
1969 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
1970 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
1971 DynamicAllocaLayout->setAlignment(32);
1972}
1973
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001974void FunctionStackPoisoner::poisonStack() {
Yury Gribov55441bb2014-11-21 10:29:50 +00001975 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1976
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00001977 // Insert poison calls for lifetime intrinsics for alloca.
1978 bool HavePoisonedAllocas = false;
1979 for (const auto &APC : AllocaPoisonCallVec) {
1980 assert(APC.InsBefore);
1981 assert(APC.AI);
1982 IRBuilder<> IRB(APC.InsBefore);
1983 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1984 HavePoisonedAllocas |= APC.DoPoison;
1985 }
1986
Yury Gribov98b18592015-05-28 07:51:49 +00001987 if (ClInstrumentAllocas && DynamicAllocaVec.size() > 0) {
Yury Gribov55441bb2014-11-21 10:29:50 +00001988 // Handle dynamic allocas.
Yury Gribov98b18592015-05-28 07:51:49 +00001989 createDynamicAllocasInitStorage();
Alexander Potapenkof90556e2015-06-12 11:27:06 +00001990 for (auto &AI : DynamicAllocaVec) handleDynamicAllocaCall(AI);
Yury Gribov98b18592015-05-28 07:51:49 +00001991
1992 unpoisonDynamicAllocas();
Kuba Breckaf5875d32015-02-24 09:47:05 +00001993 }
Yury Gribov55441bb2014-11-21 10:29:50 +00001994
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001995 if (AllocaVec.empty()) return;
Yury Gribov55441bb2014-11-21 10:29:50 +00001996
Kostya Serebryany6805de52013-09-10 13:16:56 +00001997 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00001998 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00001999 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002000 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002001
2002 Instruction *InsBefore = AllocaVec[0];
2003 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002004 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002005
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002006 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2007 // debug info is broken, because only entry-block allocas are treated as
2008 // regular stack slots.
2009 auto InsBeforeB = InsBefore->getParent();
2010 assert(InsBeforeB == &F.getEntryBlock());
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002011 for (BasicBlock::iterator I(InsBefore); I != InsBeforeB->end(); ++I)
2012 if (auto *AI = dyn_cast<AllocaInst>(I))
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002013 if (NonInstrumentedStaticAllocaVec.count(AI) > 0)
2014 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00002015
Reid Kleckner2f907552015-07-21 17:40:14 +00002016 // If we have a call to llvm.localescape, keep it in the entry block.
2017 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2018
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002019 SmallVector<ASanStackVariableDescription, 16> SVD;
2020 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00002021 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002022 ASanStackVariableDescription D = {AI->getName().data(),
2023 ASan.getAllocaSizeInBytes(AI),
2024 AI->getAlignment(), AI, 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002025 SVD.push_back(D);
2026 }
2027 // Minimal header size (left redzone) is 4 pointers,
2028 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2029 size_t MinHeaderSize = ASan.LongSize / 2;
2030 ASanStackFrameLayout L;
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00002031 ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize, &L);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002032 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
2033 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002034 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2035 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00002036 bool DoDynamicAlloca = ClDynamicAllocaStack;
2037 // Don't do dynamic alloca or stack malloc if:
2038 // 1) There is inline asm: too often it makes assumptions on which registers
2039 // are available.
2040 // 2) There is a returns_twice call (typically setjmp), which is
2041 // optimization-hostile, and doesn't play well with introduced indirect
2042 // register-relative calculation of local variable addresses.
2043 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2044 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002045
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002046 Value *StaticAlloca =
2047 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2048
2049 Value *FakeStack;
2050 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002051
2052 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002053 // void *FakeStack = __asan_option_detect_stack_use_after_return
2054 // ? __asan_stack_malloc_N(LocalStackSize)
2055 // : nullptr;
2056 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002057 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
2058 kAsanOptionDetectUAR, IRB.getInt32Ty());
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002059 Value *UARIsEnabled =
2060 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
2061 Constant::getNullValue(IRB.getInt32Ty()));
2062 Instruction *Term =
2063 SplitBlockAndInsertIfThen(UARIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002064 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002065 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002066 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2067 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2068 Value *FakeStackValue =
2069 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2070 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002071 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002072 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002073 FakeStack = createPHI(IRB, UARIsEnabled, FakeStackValue, Term,
2074 ConstantInt::get(IntptrTy, 0));
2075
2076 Value *NoFakeStack =
2077 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2078 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2079 IRBIf.SetInsertPoint(Term);
2080 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2081 Value *AllocaValue =
2082 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2083 IRB.SetInsertPoint(InsBefore);
2084 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2085 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2086 } else {
2087 // void *FakeStack = nullptr;
2088 // void *LocalStackBase = alloca(LocalStackSize);
2089 FakeStack = ConstantInt::get(IntptrTy, 0);
2090 LocalStackBase =
2091 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002092 }
2093
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002094 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002095 for (const auto &Desc : SVD) {
2096 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00002097 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00002098 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002099 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00002100 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002101 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002102 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002103
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002104 // The left-most redzone has enough space for at least 4 pointers.
2105 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002106 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2107 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2108 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002109 // Write the frame description constant to redzone[1].
2110 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002111 IRB.CreateAdd(LocalStackBase,
2112 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2113 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00002114 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00002115 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002116 /*AllowMerging*/ true);
2117 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002118 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002119 // Write the PC to redzone[2].
2120 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002121 IRB.CreateAdd(LocalStackBase,
2122 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2123 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002124 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002125
2126 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002127 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002128 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002129
Kostya Serebryany530e2072013-12-23 14:15:08 +00002130 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002131 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002132 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002133 // Mark the current frame as retired.
2134 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2135 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002136 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00002137 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002138 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00002139 // // In use-after-return mode, poison the whole stack frame.
2140 // if StackMallocIdx <= 4
2141 // // For small sizes inline the whole thing:
2142 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002143 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00002144 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002145 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00002146 // else
2147 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002148 Value *Cmp =
2149 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00002150 TerminatorInst *ThenTerm, *ElseTerm;
2151 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2152
2153 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002154 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002155 int ClassSize = kMinStackMallocSize << StackMallocIdx;
2156 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
2157 ClassSize >> Mapping.Scale);
2158 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002159 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002160 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2161 Value *SavedFlagPtr = IRBPoison.CreateLoad(
2162 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2163 IRBPoison.CreateStore(
2164 Constant::getNullValue(IRBPoison.getInt8Ty()),
2165 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2166 } else {
2167 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00002168 IRBPoison.CreateCall(
2169 AsanStackFreeFunc[StackMallocIdx],
2170 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002171 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00002172
2173 IRBuilder<> IRBElse(ElseTerm);
2174 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002175 } else if (HavePoisonedAllocas) {
2176 // If we poisoned some allocas in llvm.lifetime analysis,
2177 // unpoison whole stack frame now.
Alexey Samsonov261177a2012-12-04 01:34:23 +00002178 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany530e2072013-12-23 14:15:08 +00002179 } else {
2180 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002181 }
2182 }
2183
Kostya Serebryany09959942012-10-19 06:20:53 +00002184 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002185 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002186}
Alexey Samsonov261177a2012-12-04 01:34:23 +00002187
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002188void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00002189 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00002190 // For now just insert the call to ASan runtime.
2191 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2192 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002193 IRB.CreateCall(
2194 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2195 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00002196}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002197
2198// Handling llvm.lifetime intrinsics for a given %alloca:
2199// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2200// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2201// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2202// could be poisoned by previous llvm.lifetime.end instruction, as the
2203// variable may go in and out of scope several times, e.g. in loops).
2204// (3) if we poisoned at least one %alloca in a function,
2205// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002206
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002207AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2208 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
2209 // We're intested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00002210 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002211 // See if we've already calculated (or started to calculate) alloca for a
2212 // given value.
2213 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002214 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002215 // Store 0 while we're calculating alloca for value V to avoid
2216 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00002217 AllocaForValue[V] = nullptr;
2218 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002219 if (CastInst *CI = dyn_cast<CastInst>(V))
2220 Res = findAllocaForValue(CI->getOperand(0));
2221 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00002222 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002223 // Allow self-referencing phi-nodes.
2224 if (IncValue == PN) continue;
2225 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2226 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00002227 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2228 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002229 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002230 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002231 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002232 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002233 return Res;
2234}
Yury Gribov55441bb2014-11-21 10:29:50 +00002235
Yury Gribov98b18592015-05-28 07:51:49 +00002236void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00002237 IRBuilder<> IRB(AI);
2238
Yury Gribov55441bb2014-11-21 10:29:50 +00002239 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2240 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2241
2242 Value *Zero = Constant::getNullValue(IntptrTy);
2243 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2244 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00002245
2246 // Since we need to extend alloca with additional memory to locate
2247 // redzones, and OldSize is number of allocated blocks with
2248 // ElementSize size, get allocated memory size in bytes by
2249 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00002250 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002251 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00002252 Value *OldSize =
2253 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2254 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00002255
2256 // PartialSize = OldSize % 32
2257 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2258
2259 // Misalign = kAllocaRzSize - PartialSize;
2260 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2261
2262 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2263 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2264 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2265
2266 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2267 // Align is added to locate left redzone, PartialPadding for possible
2268 // partial redzone and kAllocaRzSize for right redzone respectively.
2269 Value *AdditionalChunkSize = IRB.CreateAdd(
2270 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2271
2272 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2273
2274 // Insert new alloca with new NewSize and Align params.
2275 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2276 NewAlloca->setAlignment(Align);
2277
2278 // NewAddress = Address + Align
2279 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2280 ConstantInt::get(IntptrTy, Align));
2281
Yury Gribov98b18592015-05-28 07:51:49 +00002282 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00002283 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00002284
2285 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2286 // for unpoisoning stuff.
2287 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2288
Yury Gribov55441bb2014-11-21 10:29:50 +00002289 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2290
Yury Gribov98b18592015-05-28 07:51:49 +00002291 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00002292 AI->replaceAllUsesWith(NewAddressPtr);
2293
Yury Gribov98b18592015-05-28 07:51:49 +00002294 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00002295 AI->eraseFromParent();
2296}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002297
2298// isSafeAccess returns true if Addr is always inbounds with respect to its
2299// base object. For example, it is a field access or an array access with
2300// constant inbounds index.
2301bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2302 Value *Addr, uint64_t TypeSize) const {
2303 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2304 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00002305 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002306 int64_t Offset = SizeOffset.second.getSExtValue();
2307 // Three checks are required to ensure safety:
2308 // . Offset >= 0 (since the offset is given from the base ptr)
2309 // . Size >= Offset (unsigned)
2310 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00002311 return Offset >= 0 && Size >= uint64_t(Offset) &&
2312 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002313}