blob: 0e5e871df9adf615d0192d7f945441e90ad28672 [file] [log] [blame]
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001//===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of AddressSanitizer, an address sanity checker.
11// Details of the algorithm:
12// http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13//
14//===----------------------------------------------------------------------===//
15
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000016#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov29dd7f22012-12-27 08:50:58 +000017#include "llvm/ADT/DenseMap.h"
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +000018#include "llvm/ADT/DepthFirstIterator.h"
Kuba Brecka8ec94ea2015-07-22 10:25:38 +000019#include "llvm/ADT/SetVector.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000020#include "llvm/ADT/SmallSet.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000021#include "llvm/ADT/SmallVector.h"
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +000022#include "llvm/ADT/Statistic.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000023#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov617232f2012-05-23 11:52:12 +000024#include "llvm/ADT/Triple.h"
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000025#include "llvm/Analysis/MemoryBuiltins.h"
26#include "llvm/Analysis/TargetLibraryInfo.h"
27#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000028#include "llvm/IR/CallSite.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000029#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/DataLayout.h"
Yury Gribov3ae427d2014-12-01 08:47:58 +000031#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Function.h"
33#include "llvm/IR/IRBuilder.h"
34#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000035#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/IntrinsicInst.h"
37#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000038#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Module.h"
40#include "llvm/IR/Type.h"
Kuba Brecka1001bb52014-12-05 22:19:18 +000041#include "llvm/MC/MCSectionMachO.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000042#include "llvm/Support/CommandLine.h"
43#include "llvm/Support/DataTypes.h"
44#include "llvm/Support/Debug.h"
Kostya Serebryany9e62b302013-06-03 14:46:56 +000045#include "llvm/Support/Endian.h"
Yury Gribov55441bb2014-11-21 10:29:50 +000046#include "llvm/Support/SwapByteOrder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000047#include "llvm/Support/raw_ostream.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000048#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany351b0782014-09-03 22:37:37 +000049#include "llvm/Transforms/Scalar.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000050#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000051#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany9f5213f2013-06-26 09:18:17 +000052#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000053#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000054#include "llvm/Transforms/Utils/ModuleUtils.h"
Anna Zaks8ed1d812015-02-27 03:12:36 +000055#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000056#include <algorithm>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000057#include <iomanip>
Vitaly Buka793913c2016-08-29 18:17:21 +000058#include <limits>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000059#include <sstream>
Chandler Carruthed0881b2012-12-03 16:50:05 +000060#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000061#include <system_error>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000062
63using namespace llvm;
64
Chandler Carruth964daaa2014-04-22 02:55:47 +000065#define DEBUG_TYPE "asan"
66
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000067static const uint64_t kDefaultShadowScale = 3;
68static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
69static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Anna Zaks3b50e702016-02-02 22:05:07 +000070static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
71static const uint64_t kIOSShadowOffset64 = 0x120200000;
72static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
73static const uint64_t kIOSSimShadowOffset64 = kDefaultShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000074static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +000075static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
Kostya Serebryany4766fe62013-01-23 12:54:55 +000076static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +000077static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +000078static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +000079static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +000080static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000081static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
82static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +000083static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Etienne Bergeron70684f92016-06-21 15:07:29 +000084// TODO(wwchrome): Experimental for asan Win64, may change.
85static const uint64_t kWindowsShadowOffset64 = 0x1ULL << 45; // 32TB.
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000086
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000087static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000088static const size_t kMaxStackMallocSize = 1 << 16; // 64K
89static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
90static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
91
Craig Topperd3a34f82013-07-16 01:17:10 +000092static const char *const kAsanModuleCtorName = "asan.module_ctor";
93static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000094static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000095static const char *const kAsanReportErrorTemplate = "__asan_report_";
Craig Topperd3a34f82013-07-16 01:17:10 +000096static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000097static const char *const kAsanUnregisterGlobalsName =
98 "__asan_unregister_globals";
Ryan Govostes653f9d02016-03-28 20:28:57 +000099static const char *const kAsanRegisterImageGlobalsName =
100 "__asan_register_image_globals";
101static const char *const kAsanUnregisterImageGlobalsName =
102 "__asan_unregister_image_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +0000103static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
104static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kuba Brecka45dbffd2015-07-23 10:54:06 +0000105static const char *const kAsanInitName = "__asan_init";
106static const char *const kAsanVersionCheckName =
Ryan Govostes653f9d02016-03-28 20:28:57 +0000107 "__asan_version_mismatch_check_v8";
Kostya Serebryany796f6552014-02-27 12:45:36 +0000108static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
109static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +0000110static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000111static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +0000112static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
113static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000114static const char *const kAsanGenPrefix = "__asan_gen_";
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000115static const char *const kODRGenPrefix = "__odr_asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000116static const char *const kSanCovGenPrefix = "__sancov_gen_";
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000117static const char *const kAsanSetShadowPrefix = "__asan_set_shadow_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000118static const char *const kAsanPoisonStackMemoryName =
119 "__asan_poison_stack_memory";
120static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000121 "__asan_unpoison_stack_memory";
Ryan Govostes653f9d02016-03-28 20:28:57 +0000122static const char *const kAsanGlobalsRegisteredFlagName =
123 "__asan_globals_registered";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000124
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +0000125static const char *const kAsanOptionDetectUseAfterReturn =
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000126 "__asan_option_detect_stack_use_after_return";
127
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000128static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
129static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
Yury Gribov98b18592015-05-28 07:51:49 +0000130
Kostya Serebryany874dae62012-07-16 16:15:40 +0000131// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
132static const size_t kNumberOfAccessSizes = 5;
133
Yury Gribov55441bb2014-11-21 10:29:50 +0000134static const unsigned kAllocaRzSize = 32;
Yury Gribov55441bb2014-11-21 10:29:50 +0000135
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000136// Command-line flags.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000137static cl::opt<bool> ClEnableKasan(
138 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
139 cl::Hidden, cl::init(false));
Yury Gribovd7731982015-11-11 10:36:49 +0000140static cl::opt<bool> ClRecover(
141 "asan-recover",
142 cl::desc("Enable recovery mode (continue-after-error)."),
143 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000144
145// This flag may need to be replaced with -f[no-]asan-reads.
146static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000147 cl::desc("instrument read instructions"),
148 cl::Hidden, cl::init(true));
149static cl::opt<bool> ClInstrumentWrites(
150 "asan-instrument-writes", cl::desc("instrument write instructions"),
151 cl::Hidden, cl::init(true));
152static cl::opt<bool> ClInstrumentAtomics(
153 "asan-instrument-atomics",
154 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
155 cl::init(true));
156static cl::opt<bool> ClAlwaysSlowPath(
157 "asan-always-slow-path",
158 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
159 cl::init(false));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000160// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000161// in any given BB. Normally, this should be set to unlimited (INT_MAX),
162// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
163// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000164static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
165 "asan-max-ins-per-bb", cl::init(10000),
166 cl::desc("maximal number of instructions to instrument in any given BB"),
167 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000168// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000169static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
170 cl::Hidden, cl::init(true));
Vitaly Buka1f9e1352016-08-20 20:23:50 +0000171static cl::opt<uint32_t> ClMaxInlinePoisoningSize(
172 "asan-max-inline-poisoning-size",
173 cl::desc(
174 "Inline shadow poisoning for blocks up to the given size in bytes."),
175 cl::Hidden, cl::init(64));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000176static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Mike Aizatsky243b71f2016-04-21 22:00:13 +0000177 cl::desc("Check stack-use-after-return"),
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000178 cl::Hidden, cl::init(true));
Kostya Serebryanya83bfea2016-04-20 20:02:58 +0000179static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
180 cl::desc("Check stack-use-after-scope"),
181 cl::Hidden, cl::init(false));
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000182static cl::opt<bool> ClExperimentalPoisoning(
183 "asan-experimental-poisoning",
184 cl::desc("Enable experimental red zones and scope poisoning"), cl::Hidden,
Vitaly Buka3c4f6bf2016-08-29 19:28:34 +0000185 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000186// This flag may need to be replaced with -f[no]asan-globals.
187static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000188 cl::desc("Handle global objects"), cl::Hidden,
189 cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000190static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000191 cl::desc("Handle C++ initializer order"),
192 cl::Hidden, cl::init(true));
193static cl::opt<bool> ClInvalidPointerPairs(
194 "asan-detect-invalid-pointer-pair",
195 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
196 cl::init(false));
197static cl::opt<unsigned> ClRealignStack(
198 "asan-realign-stack",
199 cl::desc("Realign stack to the value of this flag (power of two)"),
200 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000201static cl::opt<int> ClInstrumentationWithCallsThreshold(
202 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000203 cl::desc(
204 "If the function being instrumented contains more than "
205 "this number of memory accesses, use callbacks instead of "
206 "inline checks (-1 means never use callbacks)."),
207 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000208static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000209 "asan-memory-access-callback-prefix",
210 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
211 cl::init("__asan_"));
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000212static cl::opt<bool>
213 ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
214 cl::desc("instrument dynamic allocas"),
215 cl::Hidden, cl::init(true));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000216static cl::opt<bool> ClSkipPromotableAllocas(
217 "asan-skip-promotable-allocas",
218 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
219 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000220
221// These flags allow to change the shadow mapping.
222// The shadow mapping looks like
Ryan Govostes3f37df02016-05-06 10:25:22 +0000223// Shadow = (Mem >> scale) + offset
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000224static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000225 cl::desc("scale of asan shadow mapping"),
226 cl::Hidden, cl::init(0));
Ryan Govostes6194ae62016-05-06 11:22:11 +0000227static cl::opt<unsigned long long> ClMappingOffset(
228 "asan-mapping-offset",
229 cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden,
230 cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000231
232// Optimization flags. Not user visible, used mostly for testing
233// and benchmarking the tool.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000234static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
235 cl::Hidden, cl::init(true));
236static cl::opt<bool> ClOptSameTemp(
237 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
238 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000239static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000240 cl::desc("Don't instrument scalar globals"),
241 cl::Hidden, cl::init(true));
242static cl::opt<bool> ClOptStack(
243 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
244 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000245
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000246static cl::opt<bool> ClDynamicAllocaStack(
247 "asan-stack-dynamic-alloca",
248 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000249 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000250
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000251static cl::opt<uint32_t> ClForceExperiment(
252 "asan-force-experiment",
253 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
254 cl::init(0));
255
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000256static cl::opt<bool>
257 ClUsePrivateAliasForGlobals("asan-use-private-alias",
258 cl::desc("Use private aliases for global"
259 " variables"),
260 cl::Hidden, cl::init(false));
261
Ryan Govostese51401b2016-07-05 21:53:08 +0000262static cl::opt<bool>
263 ClUseMachOGlobalsSection("asan-globals-live-support",
264 cl::desc("Use linker features to support dead "
265 "code stripping of globals "
266 "(Mach-O only)"),
267 cl::Hidden, cl::init(false));
268
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000269// Debug flags.
270static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
271 cl::init(0));
272static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
273 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000274static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
275 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000276static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
277 cl::Hidden, cl::init(-1));
278static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
279 cl::Hidden, cl::init(-1));
280
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000281STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
282STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000283STATISTIC(NumOptimizedAccessesToGlobalVar,
284 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000285STATISTIC(NumOptimizedAccessesToStackVar,
286 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000287
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000288namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000289/// Frontend-provided metadata for source location.
290struct LocationMetadata {
291 StringRef Filename;
292 int LineNo;
293 int ColumnNo;
294
295 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
296
297 bool empty() const { return Filename.empty(); }
298
299 void parse(MDNode *MDN) {
300 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000301 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
302 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000303 LineNo =
304 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
305 ColumnNo =
306 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000307 }
308};
309
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000310/// Frontend-provided metadata for global variables.
311class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000312 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000313 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000314 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000315 LocationMetadata SourceLoc;
316 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000317 bool IsDynInit;
318 bool IsBlacklisted;
319 };
320
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000321 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000322
Keno Fischere03fae42015-12-05 14:42:34 +0000323 void reset() {
324 inited_ = false;
325 Entries.clear();
326 }
327
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000328 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000329 assert(!inited_);
330 inited_ = true;
331 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000332 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000333 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000334 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000335 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000336 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000337 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000338 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000339 // We can already have an entry for GV if it was merged with another
340 // global.
341 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000342 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
343 E.SourceLoc.parse(Loc);
344 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
345 E.Name = Name->getString();
346 ConstantInt *IsDynInit =
347 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000348 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000349 ConstantInt *IsBlacklisted =
350 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000351 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000352 }
353 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000354
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000355 /// Returns metadata entry for a given global.
356 Entry get(GlobalVariable *G) const {
357 auto Pos = Entries.find(G);
358 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000359 }
360
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000361 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000362 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000363 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000364};
365
Alexey Samsonov1345d352013-01-16 13:23:28 +0000366/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000367/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000368struct ShadowMapping {
369 int Scale;
370 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000371 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000372};
373
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000374static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
375 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000376 bool IsAndroid = TargetTriple.isAndroid();
Anna Zaks3b50e702016-02-02 22:05:07 +0000377 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000378 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
379 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000380 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
381 TargetTriple.getArch() == llvm::Triple::ppc64le;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000382 bool IsSystemZ = TargetTriple.getArch() == llvm::Triple::systemz;
Anna Zaks3b50e702016-02-02 22:05:07 +0000383 bool IsX86 = TargetTriple.getArch() == llvm::Triple::x86;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000384 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000385 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
386 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000387 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
388 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000389 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000390 bool IsWindows = TargetTriple.isOSWindows();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000391
392 ShadowMapping Mapping;
393
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000394 if (LongSize == 32) {
Evgeniy Stepanov9cb08f82015-07-17 23:51:18 +0000395 // Android is always PIE, which means that the beginning of the address
396 // space is always available.
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000397 if (IsAndroid)
398 Mapping.Offset = 0;
399 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000400 Mapping.Offset = kMIPS32_ShadowOffset32;
401 else if (IsFreeBSD)
402 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000403 else if (IsIOS)
Anna Zaks3b50e702016-02-02 22:05:07 +0000404 // If we're targeting iOS and x86, the binary is built for iOS simulator.
405 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000406 else if (IsWindows)
407 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000408 else
409 Mapping.Offset = kDefaultShadowOffset32;
410 } else { // LongSize == 64
411 if (IsPPC64)
412 Mapping.Offset = kPPC64_ShadowOffset64;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000413 else if (IsSystemZ)
414 Mapping.Offset = kSystemZ_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000415 else if (IsFreeBSD)
416 Mapping.Offset = kFreeBSD_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000417 else if (IsLinux && IsX86_64) {
418 if (IsKasan)
419 Mapping.Offset = kLinuxKasan_ShadowOffset64;
420 else
421 Mapping.Offset = kSmallX86_64ShadowOffset;
Etienne Bergeron70684f92016-06-21 15:07:29 +0000422 } else if (IsWindows && IsX86_64) {
423 Mapping.Offset = kWindowsShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000424 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000425 Mapping.Offset = kMIPS64_ShadowOffset64;
Anna Zaks3b50e702016-02-02 22:05:07 +0000426 else if (IsIOS)
427 // If we're targeting iOS and x86, the binary is built for iOS simulator.
428 Mapping.Offset = IsX86_64 ? kIOSSimShadowOffset64 : kIOSShadowOffset64;
Renato Golinaf213722015-02-03 11:20:45 +0000429 else if (IsAArch64)
430 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000431 else
432 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000433 }
434
435 Mapping.Scale = kDefaultShadowScale;
Ryan Govostes3f37df02016-05-06 10:25:22 +0000436 if (ClMappingScale.getNumOccurrences() > 0) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000437 Mapping.Scale = ClMappingScale;
438 }
439
Ryan Govostes3f37df02016-05-06 10:25:22 +0000440 if (ClMappingOffset.getNumOccurrences() > 0) {
441 Mapping.Offset = ClMappingOffset;
442 }
443
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000444 // OR-ing shadow offset if more efficient (at least on x86) if the offset
445 // is a power of two, but on ppc64 we have to use add since the shadow
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000446 // offset is not necessary 1/8-th of the address space. On SystemZ,
447 // we could OR the constant in a single instruction, but it's more
448 // efficient to load it once and use indexed addressing.
449 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ
Adhemerval Zanella35891fe2015-11-09 18:03:48 +0000450 && !(Mapping.Offset & (Mapping.Offset - 1));
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000451
Alexey Samsonov1345d352013-01-16 13:23:28 +0000452 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000453}
454
Alexey Samsonov1345d352013-01-16 13:23:28 +0000455static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000456 // Redzone used for stack and globals is at least 32 bytes.
457 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000458 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000459}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000460
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000461/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000462struct AddressSanitizer : public FunctionPass {
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000463 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
464 bool UseAfterScope = false)
Yury Gribovd7731982015-11-11 10:36:49 +0000465 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000466 Recover(Recover || ClRecover),
467 UseAfterScope(UseAfterScope || ClUseAfterScope) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000468 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
469 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000470 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000471 return "AddressSanitizerFunctionPass";
472 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000473 void getAnalysisUsage(AnalysisUsage &AU) const override {
474 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000475 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000476 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000477 uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000478 uint64_t ArraySize = 1;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000479 if (AI.isArrayAllocation()) {
480 const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000481 assert(CI && "non-constant array size");
482 ArraySize = CI->getZExtValue();
483 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000484 Type *Ty = AI.getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000485 uint64_t SizeInBytes =
Vitaly Buka21a9e572016-07-28 22:50:50 +0000486 AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000487 return SizeInBytes * ArraySize;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000488 }
489 /// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000490 bool isInterestingAlloca(const AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000491
Anna Zaks8ed1d812015-02-27 03:12:36 +0000492 /// If it is an interesting memory access, return the PointerOperand
493 /// and set IsWrite/Alignment. Otherwise return nullptr.
494 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000495 uint64_t *TypeSize, unsigned *Alignment);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000496 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000497 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000498 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000499 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
500 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000501 Value *SizeArgument, bool UseCalls, uint32_t Exp);
502 void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
503 uint32_t TypeSize, bool IsWrite,
504 Value *SizeArgument, bool UseCalls,
505 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000506 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
507 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000508 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000509 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000510 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000511 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000512 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000513 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000514 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000515 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000516 bool doInitialization(Module &M) override;
Keno Fischere03fae42015-12-05 14:42:34 +0000517 bool doFinalization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000518 static char ID; // Pass identification, replacement for typeid
519
Yury Gribov3ae427d2014-12-01 08:47:58 +0000520 DominatorTree &getDominatorTree() const { return *DT; }
521
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000522 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000523 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000524
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000525 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000526 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000527 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
528 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000529
Reid Kleckner2f907552015-07-21 17:40:14 +0000530 /// Helper to cleanup per-function state.
531 struct FunctionStateRAII {
532 AddressSanitizer *Pass;
533 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
534 assert(Pass->ProcessedAllocas.empty() &&
535 "last pass forgot to clear cache");
536 }
537 ~FunctionStateRAII() { Pass->ProcessedAllocas.clear(); }
538 };
539
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000540 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000541 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000542 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000543 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000544 bool Recover;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000545 bool UseAfterScope;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000546 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000547 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000548 DominatorTree *DT;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000549 Function *AsanCtorFunction = nullptr;
550 Function *AsanInitFunction = nullptr;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000551 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000552 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000553 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
554 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
555 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
556 // This array is indexed by AccessIsWrite and Experiment.
557 Function *AsanErrorCallbackSized[2][2];
558 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000559 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000560 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000561 GlobalsMetadata GlobalsMD;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000562 DenseMap<const AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000563
564 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000565};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000566
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000567class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000568 public:
Yury Gribovd7731982015-11-11 10:36:49 +0000569 explicit AddressSanitizerModule(bool CompileKernel = false,
570 bool Recover = false)
571 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
572 Recover(Recover || ClRecover) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000573 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000574 static char ID; // Pass identification, replacement for typeid
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000575 const char *getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000576
Kostya Serebryany20a79972012-11-22 03:18:50 +0000577 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000578 void initializeCallbacks(Module &M);
579
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000580 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000581 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000582 bool ShouldUseMachOGlobalsSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000583 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000584 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000585 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000586 return RedzoneSizeForScale(Mapping.Scale);
587 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000588
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000589 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000590 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000591 bool Recover;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000592 Type *IntptrTy;
593 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000594 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000595 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000596 Function *AsanPoisonGlobals;
597 Function *AsanUnpoisonGlobals;
598 Function *AsanRegisterGlobals;
599 Function *AsanUnregisterGlobals;
Ryan Govostes653f9d02016-03-28 20:28:57 +0000600 Function *AsanRegisterImageGlobals;
601 Function *AsanUnregisterImageGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000602};
603
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000604// Stack poisoning does not play well with exception handling.
605// When an exception is thrown, we essentially bypass the code
606// that unpoisones the stack. This is why the run-time library has
607// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
608// stack in the interceptor. This however does not work inside the
609// actual function which catches the exception. Most likely because the
610// compiler hoists the load of the shadow value somewhere too high.
611// This causes asan to report a non-existing bug on 453.povray.
612// It sounds like an LLVM bug.
613struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
614 Function &F;
615 AddressSanitizer &ASan;
616 DIBuilder DIB;
617 LLVMContext *C;
618 Type *IntptrTy;
619 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000620 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000621
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000622 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000623 SmallSetVector<AllocaInst *, 16> NonInstrumentedStaticAllocaVec;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000624 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000625 unsigned StackAlignment;
626
Kostya Serebryany6805de52013-09-10 13:16:56 +0000627 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000628 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000629 Function *AsanSetShadowFunc[0x100] = {};
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000630 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000631 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000632
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000633 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
634 struct AllocaPoisonCall {
635 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000636 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000637 uint64_t Size;
638 bool DoPoison;
639 };
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000640 SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
641 SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000642
Yury Gribov98b18592015-05-28 07:51:49 +0000643 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
644 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
645 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000646 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000647
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000648 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000649 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000650 AllocaForValueMapTy AllocaForValue;
651
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000652 bool HasNonEmptyInlineAsm = false;
653 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000654 std::unique_ptr<CallInst> EmptyInlineAsm;
655
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000656 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000657 : F(F),
658 ASan(ASan),
659 DIB(*F.getParent(), /*AllowUnresolved*/ false),
660 C(ASan.C),
661 IntptrTy(ASan.IntptrTy),
662 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
663 Mapping(ASan.Mapping),
664 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000665 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000666
667 bool runOnFunction() {
668 if (!ClStack) return false;
669 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000670 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000671
Yury Gribov55441bb2014-11-21 10:29:50 +0000672 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000673
674 initializeCallbacks(*F.getParent());
675
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000676 processDynamicAllocas();
677 processStaticAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000678
679 if (ClDebugStack) {
680 DEBUG(dbgs() << F);
681 }
682 return true;
683 }
684
Yury Gribov55441bb2014-11-21 10:29:50 +0000685 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000686 // poisoned red zones around all of them.
687 // Then unpoison everything back before the function returns.
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000688 void processStaticAllocas();
689 void processDynamicAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000690
Yury Gribov98b18592015-05-28 07:51:49 +0000691 void createDynamicAllocasInitStorage();
692
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000693 // ----------------------- Visitors.
694 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000695 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000696
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000697 /// \brief Collect all Resume instructions.
698 void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
699
700 /// \brief Collect all CatchReturnInst instructions.
701 void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
702
Yury Gribov98b18592015-05-28 07:51:49 +0000703 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
704 Value *SavedStack) {
705 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000706 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
707 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
708 // need to adjust extracted SP to compute the address of the most recent
709 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
710 // this purpose.
711 if (!isa<ReturnInst>(InstBefore)) {
712 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
713 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
714 {IntptrTy});
715
716 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
717
718 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
719 DynamicAreaOffset);
720 }
721
Yury Gribov781bce22015-05-28 08:03:28 +0000722 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000723 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000724 }
725
Yury Gribov55441bb2014-11-21 10:29:50 +0000726 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000727 void unpoisonDynamicAllocas() {
728 for (auto &Ret : RetVec)
729 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000730
Yury Gribov98b18592015-05-28 07:51:49 +0000731 for (auto &StackRestoreInst : StackRestoreVec)
732 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
733 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000734 }
735
Yury Gribov55441bb2014-11-21 10:29:50 +0000736 // Deploy and poison redzones around dynamic alloca call. To do this, we
737 // should replace this call with another one with changed parameters and
738 // replace all its uses with new address, so
739 // addr = alloca type, old_size, align
740 // is replaced by
741 // new_size = (old_size + additional_size) * sizeof(type)
742 // tmp = alloca i8, new_size, max(align, 32)
743 // addr = tmp + 32 (first 32 bytes are for the left redzone).
744 // Additional_size is added to make new memory allocation contain not only
745 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000746 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000747
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000748 /// \brief Collect Alloca instructions we want (and can) handle.
749 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000750 if (!ASan.isInterestingAlloca(AI)) {
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000751 if (AI.isStaticAlloca()) NonInstrumentedStaticAllocaVec.insert(&AI);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000752 return;
753 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000754
755 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000756 if (!AI.isStaticAlloca())
Yury Gribov98b18592015-05-28 07:51:49 +0000757 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000758 else
759 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000760 }
761
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000762 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
763 /// errors.
764 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000765 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000766 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000767 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000768 if (!ASan.UseAfterScope)
769 return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000770 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000771 return;
772 // Found lifetime intrinsic, add ASan instrumentation if necessary.
773 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
774 // If size argument is undefined, don't do anything.
775 if (Size->isMinusOne()) return;
776 // Check that size doesn't saturate uint64_t and can
777 // be stored in IntptrTy.
778 const uint64_t SizeValue = Size->getValue().getLimitedValue();
779 if (SizeValue == ~0ULL ||
780 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
781 return;
782 // Find alloca instruction that corresponds to llvm.lifetime argument.
783 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
Vitaly Bukab451f1b2016-06-09 23:31:59 +0000784 if (!AI || !ASan.isInterestingAlloca(*AI))
785 return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000786 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000787 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000788 if (AI->isStaticAlloca())
789 StaticAllocaPoisonCallVec.push_back(APC);
790 else if (ClInstrumentDynamicAllocas)
791 DynamicAllocaPoisonCallVec.push_back(APC);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000792 }
793
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000794 void visitCallSite(CallSite CS) {
795 Instruction *I = CS.getInstruction();
796 if (CallInst *CI = dyn_cast<CallInst>(I)) {
797 HasNonEmptyInlineAsm |=
798 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
799 HasReturnsTwiceCall |= CI->canReturnTwice();
800 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000801 }
802
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000803 // ---------------------- Helpers.
804 void initializeCallbacks(Module &M);
805
Yury Gribov3ae427d2014-12-01 08:47:58 +0000806 bool doesDominateAllExits(const Instruction *I) const {
807 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000808 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000809 }
810 return true;
811 }
812
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000813 /// Finds alloca where the value comes from.
814 AllocaInst *findAllocaForValue(Value *V);
Vitaly Buka793913c2016-08-29 18:17:21 +0000815
816 // Copies bytes from ShadowBytes into shadow memory for indexes where
817 // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
818 // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
819 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
820 IRBuilder<> &IRB, Value *ShadowBase);
821 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
822 size_t Begin, size_t End, IRBuilder<> &IRB,
823 Value *ShadowBase);
824 void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
825 ArrayRef<uint8_t> ShadowBytes, size_t Begin,
826 size_t End, IRBuilder<> &IRB, Value *ShadowBase);
827
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000828 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000829
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000830 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
831 bool Dynamic);
832 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
833 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000834};
835
Vitaly Buka58a81c62016-09-08 06:27:58 +0000836// Performs depth-first search on the control flow graph of block and checks if
837// we can get into the same block with different lifetime state.
838class AllocaLifetimeChecker {
839 // Contains values of the last lifetime intrinsics in the block.
840 // true: llvm.lifetime.start, false: llvm.lifetime.end
841 DenseMap<const BasicBlock *, bool> Markers;
842 // Contains the lifetime state we detected doing depth-first search on the
843 // control flow graph. We expect all future hits will have the same value.
844 // true: llvm.lifetime.start, false: llvm.lifetime.end
845 DenseMap<const BasicBlock *, bool> InboundState;
846 bool Processed = false;
847 bool CollisionDetected = false;
848
849 bool FindCollision(const std::pair<const BasicBlock *, bool> &BlockState) {
850 auto Ins = InboundState.insert(BlockState);
851 if (!Ins.second) {
852 // Already there. Return collision if they are different.
853 return BlockState.second != Ins.first->second;
854 }
855
856 // Use marker for successors if block contains any.
857 auto M = Markers.find(BlockState.first);
858 bool NewState = (M != Markers.end() ? M->second : BlockState.second);
859 for (const BasicBlock *SB : successors(BlockState.first))
860 // We may get into EHPad with any lifetime state, so ignore them.
861 if (!SB->isEHPad() && FindCollision({SB, NewState}))
862 return true;
863
864 return false;
865 }
866
867public:
868 // Assume that markers of the same block will be added in the same order as
869 // the order of corresponding intrinsics, so in the end we will keep only
870 // value of the last intrinsic.
871 void AddMarker(const BasicBlock *BB, bool start) {
872 assert(!Processed);
873 Markers[BB] = start;
874 }
875
876 bool HasAmbiguousLifetime() {
877 if (!Processed) {
878 Processed = true;
879 const Function *F = Markers.begin()->first->getParent();
880 CollisionDetected = FindCollision({&F->getEntryBlock(), false});
881 }
882 return CollisionDetected;
883 }
884};
885
886// Removes allocas for which exists at least one block simultaneously
887// reachable in both states: allocas is inside the scope, and alloca is outside
888// of the scope. We don't have enough information to validate access to such
889// variable, so we just remove such allocas from lifetime analysis.
890// This is workaround for PR28267.
891void removeAllocasWithAmbiguousLifetime(
892 SmallVectorImpl<FunctionStackPoisoner::AllocaPoisonCall> &PoisonCallVec) {
893 DenseMap<const AllocaInst *, AllocaLifetimeChecker> Checkers;
894 for (const auto &APC : PoisonCallVec)
895 Checkers[APC.AI].AddMarker(APC.InsBefore->getParent(), !APC.DoPoison);
896
897 auto IsAmbiguous =
898 [&Checkers](const FunctionStackPoisoner::AllocaPoisonCall &APC) {
899 return Checkers[APC.AI].HasAmbiguousLifetime();
900 };
901
902 PoisonCallVec.erase(
903 std::remove_if(PoisonCallVec.begin(), PoisonCallVec.end(), IsAmbiguous),
904 PoisonCallVec.end());
905}
906
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000907} // anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000908
909char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000910INITIALIZE_PASS_BEGIN(
911 AddressSanitizer, "asan",
912 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
913 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000914INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +0000915INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000916INITIALIZE_PASS_END(
917 AddressSanitizer, "asan",
918 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
919 false)
Yury Gribovd7731982015-11-11 10:36:49 +0000920FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000921 bool Recover,
922 bool UseAfterScope) {
Yury Gribovd7731982015-11-11 10:36:49 +0000923 assert(!CompileKernel || Recover);
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000924 return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000925}
926
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000927char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000928INITIALIZE_PASS(
929 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000930 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000931 "ModulePass",
932 false, false)
Yury Gribovd7731982015-11-11 10:36:49 +0000933ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
934 bool Recover) {
935 assert(!CompileKernel || Recover);
936 return new AddressSanitizerModule(CompileKernel, Recover);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000937}
938
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000939static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000940 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000941 assert(Res < kNumberOfAccessSizes);
942 return Res;
943}
944
Bill Wendling58f8cef2013-08-06 22:52:42 +0000945// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000946static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
947 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000948 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000949 // We use private linkage for module-local strings. If they can be merged
950 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000951 GlobalVariable *GV =
952 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000953 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000954 if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000955 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
956 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000957}
958
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000959/// \brief Create a global describing a source location.
960static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
961 LocationMetadata MD) {
962 Constant *LocData[] = {
963 createPrivateGlobalForString(M, MD.Filename, true),
964 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
965 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
966 };
967 auto LocStruct = ConstantStruct::getAnon(LocData);
968 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
969 GlobalValue::PrivateLinkage, LocStruct,
970 kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000971 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000972 return GV;
973}
974
Vedant Kumarf5ac6d42016-06-22 17:30:58 +0000975/// \brief Check if \p G has been created by a trusted compiler pass.
976static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
977 // Do not instrument asan globals.
978 if (G->getName().startswith(kAsanGenPrefix) ||
979 G->getName().startswith(kSanCovGenPrefix) ||
980 G->getName().startswith(kODRGenPrefix))
981 return true;
982
983 // Do not instrument gcov counter arrays.
984 if (G->getName() == "__llvm_gcov_ctr")
985 return true;
986
987 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000988}
989
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000990Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
991 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000992 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000993 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000994 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000995 if (Mapping.OrShadowOffset)
996 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
997 else
998 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000999}
1000
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001001// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001002void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
1003 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001004 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001005 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001006 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +00001007 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1008 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
1009 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001010 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001011 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001012 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +00001013 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1014 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
1015 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001016 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001017 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001018}
1019
Anna Zaks8ed1d812015-02-27 03:12:36 +00001020/// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001021bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001022 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1023
1024 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1025 return PreviouslySeenAllocaInfo->getSecond();
1026
Yury Gribov98b18592015-05-28 07:51:49 +00001027 bool IsInteresting =
1028 (AI.getAllocatedType()->isSized() &&
1029 // alloca() may be called with 0 size, ignore it.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001030 ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
Yury Gribov98b18592015-05-28 07:51:49 +00001031 // We are only interested in allocas not promotable to registers.
1032 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +00001033 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
1034 // inalloca allocas are not treated as static, and we don't want
1035 // dynamic alloca instrumentation for them as well.
1036 !AI.isUsedWithInAlloca());
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001037
1038 ProcessedAllocas[&AI] = IsInteresting;
1039 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001040}
1041
1042/// If I is an interesting memory access, return the PointerOperand
1043/// and set IsWrite/Alignment. Otherwise return nullptr.
1044Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
1045 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001046 uint64_t *TypeSize,
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001047 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +00001048 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001049 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001050
1051 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001052 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001053 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001054 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001055 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001056 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001057 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001058 PtrOperand = LI->getPointerOperand();
1059 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001060 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001061 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001062 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001063 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001064 PtrOperand = SI->getPointerOperand();
1065 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001066 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001067 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001068 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001069 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001070 PtrOperand = RMW->getPointerOperand();
1071 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001072 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001073 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001074 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001075 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001076 PtrOperand = XCHG->getPointerOperand();
Kostya Serebryany90241602012-05-30 09:04:06 +00001077 }
Anna Zaks8ed1d812015-02-27 03:12:36 +00001078
Anna Zaks644d9d32016-06-22 00:15:52 +00001079 // Do not instrument acesses from different address spaces; we cannot deal
1080 // with them.
1081 if (PtrOperand) {
1082 Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1083 if (PtrTy->getPointerAddressSpace() != 0)
1084 return nullptr;
1085 }
1086
Anna Zaks8ed1d812015-02-27 03:12:36 +00001087 // Treat memory accesses to promotable allocas as non-interesting since they
1088 // will not cause memory violations. This greatly speeds up the instrumented
1089 // executable at -O0.
1090 if (ClSkipPromotableAllocas)
1091 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1092 return isInterestingAlloca(*AI) ? AI : nullptr;
1093
1094 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001095}
1096
Kostya Serebryany796f6552014-02-27 12:45:36 +00001097static bool isPointerOperand(Value *V) {
1098 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1099}
1100
1101// This is a rough heuristic; it may cause both false positives and
1102// false negatives. The proper implementation requires cooperation with
1103// the frontend.
1104static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1105 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001106 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001107 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001108 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001109 } else {
1110 return false;
1111 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +00001112 return isPointerOperand(I->getOperand(0)) &&
1113 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001114}
1115
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001116bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1117 // If a global variable does not have dynamic initialization we don't
1118 // have to instrument it. However, if a global does not have initializer
1119 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001120 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001121}
1122
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001123void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1124 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +00001125 IRBuilder<> IRB(I);
1126 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1127 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
Benjamin Kramer135f7352016-06-26 12:28:59 +00001128 for (Value *&i : Param) {
1129 if (i->getType()->isPointerTy())
1130 i = IRB.CreatePointerCast(i, IntptrTy);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001131 }
David Blaikieff6409d2015-05-18 22:13:54 +00001132 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001133}
1134
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001135void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001136 Instruction *I, bool UseCalls,
1137 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +00001138 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001139 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001140 uint64_t TypeSize = 0;
1141 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +00001142 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001143
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001144 // Optimization experiments.
1145 // The experiments can be used to evaluate potential optimizations that remove
1146 // instrumentation (assess false negatives). Instead of completely removing
1147 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1148 // experiments that want to remove instrumentation of this instruction).
1149 // If Exp is non-zero, this pass will emit special calls into runtime
1150 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1151 // make runtime terminate the program in a special way (with a different
1152 // exit status). Then you run the new compiler on a buggy corpus, collect
1153 // the special terminations (ideally, you don't see them at all -- no false
1154 // negatives) and make the decision on the optimization.
1155 uint32_t Exp = ClForceExperiment;
1156
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001157 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001158 // If initialization order checking is disabled, a simple access to a
1159 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001160 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001161 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001162 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1163 NumOptimizedAccessesToGlobalVar++;
1164 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001165 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001166 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001167
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001168 if (ClOpt && ClOptStack) {
1169 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001170 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001171 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1172 NumOptimizedAccessesToStackVar++;
1173 return;
1174 }
1175 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001176
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001177 if (IsWrite)
1178 NumInstrumentedWrites++;
1179 else
1180 NumInstrumentedReads++;
1181
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001182 unsigned Granularity = 1 << Mapping.Scale;
1183 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1184 // if the data is properly aligned.
1185 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1186 TypeSize == 128) &&
1187 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001188 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
1189 Exp);
1190 instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
1191 UseCalls, Exp);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001192}
1193
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001194Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1195 Value *Addr, bool IsWrite,
1196 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001197 Value *SizeArgument,
1198 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001199 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001200 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1201 CallInst *Call = nullptr;
1202 if (SizeArgument) {
1203 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001204 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1205 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001206 else
David Blaikieff6409d2015-05-18 22:13:54 +00001207 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1208 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001209 } else {
1210 if (Exp == 0)
1211 Call =
1212 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1213 else
David Blaikieff6409d2015-05-18 22:13:54 +00001214 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1215 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001216 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001217
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001218 // We don't do Call->setDoesNotReturn() because the BB already has
1219 // UnreachableInst at the end.
1220 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001221 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001222 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001223}
1224
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001225Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001226 Value *ShadowValue,
1227 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001228 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001229 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001230 Value *LastAccessedByte =
1231 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001232 // (Addr & (Granularity - 1)) + size - 1
1233 if (TypeSize / 8 > 1)
1234 LastAccessedByte = IRB.CreateAdd(
1235 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1236 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001237 LastAccessedByte =
1238 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001239 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1240 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1241}
1242
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001243void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001244 Instruction *InsertBefore, Value *Addr,
1245 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001246 Value *SizeArgument, bool UseCalls,
1247 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001248 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001249 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001250 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1251
1252 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001253 if (Exp == 0)
1254 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1255 AddrLong);
1256 else
David Blaikieff6409d2015-05-18 22:13:54 +00001257 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1258 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001259 return;
1260 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001261
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001262 Type *ShadowTy =
1263 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001264 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1265 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1266 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001267 Value *ShadowValue =
1268 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001269
1270 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001271 size_t Granularity = 1ULL << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001272 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001273
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001274 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001275 // We use branch weights for the slow path check, to indicate that the slow
1276 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001277 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1278 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001279 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001280 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001281 IRB.SetInsertPoint(CheckTerm);
1282 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001283 if (Recover) {
1284 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1285 } else {
1286 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001287 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001288 CrashTerm = new UnreachableInst(*C, CrashBlock);
1289 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1290 ReplaceInstWithInst(CheckTerm, NewTerm);
1291 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001292 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001293 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001294 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001295
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001296 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001297 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001298 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001299}
1300
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001301// Instrument unusual size or unusual alignment.
1302// We can not do it with a single check, so we do 1-byte check for the first
1303// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1304// to report the actual access size.
1305void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1306 Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1307 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1308 IRBuilder<> IRB(I);
1309 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1310 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1311 if (UseCalls) {
1312 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001313 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1314 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001315 else
David Blaikieff6409d2015-05-18 22:13:54 +00001316 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1317 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001318 } else {
1319 Value *LastByte = IRB.CreateIntToPtr(
1320 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1321 Addr->getType());
1322 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1323 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1324 }
1325}
1326
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001327void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1328 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001329 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001330 IRBuilder<> IRB(&GlobalInit.front(),
1331 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001332
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001333 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001334 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1335 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001336
1337 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001338 for (auto &BB : GlobalInit.getBasicBlockList())
1339 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001340 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001341}
1342
1343void AddressSanitizerModule::createInitializerPoisonCalls(
1344 Module &M, GlobalValue *ModuleName) {
1345 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1346
1347 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1348 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001349 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001350 ConstantStruct *CS = cast<ConstantStruct>(OP);
1351
1352 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001353 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001354 if (F->getName() == kAsanModuleCtorName) continue;
1355 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1356 // Don't instrument CTORs that will run before asan.module_ctor.
1357 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1358 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001359 }
1360 }
1361}
1362
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001363bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001364 Type *Ty = G->getValueType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001365 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001366
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001367 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001368 if (!Ty->isSized()) return false;
1369 if (!G->hasInitializer()) return false;
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001370 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001371 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001372 // Don't handle ODR linkage types and COMDATs since other modules may be built
1373 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001374 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1375 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1376 G->getLinkage() != GlobalVariable::InternalLinkage)
1377 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001378 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001379 // Two problems with thread-locals:
1380 // - The address of the main thread's copy can't be computed at link-time.
1381 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001382 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001383 // For now, just ignore this Global if the alignment is large.
1384 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001385
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001386 if (G->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001387 StringRef Section = G->getSection();
Kuba Brecka086e34b2014-12-05 21:32:46 +00001388
Anna Zaks11904602015-06-09 00:58:08 +00001389 // Globals from llvm.metadata aren't emitted, do not instrument them.
1390 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001391 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001392 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001393
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001394 // Do not instrument function pointers to initialization and termination
1395 // routines: dynamic linker will not properly handle redzones.
1396 if (Section.startswith(".preinit_array") ||
1397 Section.startswith(".init_array") ||
1398 Section.startswith(".fini_array")) {
1399 return false;
1400 }
1401
Anna Zaks11904602015-06-09 00:58:08 +00001402 // Callbacks put into the CRT initializer/terminator sections
1403 // should not be instrumented.
1404 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1405 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1406 if (Section.startswith(".CRT")) {
1407 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1408 return false;
1409 }
1410
Kuba Brecka1001bb52014-12-05 22:19:18 +00001411 if (TargetTriple.isOSBinFormatMachO()) {
1412 StringRef ParsedSegment, ParsedSection;
1413 unsigned TAA = 0, StubSize = 0;
1414 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001415 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1416 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001417 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001418
1419 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1420 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1421 // them.
1422 if (ParsedSegment == "__OBJC" ||
1423 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1424 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1425 return false;
1426 }
1427 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1428 // Constant CFString instances are compiled in the following way:
1429 // -- the string buffer is emitted into
1430 // __TEXT,__cstring,cstring_literals
1431 // -- the constant NSConstantString structure referencing that buffer
1432 // is placed into __DATA,__cfstring
1433 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1434 // Moreover, it causes the linker to crash on OS X 10.7
1435 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1436 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1437 return false;
1438 }
1439 // The linker merges the contents of cstring_literals and removes the
1440 // trailing zeroes.
1441 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1442 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1443 return false;
1444 }
1445 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001446 }
1447
1448 return true;
1449}
1450
Ryan Govostes653f9d02016-03-28 20:28:57 +00001451// On Mach-O platforms, we emit global metadata in a separate section of the
1452// binary in order to allow the linker to properly dead strip. This is only
1453// supported on recent versions of ld64.
1454bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
Ryan Govostese51401b2016-07-05 21:53:08 +00001455 if (!ClUseMachOGlobalsSection)
1456 return false;
1457
Ryan Govostes653f9d02016-03-28 20:28:57 +00001458 if (!TargetTriple.isOSBinFormatMachO())
1459 return false;
1460
1461 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1462 return true;
1463 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001464 return true;
Ryan Govostes653f9d02016-03-28 20:28:57 +00001465 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1466 return true;
1467
1468 return false;
1469}
1470
Alexey Samsonov788381b2012-12-25 12:28:20 +00001471void AddressSanitizerModule::initializeCallbacks(Module &M) {
1472 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001473
Alexey Samsonov788381b2012-12-25 12:28:20 +00001474 // Declare our poisoning and unpoisoning functions.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001475 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001476 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001477 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001478 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001479 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001480 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001481
Alexey Samsonov788381b2012-12-25 12:28:20 +00001482 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001483 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001484 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001485 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001486 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001487 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1488 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001489 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001490
1491 // Declare the functions that find globals in a shared object and then invoke
1492 // the (un)register function on them.
1493 AsanRegisterImageGlobals = checkSanitizerInterfaceFunction(
1494 M.getOrInsertFunction(kAsanRegisterImageGlobalsName,
1495 IRB.getVoidTy(), IntptrTy, nullptr));
1496 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001497
Ryan Govostes653f9d02016-03-28 20:28:57 +00001498 AsanUnregisterImageGlobals = checkSanitizerInterfaceFunction(
1499 M.getOrInsertFunction(kAsanUnregisterImageGlobalsName,
1500 IRB.getVoidTy(), IntptrTy, nullptr));
1501 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001502}
1503
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001504// This function replaces all global variables with new variables that have
1505// trailing redzones. It also creates a function that poisons
1506// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001507bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001508 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001509
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001510 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1511
Alexey Samsonova02e6642014-05-29 18:40:48 +00001512 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001513 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001514 }
1515
1516 size_t n = GlobalsToChange.size();
1517 if (n == 0) return false;
1518
1519 // A global is described by a structure
1520 // size_t beg;
1521 // size_t size;
1522 // size_t size_with_redzone;
1523 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001524 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001525 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001526 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001527 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001528 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001529 StructType *GlobalStructTy =
1530 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001531 IntptrTy, IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001532 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001533
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001534 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001535
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001536 // We shouldn't merge same module names, as this string serves as unique
1537 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001538 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001539 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001540
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001541 auto &DL = M.getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001542 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001543 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001544 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001545
1546 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001547 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001548 // Create string holding the global name (use global name from metadata
1549 // if it's available, otherwise just write the name of global variable).
1550 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001551 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001552 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001553
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001554 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001555 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001556 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001557 // MinRZ <= RZ <= kMaxGlobalRedzone
1558 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001559 uint64_t RZ = std::max(
1560 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001561 uint64_t RightRedzoneSize = RZ;
1562 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001563 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001564 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001565 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1566
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001567 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001568 Constant *NewInitializer =
1569 ConstantStruct::get(NewTy, G->getInitializer(),
1570 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001571
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001572 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001573 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1574 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1575 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001576 GlobalVariable *NewGlobal =
1577 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1578 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001579 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001580 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001581
1582 Value *Indices2[2];
1583 Indices2[0] = IRB.getInt32(0);
1584 Indices2[1] = IRB.getInt32(0);
1585
1586 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001587 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001588 NewGlobal->takeName(G);
1589 G->eraseFromParent();
1590
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001591 Constant *SourceLoc;
1592 if (!MD.SourceLoc.empty()) {
1593 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1594 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1595 } else {
1596 SourceLoc = ConstantInt::get(IntptrTy, 0);
1597 }
1598
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001599 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
1600 GlobalValue *InstrumentedGlobal = NewGlobal;
1601
1602 bool CanUsePrivateAliases = TargetTriple.isOSBinFormatELF();
1603 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
1604 // Create local alias for NewGlobal to avoid crash on ODR between
1605 // instrumented and non-instrumented libraries.
1606 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
1607 NameForGlobal + M.getName(), NewGlobal);
1608
1609 // With local aliases, we need to provide another externally visible
1610 // symbol __odr_asan_XXX to detect ODR violation.
1611 auto *ODRIndicatorSym =
1612 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
1613 Constant::getNullValue(IRB.getInt8Ty()),
1614 kODRGenPrefix + NameForGlobal, nullptr,
1615 NewGlobal->getThreadLocalMode());
1616
1617 // Set meaningful attributes for indicator symbol.
1618 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
1619 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
1620 ODRIndicatorSym->setAlignment(1);
1621 ODRIndicator = ODRIndicatorSym;
1622 InstrumentedGlobal = GA;
1623 }
1624
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001625 Initializers[i] = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001626 GlobalStructTy,
1627 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001628 ConstantInt::get(IntptrTy, SizeInBytes),
1629 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1630 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001631 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001632 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
1633 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy), nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001634
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001635 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001636
Kostya Serebryany20343352012-10-17 13:40:06 +00001637 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001638 }
1639
Ryan Govostes653f9d02016-03-28 20:28:57 +00001640
1641 GlobalVariable *AllGlobals = nullptr;
1642 GlobalVariable *RegisteredFlag = nullptr;
1643
1644 // On recent Mach-O platforms, we emit the global metadata in a way that
1645 // allows the linker to properly strip dead globals.
1646 if (ShouldUseMachOGlobalsSection()) {
1647 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1648 // to look up the loaded image that contains it. Second, we can store in it
1649 // whether registration has already occurred, to prevent duplicate
1650 // registration.
1651 //
1652 // Common linkage allows us to coalesce needles defined in each object
1653 // file so that there's only one per shared library.
1654 RegisteredFlag = new GlobalVariable(
1655 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1656 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1657
1658 // We also emit a structure which binds the liveness of the global
1659 // variable to the metadata struct.
1660 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy, nullptr);
1661
1662 for (size_t i = 0; i < n; i++) {
1663 GlobalVariable *Metadata = new GlobalVariable(
1664 M, GlobalStructTy, false, GlobalVariable::InternalLinkage,
1665 Initializers[i], "");
1666 Metadata->setSection("__DATA,__asan_globals,regular");
1667 Metadata->setAlignment(1); // don't leave padding in between
1668
1669 auto LivenessBinder = ConstantStruct::get(LivenessTy,
1670 Initializers[i]->getAggregateElement(0u),
1671 ConstantExpr::getPointerCast(Metadata, IntptrTy),
1672 nullptr);
1673 GlobalVariable *Liveness = new GlobalVariable(
1674 M, LivenessTy, false, GlobalVariable::InternalLinkage,
1675 LivenessBinder, "");
1676 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1677 }
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
Reid Kleckner2f907552015-07-21 17:40:14 +00001847void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
1848 // Find the one possible call to llvm.localescape and pre-mark allocas passed
1849 // to it as uninteresting. This assumes we haven't started processing allocas
1850 // yet. This check is done up front because iterating the use list in
1851 // isInterestingAlloca would be algorithmically slower.
1852 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
1853
1854 // Try to get the declaration of llvm.localescape. If it's not in the module,
1855 // we can exit early.
1856 if (!F.getParent()->getFunction("llvm.localescape")) return;
1857
1858 // Look for a call to llvm.localescape call in the entry block. It can't be in
1859 // any other block.
1860 for (Instruction &I : F.getEntryBlock()) {
1861 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
1862 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
1863 // We found a call. Mark all the allocas passed in as uninteresting.
1864 for (Value *Arg : II->arg_operands()) {
1865 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
1866 assert(AI && AI->isStaticAlloca() &&
1867 "non-static alloca arg to localescape");
1868 ProcessedAllocas[AI] = false;
1869 }
1870 break;
1871 }
1872 }
1873}
1874
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001875bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001876 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001877 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001878 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001879 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001880
Yury Gribov3ae427d2014-12-01 08:47:58 +00001881 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1882
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001883 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001884 maybeInsertAsanInitAtFunctionEntry(F);
1885
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001886 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001887
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001888 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001889
Reid Kleckner2f907552015-07-21 17:40:14 +00001890 FunctionStateRAII CleanupObj(this);
1891
1892 // We can't instrument allocas used with llvm.localescape. Only static allocas
1893 // can be passed to that intrinsic.
1894 markEscapedLocalAllocas(F);
1895
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001896 // We want to instrument every address only once per basic block (unless there
1897 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001898 SmallSet<Value *, 16> TempsToInstrument;
1899 SmallVector<Instruction *, 16> ToInstrument;
1900 SmallVector<Instruction *, 8> NoReturnCalls;
1901 SmallVector<BasicBlock *, 16> AllBlocks;
1902 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001903 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001904 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001905 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001906 uint64_t TypeSize;
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00001907 const TargetLibraryInfo *TLI =
1908 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001909
1910 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001911 for (auto &BB : F) {
1912 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001913 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001914 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001915 for (auto &Inst : BB) {
1916 if (LooksLikeCodeInBug11395(&Inst)) return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001917 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1918 &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001919 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001920 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001921 continue; // We've seen this temp in the current BB.
1922 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001923 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001924 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1925 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001926 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001927 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001928 // ok, take it.
1929 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001930 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001931 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001932 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001933 // A call inside BB.
1934 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001935 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001936 }
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00001937 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
1938 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001939 continue;
1940 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001941 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001942 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001943 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001944 }
1945 }
1946
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001947 bool UseCalls =
1948 CompileKernel ||
1949 (ClInstrumentationWithCallsThreshold >= 0 &&
1950 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001951 const DataLayout &DL = F.getParent()->getDataLayout();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001952 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1953 /*RoundToAlign=*/true);
1954
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001955 // Instrument.
1956 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001957 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001958 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1959 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001960 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001961 instrumentMop(ObjSizeVis, Inst, UseCalls,
1962 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001963 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001964 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001965 }
1966 NumInstrumented++;
1967 }
1968
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001969 FunctionStackPoisoner FSP(F, *this);
1970 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001971
1972 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1973 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001974 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001975 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00001976 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001977 }
1978
Alexey Samsonova02e6642014-05-29 18:40:48 +00001979 for (auto Inst : PointerComparisonsOrSubtracts) {
1980 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001981 NumInstrumented++;
1982 }
1983
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001984 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001985
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001986 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1987
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001988 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001989}
1990
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001991// Workaround for bug 11395: we don't want to instrument stack in functions
1992// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1993// FIXME: remove once the bug 11395 is fixed.
1994bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1995 if (LongSize != 32) return false;
1996 CallInst *CI = dyn_cast<CallInst>(I);
1997 if (!CI || !CI->isInlineAsm()) return false;
1998 if (CI->getNumArgOperands() <= 5) return false;
1999 // We have inline assembly with quite a few arguments.
2000 return true;
2001}
2002
2003void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2004 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00002005 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
2006 std::string Suffix = itostr(i);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002007 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
2008 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
2009 IntptrTy, nullptr));
2010 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002011 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
2012 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00002013 }
Vitaly Buka79b75d32016-06-09 23:05:35 +00002014 if (ASan.UseAfterScope) {
2015 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2016 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
2017 IntptrTy, IntptrTy, nullptr));
2018 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2019 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
2020 IntptrTy, IntptrTy, nullptr));
2021 }
2022
Vitaly Buka3455b9b2016-08-20 18:34:39 +00002023 if (ClExperimentalPoisoning) {
2024 for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2025 std::ostringstream Name;
2026 Name << kAsanSetShadowPrefix;
2027 Name << std::setw(2) << std::setfill('0') << std::hex << Val;
2028 AsanSetShadowFunc[Val] =
2029 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2030 Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
2031 }
2032 }
2033
Yury Gribov98b18592015-05-28 07:51:49 +00002034 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2035 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
2036 AsanAllocasUnpoisonFunc =
2037 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2038 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002039}
2040
Vitaly Buka793913c2016-08-29 18:17:21 +00002041void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2042 ArrayRef<uint8_t> ShadowBytes,
2043 size_t Begin, size_t End,
2044 IRBuilder<> &IRB,
2045 Value *ShadowBase) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002046 if (Begin >= End)
2047 return;
Vitaly Buka186280d2016-08-20 18:34:36 +00002048
2049 const size_t LargestStoreSizeInBytes =
2050 std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2051
2052 const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2053
2054 // Poison given range in shadow using larges store size with out leading and
Vitaly Buka793913c2016-08-29 18:17:21 +00002055 // trailing zeros in ShadowMask. Zeros never change, so they need neither
2056 // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2057 // middle of a store.
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002058 for (size_t i = Begin; i < End;) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002059 if (!ShadowMask[i]) {
2060 assert(!ShadowBytes[i]);
Vitaly Buka186280d2016-08-20 18:34:36 +00002061 ++i;
2062 continue;
2063 }
2064
2065 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2066 // Fit store size into the range.
2067 while (StoreSizeInBytes > End - i)
2068 StoreSizeInBytes /= 2;
2069
2070 // Minimize store size by trimming trailing zeros.
Vitaly Buka793913c2016-08-29 18:17:21 +00002071 for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
Vitaly Buka186280d2016-08-20 18:34:36 +00002072 while (j <= StoreSizeInBytes / 2)
2073 StoreSizeInBytes /= 2;
2074 }
2075
2076 uint64_t Val = 0;
Vitaly Buka793913c2016-08-29 18:17:21 +00002077 for (size_t j = 0; j < StoreSizeInBytes; j++) {
2078 if (IsLittleEndian)
2079 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2080 else
2081 Val = (Val << 8) | ShadowBytes[i + j];
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002082 }
Vitaly Buka186280d2016-08-20 18:34:36 +00002083
2084 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2085 Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
Vitaly Buka0672a272016-08-22 04:16:14 +00002086 IRB.CreateAlignedStore(
2087 Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
Vitaly Buka186280d2016-08-20 18:34:36 +00002088
2089 i += StoreSizeInBytes;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002090 }
2091}
2092
Vitaly Buka793913c2016-08-29 18:17:21 +00002093void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2094 ArrayRef<uint8_t> ShadowBytes,
2095 IRBuilder<> &IRB, Value *ShadowBase) {
2096 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2097}
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002098
Vitaly Buka793913c2016-08-29 18:17:21 +00002099void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2100 ArrayRef<uint8_t> ShadowBytes,
2101 size_t Begin, size_t End,
2102 IRBuilder<> &IRB, Value *ShadowBase) {
2103 assert(ShadowMask.size() == ShadowBytes.size());
2104 size_t Done = Begin;
2105 for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2106 if (!ShadowMask[i]) {
2107 assert(!ShadowBytes[i]);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002108 continue;
Vitaly Buka793913c2016-08-29 18:17:21 +00002109 }
2110 uint8_t Val = ShadowBytes[i];
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002111 if (!AsanSetShadowFunc[Val])
2112 continue;
2113
2114 // Skip same values.
Vitaly Buka793913c2016-08-29 18:17:21 +00002115 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002116 }
2117
2118 if (j - i >= ClMaxInlinePoisoningSize) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002119 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002120 IRB.CreateCall(AsanSetShadowFunc[Val],
2121 {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2122 ConstantInt::get(IntptrTy, j - i)});
2123 Done = j;
2124 }
2125 }
2126
Vitaly Buka793913c2016-08-29 18:17:21 +00002127 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002128}
2129
Kostya Serebryany6805de52013-09-10 13:16:56 +00002130// Fake stack allocator (asan_fake_stack.h) has 11 size classes
2131// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2132static int StackMallocSizeClass(uint64_t LocalStackSize) {
2133 assert(LocalStackSize <= kMaxStackMallocSize);
2134 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002135 for (int i = 0;; i++, MaxSize *= 2)
2136 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00002137 llvm_unreachable("impossible LocalStackSize");
2138}
2139
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002140PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2141 Value *ValueIfTrue,
2142 Instruction *ThenTerm,
2143 Value *ValueIfFalse) {
2144 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2145 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2146 PHI->addIncoming(ValueIfFalse, CondBlock);
2147 BasicBlock *ThenBlock = ThenTerm->getParent();
2148 PHI->addIncoming(ValueIfTrue, ThenBlock);
2149 return PHI;
2150}
2151
2152Value *FunctionStackPoisoner::createAllocaForLayout(
2153 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2154 AllocaInst *Alloca;
2155 if (Dynamic) {
2156 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2157 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2158 "MyAlloca");
2159 } else {
2160 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2161 nullptr, "MyAlloca");
2162 assert(Alloca->isStaticAlloca());
2163 }
2164 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2165 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2166 Alloca->setAlignment(FrameAlignment);
2167 return IRB.CreatePointerCast(Alloca, IntptrTy);
2168}
2169
Yury Gribov98b18592015-05-28 07:51:49 +00002170void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2171 BasicBlock &FirstBB = *F.begin();
2172 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2173 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2174 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2175 DynamicAllocaLayout->setAlignment(32);
2176}
2177
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002178void FunctionStackPoisoner::processDynamicAllocas() {
2179 if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2180 assert(DynamicAllocaPoisonCallVec.empty());
2181 return;
2182 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002183
Vitaly Buka58a81c62016-09-08 06:27:58 +00002184 removeAllocasWithAmbiguousLifetime(DynamicAllocaPoisonCallVec);
2185
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002186 // Insert poison calls for lifetime intrinsics for dynamic allocas.
2187 for (const auto &APC : DynamicAllocaPoisonCallVec) {
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002188 assert(APC.InsBefore);
2189 assert(APC.AI);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002190 assert(ASan.isInterestingAlloca(*APC.AI));
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002191 assert(!APC.AI->isStaticAlloca());
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002192
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002193 IRBuilder<> IRB(APC.InsBefore);
2194 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002195 // Dynamic allocas will be unpoisoned unconditionally below in
2196 // unpoisonDynamicAllocas.
2197 // Flag that we need unpoison static allocas.
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002198 }
2199
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002200 // Handle dynamic allocas.
2201 createDynamicAllocasInitStorage();
2202 for (auto &AI : DynamicAllocaVec)
2203 handleDynamicAllocaCall(AI);
2204 unpoisonDynamicAllocas();
2205}
Yury Gribov98b18592015-05-28 07:51:49 +00002206
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002207void FunctionStackPoisoner::processStaticAllocas() {
2208 if (AllocaVec.empty()) {
2209 assert(StaticAllocaPoisonCallVec.empty());
2210 return;
Kuba Breckaf5875d32015-02-24 09:47:05 +00002211 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002212
Vitaly Buka58a81c62016-09-08 06:27:58 +00002213 removeAllocasWithAmbiguousLifetime(StaticAllocaPoisonCallVec);
2214
Kostya Serebryany6805de52013-09-10 13:16:56 +00002215 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002216 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00002217 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002218 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002219
2220 Instruction *InsBefore = AllocaVec[0];
2221 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002222 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002223
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002224 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2225 // debug info is broken, because only entry-block allocas are treated as
2226 // regular stack slots.
2227 auto InsBeforeB = InsBefore->getParent();
2228 assert(InsBeforeB == &F.getEntryBlock());
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002229 for (BasicBlock::iterator I(InsBefore); I != InsBeforeB->end(); ++I)
2230 if (auto *AI = dyn_cast<AllocaInst>(I))
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002231 if (NonInstrumentedStaticAllocaVec.count(AI) > 0)
2232 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00002233
Reid Kleckner2f907552015-07-21 17:40:14 +00002234 // If we have a call to llvm.localescape, keep it in the entry block.
2235 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2236
Vitaly Buka793913c2016-08-29 18:17:21 +00002237 // Find static allocas with lifetime analysis.
2238 DenseMap<const AllocaInst *, const ASanStackVariableDescription *>
2239 AllocaToSVDMap;
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002240 for (const auto &APC : StaticAllocaPoisonCallVec) {
2241 assert(APC.InsBefore);
2242 assert(APC.AI);
2243 assert(ASan.isInterestingAlloca(*APC.AI));
2244 assert(APC.AI->isStaticAlloca());
2245
Vitaly Buka793913c2016-08-29 18:17:21 +00002246 if (ClExperimentalPoisoning) {
2247 AllocaToSVDMap[APC.AI] = nullptr;
2248 } else {
2249 IRBuilder<> IRB(APC.InsBefore);
2250 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
2251 }
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002252 }
2253
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002254 SmallVector<ASanStackVariableDescription, 16> SVD;
2255 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00002256 for (AllocaInst *AI : AllocaVec) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002257 size_t UseAfterScopePoisonSize =
2258 AllocaToSVDMap.find(AI) != AllocaToSVDMap.end()
2259 ? ASan.getAllocaSizeInBytes(*AI)
2260 : 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002261 ASanStackVariableDescription D = {AI->getName().data(),
Vitaly Buka21a9e572016-07-28 22:50:50 +00002262 ASan.getAllocaSizeInBytes(*AI),
Vitaly Buka793913c2016-08-29 18:17:21 +00002263 UseAfterScopePoisonSize,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002264 AI->getAlignment(),
2265 AI,
2266 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002267 SVD.push_back(D);
2268 }
2269 // Minimal header size (left redzone) is 4 pointers,
2270 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2271 size_t MinHeaderSize = ASan.LongSize / 2;
Vitaly Bukadb331d82016-08-29 17:41:29 +00002272 const ASanStackFrameLayout &L =
2273 ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize);
Vitaly Buka793913c2016-08-29 18:17:21 +00002274
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002275 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
2276 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002277 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2278 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00002279 bool DoDynamicAlloca = ClDynamicAllocaStack;
2280 // Don't do dynamic alloca or stack malloc if:
2281 // 1) There is inline asm: too often it makes assumptions on which registers
2282 // are available.
2283 // 2) There is a returns_twice call (typically setjmp), which is
2284 // optimization-hostile, and doesn't play well with introduced indirect
2285 // register-relative calculation of local variable addresses.
2286 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2287 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002288
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002289 Value *StaticAlloca =
2290 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2291
2292 Value *FakeStack;
2293 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002294
2295 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002296 // void *FakeStack = __asan_option_detect_stack_use_after_return
2297 // ? __asan_stack_malloc_N(LocalStackSize)
2298 // : nullptr;
2299 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002300 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2301 kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2302 Value *UseAfterReturnIsEnabled =
2303 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002304 Constant::getNullValue(IRB.getInt32Ty()));
2305 Instruction *Term =
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002306 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002307 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002308 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002309 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2310 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2311 Value *FakeStackValue =
2312 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2313 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002314 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002315 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002316 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002317 ConstantInt::get(IntptrTy, 0));
2318
2319 Value *NoFakeStack =
2320 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2321 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2322 IRBIf.SetInsertPoint(Term);
2323 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2324 Value *AllocaValue =
2325 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2326 IRB.SetInsertPoint(InsBefore);
2327 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2328 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2329 } else {
2330 // void *FakeStack = nullptr;
2331 // void *LocalStackBase = alloca(LocalStackSize);
2332 FakeStack = ConstantInt::get(IntptrTy, 0);
2333 LocalStackBase =
2334 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002335 }
2336
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002337 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002338 for (const auto &Desc : SVD) {
2339 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00002340 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00002341 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002342 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00002343 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002344 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002345 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002346
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002347 // The left-most redzone has enough space for at least 4 pointers.
2348 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002349 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2350 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2351 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002352 // Write the frame description constant to redzone[1].
2353 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002354 IRB.CreateAdd(LocalStackBase,
2355 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2356 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00002357 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00002358 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002359 /*AllowMerging*/ true);
2360 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002361 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002362 // Write the PC to redzone[2].
2363 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002364 IRB.CreateAdd(LocalStackBase,
2365 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2366 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002367 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002368
Vitaly Buka793913c2016-08-29 18:17:21 +00002369 const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
2370
2371 // Poison the stack red zones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002372 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Vitaly Buka793913c2016-08-29 18:17:21 +00002373 // As mask we must use most poisoned case: red zones and after scope.
2374 // As bytes we can use either the same or just red zones only.
2375 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
2376
2377 if (ClExperimentalPoisoning && !StaticAllocaPoisonCallVec.empty()) {
2378 // Complete AllocaToSVDMap
2379 for (const auto &Desc : SVD) {
2380 auto It = AllocaToSVDMap.find(Desc.AI);
2381 if (It != AllocaToSVDMap.end()) {
2382 It->second = &Desc;
2383 }
2384 }
2385
2386 const auto &ShadowInScope = GetShadowBytes(SVD, L);
2387
2388 // Poison static allocas near lifetime intrinsics.
2389 for (const auto &APC : StaticAllocaPoisonCallVec) {
2390 // Must be already set.
2391 assert(AllocaToSVDMap[APC.AI]);
2392 const auto &Desc = *AllocaToSVDMap[APC.AI];
2393 assert(Desc.Offset % L.Granularity == 0);
2394 size_t Begin = Desc.Offset / L.Granularity;
2395 size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
2396
2397 IRBuilder<> IRB(APC.InsBefore);
2398 copyToShadow(ShadowAfterScope,
2399 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
2400 IRB, ShadowBase);
2401 }
2402 }
2403
2404 SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002405
Vitaly Buka79b75d32016-06-09 23:05:35 +00002406 auto UnpoisonStack = [&](IRBuilder<> &IRB) {
Vitaly Buka1ce73ef2016-08-16 16:24:10 +00002407 // Do this always as poisonAlloca can be disabled with
2408 // detect_stack_use_after_scope=0.
Vitaly Buka793913c2016-08-29 18:17:21 +00002409 copyToShadow(ShadowAfterScope, ShadowClean, IRB, ShadowBase);
2410 if (!ClExperimentalPoisoning && !StaticAllocaPoisonCallVec.empty()) {
Vitaly Buka79b75d32016-06-09 23:05:35 +00002411 // If we poisoned some allocas in llvm.lifetime analysis,
2412 // unpoison whole stack frame now.
2413 poisonAlloca(LocalStackBase, LocalStackSize, IRB, false);
Vitaly Buka79b75d32016-06-09 23:05:35 +00002414 }
2415 };
2416
Vitaly Buka793913c2016-08-29 18:17:21 +00002417 SmallVector<uint8_t, 64> ShadowAfterReturn;
Vitaly Buka186280d2016-08-20 18:34:36 +00002418
Kostya Serebryany530e2072013-12-23 14:15:08 +00002419 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002420 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002421 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002422 // Mark the current frame as retired.
2423 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2424 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002425 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00002426 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002427 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00002428 // // In use-after-return mode, poison the whole stack frame.
2429 // if StackMallocIdx <= 4
2430 // // For small sizes inline the whole thing:
2431 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002432 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00002433 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002434 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00002435 // else
2436 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002437 Value *Cmp =
2438 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00002439 TerminatorInst *ThenTerm, *ElseTerm;
2440 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2441
2442 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002443 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002444 int ClassSize = kMinStackMallocSize << StackMallocIdx;
Vitaly Buka793913c2016-08-29 18:17:21 +00002445 ShadowAfterReturn.resize(ClassSize / L.Granularity,
2446 kAsanStackUseAfterReturnMagic);
2447 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
2448 ShadowBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002449 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002450 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002451 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2452 Value *SavedFlagPtr = IRBPoison.CreateLoad(
2453 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2454 IRBPoison.CreateStore(
2455 Constant::getNullValue(IRBPoison.getInt8Ty()),
2456 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2457 } else {
2458 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00002459 IRBPoison.CreateCall(
2460 AsanStackFreeFunc[StackMallocIdx],
2461 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002462 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00002463
2464 IRBuilder<> IRBElse(ElseTerm);
Vitaly Buka79b75d32016-06-09 23:05:35 +00002465 UnpoisonStack(IRBElse);
Kostya Serebryany530e2072013-12-23 14:15:08 +00002466 } else {
Vitaly Buka79b75d32016-06-09 23:05:35 +00002467 UnpoisonStack(IRBRet);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002468 }
2469 }
2470
Kostya Serebryany09959942012-10-19 06:20:53 +00002471 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002472 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002473}
Alexey Samsonov261177a2012-12-04 01:34:23 +00002474
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002475void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00002476 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00002477 // For now just insert the call to ASan runtime.
2478 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2479 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002480 IRB.CreateCall(
2481 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2482 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00002483}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002484
2485// Handling llvm.lifetime intrinsics for a given %alloca:
2486// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2487// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2488// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2489// could be poisoned by previous llvm.lifetime.end instruction, as the
2490// variable may go in and out of scope several times, e.g. in loops).
2491// (3) if we poisoned at least one %alloca in a function,
2492// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002493
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002494AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2495 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
2496 // We're intested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00002497 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002498 // See if we've already calculated (or started to calculate) alloca for a
2499 // given value.
2500 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002501 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002502 // Store 0 while we're calculating alloca for value V to avoid
2503 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00002504 AllocaForValue[V] = nullptr;
2505 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002506 if (CastInst *CI = dyn_cast<CastInst>(V))
2507 Res = findAllocaForValue(CI->getOperand(0));
2508 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00002509 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002510 // Allow self-referencing phi-nodes.
2511 if (IncValue == PN) continue;
2512 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2513 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00002514 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2515 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002516 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002517 }
Vitaly Buka53054a72016-07-22 00:56:17 +00002518 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
2519 Res = findAllocaForValue(EP->getPointerOperand());
2520 } else {
2521 DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V << "\n");
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002522 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002523 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002524 return Res;
2525}
Yury Gribov55441bb2014-11-21 10:29:50 +00002526
Yury Gribov98b18592015-05-28 07:51:49 +00002527void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00002528 IRBuilder<> IRB(AI);
2529
Yury Gribov55441bb2014-11-21 10:29:50 +00002530 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2531 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2532
2533 Value *Zero = Constant::getNullValue(IntptrTy);
2534 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2535 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00002536
2537 // Since we need to extend alloca with additional memory to locate
2538 // redzones, and OldSize is number of allocated blocks with
2539 // ElementSize size, get allocated memory size in bytes by
2540 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00002541 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002542 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00002543 Value *OldSize =
2544 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2545 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00002546
2547 // PartialSize = OldSize % 32
2548 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2549
2550 // Misalign = kAllocaRzSize - PartialSize;
2551 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2552
2553 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2554 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2555 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2556
2557 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2558 // Align is added to locate left redzone, PartialPadding for possible
2559 // partial redzone and kAllocaRzSize for right redzone respectively.
2560 Value *AdditionalChunkSize = IRB.CreateAdd(
2561 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2562
2563 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2564
2565 // Insert new alloca with new NewSize and Align params.
2566 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2567 NewAlloca->setAlignment(Align);
2568
2569 // NewAddress = Address + Align
2570 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2571 ConstantInt::get(IntptrTy, Align));
2572
Yury Gribov98b18592015-05-28 07:51:49 +00002573 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00002574 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00002575
2576 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2577 // for unpoisoning stuff.
2578 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2579
Yury Gribov55441bb2014-11-21 10:29:50 +00002580 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2581
Yury Gribov98b18592015-05-28 07:51:49 +00002582 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00002583 AI->replaceAllUsesWith(NewAddressPtr);
2584
Yury Gribov98b18592015-05-28 07:51:49 +00002585 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00002586 AI->eraseFromParent();
2587}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002588
2589// isSafeAccess returns true if Addr is always inbounds with respect to its
2590// base object. For example, it is a field access or an array access with
2591// constant inbounds index.
2592bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2593 Value *Addr, uint64_t TypeSize) const {
2594 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2595 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00002596 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002597 int64_t Offset = SizeOffset.second.getSExtValue();
2598 // Three checks are required to ensure safety:
2599 // . Offset >= 0 (since the offset is given from the base ptr)
2600 // . Size >= Offset (unsigned)
2601 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00002602 return Offset >= 0 && Size >= uint64_t(Offset) &&
2603 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002604}