blob: dfdcd1122da973fd5f9398e24dd6ed3cb8d76a0a [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>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000057#include <iomanip>
Vitaly Buka793913c2016-08-29 18:17:21 +000058#include <limits>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000059#include <sstream>
Chandler Carruthed0881b2012-12-03 16:50:05 +000060#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000061#include <system_error>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000062
63using namespace llvm;
64
Chandler Carruth964daaa2014-04-22 02:55:47 +000065#define DEBUG_TYPE "asan"
66
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000067static const uint64_t kDefaultShadowScale = 3;
68static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
69static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Anna Zaks3b50e702016-02-02 22:05:07 +000070static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
71static const uint64_t kIOSShadowOffset64 = 0x120200000;
72static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
73static const uint64_t kIOSSimShadowOffset64 = kDefaultShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000074static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +000075static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
Kostya Serebryany4766fe62013-01-23 12:54:55 +000076static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +000077static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +000078static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +000079static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +000080static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000081static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
82static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +000083static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Etienne Bergeron70684f92016-06-21 15:07:29 +000084// TODO(wwchrome): Experimental for asan Win64, may change.
85static const uint64_t kWindowsShadowOffset64 = 0x1ULL << 45; // 32TB.
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000086
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000087static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000088static const size_t kMaxStackMallocSize = 1 << 16; // 64K
89static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
90static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
91
Craig Topperd3a34f82013-07-16 01:17:10 +000092static const char *const kAsanModuleCtorName = "asan.module_ctor";
93static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000094static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000095static const char *const kAsanReportErrorTemplate = "__asan_report_";
Craig Topperd3a34f82013-07-16 01:17:10 +000096static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000097static const char *const kAsanUnregisterGlobalsName =
98 "__asan_unregister_globals";
Ryan Govostes653f9d02016-03-28 20:28:57 +000099static const char *const kAsanRegisterImageGlobalsName =
100 "__asan_register_image_globals";
101static const char *const kAsanUnregisterImageGlobalsName =
102 "__asan_unregister_image_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +0000103static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
104static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kuba Brecka45dbffd2015-07-23 10:54:06 +0000105static const char *const kAsanInitName = "__asan_init";
106static const char *const kAsanVersionCheckName =
Ryan Govostes653f9d02016-03-28 20:28:57 +0000107 "__asan_version_mismatch_check_v8";
Kostya Serebryany796f6552014-02-27 12:45:36 +0000108static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
109static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +0000110static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000111static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +0000112static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
113static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000114static const char *const kAsanGenPrefix = "__asan_gen_";
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000115static const char *const kODRGenPrefix = "__odr_asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000116static const char *const kSanCovGenPrefix = "__sancov_gen_";
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000117static const char *const kAsanSetShadowPrefix = "__asan_set_shadow_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000118static const char *const kAsanPoisonStackMemoryName =
119 "__asan_poison_stack_memory";
120static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000121 "__asan_unpoison_stack_memory";
Ryan Govostes653f9d02016-03-28 20:28:57 +0000122static const char *const kAsanGlobalsRegisteredFlagName =
123 "__asan_globals_registered";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000124
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +0000125static const char *const kAsanOptionDetectUseAfterReturn =
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000126 "__asan_option_detect_stack_use_after_return";
127
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000128static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
129static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
Yury Gribov98b18592015-05-28 07:51:49 +0000130
Kostya Serebryany874dae62012-07-16 16:15:40 +0000131// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
132static const size_t kNumberOfAccessSizes = 5;
133
Yury Gribov55441bb2014-11-21 10:29:50 +0000134static const unsigned kAllocaRzSize = 32;
Yury Gribov55441bb2014-11-21 10:29:50 +0000135
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000136// Command-line flags.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000137static cl::opt<bool> ClEnableKasan(
138 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
139 cl::Hidden, cl::init(false));
Yury Gribovd7731982015-11-11 10:36:49 +0000140static cl::opt<bool> ClRecover(
141 "asan-recover",
142 cl::desc("Enable recovery mode (continue-after-error)."),
143 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000144
145// This flag may need to be replaced with -f[no-]asan-reads.
146static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000147 cl::desc("instrument read instructions"),
148 cl::Hidden, cl::init(true));
149static cl::opt<bool> ClInstrumentWrites(
150 "asan-instrument-writes", cl::desc("instrument write instructions"),
151 cl::Hidden, cl::init(true));
152static cl::opt<bool> ClInstrumentAtomics(
153 "asan-instrument-atomics",
154 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
155 cl::init(true));
156static cl::opt<bool> ClAlwaysSlowPath(
157 "asan-always-slow-path",
158 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
159 cl::init(false));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000160// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000161// in any given BB. Normally, this should be set to unlimited (INT_MAX),
162// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
163// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000164static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
165 "asan-max-ins-per-bb", cl::init(10000),
166 cl::desc("maximal number of instructions to instrument in any given BB"),
167 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000168// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000169static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
170 cl::Hidden, cl::init(true));
Vitaly Buka1f9e1352016-08-20 20:23:50 +0000171static cl::opt<uint32_t> ClMaxInlinePoisoningSize(
172 "asan-max-inline-poisoning-size",
173 cl::desc(
174 "Inline shadow poisoning for blocks up to the given size in bytes."),
175 cl::Hidden, cl::init(64));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000176static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Mike Aizatsky243b71f2016-04-21 22:00:13 +0000177 cl::desc("Check stack-use-after-return"),
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000178 cl::Hidden, cl::init(true));
Kostya Serebryanya83bfea2016-04-20 20:02:58 +0000179static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
180 cl::desc("Check stack-use-after-scope"),
181 cl::Hidden, cl::init(false));
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000182static cl::opt<bool> ClExperimentalPoisoning(
183 "asan-experimental-poisoning",
184 cl::desc("Enable experimental red zones and scope poisoning"), cl::Hidden,
Vitaly Buka3c4f6bf2016-08-29 19:28:34 +0000185 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000186// This flag may need to be replaced with -f[no]asan-globals.
187static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000188 cl::desc("Handle global objects"), cl::Hidden,
189 cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000190static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000191 cl::desc("Handle C++ initializer order"),
192 cl::Hidden, cl::init(true));
193static cl::opt<bool> ClInvalidPointerPairs(
194 "asan-detect-invalid-pointer-pair",
195 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
196 cl::init(false));
197static cl::opt<unsigned> ClRealignStack(
198 "asan-realign-stack",
199 cl::desc("Realign stack to the value of this flag (power of two)"),
200 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000201static cl::opt<int> ClInstrumentationWithCallsThreshold(
202 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000203 cl::desc(
204 "If the function being instrumented contains more than "
205 "this number of memory accesses, use callbacks instead of "
206 "inline checks (-1 means never use callbacks)."),
207 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000208static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000209 "asan-memory-access-callback-prefix",
210 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
211 cl::init("__asan_"));
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000212static cl::opt<bool>
213 ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
214 cl::desc("instrument dynamic allocas"),
215 cl::Hidden, cl::init(true));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000216static cl::opt<bool> ClSkipPromotableAllocas(
217 "asan-skip-promotable-allocas",
218 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
219 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000220
221// These flags allow to change the shadow mapping.
222// The shadow mapping looks like
Ryan Govostes3f37df02016-05-06 10:25:22 +0000223// Shadow = (Mem >> scale) + offset
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000224static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000225 cl::desc("scale of asan shadow mapping"),
226 cl::Hidden, cl::init(0));
Ryan Govostes6194ae62016-05-06 11:22:11 +0000227static cl::opt<unsigned long long> ClMappingOffset(
228 "asan-mapping-offset",
229 cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden,
230 cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000231
232// Optimization flags. Not user visible, used mostly for testing
233// and benchmarking the tool.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000234static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
235 cl::Hidden, cl::init(true));
236static cl::opt<bool> ClOptSameTemp(
237 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
238 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000239static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000240 cl::desc("Don't instrument scalar globals"),
241 cl::Hidden, cl::init(true));
242static cl::opt<bool> ClOptStack(
243 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
244 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000245
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000246static cl::opt<bool> ClDynamicAllocaStack(
247 "asan-stack-dynamic-alloca",
248 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000249 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000250
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000251static cl::opt<uint32_t> ClForceExperiment(
252 "asan-force-experiment",
253 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
254 cl::init(0));
255
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000256static cl::opt<bool>
257 ClUsePrivateAliasForGlobals("asan-use-private-alias",
258 cl::desc("Use private aliases for global"
259 " variables"),
260 cl::Hidden, cl::init(false));
261
Ryan Govostese51401b2016-07-05 21:53:08 +0000262static cl::opt<bool>
263 ClUseMachOGlobalsSection("asan-globals-live-support",
264 cl::desc("Use linker features to support dead "
265 "code stripping of globals "
266 "(Mach-O only)"),
267 cl::Hidden, cl::init(false));
268
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000269// Debug flags.
270static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
271 cl::init(0));
272static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
273 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000274static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
275 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000276static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
277 cl::Hidden, cl::init(-1));
278static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
279 cl::Hidden, cl::init(-1));
280
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000281STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
282STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000283STATISTIC(NumOptimizedAccessesToGlobalVar,
284 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000285STATISTIC(NumOptimizedAccessesToStackVar,
286 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000287
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000288namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000289/// Frontend-provided metadata for source location.
290struct LocationMetadata {
291 StringRef Filename;
292 int LineNo;
293 int ColumnNo;
294
295 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
296
297 bool empty() const { return Filename.empty(); }
298
299 void parse(MDNode *MDN) {
300 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000301 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
302 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000303 LineNo =
304 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
305 ColumnNo =
306 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000307 }
308};
309
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000310/// Frontend-provided metadata for global variables.
311class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000312 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000313 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000314 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000315 LocationMetadata SourceLoc;
316 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000317 bool IsDynInit;
318 bool IsBlacklisted;
319 };
320
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000321 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000322
Keno Fischere03fae42015-12-05 14:42:34 +0000323 void reset() {
324 inited_ = false;
325 Entries.clear();
326 }
327
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000328 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000329 assert(!inited_);
330 inited_ = true;
331 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000332 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000333 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000334 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000335 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000336 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000337 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000338 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000339 // We can already have an entry for GV if it was merged with another
340 // global.
341 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000342 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
343 E.SourceLoc.parse(Loc);
344 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
345 E.Name = Name->getString();
346 ConstantInt *IsDynInit =
347 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000348 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000349 ConstantInt *IsBlacklisted =
350 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000351 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000352 }
353 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000354
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000355 /// Returns metadata entry for a given global.
356 Entry get(GlobalVariable *G) const {
357 auto Pos = Entries.find(G);
358 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000359 }
360
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000361 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000362 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000363 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000364};
365
Alexey Samsonov1345d352013-01-16 13:23:28 +0000366/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000367/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000368struct ShadowMapping {
369 int Scale;
370 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000371 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000372};
373
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000374static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
375 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000376 bool IsAndroid = TargetTriple.isAndroid();
Anna Zaks3b50e702016-02-02 22:05:07 +0000377 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000378 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
379 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000380 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
381 TargetTriple.getArch() == llvm::Triple::ppc64le;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000382 bool IsSystemZ = TargetTriple.getArch() == llvm::Triple::systemz;
Anna Zaks3b50e702016-02-02 22:05:07 +0000383 bool IsX86 = TargetTriple.getArch() == llvm::Triple::x86;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000384 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000385 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
386 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000387 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
388 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000389 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000390 bool IsWindows = TargetTriple.isOSWindows();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000391
392 ShadowMapping Mapping;
393
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000394 if (LongSize == 32) {
Evgeniy Stepanov9cb08f82015-07-17 23:51:18 +0000395 // Android is always PIE, which means that the beginning of the address
396 // space is always available.
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000397 if (IsAndroid)
398 Mapping.Offset = 0;
399 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000400 Mapping.Offset = kMIPS32_ShadowOffset32;
401 else if (IsFreeBSD)
402 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000403 else if (IsIOS)
Anna Zaks3b50e702016-02-02 22:05:07 +0000404 // If we're targeting iOS and x86, the binary is built for iOS simulator.
405 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000406 else if (IsWindows)
407 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000408 else
409 Mapping.Offset = kDefaultShadowOffset32;
410 } else { // LongSize == 64
411 if (IsPPC64)
412 Mapping.Offset = kPPC64_ShadowOffset64;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000413 else if (IsSystemZ)
414 Mapping.Offset = kSystemZ_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000415 else if (IsFreeBSD)
416 Mapping.Offset = kFreeBSD_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000417 else if (IsLinux && IsX86_64) {
418 if (IsKasan)
419 Mapping.Offset = kLinuxKasan_ShadowOffset64;
420 else
421 Mapping.Offset = kSmallX86_64ShadowOffset;
Etienne Bergeron70684f92016-06-21 15:07:29 +0000422 } else if (IsWindows && IsX86_64) {
423 Mapping.Offset = kWindowsShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000424 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000425 Mapping.Offset = kMIPS64_ShadowOffset64;
Anna Zaks3b50e702016-02-02 22:05:07 +0000426 else if (IsIOS)
427 // If we're targeting iOS and x86, the binary is built for iOS simulator.
428 Mapping.Offset = IsX86_64 ? kIOSSimShadowOffset64 : kIOSShadowOffset64;
Renato Golinaf213722015-02-03 11:20:45 +0000429 else if (IsAArch64)
430 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000431 else
432 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000433 }
434
435 Mapping.Scale = kDefaultShadowScale;
Ryan Govostes3f37df02016-05-06 10:25:22 +0000436 if (ClMappingScale.getNumOccurrences() > 0) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000437 Mapping.Scale = ClMappingScale;
438 }
439
Ryan Govostes3f37df02016-05-06 10:25:22 +0000440 if (ClMappingOffset.getNumOccurrences() > 0) {
441 Mapping.Offset = ClMappingOffset;
442 }
443
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000444 // OR-ing shadow offset if more efficient (at least on x86) if the offset
445 // is a power of two, but on ppc64 we have to use add since the shadow
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000446 // offset is not necessary 1/8-th of the address space. On SystemZ,
447 // we could OR the constant in a single instruction, but it's more
448 // efficient to load it once and use indexed addressing.
449 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ
Adhemerval Zanella35891fe2015-11-09 18:03:48 +0000450 && !(Mapping.Offset & (Mapping.Offset - 1));
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000451
Alexey Samsonov1345d352013-01-16 13:23:28 +0000452 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000453}
454
Alexey Samsonov1345d352013-01-16 13:23:28 +0000455static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000456 // Redzone used for stack and globals is at least 32 bytes.
457 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000458 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000459}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000460
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000461/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000462struct AddressSanitizer : public FunctionPass {
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000463 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
464 bool UseAfterScope = false)
Yury Gribovd7731982015-11-11 10:36:49 +0000465 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000466 Recover(Recover || ClRecover),
467 UseAfterScope(UseAfterScope || ClUseAfterScope) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000468 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
469 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000470 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000471 return "AddressSanitizerFunctionPass";
472 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000473 void getAnalysisUsage(AnalysisUsage &AU) const override {
474 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000475 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000476 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000477 uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000478 uint64_t ArraySize = 1;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000479 if (AI.isArrayAllocation()) {
480 const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000481 assert(CI && "non-constant array size");
482 ArraySize = CI->getZExtValue();
483 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000484 Type *Ty = AI.getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000485 uint64_t SizeInBytes =
Vitaly Buka21a9e572016-07-28 22:50:50 +0000486 AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000487 return SizeInBytes * ArraySize;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000488 }
489 /// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000490 bool isInterestingAlloca(const AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000491
Anna Zaks8ed1d812015-02-27 03:12:36 +0000492 /// If it is an interesting memory access, return the PointerOperand
493 /// and set IsWrite/Alignment. Otherwise return nullptr.
494 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000495 uint64_t *TypeSize, unsigned *Alignment);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000496 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000497 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000498 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000499 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
500 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000501 Value *SizeArgument, bool UseCalls, uint32_t Exp);
502 void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
503 uint32_t TypeSize, bool IsWrite,
504 Value *SizeArgument, bool UseCalls,
505 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000506 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
507 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000508 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000509 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000510 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000511 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000512 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000513 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000514 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000515 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000516 bool doInitialization(Module &M) override;
Keno Fischere03fae42015-12-05 14:42:34 +0000517 bool doFinalization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000518 static char ID; // Pass identification, replacement for typeid
519
Yury Gribov3ae427d2014-12-01 08:47:58 +0000520 DominatorTree &getDominatorTree() const { return *DT; }
521
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000522 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000523 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000524
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000525 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000526 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000527 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
528 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000529
Reid Kleckner2f907552015-07-21 17:40:14 +0000530 /// Helper to cleanup per-function state.
531 struct FunctionStateRAII {
532 AddressSanitizer *Pass;
533 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
534 assert(Pass->ProcessedAllocas.empty() &&
535 "last pass forgot to clear cache");
536 }
537 ~FunctionStateRAII() { Pass->ProcessedAllocas.clear(); }
538 };
539
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000540 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000541 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000542 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000543 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000544 bool Recover;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000545 bool UseAfterScope;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000546 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000547 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000548 DominatorTree *DT;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000549 Function *AsanCtorFunction = nullptr;
550 Function *AsanInitFunction = nullptr;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000551 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000552 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000553 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
554 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
555 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
556 // This array is indexed by AccessIsWrite and Experiment.
557 Function *AsanErrorCallbackSized[2][2];
558 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000559 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000560 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000561 GlobalsMetadata GlobalsMD;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000562 DenseMap<const AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000563
564 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000565};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000566
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000567class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000568 public:
Yury Gribovd7731982015-11-11 10:36:49 +0000569 explicit AddressSanitizerModule(bool CompileKernel = false,
570 bool Recover = false)
571 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
572 Recover(Recover || ClRecover) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000573 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000574 static char ID; // Pass identification, replacement for typeid
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000575 const char *getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000576
Kostya Serebryany20a79972012-11-22 03:18:50 +0000577 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000578 void initializeCallbacks(Module &M);
579
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000580 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000581 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000582 bool ShouldUseMachOGlobalsSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000583 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000584 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000585 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000586 return RedzoneSizeForScale(Mapping.Scale);
587 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000588
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000589 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000590 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000591 bool Recover;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000592 Type *IntptrTy;
593 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000594 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000595 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000596 Function *AsanPoisonGlobals;
597 Function *AsanUnpoisonGlobals;
598 Function *AsanRegisterGlobals;
599 Function *AsanUnregisterGlobals;
Ryan Govostes653f9d02016-03-28 20:28:57 +0000600 Function *AsanRegisterImageGlobals;
601 Function *AsanUnregisterImageGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000602};
603
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000604// Stack poisoning does not play well with exception handling.
605// When an exception is thrown, we essentially bypass the code
606// that unpoisones the stack. This is why the run-time library has
607// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
608// stack in the interceptor. This however does not work inside the
609// actual function which catches the exception. Most likely because the
610// compiler hoists the load of the shadow value somewhere too high.
611// This causes asan to report a non-existing bug on 453.povray.
612// It sounds like an LLVM bug.
613struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
614 Function &F;
615 AddressSanitizer &ASan;
616 DIBuilder DIB;
617 LLVMContext *C;
618 Type *IntptrTy;
619 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000620 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000621
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000622 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000623 SmallSetVector<AllocaInst *, 16> NonInstrumentedStaticAllocaVec;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000624 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000625 unsigned StackAlignment;
626
Kostya Serebryany6805de52013-09-10 13:16:56 +0000627 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000628 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000629 Function *AsanSetShadowFunc[0x100] = {};
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000630 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000631 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000632
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000633 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
634 struct AllocaPoisonCall {
635 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000636 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000637 uint64_t Size;
638 bool DoPoison;
639 };
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000640 SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
641 SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000642
Yury Gribov98b18592015-05-28 07:51:49 +0000643 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
644 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
645 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000646 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000647
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000648 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000649 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000650 AllocaForValueMapTy AllocaForValue;
651
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000652 bool HasNonEmptyInlineAsm = false;
653 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000654 std::unique_ptr<CallInst> EmptyInlineAsm;
655
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000656 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000657 : F(F),
658 ASan(ASan),
659 DIB(*F.getParent(), /*AllowUnresolved*/ false),
660 C(ASan.C),
661 IntptrTy(ASan.IntptrTy),
662 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
663 Mapping(ASan.Mapping),
664 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000665 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000666
667 bool runOnFunction() {
668 if (!ClStack) return false;
669 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000670 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000671
Yury Gribov55441bb2014-11-21 10:29:50 +0000672 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000673
674 initializeCallbacks(*F.getParent());
675
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000676 processDynamicAllocas();
677 processStaticAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000678
679 if (ClDebugStack) {
680 DEBUG(dbgs() << F);
681 }
682 return true;
683 }
684
Yury Gribov55441bb2014-11-21 10:29:50 +0000685 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000686 // poisoned red zones around all of them.
687 // Then unpoison everything back before the function returns.
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000688 void processStaticAllocas();
689 void processDynamicAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000690
Yury Gribov98b18592015-05-28 07:51:49 +0000691 void createDynamicAllocasInitStorage();
692
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000693 // ----------------------- Visitors.
694 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000695 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000696
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000697 /// \brief Collect all Resume instructions.
698 void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
699
700 /// \brief Collect all CatchReturnInst instructions.
701 void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
702
Yury Gribov98b18592015-05-28 07:51:49 +0000703 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
704 Value *SavedStack) {
705 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000706 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
707 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
708 // need to adjust extracted SP to compute the address of the most recent
709 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
710 // this purpose.
711 if (!isa<ReturnInst>(InstBefore)) {
712 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
713 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
714 {IntptrTy});
715
716 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
717
718 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
719 DynamicAreaOffset);
720 }
721
Yury Gribov781bce22015-05-28 08:03:28 +0000722 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000723 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000724 }
725
Yury Gribov55441bb2014-11-21 10:29:50 +0000726 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000727 void unpoisonDynamicAllocas() {
728 for (auto &Ret : RetVec)
729 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000730
Yury Gribov98b18592015-05-28 07:51:49 +0000731 for (auto &StackRestoreInst : StackRestoreVec)
732 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
733 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000734 }
735
Yury Gribov55441bb2014-11-21 10:29:50 +0000736 // Deploy and poison redzones around dynamic alloca call. To do this, we
737 // should replace this call with another one with changed parameters and
738 // replace all its uses with new address, so
739 // addr = alloca type, old_size, align
740 // is replaced by
741 // new_size = (old_size + additional_size) * sizeof(type)
742 // tmp = alloca i8, new_size, max(align, 32)
743 // addr = tmp + 32 (first 32 bytes are for the left redzone).
744 // Additional_size is added to make new memory allocation contain not only
745 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000746 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000747
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000748 /// \brief Collect Alloca instructions we want (and can) handle.
749 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000750 if (!ASan.isInterestingAlloca(AI)) {
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000751 if (AI.isStaticAlloca()) NonInstrumentedStaticAllocaVec.insert(&AI);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000752 return;
753 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000754
755 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000756 if (!AI.isStaticAlloca())
Yury Gribov98b18592015-05-28 07:51:49 +0000757 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000758 else
759 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000760 }
761
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000762 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
763 /// errors.
764 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000765 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000766 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000767 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000768 if (!ASan.UseAfterScope)
769 return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000770 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000771 return;
772 // Found lifetime intrinsic, add ASan instrumentation if necessary.
773 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
774 // If size argument is undefined, don't do anything.
775 if (Size->isMinusOne()) return;
776 // Check that size doesn't saturate uint64_t and can
777 // be stored in IntptrTy.
778 const uint64_t SizeValue = Size->getValue().getLimitedValue();
779 if (SizeValue == ~0ULL ||
780 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
781 return;
782 // Find alloca instruction that corresponds to llvm.lifetime argument.
783 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
Vitaly Bukab451f1b2016-06-09 23:31:59 +0000784 if (!AI || !ASan.isInterestingAlloca(*AI))
785 return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000786 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000787 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000788 if (AI->isStaticAlloca())
789 StaticAllocaPoisonCallVec.push_back(APC);
790 else if (ClInstrumentDynamicAllocas)
791 DynamicAllocaPoisonCallVec.push_back(APC);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000792 }
793
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000794 void visitCallSite(CallSite CS) {
795 Instruction *I = CS.getInstruction();
796 if (CallInst *CI = dyn_cast<CallInst>(I)) {
797 HasNonEmptyInlineAsm |=
798 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
799 HasReturnsTwiceCall |= CI->canReturnTwice();
800 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000801 }
802
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000803 // ---------------------- Helpers.
804 void initializeCallbacks(Module &M);
805
Yury Gribov3ae427d2014-12-01 08:47:58 +0000806 bool doesDominateAllExits(const Instruction *I) const {
807 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000808 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000809 }
810 return true;
811 }
812
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000813 /// Finds alloca where the value comes from.
814 AllocaInst *findAllocaForValue(Value *V);
Vitaly Buka793913c2016-08-29 18:17:21 +0000815
816 // Copies bytes from ShadowBytes into shadow memory for indexes where
817 // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
818 // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
819 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
820 IRBuilder<> &IRB, Value *ShadowBase);
821 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
822 size_t Begin, size_t End, IRBuilder<> &IRB,
823 Value *ShadowBase);
824 void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
825 ArrayRef<uint8_t> ShadowBytes, size_t Begin,
826 size_t End, IRBuilder<> &IRB, Value *ShadowBase);
827
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000828 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000829
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000830 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
831 bool Dynamic);
832 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
833 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000834};
835
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000836} // anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000837
838char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000839INITIALIZE_PASS_BEGIN(
840 AddressSanitizer, "asan",
841 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
842 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000843INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +0000844INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000845INITIALIZE_PASS_END(
846 AddressSanitizer, "asan",
847 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
848 false)
Yury Gribovd7731982015-11-11 10:36:49 +0000849FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000850 bool Recover,
851 bool UseAfterScope) {
Yury Gribovd7731982015-11-11 10:36:49 +0000852 assert(!CompileKernel || Recover);
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000853 return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000854}
855
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000856char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000857INITIALIZE_PASS(
858 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000859 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000860 "ModulePass",
861 false, false)
Yury Gribovd7731982015-11-11 10:36:49 +0000862ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
863 bool Recover) {
864 assert(!CompileKernel || Recover);
865 return new AddressSanitizerModule(CompileKernel, Recover);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000866}
867
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000868static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000869 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000870 assert(Res < kNumberOfAccessSizes);
871 return Res;
872}
873
Bill Wendling58f8cef2013-08-06 22:52:42 +0000874// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000875static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
876 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000877 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000878 // We use private linkage for module-local strings. If they can be merged
879 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000880 GlobalVariable *GV =
881 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000882 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000883 if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000884 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
885 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000886}
887
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000888/// \brief Create a global describing a source location.
889static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
890 LocationMetadata MD) {
891 Constant *LocData[] = {
892 createPrivateGlobalForString(M, MD.Filename, true),
893 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
894 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
895 };
896 auto LocStruct = ConstantStruct::getAnon(LocData);
897 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
898 GlobalValue::PrivateLinkage, LocStruct,
899 kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000900 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000901 return GV;
902}
903
Vedant Kumarf5ac6d42016-06-22 17:30:58 +0000904/// \brief Check if \p G has been created by a trusted compiler pass.
905static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
906 // Do not instrument asan globals.
907 if (G->getName().startswith(kAsanGenPrefix) ||
908 G->getName().startswith(kSanCovGenPrefix) ||
909 G->getName().startswith(kODRGenPrefix))
910 return true;
911
912 // Do not instrument gcov counter arrays.
913 if (G->getName() == "__llvm_gcov_ctr")
914 return true;
915
916 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000917}
918
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000919Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
920 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000921 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000922 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000923 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000924 if (Mapping.OrShadowOffset)
925 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
926 else
927 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000928}
929
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000930// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000931void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
932 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000933 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000934 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000935 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +0000936 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
937 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
938 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000939 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000940 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000941 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +0000942 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
943 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
944 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000945 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000946 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000947}
948
Anna Zaks8ed1d812015-02-27 03:12:36 +0000949/// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000950bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000951 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
952
953 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
954 return PreviouslySeenAllocaInfo->getSecond();
955
Yury Gribov98b18592015-05-28 07:51:49 +0000956 bool IsInteresting =
957 (AI.getAllocatedType()->isSized() &&
958 // alloca() may be called with 0 size, ignore it.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000959 ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
Yury Gribov98b18592015-05-28 07:51:49 +0000960 // We are only interested in allocas not promotable to registers.
961 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +0000962 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
963 // inalloca allocas are not treated as static, and we don't want
964 // dynamic alloca instrumentation for them as well.
965 !AI.isUsedWithInAlloca());
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000966
967 ProcessedAllocas[&AI] = IsInteresting;
968 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000969}
970
971/// If I is an interesting memory access, return the PointerOperand
972/// and set IsWrite/Alignment. Otherwise return nullptr.
973Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
974 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000975 uint64_t *TypeSize,
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000976 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000977 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000978 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000979
980 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000981 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000982 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000983 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000984 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000985 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000986 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000987 PtrOperand = LI->getPointerOperand();
988 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000989 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000990 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000991 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000992 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000993 PtrOperand = SI->getPointerOperand();
994 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000995 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000996 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000997 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000998 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000999 PtrOperand = RMW->getPointerOperand();
1000 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001001 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001002 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001003 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001004 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001005 PtrOperand = XCHG->getPointerOperand();
Kostya Serebryany90241602012-05-30 09:04:06 +00001006 }
Anna Zaks8ed1d812015-02-27 03:12:36 +00001007
Anna Zaks644d9d32016-06-22 00:15:52 +00001008 // Do not instrument acesses from different address spaces; we cannot deal
1009 // with them.
1010 if (PtrOperand) {
1011 Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1012 if (PtrTy->getPointerAddressSpace() != 0)
1013 return nullptr;
1014 }
1015
Anna Zaks8ed1d812015-02-27 03:12:36 +00001016 // Treat memory accesses to promotable allocas as non-interesting since they
1017 // will not cause memory violations. This greatly speeds up the instrumented
1018 // executable at -O0.
1019 if (ClSkipPromotableAllocas)
1020 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1021 return isInterestingAlloca(*AI) ? AI : nullptr;
1022
1023 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001024}
1025
Kostya Serebryany796f6552014-02-27 12:45:36 +00001026static bool isPointerOperand(Value *V) {
1027 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1028}
1029
1030// This is a rough heuristic; it may cause both false positives and
1031// false negatives. The proper implementation requires cooperation with
1032// the frontend.
1033static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1034 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001035 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001036 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001037 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001038 } else {
1039 return false;
1040 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +00001041 return isPointerOperand(I->getOperand(0)) &&
1042 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001043}
1044
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001045bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1046 // If a global variable does not have dynamic initialization we don't
1047 // have to instrument it. However, if a global does not have initializer
1048 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001049 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001050}
1051
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001052void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1053 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +00001054 IRBuilder<> IRB(I);
1055 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1056 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
Benjamin Kramer135f7352016-06-26 12:28:59 +00001057 for (Value *&i : Param) {
1058 if (i->getType()->isPointerTy())
1059 i = IRB.CreatePointerCast(i, IntptrTy);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001060 }
David Blaikieff6409d2015-05-18 22:13:54 +00001061 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001062}
1063
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001064void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001065 Instruction *I, bool UseCalls,
1066 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +00001067 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001068 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001069 uint64_t TypeSize = 0;
1070 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +00001071 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001072
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001073 // Optimization experiments.
1074 // The experiments can be used to evaluate potential optimizations that remove
1075 // instrumentation (assess false negatives). Instead of completely removing
1076 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1077 // experiments that want to remove instrumentation of this instruction).
1078 // If Exp is non-zero, this pass will emit special calls into runtime
1079 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1080 // make runtime terminate the program in a special way (with a different
1081 // exit status). Then you run the new compiler on a buggy corpus, collect
1082 // the special terminations (ideally, you don't see them at all -- no false
1083 // negatives) and make the decision on the optimization.
1084 uint32_t Exp = ClForceExperiment;
1085
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001086 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001087 // If initialization order checking is disabled, a simple access to a
1088 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001089 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001090 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001091 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1092 NumOptimizedAccessesToGlobalVar++;
1093 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001094 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001095 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001096
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001097 if (ClOpt && ClOptStack) {
1098 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001099 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001100 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1101 NumOptimizedAccessesToStackVar++;
1102 return;
1103 }
1104 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001105
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001106 if (IsWrite)
1107 NumInstrumentedWrites++;
1108 else
1109 NumInstrumentedReads++;
1110
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001111 unsigned Granularity = 1 << Mapping.Scale;
1112 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1113 // if the data is properly aligned.
1114 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1115 TypeSize == 128) &&
1116 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001117 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
1118 Exp);
1119 instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
1120 UseCalls, Exp);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001121}
1122
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001123Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1124 Value *Addr, bool IsWrite,
1125 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001126 Value *SizeArgument,
1127 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001128 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001129 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1130 CallInst *Call = nullptr;
1131 if (SizeArgument) {
1132 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001133 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1134 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001135 else
David Blaikieff6409d2015-05-18 22:13:54 +00001136 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1137 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001138 } else {
1139 if (Exp == 0)
1140 Call =
1141 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1142 else
David Blaikieff6409d2015-05-18 22:13:54 +00001143 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1144 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001145 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001146
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001147 // We don't do Call->setDoesNotReturn() because the BB already has
1148 // UnreachableInst at the end.
1149 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001150 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001151 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001152}
1153
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001154Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001155 Value *ShadowValue,
1156 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001157 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001158 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001159 Value *LastAccessedByte =
1160 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001161 // (Addr & (Granularity - 1)) + size - 1
1162 if (TypeSize / 8 > 1)
1163 LastAccessedByte = IRB.CreateAdd(
1164 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1165 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001166 LastAccessedByte =
1167 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001168 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1169 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1170}
1171
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001172void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001173 Instruction *InsertBefore, Value *Addr,
1174 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001175 Value *SizeArgument, bool UseCalls,
1176 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001177 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001178 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001179 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1180
1181 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001182 if (Exp == 0)
1183 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1184 AddrLong);
1185 else
David Blaikieff6409d2015-05-18 22:13:54 +00001186 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1187 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001188 return;
1189 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001190
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001191 Type *ShadowTy =
1192 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001193 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1194 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1195 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001196 Value *ShadowValue =
1197 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001198
1199 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001200 size_t Granularity = 1ULL << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001201 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001202
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001203 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001204 // We use branch weights for the slow path check, to indicate that the slow
1205 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001206 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1207 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001208 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001209 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001210 IRB.SetInsertPoint(CheckTerm);
1211 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001212 if (Recover) {
1213 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1214 } else {
1215 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001216 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001217 CrashTerm = new UnreachableInst(*C, CrashBlock);
1218 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1219 ReplaceInstWithInst(CheckTerm, NewTerm);
1220 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001221 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001222 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001223 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001224
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001225 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001226 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001227 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001228}
1229
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001230// Instrument unusual size or unusual alignment.
1231// We can not do it with a single check, so we do 1-byte check for the first
1232// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1233// to report the actual access size.
1234void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1235 Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1236 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1237 IRBuilder<> IRB(I);
1238 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1239 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1240 if (UseCalls) {
1241 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001242 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1243 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001244 else
David Blaikieff6409d2015-05-18 22:13:54 +00001245 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1246 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001247 } else {
1248 Value *LastByte = IRB.CreateIntToPtr(
1249 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1250 Addr->getType());
1251 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1252 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1253 }
1254}
1255
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001256void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1257 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001258 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001259 IRBuilder<> IRB(&GlobalInit.front(),
1260 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001261
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001262 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001263 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1264 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001265
1266 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001267 for (auto &BB : GlobalInit.getBasicBlockList())
1268 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001269 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001270}
1271
1272void AddressSanitizerModule::createInitializerPoisonCalls(
1273 Module &M, GlobalValue *ModuleName) {
1274 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1275
1276 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1277 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001278 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001279 ConstantStruct *CS = cast<ConstantStruct>(OP);
1280
1281 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001282 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001283 if (F->getName() == kAsanModuleCtorName) continue;
1284 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1285 // Don't instrument CTORs that will run before asan.module_ctor.
1286 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1287 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001288 }
1289 }
1290}
1291
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001292bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001293 Type *Ty = G->getValueType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001294 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001295
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001296 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001297 if (!Ty->isSized()) return false;
1298 if (!G->hasInitializer()) return false;
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001299 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001300 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001301 // Don't handle ODR linkage types and COMDATs since other modules may be built
1302 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001303 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1304 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1305 G->getLinkage() != GlobalVariable::InternalLinkage)
1306 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001307 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001308 // Two problems with thread-locals:
1309 // - The address of the main thread's copy can't be computed at link-time.
1310 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001311 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001312 // For now, just ignore this Global if the alignment is large.
1313 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001314
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001315 if (G->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001316 StringRef Section = G->getSection();
Kuba Brecka086e34b2014-12-05 21:32:46 +00001317
Anna Zaks11904602015-06-09 00:58:08 +00001318 // Globals from llvm.metadata aren't emitted, do not instrument them.
1319 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001320 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001321 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001322
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001323 // Do not instrument function pointers to initialization and termination
1324 // routines: dynamic linker will not properly handle redzones.
1325 if (Section.startswith(".preinit_array") ||
1326 Section.startswith(".init_array") ||
1327 Section.startswith(".fini_array")) {
1328 return false;
1329 }
1330
Anna Zaks11904602015-06-09 00:58:08 +00001331 // Callbacks put into the CRT initializer/terminator sections
1332 // should not be instrumented.
1333 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1334 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1335 if (Section.startswith(".CRT")) {
1336 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1337 return false;
1338 }
1339
Kuba Brecka1001bb52014-12-05 22:19:18 +00001340 if (TargetTriple.isOSBinFormatMachO()) {
1341 StringRef ParsedSegment, ParsedSection;
1342 unsigned TAA = 0, StubSize = 0;
1343 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001344 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1345 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001346 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001347
1348 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1349 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1350 // them.
1351 if (ParsedSegment == "__OBJC" ||
1352 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1353 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1354 return false;
1355 }
1356 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1357 // Constant CFString instances are compiled in the following way:
1358 // -- the string buffer is emitted into
1359 // __TEXT,__cstring,cstring_literals
1360 // -- the constant NSConstantString structure referencing that buffer
1361 // is placed into __DATA,__cfstring
1362 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1363 // Moreover, it causes the linker to crash on OS X 10.7
1364 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1365 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1366 return false;
1367 }
1368 // The linker merges the contents of cstring_literals and removes the
1369 // trailing zeroes.
1370 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1371 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1372 return false;
1373 }
1374 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001375 }
1376
1377 return true;
1378}
1379
Ryan Govostes653f9d02016-03-28 20:28:57 +00001380// On Mach-O platforms, we emit global metadata in a separate section of the
1381// binary in order to allow the linker to properly dead strip. This is only
1382// supported on recent versions of ld64.
1383bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
Ryan Govostese51401b2016-07-05 21:53:08 +00001384 if (!ClUseMachOGlobalsSection)
1385 return false;
1386
Ryan Govostes653f9d02016-03-28 20:28:57 +00001387 if (!TargetTriple.isOSBinFormatMachO())
1388 return false;
1389
1390 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1391 return true;
1392 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001393 return true;
Ryan Govostes653f9d02016-03-28 20:28:57 +00001394 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1395 return true;
1396
1397 return false;
1398}
1399
Alexey Samsonov788381b2012-12-25 12:28:20 +00001400void AddressSanitizerModule::initializeCallbacks(Module &M) {
1401 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001402
Alexey Samsonov788381b2012-12-25 12:28:20 +00001403 // Declare our poisoning and unpoisoning functions.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001404 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001405 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001406 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001407 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001408 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001409 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001410
Alexey Samsonov788381b2012-12-25 12:28:20 +00001411 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001412 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001413 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001414 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001415 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001416 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1417 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001418 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001419
1420 // Declare the functions that find globals in a shared object and then invoke
1421 // the (un)register function on them.
1422 AsanRegisterImageGlobals = checkSanitizerInterfaceFunction(
1423 M.getOrInsertFunction(kAsanRegisterImageGlobalsName,
1424 IRB.getVoidTy(), IntptrTy, nullptr));
1425 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001426
Ryan Govostes653f9d02016-03-28 20:28:57 +00001427 AsanUnregisterImageGlobals = checkSanitizerInterfaceFunction(
1428 M.getOrInsertFunction(kAsanUnregisterImageGlobalsName,
1429 IRB.getVoidTy(), IntptrTy, nullptr));
1430 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001431}
1432
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001433// This function replaces all global variables with new variables that have
1434// trailing redzones. It also creates a function that poisons
1435// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001436bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001437 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001438
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001439 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1440
Alexey Samsonova02e6642014-05-29 18:40:48 +00001441 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001442 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001443 }
1444
1445 size_t n = GlobalsToChange.size();
1446 if (n == 0) return false;
1447
1448 // A global is described by a structure
1449 // size_t beg;
1450 // size_t size;
1451 // size_t size_with_redzone;
1452 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001453 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001454 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001455 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001456 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001457 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001458 StructType *GlobalStructTy =
1459 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001460 IntptrTy, IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001461 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001462
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001463 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001464
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001465 // We shouldn't merge same module names, as this string serves as unique
1466 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001467 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001468 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001469
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001470 auto &DL = M.getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001471 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001472 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001473 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001474
1475 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001476 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001477 // Create string holding the global name (use global name from metadata
1478 // if it's available, otherwise just write the name of global variable).
1479 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001480 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001481 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001482
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001483 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001484 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001485 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001486 // MinRZ <= RZ <= kMaxGlobalRedzone
1487 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001488 uint64_t RZ = std::max(
1489 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001490 uint64_t RightRedzoneSize = RZ;
1491 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001492 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001493 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001494 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1495
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001496 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001497 Constant *NewInitializer =
1498 ConstantStruct::get(NewTy, G->getInitializer(),
1499 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001500
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001501 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001502 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1503 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1504 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001505 GlobalVariable *NewGlobal =
1506 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1507 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001508 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001509 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001510
1511 Value *Indices2[2];
1512 Indices2[0] = IRB.getInt32(0);
1513 Indices2[1] = IRB.getInt32(0);
1514
1515 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001516 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001517 NewGlobal->takeName(G);
1518 G->eraseFromParent();
1519
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001520 Constant *SourceLoc;
1521 if (!MD.SourceLoc.empty()) {
1522 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1523 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1524 } else {
1525 SourceLoc = ConstantInt::get(IntptrTy, 0);
1526 }
1527
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001528 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
1529 GlobalValue *InstrumentedGlobal = NewGlobal;
1530
1531 bool CanUsePrivateAliases = TargetTriple.isOSBinFormatELF();
1532 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
1533 // Create local alias for NewGlobal to avoid crash on ODR between
1534 // instrumented and non-instrumented libraries.
1535 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
1536 NameForGlobal + M.getName(), NewGlobal);
1537
1538 // With local aliases, we need to provide another externally visible
1539 // symbol __odr_asan_XXX to detect ODR violation.
1540 auto *ODRIndicatorSym =
1541 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
1542 Constant::getNullValue(IRB.getInt8Ty()),
1543 kODRGenPrefix + NameForGlobal, nullptr,
1544 NewGlobal->getThreadLocalMode());
1545
1546 // Set meaningful attributes for indicator symbol.
1547 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
1548 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
1549 ODRIndicatorSym->setAlignment(1);
1550 ODRIndicator = ODRIndicatorSym;
1551 InstrumentedGlobal = GA;
1552 }
1553
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001554 Initializers[i] = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001555 GlobalStructTy,
1556 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001557 ConstantInt::get(IntptrTy, SizeInBytes),
1558 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1559 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001560 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001561 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
1562 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy), nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001563
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001564 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001565
Kostya Serebryany20343352012-10-17 13:40:06 +00001566 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001567 }
1568
Ryan Govostes653f9d02016-03-28 20:28:57 +00001569
1570 GlobalVariable *AllGlobals = nullptr;
1571 GlobalVariable *RegisteredFlag = nullptr;
1572
1573 // On recent Mach-O platforms, we emit the global metadata in a way that
1574 // allows the linker to properly strip dead globals.
1575 if (ShouldUseMachOGlobalsSection()) {
1576 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1577 // to look up the loaded image that contains it. Second, we can store in it
1578 // whether registration has already occurred, to prevent duplicate
1579 // registration.
1580 //
1581 // Common linkage allows us to coalesce needles defined in each object
1582 // file so that there's only one per shared library.
1583 RegisteredFlag = new GlobalVariable(
1584 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1585 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1586
1587 // We also emit a structure which binds the liveness of the global
1588 // variable to the metadata struct.
1589 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy, nullptr);
1590
1591 for (size_t i = 0; i < n; i++) {
1592 GlobalVariable *Metadata = new GlobalVariable(
1593 M, GlobalStructTy, false, GlobalVariable::InternalLinkage,
1594 Initializers[i], "");
1595 Metadata->setSection("__DATA,__asan_globals,regular");
1596 Metadata->setAlignment(1); // don't leave padding in between
1597
1598 auto LivenessBinder = ConstantStruct::get(LivenessTy,
1599 Initializers[i]->getAggregateElement(0u),
1600 ConstantExpr::getPointerCast(Metadata, IntptrTy),
1601 nullptr);
1602 GlobalVariable *Liveness = new GlobalVariable(
1603 M, LivenessTy, false, GlobalVariable::InternalLinkage,
1604 LivenessBinder, "");
1605 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1606 }
1607 } else {
1608 // On all other platfoms, we just emit an array of global metadata
1609 // structures.
1610 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1611 AllGlobals = new GlobalVariable(
1612 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1613 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1614 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001615
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001616 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001617 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001618 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001619
Ryan Govostes653f9d02016-03-28 20:28:57 +00001620 // Create a call to register the globals with the runtime.
1621 if (ShouldUseMachOGlobalsSection()) {
1622 IRB.CreateCall(AsanRegisterImageGlobals,
1623 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1624 } else {
1625 IRB.CreateCall(AsanRegisterGlobals,
1626 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1627 ConstantInt::get(IntptrTy, n)});
1628 }
1629
1630 // We also need to unregister globals at the end, e.g., when a shared library
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001631 // gets closed.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001632 Function *AsanDtorFunction =
1633 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1634 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001635 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1636 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001637
1638 if (ShouldUseMachOGlobalsSection()) {
1639 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1640 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1641 } else {
1642 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1643 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1644 ConstantInt::get(IntptrTy, n)});
1645 }
1646
Alexey Samsonov1f647502014-05-29 01:10:14 +00001647 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001648
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001649 DEBUG(dbgs() << M);
1650 return true;
1651}
1652
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001653bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001654 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001655 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001656 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001657 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001658 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001659 initializeCallbacks(M);
1660
1661 bool Changed = false;
1662
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001663 // TODO(glider): temporarily disabled globals instrumentation for KASan.
1664 if (ClGlobals && !CompileKernel) {
1665 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1666 assert(CtorFunc);
1667 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1668 Changed |= InstrumentGlobals(IRB, M);
1669 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001670
1671 return Changed;
1672}
1673
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001674void AddressSanitizer::initializeCallbacks(Module &M) {
1675 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001676 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001677 // IsWrite, TypeSize and Exp are encoded in the function name.
1678 for (int Exp = 0; Exp < 2; Exp++) {
1679 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1680 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1681 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001682 const std::string SuffixStr = CompileKernel ? "N" : "_n";
Yury Gribovd7731982015-11-11 10:36:49 +00001683 const std::string EndingStr = Recover ? "_noabort" : "";
Craig Toppere3dcce92015-08-01 22:20:21 +00001684 Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001685 AsanErrorCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001686 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001687 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001688 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1689 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001690 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001691 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001692 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1693 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1694 AccessSizeIndex++) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001695 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001696 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001697 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001698 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001699 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001700 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001701 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001702 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1703 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001704 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001705 }
1706 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00001707
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001708 const std::string MemIntrinCallbackPrefix =
1709 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001710 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001711 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001712 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001713 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001714 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001715 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001716 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001717 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001718 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001719
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001720 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001721 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001722
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001723 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001724 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001725 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001726 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001727 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1728 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1729 StringRef(""), StringRef(""),
1730 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001731}
1732
1733// virtual
1734bool AddressSanitizer::doInitialization(Module &M) {
1735 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001736
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001737 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001738
1739 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001740 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001741 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001742 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001743
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001744 if (!CompileKernel) {
1745 std::tie(AsanCtorFunction, AsanInitFunction) =
Kuba Brecka45dbffd2015-07-23 10:54:06 +00001746 createSanitizerCtorAndInitFunctions(
1747 M, kAsanModuleCtorName, kAsanInitName,
1748 /*InitArgTypes=*/{}, /*InitArgs=*/{}, kAsanVersionCheckName);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001749 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1750 }
1751 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001752 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001753}
1754
Keno Fischere03fae42015-12-05 14:42:34 +00001755bool AddressSanitizer::doFinalization(Module &M) {
1756 GlobalsMD.reset();
1757 return false;
1758}
1759
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001760bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1761 // For each NSObject descendant having a +load method, this method is invoked
1762 // by the ObjC runtime before any of the static constructors is called.
1763 // Therefore we need to instrument such methods with a call to __asan_init
1764 // at the beginning in order to initialize our runtime before any access to
1765 // the shadow memory.
1766 // We cannot just ignore these methods, because they may call other
1767 // instrumented functions.
1768 if (F.getName().find(" load]") != std::string::npos) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001769 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00001770 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001771 return true;
1772 }
1773 return false;
1774}
1775
Reid Kleckner2f907552015-07-21 17:40:14 +00001776void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
1777 // Find the one possible call to llvm.localescape and pre-mark allocas passed
1778 // to it as uninteresting. This assumes we haven't started processing allocas
1779 // yet. This check is done up front because iterating the use list in
1780 // isInterestingAlloca would be algorithmically slower.
1781 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
1782
1783 // Try to get the declaration of llvm.localescape. If it's not in the module,
1784 // we can exit early.
1785 if (!F.getParent()->getFunction("llvm.localescape")) return;
1786
1787 // Look for a call to llvm.localescape call in the entry block. It can't be in
1788 // any other block.
1789 for (Instruction &I : F.getEntryBlock()) {
1790 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
1791 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
1792 // We found a call. Mark all the allocas passed in as uninteresting.
1793 for (Value *Arg : II->arg_operands()) {
1794 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
1795 assert(AI && AI->isStaticAlloca() &&
1796 "non-static alloca arg to localescape");
1797 ProcessedAllocas[AI] = false;
1798 }
1799 break;
1800 }
1801 }
1802}
1803
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001804bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001805 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001806 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001807 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001808 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001809
Yury Gribov3ae427d2014-12-01 08:47:58 +00001810 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1811
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001812 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001813 maybeInsertAsanInitAtFunctionEntry(F);
1814
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001815 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001816
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001817 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001818
Reid Kleckner2f907552015-07-21 17:40:14 +00001819 FunctionStateRAII CleanupObj(this);
1820
1821 // We can't instrument allocas used with llvm.localescape. Only static allocas
1822 // can be passed to that intrinsic.
1823 markEscapedLocalAllocas(F);
1824
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001825 // We want to instrument every address only once per basic block (unless there
1826 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001827 SmallSet<Value *, 16> TempsToInstrument;
1828 SmallVector<Instruction *, 16> ToInstrument;
1829 SmallVector<Instruction *, 8> NoReturnCalls;
1830 SmallVector<BasicBlock *, 16> AllBlocks;
1831 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001832 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001833 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001834 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001835 uint64_t TypeSize;
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00001836 const TargetLibraryInfo *TLI =
1837 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001838
1839 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001840 for (auto &BB : F) {
1841 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001842 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001843 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001844 for (auto &Inst : BB) {
1845 if (LooksLikeCodeInBug11395(&Inst)) return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001846 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1847 &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001848 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001849 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001850 continue; // We've seen this temp in the current BB.
1851 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001852 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001853 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1854 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001855 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001856 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001857 // ok, take it.
1858 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001859 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001860 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001861 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001862 // A call inside BB.
1863 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001864 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001865 }
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00001866 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
1867 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001868 continue;
1869 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001870 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001871 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001872 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001873 }
1874 }
1875
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001876 bool UseCalls =
1877 CompileKernel ||
1878 (ClInstrumentationWithCallsThreshold >= 0 &&
1879 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001880 const DataLayout &DL = F.getParent()->getDataLayout();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001881 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1882 /*RoundToAlign=*/true);
1883
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001884 // Instrument.
1885 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001886 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001887 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1888 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001889 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001890 instrumentMop(ObjSizeVis, Inst, UseCalls,
1891 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001892 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001893 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001894 }
1895 NumInstrumented++;
1896 }
1897
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001898 FunctionStackPoisoner FSP(F, *this);
1899 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001900
1901 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1902 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001903 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001904 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00001905 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001906 }
1907
Alexey Samsonova02e6642014-05-29 18:40:48 +00001908 for (auto Inst : PointerComparisonsOrSubtracts) {
1909 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001910 NumInstrumented++;
1911 }
1912
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001913 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001914
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001915 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1916
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001917 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001918}
1919
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001920// Workaround for bug 11395: we don't want to instrument stack in functions
1921// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1922// FIXME: remove once the bug 11395 is fixed.
1923bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1924 if (LongSize != 32) return false;
1925 CallInst *CI = dyn_cast<CallInst>(I);
1926 if (!CI || !CI->isInlineAsm()) return false;
1927 if (CI->getNumArgOperands() <= 5) return false;
1928 // We have inline assembly with quite a few arguments.
1929 return true;
1930}
1931
1932void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1933 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001934 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1935 std::string Suffix = itostr(i);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001936 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1937 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1938 IntptrTy, nullptr));
1939 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001940 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1941 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001942 }
Vitaly Buka79b75d32016-06-09 23:05:35 +00001943 if (ASan.UseAfterScope) {
1944 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
1945 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1946 IntptrTy, IntptrTy, nullptr));
1947 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
1948 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1949 IntptrTy, IntptrTy, nullptr));
1950 }
1951
Vitaly Buka3455b9b2016-08-20 18:34:39 +00001952 if (ClExperimentalPoisoning) {
1953 for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
1954 std::ostringstream Name;
1955 Name << kAsanSetShadowPrefix;
1956 Name << std::setw(2) << std::setfill('0') << std::hex << Val;
1957 AsanSetShadowFunc[Val] =
1958 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1959 Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1960 }
1961 }
1962
Yury Gribov98b18592015-05-28 07:51:49 +00001963 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1964 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1965 AsanAllocasUnpoisonFunc =
1966 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1967 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001968}
1969
Vitaly Buka793913c2016-08-29 18:17:21 +00001970void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
1971 ArrayRef<uint8_t> ShadowBytes,
1972 size_t Begin, size_t End,
1973 IRBuilder<> &IRB,
1974 Value *ShadowBase) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00001975 if (Begin >= End)
1976 return;
Vitaly Buka186280d2016-08-20 18:34:36 +00001977
1978 const size_t LargestStoreSizeInBytes =
1979 std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
1980
1981 const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
1982
1983 // Poison given range in shadow using larges store size with out leading and
Vitaly Buka793913c2016-08-29 18:17:21 +00001984 // trailing zeros in ShadowMask. Zeros never change, so they need neither
1985 // poisoning nor up-poisoning. Still we don't mind if some of them get into a
1986 // middle of a store.
Vitaly Buka1f9e1352016-08-20 20:23:50 +00001987 for (size_t i = Begin; i < End;) {
Vitaly Buka793913c2016-08-29 18:17:21 +00001988 if (!ShadowMask[i]) {
1989 assert(!ShadowBytes[i]);
Vitaly Buka186280d2016-08-20 18:34:36 +00001990 ++i;
1991 continue;
1992 }
1993
1994 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
1995 // Fit store size into the range.
1996 while (StoreSizeInBytes > End - i)
1997 StoreSizeInBytes /= 2;
1998
1999 // Minimize store size by trimming trailing zeros.
Vitaly Buka793913c2016-08-29 18:17:21 +00002000 for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
Vitaly Buka186280d2016-08-20 18:34:36 +00002001 while (j <= StoreSizeInBytes / 2)
2002 StoreSizeInBytes /= 2;
2003 }
2004
2005 uint64_t Val = 0;
Vitaly Buka793913c2016-08-29 18:17:21 +00002006 for (size_t j = 0; j < StoreSizeInBytes; j++) {
2007 if (IsLittleEndian)
2008 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2009 else
2010 Val = (Val << 8) | ShadowBytes[i + j];
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002011 }
Vitaly Buka186280d2016-08-20 18:34:36 +00002012
2013 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2014 Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
Vitaly Buka0672a272016-08-22 04:16:14 +00002015 IRB.CreateAlignedStore(
2016 Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
Vitaly Buka186280d2016-08-20 18:34:36 +00002017
2018 i += StoreSizeInBytes;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002019 }
2020}
2021
Vitaly Buka793913c2016-08-29 18:17:21 +00002022void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2023 ArrayRef<uint8_t> ShadowBytes,
2024 IRBuilder<> &IRB, Value *ShadowBase) {
2025 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2026}
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002027
Vitaly Buka793913c2016-08-29 18:17:21 +00002028void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2029 ArrayRef<uint8_t> ShadowBytes,
2030 size_t Begin, size_t End,
2031 IRBuilder<> &IRB, Value *ShadowBase) {
2032 assert(ShadowMask.size() == ShadowBytes.size());
2033 size_t Done = Begin;
2034 for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2035 if (!ShadowMask[i]) {
2036 assert(!ShadowBytes[i]);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002037 continue;
Vitaly Buka793913c2016-08-29 18:17:21 +00002038 }
2039 uint8_t Val = ShadowBytes[i];
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002040 if (!AsanSetShadowFunc[Val])
2041 continue;
2042
2043 // Skip same values.
Vitaly Buka793913c2016-08-29 18:17:21 +00002044 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002045 }
2046
2047 if (j - i >= ClMaxInlinePoisoningSize) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002048 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002049 IRB.CreateCall(AsanSetShadowFunc[Val],
2050 {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2051 ConstantInt::get(IntptrTy, j - i)});
2052 Done = j;
2053 }
2054 }
2055
Vitaly Buka793913c2016-08-29 18:17:21 +00002056 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002057}
2058
Kostya Serebryany6805de52013-09-10 13:16:56 +00002059// Fake stack allocator (asan_fake_stack.h) has 11 size classes
2060// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2061static int StackMallocSizeClass(uint64_t LocalStackSize) {
2062 assert(LocalStackSize <= kMaxStackMallocSize);
2063 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002064 for (int i = 0;; i++, MaxSize *= 2)
2065 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00002066 llvm_unreachable("impossible LocalStackSize");
2067}
2068
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002069PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2070 Value *ValueIfTrue,
2071 Instruction *ThenTerm,
2072 Value *ValueIfFalse) {
2073 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2074 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2075 PHI->addIncoming(ValueIfFalse, CondBlock);
2076 BasicBlock *ThenBlock = ThenTerm->getParent();
2077 PHI->addIncoming(ValueIfTrue, ThenBlock);
2078 return PHI;
2079}
2080
2081Value *FunctionStackPoisoner::createAllocaForLayout(
2082 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2083 AllocaInst *Alloca;
2084 if (Dynamic) {
2085 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2086 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2087 "MyAlloca");
2088 } else {
2089 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2090 nullptr, "MyAlloca");
2091 assert(Alloca->isStaticAlloca());
2092 }
2093 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2094 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2095 Alloca->setAlignment(FrameAlignment);
2096 return IRB.CreatePointerCast(Alloca, IntptrTy);
2097}
2098
Yury Gribov98b18592015-05-28 07:51:49 +00002099void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2100 BasicBlock &FirstBB = *F.begin();
2101 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2102 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2103 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2104 DynamicAllocaLayout->setAlignment(32);
2105}
2106
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002107void FunctionStackPoisoner::processDynamicAllocas() {
2108 if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2109 assert(DynamicAllocaPoisonCallVec.empty());
2110 return;
2111 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002112
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002113 // Insert poison calls for lifetime intrinsics for dynamic allocas.
2114 for (const auto &APC : DynamicAllocaPoisonCallVec) {
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002115 assert(APC.InsBefore);
2116 assert(APC.AI);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002117 assert(ASan.isInterestingAlloca(*APC.AI));
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002118 assert(!APC.AI->isStaticAlloca());
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002119
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002120 IRBuilder<> IRB(APC.InsBefore);
2121 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002122 // Dynamic allocas will be unpoisoned unconditionally below in
2123 // unpoisonDynamicAllocas.
2124 // Flag that we need unpoison static allocas.
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002125 }
2126
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002127 // Handle dynamic allocas.
2128 createDynamicAllocasInitStorage();
2129 for (auto &AI : DynamicAllocaVec)
2130 handleDynamicAllocaCall(AI);
2131 unpoisonDynamicAllocas();
2132}
Yury Gribov98b18592015-05-28 07:51:49 +00002133
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002134void FunctionStackPoisoner::processStaticAllocas() {
2135 if (AllocaVec.empty()) {
2136 assert(StaticAllocaPoisonCallVec.empty());
2137 return;
Kuba Breckaf5875d32015-02-24 09:47:05 +00002138 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002139
Kostya Serebryany6805de52013-09-10 13:16:56 +00002140 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002141 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00002142 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002143 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002144
2145 Instruction *InsBefore = AllocaVec[0];
2146 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002147 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002148
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002149 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2150 // debug info is broken, because only entry-block allocas are treated as
2151 // regular stack slots.
2152 auto InsBeforeB = InsBefore->getParent();
2153 assert(InsBeforeB == &F.getEntryBlock());
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002154 for (BasicBlock::iterator I(InsBefore); I != InsBeforeB->end(); ++I)
2155 if (auto *AI = dyn_cast<AllocaInst>(I))
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002156 if (NonInstrumentedStaticAllocaVec.count(AI) > 0)
2157 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00002158
Reid Kleckner2f907552015-07-21 17:40:14 +00002159 // If we have a call to llvm.localescape, keep it in the entry block.
2160 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2161
Vitaly Buka793913c2016-08-29 18:17:21 +00002162 // Find static allocas with lifetime analysis.
2163 DenseMap<const AllocaInst *, const ASanStackVariableDescription *>
2164 AllocaToSVDMap;
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002165 for (const auto &APC : StaticAllocaPoisonCallVec) {
2166 assert(APC.InsBefore);
2167 assert(APC.AI);
2168 assert(ASan.isInterestingAlloca(*APC.AI));
2169 assert(APC.AI->isStaticAlloca());
2170
Vitaly Buka793913c2016-08-29 18:17:21 +00002171 if (ClExperimentalPoisoning) {
2172 AllocaToSVDMap[APC.AI] = nullptr;
2173 } else {
2174 IRBuilder<> IRB(APC.InsBefore);
2175 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
2176 }
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002177 }
2178
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002179 SmallVector<ASanStackVariableDescription, 16> SVD;
2180 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00002181 for (AllocaInst *AI : AllocaVec) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002182 size_t UseAfterScopePoisonSize =
2183 AllocaToSVDMap.find(AI) != AllocaToSVDMap.end()
2184 ? ASan.getAllocaSizeInBytes(*AI)
2185 : 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002186 ASanStackVariableDescription D = {AI->getName().data(),
Vitaly Buka21a9e572016-07-28 22:50:50 +00002187 ASan.getAllocaSizeInBytes(*AI),
Vitaly Buka793913c2016-08-29 18:17:21 +00002188 UseAfterScopePoisonSize,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002189 AI->getAlignment(),
2190 AI,
2191 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002192 SVD.push_back(D);
2193 }
2194 // Minimal header size (left redzone) is 4 pointers,
2195 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2196 size_t MinHeaderSize = ASan.LongSize / 2;
Vitaly Bukadb331d82016-08-29 17:41:29 +00002197 const ASanStackFrameLayout &L =
2198 ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize);
Vitaly Buka793913c2016-08-29 18:17:21 +00002199
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002200 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
2201 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002202 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2203 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00002204 bool DoDynamicAlloca = ClDynamicAllocaStack;
2205 // Don't do dynamic alloca or stack malloc if:
2206 // 1) There is inline asm: too often it makes assumptions on which registers
2207 // are available.
2208 // 2) There is a returns_twice call (typically setjmp), which is
2209 // optimization-hostile, and doesn't play well with introduced indirect
2210 // register-relative calculation of local variable addresses.
2211 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2212 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002213
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002214 Value *StaticAlloca =
2215 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2216
2217 Value *FakeStack;
2218 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002219
2220 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002221 // void *FakeStack = __asan_option_detect_stack_use_after_return
2222 // ? __asan_stack_malloc_N(LocalStackSize)
2223 // : nullptr;
2224 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002225 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2226 kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2227 Value *UseAfterReturnIsEnabled =
2228 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002229 Constant::getNullValue(IRB.getInt32Ty()));
2230 Instruction *Term =
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002231 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002232 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002233 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002234 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2235 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2236 Value *FakeStackValue =
2237 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2238 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002239 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002240 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002241 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002242 ConstantInt::get(IntptrTy, 0));
2243
2244 Value *NoFakeStack =
2245 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2246 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2247 IRBIf.SetInsertPoint(Term);
2248 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2249 Value *AllocaValue =
2250 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2251 IRB.SetInsertPoint(InsBefore);
2252 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2253 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2254 } else {
2255 // void *FakeStack = nullptr;
2256 // void *LocalStackBase = alloca(LocalStackSize);
2257 FakeStack = ConstantInt::get(IntptrTy, 0);
2258 LocalStackBase =
2259 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002260 }
2261
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002262 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002263 for (const auto &Desc : SVD) {
2264 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00002265 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00002266 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002267 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00002268 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002269 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002270 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002271
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002272 // The left-most redzone has enough space for at least 4 pointers.
2273 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002274 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2275 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2276 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002277 // Write the frame description constant to redzone[1].
2278 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002279 IRB.CreateAdd(LocalStackBase,
2280 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2281 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00002282 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00002283 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002284 /*AllowMerging*/ true);
2285 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002286 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002287 // Write the PC to redzone[2].
2288 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002289 IRB.CreateAdd(LocalStackBase,
2290 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2291 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002292 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002293
Vitaly Buka793913c2016-08-29 18:17:21 +00002294 const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
2295
2296 // Poison the stack red zones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002297 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Vitaly Buka793913c2016-08-29 18:17:21 +00002298 // As mask we must use most poisoned case: red zones and after scope.
2299 // As bytes we can use either the same or just red zones only.
2300 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
2301
2302 if (ClExperimentalPoisoning && !StaticAllocaPoisonCallVec.empty()) {
2303 // Complete AllocaToSVDMap
2304 for (const auto &Desc : SVD) {
2305 auto It = AllocaToSVDMap.find(Desc.AI);
2306 if (It != AllocaToSVDMap.end()) {
2307 It->second = &Desc;
2308 }
2309 }
2310
2311 const auto &ShadowInScope = GetShadowBytes(SVD, L);
2312
2313 // Poison static allocas near lifetime intrinsics.
2314 for (const auto &APC : StaticAllocaPoisonCallVec) {
2315 // Must be already set.
2316 assert(AllocaToSVDMap[APC.AI]);
2317 const auto &Desc = *AllocaToSVDMap[APC.AI];
2318 assert(Desc.Offset % L.Granularity == 0);
2319 size_t Begin = Desc.Offset / L.Granularity;
2320 size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
2321
2322 IRBuilder<> IRB(APC.InsBefore);
2323 copyToShadow(ShadowAfterScope,
2324 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
2325 IRB, ShadowBase);
2326 }
2327 }
2328
2329 SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002330
Vitaly Buka79b75d32016-06-09 23:05:35 +00002331 auto UnpoisonStack = [&](IRBuilder<> &IRB) {
Vitaly Buka1ce73ef2016-08-16 16:24:10 +00002332 // Do this always as poisonAlloca can be disabled with
2333 // detect_stack_use_after_scope=0.
Vitaly Buka793913c2016-08-29 18:17:21 +00002334 copyToShadow(ShadowAfterScope, ShadowClean, IRB, ShadowBase);
2335 if (!ClExperimentalPoisoning && !StaticAllocaPoisonCallVec.empty()) {
Vitaly Buka79b75d32016-06-09 23:05:35 +00002336 // If we poisoned some allocas in llvm.lifetime analysis,
2337 // unpoison whole stack frame now.
2338 poisonAlloca(LocalStackBase, LocalStackSize, IRB, false);
Vitaly Buka79b75d32016-06-09 23:05:35 +00002339 }
2340 };
2341
Vitaly Buka793913c2016-08-29 18:17:21 +00002342 SmallVector<uint8_t, 64> ShadowAfterReturn;
Vitaly Buka186280d2016-08-20 18:34:36 +00002343
Kostya Serebryany530e2072013-12-23 14:15:08 +00002344 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002345 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002346 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002347 // Mark the current frame as retired.
2348 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2349 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002350 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00002351 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002352 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00002353 // // In use-after-return mode, poison the whole stack frame.
2354 // if StackMallocIdx <= 4
2355 // // For small sizes inline the whole thing:
2356 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002357 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00002358 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002359 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00002360 // else
2361 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002362 Value *Cmp =
2363 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00002364 TerminatorInst *ThenTerm, *ElseTerm;
2365 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2366
2367 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002368 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002369 int ClassSize = kMinStackMallocSize << StackMallocIdx;
Vitaly Buka793913c2016-08-29 18:17:21 +00002370 ShadowAfterReturn.resize(ClassSize / L.Granularity,
2371 kAsanStackUseAfterReturnMagic);
2372 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
2373 ShadowBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002374 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002375 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002376 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2377 Value *SavedFlagPtr = IRBPoison.CreateLoad(
2378 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2379 IRBPoison.CreateStore(
2380 Constant::getNullValue(IRBPoison.getInt8Ty()),
2381 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2382 } else {
2383 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00002384 IRBPoison.CreateCall(
2385 AsanStackFreeFunc[StackMallocIdx],
2386 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002387 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00002388
2389 IRBuilder<> IRBElse(ElseTerm);
Vitaly Buka79b75d32016-06-09 23:05:35 +00002390 UnpoisonStack(IRBElse);
Kostya Serebryany530e2072013-12-23 14:15:08 +00002391 } else {
Vitaly Buka79b75d32016-06-09 23:05:35 +00002392 UnpoisonStack(IRBRet);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002393 }
2394 }
2395
Kostya Serebryany09959942012-10-19 06:20:53 +00002396 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002397 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002398}
Alexey Samsonov261177a2012-12-04 01:34:23 +00002399
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002400void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00002401 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00002402 // For now just insert the call to ASan runtime.
2403 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2404 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002405 IRB.CreateCall(
2406 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2407 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00002408}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002409
2410// Handling llvm.lifetime intrinsics for a given %alloca:
2411// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2412// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2413// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2414// could be poisoned by previous llvm.lifetime.end instruction, as the
2415// variable may go in and out of scope several times, e.g. in loops).
2416// (3) if we poisoned at least one %alloca in a function,
2417// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002418
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002419AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2420 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
2421 // We're intested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00002422 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002423 // See if we've already calculated (or started to calculate) alloca for a
2424 // given value.
2425 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002426 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002427 // Store 0 while we're calculating alloca for value V to avoid
2428 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00002429 AllocaForValue[V] = nullptr;
2430 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002431 if (CastInst *CI = dyn_cast<CastInst>(V))
2432 Res = findAllocaForValue(CI->getOperand(0));
2433 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00002434 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002435 // Allow self-referencing phi-nodes.
2436 if (IncValue == PN) continue;
2437 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2438 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00002439 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2440 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002441 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002442 }
Vitaly Buka53054a72016-07-22 00:56:17 +00002443 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
2444 Res = findAllocaForValue(EP->getPointerOperand());
2445 } else {
2446 DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V << "\n");
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002447 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002448 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002449 return Res;
2450}
Yury Gribov55441bb2014-11-21 10:29:50 +00002451
Yury Gribov98b18592015-05-28 07:51:49 +00002452void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00002453 IRBuilder<> IRB(AI);
2454
Yury Gribov55441bb2014-11-21 10:29:50 +00002455 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2456 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2457
2458 Value *Zero = Constant::getNullValue(IntptrTy);
2459 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2460 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00002461
2462 // Since we need to extend alloca with additional memory to locate
2463 // redzones, and OldSize is number of allocated blocks with
2464 // ElementSize size, get allocated memory size in bytes by
2465 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00002466 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002467 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00002468 Value *OldSize =
2469 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2470 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00002471
2472 // PartialSize = OldSize % 32
2473 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2474
2475 // Misalign = kAllocaRzSize - PartialSize;
2476 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2477
2478 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2479 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2480 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2481
2482 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2483 // Align is added to locate left redzone, PartialPadding for possible
2484 // partial redzone and kAllocaRzSize for right redzone respectively.
2485 Value *AdditionalChunkSize = IRB.CreateAdd(
2486 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2487
2488 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2489
2490 // Insert new alloca with new NewSize and Align params.
2491 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2492 NewAlloca->setAlignment(Align);
2493
2494 // NewAddress = Address + Align
2495 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2496 ConstantInt::get(IntptrTy, Align));
2497
Yury Gribov98b18592015-05-28 07:51:49 +00002498 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00002499 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00002500
2501 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2502 // for unpoisoning stuff.
2503 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2504
Yury Gribov55441bb2014-11-21 10:29:50 +00002505 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2506
Yury Gribov98b18592015-05-28 07:51:49 +00002507 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00002508 AI->replaceAllUsesWith(NewAddressPtr);
2509
Yury Gribov98b18592015-05-28 07:51:49 +00002510 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00002511 AI->eraseFromParent();
2512}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002513
2514// isSafeAccess returns true if Addr is always inbounds with respect to its
2515// base object. For example, it is a field access or an array access with
2516// constant inbounds index.
2517bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2518 Value *Addr, uint64_t TypeSize) const {
2519 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2520 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00002521 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002522 int64_t Offset = SizeOffset.second.getSExtValue();
2523 // Three checks are required to ensure safety:
2524 // . Offset >= 0 (since the offset is given from the base ptr)
2525 // . Size >= Offset (unsigned)
2526 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00002527 return Offset >= 0 && Size >= uint64_t(Offset) &&
2528 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002529}