blob: f08672a58579edfc7ba2d9ee7ada42e58367f419 [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;
Etienne Bergeron0ca05682016-09-30 17:46:32 +000070static const uint64_t kDynamicShadowSentinel = ~(uint64_t)0;
Anna Zaks3b50e702016-02-02 22:05:07 +000071static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
Anna Zaks3b50e702016-02-02 22:05:07 +000072static 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 Bergeron0ca05682016-09-30 17:46:32 +000084// The shadow memory space is dynamically allocated.
85static const uint64_t kWindowsShadowOffset64 = kDynamicShadowSentinel;
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
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000128static const char *const kAsanShadowMemoryDynamicAddress =
129 "__asan_shadow_memory_dynamic_address";
130
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000131static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
132static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
Yury Gribov98b18592015-05-28 07:51:49 +0000133
Kostya Serebryany874dae62012-07-16 16:15:40 +0000134// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
135static const size_t kNumberOfAccessSizes = 5;
136
Yury Gribov55441bb2014-11-21 10:29:50 +0000137static const unsigned kAllocaRzSize = 32;
Yury Gribov55441bb2014-11-21 10:29:50 +0000138
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000139// Command-line flags.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000140static cl::opt<bool> ClEnableKasan(
141 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
142 cl::Hidden, cl::init(false));
Yury Gribovd7731982015-11-11 10:36:49 +0000143static cl::opt<bool> ClRecover(
144 "asan-recover",
145 cl::desc("Enable recovery mode (continue-after-error)."),
146 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000147
148// This flag may need to be replaced with -f[no-]asan-reads.
149static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000150 cl::desc("instrument read instructions"),
151 cl::Hidden, cl::init(true));
152static cl::opt<bool> ClInstrumentWrites(
153 "asan-instrument-writes", cl::desc("instrument write instructions"),
154 cl::Hidden, cl::init(true));
155static cl::opt<bool> ClInstrumentAtomics(
156 "asan-instrument-atomics",
157 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
158 cl::init(true));
159static cl::opt<bool> ClAlwaysSlowPath(
160 "asan-always-slow-path",
161 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
162 cl::init(false));
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000163static cl::opt<bool> ClForceDynamicShadow(
164 "asan-force-dynamic-shadow",
165 cl::desc("Load shadow address into a local variable for each function"),
166 cl::Hidden, cl::init(false));
167
Kostya Serebryany874dae62012-07-16 16:15:40 +0000168// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000169// in any given BB. Normally, this should be set to unlimited (INT_MAX),
170// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
171// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000172static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
173 "asan-max-ins-per-bb", cl::init(10000),
174 cl::desc("maximal number of instructions to instrument in any given BB"),
175 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000176// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000177static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
178 cl::Hidden, cl::init(true));
Vitaly Buka1f9e1352016-08-20 20:23:50 +0000179static cl::opt<uint32_t> ClMaxInlinePoisoningSize(
180 "asan-max-inline-poisoning-size",
181 cl::desc(
182 "Inline shadow poisoning for blocks up to the given size in bytes."),
183 cl::Hidden, cl::init(64));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000184static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Mike Aizatsky243b71f2016-04-21 22:00:13 +0000185 cl::desc("Check stack-use-after-return"),
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000186 cl::Hidden, cl::init(true));
Kostya Serebryanya83bfea2016-04-20 20:02:58 +0000187static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
188 cl::desc("Check stack-use-after-scope"),
189 cl::Hidden, cl::init(false));
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000190static cl::opt<bool> ClExperimentalPoisoning(
191 "asan-experimental-poisoning",
192 cl::desc("Enable experimental red zones and scope poisoning"), cl::Hidden,
Vitaly Buka3c4f6bf2016-08-29 19:28:34 +0000193 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000194// This flag may need to be replaced with -f[no]asan-globals.
195static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000196 cl::desc("Handle global objects"), cl::Hidden,
197 cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000198static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000199 cl::desc("Handle C++ initializer order"),
200 cl::Hidden, cl::init(true));
201static cl::opt<bool> ClInvalidPointerPairs(
202 "asan-detect-invalid-pointer-pair",
203 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
204 cl::init(false));
205static cl::opt<unsigned> ClRealignStack(
206 "asan-realign-stack",
207 cl::desc("Realign stack to the value of this flag (power of two)"),
208 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000209static cl::opt<int> ClInstrumentationWithCallsThreshold(
210 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000211 cl::desc(
212 "If the function being instrumented contains more than "
213 "this number of memory accesses, use callbacks instead of "
214 "inline checks (-1 means never use callbacks)."),
215 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000216static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000217 "asan-memory-access-callback-prefix",
218 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
219 cl::init("__asan_"));
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000220static cl::opt<bool>
221 ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
222 cl::desc("instrument dynamic allocas"),
223 cl::Hidden, cl::init(true));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000224static cl::opt<bool> ClSkipPromotableAllocas(
225 "asan-skip-promotable-allocas",
226 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
227 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000228
229// These flags allow to change the shadow mapping.
230// The shadow mapping looks like
Ryan Govostes3f37df02016-05-06 10:25:22 +0000231// Shadow = (Mem >> scale) + offset
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000232static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000233 cl::desc("scale of asan shadow mapping"),
234 cl::Hidden, cl::init(0));
Ryan Govostes6194ae62016-05-06 11:22:11 +0000235static cl::opt<unsigned long long> ClMappingOffset(
236 "asan-mapping-offset",
237 cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden,
238 cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000239
240// Optimization flags. Not user visible, used mostly for testing
241// and benchmarking the tool.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000242static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
243 cl::Hidden, cl::init(true));
244static cl::opt<bool> ClOptSameTemp(
245 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
246 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000247static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000248 cl::desc("Don't instrument scalar globals"),
249 cl::Hidden, cl::init(true));
250static cl::opt<bool> ClOptStack(
251 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
252 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000253
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000254static cl::opt<bool> ClDynamicAllocaStack(
255 "asan-stack-dynamic-alloca",
256 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000257 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000258
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000259static cl::opt<uint32_t> ClForceExperiment(
260 "asan-force-experiment",
261 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
262 cl::init(0));
263
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000264static cl::opt<bool>
265 ClUsePrivateAliasForGlobals("asan-use-private-alias",
266 cl::desc("Use private aliases for global"
267 " variables"),
268 cl::Hidden, cl::init(false));
269
Ryan Govostese51401b2016-07-05 21:53:08 +0000270static cl::opt<bool>
271 ClUseMachOGlobalsSection("asan-globals-live-support",
272 cl::desc("Use linker features to support dead "
273 "code stripping of globals "
274 "(Mach-O only)"),
275 cl::Hidden, cl::init(false));
276
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000277// Debug flags.
278static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
279 cl::init(0));
280static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
281 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000282static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
283 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000284static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
285 cl::Hidden, cl::init(-1));
Etienne Bergeron7f0e3152016-09-22 14:57:24 +0000286static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000287 cl::Hidden, cl::init(-1));
288
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000289STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
290STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000291STATISTIC(NumOptimizedAccessesToGlobalVar,
292 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000293STATISTIC(NumOptimizedAccessesToStackVar,
294 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000295
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000296namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000297/// Frontend-provided metadata for source location.
298struct LocationMetadata {
299 StringRef Filename;
300 int LineNo;
301 int ColumnNo;
302
303 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
304
305 bool empty() const { return Filename.empty(); }
306
307 void parse(MDNode *MDN) {
308 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000309 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
310 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000311 LineNo =
312 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
313 ColumnNo =
314 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000315 }
316};
317
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000318/// Frontend-provided metadata for global variables.
319class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000320 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000321 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000322 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000323 LocationMetadata SourceLoc;
324 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000325 bool IsDynInit;
326 bool IsBlacklisted;
327 };
328
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000329 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000330
Keno Fischere03fae42015-12-05 14:42:34 +0000331 void reset() {
332 inited_ = false;
333 Entries.clear();
334 }
335
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000336 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000337 assert(!inited_);
338 inited_ = true;
339 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000340 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000341 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000342 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000343 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000344 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000345 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000346 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000347 // We can already have an entry for GV if it was merged with another
348 // global.
349 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000350 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
351 E.SourceLoc.parse(Loc);
352 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
353 E.Name = Name->getString();
354 ConstantInt *IsDynInit =
355 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000356 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000357 ConstantInt *IsBlacklisted =
358 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000359 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000360 }
361 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000362
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000363 /// Returns metadata entry for a given global.
364 Entry get(GlobalVariable *G) const {
365 auto Pos = Entries.find(G);
366 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000367 }
368
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000369 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000370 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000371 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000372};
373
Alexey Samsonov1345d352013-01-16 13:23:28 +0000374/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000375/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000376struct ShadowMapping {
377 int Scale;
378 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000379 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000380};
381
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000382static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
383 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000384 bool IsAndroid = TargetTriple.isAndroid();
Anna Zaks3b50e702016-02-02 22:05:07 +0000385 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000386 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
387 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000388 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
389 TargetTriple.getArch() == llvm::Triple::ppc64le;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000390 bool IsSystemZ = TargetTriple.getArch() == llvm::Triple::systemz;
Anna Zaks3b50e702016-02-02 22:05:07 +0000391 bool IsX86 = TargetTriple.getArch() == llvm::Triple::x86;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000392 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000393 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
394 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000395 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
396 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000397 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000398 bool IsWindows = TargetTriple.isOSWindows();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000399
400 ShadowMapping Mapping;
401
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000402 if (LongSize == 32) {
Evgeniy Stepanov9cb08f82015-07-17 23:51:18 +0000403 // Android is always PIE, which means that the beginning of the address
404 // space is always available.
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000405 if (IsAndroid)
406 Mapping.Offset = 0;
407 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000408 Mapping.Offset = kMIPS32_ShadowOffset32;
409 else if (IsFreeBSD)
410 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000411 else if (IsIOS)
Anna Zaks3b50e702016-02-02 22:05:07 +0000412 // If we're targeting iOS and x86, the binary is built for iOS simulator.
413 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000414 else if (IsWindows)
415 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000416 else
417 Mapping.Offset = kDefaultShadowOffset32;
418 } else { // LongSize == 64
419 if (IsPPC64)
420 Mapping.Offset = kPPC64_ShadowOffset64;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000421 else if (IsSystemZ)
422 Mapping.Offset = kSystemZ_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000423 else if (IsFreeBSD)
424 Mapping.Offset = kFreeBSD_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000425 else if (IsLinux && IsX86_64) {
426 if (IsKasan)
427 Mapping.Offset = kLinuxKasan_ShadowOffset64;
428 else
429 Mapping.Offset = kSmallX86_64ShadowOffset;
Etienne Bergeron70684f92016-06-21 15:07:29 +0000430 } else if (IsWindows && IsX86_64) {
431 Mapping.Offset = kWindowsShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000432 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000433 Mapping.Offset = kMIPS64_ShadowOffset64;
Anna Zaks3b50e702016-02-02 22:05:07 +0000434 else if (IsIOS)
435 // If we're targeting iOS and x86, the binary is built for iOS simulator.
Anna Zaks9a6a6ef2016-10-05 20:34:13 +0000436 // We are using dynamic shadow offset on the 64-bit devices.
437 Mapping.Offset =
438 IsX86_64 ? kIOSSimShadowOffset64 : kDynamicShadowSentinel;
Renato Golinaf213722015-02-03 11:20:45 +0000439 else if (IsAArch64)
440 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000441 else
442 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000443 }
444
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000445 if (ClForceDynamicShadow) {
446 Mapping.Offset = kDynamicShadowSentinel;
447 }
448
Alexey Samsonov1345d352013-01-16 13:23:28 +0000449 Mapping.Scale = kDefaultShadowScale;
Ryan Govostes3f37df02016-05-06 10:25:22 +0000450 if (ClMappingScale.getNumOccurrences() > 0) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000451 Mapping.Scale = ClMappingScale;
452 }
453
Ryan Govostes3f37df02016-05-06 10:25:22 +0000454 if (ClMappingOffset.getNumOccurrences() > 0) {
455 Mapping.Offset = ClMappingOffset;
456 }
457
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000458 // OR-ing shadow offset if more efficient (at least on x86) if the offset
459 // is a power of two, but on ppc64 we have to use add since the shadow
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000460 // offset is not necessary 1/8-th of the address space. On SystemZ,
461 // we could OR the constant in a single instruction, but it's more
462 // efficient to load it once and use indexed addressing.
463 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000464 && !(Mapping.Offset & (Mapping.Offset - 1))
465 && Mapping.Offset != kDynamicShadowSentinel;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000466
Alexey Samsonov1345d352013-01-16 13:23:28 +0000467 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000468}
469
Alexey Samsonov1345d352013-01-16 13:23:28 +0000470static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000471 // Redzone used for stack and globals is at least 32 bytes.
472 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000473 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000474}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000475
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000476/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000477struct AddressSanitizer : public FunctionPass {
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000478 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
479 bool UseAfterScope = false)
Yury Gribovd7731982015-11-11 10:36:49 +0000480 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000481 Recover(Recover || ClRecover),
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000482 UseAfterScope(UseAfterScope || ClUseAfterScope),
483 LocalDynamicShadow(nullptr) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000484 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
485 }
Mehdi Amini117296c2016-10-01 02:56:57 +0000486 StringRef getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000487 return "AddressSanitizerFunctionPass";
488 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000489 void getAnalysisUsage(AnalysisUsage &AU) const override {
490 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000491 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000492 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000493 uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000494 uint64_t ArraySize = 1;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000495 if (AI.isArrayAllocation()) {
496 const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000497 assert(CI && "non-constant array size");
498 ArraySize = CI->getZExtValue();
499 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000500 Type *Ty = AI.getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000501 uint64_t SizeInBytes =
Vitaly Buka21a9e572016-07-28 22:50:50 +0000502 AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000503 return SizeInBytes * ArraySize;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000504 }
505 /// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000506 bool isInterestingAlloca(const AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000507
Anna Zaks8ed1d812015-02-27 03:12:36 +0000508 /// If it is an interesting memory access, return the PointerOperand
509 /// and set IsWrite/Alignment. Otherwise return nullptr.
510 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000511 uint64_t *TypeSize, unsigned *Alignment);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000512 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000513 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000514 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000515 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
516 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000517 Value *SizeArgument, bool UseCalls, uint32_t Exp);
518 void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
519 uint32_t TypeSize, bool IsWrite,
520 Value *SizeArgument, bool UseCalls,
521 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000522 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
523 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000524 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000525 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000526 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000527 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000528 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000529 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000530 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000531 void maybeInsertDynamicShadowAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000532 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000533 bool doInitialization(Module &M) override;
Keno Fischere03fae42015-12-05 14:42:34 +0000534 bool doFinalization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000535 static char ID; // Pass identification, replacement for typeid
536
Yury Gribov3ae427d2014-12-01 08:47:58 +0000537 DominatorTree &getDominatorTree() const { return *DT; }
538
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000539 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000540 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000541
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000542 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000543 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000544 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
545 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000546
Reid Kleckner2f907552015-07-21 17:40:14 +0000547 /// Helper to cleanup per-function state.
548 struct FunctionStateRAII {
549 AddressSanitizer *Pass;
550 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
551 assert(Pass->ProcessedAllocas.empty() &&
552 "last pass forgot to clear cache");
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000553 assert(!Pass->LocalDynamicShadow);
Reid Kleckner2f907552015-07-21 17:40:14 +0000554 }
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000555 ~FunctionStateRAII() {
556 Pass->LocalDynamicShadow = nullptr;
557 Pass->ProcessedAllocas.clear();
558 }
Reid Kleckner2f907552015-07-21 17:40:14 +0000559 };
560
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000561 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000562 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000563 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000564 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000565 bool Recover;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000566 bool UseAfterScope;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000567 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000568 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000569 DominatorTree *DT;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000570 Function *AsanCtorFunction = nullptr;
571 Function *AsanInitFunction = nullptr;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000572 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000573 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000574 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
575 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
576 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
577 // This array is indexed by AccessIsWrite and Experiment.
578 Function *AsanErrorCallbackSized[2][2];
579 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000580 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000581 InlineAsm *EmptyAsm;
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000582 Value *LocalDynamicShadow;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000583 GlobalsMetadata GlobalsMD;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000584 DenseMap<const AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000585
586 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000587};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000588
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000589class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000590 public:
Yury Gribovd7731982015-11-11 10:36:49 +0000591 explicit AddressSanitizerModule(bool CompileKernel = false,
592 bool Recover = false)
593 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
594 Recover(Recover || ClRecover) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000595 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000596 static char ID; // Pass identification, replacement for typeid
Mehdi Amini117296c2016-10-01 02:56:57 +0000597 StringRef getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000598
Mehdi Amini117296c2016-10-01 02:56:57 +0000599private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000600 void initializeCallbacks(Module &M);
601
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000602 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000603 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000604 bool ShouldUseMachOGlobalsSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000605 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000606 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000607 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000608 return RedzoneSizeForScale(Mapping.Scale);
609 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000610
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000611 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000612 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000613 bool Recover;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000614 Type *IntptrTy;
615 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000616 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000617 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000618 Function *AsanPoisonGlobals;
619 Function *AsanUnpoisonGlobals;
620 Function *AsanRegisterGlobals;
621 Function *AsanUnregisterGlobals;
Ryan Govostes653f9d02016-03-28 20:28:57 +0000622 Function *AsanRegisterImageGlobals;
623 Function *AsanUnregisterImageGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000624};
625
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000626// Stack poisoning does not play well with exception handling.
627// When an exception is thrown, we essentially bypass the code
628// that unpoisones the stack. This is why the run-time library has
629// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
630// stack in the interceptor. This however does not work inside the
631// actual function which catches the exception. Most likely because the
632// compiler hoists the load of the shadow value somewhere too high.
633// This causes asan to report a non-existing bug on 453.povray.
634// It sounds like an LLVM bug.
635struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
636 Function &F;
637 AddressSanitizer &ASan;
638 DIBuilder DIB;
639 LLVMContext *C;
640 Type *IntptrTy;
641 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000642 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000643
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000644 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000645 SmallSetVector<AllocaInst *, 16> NonInstrumentedStaticAllocaVec;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000646 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000647 unsigned StackAlignment;
648
Kostya Serebryany6805de52013-09-10 13:16:56 +0000649 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000650 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000651 Function *AsanSetShadowFunc[0x100] = {};
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000652 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000653 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000654
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000655 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
656 struct AllocaPoisonCall {
657 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000658 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000659 uint64_t Size;
660 bool DoPoison;
661 };
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000662 SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
663 SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000664
Yury Gribov98b18592015-05-28 07:51:49 +0000665 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
666 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
667 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000668 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000669
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000670 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000671 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000672 AllocaForValueMapTy AllocaForValue;
673
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000674 bool HasNonEmptyInlineAsm = false;
675 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000676 std::unique_ptr<CallInst> EmptyInlineAsm;
677
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000678 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000679 : F(F),
680 ASan(ASan),
681 DIB(*F.getParent(), /*AllowUnresolved*/ false),
682 C(ASan.C),
683 IntptrTy(ASan.IntptrTy),
684 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
685 Mapping(ASan.Mapping),
686 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000687 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000688
689 bool runOnFunction() {
690 if (!ClStack) return false;
691 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000692 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000693
Yury Gribov55441bb2014-11-21 10:29:50 +0000694 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000695
696 initializeCallbacks(*F.getParent());
697
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000698 processDynamicAllocas();
699 processStaticAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000700
701 if (ClDebugStack) {
702 DEBUG(dbgs() << F);
703 }
704 return true;
705 }
706
Yury Gribov55441bb2014-11-21 10:29:50 +0000707 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000708 // poisoned red zones around all of them.
709 // Then unpoison everything back before the function returns.
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000710 void processStaticAllocas();
711 void processDynamicAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000712
Yury Gribov98b18592015-05-28 07:51:49 +0000713 void createDynamicAllocasInitStorage();
714
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000715 // ----------------------- Visitors.
716 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000717 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000718
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000719 /// \brief Collect all Resume instructions.
720 void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
721
722 /// \brief Collect all CatchReturnInst instructions.
723 void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
724
Yury Gribov98b18592015-05-28 07:51:49 +0000725 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
726 Value *SavedStack) {
727 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000728 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
729 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
730 // need to adjust extracted SP to compute the address of the most recent
731 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
732 // this purpose.
733 if (!isa<ReturnInst>(InstBefore)) {
734 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
735 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
736 {IntptrTy});
737
738 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
739
740 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
741 DynamicAreaOffset);
742 }
743
Yury Gribov781bce22015-05-28 08:03:28 +0000744 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000745 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000746 }
747
Yury Gribov55441bb2014-11-21 10:29:50 +0000748 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000749 void unpoisonDynamicAllocas() {
750 for (auto &Ret : RetVec)
751 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000752
Yury Gribov98b18592015-05-28 07:51:49 +0000753 for (auto &StackRestoreInst : StackRestoreVec)
754 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
755 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000756 }
757
Yury Gribov55441bb2014-11-21 10:29:50 +0000758 // Deploy and poison redzones around dynamic alloca call. To do this, we
759 // should replace this call with another one with changed parameters and
760 // replace all its uses with new address, so
761 // addr = alloca type, old_size, align
762 // is replaced by
763 // new_size = (old_size + additional_size) * sizeof(type)
764 // tmp = alloca i8, new_size, max(align, 32)
765 // addr = tmp + 32 (first 32 bytes are for the left redzone).
766 // Additional_size is added to make new memory allocation contain not only
767 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000768 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000769
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000770 /// \brief Collect Alloca instructions we want (and can) handle.
771 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000772 if (!ASan.isInterestingAlloca(AI)) {
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000773 if (AI.isStaticAlloca()) NonInstrumentedStaticAllocaVec.insert(&AI);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000774 return;
775 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000776
777 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000778 if (!AI.isStaticAlloca())
Yury Gribov98b18592015-05-28 07:51:49 +0000779 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000780 else
781 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000782 }
783
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000784 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
785 /// errors.
786 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000787 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000788 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000789 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000790 if (!ASan.UseAfterScope)
791 return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000792 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000793 return;
794 // Found lifetime intrinsic, add ASan instrumentation if necessary.
795 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
796 // If size argument is undefined, don't do anything.
797 if (Size->isMinusOne()) return;
798 // Check that size doesn't saturate uint64_t and can
799 // be stored in IntptrTy.
800 const uint64_t SizeValue = Size->getValue().getLimitedValue();
801 if (SizeValue == ~0ULL ||
802 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
803 return;
804 // Find alloca instruction that corresponds to llvm.lifetime argument.
805 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
Vitaly Bukab451f1b2016-06-09 23:31:59 +0000806 if (!AI || !ASan.isInterestingAlloca(*AI))
807 return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000808 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000809 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000810 if (AI->isStaticAlloca())
811 StaticAllocaPoisonCallVec.push_back(APC);
812 else if (ClInstrumentDynamicAllocas)
813 DynamicAllocaPoisonCallVec.push_back(APC);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000814 }
815
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000816 void visitCallSite(CallSite CS) {
817 Instruction *I = CS.getInstruction();
818 if (CallInst *CI = dyn_cast<CallInst>(I)) {
819 HasNonEmptyInlineAsm |=
820 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
821 HasReturnsTwiceCall |= CI->canReturnTwice();
822 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000823 }
824
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000825 // ---------------------- Helpers.
826 void initializeCallbacks(Module &M);
827
Yury Gribov3ae427d2014-12-01 08:47:58 +0000828 bool doesDominateAllExits(const Instruction *I) const {
829 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000830 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000831 }
832 return true;
833 }
834
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000835 /// Finds alloca where the value comes from.
836 AllocaInst *findAllocaForValue(Value *V);
Vitaly Buka793913c2016-08-29 18:17:21 +0000837
838 // Copies bytes from ShadowBytes into shadow memory for indexes where
839 // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
840 // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
841 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
842 IRBuilder<> &IRB, Value *ShadowBase);
843 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
844 size_t Begin, size_t End, IRBuilder<> &IRB,
845 Value *ShadowBase);
846 void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
847 ArrayRef<uint8_t> ShadowBytes, size_t Begin,
848 size_t End, IRBuilder<> &IRB, Value *ShadowBase);
849
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000850 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000851
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000852 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
853 bool Dynamic);
854 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
855 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000856};
857
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000858} // anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000859
860char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000861INITIALIZE_PASS_BEGIN(
862 AddressSanitizer, "asan",
863 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
864 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000865INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +0000866INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000867INITIALIZE_PASS_END(
868 AddressSanitizer, "asan",
869 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
870 false)
Yury Gribovd7731982015-11-11 10:36:49 +0000871FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000872 bool Recover,
873 bool UseAfterScope) {
Yury Gribovd7731982015-11-11 10:36:49 +0000874 assert(!CompileKernel || Recover);
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000875 return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000876}
877
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000878char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000879INITIALIZE_PASS(
880 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000881 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000882 "ModulePass",
883 false, false)
Yury Gribovd7731982015-11-11 10:36:49 +0000884ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
885 bool Recover) {
886 assert(!CompileKernel || Recover);
887 return new AddressSanitizerModule(CompileKernel, Recover);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000888}
889
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000890static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000891 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000892 assert(Res < kNumberOfAccessSizes);
893 return Res;
894}
895
Bill Wendling58f8cef2013-08-06 22:52:42 +0000896// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000897static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
898 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000899 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000900 // We use private linkage for module-local strings. If they can be merged
901 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000902 GlobalVariable *GV =
903 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000904 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000905 if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000906 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
907 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000908}
909
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000910/// \brief Create a global describing a source location.
911static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
912 LocationMetadata MD) {
913 Constant *LocData[] = {
914 createPrivateGlobalForString(M, MD.Filename, true),
915 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
916 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
917 };
918 auto LocStruct = ConstantStruct::getAnon(LocData);
919 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
920 GlobalValue::PrivateLinkage, LocStruct,
921 kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000922 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000923 return GV;
924}
925
Vedant Kumarf5ac6d42016-06-22 17:30:58 +0000926/// \brief Check if \p G has been created by a trusted compiler pass.
927static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
928 // Do not instrument asan globals.
929 if (G->getName().startswith(kAsanGenPrefix) ||
930 G->getName().startswith(kSanCovGenPrefix) ||
931 G->getName().startswith(kODRGenPrefix))
932 return true;
933
934 // Do not instrument gcov counter arrays.
935 if (G->getName() == "__llvm_gcov_ctr")
936 return true;
937
938 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000939}
940
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000941Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
942 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000943 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000944 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000945 // (Shadow >> scale) | offset
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000946 Value *ShadowBase;
947 if (LocalDynamicShadow)
948 ShadowBase = LocalDynamicShadow;
Etienne Bergeron6ba51762016-09-19 15:58:38 +0000949 else
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000950 ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
951 if (Mapping.OrShadowOffset)
952 return IRB.CreateOr(Shadow, ShadowBase);
953 else
954 return IRB.CreateAdd(Shadow, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000955}
956
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000957// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000958void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
959 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000960 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000961 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000962 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +0000963 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
964 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
965 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000966 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000967 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000968 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +0000969 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
970 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
971 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000972 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000973 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000974}
975
Anna Zaks8ed1d812015-02-27 03:12:36 +0000976/// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000977bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000978 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
979
980 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
981 return PreviouslySeenAllocaInfo->getSecond();
982
Yury Gribov98b18592015-05-28 07:51:49 +0000983 bool IsInteresting =
984 (AI.getAllocatedType()->isSized() &&
985 // alloca() may be called with 0 size, ignore it.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000986 ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
Yury Gribov98b18592015-05-28 07:51:49 +0000987 // We are only interested in allocas not promotable to registers.
988 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +0000989 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
990 // inalloca allocas are not treated as static, and we don't want
991 // dynamic alloca instrumentation for them as well.
992 !AI.isUsedWithInAlloca());
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000993
994 ProcessedAllocas[&AI] = IsInteresting;
995 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000996}
997
998/// If I is an interesting memory access, return the PointerOperand
999/// and set IsWrite/Alignment. Otherwise return nullptr.
1000Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
1001 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001002 uint64_t *TypeSize,
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001003 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +00001004 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001005 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001006
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001007 // Do not instrument the load fetching the dynamic shadow address.
1008 if (LocalDynamicShadow == I)
1009 return nullptr;
1010
Anna Zaks8ed1d812015-02-27 03:12:36 +00001011 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001012 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001013 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001014 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001015 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001016 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001017 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001018 PtrOperand = LI->getPointerOperand();
1019 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001020 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001021 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001022 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001023 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001024 PtrOperand = SI->getPointerOperand();
1025 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001026 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001027 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001028 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001029 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001030 PtrOperand = RMW->getPointerOperand();
1031 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001032 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001033 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001034 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001035 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001036 PtrOperand = XCHG->getPointerOperand();
Kostya Serebryany90241602012-05-30 09:04:06 +00001037 }
Anna Zaks8ed1d812015-02-27 03:12:36 +00001038
Anna Zaks644d9d32016-06-22 00:15:52 +00001039 // Do not instrument acesses from different address spaces; we cannot deal
1040 // with them.
1041 if (PtrOperand) {
1042 Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1043 if (PtrTy->getPointerAddressSpace() != 0)
1044 return nullptr;
1045 }
1046
Anna Zaks8ed1d812015-02-27 03:12:36 +00001047 // Treat memory accesses to promotable allocas as non-interesting since they
1048 // will not cause memory violations. This greatly speeds up the instrumented
1049 // executable at -O0.
1050 if (ClSkipPromotableAllocas)
1051 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1052 return isInterestingAlloca(*AI) ? AI : nullptr;
1053
1054 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001055}
1056
Kostya Serebryany796f6552014-02-27 12:45:36 +00001057static bool isPointerOperand(Value *V) {
1058 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1059}
1060
1061// This is a rough heuristic; it may cause both false positives and
1062// false negatives. The proper implementation requires cooperation with
1063// the frontend.
1064static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1065 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001066 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001067 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001068 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001069 } else {
1070 return false;
1071 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +00001072 return isPointerOperand(I->getOperand(0)) &&
1073 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001074}
1075
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001076bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1077 // If a global variable does not have dynamic initialization we don't
1078 // have to instrument it. However, if a global does not have initializer
1079 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001080 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001081}
1082
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001083void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1084 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +00001085 IRBuilder<> IRB(I);
1086 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1087 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
Benjamin Kramer135f7352016-06-26 12:28:59 +00001088 for (Value *&i : Param) {
1089 if (i->getType()->isPointerTy())
1090 i = IRB.CreatePointerCast(i, IntptrTy);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001091 }
David Blaikieff6409d2015-05-18 22:13:54 +00001092 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001093}
1094
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001095void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001096 Instruction *I, bool UseCalls,
1097 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +00001098 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001099 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001100 uint64_t TypeSize = 0;
1101 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +00001102 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001103
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001104 // Optimization experiments.
1105 // The experiments can be used to evaluate potential optimizations that remove
1106 // instrumentation (assess false negatives). Instead of completely removing
1107 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1108 // experiments that want to remove instrumentation of this instruction).
1109 // If Exp is non-zero, this pass will emit special calls into runtime
1110 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1111 // make runtime terminate the program in a special way (with a different
1112 // exit status). Then you run the new compiler on a buggy corpus, collect
1113 // the special terminations (ideally, you don't see them at all -- no false
1114 // negatives) and make the decision on the optimization.
1115 uint32_t Exp = ClForceExperiment;
1116
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001117 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001118 // If initialization order checking is disabled, a simple access to a
1119 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001120 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001121 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001122 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1123 NumOptimizedAccessesToGlobalVar++;
1124 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001125 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001126 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001127
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001128 if (ClOpt && ClOptStack) {
1129 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001130 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001131 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1132 NumOptimizedAccessesToStackVar++;
1133 return;
1134 }
1135 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001136
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001137 if (IsWrite)
1138 NumInstrumentedWrites++;
1139 else
1140 NumInstrumentedReads++;
1141
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001142 unsigned Granularity = 1 << Mapping.Scale;
1143 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1144 // if the data is properly aligned.
1145 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1146 TypeSize == 128) &&
1147 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001148 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
1149 Exp);
1150 instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
1151 UseCalls, Exp);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001152}
1153
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001154Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1155 Value *Addr, bool IsWrite,
1156 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001157 Value *SizeArgument,
1158 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001159 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001160 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1161 CallInst *Call = nullptr;
1162 if (SizeArgument) {
1163 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001164 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1165 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001166 else
David Blaikieff6409d2015-05-18 22:13:54 +00001167 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1168 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001169 } else {
1170 if (Exp == 0)
1171 Call =
1172 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1173 else
David Blaikieff6409d2015-05-18 22:13:54 +00001174 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1175 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001176 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001177
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001178 // We don't do Call->setDoesNotReturn() because the BB already has
1179 // UnreachableInst at the end.
1180 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001181 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001182 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001183}
1184
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001185Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001186 Value *ShadowValue,
1187 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001188 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001189 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001190 Value *LastAccessedByte =
1191 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001192 // (Addr & (Granularity - 1)) + size - 1
1193 if (TypeSize / 8 > 1)
1194 LastAccessedByte = IRB.CreateAdd(
1195 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1196 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001197 LastAccessedByte =
1198 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001199 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1200 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1201}
1202
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001203void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001204 Instruction *InsertBefore, Value *Addr,
1205 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001206 Value *SizeArgument, bool UseCalls,
1207 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001208 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001209 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001210 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1211
1212 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001213 if (Exp == 0)
1214 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1215 AddrLong);
1216 else
David Blaikieff6409d2015-05-18 22:13:54 +00001217 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1218 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001219 return;
1220 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001221
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001222 Type *ShadowTy =
1223 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001224 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1225 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1226 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001227 Value *ShadowValue =
1228 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001229
1230 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001231 size_t Granularity = 1ULL << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001232 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001233
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001234 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001235 // We use branch weights for the slow path check, to indicate that the slow
1236 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001237 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1238 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001239 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001240 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001241 IRB.SetInsertPoint(CheckTerm);
1242 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001243 if (Recover) {
1244 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1245 } else {
1246 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001247 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001248 CrashTerm = new UnreachableInst(*C, CrashBlock);
1249 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1250 ReplaceInstWithInst(CheckTerm, NewTerm);
1251 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001252 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001253 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001254 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001255
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001256 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001257 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001258 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001259}
1260
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001261// Instrument unusual size or unusual alignment.
1262// We can not do it with a single check, so we do 1-byte check for the first
1263// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1264// to report the actual access size.
1265void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1266 Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1267 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1268 IRBuilder<> IRB(I);
1269 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1270 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1271 if (UseCalls) {
1272 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001273 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1274 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001275 else
David Blaikieff6409d2015-05-18 22:13:54 +00001276 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1277 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001278 } else {
1279 Value *LastByte = IRB.CreateIntToPtr(
1280 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1281 Addr->getType());
1282 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1283 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1284 }
1285}
1286
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001287void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1288 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001289 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001290 IRBuilder<> IRB(&GlobalInit.front(),
1291 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001292
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001293 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001294 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1295 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001296
1297 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001298 for (auto &BB : GlobalInit.getBasicBlockList())
1299 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001300 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001301}
1302
1303void AddressSanitizerModule::createInitializerPoisonCalls(
1304 Module &M, GlobalValue *ModuleName) {
1305 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1306
1307 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1308 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001309 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001310 ConstantStruct *CS = cast<ConstantStruct>(OP);
1311
1312 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001313 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001314 if (F->getName() == kAsanModuleCtorName) continue;
1315 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1316 // Don't instrument CTORs that will run before asan.module_ctor.
1317 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1318 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001319 }
1320 }
1321}
1322
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001323bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001324 Type *Ty = G->getValueType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001325 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001326
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001327 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001328 if (!Ty->isSized()) return false;
1329 if (!G->hasInitializer()) return false;
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001330 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001331 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001332 // Don't handle ODR linkage types and COMDATs since other modules may be built
1333 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001334 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1335 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1336 G->getLinkage() != GlobalVariable::InternalLinkage)
1337 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001338 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001339 // Two problems with thread-locals:
1340 // - The address of the main thread's copy can't be computed at link-time.
1341 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001342 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001343 // For now, just ignore this Global if the alignment is large.
1344 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001345
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001346 if (G->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001347 StringRef Section = G->getSection();
Kuba Brecka086e34b2014-12-05 21:32:46 +00001348
Anna Zaks11904602015-06-09 00:58:08 +00001349 // Globals from llvm.metadata aren't emitted, do not instrument them.
1350 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001351 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001352 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001353
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001354 // Do not instrument function pointers to initialization and termination
1355 // routines: dynamic linker will not properly handle redzones.
1356 if (Section.startswith(".preinit_array") ||
1357 Section.startswith(".init_array") ||
1358 Section.startswith(".fini_array")) {
1359 return false;
1360 }
1361
Anna Zaks11904602015-06-09 00:58:08 +00001362 // Callbacks put into the CRT initializer/terminator sections
1363 // should not be instrumented.
1364 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1365 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1366 if (Section.startswith(".CRT")) {
1367 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1368 return false;
1369 }
1370
Kuba Brecka1001bb52014-12-05 22:19:18 +00001371 if (TargetTriple.isOSBinFormatMachO()) {
1372 StringRef ParsedSegment, ParsedSection;
1373 unsigned TAA = 0, StubSize = 0;
1374 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001375 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1376 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001377 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001378
1379 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1380 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1381 // them.
1382 if (ParsedSegment == "__OBJC" ||
1383 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1384 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1385 return false;
1386 }
1387 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1388 // Constant CFString instances are compiled in the following way:
1389 // -- the string buffer is emitted into
1390 // __TEXT,__cstring,cstring_literals
1391 // -- the constant NSConstantString structure referencing that buffer
1392 // is placed into __DATA,__cfstring
1393 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1394 // Moreover, it causes the linker to crash on OS X 10.7
1395 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1396 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1397 return false;
1398 }
1399 // The linker merges the contents of cstring_literals and removes the
1400 // trailing zeroes.
1401 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1402 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1403 return false;
1404 }
1405 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001406 }
1407
1408 return true;
1409}
1410
Ryan Govostes653f9d02016-03-28 20:28:57 +00001411// On Mach-O platforms, we emit global metadata in a separate section of the
1412// binary in order to allow the linker to properly dead strip. This is only
1413// supported on recent versions of ld64.
1414bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
Ryan Govostese51401b2016-07-05 21:53:08 +00001415 if (!ClUseMachOGlobalsSection)
1416 return false;
1417
Ryan Govostes653f9d02016-03-28 20:28:57 +00001418 if (!TargetTriple.isOSBinFormatMachO())
1419 return false;
1420
1421 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1422 return true;
1423 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001424 return true;
Ryan Govostes653f9d02016-03-28 20:28:57 +00001425 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1426 return true;
1427
1428 return false;
1429}
1430
Alexey Samsonov788381b2012-12-25 12:28:20 +00001431void AddressSanitizerModule::initializeCallbacks(Module &M) {
1432 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001433
Alexey Samsonov788381b2012-12-25 12:28:20 +00001434 // Declare our poisoning and unpoisoning functions.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001435 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001436 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001437 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001438 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001439 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001440 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001441
Alexey Samsonov788381b2012-12-25 12:28:20 +00001442 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001443 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001444 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001445 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001446 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001447 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1448 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001449 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001450
1451 // Declare the functions that find globals in a shared object and then invoke
1452 // the (un)register function on them.
1453 AsanRegisterImageGlobals = checkSanitizerInterfaceFunction(
1454 M.getOrInsertFunction(kAsanRegisterImageGlobalsName,
1455 IRB.getVoidTy(), IntptrTy, nullptr));
1456 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001457
Ryan Govostes653f9d02016-03-28 20:28:57 +00001458 AsanUnregisterImageGlobals = checkSanitizerInterfaceFunction(
1459 M.getOrInsertFunction(kAsanUnregisterImageGlobalsName,
1460 IRB.getVoidTy(), IntptrTy, nullptr));
1461 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001462}
1463
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001464// This function replaces all global variables with new variables that have
1465// trailing redzones. It also creates a function that poisons
1466// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001467bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001468 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001469
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001470 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1471
Alexey Samsonova02e6642014-05-29 18:40:48 +00001472 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001473 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001474 }
1475
1476 size_t n = GlobalsToChange.size();
1477 if (n == 0) return false;
1478
1479 // A global is described by a structure
1480 // size_t beg;
1481 // size_t size;
1482 // size_t size_with_redzone;
1483 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001484 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001485 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001486 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001487 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001488 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001489 StructType *GlobalStructTy =
1490 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001491 IntptrTy, IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001492 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001493
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001494 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001495
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001496 // We shouldn't merge same module names, as this string serves as unique
1497 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001498 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001499 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001500
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001501 auto &DL = M.getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001502 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001503 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001504 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001505
1506 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001507 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001508 // Create string holding the global name (use global name from metadata
1509 // if it's available, otherwise just write the name of global variable).
1510 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001511 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001512 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001513
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001514 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001515 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001516 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001517 // MinRZ <= RZ <= kMaxGlobalRedzone
1518 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001519 uint64_t RZ = std::max(
1520 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001521 uint64_t RightRedzoneSize = RZ;
1522 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001523 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001524 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001525 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1526
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001527 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001528 Constant *NewInitializer =
1529 ConstantStruct::get(NewTy, G->getInitializer(),
1530 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001531
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001532 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001533 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1534 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1535 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001536 GlobalVariable *NewGlobal =
1537 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1538 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001539 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001540 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001541
Adrian Prantl12fa3b32016-09-20 18:28:42 +00001542 // Transfer the debug info. The payload starts at offset zero so we can
1543 // copy the debug info over as is.
1544 SmallVector<DIGlobalVariable *, 1> GVs;
1545 G->getDebugInfo(GVs);
1546 for (auto *GV : GVs)
1547 NewGlobal->addDebugInfo(GV);
1548
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001549 Value *Indices2[2];
1550 Indices2[0] = IRB.getInt32(0);
1551 Indices2[1] = IRB.getInt32(0);
1552
1553 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001554 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001555 NewGlobal->takeName(G);
1556 G->eraseFromParent();
1557
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001558 Constant *SourceLoc;
1559 if (!MD.SourceLoc.empty()) {
1560 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1561 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1562 } else {
1563 SourceLoc = ConstantInt::get(IntptrTy, 0);
1564 }
1565
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001566 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
1567 GlobalValue *InstrumentedGlobal = NewGlobal;
1568
Kuba Breckaa1ea64a2016-09-14 14:06:33 +00001569 bool CanUsePrivateAliases =
1570 TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO();
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001571 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
1572 // Create local alias for NewGlobal to avoid crash on ODR between
1573 // instrumented and non-instrumented libraries.
1574 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
1575 NameForGlobal + M.getName(), NewGlobal);
1576
1577 // With local aliases, we need to provide another externally visible
1578 // symbol __odr_asan_XXX to detect ODR violation.
1579 auto *ODRIndicatorSym =
1580 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
1581 Constant::getNullValue(IRB.getInt8Ty()),
1582 kODRGenPrefix + NameForGlobal, nullptr,
1583 NewGlobal->getThreadLocalMode());
1584
1585 // Set meaningful attributes for indicator symbol.
1586 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
1587 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
1588 ODRIndicatorSym->setAlignment(1);
1589 ODRIndicator = ODRIndicatorSym;
1590 InstrumentedGlobal = GA;
1591 }
1592
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001593 Initializers[i] = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001594 GlobalStructTy,
1595 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001596 ConstantInt::get(IntptrTy, SizeInBytes),
1597 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1598 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001599 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001600 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
1601 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy), nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001602
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001603 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001604
Kostya Serebryany20343352012-10-17 13:40:06 +00001605 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001606 }
1607
Ryan Govostes653f9d02016-03-28 20:28:57 +00001608
1609 GlobalVariable *AllGlobals = nullptr;
1610 GlobalVariable *RegisteredFlag = nullptr;
1611
1612 // On recent Mach-O platforms, we emit the global metadata in a way that
1613 // allows the linker to properly strip dead globals.
1614 if (ShouldUseMachOGlobalsSection()) {
1615 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1616 // to look up the loaded image that contains it. Second, we can store in it
1617 // whether registration has already occurred, to prevent duplicate
1618 // registration.
1619 //
1620 // Common linkage allows us to coalesce needles defined in each object
1621 // file so that there's only one per shared library.
1622 RegisteredFlag = new GlobalVariable(
1623 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1624 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1625
1626 // We also emit a structure which binds the liveness of the global
1627 // variable to the metadata struct.
1628 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy, nullptr);
1629
Mehdi Amini6610b012016-10-01 00:05:34 +00001630 // Keep the list of "Liveness" GV created to be added to llvm.compiler.used
1631 SmallVector<Constant *, 16> LivenessGlobals;
1632 LivenessGlobals.reserve(n);
1633
Ryan Govostes653f9d02016-03-28 20:28:57 +00001634 for (size_t i = 0; i < n; i++) {
1635 GlobalVariable *Metadata = new GlobalVariable(
1636 M, GlobalStructTy, false, GlobalVariable::InternalLinkage,
1637 Initializers[i], "");
1638 Metadata->setSection("__DATA,__asan_globals,regular");
1639 Metadata->setAlignment(1); // don't leave padding in between
1640
1641 auto LivenessBinder = ConstantStruct::get(LivenessTy,
1642 Initializers[i]->getAggregateElement(0u),
1643 ConstantExpr::getPointerCast(Metadata, IntptrTy),
1644 nullptr);
Mehdi Amini6610b012016-10-01 00:05:34 +00001645
1646 // Recover the name of the variable this global is pointing to
1647 StringRef GVName =
1648 Initializers[i]->getAggregateElement(0u)->getOperand(0)->getName();
1649
Ryan Govostes653f9d02016-03-28 20:28:57 +00001650 GlobalVariable *Liveness = new GlobalVariable(
Mehdi Amini6610b012016-10-01 00:05:34 +00001651 M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
1652 Twine("__asan_binder_") + GVName);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001653 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
Mehdi Amini6610b012016-10-01 00:05:34 +00001654 LivenessGlobals.push_back(
1655 ConstantExpr::getBitCast(Liveness, IRB.getInt8PtrTy()));
1656 }
1657
1658 if (!LivenessGlobals.empty()) {
1659 // Update llvm.compiler.used, adding the new liveness globals. This is
1660 // needed so that during LTO these variables stay alive. The alternative
1661 // would be to have the linker handling the LTO symbols, but libLTO
1662 // current
1663 // API does not expose access to the section for each symbol.
1664 if (GlobalVariable *LLVMUsed =
1665 M.getGlobalVariable("llvm.compiler.used")) {
1666 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
1667 for (auto &V : Inits->operands())
1668 LivenessGlobals.push_back(cast<Constant>(&V));
1669 LLVMUsed->eraseFromParent();
1670 }
1671 llvm::ArrayType *ATy =
1672 llvm::ArrayType::get(IRB.getInt8PtrTy(), LivenessGlobals.size());
1673 auto *LLVMUsed = new llvm::GlobalVariable(
1674 M, ATy, false, llvm::GlobalValue::AppendingLinkage,
1675 llvm::ConstantArray::get(ATy, LivenessGlobals), "llvm.compiler.used");
1676 LLVMUsed->setSection("llvm.metadata");
Ryan Govostes653f9d02016-03-28 20:28:57 +00001677 }
1678 } else {
1679 // On all other platfoms, we just emit an array of global metadata
1680 // structures.
1681 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1682 AllGlobals = new GlobalVariable(
1683 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1684 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1685 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001686
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001687 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001688 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001689 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001690
Ryan Govostes653f9d02016-03-28 20:28:57 +00001691 // Create a call to register the globals with the runtime.
1692 if (ShouldUseMachOGlobalsSection()) {
1693 IRB.CreateCall(AsanRegisterImageGlobals,
1694 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1695 } else {
1696 IRB.CreateCall(AsanRegisterGlobals,
1697 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1698 ConstantInt::get(IntptrTy, n)});
1699 }
1700
1701 // We also need to unregister globals at the end, e.g., when a shared library
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001702 // gets closed.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001703 Function *AsanDtorFunction =
1704 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1705 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001706 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1707 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001708
1709 if (ShouldUseMachOGlobalsSection()) {
1710 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1711 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1712 } else {
1713 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1714 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1715 ConstantInt::get(IntptrTy, n)});
1716 }
1717
Alexey Samsonov1f647502014-05-29 01:10:14 +00001718 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001719
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001720 DEBUG(dbgs() << M);
1721 return true;
1722}
1723
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001724bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001725 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001726 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001727 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001728 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001729 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001730 initializeCallbacks(M);
1731
1732 bool Changed = false;
1733
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001734 // TODO(glider): temporarily disabled globals instrumentation for KASan.
1735 if (ClGlobals && !CompileKernel) {
1736 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1737 assert(CtorFunc);
1738 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1739 Changed |= InstrumentGlobals(IRB, M);
1740 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001741
1742 return Changed;
1743}
1744
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001745void AddressSanitizer::initializeCallbacks(Module &M) {
1746 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001747 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001748 // IsWrite, TypeSize and Exp are encoded in the function name.
1749 for (int Exp = 0; Exp < 2; Exp++) {
1750 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1751 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1752 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001753 const std::string SuffixStr = CompileKernel ? "N" : "_n";
Yury Gribovd7731982015-11-11 10:36:49 +00001754 const std::string EndingStr = Recover ? "_noabort" : "";
Craig Toppere3dcce92015-08-01 22:20:21 +00001755 Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001756 AsanErrorCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001757 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001758 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001759 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1760 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001761 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001762 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001763 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1764 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1765 AccessSizeIndex++) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001766 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001767 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001768 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001769 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001770 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001771 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001772 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001773 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1774 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001775 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001776 }
1777 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00001778
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001779 const std::string MemIntrinCallbackPrefix =
1780 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001781 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001782 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001783 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001784 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001785 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001786 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001787 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001788 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001789 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001790
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001791 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001792 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001793
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001794 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001795 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001796 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001797 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001798 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1799 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1800 StringRef(""), StringRef(""),
1801 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001802}
1803
1804// virtual
1805bool AddressSanitizer::doInitialization(Module &M) {
1806 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001807
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001808 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001809
1810 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001811 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001812 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001813 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001814
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001815 if (!CompileKernel) {
1816 std::tie(AsanCtorFunction, AsanInitFunction) =
Kuba Brecka45dbffd2015-07-23 10:54:06 +00001817 createSanitizerCtorAndInitFunctions(
1818 M, kAsanModuleCtorName, kAsanInitName,
1819 /*InitArgTypes=*/{}, /*InitArgs=*/{}, kAsanVersionCheckName);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001820 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1821 }
1822 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001823 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001824}
1825
Keno Fischere03fae42015-12-05 14:42:34 +00001826bool AddressSanitizer::doFinalization(Module &M) {
1827 GlobalsMD.reset();
1828 return false;
1829}
1830
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001831bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1832 // For each NSObject descendant having a +load method, this method is invoked
1833 // by the ObjC runtime before any of the static constructors is called.
1834 // Therefore we need to instrument such methods with a call to __asan_init
1835 // at the beginning in order to initialize our runtime before any access to
1836 // the shadow memory.
1837 // We cannot just ignore these methods, because they may call other
1838 // instrumented functions.
1839 if (F.getName().find(" load]") != std::string::npos) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001840 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00001841 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001842 return true;
1843 }
1844 return false;
1845}
1846
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001847void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
1848 // Generate code only when dynamic addressing is needed.
1849 if (Mapping.Offset != kDynamicShadowSentinel)
1850 return;
1851
1852 IRBuilder<> IRB(&F.front().front());
1853 Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
1854 kAsanShadowMemoryDynamicAddress, IntptrTy);
1855 LocalDynamicShadow = IRB.CreateLoad(GlobalDynamicAddress);
1856}
1857
Reid Kleckner2f907552015-07-21 17:40:14 +00001858void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
1859 // Find the one possible call to llvm.localescape and pre-mark allocas passed
1860 // to it as uninteresting. This assumes we haven't started processing allocas
1861 // yet. This check is done up front because iterating the use list in
1862 // isInterestingAlloca would be algorithmically slower.
1863 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
1864
1865 // Try to get the declaration of llvm.localescape. If it's not in the module,
1866 // we can exit early.
1867 if (!F.getParent()->getFunction("llvm.localescape")) return;
1868
1869 // Look for a call to llvm.localescape call in the entry block. It can't be in
1870 // any other block.
1871 for (Instruction &I : F.getEntryBlock()) {
1872 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
1873 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
1874 // We found a call. Mark all the allocas passed in as uninteresting.
1875 for (Value *Arg : II->arg_operands()) {
1876 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
1877 assert(AI && AI->isStaticAlloca() &&
1878 "non-static alloca arg to localescape");
1879 ProcessedAllocas[AI] = false;
1880 }
1881 break;
1882 }
1883 }
1884}
1885
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001886bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001887 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001888 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Etienne Bergeron752f8832016-09-14 17:18:37 +00001889 if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
Etienne Bergeron52e47432016-09-15 15:35:59 +00001890 if (F.getName().startswith("__asan_")) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +00001891
Etienne Bergeron78582b22016-09-15 15:45:05 +00001892 bool FunctionModified = false;
1893
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001894 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Etienne Bergeron752f8832016-09-14 17:18:37 +00001895 // This function needs to be called even if the function body is not
1896 // instrumented.
Etienne Bergeron78582b22016-09-15 15:45:05 +00001897 if (maybeInsertAsanInitAtFunctionEntry(F))
1898 FunctionModified = true;
Etienne Bergeron752f8832016-09-14 17:18:37 +00001899
1900 // Leave if the function doesn't need instrumentation.
Etienne Bergeron78582b22016-09-15 15:45:05 +00001901 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001902
Etienne Bergeron752f8832016-09-14 17:18:37 +00001903 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1904
1905 initializeCallbacks(*F.getParent());
1906 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001907
Reid Kleckner2f907552015-07-21 17:40:14 +00001908 FunctionStateRAII CleanupObj(this);
1909
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001910 maybeInsertDynamicShadowAtFunctionEntry(F);
1911
Reid Kleckner2f907552015-07-21 17:40:14 +00001912 // We can't instrument allocas used with llvm.localescape. Only static allocas
1913 // can be passed to that intrinsic.
1914 markEscapedLocalAllocas(F);
1915
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001916 // We want to instrument every address only once per basic block (unless there
1917 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001918 SmallSet<Value *, 16> TempsToInstrument;
1919 SmallVector<Instruction *, 16> ToInstrument;
1920 SmallVector<Instruction *, 8> NoReturnCalls;
1921 SmallVector<BasicBlock *, 16> AllBlocks;
1922 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001923 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001924 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001925 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001926 uint64_t TypeSize;
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00001927 const TargetLibraryInfo *TLI =
1928 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001929
1930 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001931 for (auto &BB : F) {
1932 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001933 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001934 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001935 for (auto &Inst : BB) {
1936 if (LooksLikeCodeInBug11395(&Inst)) return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001937 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1938 &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001939 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001940 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001941 continue; // We've seen this temp in the current BB.
1942 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001943 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001944 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1945 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001946 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001947 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001948 // ok, take it.
1949 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001950 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001951 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001952 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001953 // A call inside BB.
1954 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001955 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001956 }
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00001957 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
1958 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001959 continue;
1960 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001961 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001962 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001963 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001964 }
1965 }
1966
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001967 bool UseCalls =
1968 CompileKernel ||
1969 (ClInstrumentationWithCallsThreshold >= 0 &&
1970 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001971 const DataLayout &DL = F.getParent()->getDataLayout();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001972 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1973 /*RoundToAlign=*/true);
1974
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001975 // Instrument.
1976 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001977 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001978 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1979 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001980 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001981 instrumentMop(ObjSizeVis, Inst, UseCalls,
1982 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001983 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001984 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001985 }
1986 NumInstrumented++;
1987 }
1988
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001989 FunctionStackPoisoner FSP(F, *this);
1990 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001991
1992 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1993 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001994 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001995 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00001996 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001997 }
1998
Alexey Samsonova02e6642014-05-29 18:40:48 +00001999 for (auto Inst : PointerComparisonsOrSubtracts) {
2000 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002001 NumInstrumented++;
2002 }
2003
Etienne Bergeron78582b22016-09-15 15:45:05 +00002004 if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
2005 FunctionModified = true;
Bob Wilsonda4147c2013-11-15 07:16:09 +00002006
Etienne Bergeron78582b22016-09-15 15:45:05 +00002007 DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2008 << F << "\n");
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002009
Etienne Bergeron78582b22016-09-15 15:45:05 +00002010 return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002011}
2012
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002013// Workaround for bug 11395: we don't want to instrument stack in functions
2014// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2015// FIXME: remove once the bug 11395 is fixed.
2016bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2017 if (LongSize != 32) return false;
2018 CallInst *CI = dyn_cast<CallInst>(I);
2019 if (!CI || !CI->isInlineAsm()) return false;
2020 if (CI->getNumArgOperands() <= 5) return false;
2021 // We have inline assembly with quite a few arguments.
2022 return true;
2023}
2024
2025void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2026 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00002027 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
2028 std::string Suffix = itostr(i);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002029 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
2030 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
2031 IntptrTy, nullptr));
2032 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002033 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
2034 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00002035 }
Vitaly Buka79b75d32016-06-09 23:05:35 +00002036 if (ASan.UseAfterScope) {
2037 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2038 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
2039 IntptrTy, IntptrTy, nullptr));
2040 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2041 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
2042 IntptrTy, IntptrTy, nullptr));
2043 }
2044
Vitaly Buka3455b9b2016-08-20 18:34:39 +00002045 if (ClExperimentalPoisoning) {
2046 for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2047 std::ostringstream Name;
2048 Name << kAsanSetShadowPrefix;
2049 Name << std::setw(2) << std::setfill('0') << std::hex << Val;
2050 AsanSetShadowFunc[Val] =
2051 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2052 Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
2053 }
2054 }
2055
Yury Gribov98b18592015-05-28 07:51:49 +00002056 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2057 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
2058 AsanAllocasUnpoisonFunc =
2059 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2060 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002061}
2062
Vitaly Buka793913c2016-08-29 18:17:21 +00002063void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2064 ArrayRef<uint8_t> ShadowBytes,
2065 size_t Begin, size_t End,
2066 IRBuilder<> &IRB,
2067 Value *ShadowBase) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002068 if (Begin >= End)
2069 return;
Vitaly Buka186280d2016-08-20 18:34:36 +00002070
2071 const size_t LargestStoreSizeInBytes =
2072 std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2073
2074 const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2075
2076 // Poison given range in shadow using larges store size with out leading and
Vitaly Buka793913c2016-08-29 18:17:21 +00002077 // trailing zeros in ShadowMask. Zeros never change, so they need neither
2078 // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2079 // middle of a store.
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002080 for (size_t i = Begin; i < End;) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002081 if (!ShadowMask[i]) {
2082 assert(!ShadowBytes[i]);
Vitaly Buka186280d2016-08-20 18:34:36 +00002083 ++i;
2084 continue;
2085 }
2086
2087 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2088 // Fit store size into the range.
2089 while (StoreSizeInBytes > End - i)
2090 StoreSizeInBytes /= 2;
2091
2092 // Minimize store size by trimming trailing zeros.
Vitaly Buka793913c2016-08-29 18:17:21 +00002093 for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
Vitaly Buka186280d2016-08-20 18:34:36 +00002094 while (j <= StoreSizeInBytes / 2)
2095 StoreSizeInBytes /= 2;
2096 }
2097
2098 uint64_t Val = 0;
Vitaly Buka793913c2016-08-29 18:17:21 +00002099 for (size_t j = 0; j < StoreSizeInBytes; j++) {
2100 if (IsLittleEndian)
2101 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2102 else
2103 Val = (Val << 8) | ShadowBytes[i + j];
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002104 }
Vitaly Buka186280d2016-08-20 18:34:36 +00002105
2106 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2107 Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
Vitaly Buka0672a272016-08-22 04:16:14 +00002108 IRB.CreateAlignedStore(
2109 Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
Vitaly Buka186280d2016-08-20 18:34:36 +00002110
2111 i += StoreSizeInBytes;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002112 }
2113}
2114
Vitaly Buka793913c2016-08-29 18:17:21 +00002115void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2116 ArrayRef<uint8_t> ShadowBytes,
2117 IRBuilder<> &IRB, Value *ShadowBase) {
2118 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2119}
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002120
Vitaly Buka793913c2016-08-29 18:17:21 +00002121void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2122 ArrayRef<uint8_t> ShadowBytes,
2123 size_t Begin, size_t End,
2124 IRBuilder<> &IRB, Value *ShadowBase) {
2125 assert(ShadowMask.size() == ShadowBytes.size());
2126 size_t Done = Begin;
2127 for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2128 if (!ShadowMask[i]) {
2129 assert(!ShadowBytes[i]);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002130 continue;
Vitaly Buka793913c2016-08-29 18:17:21 +00002131 }
2132 uint8_t Val = ShadowBytes[i];
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002133 if (!AsanSetShadowFunc[Val])
2134 continue;
2135
2136 // Skip same values.
Vitaly Buka793913c2016-08-29 18:17:21 +00002137 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002138 }
2139
2140 if (j - i >= ClMaxInlinePoisoningSize) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002141 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002142 IRB.CreateCall(AsanSetShadowFunc[Val],
2143 {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2144 ConstantInt::get(IntptrTy, j - i)});
2145 Done = j;
2146 }
2147 }
2148
Vitaly Buka793913c2016-08-29 18:17:21 +00002149 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002150}
2151
Kostya Serebryany6805de52013-09-10 13:16:56 +00002152// Fake stack allocator (asan_fake_stack.h) has 11 size classes
2153// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2154static int StackMallocSizeClass(uint64_t LocalStackSize) {
2155 assert(LocalStackSize <= kMaxStackMallocSize);
2156 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002157 for (int i = 0;; i++, MaxSize *= 2)
2158 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00002159 llvm_unreachable("impossible LocalStackSize");
2160}
2161
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002162PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2163 Value *ValueIfTrue,
2164 Instruction *ThenTerm,
2165 Value *ValueIfFalse) {
2166 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2167 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2168 PHI->addIncoming(ValueIfFalse, CondBlock);
2169 BasicBlock *ThenBlock = ThenTerm->getParent();
2170 PHI->addIncoming(ValueIfTrue, ThenBlock);
2171 return PHI;
2172}
2173
2174Value *FunctionStackPoisoner::createAllocaForLayout(
2175 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2176 AllocaInst *Alloca;
2177 if (Dynamic) {
2178 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2179 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2180 "MyAlloca");
2181 } else {
2182 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2183 nullptr, "MyAlloca");
2184 assert(Alloca->isStaticAlloca());
2185 }
2186 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2187 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2188 Alloca->setAlignment(FrameAlignment);
2189 return IRB.CreatePointerCast(Alloca, IntptrTy);
2190}
2191
Yury Gribov98b18592015-05-28 07:51:49 +00002192void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2193 BasicBlock &FirstBB = *F.begin();
2194 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2195 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2196 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2197 DynamicAllocaLayout->setAlignment(32);
2198}
2199
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002200void FunctionStackPoisoner::processDynamicAllocas() {
2201 if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2202 assert(DynamicAllocaPoisonCallVec.empty());
2203 return;
2204 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002205
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002206 // Insert poison calls for lifetime intrinsics for dynamic allocas.
2207 for (const auto &APC : DynamicAllocaPoisonCallVec) {
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002208 assert(APC.InsBefore);
2209 assert(APC.AI);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002210 assert(ASan.isInterestingAlloca(*APC.AI));
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002211 assert(!APC.AI->isStaticAlloca());
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002212
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002213 IRBuilder<> IRB(APC.InsBefore);
2214 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002215 // Dynamic allocas will be unpoisoned unconditionally below in
2216 // unpoisonDynamicAllocas.
2217 // Flag that we need unpoison static allocas.
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002218 }
2219
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002220 // Handle dynamic allocas.
2221 createDynamicAllocasInitStorage();
2222 for (auto &AI : DynamicAllocaVec)
2223 handleDynamicAllocaCall(AI);
2224 unpoisonDynamicAllocas();
2225}
Yury Gribov98b18592015-05-28 07:51:49 +00002226
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002227void FunctionStackPoisoner::processStaticAllocas() {
2228 if (AllocaVec.empty()) {
2229 assert(StaticAllocaPoisonCallVec.empty());
2230 return;
Kuba Breckaf5875d32015-02-24 09:47:05 +00002231 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002232
Kostya Serebryany6805de52013-09-10 13:16:56 +00002233 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002234 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00002235 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002236 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002237
2238 Instruction *InsBefore = AllocaVec[0];
2239 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002240 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002241
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002242 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2243 // debug info is broken, because only entry-block allocas are treated as
2244 // regular stack slots.
2245 auto InsBeforeB = InsBefore->getParent();
2246 assert(InsBeforeB == &F.getEntryBlock());
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002247 for (BasicBlock::iterator I(InsBefore); I != InsBeforeB->end(); ++I)
2248 if (auto *AI = dyn_cast<AllocaInst>(I))
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002249 if (NonInstrumentedStaticAllocaVec.count(AI) > 0)
2250 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00002251
Reid Kleckner2f907552015-07-21 17:40:14 +00002252 // If we have a call to llvm.localescape, keep it in the entry block.
2253 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2254
Vitaly Buka793913c2016-08-29 18:17:21 +00002255 // Find static allocas with lifetime analysis.
2256 DenseMap<const AllocaInst *, const ASanStackVariableDescription *>
2257 AllocaToSVDMap;
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002258 for (const auto &APC : StaticAllocaPoisonCallVec) {
2259 assert(APC.InsBefore);
2260 assert(APC.AI);
2261 assert(ASan.isInterestingAlloca(*APC.AI));
2262 assert(APC.AI->isStaticAlloca());
2263
Vitaly Buka793913c2016-08-29 18:17:21 +00002264 if (ClExperimentalPoisoning) {
2265 AllocaToSVDMap[APC.AI] = nullptr;
2266 } else {
2267 IRBuilder<> IRB(APC.InsBefore);
2268 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
2269 }
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002270 }
2271
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002272 SmallVector<ASanStackVariableDescription, 16> SVD;
2273 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00002274 for (AllocaInst *AI : AllocaVec) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002275 size_t UseAfterScopePoisonSize =
2276 AllocaToSVDMap.find(AI) != AllocaToSVDMap.end()
2277 ? ASan.getAllocaSizeInBytes(*AI)
2278 : 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002279 ASanStackVariableDescription D = {AI->getName().data(),
Vitaly Buka21a9e572016-07-28 22:50:50 +00002280 ASan.getAllocaSizeInBytes(*AI),
Vitaly Buka793913c2016-08-29 18:17:21 +00002281 UseAfterScopePoisonSize,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002282 AI->getAlignment(),
2283 AI,
2284 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002285 SVD.push_back(D);
2286 }
2287 // Minimal header size (left redzone) is 4 pointers,
2288 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2289 size_t MinHeaderSize = ASan.LongSize / 2;
Vitaly Bukadb331d82016-08-29 17:41:29 +00002290 const ASanStackFrameLayout &L =
2291 ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize);
Vitaly Buka793913c2016-08-29 18:17:21 +00002292
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002293 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
2294 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002295 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2296 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00002297 bool DoDynamicAlloca = ClDynamicAllocaStack;
2298 // Don't do dynamic alloca or stack malloc if:
2299 // 1) There is inline asm: too often it makes assumptions on which registers
2300 // are available.
2301 // 2) There is a returns_twice call (typically setjmp), which is
2302 // optimization-hostile, and doesn't play well with introduced indirect
2303 // register-relative calculation of local variable addresses.
2304 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2305 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002306
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002307 Value *StaticAlloca =
2308 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2309
2310 Value *FakeStack;
2311 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002312
2313 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002314 // void *FakeStack = __asan_option_detect_stack_use_after_return
2315 // ? __asan_stack_malloc_N(LocalStackSize)
2316 // : nullptr;
2317 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002318 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2319 kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2320 Value *UseAfterReturnIsEnabled =
2321 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002322 Constant::getNullValue(IRB.getInt32Ty()));
2323 Instruction *Term =
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002324 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002325 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002326 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002327 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2328 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2329 Value *FakeStackValue =
2330 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2331 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002332 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002333 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002334 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002335 ConstantInt::get(IntptrTy, 0));
2336
2337 Value *NoFakeStack =
2338 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2339 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2340 IRBIf.SetInsertPoint(Term);
2341 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2342 Value *AllocaValue =
2343 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2344 IRB.SetInsertPoint(InsBefore);
2345 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2346 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2347 } else {
2348 // void *FakeStack = nullptr;
2349 // void *LocalStackBase = alloca(LocalStackSize);
2350 FakeStack = ConstantInt::get(IntptrTy, 0);
2351 LocalStackBase =
2352 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002353 }
2354
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002355 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002356 for (const auto &Desc : SVD) {
2357 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00002358 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00002359 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002360 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00002361 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002362 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002363 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002364
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002365 // The left-most redzone has enough space for at least 4 pointers.
2366 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002367 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2368 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2369 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002370 // Write the frame description constant to redzone[1].
2371 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002372 IRB.CreateAdd(LocalStackBase,
2373 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2374 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00002375 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00002376 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002377 /*AllowMerging*/ true);
2378 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002379 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002380 // Write the PC to redzone[2].
2381 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002382 IRB.CreateAdd(LocalStackBase,
2383 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2384 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002385 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002386
Vitaly Buka793913c2016-08-29 18:17:21 +00002387 const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
2388
2389 // Poison the stack red zones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002390 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Vitaly Buka793913c2016-08-29 18:17:21 +00002391 // As mask we must use most poisoned case: red zones and after scope.
2392 // As bytes we can use either the same or just red zones only.
2393 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
2394
2395 if (ClExperimentalPoisoning && !StaticAllocaPoisonCallVec.empty()) {
2396 // Complete AllocaToSVDMap
2397 for (const auto &Desc : SVD) {
2398 auto It = AllocaToSVDMap.find(Desc.AI);
2399 if (It != AllocaToSVDMap.end()) {
2400 It->second = &Desc;
2401 }
2402 }
2403
2404 const auto &ShadowInScope = GetShadowBytes(SVD, L);
2405
2406 // Poison static allocas near lifetime intrinsics.
2407 for (const auto &APC : StaticAllocaPoisonCallVec) {
2408 // Must be already set.
2409 assert(AllocaToSVDMap[APC.AI]);
2410 const auto &Desc = *AllocaToSVDMap[APC.AI];
2411 assert(Desc.Offset % L.Granularity == 0);
2412 size_t Begin = Desc.Offset / L.Granularity;
2413 size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
2414
2415 IRBuilder<> IRB(APC.InsBefore);
2416 copyToShadow(ShadowAfterScope,
2417 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
2418 IRB, ShadowBase);
2419 }
2420 }
2421
2422 SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002423
Vitaly Buka79b75d32016-06-09 23:05:35 +00002424 auto UnpoisonStack = [&](IRBuilder<> &IRB) {
Vitaly Buka1ce73ef2016-08-16 16:24:10 +00002425 // Do this always as poisonAlloca can be disabled with
2426 // detect_stack_use_after_scope=0.
Vitaly Buka793913c2016-08-29 18:17:21 +00002427 copyToShadow(ShadowAfterScope, ShadowClean, IRB, ShadowBase);
2428 if (!ClExperimentalPoisoning && !StaticAllocaPoisonCallVec.empty()) {
Vitaly Buka79b75d32016-06-09 23:05:35 +00002429 // If we poisoned some allocas in llvm.lifetime analysis,
2430 // unpoison whole stack frame now.
2431 poisonAlloca(LocalStackBase, LocalStackSize, IRB, false);
Vitaly Buka79b75d32016-06-09 23:05:35 +00002432 }
2433 };
2434
Vitaly Buka793913c2016-08-29 18:17:21 +00002435 SmallVector<uint8_t, 64> ShadowAfterReturn;
Vitaly Buka186280d2016-08-20 18:34:36 +00002436
Kostya Serebryany530e2072013-12-23 14:15:08 +00002437 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002438 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002439 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002440 // Mark the current frame as retired.
2441 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2442 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002443 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00002444 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002445 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00002446 // // In use-after-return mode, poison the whole stack frame.
2447 // if StackMallocIdx <= 4
2448 // // For small sizes inline the whole thing:
2449 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002450 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00002451 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002452 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00002453 // else
2454 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002455 Value *Cmp =
2456 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00002457 TerminatorInst *ThenTerm, *ElseTerm;
2458 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2459
2460 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002461 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002462 int ClassSize = kMinStackMallocSize << StackMallocIdx;
Vitaly Buka793913c2016-08-29 18:17:21 +00002463 ShadowAfterReturn.resize(ClassSize / L.Granularity,
2464 kAsanStackUseAfterReturnMagic);
2465 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
2466 ShadowBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002467 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002468 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002469 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2470 Value *SavedFlagPtr = IRBPoison.CreateLoad(
2471 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2472 IRBPoison.CreateStore(
2473 Constant::getNullValue(IRBPoison.getInt8Ty()),
2474 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2475 } else {
2476 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00002477 IRBPoison.CreateCall(
2478 AsanStackFreeFunc[StackMallocIdx],
2479 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002480 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00002481
2482 IRBuilder<> IRBElse(ElseTerm);
Vitaly Buka79b75d32016-06-09 23:05:35 +00002483 UnpoisonStack(IRBElse);
Kostya Serebryany530e2072013-12-23 14:15:08 +00002484 } else {
Vitaly Buka79b75d32016-06-09 23:05:35 +00002485 UnpoisonStack(IRBRet);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002486 }
2487 }
2488
Kostya Serebryany09959942012-10-19 06:20:53 +00002489 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002490 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002491}
Alexey Samsonov261177a2012-12-04 01:34:23 +00002492
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002493void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00002494 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00002495 // For now just insert the call to ASan runtime.
2496 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2497 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002498 IRB.CreateCall(
2499 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2500 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00002501}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002502
2503// Handling llvm.lifetime intrinsics for a given %alloca:
2504// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2505// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2506// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2507// could be poisoned by previous llvm.lifetime.end instruction, as the
2508// variable may go in and out of scope several times, e.g. in loops).
2509// (3) if we poisoned at least one %alloca in a function,
2510// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002511
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002512AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2513 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
Etienne Bergeron9bd42812016-09-14 15:59:32 +00002514 // We're interested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00002515 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002516 // See if we've already calculated (or started to calculate) alloca for a
2517 // given value.
2518 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002519 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002520 // Store 0 while we're calculating alloca for value V to avoid
2521 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00002522 AllocaForValue[V] = nullptr;
2523 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002524 if (CastInst *CI = dyn_cast<CastInst>(V))
2525 Res = findAllocaForValue(CI->getOperand(0));
2526 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00002527 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002528 // Allow self-referencing phi-nodes.
2529 if (IncValue == PN) continue;
2530 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2531 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00002532 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2533 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002534 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002535 }
Vitaly Buka53054a72016-07-22 00:56:17 +00002536 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
2537 Res = findAllocaForValue(EP->getPointerOperand());
2538 } else {
2539 DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V << "\n");
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002540 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002541 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002542 return Res;
2543}
Yury Gribov55441bb2014-11-21 10:29:50 +00002544
Yury Gribov98b18592015-05-28 07:51:49 +00002545void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00002546 IRBuilder<> IRB(AI);
2547
Yury Gribov55441bb2014-11-21 10:29:50 +00002548 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2549 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2550
2551 Value *Zero = Constant::getNullValue(IntptrTy);
2552 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2553 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00002554
2555 // Since we need to extend alloca with additional memory to locate
2556 // redzones, and OldSize is number of allocated blocks with
2557 // ElementSize size, get allocated memory size in bytes by
2558 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00002559 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002560 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00002561 Value *OldSize =
2562 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2563 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00002564
2565 // PartialSize = OldSize % 32
2566 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2567
2568 // Misalign = kAllocaRzSize - PartialSize;
2569 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2570
2571 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2572 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2573 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2574
2575 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2576 // Align is added to locate left redzone, PartialPadding for possible
2577 // partial redzone and kAllocaRzSize for right redzone respectively.
2578 Value *AdditionalChunkSize = IRB.CreateAdd(
2579 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2580
2581 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2582
2583 // Insert new alloca with new NewSize and Align params.
2584 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2585 NewAlloca->setAlignment(Align);
2586
2587 // NewAddress = Address + Align
2588 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2589 ConstantInt::get(IntptrTy, Align));
2590
Yury Gribov98b18592015-05-28 07:51:49 +00002591 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00002592 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00002593
2594 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2595 // for unpoisoning stuff.
2596 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2597
Yury Gribov55441bb2014-11-21 10:29:50 +00002598 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2599
Yury Gribov98b18592015-05-28 07:51:49 +00002600 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00002601 AI->replaceAllUsesWith(NewAddressPtr);
2602
Yury Gribov98b18592015-05-28 07:51:49 +00002603 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00002604 AI->eraseFromParent();
2605}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002606
2607// isSafeAccess returns true if Addr is always inbounds with respect to its
2608// base object. For example, it is a field access or an array access with
2609// constant inbounds index.
2610bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2611 Value *Addr, uint64_t TypeSize) const {
2612 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2613 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00002614 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002615 int64_t Offset = SizeOffset.second.getSExtValue();
2616 // Three checks are required to ensure safety:
2617 // . Offset >= 0 (since the offset is given from the base ptr)
2618 // . Size >= Offset (unsigned)
2619 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00002620 return Offset >= 0 && Size >= uint64_t(Offset) &&
2621 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002622}